MICROSOFT DYNAMICS ® NAV 2009
C/SIDE SOLUTION DEVELOPMENT
Microsoft Official Training Materials for Microsoft Dynamics...
156 downloads
1495 Views
8MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
MICROSOFT DYNAMICS ® NAV 2009
C/SIDE SOLUTION DEVELOPMENT
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Last Revision: January 2009 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.
© 2009 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 Requirements
1-1
Objectives ........................................................................................................... 1-1 Introduction ......................................................................................................... 1-1 Diagnosis - Executive Summary......................................................................... 1-2 Analysis - Functional Requirements ................................................................... 1-2 Data Model ......................................................................................................... 1-5 Project Plan ........................................................................................................ 1-6 Summary ............................................................................................................ 1-6 Quick Interaction: Lessons Learned ................................................................... 1-7
Chapter 2: Master Tables and Pages
2-1
Objectives ........................................................................................................... 2-1 Introduction ......................................................................................................... 2-1 A Quick Refresher .............................................................................................. 2-2 Customers and Participants ............................................................................... 2-3 Rooms ................................................................................................................ 2-5 Lab 2.1 - Create Seminar Room Tables and Pages........................................... 2-8 Lab 2.2 - Adding Code for Seminar Rooms ..................................................... 2-13 Instructors ......................................................................................................... 2-16 Lab 2.3 - Creating Instructor Tables and Pages ............................................... 2-18 Seminars .......................................................................................................... 2-19 Lab 2.4 - Creating Seminar Tables and Pages ................................................ 2-22 Testing .............................................................................................................. 2-28 Summary .......................................................................................................... 2-29 Test Your Knowledge ....................................................................................... 2-30 Quick Interaction: Lessons Learned ................................................................. 2-34 Solutions ........................................................................................................... 2-35
Chapter 3: Registrations
3-1
Objectives ........................................................................................................... 3-1 Introduction ......................................................................................................... 3-1 Prerequisite Information ..................................................................................... 3-2 Types of Tables .................................................................................................. 3-6 Additional Functions ........................................................................................... 3-8 Registrations .................................................................................................... 3-10 Lab 3.1 - Creating the Tables and Pages for Seminar Registration ................. 3-18 Lab 3.3 - Adding Code to the Seminar Registration Header Table and Page .. 3-29 Lab 3.4 - Adding Code for Seminar Registration Lines .................................... 3-36 Lab 3.5 - Set Up a Seminar Management Department Page ........................... 3-40 Testing Seminar Registrations ......................................................................... 3-42 Summary .......................................................................................................... 3-42 Test Your Knowledge ....................................................................................... 3-43 Quick Interaction: Lessons Learned ................................................................. 3-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
i
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solutions ........................................................................................................... 3-47
Chapter 4: Posting
4-1
Objectives ........................................................................................................... 4-1 Introduction ......................................................................................................... 4-1 Prerequisite Information ..................................................................................... 4-2 Posting Seminar Registrations ......................................................................... 4-17 Lab 4.1 - Creating the Tables and Pages for Seminar Registration Posting .... 4-25 Lab 4.2 - Creating the Codeunits and Page for Seminar Journal Posting ........ 4-30 Lab 4.3 - Modifying the Tables, Pages and Codeunits for Job Posting ............ 4-34 Lab 4.4 - Creating the Tables and Pages for Posted Information .................... 4-35 Lab 4.5 - Creating the Codeunits for Document Posting .................................. 4-41 RoleTailored Client Menu Setup....................................................................... 4-49 Testing .............................................................................................................. 4-49 Summary .......................................................................................................... 4-50 Test Your Knowledge ....................................................................................... 4-51 Quick Interaction: Lessons Learned ................................................................. 4-53 Solutions ........................................................................................................... 4-54
Chapter 5: Integration
5-1
Objectives ........................................................................................................... 5-1 Introduction ......................................................................................................... 5-1 Prerequisite Information ..................................................................................... 5-2 Seminar Feature Integration ............................................................................... 5-2 Lab 5.1 - Integrating Seminar Features .............................................................. 5-8 Navigate Integration ........................................................................................... 5-9 Lab 5.2 - Modifying Objects to Integrate with Navigate .................................... 5-11 Testing Managing Integration ........................................................................... 5-14 Summary .......................................................................................................... 5-14 Test Your Knowledge ....................................................................................... 5-15 Quick Interaction: Lessons Learned ................................................................. 5-16 Solutions ........................................................................................................... 5-17
Chapter 6: Reporting
6-1
Objectives ........................................................................................................... 6-1 Introduction ......................................................................................................... 6-1 Prerequisite Information ..................................................................................... 6-2 Reporting Lab Overview ..................................................................................... 6-6 Participant List Reporting ................................................................................... 6-6 Lab 6.1 - Creating the Participant List ................................................................ 6-9 Certificate Information ...................................................................................... 6-17 Lab 6.2 - Creating the Certificate Confirmation Report .................................... 6-19 Invoice Posting ................................................................................................. 6-21 Lab 6.3 - Creating the Invoice Posting Report.................................................. 6-22 Summary .......................................................................................................... 6-27 Solutions ........................................................................................................... 6-32
ii
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Table of Contents Chapter 7: Statistics
7-1
Objectives ........................................................................................................... 7-1 Introduction ......................................................................................................... 7-1 Prerequisite Information ..................................................................................... 7-2 Seminar Statistics ............................................................................................... 7-3 Lab 7.1 - Creating FlowFields for Sums ............................................................. 7-5 Lab 7.2 - Creating the Seminar Statistics Page.................................................. 7-7 Summary .......................................................................................................... 7-10 Test Your Knowledge ....................................................................................... 7-11 Quick Interaction: Lessons Learned ................................................................. 7-13 Solutions ........................................................................................................... 7-14
Chapter 8: Dimensions
8-1
Objectives ........................................................................................................... 8-1 Introduction ......................................................................................................... 8-1 Prerequisites ...................................................................................................... 8-2 Code Walkthrough - Dimension Management Codeunit .................................... 8-4 Dimensions in Master Tables, Pages, and Codeunits ........................................ 8-5 Dimensions in Documents .................................................................................. 8-7 Dimensions in Posting ...................................................................................... 8-10 Summary .......................................................................................................... 8-27 Test Your Knowledge ....................................................................................... 8-28 Quick Interaction: Lessons Learned ................................................................. 8-29 Solutions ........................................................................................................... 8-30
Chapter 9: Interfaces
9-1
Objectives ........................................................................................................... 9-1 Introduction ......................................................................................................... 9-1 Prerequisite Information ..................................................................................... 9-2 File-Handling ...................................................................................................... 9-5 E-mail Confirmation ............................................................................................ 9-7 Lab 9.1 - Creating E-mail Confirmations .......................................................... 9-10 Using an XMLport ............................................................................................. 9-12 Lab 9.2 - Creating the XML Sem. Reg. - Participant List.................................. 9-14 Summary .......................................................................................................... 9-16 Test Your Knowledge ....................................................................................... 9-17 Solutions ........................................................................................................... 9-21
Chapter 10: Web Services
10-1
Objectives ......................................................................................................... 10-1 Introduction ....................................................................................................... 10-1 Web Services Overview ................................................................................... 10-2 Web Service Opportunities ............................................................................... 10-5 Creating, Exposing and Consuming Web Services .......................................... 10-6 Lab 10.1 - Creating a Web Service .................................................................. 10-8 Lab 10.2 - Create a Console Application to Consume the Codeunit Web Service ...................................................... 10-12 Page Web Services ........................................................................................ 10-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
iii
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Lab 10.3 - Create a Console Application to Consume the Seminar Card Page Web Service ..................................... 10-17 Lab 10.4 - Create an Infopath Form to Consume a New Page Web Service for Seminar Participants ................ 10-24 Summary ........................................................................................................ 10-33 Test Your Knowledge ..................................................................................... 10-34 Quick Interaction: Lessons Learned ............................................................... 10-36 Solutions ......................................................................................................... 10-37
Chapter 11: Optimizing For SQL Server
11-1
Objectives ......................................................................................................... 11-1 Introduction ....................................................................................................... 11-1 Classic Database Server for Microsoft Dynamics NAV .................................... 11-2 SQL Server for Microsoft Dynamics NAV ......................................................... 11-3 Representation of Microsoft Dynamics NAV Tables and Indexes in SQL Server ........................................................................... 11-4 Collation Options .............................................................................................. 11-6 SQL Server Data Replication ........................................................................... 11-7 Backup Options ................................................................................................ 11-9 SQL Server Query Optimizer.......................................................................... 11-11 Optimizing a Microsoft Dynamics NAV Application ........................................ 11-16 Overview of NDBCS ....................................................................................... 11-23 Optimization of Cursors .................................................................................. 11-25 Locking, Blocking, and Deadlocks .................................................................. 11-31 How SIFT Data is Stored in SQL Server ........................................................ 11-36 Summary ........................................................................................................ 11-48 Test Your Knowledge ..................................................................................... 11-49 Quick Interaction: Lessons Learned ............................................................... 11-53 Solutions ......................................................................................................... 11-54
Chapter 12: Deployment
12-1
Objectives ......................................................................................................... 12-1 Introduction ....................................................................................................... 12-1 Deployment Tasks ............................................................................................ 12-2 Ongoing Support Phase ................................................................................... 12-4 Upgrades and Updates .................................................................................... 12-6 Summary ........................................................................................................ 12-21 Test Your Knowledge ..................................................................................... 12-22 Quick Interaction: Lessons Learned ............................................................... 12-25 Solutions ......................................................................................................... 12-26
iv
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 Solution Development 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 Solution Development 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 Requirements
CHAPTER 1: CLIENT REQUIREMENTS Objectives The objectives are: •
Diagnosis - Executive Summary
•
Analysis - Functional Requirements
•
Data Model
•
Project Plan
Introduction The Diagnosis section of this chapter provides the "executive summary" of the business case, including the client's profile and a high-level description of their needs. The Analysis section describes the client's specific requirements for the system, including the data models based on those requirements and the basic project implementation plan. An essential step in effective solution development is the analysis of functional requirements encompassing data models and use cases. Proceeding with implementation without these materials is likely to result in an unpleasant experience, both for the developer and the customer. Documenting the project planning of the business case is the basis of the contract between the developer and the customer, and use cases help reveal flaws or deficiencies that may be present in the design, not just at the outset, but as the solution is implemented. In subsequent chapters, the Analysis, Design, and Development phases are broken down in chapter lab exercises. While these labs constitute separate development pieces of the project plan, they are interrelated and dependencies exist. The tasks for this project are defined by chapter, beginning with Master Tables and Pages and ending with Deployment. SQL Server performance and Web Services are also covered.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Diagnosis - Executive Summary This course is built on the assumption that the student is a certified Microsoft Dynamics® NAV Developer working for a Microsoft Certified Dynamics Partner. The project is for CRONUS International Training Academy, a software training center that is a branch of CRONUS International Ltd. Due to significant growth they require a new computer-based system that allows them to store and integrate all of their seminar, instructor, customer, and financial information in one solution. The client currently uses a full suite of Microsoft Dynamics NAV granules under the parent company CRONUS International Ltd. To take advantage of their investment and of the existing functionality and flexibility of Microsoft Dynamics NAV, they have decided to add a customized Seminar Management module to their current solution. This new module must allow them to do the following: •
Track their master data.
•
Register participants in their seminars.
•
Create invoices for customers.
•
Have an overview of their statistics.
The preliminary analysis and design of the processes and requirements is complete and is included in this training manual. If the client is satisfied with the Seminar Management module, this type of system can be sold to other training academies. The solution must therefore be developed in such a way that it can also be used by other prospective clients.
Analysis - Functional Requirements The client has defined their requirements for the new Seminar Management module with the following descriptions of how they run their training academy.
Seminars The CRONUS Training Department holds several different seminars. Each seminar has a fixed duration, and a minimum and maximum number of participants. In some cases seminars can be overbooked, depending on the capacity of the assigned room. Each seminar can be cancelled if there are not a sufficient number of participants. The price of each seminar is fixed, but it must be possible to assign additional expenses to an instance of a seminar, such as catering expenses or equipment rentals. Additional comments for each seminar are entered for required equipment or other particular requirements.
1-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client Requirements To take advantage of the current Job functionality in Microsoft Dynamics NAV, each seminar is to be defined as a Job. When a seminar is completed, the seminar is posted as a Job, with additional seminar-specific information. Each seminar is held in a seminar room. Some are held in-house and some are held off-site. If a seminar takes place in-house, a room must be assigned. For offsite rooms, the rental rate must be tracked as well.
Instructors Each seminar is taught by an instructor, who is a CRONUS employee or a subcontractor. To make use of existing Resource functionality, each instructor employee must be set up as a Resource in Microsoft Dynamics NAV. Existing Contact functionality is used by requiring each subcontractor instructor to be set up as a Contact, associated with a Vendor.
Participants Seminar participants must be set up as Contacts, each one associated with a Customer. These Customer/Contact relations are required for registration and invoicing. The system must also maintain additional participant information, such as the number and names of previously attended seminars.
Registration A Customer can register one or more participants for a seminar. The registration information must include how the seminar is invoiced, for example, whether to include expenses or catering.
Invoicing When each seminar is finished, the Customers with participants are invoiced. This is done with Job and Resource functionality.
Reporting and Statistics The customer requires that a number of reports and statistics be available. These include the following: •
A list of the participants registered for a seminar.
•
A list of the participants who have successfully completed each seminar. This is for the purpose of providing certificates. The certificates themselves are also produced by the system.
•
The total costs for each seminar, broken down according to what is and what is not chargeable to the customer.
•
Statistics for different time periods, for example: for a month; for last year; for this year; and cumulative (since day one).
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Interfaces The solution must allow e-mail notification to be sent to the Customer's participants in several situations, such as registration confirmation. Also, the participant list for a seminar must be exportable as an XML file.
Dimensions Analysis features must be provided by extending the standard customer dimension functionality in the Seminar Management module. Make Dimensions available for the following: •
Master files
•
Registrations
•
Posting
•
Invoicing
Calendars A calendar system must be created that provides an overview of the seminar dates to help in seminar planning. The calendar system must allow seminars to be: •
Viewed by date.
•
Filtered to view seminars with a specific seminar status, seminar room, or instructor.
Other Requirements To make the solution as user-friendly for the client as possible, keep the following requirements in mind throughout development:
1-4
•
Easy to learn - The Seminar Management module must be easy to understand, and the terminology and symbols must be consistent with the rest of the program. This means that if the user knows how to use other Microsoft applications, they are also able to intuitively learn this solution.
•
Efficient - Experienced users must be able to work with the program efficiently. This means that the most frequently used functions are accessible from the keyboard, making it possible to efficiently use both the keyboard and the mouse.
•
Clarity - The user interface must be intuitive so that the leastexperienced user can easily understand how the program functions.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client Requirements •
Good error reporting - The program must be built so that there are as few opportunities for error as possible. Error messages must explain the cause of the error and provide a suggestion as to how the user can correct the error.
•
Design consistency - Because the solution for the Seminar Management module may be sold as an add-on to other customers, it must adhere to the guidelines contained in the Microsoft Dynamics NAV 2009 Developer and IT Pro Help http://go.microsoft.com/fwlink?linkid=126282.
Data Model The following image displays the data model that encapsulates client's specification of the functional requirements. The asterisks identify those areas that are non-standard to Microsoft Dynamics NAV 2009 and will have to be created.
FIGURE 1.1 THE DATA MODEL
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Project Plan As in any other project, the business case is broken down into tasks, which make up the exercises in each chapter. There are dependencies among the labs and the technical complexity of the project increases as development progresses. The structure of the labs reflects the principles of the implementation methodology. Diagnosis and Analysis phases precede the development and testing of individual tasks. The end result of a chapter's labs is a deliverable for that particular stage of the project. The tasks for this project are: •
Master Tables and Pages (Chapter 2)
•
Registrations (Chapter 3)
•
Posting (Chapter 4)
•
Integration (Chapter 5)
•
Reporting (Chapter 6)
•
Statistics (Chapter 7)
•
Dimensions (Chapter 8)
•
Interfaces (Chapter 9)
•
Web Services (Chapter 10)
•
Optimizing SQL Server (Chapter 11)
•
Deployment (Chapter 12)
Summary Throughout this course each implementation phase or lab, is preceded by an Analysis and Design phase. This practice is meant to minimize the time it takes to implement a solution and optimize the solution's effectiveness.
1-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client Requirements
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-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
1-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages
CHAPTER 2: MASTER TABLES AND PAGES Objectives The objectives are: •
Use formalized analysis and design methodology.
•
Understand master table and page standards.
•
Work with table event triggers.
•
Work with the complex data types and their member functions.
•
Enable multi-language functionality.
•
Define the strategy for implementing Customers and Participants,
•
Create the tables to manage the seminar rooms.
•
Create instructor data management.
•
Create seminar data management.
•
Test the master tables and pages by following a test script.
Introduction In this chapter the requirements for master tables and pages for the solution are discussed before moving on to the Design and Implementation phases. The planning documentation in chapter 1 is used as a reference, particularly for the Analysis phase. Review the functional requirements in chapter 1 for general use case requirements. For example, the functional requirements state, "Customers can register one or more participants for a seminar."
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
A Quick Refresher In this chapter master tables, pages and triggers are all used to support the data required to implement the Serminar Management solution. Also, this chapter will enable multi-language support in some of the labs. These are concepts already familiar to those who have used Microsoft Dynamics NAV and completed the C/SIDE Introduction in Microsoft Dynamics® NAV 2009 course. These tools and concepts are reviewed here as a quick refresher.
Tables Tables define the structure for and storage of the data upon which a solution relies. Tables are stored in a database, either the Microsoft Dynamics® NAV database or SQL server, depending on the installation. At this point, the application code is not affected by the database choice. Performance implications depending on the database being used are discussed later. Master tables define the data-foundation upon which a solution relies. A solution may use additional non-master tables. Non-master tables contain information that is derived from the master tables. In this chapter master tables are created to support the data required to implement the solution.
Pages Master pages are pages that support the display and modification of the data stored in the master tables. There are two types of master pages in Microsoft Dynamics NAV as follows: •
Card pages
•
List pages
Both types are explicitly tied to master tables. The primary difference is that card pages display one record at a time, and list pages display multiple records at one time. In the RoleTailored client, clicking on an action for a master table will take you first to the associated list page from which you can access the cad page for a specific record.
Triggers Triggers are methods that execute when a system event occurs or when they are invoked by calling code. There are two types of active triggers, triggers that contain executable code. Event Triggers, which have names that start with "On..." fire when specific events occur. Example events are the insertion, modification or deletion of data.
2-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages Function Triggers are Developer defined (either as part of the base system or added as part of a customization). These triggers execute when they are called by coded logic. There is a third type of trigger, Documentation Triggers. Documentation Triggers contain no executable code, but contain only free-form documentation. These are intended to allow developers to document at the object level changes that they have made. This chapter explains how Event Triggers can be used to validate data values entered by the user.
Multi-Language Support Microsoft Dynamics NAV is multi-language enabled. This means that a localized version of Microsoft Dynamics NAV can present itself in different languages. In other words, two or more clients tied to the same database can present their User Interface in two or more different languages at the same time. Users can change the choice of language that is used to display text, and the change is immediate. There is no need to stop and restart Microsoft Dynamics NAV. Before starting to work in a multi-language-enabled database, set the working language to English - United States. Click Tools, click Language, and then select English - United States. To enable multi-language functionality when developing solutions, there are a few guidelines to follow. •
When creating objects in Microsoft Dynamics NAV, the Name property of an object must always be in English - United States (ENU), and it must never be visible to the user.
•
Language-specific names must be provided in the CaptionML property.
In this chapter, multi-language support is enabled in some of the labs.
Customers and Participants These two entities are key parts of a solution that provides a way to schedule seminars that are attended by participants and paid for by customers. This section discusses the strategy for implementing customers and participants.
Solution Analysis Even at this early stage, it is clear that representing customers and seminar participants requires master tables and pages, but it is important to resist the temptation to create these items immediately.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Regarding customers and seminar participants, the functional requirements in Chapter 1 stated: "Seminar participants come from a company that is set up as a customer in Microsoft Dynamics NAV. Every customer can register several participants for a seminar, but participants cannot be registered unless they are connected with a customer. This is necessary to invoice customers for the participation of their related contacts at seminars." This means that there must be a one-to-many relationship between customers and seminar participants. This is an important fact to consider during the design phase. The functional requirements also mention the need to invoice customers. This implies that a table with only a company name does not suffice. For example, the table used to represent customers must be complete with addresses, phone numbers, and accounts numbers. The exact requirements call for an analysis of all the solution elements, especially reports. However, this level of detailed analysis is not necessary in this course scenario.
Solution Design Before moving into the Implementation phase and creating new tables and pages, determine if any existing elements can be used instead. This helps to save time developing and debugging. Microsoft Dynamics NAV has many built-in tables and pages, and there are some that work for representing customers and seminar participants. These tables and forms are as follows: Table
Page
18 Customer
21 Customer Card 22 Customer List
5050 Contact
5050 Contact Card 5052 Contact List
The Customer tables and pages can be used to represent customers that enroll seminar participants. Participants can be represented by the Contact tables and pages. Additionally, there is a one-to-many relationship between the Customer and Contact tables in Microsoft Dynamics NAV, so this meets the requirements for this solution.
Development In this case, because of the complete Analysis and Design phases, no new development is necessary.
2-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages
Rooms The next step is to create the tables to manage the seminar rooms in which the seminars are held.
Solution Analysis The client's functional requirements describe the management of seminar rooms in this way: Each seminar is held in a seminar room. Some are held in-house and some are held off-site. If a seminar takes place in-house, a room must be assigned. For off-site rooms, the rental rate must be tracked as well. This description makes it clear that the table and pages used to represent seminar rooms need – at minimum – the location and number of the room, whether it is on-site or off-site, and the rental rate.
Solution Design The analysis of the room management process shows the need for only one basic table, a Seminar Room table, and the associated Card and List pages. The tracking of prices and costs is the complex part of representing rooms. However, the Resource table (156) provides a way of tracking this kind of information for company resources, such as employees or machinery. Leveraging the Resource table and its built-in behaviors eliminates the need to duplicate this functionality in the new Seminar Room table. The new table is associated with both the Contact table and the Resource table, as shown in the image.
FIGURE 2.1 RELATIONSHIP BETWEEN SEMINAR ROOMS, RESOURCES, AND CONTACTS
Before proceeding, review the pages as they appear when implementation is complete.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Seminar Room Card page, as shown in the image, displays one room at a time, and can be used to modify the data in the Seminar Room table.
FIGURE 2.2 SEMINAR ROOM CARD PAGE (123456703)
The Seminar Room Card page has two FastTabs:
2-6
•
A standard General FastTab
•
A Communication FastTab
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages The Seminar Room List page (123456704) allows multiple rooms to be displayed at once. It provides an overview of the seminar rooms, but does not allow the underlying Seminar Room table to be modified.
FIGURE 2.3 SEMINAR ROOM LIST (PAGE 123456704)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 2.1 - Create Seminar Room Tables and Pages Part of developing any solution is to tag and document objects when working on them, and thereby leaving a trail of all the changes that are made to the object. A short tag will go into the Version List Field in the object designer, which identifies the modified project. One example of such a tag is "CSD.02.01", which is short for C/SIDE Solution Development, Chapter 02, Lab 01. For simplicity, use the tag "CSD" in the version list. Inside each object that is modified include a short description of the change in the documentation trigger. It is recommended that this short description include the project tag, the date, the developer's name, and a short description of the change itself.
FIGURE 2.4 THE DOCUMENTATION TRIGGER
Scenario To begin the development of the Seminar module, the Seminar Room table must be created so that it can be integrated later with the base Microsoft Dynamics NAV 2009 system. Appropriate card and list pages to allow data entry and inquiry must also be developed and tested.
Step by Step 1. In the Comment Line table (97), add the option Seminar Room to the options for the field Table Name. It is recommended to add a few commas (unused options) before entering the new option value. This prevents an upgrade issue if Microsoft later adds new options to this field in the core application. Ensure that this change is also reflected in the same manner in the OptionCaption and the OptionCaptionML properties. The number of empty options (for example, commas) to add is an arbitrary decision, so in these labs, add five extra commas. 2. In the Extended Text Header table (279) and the Extended Text Line table (280), add the option Seminar Room to the options for the field Table Name. As with the Comment Line table, add five commas before the new option value, to keep some room for future additions to the option string. Ensure that the change is reflected in the caption properties as well.
2-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages 3. Create the Seminar Room table (123456702) with the following fields: No.
Field Name
Type
Length
Comment
1
Code
Code
10
Must not be blank
2
Name
Text
50
3
Address
Text
50
4
Address 2
Text
50
5
City
Text
30
6
Post Code
Code
20
Relation to the Post Code table (225)
7
Country/Region Code
Code
10
Relation to table 9 Country/Region
8
Phone No.
Text
30
ExtendedDataType = Phone No.
9
Fax No.
Text
30
ExtendedDataType = Phone No.
10
Name 2
Text
50
11
Contact
Text
50
12
E-Mail
Text
80
ExtendedDataType = E-Mail
13
Home Page
Text
90
ExtendedDataType = URL
14
Maximum Participants
Integer
15
Allocation
Decimal
16
Resource No.
Code
17
Comment
Boolean
FlowField; checks whether any lines exist on the Comment Line table for the Seminar Room table and the corresponding seminar room code Cannot be edited.
18
Internal/External
Option
Options: Internal, External
19
Contact No.
Code
•
Cannot be edited. 20
20
Relation to table 156 Resource, where Type=Machine
Relation to the Contact table (5050)
The primary key is Code. After the List page is created for this table, set the LookupFormID property to specify form/page 123456704 as the lookup form/page for this table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 NOTE: The extended data types are used by the system to associate certain standard built-in actions to certain types of fields. For example, a field that has the extended data type "URL" will have a button displayed next to the field that opens a web browser for the URL entered. In the same way, a field with the extended data type "E-Mail" will have a button displayed next to it that opens a new message for the email address that is entered into the field.
HINT: For all fields, set the Caption value to the Name. To save time, use F8 (Copy Previous shortcut). 4. Use the wizard to create the Seminar Room Card page (123456703) - create the FastTabs as shown in the image "SEMINAR ROOM CARD PAGE (123456703)" in the previous section. 5. From the Page area of the object designer, press F3 to create a new page. Enter "Seminar Room" or the table number 123456702 into the Table textbox to select the right table. Select "Card" as the page type. This will create an empty page object of the type Card. 6. In the first line, enter "Container" as the Type, and "Content Area" as the SubType. This will create the area on the page to display the fields in the Card. Enter a Name for the Container, such as SeminarRoomCardContainer. 7. Next create a line with the value "Group" in both the Type and the SubType, and enter "General" as the name and caption of the group. This will create the General FastTab that holds general Seminar Room fields. 8. Open the Field Menu, select the fields that go into the General FastTab, and then click into the page object. When the system asks for confirmation to add the fields, click "Yes" to accept the fields. 9. Create another Group for the "Communication" FastTab, and enter the correct fields into this FastTab. For the "Phone No." and "EMail" fields, set the "Importance" property to "Promoted", so that when the Communication FastTab is minimized, the phone number and email address of the seminar room will always be visible.
2-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages 10. Like most other Card pages, the Seminar Room Card page will have a RecordLinks factbox and a Notes factbox, which are standard factboxes provided by the system. A Container of the SubType "FactBoxArea" will be added to place these two factboxes on the page. This Container must be indented all the way to the left. Then add two "Part" type lines to the page, with the PartType property set to "System", and the SystemPartID property set to RecordLinks and Notes respectively. o RecordLinks are references to external files, Web sites, and more. For instance, an Item record can have a RecordLink to a user manual that is stored as a Word document in a network folder, or a URL can be added to a related Web page. RecordLinks are links which can be clicked that the system will attempt to open with the program that is associated with the type of link that is entered into the RecordLink. o Notes are part of application-wide functionality to add user defined notes to any record in the database. These notes are associated to the record automatically. Notes can be used for any appropriate purpose. 11. Add the Related Information menu item. Go to the first empty line at the bottom of the page designer and select "Actions" from the view menu. Create the menu as follows: Type/Subtype
Caption
ActionContainer / Related Information
Comment Select the SubType, move the cursor down off the line and move it back up. The Name and Caption will appear automatically with default values.
ActionGroup
&Seminar Room
Indented one level under the ActionContainer. Enter the caption, move the cursor down one line and move it back up. The name will appear automatically with a default value.
Action
Co&mments
Opens the Comment Sheet page (124) for the selected entry. Enter "View Comments" in the Image property. The link between the seminar room and the comment sheet is entered into the RunFormLink property. Link the field "Table Name" to the CONST "Seminar Room". Link the field "No." to the FIELD "Code".
Action
E&xtended Texts
Opens the Extended Text page (386) for the selected entry. Link this field the same as above.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
NOTE: The Action Designer Page can only be properly accessed when the first empty line at the bottom of the Page Designer is highlighted. Actions that are defined when the cursor is focusing on a line will not display when the page object runs. 12. Save and compile the page. Test run it by going to the Windows START menu, Click Run, then enter the command: dynamicsnav:////runpage?page=123456703 The RoleTailored client will open and display the page. 13. Use the wizard to create the Seminar Room List page (123456704) as shown in the GUI design in the image "SEMINAR ROOM LIST (PAGE 123456704)." The only fields necessary on this form are Code, Name, Maximum Participants, and Resource No. 14. Just like the Seminar Room Card page, start with the Page wizard. Select the Seminar Room table and set the Page Type to "List". 15. List pages also need a ContentArea as the first elements, and a Group element of SubType "Repeater". Add the specified fields to the Repeater group. 16. Just as on the Seminar Room Card page, add a FactBoxArea to the list page and include RecordLinks and Notes FactBoxes. 17. Enter "Seminar Room Card" as the CardFormID property. This property links the Seminar Room List page and the Seminar Room Card page together. When the List page is displayed, the user can double-click any record to view the details in the Card page that is specified in the CardFormID property. 18. Add the Related Information menu item as follows: Type/SubType
Options
Comments
ActionContainer / RelatedInformation Action Group
&Seminar Room
Action
Co&mments
Opens the Comment Sheet page (124) for the selected entry.
Action
E&xtended Texts
Opens the Extended Texts page (386) for the selected entry.
19. Set the Action links the same as for the Card page. 20. The table and pages are created, but they are not complete. It is necessary to add some code, mostly for the purposes of data validation which will be done in the next lab.
2-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages
Lab 2.2 - Adding Code for Seminar Rooms Within the Seminar Room table, certain fields require validation code in the appropriate triggers to ensure that data entered follows the defined business rules. Scenario The functionality of the City and Post Code fields must be enhanced. In Microsoft Dynamics NAV, the Post Code table links cities and post codes. Therefore, write code so that when a user enters a City, the program fills in the corresponding Post Code value from the Post Code table, and vice versa. The existing table, Post Code, has functions that help in doing this.
Challenge Yourself! Create the Seminar Room Card and List pages like those in the preceding Solution Design.
Step by Step 1. In the Seminar Room table, create a global C/AL variable called PostCode for the record Post Code. 2. Validate the City field using the ValidateCity function from the Post Code table. Use the C/AL Symbol Menu to lookup the parameters for this function and insert the following code in the City - OnValidate trigger: PostCode.ValidateCity(City,"Post Code");
3. Enter code so that when the user performs a lookup on the City field, the program runs the Post Code table's LookUpCity function. Use the C/AL Symbol Menu to determine what parameters must be sent to the function when calling it. When calling the function, set the ReturnValues parameter to TRUE. Solution: The City - OnLookup trigger code is as follows: PostCode.LookUpCity(City,"Post Code",TRUE);
4. Use the Post Code table's ValidatePostCode function to validate the value entered by the user in the Post Code field. Solution: The Post Code - OnValidate trigger code is as follows: PostCode.ValidatePostCode(City,"Post Code");
5. Enter code so that when the user performs a lookup on the Post Code field, the program runs the Post Code table's LookUpPostCode function. When calling the function, set the ReturnValues parameter to TRUE.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution: The Post Code - OnLookup trigger code is as follows: PostCode.LookUpPostCode(City,"Post Code",TRUE);
The next task is to improve the functionality of the Resource No. and Contact No. fields by retrieving information. In the following steps, create code so that when a user enters a Resource No. or a Contact No., if the Name field is empty, it is filled with the Name from the corresponding Resource or Contact record. 6. Create two global record variables, one for the Resource table and one for the Contact table. Standard Microsoft Dynamics NAV naming conventions dictate that these variables be called "Resource" and "Contact" respectively. However, the variable name "Contact" cannot be used because there is already a field by that name in the Seminar Room table. Instead, enter "MyContact" as the name of this variable. 7. Enter code so that when validating the Resource No. entered by the user, if the Name field in the Seminar Room table is empty, the program looks up the Name field in the corresponding Resource record and assigns it to the Name field in the Seminar Room table. Solution: Enter this code in the Resource No. -OnValidate trigger: IF Resource.GET("Resource No.") AND (Name = '') THEN Name := Resource.Name;
NOTE: For an expression in the form of Name = '' there is no blank character embedded between the quote marks, unless the instructions direct otherwise. 8. Enter code so that when validating the Contact No. entered by the user, if the Name field in the Seminar Room table is empty, the program looks up the Name field in the corresponding Contact record and assigns it to the Name field in the Seminar Room table. Solution: Enter this code in the Contact No. - OnValidate trigger: IF MyContact.GET("Contact No.") AND (Name = '') THEN Name := MyContact.Name;
9. Create two global record variables, one for the Comment Line and one for the Extended Text Header tables. 10. Enter code in the appropriate table trigger so that when a record is deleted, any corresponding records in the Comment Line table are deleted as well. HINT: Use the DELETEALL function to delete the records.
2-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages Solution: Enter this code in the OnDelete trigger: CommentLine.RESET; CommentLine.SETRANGE("Table Name",CommentLine."Table Name"::"Seminar Room"); CommentLine.SETRANGE("No.",Code); CommentLine.DELETEALL;
11. Enter code in the appropriate table trigger so that when a record is deleted, any corresponding records in the Extended Text Header table are deleted as well. HINT: Use the DELETEALL function again, but this time, ensure that the parameter is set to TRUE so that the code in the delete trigger of the Extended Text Header fires. The reason to set the parameter to TRUE for the Extended Text Header, and not for the Comment Line, is that the OnDelete trigger code for the Extended Text Header includes code to delete the associated Extended Text Line records. Solution: Add this code to the OnDelete trigger: ExtTextHeader.RESET; ExtTextHeader.SETRANGE("Table Name",ExtTextHeader."Table Name"::"Seminar Room"); ExtTextHeader.SETRANGE("No.",Code); ExtTextHeader.DELETEALL(TRUE);
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Instructors The next step is to create the instructor data management.
Solution Analysis The functional requirements in Chapter 1 describe the instructor functionality this way: "Each seminar is taught by an instructor, who is either a CRONUS employee or a subcontractor. To make use of existing Resource and Contact information, each instructor must be set up either as a Resource or as a Contact associated with a Vendor." With this information, define how instructors are managed in the module.
Solution Design According to the analysis of the management of instructor information, create one table for managing the instructors. Managing instructors is done the same way as managing the seminar rooms. Define them as resources to track their assignments, costs, and prices.
FIGURE 2.5 RELATIONSHIP BETWEEN INSTRUCTORS, RESOURCES, AND CONTACTS
2-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages Review the pages as they appear when complete, starting with the simplest page, the Instructors page. The Instructors page, as shown in the image, enables the entry of instructor information.
FIGURE 2.6 INSTRUCTORS PAGE (123456705)
Development The following labs implement the instructor functionality.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 2.3 - Creating Instructor Tables and Pages As with most enhancements of any consequence, the Seminar module requires multiple master data tables and supporting pages. Scenario The Seminar module also requires an Instructor table and a list page to inquire and update the data in that table.
Step by Step 1. Create the Instructor table (123456703) with the following fields: No.
Field Name
Type
Length
Comment
1
Code
Code
10
Must not be blank.
2
Name
Text
50
3
Internal/Exte rnal
Opti on
4
Resource No.
Code
20
Relation to table 156 Resource, where Type=Person.
5
Contact No.
Code
20
Relation to the Contact table (5050)
Options: Internal, External
The primary key is the Code field. NOTE: Specify the contents of the DataCaptionFields property for the table and a Caption property for each field in the table. 2. In the Instructor table, enter code so that when the program validates the value in the Resource No. field, if the Name field in the Instructor record is empty, the program fills it with the Name field from the corresponding Resource record. Do the same for the Contact No. field. HINT: Similar code was written in the previous lab. 3. Create the Instructors page (123456705) as shown in the GUI design.
2-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages
Seminars The next step is to create the seminar data management.
Solution Analysis The functional requirements in chapter 1 describe the seminar functionality in the following way: "The CRONUS training department holds several different seminars. Each seminar has a fixed duration, and a minimum and maximum number of participants. In some cases seminars can be overbooked, depending on the capacity of the assigned room. Each seminar can be cancelled if there are not enough participants. The price of each seminar is fixed." "To take advantage of the current Job functionality in Microsoft Dynamics NAV, each seminar is to be defined as a Job. When a seminar is completed, the seminar is posted as a Job, with additional seminarspecific information." From this description it is possible to create the following use case: "When defining a new seminar, seminar managers describe the course details, including information such as the seminar name, duration, price, maximum and minimum number of participants, and a Job code." As in the analysis of the seminar management process, there must be two tables to manage seminar information. The first table is a setup table where the user can define seminar numbering. The second table is to track the seminar profile information.
FIGURE 2.7 RELATIONSHIP BETWEEN SEMINARS AND OTHER ENTITIES
This description provides the information necessary to design and implement the seminar functionality.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution Design With the design complete, review how the pages appear when implementation is complete. The Seminar Setup Card page as shown, in the following image, allows the entry of setup information for the seminar.
FIGURE 2.8 SEMINAR SETUP (PAGE 123456702)
The Seminar Card page, shown in the following image, allows the entry of seminar details. The associated Fact Boxes allow entry of related Links and Notes.
FIGURE 2.9 SEMINAR CARD (PAGE 123456700)
2-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages The Seminar List page, as shown in the following image, provides an overview of the seminars, but does not allow the underlying Seminar table data to be modified.
FIGURE 2.10 SEMINAR LIST (PAGE 123456701)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 2.4 - Creating Seminar Tables and Pages The reality of a development project is an incremental effort to build the complete set of foundation tables and their attendant pages for use first in testing and subsequently in the production environment. Scenario Just as in the Lab 2.3 exercise, more tables (Seminar Setup and Seminar) must be created. Any time a new table is created, it is necessary to create at least a list page for data maintenance and display. If the table is a master data table, then generally both a card and list page are required for a full featured set of user tools.
Challenge Yourself! Create Seminar Setup tables and then create the associated Card page. Create the Seminar table and associated Card and List pages. The GUI designs for the page precede this Lab.
Step by Step To create the seminar master files and pages, do the following: 1. In the Comment Line table (97), add the option Seminar to the options for the field Table Name. Since the five commas and a new option (Seminar Room) were already added in the first lab in this chapter, it is not necessary to repeat the comma addition here. 2. In the Extended Text Header table 279 and the Extended Text Line table (280), add the option Seminar to the options for the field Table Name. 3. Create Table 123456701 Seminar Setup with the following fields: No.
Field Name
Type
Length
1
Primary Key
Code
10
2
Seminar Nos.
Code
10
Relation to 308 No. Series table.
3
Seminar Registration Nos.
Code
10
Relation to 308 No. Series table.
4
Posted Seminar Reg. Nos.
Code
10
Relation to 308 No. Series table.
o
2-22
Comment
Per Microsoft Dynamics NAV standards for setup tables, the key for this table is the Primary Key field, which is left blank.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages 4. Create the Seminar table (123456700) with the following fields: No.
Field Name
Type
Length
Comment
1
No.
Code
20
An alternate search field is the Search Name field.
2
Name
Text
50
3
Seminar Duration
Decimal
4
Minimum Participants
Integer
5
Maximum Participants
Integer
6
Search Name
Code
7
Blocked
Boolean
8
Last Date Modified
Date
Cannot be edited.
9
Comment
Boolean
FlowField; CalcFormula checks whether lines exist in the Comment Line table for the seminar. Cannot be edited.
10
Job No.
Code
11
Seminar Price
Decimal
12
Gen. Prod. Posting Group
Code
10
Relation to table 251 Gen. Product Posting Group.
13
VAT Prod. Posting Group
Code
10
Relation to table 324 VAT Product Posting Group.
14
No. Series
Code
10
Cannot be edited. Relation to table 308 No. Series.
o
Decimal places 0:1
50
20
Relation to table 167 Job. AutoFormat type is 1.
The primary key for this table is the No. field with a secondary key of Search Name.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 5. In the Seminar table, enter code to perform the following validation tasks: o When the user changes the No. value from what it is previously, the program gets the Seminar Setup record and uses the TestManual function of the NoSeriesManagement codeunit to test whether the number series is allowed to be manually changed. The program then sets the No. Series field to blank. HINT: Use the xRec variable to test whether the No. field is modified. To perform this task a record variable is needed with a subtype of Seminar Setup and a Codeunit variable of subtype NoSeriesManagement. Remember that there is only one record in the Seminar Setup table and the primary key field is left null. Solution: IF "No." <> xRec."No." THEN BEGIN SeminarSetup.GET; NoSeriesMgt.TestManual(SeminarSetup."Seminar Nos."); "No. Series" := ''; END;
o
When the user enters or changes a value in the Name field, if the Search Name is still equal to the uppercase value of the previous Name or if the Search Name is blank, the program assigns the new Name to Search Name.
HINT: Use the function UPPERCASE when testing the Search Name field. Solution: IF ("Search Name" = UPPERCASE(xRec.Name)) OR ("Search Name" = '') THEN BEGIN "Search Name" := Name; END;
o
When the user enters or changes a value in the Job No. field, the program retrieves the corresponding Job record and checks that the Blocked field is set to .
HINT: Use the TESTFIELD function to check a field's value. Solution: Job.GET("Job No."); Job.TESTFIELD(Blocked, Job.Blocked::" ");
2-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages o
When the user changes the Gen. Prod. Posting Group to a new value, the program checks that the function ValidateVatProdPostingGroup for the Gen. Product Posting Group table returns true. If it does, the program sets the VAT Prod. Posting Group to the Def. VAT Prod. Posting Group value from the Gen. Product Posting Group table.
Solution: IF xRec."Gen. Prod. Posting Group" <> "Gen. Prod. Posting Group" THEN BEGIN IF GenProdPostingGrp.ValidateVatProdPostingGroup(GenProdPostin gGrp,"Gen. Prod. Posting Group") THEN BEGIN VALIDATE("VAT Prod. Posting Group",GenProdPostingGrp."Def. VAT Prod. Posting Group"); END; END;
6. In the Seminar table, create a new function named AssistEdit with a return type of Boolean. In this function, enter code that checks for a Seminar Nos. series in the Seminar Setup table. If it finds one, the program uses the SelectSeries function in the NoSeriesManagement codeunit to check the series number. If this function returns true, the program uses the SetSeries function in the NoSeriesManagement codeunit to set the No. field, and the program then exits TRUE. Solution: WITH Seminar DO BEGIN Seminar := Rec; SeminarSetup.GET; SeminarSetup.TESTFIELD("Seminar Nos."); IF NoSeriesMgt.SelectSeries(SeminarSetup."Seminar Nos.",xRec."No. Series","No. Series") THEN BEGIN SeminarSetup.GET; SeminarSetup.TESTFIELD("Seminar Nos."); NoSeriesMgt.SetSeries("No."); Rec := Seminar; EXIT(TRUE); END; END;
7. In the Seminar table, enter code in the appropriate table triggers to perform the following tasks: o Document the code. o When a record is inserted, if the No. field is blank, the program gets the Seminar Setup record and runs the InitSeries function of the NoSeriesManagement codeunit to initialize the series.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution: Enter the following code in the OnInsert trigger: IF "No." = '' THEN BEGIN SeminarSetup.GET; SeminarSetup.TESTFIELD("Seminar Nos."); NoSeriesMgt.InitSeries(SeminarSetup."Seminar Nos.",xRec."No. Series",0D,"No.","No. Series"); END;
o
When a record is modified or renamed, the program sets the Last Date Modified to the current date.
HINT: Use the TODAY function to get the current date. Solution: Enter the following code in the OnModify and OnRename triggers: "Last Date Modified" := TODAY;
o
When a record is deleted, the program deletes the corresponding records from the Comment Line table and the Extended Text Header table.
HINT: Similar code was created for the Seminar Room comment and extended text records. 8. Create the Seminar Setup page (123456702) as shown in the GUI design. 9. Enter code in the appropriate trigger of the Seminar Setup page so that when the user opens the form, the program resets the record, and if it does not get a record, it inserts a new one. Solution: Enter the following code in the Page - OnOpenPage trigger: RESET; IF NOT GET THEN INSERT;
10. Create the page 123456700 Seminar Card as shown in the GUI design. o Set the property to update the page when it is activated. o Add the Related Information menu item as follows: Type/SubType
Options
ActionContainer / RelatedInformation ActionGroup
2-26
Comment Enter a reference name such as SeminarCardSetupContainer
&Seminar
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages Type/SubType
Options
Comment
Action
Co&mmen ts
Opens the Comment Sheet page (124) for the selected entry.
Action
E&xtende d Texts
Opens the page 386 Extended Texts for the selected entry.
Solution: Enter the following code in the No. - OnAssistEdit trigger: IF AssistEdit THEN CurrPage.UPDATE;
o
Enter code in the appropriate trigger so that after the page gets the record, the program removes the table's filter on the No. field.
11. Create the Seminar List page (123456701) according to the GUI Design section. Include the fields No., Name, Seminar Duration, Minimum Participants (not visible), Maximum Participants (not visible), Seminar Price, Gen. Prod. Posting Group, VAT Prod. Posting Group, and Job No. o Make the page so that it cannot be edited. o The navigation from this page is the same as the Seminar Card page, so add the same options to the Actions menu as the actions on the Seminar Card. HINT: Line items and action items can be copied from one page to another.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Testing With the master tables and pages in place, it is critical that the functionality is tested. To this end, a test script can be used. Because not all solution pieces are coded, the test script may seem incomplete at this point. Since none of the pages are set up in a Role Center, the pages will be tested from the command prompt, as described in the test script steps. NOTE: To test the Email functionality, the system that is being used must have Microsoft® Outlook® running with a profile set up.
Steps 1. Start by running the page 123456702 Seminar Setup from the Run command. Click the Start button and select "Run." Enter Dynamicsnav:////runpage?page=123456702, and click OK. The fields in this page are blank because they are not yet set up. Select "Edit" from the "Actions" menu so the page can be edited. Click the drop-down list for Seminar Nos. Seminars are now setup to use the standard Microsoft numbering functionality. o Set up all three numbers by choosing any values. o Set to Default automatically o Close and re-open the Seminar Setup page to verify that the values are saved. 2. Run the page 123456700 Seminar Card from the Run command. o If the page opens on an existing Seminar record, select "New" from the "Actions" menu or use the 'Ctrl + N' shortcut keys to open the page with a new record. o Tab off the No. field and be sure that a number is assigned with the values that are set up in step 1. o Fill in the fields under the General FastTab and then move to the Invoicing FastTab. o Use the dropdown to select a Gen. Prod. Posting Group that has a Default VAT Prod. Posting Group set up. o When selecting this record, be sure that the VAT Prod. Posting Group fills in automatically. 3. On the Seminar Card page, use the Related Information menu to enter comments and extended texts. When finished, close the Seminar Card page. 4. Run the page 123456701 Seminar List from the Run command, Dynamicsnav:////runpage?page=123456701. Doubleclick on an existing record and verify that the Seminar Card page opens up in Edit mode, with the selected record.
2-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages 5. The Seminar module is now designed so that Instructors are set up as Resources and Contacts in the system. o Set up a new Resource (type Person) and Contact to use to test the Instructor functionality. o When done, run the page 123456705 Instructors from the Run command. o Enter a new instructor using the Internal/External Option in combination with the Resource and Contact lookup buttons to select the Resource and Contact set. o Note that when using the Resource lookup, all the Resources in the list are of type Person. Try entering a Resource No. or Contact No. that does not exist to test the validation. o When you have finished close the Instructors page. 6. The Seminar module is now designed so the Rooms are set up as Resources of type Machine and Contacts in the system. o Set up a new Resource and Contact to test the Seminar Room functionality. o When finished, run the page 123456703 Seminar Room Card from the Run command. o If the page opens up with an existing record, select "New" from the "Actions" menu and verify that the Seminar Room page opens up with a new blank record. o Create a new Seminar Room by entering a value in the Code field. 7. Code is added so that the Name field defaults from the Resource or Contact if the Name field is blank. o Ensure that code is functioning. o On the Communications tab, try entering an E-Mail address and Home Page and use the command buttons next to them. o Check the items on the "Related Information" menu. 8. Run the page 123456704 Seminar Room List from the Run command and ensure that the Seminar Room Card page opens up when double-clicking on the existing Seminar Room record on the List page.
Summary In this chapter, two of the most fundamental object types, tables and pages, are used to put the foundation for the solution in place. The tables define and store the data for the solution, and the pages provide an intuitive interface with which the user can interact with the table data. Defining the tables requires analysis of the relationships between the entities represented by each table. Implementation of the tables is easier if the simpler tables, those with fewer dependencies, are defined first.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-29
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. Where is internal documentation located for new objects?
2. To ensure that Microsoft Dynamics NAV's multilanguage functionality is properly enabled, which property must be set for controls?
3. In the Seminar table, a check is performed to ensure that the value in the Minimum Participants field is always less than the value in the Maximum Participants field in each of the following situations: •
Whenever a record is inserted.
•
Whenever a record is changed.
•
Whenever a value is entered in the Maximum Participants field and the Minimum Participants field is not empty.
4. a) Which table and field event triggers are used for these three checks?
2-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages 5. b) What code is used to perform these checks?
6. What do the Rec and xRec record variables do?
7. What function is used to retrieve a specific record using its primary key?
8. Using the table shown below, answer the following questions: Table: Employee (key = Employee No.) Employee No. 5834 3723 3475 6434
Name John Doe Ann Smith Bill Skaggs Todd Lawrence
Department Purchasing Sales Receivables Sales
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-31
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Employee No. 9482 0980 9483
Name Janet Davila Susan Morris Rick Hamilton
Department Receivables Purchasing Sales
a) Assuming that work is being performed with the record variable EmployeeVar, what code needs to be written to get the record for Employee No. 3475? b) What code can be written to jump to the fourth next record? c) What code can be written to jump to the last record in the table? d) What code is used to define a record set to include the records between employee number 3475 and 6434? e) What code is used to define a record set to include the records greater than 5834? f) What code is used to define a record set for employees in the Purchasing department only? g)What code is used to remove the filter on department? h) What code is used to change Ann Smith's department from Sales to Purchasing? i) What code is used to delete all Receivables employees?
2-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages 9. What is the standard way to associate a Card page with a List page?
10. What two triggers does a Codeunit have by default?
11. How are functions and access to related tables defined on pages?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-33
C/SIDE Solution Development 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.
2-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages
Solutions Test Your Knowledge 1. Where is internal documentation located for new objects? MODEL ANSWER: Internal documentation for new objects is located in the Documentation trigger, which is available in every object. Comments can be entered in this trigger without having to enter them as code remarks. 2. To ensure that Microsoft Dynamics NAV's multilanguage functionality is properly enabled, which property must be set for controls? MODEL ANSWER: The CaptionML property is used to define multi-language captions, one for each language that the user can select. 3. In the Seminar table, a check is performed to ensure that the value in the Minimum Participants field is always less than the value in the Maximum Participants field in each of the following situations: •
Whenever a record is inserted.
•
Whenever a record is changed.
•
Whenever a value is entered in the Maximum Participants field and the Minimum Participants field is not empty.
4. a) Which table and field event triggers are used for these three checks? 5. b) What code is used to perform these checks? MODEL ANSWER: a) In the OnValidate trigger of each relevant field and in the OnInsert and OnModify triggers of the table. It is best to create a new function that checks the values and enter a call to this function in the relevant table triggers. b) The suggested code is in the form of a Function named MinMaxParticipantsCheck MinMaxParticipantsCheck IF ("Minimum Participants" <> 0) AND NOT ("Maximum Participants" > "Minimum Participants") THEN ERROR(Text500);
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-35
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 6. What do the Rec and xRec record variables do? MODEL ANSWER: The Rec record variable specifies the values of the current record, including the changes that are made. The xRec record variable specifies the original values of the record, before the changes. 7. What function is used to retrieve a specific record using its primary key? MODEL ANSWER: To retrieve a function using its primary key, the GET function is used. 8. Using the table shown below, answer the following questions: Table: Employee (key = Employee No.) Employee No. 5834 3723 3475 6434 9482 0980 9483
Name John Doe Ann Smith Bill Skaggs Todd Lawrence Janet Davila Susan Morris Rick Hamilton
Department Purchasing Sales Receivables Sales Receivables Purchasing Sales
a) Assuming that work is being performed with the record variable EmployeeVar, what code needs to be written to get the record for Employee No. 3475? b) What code can be written to jump to the fourth next record? c) What code can be written to jump to the last record in the table? d) What code is used to define a record set to include the records between employee number 3475 and 6434? e) What code is used to define a record set to include the records greater than 5834? f) What code is used to define a record set for employees in the Purchasing department only? g)What code is used to remove the filter on department? h) What code is used to change Ann Smith's department from Sales to Purchasing? i) What code is used to delete all Receivables employees?
2-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Master Tables and Pages MODEL ANSWER: a) EmployeeVar.GET('3475'); b) EmployeeVar.NEXT(4); c) EmployeeVar.FINDLAST; d) EmployeeVar.SETRANGE("No.",'3475','6434'); e) EmployeeVar.SETFILTER("No.",'>5834"); f) EmployeeVar.SETRANGE("Global Dimension 1 Code",'PURCHASE'); (NOTE: This code assumes that Global Dimension 1 is used for DEPARTMENT, and that the value PURCHASE is the value for the purchasing department.) g) EmployeeVar.SETRANGE("Global Dimension 1 Code"); h) EmployeeVar.GET('ANNSMITH');// assuming that is her No. EmployeeVar.VALIDATE("Global Dimension 1 Code",'PURCHASE'); EmployeeVar.MODIFY(TRUE); i) EmployeeVar.SETRANGE("Global Dimension 1 Code",'RECEIVABLES'); EmployeeVar.DELETEALL; 9. What is the standard way to associate a Card page with a List page? MODEL ANSWER: The standard way to associate a Card page with a List page is by setting the "CardFormID" property on the List page. 10. What two triggers does a Codeunit have by default? MODEL ANSWER: Documentation and OnRun 11. How are functions and access to related tables defined on pages? MODEL ANSWER: Functions and access to related tables are defined on pages by defining the selections in the Actions menu, which can be accessed by moving the cursor to the first available empty line in the page designer and then selecting "Actions" from the View menu. The Type of the action defined as "ActionContainer" and the Subtype of the action is defined as any of the available system values, depending on where the action needs to be on the page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-37
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
2-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations
CHAPTER 3: REGISTRATIONS Objectives The objectives are: •
Import and export objects as text files.
•
Support multilanguage functionality.
•
Use main and subpages (document pages).
•
Use virtual tables.
•
Use temporary tables.
•
Review the various types of tables
•
Review of C/AL functions
•
Create additional tables and user interfaces (pages) to maintain registrations
•
Test the results of the Labs
Introduction Now that the master tables and pages are in place, the next step is to implement functionality to allow users to perform transactions with the master data. As with the tasks in the previous chapter, this requires frequent referral to planning documentation, including the Analysis, Design, and Implementation phases. Before starting the Analysis phase, however, there are some concepts and features that are necessary during the Implementation phase. They are as follows: •
Working with objects as text files
•
Multi-language support
•
Document pages
•
Table types
•
Useful C/AL functions
By the end of this chapter, the tables and pages that are necessary for registering participants in seminars will be in place.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Prerequisite Information Before getting into the subject of registration, there is some information that must be reviewed.
Working with Objects as Text Files Analyzing and modifying objects can sometimes be much easier when the objects are in text file format. Any object in the Object Designer can be exported as text and imported back into Microsoft Dynamics® NAV as an uncompiled object. To export one or more objects as a text file, follow these steps: a. Select the object or objects in the Object Designer. b. Click file, and then click export in the menu bar. c. In the Export Objects dialog window, select Text Format as the Save as type, and then enter a file name. d. Click OK. One text file is created containing the text representations for the object or objects. The resulting text file contains all the details of the object. The first line for every object in the file begins with the word OBJECT, the object type, number, and name. The text for the rest of the object follows. For example: OBJECT Table 123456703 Instructor { OBJECT-PROPERTIES { Date=09/26/08; Time=[ 6:41:44 AM]; Modified=Yes; Version List=CSD; } PROPERTIES { DataCaptionFields=Code,Name; } FIELDS { { 1 ; ;Code ;CaptionML=ENU=Code; NotBlank=Yes } { 2 ; ;Name ;CaptionML=ENU=Name } { 3 ; ;Internal/External ;CaptionML=ENU=Internal/External;
3-2
;Code10
;Text50 ;Option
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations OptionString=Internal,External } { 4 ; ;Resource No. ;Code20 ;TableRelation=Resource.No. WHERE (Type=CONST(Person)); OnValidate=BEGIN IF Resource.GET("Resource No.") AND (Name = '') THEN Name := Resource.Name; END;
CaptionML=ENU=Resource No. } { 5 ; ;Contact No. ;TableRelation=Contact.No.;
;Code20
OnValidate=BEGIN IF Contact.GET("Contact No.") AND (Name = '') THEN Name := Contact.Name; END;
CaptionML=ENU=Contact No. } } KEYS { { ;Code ;Clustered=Yes } } FIELDGROUPS { } CODE { VAR Resource@1000000000 (mailto:Resource@1000000000) : Record 156; Contact@1000000001 (mailto:Contact@1000000001) : Record 5050; BEGIN { CSD - MM/DD/YYYY - D.E. Veloper Chapter 2 Lab 3 - Created table } END. } }
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 OBJECT-PROPERTIES Section This section contains the object's date, time, and version properties. PROPERTIES Section This section includes the table object's OnInsert, OnModify, OnDelete and OnRename triggers, and general table properties. Triggers are only included in the text file when they contain C/AL code. Properties are only included when the value is set to something other than the default value. Properties that have default values and triggers without any C/AL code do not show up in an object's text file. SUB-OBJECTS Section This section lists the sub-objects. For tables, these consist of FIELDS and KEYS. This section contains the sub-object properties that do not contain default values and the triggers that contain code. CODE Section This section contains the global variables and functions for the object. Once the text files are changed and saved, import the text file back into Microsoft Dynamics NAV. 1. Open the Object Designer. 2. Click File, and then click Import. 3. Select the appropriate file in the Import Objects dialog window and click Open. The object or objects are imported. The objects must be compiled before they can be used. The Import Worksheet The Import Worksheet cannot be used when importing a text file, which means the following: •
No warning is received about overwriting existing tables.
•
There is no opportunity to skip the import of some objects.
•
There is no opportunity to merge objects.
Multilanguage Functionality in Text Messages When creating messages for the user, ensure that the text and the object names in the messages are enabled for multilanguage functionality. Error and text messages must be entered as text constants so that they can be easily translated. The C/AL Globals and C/AL Locals forms in the C/AL Designers have a Text Constants tab with a (normally) hidden column, ConstValueML. This column displays all the languages for a text constant. Text constants replace the use of hard-coded, language-dependent text strings.
3-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations Once it is assigned as a text constant, the message can be used in code as in the following example: ERROR(Text001); //where Text001 is defined as Text Constant in the global or local variables
The following example uses the FIELDCAPTION function within an error message. The Text Constant 025 value is "Please enter "Yes" in %1 and/or %2 and/or %3". ERROR(Text025,FIELDCAPTION(Receive), FIELDCAPTION(Invoice), FIELDCAPTION(Ship));
When the code is run, the error message translates into: Please enter "Yes" in Receive and/or Invoice and/or Ship. When referring to fields in a message, the code must refer to the caption rather than the name of the field. By using the FIELDCAPTION function, the current caption of a field is returned as a string. The field property CaptionML must be populated to enable this functionality. The TABLECAPTION function can be used to return the table name. The following code returns the caption of the Document Type field: SalesLine.FIELDCAPTION("Document Type");
Document Pages A Document page (also commonly referred to as a Header/Line page) is a combination of a card page and a list page. It is used to display records from two tables with a one-to-many relationship, all on one page. The Card part of this type of page acts as a master page for the main table, and the subpage part lists the related records from the second table. For example, the Sales Invoice page (Page 43) is used to create, view, or modify sales invoice documents. Just like any other Card page, it displays fields from the Header table grouped in a number of FastTabs. In addition to the FastTabs that group fields of the main records, the page also has a special type of FastTab that displays the subpage, which displays the records that are related to the main record. The main page is associated with the header table, Sales Header (Table 36). The subpage (Page 47) is associated with the line table, Sales Line (Table 37). The two pages are linked together by the Document Type and Document Number fields, which are the fields that define the relationship between the Sales Header table and the Sales Line table. In the page designer, a subpage control is defined with a Type of 'Part'. The ID of the subpage and the link to the main page is defined in the properties. In the properties of the subpage's Part element, the "PagePartID" property is set to the "Sales Invoice Subform" (Page 47). To link the subpage records to the current Sales Header record, the SubFormLink property is set.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Sales Invoice subpage indicates that the page is associated to the line table, Sales Line (Table 37). The page itself is a tabular page with a Repeater element that contains certain fields from the table. The key fields from the Sales Line (Document Type, Document No., and Line No.) are NOT displayed. Since this is a worksheet type page, it adheres to the following standards: •
The key fields from the Sales Line (Document Type, Document No., and Line No.) are NOT displayed. The values of the Document Type and Document No. fields are automatically populated by the link between the main page and the subpage.
•
AutoSplitKey property is set to Yes. This property causes the Line No. field to be automatically populated by the system.
Standard Microsoft Dynamics NAV naming conventions for these forms and tables are: Type
Naming Convention
Example
Document Table (Header)
Name of Transaction or Document + 'Header'
Sales Header (Table 36)
Document Table (Line)
Name of Transaction or Document + 'Line'
Sales Line (Table 37)
Document Page
Name of Document Represented
Sales Invoice (Page 43)
Document Subpage
Name of Document Represented + "Subform"
Sales Invoice Subform (Form 47)
To follow Microsoft Dynamics NAV standards, the Seminar Registration window in this chapter is similar to the existing Sales Invoice window. For more information about design standards, refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help, on the Microsoft Download Center: http://go.microsoft.com/fwlink?linkid=126282.
Types of Tables Up until now, regular database tables were used to implement the Seminar module. The upcoming exercises make use of other types of tables.
Virtual Tables A virtual table contains information provided by the system and is presented in C/SIDE as table objects, so that handling this information is done the same way that physical tables are handled. C/SIDE provides access to a number of virtual tables. They work in much the same way as regular database tables, but the information in them cannot be changed – they contain read-only information. Virtual tables are not stored in the database as normal tables are, but are computed by the system at run time.
3-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations Because a virtual table can be treated the same as an ordinary table, the same methods can access their information. For example, use filters to get subsets or ranges of integers or dates. Here is a list of virtual tables that are available in Microsoft Dynamics NAV 2009: •
Date
•
Integer
•
File
•
Drive
•
Monitor
•
Session
•
Database File
•
Table Information
•
Field
•
Server
•
Windows Object
•
Windows Group Member
•
SID – Account ID
•
User SID
•
Several others
Because the virtual tables are not stored in the database, they cannot be viewed directly from the Object Designer. The content of a virtual table can be viewed in a tabular page and accessed by C/AL code. The virtual tables have the highest numbers in the table list (they are listed in the 2000000000+ object range when designing an object that can be based on a table, such as pages, reports, dataports, and more). Refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help for additional information on a number of the virtual tables. The Date virtual table is used for the Seminar Registration process. The Date virtual table provides easy access to days, weeks, months, quarters, and years. This table has three fields as follows: •
Period Type: Days, weeks, months, quarters, or years
•
Period Start: The date of the first day in the period
•
Period End: The date of the last day in the period
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Temporary Tables A temporary table is a memory-based table; a record type variable that exists only in the computer's memory. Temporary tables are not physical tables in the database, but are always based on physical tables. Unlike virtual tables, they are not read-only. A temporary table can do almost anything that a normal database table can, but the information in the table is lost when the table is closed. The write transaction principle that applies to normal database tables does not apply to temporary tables. Refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help for more information on the transaction principle. The advantage of using a temporary table is that all interaction with a temporary table takes place on the client or on the server tier. This reduces the load both on the network and on the server. To perform many operations on data in a specific table in the database, it can be beneficial to load the information into a temporary table for processing. Because all operations are local to the server tier, this speeds up the process. Creating a temporary table is similar to creating a record variable; use the following steps: 1. In either the C/AL Globals or C/AL Locals variable window, define a variable with the data type Record. Select a table in the Subtype field. 2. Open the Properties window for the variable, and set the Temporary property to Yes. A record type variable is by default linked to a physical table in the database. By setting a record variable's Temporary property to Yes, the record variable becomes a temporary table.
System Tables System Tables are stored in the database just like regular tables, but they are different because they are created automatically by the system. System table data can be read, written, modified, and deleted. The eight system tables in C/SIDE are primarily used to manage security and permissions. Refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help for detailed information on each one of the System Tables.
Additional Functions In the C/SIDE Introduction Course, the following functions were introduced. These functions are used later in this chapter. Refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help for more information.
3-8
•
CALCDATE
•
DATE2DMY
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations •
DATE2DWY
•
ROUND
•
RUNMODAL
•
CONFIRM
•
MESSAGE
•
ERROR
•
TESTFIELD
•
WORKDATE
•
VALIDATE
•
FORMAT
•
COUNT
Page Functions Page functions are called through the CurrPage variable. This variable is a reference to the instance of the current page. The table contains several of the most useful page functions available. Refer to the online Microsoft Dynamics NAV 2009 Developer and IT Pro Help http://go.microsoft.com/fwlink?linkid=126282 for a complete list. Function
Description
CurrPage.UPDATE
Use this function to save the current record and then update the controls in the page. If the SaveRecord parameter is set to TRUE, this function saves the record before the system updates the page.
CurrPage.SETSELECTION FILTER
Use this function to have the system note the records the user has selected on the page, mark those records in the table specified, and set the filter to "marked only".
CurrPage.CLOSE
Use this function to close the current page.
CurrPage.EDITABLE
Use this function to return the current setting of the Editable property and to change the setting of the property. Most, but not all properties can also be changed from within code. This property is especially useful for using the same page for viewing and editing, but only allow some users to edit the records.
Control Functions Microsoft Dynamics NAV also has a number of properties at the page and control level which can be modified at run time. Examples of these are the Visible and Editable properties. If the Visible property is True, then the page or control (depending on which level of property is being considered) can be seen. If it is False, the page or control, as appropriate, cannot be seen. The Editable property operates in a similar manner.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help for more information on control functions. If the information in the Help files is not specific on which functions can be changed at run time, review of standard NAV 2009 code or even some experimentation may be required. Properties such as Editable and Visible can be changed at runtime in a page. See Customer Card (or Vendor Card) for the Contact Control Editable property settings as an example.
Registrations Now that the master data is complete, make it possible for users to apply the master data to daily transactions related to registrations.
Solution Analysis The functional requirements define the role of registrations in the following way: "If a customer wants to register one or more participants for a seminar, enter the relevant information into a registration page." Therefore, the main process related to registrations is managing seminar registrations. There is an additional optional requirement to manage seminar planning. This use case and related exercise is covered in the Additional Exercises section. Based on the results of the diagnosis, the analysis and implementation phases of this chapter are the following use case: •
Managing Seminar Registration
The client's functional requirements describe the process of seminar registration in the following way: "A customer can register one or more participants for a seminar. Each registration is assigned a job number. It must be possible to assign additional expenses to an instance of a seminar, such as catering expenses or equipment rentals. The registration information must include how the seminar is to be invoiced (for example, whether to include expenses or catering)." "Additional comments for each seminar can be entered to allow for things like necessary equipment or other particular requirements."
3-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations Therefore, registering a participant in a seminar must accomplish or allow the following items: •
A place is reserved for the participant in the seminar
•
Invoicing information is gathered and stored
•
The appropriate facilities are reserved
•
The seminar and participant information can be tracked with a job number
•
Additional expenses can be invoiced as well
The next step is to define the process of creating a new seminar. Once the details of a seminar are established, a seminar manager can create an instance of the seminar with this information: •
An instructor
•
An available and properly equipped room
•
Any charges or additional comments
Once the seminar is created, a customer training manager can add participants to the seminar. The following illustration shows this scenario.
FIGURE 3.1 THE SEMINAR MANAGEMENT FLOWCHART
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution Design The analysis of the seminar registration management process shows there are two main processes: •
The creation of seminar instances o o o
•
Define seminar registration details Assign additional comments Assign seminar charges
The registration of participants
The following illustration shows the relationship between the system tables and the pages used to control these. Here, the prerequisite tables are shown to the left, the main processing tables are in the middle and the subprocess tables are to the right.
FIGURE 3.2 SEMINAR REGISTRATION RELATIONSHIPS
GUI Design The pages for the seminar registration and the navigation between them reflect the relationships shown in the previous diagram. Start by defining the simplest pages first so they can be integrated with the more complex pages at the end of the GUI design.
3-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations The Seminar Comment List page displays the comments for a seminar as shown in the following illustration.
FIGURE 3.3 SEMINAR COMMENT LIST PAGE (123456707)
The Seminar Comment Sheet page, as shown in the following illustration, enables the entry of comments for a seminar.
FIGURE 3.4 SEMINAR COMMENT SHEET PAGE (123456706)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Seminar Charges page, as shown in the following illustration, enables the entry of charges for a seminar.
FIGURE 3.5 THE SEMINAR CHARGES PAGE (123456724)
3-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations Since the seminar registration and participant registration are so closely linked, it is best to handle them in one window with header and lines as shown in the following illustration. This Document page actually consists of two pages, a header page, and a subpage that contains the lines.
FIGURE 3.6 THE SEMINAR REGISTRATION PAGE (MAIN 123456710, SUBPAGE 123456711)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
FIGURE 3.7 THE SEMINAR REGISTRATION PAGE, WITH THE SEMINAR ROOM FASTTAB AND THE INVOICING FASTTAB EXPANDED
3-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations The Seminar Registration List page, as shown in the following illustration, displays the seminar registrations.
FIGURE 3.8 THE SEMINAR REGISTRATION LIST PAGE IN THE ROLETAILORED CLIENT (123456713)
Table Design The following tables are required for registrations: Table
Description
Table 123456710 Seminar Registration Header
Holds the information for one instance of a Seminar, which is referred to as a registration.
Table 123456711 Seminar Registration Line
Holds the information for one participant in a seminar registration.
Table 123456704 Seminar Comment Line
Holds comments for the seminar registrations.
Table 123456712 Seminar Charge
Holds charges related to the seminar registration. These are in addition to the individual participant charges of the Seminar Registration Line table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 3.1 - Creating the Tables and Pages for Seminar Registration In Chapter 2 labs, the master tables for the Seminar module were created. Now the variety of transaction tables and associated pages must also be created. Scenario The Seminar module design calls for the entry and processing of Seminar Registrations (in header/detail format), Comments about Seminars, and Seminar Charges. Tables and pages for each of these must be created. The header/detail data structure requires the use of a Document page type. Create these tables and their supporting pages.
Challenge Yourself! Using the table definitions in the preceding Table Design and the GUI page designs as guides, create the following: 1. Tables a. Seminar Registration Header b. Seminar Registration Line c. Seminar Comment Line d. Seminar Charge 2. Pages a. Seminar Comment List b. Seminar Comment Sheet c. Seminar Charges Page d. Seminar Registration Page e. Seminar Registration Subpage f. Seminar Registration List
Step by Step The first task is to create the Seminar Comment Line table, which contains comments about the seminar registration, if any. The fastest way to create this table is by exporting an existing table as a text file (described at the beginning of this chapter), making the appropriate changes to the text file and importing it back into Microsoft Dynamics NAV.
3-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations 1. Create table 123456704 Seminar Comment Line by exporting the standard table Sales Comment Line, modifying it, and importing it back into Microsoft Dynamics NAV. o To do this, first export the Sales Comment Line table (44) as a text file using the steps given earlier in the chapter. Give the text file the name "Table 123456704 - seminar comment Line.txt" to match the number and name that the new table will have. o Open the file in Notepad. Change the object number to 123456704. o Change the object name and the CaptionML value in the PROPERTIES section to "Seminar Comment Line." o Replace all instances of the word "Sales" with "Seminar." These instances include instances of the word "Sales" in variable names and C/AL code. o Replace the OptionString and OptionCaptionML values for the Document Type field to "Seminar Registration, Posted Seminar Registration" as shown in the table design. o Set the LookupFormID and DrillDownFormID properties to form 123456707. o Save the text file, import it into Microsoft Dynamics NAV, and compile it. Note that at this point the table object can be compiled, even though page 123456707 is not yet created. o Write a proper reference in the documentation trigger of the table and change the value of the Version List to "CSD." The completed table has the following fields: No.
Field Name
Type
Length
1
Document Type
Option
2
No.
Code
3
Line No.
Integer
4
Date
Date
5
Code
Code
10
6
Comment
Text
80
Comment Options: Seminar Registration, Posted Seminar Registration.
20
NOTE: The key for the table is Document Type, No., Document Line No., and Line No. This is also imported with the table. The next step is to create the Seminar Comment List and Seminar Comment Sheet pages. These pages are used to enter and display any comments about the registration.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 2. Create the Seminar Comment List page (123456707) with the fields No., Date, and Comment as shown in the GUI design. Define the Code field on the page with its Visible property set to FALSE. Set the property to specify that this page cannot be edited, set the DataCaptionFields to the No. field, and set the LinksAllowed property to No. The Comment List page (number 125) can be used as an example for the Seminar comment List page. 3. Create the Seminar Comment Sheet form (123456706) with the Date, Comment, and Code fields. The Code field Visible property is set to FALSE. o Set the properties to automatically split the key, allow multiple new lines, and to specify that the program does not insert the record until the user has left the record. (The AutoSplitKey, MultipleNewLines, and DelayedInsert properties.) o In the appropriate page trigger, run the function SetUpNewLine whenever the user enters a new record. This function is imported with the Seminar Comment Line table. The next step is to create the Seminar Registration Header table, which contains information about specific offerings of the seminar. 4. Create table 123456710 Seminar Registration Header with the following fields:
3-20
No.
Field Name
Type
Length
Comment
1
No.
Code
20
2
Starting Date
Date
3
Seminar No.
Code
20
4
Seminar Name
Text
50
5
Instructor Code
Code
10
Relation to Instructor table.
6
Instructor Name
Text
50
FlowField; The CalcFormula looks up the Name field on the Instructor table and cannot be edited.
7
Status
Options
Options: Planning, Registration, Closed, Canceled.
8
Duration
Decimal
Decimal Places 0:1
9
Maximum Participants
Integer
Relation to the Seminar table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations No.
Field Name
Type
Length
Comment
10
Minimum Participants
Integer
11
Seminar Room Code
Code
10
Relation to Seminar Room table.
12
Seminar Room Name
Text
30
13
Seminar Room Address
Text
30
14
Seminar Room Address2
Text
30
15
Seminar Room Post Code
Code
20
16
Seminar Room City
Text
30
17
Seminar Room Phone No.
Text
30
18
Seminar Price
Decimal
19
Gen. Prod. Posting Group
Code
10
Relation to Gen. Product Posting Group table.
20
VAT Prod. Posting Group
Code
10
Relation to VAT Product Posting Group table.
21
Comment
Boolean
22
Posting Date
Date
23
Document Date
Date
24
Job No.
Code
20
Relation to Job table.
25
Reason Code
Code
10
Relation to Reason Code table.
Relation to Post Code table. There is to be no validation or testing of the table relation.
Put in comment column "Set ExtendedDataType property" AutoFormatType=1
FlowField; The CalcFormula checks whether lines exist on the Seminar Comment Line table for the current Seminar Registration Header. Cannot be edited.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 No.
Field Name
Type
Length
Comment
26
No. Series
Code
10
Relation to No. Series table. Cannot be edited.
27
Posting No. Series
Code
10
Relation to No. Series table.
28
Posting No.
Code
20
The primary key for this table is the No. field, with a secondary key of Room Code. The sum index field for the secondary key is Duration. Ensure that the table and all fields have their Caption and CaptionML properties set. The next step is to create the Seminar Line Table. 5. Create the Seminar Registration Line table (123456711) with the following fields:
3-22
No.
Field Name
Type
Length
Comment
1
Seminar Registration No.
Code
20
Relation to Seminar Registration Header table.
2
Line No.
Integer
3
Bill-to Customer No.
Code
20
Relation to Customer table.
4
Participant Contact No.
Code
20
Relation to Contact table.
5
Participant Name
Text
50
Flowfield; Lookup the value based on the Participant Contact No. Cannot be edited.
6
Register Date
Date
Cannot be edited.
7
To Invoice
Boolean
Initial value is Yes.
8
Participated
Boolean
9
Confirmation Date
Date
Cannot be edited.
10
Seminar Price
Decimal
AutoFormatType = 2
11
Line Discount %
Decimal
Decimal places 0:5; The minimum value is 0 and the maximum is 100.
12
Line Discount Amount
Decimal
AutoFormatType = 1
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations No.
Field Name
Type
Length
Comment
13
Amount
Decimal
AutoFormatType = 1
14
Registered
Boolean
Cannot be edited.
The primary key is Seminar Registration No., Line No. The next step is to create the Seminar Charge table, which contains information for invoicing. 6. Create table 123456712 Seminar Charge with the following fields: No.
Field Name
Type
Length
Comment
1
Seminar Registration No.
Code
20
Relation to table 123456710 Seminar Registration Header. Must not be blank.
2
Line No.
Integer
3
Job No.
Code
20
Relation to table 167 Job
4
Type
Option
5
No.
Code
20
6
Description
Text
50
7
Quantity
Decimal
Decimal Places 0:5
8
Unit Price
Decimal
AutoFormatType = 2 Minimum value of 0.
9
Total Price
Decimal
Cannot be edited. AutoFormatType=1
10
To Invoice
Boolean
Initial value is Yes.
11
Bill-to Customer No.
Code
20
Relation to Customer table.
12
Unit of Measure Code
Code
10
If Type=Resource, relation to the Code field of table 205 Resource Unit of Measure table, where the Resource No. = No. Otherwise, relation to table 204 Unit of Measure.
Options: Resource, G/L Account If Type=Resource, relation to table 156 Resource If Type=G/L Account, relation to table 15 G/L Account.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 No.
Field Name
Type
Length
Comment
13
Gen. Prod. Posting Group
Code
10
Relation to table 251 Gen. Product Posting Group.
14
VAT Prod. Posting Group
Code
10
Relation to table 324 VAT Product Posting Group.
15
Qty. per Unit of Measure
Decimal
16
Registered
Boolean
Cannot be edited.
The primary key is Seminar Registration No., Line No. and a secondary key of Job No. The next step is to create the Seminar Charges form, which allows for the input and display of invoice information. 7. Create the Seminar Charges form (123456724) with the following fields: Type, No., Description, Bill-to Customer No., To Invoice, Unit of Measure Code, Quantity, Unit Price, and Total Price. Set the property to automatically split the key. The next steps are to create the Seminar Registration page and subpages. 8. Create the page 123456711 Seminar Registration Subpage. The fields to include on the subpage are: Bill-to Customer No., Participant Contact No., Participant Name, Participated, Register Date, Confirmation Date, To Invoice, Registered, Seminar Price, Line Discount %, Line Discount Amount, and Amount. o Set the Caption on the page to Lines. o Set the properties for the Line Discount % and Line Discount Amount fields so that they are blank if the value is 0. o Set the page property to specify that the program automatically creates a key for a newly inserted record. 9. Create the Seminar Registration main page (123456710) as shown in the GUI design. Include the three FastTabs: General, Seminar Room and Invoicing, and the subpage FastTab. o The Lines subpage FastTab is always the second FastTab on Document (Header/Line) pages. It is defined as an element with type Part, with the same indentation as the other FastTabs, and it is entered right above the Seminar Room FastTab. Give the subpage element the name SeminarRegistrationLines.
3-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations o
o o
The Subpage ID is entered into the PagePartID property of the element. Set the property to link the subpage to its table where the Seminar Registration No. field equals the No. field in the header. Set the Drilldown property of the Instructor Name to No. Add menu button and menu items as follows:
Type/Subtype
Option
Comment
Action Group
&Seminar Registration
Opens the Seminar Comment Sheet form (123456706). The link runs whenever there is an update.
Action
Co&mments
Opens the Seminar Comment Sheet page (123456706)
Action
Charges
Opens the Seminar Charges page (123456724) for the corresponding Seminar Registration No. The link runs whenever there is an update.
Actioncontainer / RelatedInformation
10. Create the Seminar Registration List page (123456713) with the following fields: No., Starting Date, Seminar Code, Seminar Name, Status, Duration, Maximum Participants, and Room Code. o Set the property to specify this page cannot be edited. o Set the CardFormID property to the Seminar Registration page. o Add the same Related Information selections to the Seminar Registration List page that were added to the Seminar Registration page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 3.2 - Adding Code to the Seminar Charge Table The business rules for the data in the Seminar Charge table require creating C/AL code to initialize and/or validate data in a number of fields. Scenario Process the entry of Seminar Charges data for a seminar.
Challenge Yourself! Handle the entry of Seminar Charges for both Resources and G/L Account entries. Initialize and Validate fields as new records are entered.
Step by Step In the Seminar Charge table, enter code to perform the following tasks: 1. When a record is inserted into the table, the program gets the corresponding Seminar Registration Header record and sets the Job No. field to that of the Seminar Registration Header. 2. When a user deletes a record, the program checks that the Registered field is false. Users cannot delete registered seminars. HINT: Use the TESTFIELD function to test the Registered value. 3. When a user enters or changes a value in the Job No. field, the program checks that the corresponding record in the Job table is not blocked and that the status of the job is Order. 4. When a user enters or changes a value in the Type field, the program sets the Description to blank. 5. When a user enters or changes a value in the No. field, the program checks the following: o If the Type is Resource: - Tests that the corresponding Resource is not blocked. - Tests that the Gen. Prod. Posting Group field is filled on the Resource record. - Sets the Description field of the Seminar Charge table to the Name from the Resource. - Sets the Gen. Prod. Posting Group, the VAT Prod. Posting Group, the Unit of Measure Code, and the Unit Price to the corresponding values in the Resource record. o
3-26
If the Type is G/L Account: - Gets the corresponding G/L Account record and runs the CheckGLAcc function. - Tests that Direct Posting is TRUE for the G/L Account.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations -
Sets the Description field of the Charge table to the Name of the G/L Account. Sets the Gen. Prod. Posting Group and VAT Prod. Posting Group to the corresponding values in the G/L Account record.
Solution: The code in the No. - OnValidate trigger is as follows: CASE Type OF Type::Resource: BEGIN Resource.GET("No."); Resource.TESTFIELD(Blocked,FALSE); Resource.TESTFIELD("Gen. Prod. Posting Group"); Description := Resource.Name; "Gen. Prod. Posting Group" := Resource."Gen. Prod. Posting Group"; "VAT Prod. Posting Group" := Resource."VAT Prod. Posting Group"; "Unit of Measure Code" := Resource."Base Unit of Measure"; "Unit Price" := Resource."Unit Price"; END; Type::"G/L Account": BEGIN GLAccount.GET("No."); GLAccount.CheckGLAcc(); GLAccount.TESTFIELD("Direct Posting",TRUE); Description := GLAccount.Name; "Gen. Prod. Posting Group" := GLAccount."Gen. Bus. Posting Group"; "VAT Prod. Posting Group" := GLAccount."VAT Bus. Posting Group"; END; END;
6. When a user enters or changes the value in the Quantity field, the program calculates the Total Price field by multiplying the Unit Price by the Quantity. The same thing is done when the user enters or changes the Unit Price. HINT: Use the ROUND function to ensure the correct number of decimal places. 7. When a user enters or changes a value in the Unit of Measure Code field, the program does the following: o If the Type is Resource: - Gets the corresponding Resource record. - If the Unit of Measure Code is blank, the program sets it to the Base Unit of Measure Code from the Resource record.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 -
-
o
Finds the corresponding record in the Resource Unit of Measure table and sets the Qty. per Unit of Measure field to the corresponding value in the Resource Unit of Measure table. Calculates the Unit Price according to the Unit Price from the Resource record.
If the Type is G/L Account: - Sets the Qty. per Unit of Measure to 1. - If the current field is the Unit of Measure Code field, the program validates the Quantity. Use CurrFieldNo to check the current field. Do this in case OnValidate is triggered by some other field or code besides Unit of Measure Code.
Solution: The code in the Unit of Measure Code - OnValidate trigger is as follows: CASE Type OF Type::Resource: BEGIN Resource.GET("No."); IF "Unit of Measure Code" = '' THEN BEGIN "Unit of Measure Code" := Resource."Base Unit of Measure"; END; ResourceUofM.GET("No.","Unit of Measure Code"); "Qty. per Unit of Measure" := ResourceUofM."Qty. per Unit of Measure"; "Unit Price" := ROUND(Resource."Unit Price" * "Qty. per Unit of Measure"); END; Type::"G/L Account": BEGIN "Qty. per Unit of Measure" := 1; END; END; IF CurrFieldNo = FIELDNO("Unit of Measure Code") THEN BEGIN VALIDATE(Quantity); END;
3-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations
Lab 3.3 - Adding Code to the Seminar Registration Header Table and Page The business rules for the data in the Seminar Registration Header table require creating C/AL code to initialize and/or validate data in a number of fields. Scenario The fields in a Header that must be validated include the unique key field that identifies the document according to a set of standard NAV rules. Other C/AL code must be created to make sure required data is present according to standard NAV business rules for this type of document data. Referential integrity code must also be created so that when Header records are changed or deleted, associated Detail (child) records are kept consistent with their parent records (or deleted when appropriate).
Challenge Yourself! Add code to make record addition, new record numbering, and record deletion follow Microsoft Dynamics NAV standards. Add code to support field validation and default value initialization in the same style as in other Microsoft Dynamcis NAV documents.
Step by Step 1. Create a new function called AssistEdit with a return type of Boolean that: o Takes a parameter called OldSeminarRegHeader which is a record variable of the Seminar Registration Header table. o Checks for a Seminar Nos. series in the Seminar Setup table. o If found, uses the SelectSeries function in the NoSeriesManagement codeunit to check the series number. o If SelectSeries returns TRUE, the program uses the SetSeries function in the NoSeriesManagement codeunit to set the No. field, and the program then exits TRUE. HINT: The AssistEdit function created for the Seminar table is similar. 2. Create a new function called InitRecord which: o Sets the Posting Date to the work date if the Posting Date is blank (= 0D) o Sets the Document Date to the work date. o Gets the Seminar Setup record and runs the SetDefaultSeries function of the NoSeriesManagement codeunit to set the Posting No. Series value.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-29
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution: IF "Posting Date" = 0D THEN "Posting Date" := WORKDATE; "Document Date" := WORKDATE; SeminarSetup.GET; NoSeriesMgt.SetDefaultSeries( "Posting No. Series", SeminarSetup."Posted Seminar Reg. Nos.");
3. When a new record is inserted, if the program finds that the No. field is blank, it gets the Seminar Registration Nos. series from the Seminar Setup table and tests it. It then fills the No. field by using the InitSeries function of the NoSeriesManagement codeunit. The program then runs the new InitRecord function. Solution: Enter the following code in the OnInsert trigger: IF "No." = '' THEN BEGIN SeminarSetup.GET; SeminarSetup.TESTFIELD("Seminar Registration Nos."); NoSeriesMgt.InitSeries( SeminarSetup."Seminar Registration Nos.", xRec."No. Series",0D,"No.","No. Series"); END; InitRecord;
4. When the user deletes a record, the program tests that the Status is Canceled and shows an error if the Status is not Canceled. The program also shows an error if the header has registered Seminar Registration Lines or if there are associated Seminar Charge lines. The program then deletes corresponding records in the Seminar Comment Line table. TESTFIELD(Status,Status::Canceled); SeminarRegLine.RESET; SeminarRegLine.SETRANGE("Seminar Registration No.","No."); SeminarRegLine.SETRANGE(Registered,TRUE); IF SeminarRegLine.FIND('-') THEN ERROR( Text001, SeminarRegLine.TABLECAPTION, SeminarRegLine.FIELDCAPTION(Registered), TRUE); SeminarRegLine.SETRANGE(Registered); SeminarRegLine.DELETEALL(TRUE); SeminarCharge.RESET; SeminarCharge.SETRANGE("Seminar Registration No.","No."); IF NOT SeminarCharge.ISEMPTY THEN ERROR( Text006, SeminarCharge.TABLECAPTION);
3-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations SeminarCommentLine.RESET; SeminarCommentLine.SETRANGE( "Document Type", SeminarCommentLine."Document Type"::"Seminar Registration"); SeminarCommentLine.SETRANGE("No.","No."); SeminarCommentLine.DELETEALL;
5. When a user attempts to rename a record, the program shows an error stating that a Seminar Registration Header cannot be renamed. HINT: Use a text constant and the TABLECAPTION function. 6. If the user changes No. to a new value from what it was previously, the program tests whether the number series (from the Seminar Registration Nos. field in the Seminar Setup) is allowed to be changed manually by using the TestManual function from the NoSeriesManagement codeunit. It then sets the No. Series field to blank. IF "No." <> xRec."No." THEN BEGIN SeminarSetup.GET; NoSeriesMgt.TestManual(SeminarSetup."Seminar Registration Nos."); "No. Series" := ''; END;
7. When the user changes a value in the Starting Date from what it was previously, the program tests that the Status is Planning. 8. When the user changes a value in the Seminar No. from what it was previously, the program performs the following tasks: o Shows an error if there are any corresponding registered Seminar Registration Line records. o Gets the Seminar record and tests the following: - That the Blocked field is false. - That the Gen. Prod. Posting Group field is not blank. - That the VAT Prod. Posting Group field is not blank. o
Fills in the following fields with values from the Seminar record: Seminar Name, Duration, Seminar Price, Gen. Prod. Posting Group, VAT Prod. Posting Group, Minimum Participants, Maximum Participants. The program validates and fills in the Job No. field.
IF "Seminar No." <> xRec."Seminar No." THEN BEGIN SeminarRegLine.RESET; SeminarRegLine.SETRANGE("Seminar Registration No.","No."); SeminarRegLine.SETRANGE(Registered,TRUE);
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-31
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 IF NOT SeminarRegLine.ISEMPTY THEN ERROR( Text002, FIELDCAPTION("Seminar No."), SeminarRegLine.TABLECAPTION, SeminarRegLine.FIELDCAPTION(Registered), TRUE); Seminar.GET("Seminar No."); Seminar.TESTFIELD(Blocked,FALSE); Seminar.TESTFIELD("Gen. Prod. Posting Group"); Seminar.TESTFIELD("VAT Prod. Posting Group"); "Seminar Name" := Seminar.Name; Duration := Seminar."Seminar Duration"; "Seminar Price" := Seminar."Seminar Price"; "Gen. Prod. Posting Group" := Seminar."Gen. Prod. Posting Group"; "VAT Prod. Posting Group" := Seminar."VAT Prod. Posting Group"; "Minimum Participants" := Seminar."Minimum Participants"; "Maximum Participants" := Seminar."Maximum Participants"; VALIDATE("Job No.",Seminar."Job No."); END;
9. When the user enters or changes a value in the Instructor Code, the program calculates the value of the Instructor Name field. 10. When the user enters or changes a value in the Seminar Room Code, if the Seminar Room Code is blank, the program clears the values of the Room Name, Room Address, Room Address2, Room Post Code, Room City and Room Phone No. fields. Otherwise, the program gets the Seminar Room record and fills in those fields with the corresponding Seminar Room values. 11. When the user enters or changes a value in the Seminar Room Code, if the Maximum Participants in the corresponding Seminar Room record is less than the Maximum Participants in the Seminar Registration Header, the program asks the user whether to change the Maximum Participants in the Seminar Registration Header to the number of Maximum Participants from the Seminar Room record. If the user answers yes, the program changes the Maximum Participants value in the Seminar Registration Header. IF "Seminar Room Code" = '' THEN BEGIN "Seminar Room Name" := ''; "Seminar Room Address" := ''; "Seminar Room Address 2" := ''; "Seminar Room Post Code" := ''; "Seminar Room City" := ''; "Seminar Room Phone No." := ''; END ELSE BEGIN SeminarRoom.GET("Seminar Room Code"); "Seminar Room Name" := SeminarRoom.Name; "Seminar Room Address" := SeminarRoom.Address; "Seminar Room Address 2" := SeminarRoom."Address 2";
3-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations "Seminar Room Post Code" := SeminarRoom."Post Code"; "Seminar Room City" := SeminarRoom.City; "Seminar Room Phone No." := SeminarRoom."Phone No."; IF (CurrFieldNo <> 0) THEN BEGIN IF (SeminarRoom."Maximum Participants" <> 0) AND (SeminarRoom."Maximum Participants" < "Maximum Participants") THEN BEGIN IF CONFIRM(Text004,TRUE, "Maximum Participants", SeminarRoom."Maximum Participants", FIELDCAPTION("Maximum Participants"), "Maximum Participants", SeminarRoom."Maximum Participants") THEN "Maximum Participants" := SeminarRoom."Maximum Participants"; END; END; END;
HINT: Use a CONFIRM message. 12. When the user enters or changes a value in the Room Post Code, the program runs the ValidatePostCode function from the Post Code table. 13. When the user performs a lookup on the Room Post Code field, the program runs the LookUpPostCode function from the Post Code table. 14. When the user enters or changes a value in the Room City field, the program runs the ValidateCity function from the Post Code table. 15. When the user performs a lookup on the Room City field, the program runs the LookUpCity function from the Post Code table. 16. When the user changes the Seminar Price to a new value from what it was before and the Status is not Canceled, the program searches for corresponding, unregistered Seminar Registration Lines. If any are found, the program asks the user whether to change the Seminar Price in the unregistered Seminar Registration Lines. If the user answers yes, the program validates and modifies the lines with the new Seminar Price. IF ("Seminar Price" <> xRec."Seminar Price") AND (Status <> Status::Canceled) THEN BEGIN SeminarRegLine.RESET; SeminarRegLine.SETRANGE("Seminar Registration No.","No."); SeminarRegLine.SETRANGE(Registered,FALSE); IF SeminarRegLine.FINDSET(FALSE,FALSE) THEN IF CONFIRM(Text005,FALSE, FIELDCAPTION("Seminar Price"),
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-33
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 SeminarRegLine.TABLECAPTION) THEN BEGIN REPEAT SeminarRegLine.VALIDATE("Seminar Price","Seminar Price"); SeminarRegLine.MODIFY; UNTIL SeminarRegLine.NEXT = 0; MODIFY; END; END;
17. When the user changes the Job No. to a new value from what it was before, if the program finds any Seminar Charge records with the old Job No., it asks whether to change the Job No. on the Seminar Charge lines. If the user answers yes, then the program modifies Seminar Charge lines with the new Job No. Otherwise, if the user answers no, the program changes the Job No. back to the old Job No. IF "Job No." <> xRec."Job No." THEN BEGIN SeminarCharge.RESET; SeminarCharge.SETCURRENTKEY("Job no."); SeminarCharge.SETRANGE("Job no.",xRec."Job No."); IF SeminarCharge.FINDSET(TRUE,TRUE) THEN BEGIN IF CONFIRM(Text007,TRUE, FIELDCAPTION("Job No."), SeminarCharge.TABLECAPTION) THEN BEGIN SeminarCharge.MODIFYALL("Job no.","Job No."); MODIFY; END ELSE BEGIN "Job No." := xRec."Job No."; END; END; END;
HINT: Use the CONFIRM message function and use the MODIFYALL function to change the Seminar Charge lines. 18. When validating the Posting No. Series field, if the Posting No. Series is not blank, the program tests that there are values in the Seminar Registration Nos. and Posted Sem. Registration Nos. fields on the Seminar Setup table. It then runs the TestSeries function from the NoSeriesManagement codeunit. Regardless of whether the Posting No. Series field is blank, the program tests that the Posting No. field is blank.
3-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations Solution: Enter the following code in the Posting No. Series - OnValidate trigger: IF "Posting No. Series" <> '' THEN BEGIN SeminarSetup.GET; SeminarSetup.TESTFIELD("Seminar Registration Nos."); SeminarSetup.TESTFIELD("Posted Seminar Reg. Nos."); NoSeriesMgt.TestSeries(SeminarSetup."Posted Seminar Reg. Nos.", "Posting No. Series"); END; TESTFIELD("Posting No.",'');
19. When the user performs a lookup on the Posting No. Series field, the program tests that there are values in the Seminar Registration Nos. and Posted Sem. Registration Nos. fields on the Seminar Setup table. If the LookupSeries function of the NoSeriesManagement codeunit is true, the program validates the Posting No. Series field. Solution: Enter the following code in the Posting No. Series - OnLookup trigger: WITH SeminarRegHeader DO BEGIN SeminarRegHeader := Rec; SeminarSetup.GET; SeminarSetup.TESTFIELD("Seminar Registration Nos."); SeminarSetup.TESTFIELD("Posted Seminar Reg. Nos."); IF NoSeriesMgt.LookupSeries(SeminarSetup."Posted Seminar Reg. Nos.", "Posting No. Series") THEN BEGIN VALIDATE("Posting No. Series"); END; Rec := SeminarRegHeader; END;
20. In the Seminar Registration page, when the user clicks the AssistEdit on the No. field, the program runs the AssistEdit function for xRec, and if it returns true, updates the current page. HINT: Use the UPDATE function of the CurrPage object to update the current page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-35
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 3.4 - Adding Code for Seminar Registration Lines As with the Seminar Registration Header record table, the Seminar Registration Line table must also have C/AL code included to enforce the business rules that will logically support the module design. Scenario Create validation code in the Seminar Registration Line table so that each record in this table is initialized to relate properly to its parent Seminar Registration Header record. Within this table, create code to also do calculations and validation lookups as necessary to ensure that all fields are properly completed.
Challenge Yourself! As was done for the Seminar Registration Header, add code to the Seminar Registration Line table to handle field validation, initialization and consistency checking,
Step by Step In the Seminar Registration Line table, enter code to perform the following tasks: 1. Create a new function called GetSeminarRegHeader that retrieves the corresponding Seminar Registration Header record and stores it in a global variable. IF SeminarRegHeader."No." <> "Seminar Registration No." THEN BEGIN SeminarRegHeader.GET("Seminar Registration No."); END;
2. Create a new function, CalculateAmount, to calculate the Amount field as the Seminar Price reduced by the Line Discount %. Use the ROUND function. Amount := ROUND(("Seminar Price" / 100) * (100 - "Line Discount %"));
3. Create a new function called UpdateAmount to calculate the Amount field to equal the Seminar Price minus the Line Discount Amount. Use the ROUND function with the Amount Rounding Precision field on the G/L Setup table as the precision parameter. GLSetup.GET; Amount := ROUND("Seminar Price" - "Line Discount Amount", GLSetup."Amount Rounding Precision");
3-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations 4. When the user inserts a new line, the program retrieves the corresponding Seminar Registration Header record, sets the Register Date to the current work date, and sets both the Seminar Price and the Amount to the Seminar Price from the Seminar Registration Header. 5. When the user deletes a record, the program tests that the line is not registered. 6. When the user changes the value in the Bill-to Customer No. field from what it was previously, the program shows an error if the line is registered. 7. When the user performs a lookup on the Participant Contact No., show the Contact List filtered for the Bill-to Customer Number. o To do so, the program filters the Contact Business Relation table to the appropriate customer using the Bill-to Customer No. o It then filters the Contact table to only those records where the Company No. is the same as that of the Contact Business Relation record. o The program runs the Contact List form (using the RUNMODAL function) using the filtered Contact record, and if the user selects a contact and clicks OK, the program assigns the Contact No. field of the Contact record to the Participant Contact No. Solution: Insert the following code in the Participant Contact No. - OnLookup trigger: ContactBusinessRelation.RESET; ContactBusinessRelation.SETRANGE("Link to Table", ContactBusinessRelation."Link to Table"::Customer); ContactBusinessRelation.SETRANGE("No.","Bill-to Customer No."); IF ContactBusinessRelation.FINDFIRST THEN BEGIN Contact.SETRANGE("Company No.",ContactBusinessRelation."Contact No."); IF FORM.RUNMODAL(FORM::"Contact List",Contact) = ACTION::LookupOK THEN BEGIN "Participant Contact No." := Contact."No."; END; END; CALCFIELDS("Participant Name");
8. When the user enters or changes a value in the Seminar Price, the program validates the Line Discount %.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-37
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 9. When the user enters or changes a value in the Line Discount %, the program calculates the Line Discount Amount (rounded by using the Amount Rounding Precision from the G/L Setup table) and then updates the Amount field using the new UpdateAmount function. IF "Seminar Price" = 0 THEN BEGIN "Line Discount Amount" := 0; END ELSE BEGIN GLSetup.GET; "Line Discount Amount" := ROUND("Line Discount %" * "Seminar Price" * 0.01, GLSetup."Amount Rounding Precision"); END; UpdateAmount;
10. When the user enters or changes a value in the Line Discount Amount, if the Seminar Price is not 0, the program calculates the Line Discount % using the Line Discount Amount and the Seminar Price. If the Seminar Price is 0, the program sets the Line Discount % to 0. The program runs the UpdateAmount function. IF "Seminar Price" = 0 THEN BEGIN "Line Discount %" := 0; END ELSE BEGIN GLSetup.GET; "Line Discount %" := ROUND("Line Discount Amount" / "Seminar Price" * 100, GLSetup."Amount Rounding Precision"); END; UpdateAmount;
11. When the user enters or changes a value in the Amount field, the program checks that the Bill-to Customer and Seminar Price fields are not empty. It rounds the Amount value with the Amount Rounding Precision field from the G/L Setup table as the precision parameter. It calculates the Line Discount Amount and the Line Discount %.
3-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations Solution: Insert the following code in the Amount - OnValidate trigger: TESTFIELD("Bill-to Customer No."); TESTFIELD("Seminar Price"); GLSetup.GET; Amount := ROUND(Amount,GLSetup."Amount Rounding Precision"); "Line Discount Amount" :="Seminar Price" - Amount; IF "Seminar Price" = 0 THEN BEGIN "Line Discount %" := 0; END ELSE BEGIN "Line Discount %" := ROUND("Line Discount Amount" / "Seminar Price" * 100, GLSetup."Amount Rounding Precision"); END;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-39
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 3.5 - Set Up a Seminar Management Department Page To make testing easier, access to all the pages that are developed in the labs can be added to a department page. This enables access directly from the RoleTailored client, instead of having to run the pages from the Run command prompt. A department page can be created by adding a menu for the department to a MenuSuite object. Scenario While pages and reports can be run directly by the developer on a test basis, the creation of actions defined in a menu from which to invoke the new objects makes testing more complete and similar to what the target user will experience. Since the creation of menu functionality is necessary to put the new module, the basis for that production menu will be created now for use in testing.
Step by Step 1. In the Object Designer, go to the MenuSuite area. Click the New button and select Partner. Clicking the OK button opens the MenuSuite in design mode. 2. Right-click in the menu area and select Create Menu. Enter Seminar Management as the Name, and enter the number 1 as the Bitmap value. Clicking the OK button creates a new Menu for the Seminar Management Department. 3. Create two Items, one for Planning and one for Setup. Items can be created by right-clicking the empty Seminar Management Department Menu and selecting Create Item. 4. Expand the Planning Item and add Items for Instructors (Page 123456705), Seminars (Page 123456701), Seminar Rooms (Page 123456745), and Seminar Registrations (Page 123456713). For each selection, enter the list pages as the objects. For instance, the Instructors selection has its Object Type set to Page, the Object ID to Instructors, and the Caption to Instructors.
FIGURE 3.9 INSTRUCTORS SELECTION
3-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations 5. Expand the Setup Item and add an Item for Seminar Setup. 6. Save the Menusuite. Next time that the Role Tailored client is opened, there will be a department for Seminar Management. The Seminar Management Department in the RoleTailored client:
FIGURE 3.10 SEMINAR MANAGEMENT DEPARTMENT IN ROLETAILORED CLIENT
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-41
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Testing Seminar Registrations Use the following test script to check the Seminar Registrations functionality. It is assumed that at least one Seminar Room, one Instructor, and one Seminar are set up from the test script in the last chapter. 1. In the RoleTailored client, browse to the Seminar Management Department and select Seminar Registrations from the Planning menu. Click the New button, which opens the Seminar Registration page with a new empty record. 2. Tab off the No. field. The next number in the number series set up in the last chapter is automatically filled into the No. field. Note that when a new record is started, the Posting Date and Document Date values are set to the work date. 3. Select a Seminar No. and see that the Seminar Name is populated. 4. Select an Instructor Code and see that the Instructor Name is populated. 5. Expand the Seminar Room FastTab, select a Seminar Room Code and see that the other fields are populated. 6. Expand the Invoicing tab, and enter a Price and a Job No. The values do not matter for now, but the Job No. becomes important in subsequent chapters when registrations are posted. 7. In the Lines FastTab, use the lookup to select a Bill-to Customer. Then use the Participant Contact No. lookup. The values in the Contact List must be filtered to only show Contact related to the Bill-to Customer. Select a Contact and click OK. The Participant Name field is populated automatically. 8. Tab through the rest of the fields on the line. Note that the Seminar Price is defaulted from the Invoicing FastTab. Enter a value in the Line Discount % and notice the Line Discount Amounts and Amount fields calculate accordingly. 9. Select the Charges menu item from the Related Information menu and enter a new charge. See that the line item values are populated appropriately based on the Resource or G/L Account selected. That concludes the testing for this use case. If there are areas that did not function as expected, make the necessary changes.
Summary This chapter described how to create the tables and pages that are necessary to register participants in seminars, along with how to create code to improve usability and data validation. The next step is to take the transaction information and create a posting routine that can certify participants and create ledger entries for completed courses. It will also be possible to post invoices to customers.
3-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations
Test Your Knowledge 1. What method is used to retrieve a field's caption? How about a table's caption?
2. Why is it necessary to be cautious when importing objects as text files?
3. How do card and list pages relate to a table, and how do they relate to each other?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-43
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 4. Is it possible to write to a virtual table?
5. When are virtual tables computed by the system?
6. What does the AutoSplitKey property do?
3-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations 7. What function is used to force the calculation of a FlowField?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-45
C/SIDE Solution Development 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.
3-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Registrations
Solutions Test Your Knowledge 1. What method is used to retrieve a field's caption? How about a table's caption? MODEL ANSWER: The FIELDCAPTION method is used to retrieve a field's caption. The TABLECAPTION method is used to retrieve a table's caption. 2. Why is it necessary to be cautious when importing objects as text files? MODEL ANSWER: It is important to be careful when importing objects as text files for two reasons: 1. They are in an uncompiled state, so it is not possible to use the object immediately. A developer needs to compile the object before it can be used. 2. When importing objects as text files, there is no confirmation, nor is the import worksheet available. 3. How do card and list pages relate to a table, and how do they relate to each other? MODEL ANSWER: A card page displays a single record. A list page displays a list of records for that table. A card page is tied to a list page so that selection of a specific record on the list can cause the associated card to be displayed showing that record in full detail. 4. Is it possible to write to a virtual table? MODEL ANSWER: Virtual tables are used to present static system information in a structure that works the same as regular tables. It is not possible to write to a virtual table. 5. When are virtual tables computed by the system? MODEL ANSWER: Virtual tables are computed by the system when they are opened. For instance, the virtual table Integer is populated when an instance of the virtual table is used in an object.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-47
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 6. What does the AutoSplitKey property do? MODEL ANSWER: The AutoSplitKey property is a form and/or page property that automatically calculates the value of the last field of the primary key when a record is inserted from the form/page, provided that this field has the data type Integer. 7. What function is used to force the calculation of a FlowField? MODEL ANSWER: The CALCFIELDS method is used to calculate a FlowField in C/AL code.
3-48
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting
CHAPTER 4: POSTING Objectives The objectives are: •
Create journal posting routines.
•
Create document posting routines.
•
Write internal documentation for modifications to existing objects.
•
Debug code.
•
Program for low-impact on the application.
•
Develop pages and codeunits for posting.
•
Add objects to the RoleTailored Client menu.
•
Test the design and development work.
Introduction The Seminar module now contains master files and a means of creating registrations. The next step is to use the registration information to create ledger entries for seminars through a posting routine. This functionality is added to the Seminar module by the end of this chapter.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Prerequisite Information Before beginning work on posting, it is important to know about journal tables, ledger tables, and some of the elements involved in posting.
Posting Tables and Routines Journal Tables A Journal is a temporary work area for the user. Records can be inserted, modified and deleted as the user wishes. There are three tables that comprise the Journal: •
Journal Line (the main table)
•
Journal Template (supplemental table)
•
Journal Batch (supplemental table)
The primary key of the Journal Line table is a compound key; it has more than one field. It consists of Journal Template Name, Journal Batch Name and Line No. •
The journal page that the user chooses sets the Journal Template Name, and this does not change unless the user goes into a different journal page.
•
The Journal Batch Name may be changed at the top of the page (the options that are available depend upon the template chosen), but only one can be viewed at a time.
•
The Line No. keeps each record in the same template and batch unique. Line No. is incremented automatically by the page (refer to the AutoSplitKey property). The user never sees most of the primary key fields on the page, other than the batch.
The journal page lets users enter journal lines that are added to the detail tables of the system (the ledgers), but nothing happens until users decide to post. Users can leave the lines in the journal table as long as they wish without posting.
Ledger Tables A ledger is a protected table that holds all the transactions for a particular functional area. These records are permanent and cannot be deleted or modified except through special objects. Also, records cannot be inserted directly into the table. Records cannot get into a ledger except through a posting routine, and posting routines only post journal lines. The primary key is the Entry No. field. There are many secondary keys, and most are compound. They are set up for reports, pages, and FlowFields. The Ledger table holds the majority of detail information for the functional area.
4-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting A ledger table is never modified directly, especially not by inserting or deleting records. There is a link between most of the ledger tables back to the General Ledger. Because of this link, any modifications made directly to a ledger table can be disastrous. Usually, the only way to undo such changes is to restore the most recent backup of the database.
Posting Routines A posting routine is a group of codeunits responsible for ensuring that all transactions put into the corresponding ledgers are correct per line and correct as a whole. The posting routine takes Journal Lines, checks them, converts them to ledger entries, inserts them into the Ledger table, and ensures that all transactions made were consistent. Although there are many different types of posting routines in Microsoft Dynamics® NAV, there are some general rules that pertain to all of them. The primary codeunit that does the work of posting for a particular journal is simply called the posting routine. This codeunit is named after the Journal name with the addition of "-Post Line." Its main job is to transfer the information from the Journal record to the Ledger table, though it also does other things, such as calculations and data checking.
Posting Routine Companion Codeunits For each type of posting routine (General Ledger, Sales, Item, etc.), the Post Line codeunit has two companion codeunits: •
Check Line
•
Post Batch
The Check Line codeunit is called by the Post Line codeunit to check each Journal line before it is posted. The Post Batch codeunit repeatedly calls the Check Line codeunit to test all lines. It then repeatedly calls the Post Line codeunit to post all lines. The Post Batch codeunit is the only one that actually reads or updates the Journal table; the others use the Journal record passed into them. In this way, a programmer can call the Post Line codeunit directly (from another posting codeunit) without having to update the Journal table. The Post Batch codeunit is used only when the user selects Post within the Journal page. The last digits of the object numbers of these posting codeunit are standardized. Posting Codeunit
End with
Example
Check Line
1
Gen. Jnl.-Check Line is codeunit 11
Post Line
2
Gen. Jnl.-Post Line is codeunit 12
Post Batch
3
Gen. Jnl.-Post Batch is codeunit 13
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Note that none of these codeunits have any interface that requires user input. This is so that they can be called from other applications without having to worry about messages popping up (except error messages). The Post Batch codeunit has a dialog that displays the progress of the posting and lets the user cancel. The rest of the user interface that has to do with posting is handled by another set of objects. Codeunit
Description
Object ID ends with
Example
Post routine
Asks whether to post, and then calls Post Batch
1
Gen. Jnl.-Post is codeunit 231.
Post and Print routine
Asks whether to post, calls Post Batch, and then calls the Register Report
2
Gen. Jnl.Post+Print is codeunit 232
Post Batch
Asks whether to post the selected batches and then repeatedly calls Post Batch for each one Is called from the Journal Batches page
3
Gen. Jnl.B.Post is codeunit 233
Post Batch and Print
Confirms that the user wants to post, then calls Post Batch for each batch, and then calls the Register Report
4
Gen. Jnl.-B. Post+Print is codeunit 234
Check Line Codeunit The name of the Check Line codeunit explains its function. It is designed to check the Journal Line that is passed to it. It does so without reading from the database server, except the first time it is called. Before checking any of the fields, this codeunit ensures that the journal line is not empty. It does so by calling the EmptyLine function in the Journal table. If the line is empty, the codeunit skips it by calling the EXIT function. If there is no error, and the posting process continues. The last thing that the codeunit verifies is the validity of the dimensions that are passed into the function in a temporary Dimensions table. This is done by some simple calls to the DimensionManagement codeunit. Dimensions are discussed later in this course. If the codeunit does not stop the process with an error, then the journal line is accepted.
4-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting Post Line Codeunit The Post Line codeunit is responsible for actually writing the journal line to the ledger. It only posts one Journal Line at a time. It does not look at previous or upcoming records. The code in the OnRun trigger of this codeunit is inserting records. The OnRun trigger of the Post Line codeunit is normally never called, but in prior versions of the product it was. For backward compatibility, the OnRun trigger loads the temporary Dimensions table with the two global dimensions and then calls the RunWithCheck function. This is the function that is normally called by other functions or triggers. It in turn calls the workhorse of the Post Line routine, the Code function. Like Check Line, this codeunit skips empty lines by exiting. This ensures that empty lines are not inserted into the ledger. The first thing the codeunit does, if the line is not empty, is to call Check Line to verify that all the needed journal fields are correct. Next, the codeunit checks the important table relations. This requires reading the database (using GET), which is why it is done here rather than in Check Line. Before writing to the ledger, Post Line writes to the register. The first time the program runs through the Post Line codeunit, it inserts a new record in the Register table. In every subsequent run through Post Line, the program modifies the record by incrementing the To Entry No. Then the codeunit takes the next entry number and the values from the journal line and puts them into a ledger record. Finally, it can insert the ledger record. Near the bottom of the Code function is the call to the DimensionManagement codeunit that copies the dimensions from the temporary Journal Line Dimension table to the real Ledger Entry Dimension table. The entry number for this new ledger record is passed into the function to keep the dimension records associated with this ledger entry. The very last thing that the codeunit does is to increment the variable that holds the next entry number by one. Thus, when the codeunit is called again, the next entry number is ready. When the Post Line codeunit is done, one journal line is processed, but more than one ledger record may be inserted into more than one ledger.
Post Batch Codeunit The Post Batch codeunit is responsible for posting the Template and Batch that were passed to it. Only one record variable for the journal is actually passed in, but the codeunit starts by filtering down to the template and batch of the record that is passed in. Then it finds out how many records are in the record set that the record variable represents. If the answer is none, the codeunit exits without an error, and it is up to the calling routine to let the user know that there is nothing to post.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Post Batch codeunit can then begin checking each journal line in the record set by calling the Check Line codeunit for each line. Once all the lines are checked, they can be posted by calling the Post Line codeunit for each line. By then, the codeunit has looped through all the records twice, once for Check Line and a second time for Post Line. To call the appropriate functions in Check Line and Post Line, Post Batch must fill in a temporary Journal Line Dimension table with all of the dimensions for the journal line. It can then pass this temporary record variable into the RunCheck function of Check Line (or the RunWithCheck function of Post Line) along with the journal line record variable. Where Check Line checks the consistency of a given line, the Post Batch codeunit is responsible for checking the inter-relation of the lines. For example, if the codeunit is for general journal lines, it may also be responsible for making ensuring that the journal lines balance. This usually takes place after they are checked and before they are posted. The codeunit may perform other functions depending on the Journal Template. For recurring journals, the journal lines are updated with new dates based on the date formula. When a recurring journal line is posted, the codeunit must check the Description and Document No. fields and perhaps replace any replaceable parameters with the correct values, for example %1 = day, %2 = week, and %3 = month. If the template is not recurring, the codeunit deletes all the journal lines after they are successfully posted.
4-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting The following diagram outlines the steps in the Posting Routine when Post Batch is called.
FIGURE 4.1 THE POST BATCH LOGIC DIAGRAM
Example Posting Routine In this section existing posting routines are discussed to provide a basic idea of how these routines tend to be written.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Check Line Design the Res. Jnl.-Check Line codeunit (211). Notice that the OnRun trigger gets the GL Setup record and then sets a temporary record for the dimensions. •
In the RunCheck function trigger, notice that the codeunit checks to see if the line is empty. If the line is empty, the codeunit skips further checking and exits without error.
•
The codeunit also checks to see if the posting date is within the allowable posting date from the GL Setup table.
•
The Check Line codeunit calls functions from the DimensionManagement codeunit to verify the dimensions.
If this codeunit goes through without error, then the posting routine continues.
Post Line Design the Res. Jnl.-Post Line codeunit (212). Notice that the OnRun trigger again gets the GL Setup record and also sets a temporary record for the dimensions. As mentioned previously, the OnRun trigger contains code for backward compatibility. Most codeunits call the RunWithCheck function, which then calls the Code function, where most of the posting is done in the posting routine. Notice, like the Check Line codeunit, the Post Line codeunit skips empty lines by exiting. This ensures that empty lines are not inserted into the ledger. If the line is not empty, it calls Check Line to verify that all required journal fields are correct. Next, the codeunit gets the next entry number from the Resource Ledger Entry table to be used with the resource register table. As previously mentioned, before writing to the ledger, Post Line writes to the register. The codeunit first adds a new record into the Register table, and then every subsequent run through Post Line increments the To Entry No. Then the codeunit takes the next entry number and the values from the journal line and puts them into a ledger record. Finally, it can insert the ledger record. After the Ledger is inserted into the table, this codeunit calls the DimensionManagement codeunit to transfer the dimension lines from the temporary record to the Ledger entry table.
Post Batch Design the Res. Jnl.-Post Batch codeunit (213). This codeunit is responsible for posting the Resource Template and Resource Batch that is passed to it.
4-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting The codeunit starts by filtering to the template and batch of the Resource Journal Line. If no records are found in this range, Post Batch exits and it is up to the calling routine (codeunit 271, 272, 273, or 274 in this case) to let the user know that there is nothing to post. The Post Batch codeunit then loops and checks each journal line in the record set by calling the Check Line codeunit. Once all the lines are checked, they enter another loop which posts the records by calling the Post Line codeunit for each line. Post Batch must fill in a temporary Journal Line Dimension table with all of the dimensions for the journal line. It can then pass this temporary record variable into the RunCheck function of Check Line (or the RunWithCheck function of Post Line) along with the journal line record variable. Unlike the General Journal, there are no interdependencies between Resource Journal lines, so no checks such as checking the balance need to be done here. Lastly, this codeunit calls the UpdateAnalysisView codeunit to update all of the Analysis Views.
Document Posting Routines A document in Microsoft Dynamics NAV is an easy interface for a user to perform many complicated transactions. The seminar registration document is used to tie a seminar registration to a number of customers and participants as well as to comments and seminar charges. The document posting routine for seminar registration translates this document information into journal entries, which can then be posted to ledger entries. To understand more clearly how a document posting routine works and what its components are, consider the example of a sales order with three sales lines: •
Line 1: Selling a G/L Account - for example this line may add a surcharge or freight
•
Line 2: Selling an item - for example, a computer
•
Line 3: Selling a resource - for example, the time an employee spends custom-building the computer
When the user posts the document, the program generates an entry that debits the Accounts Receivable Account in the G/L, and each line can generate a separate G/L entry for the amount of that line. At the same time, entries are being made for the Item and Resource journals, as well as the General journal for the Customer. When these journal entries are posted, they are posted as if the user had entered them into the journals. The biggest difference is that the journal records are posted one at a time, which allows the Sales Post routine to bypass Post Batch and call Post Line directly.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 In the example of a sales order posting, the Gen. Jnl.-Post Line codeunit (12) is called at least twice, the Item Jnl.-Post Line codeunit (22) is called once, and the Res. Jnl.-Post Line codeunit (212) is called once. A sales document is posted primarily by the Sales-Post codeunit (80). An entire batch of sales documents can be posted by calling the Batch Post Sales Invoices report (297). Note that this report is for invoices only. There is a separate report for each document type. These reports call the Sales-Post codeunit repeatedly for each document. For this to work, Sales-Post must not interact with the user. In fact, Sales-Post is never called directly by a page. The page calls the Sales-Post (Yes/No) codeunit (81), codeunit Sales-Post + Print (82), or one of the reports mentioned previously. They in turn interact with the user (getting confirmation or other information) and then call Sales-Post as appropriate. These interactions are shown in the following diagram.
FIGURE 4.2 THE DOCUMENT POSTING DIAGRAM
Document Posting Codeunit Codeunit 80 posts documents. When a user ships and invoices a Sales Order much of the work is done in Codeunit 80. Study this codeunit and identify the sections that perform the following tasks: •
Determines document type and validates the information that appears on the sales header and lines. o o
4-10
The codeunit determines what the posted document numbers are going to be and updates the header. This section ends with a COMMIT.
•
Locks the appropriate tables.
•
Inserts the Shipment Header and Invoice or Credit Memo Header.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting •
Processes the sales lines, starting by clearing the Posting Buffer (a temporary table based on the Invoice Post.Buffer table) and ends with the UNTIL that goes with REPEAT, which loops through all the sales lines. Each line is processed individually.
•
Within the REPEAT loop, checks each line with its matching Shipment line (if the line is previously shipped). o
o o
•
Posts all entries in the Posting Buffer to the General Ledger. o o o o
•
If the line type is an Item or a Resource, it is posted through the correct journal. The line is then added to the posting buffer. It may be inserted, or it may update a row already there. If the line is related to a job, it posts a journal line through the Job Journal. Then, if there is no shipment line, it inserts one. Finally, it copies the Sales Line to the Invoice Line or Credit Memo Line (the posted tables).
These are the Credits that are created from the sale of the lines. Then the codeunit can post the Debit to the General Ledger. The customer entry is made to the Sales Receivables Account. The routine then checks whether there is a balancing account for the header. This corresponds to an automatic payment for the invoice.
Updates and/or deletes the Sales Header and Lines and commits all changes.
Documentation in Existing Objects When changes are made to an existing object, enter a note in the Documentation trigger, just the same as for new objects discussed in earlier chapters. The note contains a reference number, the date the modification is completed, the name of the developer responsible for the modification, the project name, and a short description of the change. Here is an example taken from the Seminar Room table, with notes from Chapter 2, Labs 1 and 2: CSD - MM/DD/YYYY - D.E. Veloper Chapter 2 Lab 1 - Created table Lab 2 - Added validation and lookup logic
Notice that documentation in an existing object looks similar to the documentation in a new object. The details of these notes and the way they are formatted can vary from one developer to another. They may also be the subject of an organization-wide set of standards. It is important to understand that these notes are essential to keep track of the changes that are made to objects over the life span of the objects in a Microsoft Dynamics NAV database.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Code Comments Along with the general comments provided in the Documentation trigger, it is important to provide comments in the code at the lines where a change is made. Only do this when modifying an existing object, not when creating a new object. The key is to mark the changed code with the same reference number as used in the Documentation trigger of the object. For example, mark a modified single line of code like this: State :="Employee."Default Work State"; // jtd002
If an entire block of code is added or modified, mark the change as follows: // - jtd:002 --JobLedgEntry."Seminar Registration No." :="Seminar Registration No."; // + jtd:002 +++
For the removal of a block of code, mark it as follows: { - jtd:002 --- Start Deletion State :="Employee."Default Work State"; Locality :="Employee."Default Work Locality"; "Work Type Code" := Employee."Default Work Type Code"; + jtd:002 +++ End Deletion}
NOTE 1: Notice that the old code is kept in place; it is merely commented out. Never delete Microsoft Dynamics NAV base code. Always comment it out.
NOTE 2: Curly braces are a valid way to comment out multiple lines of code. However, use them only when small blocks of code are commented out, or when bigger blocks of code are commented out temporarily (for testing only). For upgrade purposes it is much easier to identify code changes when that code is commented out using the double slashes, even though it takes a little more time to put them in place in larger blocks of code.
Performance Issues When writing large posting routines, it is important to program with the idea of maximizing performance. There are a number of steps to take while programming a solution in Microsoft Dynamics NAV that will help improve performance.
4-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting Table Locking Normally there is no need to be concerned with transactions and table locking when developing applications in C/SIDE. There are, however, some situations where a table must be locked explicitly. For example, suppose that in the beginning of a function, data in a table is inspected and then used to perform various checks and calculations. Then, the record is written back based upon the result of this processing. The values retrieved at the beginning are consistent with the final data in the table. In short, other users cannot update the table while a function is busy doing calculations. The solution is to lock the table at the beginning of the function by using the LOCKTABLE function. This function locks the table until the write transaction is committed or aborted. This means that other users can read from the table, but they cannot write to it. Calling the COMMIT function unlocks the table. NOTE: The LOCKTABLE command only locks the entire table in the C/SIDE database option. The SQL Server locking option is managed with "lock escalation," meaning that locks may occur on a record level, on an index page level, and even on higher levels. SQL Server's LOCKTABLE does not automatically lock the entire table. The RECORDLEVELLOCKING property is used to detect whether record level locking is being used. This property is only used with the SQL Server Option for Microsoft Dynamics NAV, which is currently the only server that supports record level locking. In effect, the RECORDLEVELLOCKING keyword can be used to determine if the active database is a SQL Server database.
Keys and Queries When writing a query that searches through a subset of the records in a table, always carefully define the keys both in the table and in the query so that Microsoft Dynamics NAV can quickly identify this subset. For example, the entries for a specific customer are normally a small subset of a table containing entries for all the customers. The more efficiently Microsoft Dynamics NAV can locate and read a subset, the less time it takes to complete the query and the faster the response time of the application. To maximize performance, define the keys in the table so that they facilitate the necessary queries. These keys must then be specified correctly in the queries. NOTE: The SQL Server SETCURRENTKEY command determines the ORDER BY clause. However, this is not the clause that determines the index used on SQL Server. More on SQL Server performance issues will be covered in the chapter on SQL Server.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Reducing Impact on the Server Good code design minimizes the load on the server. There are several ways to achieve this including the following: •
Try to use the COMMIT function as little as possible. This function is handled automatically by the database for almost all circumstances.
•
Limit the use of the LOCKTABLE function to where it is necessary. Remember that an insert, modify, rename, or delete locks the table automatically, so for most situations tables do not need to be locked explicitly.
•
Try to structure the code so that it does not have to examine the return values of the INSERT, MODIFY, or DELETE functions. When using the return value, the server has to be notified right away so that a response can be obtained. Therefore, if they are not necessary, do not look at these return values.
•
Use the CALCSUMS and CALCFIELDS functions whenever possible to avoid going through records to add up values.
Reducing Impact on Network Traffic Consider setting keys and filters and then using MODIFYALL or DELETEALL functions. These functions send only one command to the server, rather than getting and deleting or modifying each of many records, which sends more information back and forth through the network. Since CALCSUMS and CALCFIELDS can both take multiple parameters, use these functions to perform calculations on several fields with one function call.
Debugging Tools There are three categories of possible errors when developing applications in C/AL code: •
Syntax errors – These are errors where the program encounters an unknown identifier, or where the program expects keywords that are not there, such as an IF or THEN that is missing. Syntax errors are detected by the compiler.
•
Runtime errors – These errors are not detected by the compiler and only occur when the code is executed. A good example of this is when division by zero occurs in the code.
•
Program logic errors – These errors occur when the code compiles and runs, but does not function as intended.
Microsoft Dynamics NAV has tools that help track the source of errors and report what code is run.
4-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting Debugger Microsoft Dynamics NAV provides an integrated debugging tool to use with the Classic Client to help check and correct code that does not run smoothly. The debugger allows breakpoints to be defined. These are marks in the code where the debugger stops execution so that the current state of the program can be examined. The Breakpoint on Triggers setting (Shift+Ctrl+F12) is enabled by default when the debugger is activated for the first time. This setting causes the debugger to interpret each trigger as a breakpoint during C\AL code execution. The debugger therefore suspends execution of the code when it reaches the first trigger. At this point other breakpoints can be set, and then the Breakpoint on Triggers option can be disabled if desired. If the Breakpoint on Triggers setting is turned off, the debugger will only stop code execution when it encounters a breakpoint that is set manually, or when it encounters an error. Breakpoints can also be set or removed individually from the C/AL Editor by pressing F9 or clicking Tools, clicking Debugger, and then clicking Toggle Breakpoints. To remove all breakpoints, press Ctrl+Shift+F9. Information about breakpoints is stored in the Breakpoints virtual table when the C/AL Editor is closed. Activate the debugger from Microsoft Dynamics NAV by clicking Tools, clicking Debugger, and then clicking Active (Shift+Ctrl+F11). In the debugger interface there are several windows and menus: •
From the Edit menu, the Breakpoints dialog box (Shift+F9) displays a list of the breakpoints that are set for the object being debugged. This dialog box can be used to enable, disable, and remove breakpoints in the list.
•
The View menu contains commands that display the various debugger windows, such as the Variables window and the Call Stack window.
•
The Debug menu contains commands that start and control the debugging process, such as Go (F5), Step Into (F8), Step Over (Ctrl+F8), and Show Next Statement (Alt+Num*). o
o
The Go command executes code from the current statement until a breakpoint or the end of the code is reached, or until the application pauses for user input. The Step Into command executes statements one at a time, by stepping into any function that is called. This means that the debugger follows execution into the function as opposed to executing the function and moving to the next command.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o
o
The Step Over command executes statements one at a time, like Step Into, but if using this command, when a function call is reached, the function is executed without the debugger stepping into the function instructions. The Show Next Statement command shows the next statement in the code.
Code Coverage When the code coverage functionality is activated, the program logs the code and objects that are run. This applies only for the duration that the code coverage is activated. This can be useful when customizing Microsoft Dynamics NAV and wanting to test the implementation. It provides a quick overview of the objects for which code is executed and displays the code that is run. To activate code coverage: 1. Click Tools, click Debugger, and then click Code Coverage. The Code Coverage window opens. 2. Click Start to begin logging code. 3. When the monitor's transactions are completed, return to the Code Coverage window, which now contains a list of any tables, pages, reports, dataports, and codeunits that were executed. 4. Click Stop. 5. Select an object and click Code to open the Code Overview window. The Code Overview window displays code for the object selected in the Code Coverage window. Lines of code are executed during the transaction(s) are shown in black. Lines of code that are not executed are shown in red.
Client Monitor The Client Monitor which is accessed by clicking Tools and then clicking Client Monitor, activates a virtual table called Monitor. This can be used to get an overview of the time consumption and processing sequence of specific operations. This tool can be valuable when optimizing performance. In the Client Monitor window, use the Options tab to specify the kind of information gathered by the Client Monitor. The Options tab also contains advanced parameters that are only available with the SQL Server database. Refer to the Application Designer's Guide for more information on these parameters. The SQL Server Resource Kit contains a set of objects in which the code coverage and the Client Monitor functionality is combined into one set of forms where Client Monitor entries can be directly linked to code coverage lines. The information can then be copied into external tools for further analysis. The SQL Server Resource Kit also has documentation that explains how to use these tools.
4-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting Handling Runtime Errors To avoid some runtime errors, it is recommended to write code that handles possible errors. A typical example of this is the GET function. The return value of the GET function is a Boolean, so that if the program finds the record in the table, the function returns TRUE; if the program does not find the record, the function returns FALSE. If the GET function is used as it is shown here, a runtime error occurs if the program cannot find the specified record: Customer.GET("Customer Number");
Handling a FALSE result from the GET function with a message or error provides a much better opportunity for the user to understand how to correct the problem. For example, the GET function can be called this way, with the error handled by the ELSE clause: IF Customer.GET("Customer Number") THEN .... ELSE ....
Posting Seminar Registrations In this section the client's functional requirements are analyzed and a solution is designed and implemented.
Solution Analysis The client's functional requirements presented in Chapter 1 describe the posting of registration information as follows: "When each seminar is finished, the customers with participants are invoiced. This is done by Jobs and Resources." Therefore, seminars are posted as Jobs, but also have a separate ledger with seminar-specific information. Posting the registration enables customers to be invoiced for their participation in seminars. Upon completion of a seminar, seminar managers can verify the participant list with the trainer, and post the registration document.
Solution Design Implementing the registration posting functionality means that the completed transaction data is used to create ledger entries from which to view history, create statistics, and create invoices.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The basic design for posting seminar registrations is similar to that of standard journal posting. When a document is being posted, additional posted document tables and pages that contain historical information can be created as well. The master table relationships are shown in the following diagram.
FIGURE 4.3 TABLE INTERACTION
GUI Design The pages for the seminar registration posting and the navigation between them reflect the relationships shown in the following illustration. By designing the simplest pages first, integration with the more complex pages is made easier.
4-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting The Source Code Setup page is modified by adding one new field to the page, Seminar, as shown.
FIGURE 4.4 THE SOURCE CODE SETUP PAGE (279)
The Seminar Ledger Entries page displays the Ledger entries.
FIGURE 4.5 THE SEMINAR LEDGER ENTRIES PAGE (123456721)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Seminar Registers page displays the registers created when seminar registrations are posted.
FIGURE 4.6 THE SEMINAR REGISTERS PAGE (123456722)
The Posted Seminar Charges page (123456739) shows the posted seminar charges from a posted seminar registration.
FIGURE 4.7 POSTED SEMINAR CHARGES PAGE (123456739):
4-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting The Posted Seminar Registration page shows the posted seminar registration header and line information.
FIGURE 4.8 THE POSTED SEMINAR REGISTRATION PAGE (123456734) WITH ALL FASTTABS EXPANDED
The Posted Seminar Reg. List page displays a list of posted seminar registrations.
FIGURE 4.9 POSTED SEMINAR REG. LIST PAGE (123456736)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Seminar Registration page (123456710) is modified by adding a Posting command to its Action pane.
FIGURE 4.10 THE ACTION MENU ON THE SEMINAR REGISTRATION PAGE (123456710)
By promoting the menu selection, the Post selection also displays as a large command icon directly on the Seminar Registration page.
FIGURE 4.11 THE SEMINAR REGISTRATION PAGE WITH THE POST COMMAND ICON
4-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting The Seminar Registration List page (123456713) is modified by adding a Posting command to its Actions menu.
FIGURE 4.12 SEMINAR REGISTRATION LIST PAGE (123456713)
NOTE: The page heading "Seminar Registration List" appears (as shown in the preceding illustration) when the page is invoked by testing through the use of the Run command. When the page is invoked from a menu command, other properties (such as Caption property) may cause a different page heading to display.
Functional Design As in all journal postings, the journal posting codeunits check Seminar Journal lines and post them. However, unlike some posting codeunits (such as General Journal), a codeunit is not needed to post a batch of these journal lines, because posting batches is not required for this solution. •
Check Line: This codeunit helps ensure the data validity of a seminar journal line before it is sent to the posting routine. o
o
o
The codeunit checks that the journal line is not empty and that there are values for the Posting Date, Job No., Instructor Code, and Seminar No. Depending on whether the line is posting an Instructor, a Room, or a Participant, the codeunit checks that the applicable key fields are not blank. The codeunit also verifies that the dates are valid.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 •
Post Line: This codeunit performs the posting of the Seminar Journal Line. o
The codeunit creates a Seminar Ledger Entry for each Seminar Journal Line and creates a Seminar Register to track which entries are created during the posting.
Modify the Job Jnl.-Post codeunit to ensure that the Seminar Registration No. is recorded in the Job Ledger Entry. Two codeunits are necessary to enable the posting of the Seminar Registration document: Seminar Post and Seminar Post (Y/N). •
Seminar Post: This codeunit does the posting of an entire seminar registration, including the job posting and seminar posting. o
o o
o
•
The codeunit transfers the comment records to new comment records corresponding to the posted document, and it copies charges to new tables containing posted charges. The codeunit creates a new Posted Seminar Registration Header record as well as Posted Seminar Registration Lines. The codeunit then runs the job journal posting, and posts seminar ledger entries for each participant, for the instructor, and for the room. Finally, the codeunit deletes the records from the transaction tables, including the header, lines, comment lines, and charges.
Seminar Post (Y/N): This codeunit interacts with users, asking whether they really want to post the registration. If users answer Yes, the codeunit runs the Seminar Post codeunit.
Table Design The following tables are required to implement the posting routines: •
Table 123456731 Seminar Journal Line
•
Table 123456732 Seminar Ledger Entry
•
Table 123456733 Seminar Register
•
Table 123456721 Posted Seminar Charge
•
Table 123456719 Posted Seminar Reg. Line
•
Table 123456718 Posted Seminar Reg. Header
Add fields to the following Microsoft Dynamics NAV tables:
4-24
•
Table 210 Job Journal Line
•
Table 169 Job Ledger Entry
•
Table 242 Source Code Setup
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting
Lab 4.1 - Creating the Tables and Pages for Seminar Registration Posting A complete application module such as the Seminar module, includes the processing of transaction data once it has been entered. Scenario Create the Journal, Ledger and Register tables and pages to support Posting of Seminar Registrations.
Step by Step Follow these steps to create the tables and pages required for seminar registration posting: 1. Source codes are used in posting tables to identify where entries originated. Add the additional field to table 242 Source Code Setup as follows: No.
Field Name
Type
Length
Comment
12345670 0
Seminar
Code
10
Relation to the Source Code table.
2. Modify the Source Code Setup page (279) by adding the new Seminar field as shown in the GUI Design section. 3. Create the Seminar Journal Line table (123456731) with the following fields: No.
Field Name
Type
Length
1
Journal Template Name
Code
10
2
Line No.
Integer
3
Seminar No.
Code
4
Posting Date
Date
5
Document Date
Date
6
Entry Type
Option
7
Document No.
Code
20
8
Description
Text
50
9
Bill-to Customer No.
Code
20
20
Comment
Relation to Seminar table.
Options: Registration, Cancellation.
Relation to Customer table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 No.
Field Name
Type
Length
Comment
10
Charge Type
Option
Options: Instructor, Room, Participant, Charge.
11
Type
Option
Options: Resource, G/L Account
12
Quantity
Decimal
DecimalPlaces = 0:5
13
Unit Price
Decimal
AutoFormatType = 2
14
Total Price
Decimal
AutoFormatType = 1
15
Participant Contact No.
Code
20
16
Participant Name
Text
50
17
Chargeable
Boolean
18
Seminar Room Code
Code
10
Relation to Seminar Room table.
19
Instructor Code
Code
10
Relation to Instructor table.
20
Starting Date
Date
21
Seminar Registration No.
Code
20
22
Job No.
Code
20
23
Job Ledger Entry No.
Integer
Relation to Job Ledger Entry table.
24
Source Type
Option
Options: , Seminar.
25
Source No.
Code
20
26
Journal Batch Name
Code
10
27
Source Code
Code
10
Relation to Source Code table.
28
Reason Code
Code
10
Relation to Reason Code table.
29
Posting No. Series
Code
10
Relation to No. Series table.
Relation to Contact table.
Initial value is Yes.
Relation to Job table.
If Source Type=Seminar, relation to Seminar table.
4. The primary key for this table is Journal Template Name, Journal Batch Name, and Line No. 5. Create a new function in the Seminar Journal Line table (123456731) with a return type of Boolean, called EmptyLine. Enter one line of code in the function trigger so that the function returns TRUE if the Seminar No. is blank.
4-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting 6. Create the Seminar Ledger Entry table (123456732) with the following fields: No.
Field Name
Type
Length
Comment
1
Entry No.
Integer
2
Seminar No.
Code
20
Relation to Seminar table.
3
Posting Date
Date
4
Document Date
Date
5
Entry Type
Option
6
Document No.
Code
20
7
Description
Text
50
8
Bill-to Customer No.
Code
20
9
Charge Type
Option
Options: Instructor, Room, Participant, Charge.
10
Type
Option
Options: Resource, G/L Account.
11
Quantity
Decimal
DecimalPlaces = 0:5
12
Unit Price
Decimal
AutoFormatType = 2
13
Total Price
Decimal
AutoFormatType = 1
14
Participant Contact No.
Code
20
15
Participant Name
Text
50
16
Chargeable
Boolean
17
Seminar Room Code
Code
10
Relation to Seminar Room table.
18
Instructor Code
Code
10
Relation to Instructor table.
19
Starting Date
Date
20
Seminar Registration No.
Code
Options: Registration, Cancellation.
Relation to Customer table.
Relation to Contact table.
Initial value is Yes.
20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 No.
Field Name
Type
Length
Comment
21
Job No.
Code
20
Relation to Job table.
22
Remaining Amount
Decimal
FlowField; CalcFormula looks up the Remaining Amount in the corresponding Job Ledger Entry. AutoFormatType = 1. Not editable.
23
Source Type
Option
Options: , Seminar.
24
Source No.
Code
20
25
Journal Batch Name
Code
10
26
Source Code
Code
10
Relation to Source Code table.
27
Reason Code
Code
10
Relation to Reason Code table.
28
No. Series
Code
10
Relation to No. Series table.
29
User ID
Code
20
Relation to User table which is a TableRelation property. Set TestTableRelation property to No.
If Source Type=Seminar, relation to Seminar table.
7. Enter code in the appropriate trigger so that when the user performs a lookup on the User ID field, the program runs the LookupUserID function from the LoginManagement codeunit. 8. The primary key for table 123456732 is Entry No., with one secondary key of Seminar No., Posting Date, and a second secondary key of Bill-to Customer No., Seminar Registration No., Charge Type, Participant Contact No. 9. Create the Seminar Register table (123456733) with the following fields:
4-28
No.
Field Name
Type
Length
Comment
1
No.
Integer
2
From Entry No.
Integer
Relation to Seminar Ledger Entry table.
3
To Entry No.
Integer
Relation to Seminar Ledger Entry table.
4
Creation Date
Date
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting No.
Field Name
Type
Length
Comment
5
Source Code
Code
10
Relation to Source Code table.
6
User ID
Code
20
Relation to User table which is a TableRelation property. Set TestTableRelation property to No.
7
Journal Batch Name
Code
10
10. The primary key for table 123456733 is No., with one secondary key of Creation Date and a second secondary key of Source Code, Journal Batch Name, Creation Date. 11. Enter code in the appropriate trigger so that when the user performs a lookup on the User ID field, the program runs the LookupUserID function from the LoginManagement codeunit. 12. Create the Seminar Ledger Entries page (123456721) with the fields Posting Date, Document No., Document Date (not visible), Entry Type, Seminar No., Description, Bill-to Customer No., Charge Type, Type, Quantity, Unit Price, Total Price, Remaining Amount, Chargeable, Participant Contact No., Participant Name, Instructor Code, Starting Date, Seminar Registration No., Job No., Job Ledger Entry No., and Entry No. as shown in the GUI Design section. Set the property to make this page not editable. With the new tables defined, the codeunits to post seminar-specific information from the seminar journal to the seminar ledger can be created. These codeunits are similar to other posting codeunits, except that a Post Batch codeunit for the document posting is not needed.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-29
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 4.2 - Creating the Codeunits and Page for Seminar Journal Posting Once the underlying tables and supporting pages have been created, the actual processing objects must be created. Scenario In accordance with the standard Microsoft Dynamics NAV approach to Posting, create Check Line and Post Line codeunits. Also create the necessary logic and supporting objects to update and access Seminar Registers data. Add access to this new Posting process to the Seminar module menu.
Challenge Yourself! Using Codeunits 275, 211, and 212 as models, create equivalent Posting Codeunits for Seminar Journal Posting. Also create a Seminar Registers page.
Step by Step First create a codeunit to show the Seminar Ledger Entry page for a set of entries: 1. Create the Seminar Reg.-Show Ledger codeunit (123456734). Set the property to specify Seminar Register as the source table for this codeunit. 2. Enter code in the appropriate trigger so that when the program runs the codeunit, the codeunit runs the Seminar Ledger Entries page, showing only those entries between the From Entry No. and To Entry No. on the Seminar Register. HINT: Look at Codeunit 275 Res.Reg.-Show Ledger. 3. The next step is to create the Check Line codeunit to help ensure data validity before posting. Create the Seminar Jnl.-Check Line codeunit (123456731). Set the property to specify Seminar Journal Line as the source table for this codeunit. 4. In codeunit 123456731, create a function called RunCheck that takes a parameter that is passed by reference. This parameter is a record variable of the Seminar Journal Line table, called SeminarJnlLine. 5. Enter code in the appropriate trigger so that when the program runs codeunit 123456731, it runs the RunCheck function for the current record. 6. Enter code in the RunCheck function trigger so that the function performs the following tasks:
4-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting HINT: Look at the RunCheck function in Codeunit 211 Res.Jnl.-Check Line. o o o
o o o
o
Tests whether the Seminar Journal Line is empty using the EmptyLine function. If the line is empty, the function exits. Tests that the Posting Date, Job No., and Seminar No. fields are not empty. Depending on the value of the Charge Type, tests that the Instructor Code, Seminar Room Code, and Participant Contact No. are not empty. If the line is Chargeable, tests that the Bill-to Customer No. is not blank. Shows an error if the Posting Date is a closing date. Tests that the Posting Date is between the Allow Posting From and Allow Posting To dates on the user's User Setup record. - If those fields are empty on the User Setup record, tests that the Posting Date is between the Allow Posting From and Allow Posting To dates on the G/L Setup record. - The function shows an error if the Posting Date is not between the dates on either of these Setup records. Shows an error if the Document Date is a closing date.
7. Now create the Post Line codeunit to post Seminar Journal lines. Create the Seminar Jnl.-Post Line codeunit (123456732). o Set the property to specify Seminar Journal Line as the source table for this codeunit. o Define the following global variables for the codeunit: Name
Data Type
Subtype
SeminarJnlLine
Record
Seminar Journal Line
SeminarLedgerEntry
Record
Seminar Ledger Entry
SeminarRegister
Record
Seminar Register
SeminarJnlCheckLine
Codeunit
Seminar Jnl.-Check Line
NextEntryNo
Integer
Length
8. Create a function called GetSeminarRegister that takes as a parameter a record variable for the Seminar Register table, called NewSeminarRegister. This parameter is passed by reference. 9. Create a function called RunWithCheck that takes as a parameter a record variable for the Seminar Journal Line, called SeminarJnlLine2, which is passed by reference. 10. Create a function called Code.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-31
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 11. Enter code in the appropriate trigger so that when the program runs codeunit 123456732 Seminar Jnl.-Post Line, it runs the RunWithCheck function for the current record. 12. Enter code in the GetSeminarRegister function trigger so that the function sets the NewSeminarRegister parameter to the SeminarRegister record. 13. Enter code in the RunWithCheck function trigger so that the function copies the SeminarJnlLine from the SeminarJnlLine2 record, runs the Code trigger, and copies the SeminarJnlLine2 record from the SeminarJnlLine. 14. Enter code in the Code function trigger so that the function performs the following tasks: HINT: Look at the Code function in Codeunit 212 Res. Jnl.-Post Line. o o o
o o
o
4-32
Tests whether the SeminarJnlLine is empty using the EmptyLine function. If it is empty, the function exits. Runs the RunCheck function of the SeminarJnlCheckLine codeunit. If the NextEntryNo is 0, the function locks the SeminarLedgEntry table and sets the NextEntryNo to one more than the Entry No. of the last record in the SeminarLedgEntry table. If the Document Date is empty, the function sets the Document Date to the Posting Date. Creates or updates the SeminarRegister record, depending on whether the register record is created for this posting. The function does this by checking whether the No. of the SeminarRegister record is 0 (zero). - If so, the function locks the SeminarRegister table. - If the function either cannot find the last record of the SeminarRegister table, or if the To Entry No. is not 0 (zero), the function creates a new SeminarRegister record, fills the fields as appropriate, and inserts the new record. - Regardless of whether the function creates a new record, the function sets the To Entry No. for the record to the NextEntryNo and modifies the record. Creates a new SeminarLedgerEntry record, fills the fields as appropriate from the SeminarJnlLine record, sets the Entry No. to NextEntryNo, inserts the new record, and increments NextEntryNo by 1.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting 15. Now create the Seminar Registers page from which the seminar registers can be viewed. Create a Seminar Registers page (123456722) with fields No., Creation Date, User ID, Source Code, Journal Batch Name, From Entry No., and To Entry No. as shown in the GUI Design section. o Set the property to specify that this page is not editable. o Add a selection to the Related Information action menu, to the page as follows: Menu Button
Option
Comment
Register
Seminar Ledger
Runs the codeunit 123456734 Seminar Reg.-Show Ledger. Set the new selection's Promoted and PromotedIsBig properties to Yes, and assign Process as the PromotedCategory. Set its Image property to ItemLedger.
One of the requirements specified by the client’s functional requirements is that the seminar registration posts as a job with additional seminar-specific information. The journals and codeunits to cover the seminar-specific information are already created, so now it is necessary to modify the tables, pages, and codeunits for posting job journals to allow the posting of seminar registrations as jobs.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-33
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 4.3 - Modifying the Tables, Pages and Codeunits for Job Posting When a new module, such as the Seminar module, is added to the Microsoft Dynamics NAV 2009 system, it must be integrated into portions of the base system. Scenario Integrate the Seminar module into the Job Journal, Job Ledger and Job Journal posting.
Step by Step Follow these steps to make the necessary changes to the Seminar solution objects for performing Job Posting: 1. Add a new field to the Job Journal Line table (210) as follows: No.
Field Name
Type
Length
123456700
Seminar Registration No.
Code
20
Comment
2. Add a new field to the Job Ledger Entry table (169) as follows: No.
Field Name
Type
Length
123456700
Seminar Registration No.
Code
20
Comment
3. In codeunit 1012 Job Jnl.-Post Line, enter code into the CreateJobLedgEntry function trigger so that when the function is filling the JobLedgEntry fields, it fills the ledger's Seminar Registration No. field from the Job Journal Line.
4-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting
Lab 4.4 - Creating the Tables and Pages for Posted Information Standard Microsoft Dynamics NAV 2009 structure for posted data includes tables to store the documents that have been posted and the pages to access that data. Scenario Seminar Registrations (a header/detail structure) and Seminar Charges will be posted. Posted history tables and access pages for these are to be created.
Challenge Yourself! Now create the tables and pages to use to store posted seminar registration information.
Step by Step 1. Create the Posted Seminar Reg. Header table (123456718) with the following fields: No.
Field Name
Type
Length
Comment
1
No.
Code
20
2
Starting Date
Date
3
Seminar No.
Code
10
4
Seminar Name
Text
50
5
Instructor Code
Code
10
Relation to Instructor table.
6
Instructor Name
Text
50
FlowField; The CalcFormula looks up the Name field on the Instructor table. Must not be editable.
7
Duration
Decimal
8
Maximum Participants
Integer
9
Minimum Participants
Integer
10
Seminar Room Code
Code
Relation to the Seminar table.
DecimalPlaces = 0:1
20
Relation to Seminar Room table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-35
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
4-36
No.
Field Name
Type
Length
Comment
11
Seminar Room Name
Text
30
12
Seminar Room Address
Text
30
13
Seminar Room Address2
Text
30
14
Seminar Room Post Code
Code
20
15
Seminar Room City
Text
30
16
Seminar Room Phone No.
Text
30
17
Seminar Price
Decimal
18
Gen. Prod. Posting Group
Code
10
Relation to Gen. Product Posting Group table.
19
VAT Prod. Posting Group
Code
10
Relation to VAT Product Posting Group table.
20
Comment
Boolean
21
Posting Date
Date
22
Document Date
Date
23
Job No.
Code
20
Relation to Job table.
24
Reason Code
Code
10
Relation to Reason Code table.
25
No. Series
Code
10
Relation to No. Series table.
Relation to Post Code table. There is to be no validation or testing of the table relation.
AutoFormatType=1
FlowField; The CalcFormula checks whether lines exist on the Seminar Comment Line table for the current Posted Seminar Registration. Must not be editable.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting No.
Field Name
Type
Length
Comment
26
Registration No. Series
Code
10
Relation to No. Series table.
27
Registration No.
Code
20
29
User ID
Code
20
Relation to User table. Relation is not to be tested.
30
Source Code
Code
10
Relation to Source Code table.
o
o
The primary key for the Posted Seminar Reg. Header table (123456718) is No. with a secondary key of Seminar Room Code. The sum index field for the secondary key is Duration. Set the property to specify page 123456736 as the lookup page for the table.
NOTE: The field numbers in the Posted Seminar Reg. Header are set to match those of the Seminar Registration Header table, even though they are not using all of the same fields. This is so the TRANSFERFIELDS function, which relies on Field No., can be used when copying. 2. Create the Posted Seminar Reg. Line table (123456719) with the following fields: No.
Field Name
Type
Length
Comment
1
Seminar Registration No.
Code
20
Relation to table 123456718 Posted Seminar Reg. Header.
2
Line No.
Integer
3
Bill-to Customer No.
Code
20
Relation to Customer table.
4
Participant Contact No.
Code
20
Relation to Contact table.
5
Participant Name
Text
50
FlowField based on the Participant Contact No. Must not be editable.
6
Register Date
Date
Must not be editable.
7
To Invoice
Boolean
Initial value is Yes.
8
Participated
Boolean
9
Confirmation Date
Date
Must not be editable.
10
Seminar Price
Decimal
AutoFormatType = 2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-37
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 No.
Field Name
Type
11
LineDiscount %
Decimal
Decimal places 0:5. The minimum value is 0 and the maximum is 100.
12
Line Discount Amount
Decimal
AutoFormatType = 1
13
Amount
Decimal
AutoFormatType = 1
14
Registered
Boolean
Must not be editable.
o
Length
Comment
The primary key for this table is Document No., and Line No.
3. Create the Posted Seminar Charge table (123456721) with the following fields:
4-38
No.
Field Name
Type
Length
Comment
1
Seminar Registration No.
Code
10
Relation to table 123456718. Must not be blank.
2
Line No.
Integer
3
Job No.
Code
20
Relation to Job table.
4
Type
Option
5
No.
Code
20
6
Description
Text
50
7
Quantity
Decimal
Decimal Places=0:5
8
Unit Price
Decimal
AutoFormatType = 2 Minimum value is 0.
9
Total Price
Decimal
AutoFormatType=1 Must not be editable.
10
To Invoice
Boolean
Initial value is Yes.
11
Bill-to Customer No.
Code
20
Relation to Customer table.
12
Unit of Measure Code
Code
10
If Type=Resource, relation to the Code field of the Resource Unit of Measure table, where the Resource No. = No.; otherwise, relation to the Unit of Measure table.
Options: Resource, G/L Account. If Type=Resource, relation to the Resource table. If Type=G/L Account, relation to the G/L Account table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting No.
Field Name
Type
Length
Comment
13
Gen. Prod. Posting Group
Code
10
Relation to Gen. Product Posting Group table.
14
VAT Prod. Posting Group
Code
10
Relation to VAT Product Posting Group table.
15
Qty. per Unit of Measure
Decimal
16
Registered
Boolean
o
o
Must not be editable.
The primary key for the Posted Seminar Charge table (123456721) is Seminar Registration No., Line No., with a secondary key of Job No. Set the property to specify page 123456736 as the lookup page for the table.
NOTE: The field numbers in the Posted Seminar Reg. Header are set to match those of the Seminar Registration Header table, even though they are not using all of the same fields. This is so the TRANSFERFIELDS function, which relies on Field No., can be used when copying. 4. Create page 123456739 Posted Seminar Charges with the fields Type, No., Description, Bill-to, Customer No., To Invoice, Unit of Measure Code, Quantity, Unit Price, and Total Price as shown in the GUI Design section. Set the property to specify that the page is not editable. 5. Create the Posted Seminar Reg. Subpage page (123456735) with the fields Bill-to Customer No., Participant Contact No., Participant Name, Participated, Register Date, Confirmation Date, To Invoice, Registered, Seminar Price, Line Discount %, Line Discount Amount, and Amount as shown in the GUI Design section. o Set the width, height, and positioning properties for the subpage so that there is no empty space around the table box. o Set the properties for the Line Discount % and Line Discount Amount so that they are blank if the value is 0. o Set the property to specify that the page is not editable. o Set the property to specify that the program automatically creates a new key when a new line is inserted.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-39
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 6. Create the Posted Seminar Registration page (123456734) as shown in the GUI Design section. o Set the property to specify that the page is not editable. o Add a subpage control to the page. Set the PagePartID and the SubFormLink properties to specify the ID for the subpage and the proper link to the table. 7. Add a Related Information menu to page 123456734 with menu items as follows: Menu Button
Option
Comment
Comments
Opens the Seminar Comment Sheet page (123456706) showing the corresponding records. The link runs when the page is updated.
Charges
Opens the Posted Seminar Charges page (123456739) showing the corresponding records. The link runs when the page is updated.
o
Enter code in the appropriate trigger so that after the page gets the record, the program releases the filter on the No. field of the Posted Seminar Header table.
8. Create page 123456736 Posted Seminar Reg. List with the fields No., Starting Date, Seminar No., Seminar Name, Duration, Maximum Participants, and Room Code as shown in the GUI Design section. o Set the property to specify that the page is not editable. o Set the CardPageID to the Posted Seminar Registration page.
4-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting
Lab 4.5 - Creating the Codeunits for Document Posting The tables and pages for Seminar Document Posting were created earlier. The processing for posting those codeunits is also required. Scenario Create Seminar-Post and Seminar-Post (Yes/No) codeunits. Integrate then with the previously created menu structure so they can be invoked in the standard Microsoft Dynamics NAV 2009 fashion.
Challenge Yourself! Create the codeunits needed to Post Seminar Registration Header / Line documents. Use Sales or Purchase Invoice Posting as a model.
Step by Step As shown in the client’s functional requirements, two codeunits are needed to handle the document posting. The first is the codeunit that actually does the work of generating journal lines and running the posting routine, and the second is the codeunit that interacts with the user. The first codeunit is the Seminar-Post codeunit: 1. Create the Seminar-Post codeunit (123456700). 2. Define the following global variables for the codeunit: Name
DataType
Subtype
SeminarRegHeader
Record
Seminar Registration Header
SeminarRegLine
Record
Seminar Registration Line
PstdSeminarRegHeader
Record
Posted Seminar Reg. Header
PstdSeminarRegLine
Record
Posted Seminar Reg. Line
SeminarCommentLine
Record
Seminar Comment Line
SeminarCommentLine2
Record
Seminar Comment Line
SeminarCharge
Record
Seminar Charge
PstdSeminarCharge
Record
Posted Seminar Charge
SeminarRoom
Record
Seminar Room
Instructor
Record
Instructor
Job
Record
Job
Resource
Record
Resource
Customer
Record
Customer
JobLedgEntry
Record
Job Ledger Entry
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Length
4-41
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Name
DataType
Subtype
SeminarLedgEntry
Record
Seminar Ledger Entry
JobJnlLine
Record
Job Journal Line
SeminarJnlLine
Record
Seminar Journal Line
SourceCodeSetup
Record
Source Code Setup
JobJnlPostLine
Codeunit
Job Jnl.-Post Line
SeminarJnlPostLine
Codeunit
Seminar Jnl.-Post Line
NoSeriesMgt
Codeunit
NoSeriesManagement
ModifyHeader
Boolean
Window
Dialog
SourceCode
Code
LineCount
Integer
JobLedgEntryNo
Integer
SeminarLedgEntryNo
Integer
Length
10
3. Set the property to specify Seminar Registration Header as the source table for this codeunit. 4. Create a function called CopyCommentLines and set the property for this function to specify it as a local function. This function has the following parameters: o An integer variable called FromDocumentType o An integer variable called ToDocumentType o A code variable with length 20 called FromNumber o A code variable with length 20 called ToNumber 5. Create a function called CopyCharges and set the property to specify it as a local function. This function has two parameters: o A code variable with length 20 called FromNumber o A code variable with length 20 called ToNumber 6. Create a function called PostJobJnlLine with a return type of Integer. Set the property to specify it as a local function. This function has one parameter of an option variable called ChargeType with the options Participant, Charge. 7. Create a function called PostSeminarJnlLine with a return type of integer. Set the property to specify it as a local function. This function has one parameter of an option variable called ChargeType with the options: Instructor, Room, Participant, and Charge. 8. Create a function called PostCharge and set the property to specify it as a local function.
4-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting 9. Enter code in the CopyCommentLines function trigger so that this function finds records in the Seminar Comment Line table that correspond to the FromDocumentType and FromNumber values that passed as parameters. For each record the function finds, the function creates a new Seminar Comment Line record that is a copy of the old record, except that the function sets the Document Type and No. to the ToDocumentType and ToNumber. Because both record variables are based on the same table, this can be done by assigning the SeminarCommentLine2 variable to the Seminar CommentLine variable, and then assigning the key values to parameter values. 10. Enter code in the CopyCharges function trigger so that the function finds all Seminar Charge records that correspond to the FromNumber. For each record found, the function transfers the values to a new Posted Seminar Charge record, using the ToNumber as the Seminar Registration No. Because the SeminarCharge and the PstdSeminarCharge variables are based on different tables, this cannot be done by assigning the variable, and all field values must be assigned individually. If the PstdSeminarCharge table field number and types (and ideally, names) are the same as the SeminarCharge table, the TRANSFERFIELDS command can be used to transfer the field values in one statement. 11. Enter code in the PostJobJnlLine function trigger so that the function performs the following tasks: o Gets the Instructor, Resource, and Customer records that correspond to the Seminar Registration Header record. o Creates a new Job Journal Line record and fills the fields appropriately. - The Gen. Bus. Posting Group comes from the Customer record. - The Entry Type is Usage. - The Document No. and the Seminar Registration No. are both the No. from the Posted Seminar Reg. Header. - The Source Code is the value in the SourceCode variable. - The Source Currency Total Cost is the Seminar Price from the Seminar Registration Line. o
If the ChargeType is Participant, certain fields are filled as follows: - The Description in the Job Journal Line is the participant's name. - The No. is the instructor's Resource No. - The Unit of Measure Code is taken from the Resource's Base Unit of Measure. - Chargeable is the To Invoice value from the registration line
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-43
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o o
o
o o
The quantity fields are 1, the cost fields are 0, and the price fields are taken from the Amount field on the registration line. If the ChargeType is Charge, certain fields are filled as follows: - The Description in the Job Journal Line is the Description from the Seminar Charge record. - If the Type from the Seminar Charge is Resource, the journal line's Type is Resource, and the Unit of Measure Code and Qty. per Unit of Measure are the corresponding values from the Seminar Charge record. - If the Type of the Seminar Charge is G/L Account, the journal line's Type is G/L Account, Chargeable is the To Invoice value on the Seminar Charge record, the Quantity (Base) is 1, the Unit Cost is 0, and the Total Cost is 0, and the No., Quantity, Unit Price, and Total Price are the corresponding values from the Seminar Charge record. It is assumed that the job has only one Job Task Line, therefore, the posting of the job will only post the FIRST Job Task Line of the specific job. Runs the Job Jnl.-Post Line codeunit with the newly created Job Journal Line. Exits and returns the Entry No. of the last Job Ledger Entry record in the table.
12. Enter code in the PostSeminarJnlLine function trigger so that the function performs the following tasks: o Creates a new Seminar Journal Line and fills the fields as appropriate from the Seminar Registration Header, Posted Seminar Reg. Header, and parameter values. o If the ChargeType is Instructor, certain fields are filled as follows: - The Description is the instructor's Name. - The Type is Resource. - Chargeable is FALSE. - The Quantity is the Duration from the registration header. o
4-44
If the ChargeType is Room, certain fields are filled as follows: - The Description is the room's Name. - The Type is Resource. - Chargeable is FALSE. - The Quantity is the Duration from the registration header.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting o
If the ChargeType is Participant, certain fields are filled as follows: - The Bill-to Customer No., Participant Contact No., and Participant Name values come from the corresponding fields on the registration line. - The Description is the Participant Name on the registration line. - The Type is Resource. - Chargeable comes from the To Invoice field on the registration line. - Quantity is 1. - The Unit Price and Total Price come from the Amount field on the registration line.
o
If the ChargeType is Charge, certain fields are filled as follows: - The Description, Bill-to Customer No., Type, Quantity, Unit Price, and Total Price values all come from the corresponding fields on the Seminar Charge record. - Chargeable comes from To Invoice on the Seminar Charge record.
o
Runs the Seminar Jnl.-Post Line codeunit with the newly created Seminar Journal Line. Exits with the Entry No. of the last Seminar Ledger Entry record in the table.
o
13. Enter code in the PostCharge function trigger so that the function performs the following tasks: o For each record in the Seminar Charge table that corresponds with the Seminar Registration Header, the function sets the JobLedgEntryNo to the result of the PostJobJnlLine function (run with a parameter of 1) and runs the PostSeminarJnlLine function (with a parameter of 3). o Sets the JobLedgEntryNo to 0. 14. Enter code in the appropriate trigger so that when the program runs the Seminar-Post codeunit, the codeunit performs the following tasks: o Clears all variables and sets the SeminarRegHeader variable to the current record. o Tests that the Posting Date, Document Date, Starting Date, Seminar No., Duration, Instructor Code, Seminar Room Code, and Job No. fields on the registration line are not empty. o Tests that the Status is Closed.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-45
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o
o
Gets the Seminar Room and Instructor records that correspond to the registration header and tests for both of them that the Resource No. field is not empty. Filters the Seminar Registration Line table to records that correspond to the registration header and shows an error message if no records are found.
HINT: Because none of the values in the Seminar Registration Line table are needed, use the ISEMPTY method to check for "no records found." o o
o
o o
Opens a dialog window to keep the user informed of the progress. If the Posting No. is blank on the registration header, tests that the Posting No. Series is not blank and runs the GetNextNo function of the NoSeriesManagement codeunit modifies the header, and performs a commit. If record level locking applies, locks the Seminar Registration Line and Seminar Ledger Entry tables and finds the last Seminar Ledger Entry record. Sets the SourecCode variable to the Seminar value in the Source Code Setup table. Creates a new Posted Seminar Reg. Header record and transfers fields from the Seminar Registration Header record to the new record.
HINT: Use the TRANSFERFIELDS function to do this. o
In the Posted Seminar Reg. Header record: - Sets the No. to the Posting No. from the registration header - Sets the Registration No. Series to the No. Series of the registration header - Sets the Registration No. to the No. of the registration header
o o
Updates the dialog window. Sets the Source Code and User ID fields on the Posted Seminar Reg. Header record before inserting the record. Runs the CopyCommentLines and CopyCharges functions. Resets the filter on the Seminar Registration Line table to get the records corresponding to the Seminar Registration Header record. For each registration line found, the function updates the dialog window with an updated line count. - The function then tests that the Bill-to Customer No. and Participant Contact No. are not blank. - If To Invoice is FALSE, the function sets the Seminar Price, Line Discount %, Line Discount Amount, and Amount to 0.
o o
o
4-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting -
-
-
The function then sets the JobLedgEntryNo variable to the result of the PostJobJnlLine function and the SeminarLedgEntryNo variable to the result of the PostSeminarJnlLine function. The function then creates a new Posted Seminar Reg. Line record and transfers the fields from the Seminar Registration Line record to the new posted record. The function sets the Document No. field of the new record to the No. of the Posted Seminar Reg. Header. Finally, the function inserts the new record and sets the JobLedgEntryNo and SeminarLedgEntryNo variables to 0.
Runs the PostCharge, PostSeminarJnlLine (to post the instructor), and PostSeminarJnlLine (to post the room) functions. o If record level locking does not apply, locks the Seminar Registration Line table. o Deletes the Seminar Registration Header and all corresponding Seminar Registration Line records, Seminar Comment Line records, and Seminar Charge records. o Sets the current record to the Seminar Registration Header record. 15. Create codeunit 123456701 Seminar-Post (Yes/No). 16. Define the following global variables for the codeunit: o
Name
DataType
Subtype
SeminarRegHeader
Record
Seminar Registration Header
SeminarPost
Codeunit
Seminar-Post
Length
17. Set the property to specify Seminar Registration Header as the source table for this codeunit. 18. Create a function called Code and set the property to specify that it is a local function. 19. Enter code into the Code function trigger so that the function confirms that the user wants to post the registration. o If the user answers No, the function exits. o If the user answers Yes, the function runs the Seminar-Post codeunit with the Seminar Registration Header record. o The function performs a Commit at the end. 20. Enter code into the appropriate trigger so that when the program runs this codeunit, the codeunit copies the current record into the Seminar Registration Header record, runs the Code function and copies the Seminar Registration Header into the current record.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-47
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 21. Finally, modify two pages to enable the registration posting. Add a Posting submenu to Actions on page 123456710 Seminar Registration as follows: Menu Button
Option
Comment
Posting
Post (F9)
Runs codeunit 123456701 Seminar-Post (Yes/No). There should be ellipses on this button.
Set the following properties: •
The caption property to P&ost.
•
The Image property to Post.
•
Promoted and PromotedIsBig to Yes.
•
PromotedCategory to Process.
•
ShortCutKey to F9.
22. Add a Posting submenu to the Actions menubutton on page 123456713 Seminar Registration List as follows:
4-48
Menu Button
Option
Comment
Posting
Post (F9)
Runs the Seminar-Post (Yes/No) codeunit (123456701). Set the same properties as the action menu selection on page 123456710.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting
RoleTailored Client Menu Setup Before the new functionality can be tested, it must be added to the Seminar Management department menu.
Step by Step 1. In the Object Designer go to the MenuSuite area, and open the DeptPartner MenuSuite in design mode. 2. In the Seminar Management menu, create a group called History. 3. Add three Items to the new History Group: o One group for Posted Seminar Registrations, which opens the Posted Seminar Reg. List page o One group for Posted Seminar Charges, which opens the Posted Seminar Charges page o One group for Seminar Registers page 4. Assign all new items to the History Department Category.
Testing It is assumed that some setup is been performed during previous test scripts and that there is some sample data of customers, contacts (participants), seminars, rooms, and instructors when testing posting. Follow these steps to test the solution: 1. Some set-up is required to test the posting routine: o In the Departments area of the RoleTailored Client, under financial management, select the Administration category. Under trail codes, open the Source Code Setup window. The new Seminar field can be found by expanding the Jobs FastTab. o Click the dropdown arrow to open the Source Codes window. o Enter a new source code of SEMJNL with a description of Seminar Journal and click OK. o Close the Source Code Setup window. 2. In Departments, click Jobs, and then click Jobs under Lists to open the Job List. Click the New icon. Enter a new job to use with testing. Most of the fields do not matter, but on the Posting FastTab, the Status must be set to Order to be able to post. On the Posting tab, specify a Job Posting Group. Close the Job Card. 3. Under the Planning area under Seminar Management Department, select Seminar Registrations. Enter a new Seminar Registration, filling out all fields and entering at least one line.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-49
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 4. Select Posting from the Actions menu, and then click Post to initiate the posting routine. Some errors may occur. Some are due to the validation code, while others may likely be bugs in the code. If the Debugger is used to find the sources of unexpected errors that occur when running the code, this must be done from within the Classic Client. 5. When all errors are resolved, verify that the posting worked as expected. Select the Posted Seminar Registrations from the History category in the Seminar Management Department. Find the seminar registration that posted, and verify the following: o All header fields are copied. o All lines and fields within them are copied. o Any related charges appear in the Posted Seminar Charges window. 6. Create another Seminar Registration. Try posting from the Seminar Registrations List page directly. 7. Open the Job Card for the new job and select Ledger Entries from the JRelated Information Action menu. The records with a Source Code of SEMJNL created from Seminar posting appear. 8. Run the Seminar Registers page (123456722) from the Object Designer. The entries created from the posting tests appear.
Summary This chapter covered the following subjects: •
Posting in Microsoft Dynamics NAV from journals and from transaction documents.
•
Tables and codeunits that comprise a standard posting routine.
•
Using the Microsoft Dynamics NAV debugger and code coverage functionality.
•
Key aspects of programming to keep in mind to maximize performance.
The next step is to integrate the different aspects of the solution into the standard Microsoft Dynamics NAV interface.
4-50
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting
Test Your Knowledge 1. What three tables comprise a journal?
2. In which type of table is permanent transaction data stored? Can these tables be modified directly?
3. Which function is used to ensure that the data in a table is not changed by another user until the programmer is finished writing to the table? Is it always necessary to use this function?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-51
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 4. What are the three standard posting routine codeunits? What does each of these codeunits do and how do they interrelate?
5. When is a document posting routine used? How does a document posting routine interact with other posting routines?
6. What is the standard Microsoft Dynamics NAV shortcut for Posting?
4-52
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting
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
4-53
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. What three tables comprise a journal? MODEL ANSWER: The three tables that comprise a Journal are: 1. Journal Line (Main table) 2. Journal Template (supplemental table) 3. Journal Batch (supplemental table) 2. In which type of table is permanent transaction data stored? Can these tables be modified directly? MODEL ANSWER: Permanent transaction data is stored in a Ledger table. Information in a ledger table cannot be modified directly. 3. Which function is used to ensure that the data in a table is not changed by another user until the programmer is finished writing to the table? Is it always necessary to use this function? MODEL ANSWER: The method is called LOCKTABLE. It is not always necessary to explicitly call this method, as the DBMS will set the locks that it deems necessary based on the type of transaction that it is processing. 4. What are the three standard posting routine codeunits? What does each of these codeunits do and how do they interrelate? MODEL ANSWER: The three standard posting codeunits are: 1. Check Line (ends with the number 1). It is typically called by the Post Batch before Post Line. 2. Post Line (ends with the number 2). It is typically called by the Post Batch after Check Line. 3. Post Batch (ends with the number 3).
4-54
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Posting 5. When is a document posting routine used? How does a document posting routine interact with other posting routines? MODEL ANSWER: A document posting routine is used to translate a document in Microsoft Dynamics NAV into the proper journal entries, and post those journal entries into the proper ledgers. One document can apply to multiple types of journals, for instance a sales order with an Item line and a G/L Account line will post into the Item Ledger, into the Customer Ledger, and into the General Ledger. The document posting routine will build the proper journal lines, and call their posting routines repeatedly until all details of the document's transaction are processed. 6. What is the standard Microsoft Dynamics NAV shortcut for Posting? MODEL ANSWER: In the RoleTailored Client the standard Microsoft Dynamics NAV shortcut for posting is Ctrl+Shift+P. In the Classic Client the shortcut is F11.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-55
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
4-56
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration
CHAPTER 5: INTEGRATION Objectives The objectives are: •
Integrate previously created Seminar module features with one another by adding the Navigate feature to pages.
•
Add to the Department Menu so that the Seminar module functionality is accessible in a standard way.
•
Integrate the Navigate feature into the Seminar module.
•
Test integration of the Navigate feature.
Introduction At this stage the Seminar Management solution is a combination of individual functions which the Cronus International Training Academy could use to input seminar master data, perform registrations, and post completed seminar registrations. The next step is to integrate these features with one another and with the standard application, making it user-friendly. This requires using MenuSuite objects and implementing Microsoft Dynamics® NAV Navigate functionality. This chapter addresses the integration of solution functionality with the user interface (UI) of the application.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Prerequisite Information Part of the Seminar module solution to be covered in this chapter involves making changes to tables that already contain data. Client data is valuable and moving that data about requires planning and accuracy. The following guidelines are put to use in this chapter and also later on in this course.
Changing Tables that Contain Data When creating the Seminar module, a number of tables are created and a few are modified. C/SIDE is designed to ensure that data is not lost when modifying the design of a table. This means that while it is possible to change a table that contains data, there are important guidelines that specify which types of changes are allowed under certain conditions. These guidelines are as follows: •
The name of a field can always be changed.
•
In general, the data type for a field can only be changed if there is no data in the field for any of the records in the table.
•
A field can always be added to a table as long as the maximum record size is not exceeded.
•
A field can be deleted if the field does not contain any values. Although the system will allows for the removal of a field even when there are remaining references, all references to the field from other tables, pages, and reports must be removed manually. The system will generate a run time error when a page or report is run with a reference to a field that no longer exists in the database.
•
The length of a string field can always be increased. A string field has a data type of Code or Text.
•
The length of a string field can be decreased as long as the length of all values in that field is equal to or smaller than the target size.
•
Although the Field No. may be changed, that is allowed only if the field does not contain any values. This is done only if absolutely required. This is because existing code in other objects must be modified to reflect correct values in the references to the Field No.
Seminar Feature Integration The Seminar module project is now ready to integrate the features created thus far with one another and with those available in the standard application. To do so, it is necessary to add Navigate support to some pages and create a menu for the Seminar module as part of the main menu shown in the Departments area of the application.
5-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration In addition to creating a new department in the Navigation Pane, it might be beneficial to also create a new Role Center, and bring Seminar functionality straight to the users' home area. A Role Center is a special type of page that provides specific functionality in the home area for certain types of users. Guidelines on how to create Role Centers can be found in the UX Guide and in the Microsoft Dynamics NAV 2009 Developer and IT Pro Help. These sources are available in the standard documentation found on the Microsoft Dynamics NAV 2009 product media or in the following locations: •
User Experience Guidelines for Microsoft Dynamics NAV 2009 on the Microsoft Download Center
•
Microsoft Dynamics NAV 2009 Developer and IT Pro Help on the Microsoft Download Center
•
Microsoft Dynamics NAV 2009 Developer and IT Pro Help on MSDN
The Navigation Pane in Microsoft Dynamics NAV provides a summary of the number and type of entries posted for a specific document number posting date. This feature can be useful in helping the user easily trace the ledger entries that result from certain transactions. To make the Seminar module fit with the standard application and to improve usability, this feature will be integrated into the module.
Solution Analysis To integrate the seminar features with one another, the registrations and ledger entries are available from the seminar pages developed earlier. A MenuSuite object is created for the Seminar module, which is used to expose functionality to the Departments area of the RoleTailored client. The purpose of integration is to make all Seminar features available from the appropriate places in the application. This makes the customized application more user-friendly. The appropriate seminar registrations and ledger entries must be accessible from the Seminar Card and Seminar List pages. The Seminar module must be accessible from the Departments area in the RoleTailored client, and this must be the typical method for seminar managers to access the Seminar module features. When the seminar managers look at a seminar definition in the Seminar Card or Seminar List page, they can access the Seminar Registration for the seminar as well as the Seminar Ledger Entries that relate to the seminar.
Solution Design To integrate the Seminar module as described in the analysis section, make modifications to some existing pages and tables and add the selections to the new Seminar Management Menu to the Partner MenuSuite. Because integration is largely a user interface issue, it is important to plan the user interface.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Seminar Card page is modified by adding a Registration section to the Related Information menu button as shown in the following illustration.
FIGURE 5.1 THE SEMINAR CARD PAGE (123456700) WITH RELATED INFORMATION MENU EXPANDED
The Seminar List page is modified by adding the same Registration section to the Action menu button as illustrated.
FIGURE 5.2 THE SEMINAR LIST PAGE (123456701)
5-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration The Seminar Management Menu (as illustrated) is a new Partner-level menu accessible from the Departments area in the RoleTailored client. All Seminar module features are available from this menu.
FIGURE 5.3 THE SEMINAR MENU IN THE MENUSUITE DESIGNER
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
FIGURE 5.4 THE SEMINAR DEPARTMENT IN THE ROLETAILORED CLIENT
The seminar tree for this menu is as follows:
5-6
Menu Type
Menu Name
Group
Comment
Group
Seminars
Item
Contacts
Seminars
Opens the Contact List page (5052).
Item
Instructors
Seminars
Opens the Instructors page (123456705).
Item
Seminars
Seminars
Opens the Seminar List page (123456701).
Group
Periodic Activities
Seminars
Item
Create Invoices
Periodic Activities
Runs report 123456700 (to be created later in the course) which create Seminar Invoices.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration Menu Type
Menu Name
Group
Comment
Group
Order Processing
Item
Seminar Registrations
Order Processing
Opens the Seminar Registration List page (123456710).
Item
Sales Invoices
Order Processing
Opens the Sales Invoice List page (9301).
Group
Reports
Order Processing
Add reports under this group in Chapter 6.
Group
Documents
Order Processing
Add documents under this group in a later chapter.
Group
History
Order Processing
Item
Posted Seminar Registrations
History
Opens the Posted Seminar Registration List page (123456734).
Item
Posted Seminar Charges
History
Opens the Posted Seminar Charges page (123456739).
Item
Posted Sales Invoices
History
Opens the Posted Sales Invoice page (143).
Item
Seminar Registers
History
Opens the Seminar Registers page (123456722).
Item
Navigate
History
Opens the Navigate page (344).
Group
Setup
Item
Seminar Setup
Setup
Opens the Seminar Setup page (123456702).
Item
Seminar Rooms
Setup
Opens the Seminar Room Card page (123456703).
Item
Seminar Charges
Setup
Opens the Seminar Charges page (123456724).
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 5.1 - Integrating Seminar Features In the later stages of the Seminar module development and integration, a number of necessary, relatively simple processes and connections must be created. Scenario Modify the Seminar Card and the Seminar List to add actions to call up the Seminar Leger Entries List and the Seminar Registration List. Create a new Navigation Pane layout as shown in the preceding Solution Design section of this chapter.
Step by Step Now that the Analysis and Design phases are complete, the solution can be implemented. Begin by making modifications to the Seminar Card and Seminar List pages. 1. Add the new section and the new menu items to the Related Information menu on the Seminar Card page (123456700) as follows: Menu Button
Options
Comment
Seminar
Entries
Opens the submenu with the following option: Ledger Entries (CTRL + Shift + N): Opens the Seminar Ledger Entries page (123456721) filtered to entries with a corresponding Seminar No. Run the link whenever the page is updated. The lines in the page are to be sorted by Seminar No. and Posting Date.
Registration
Registrations
Opens the Seminar Registration page (123456710) for registrations with a Seminar Code that corresponds to the No. field. Run the link whenever the page is updated.
2. Add the same selection and menu items to the Related Information menu on the Seminar List page (123456701) added to the Seminar Card above. 3. Open the new MenuSuite using the "Partner" level created for testing in earlier chapters. Refer to the Navigation Pane Designer open on the left. 4. Right-click on a menu on the Navigation Pane Designer and select Create Menu. Set the caption to Seminars and the bitmap to 8. 5. Create the tree in the Seminar Menu as shown in the Solution Design section.
5-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration
Navigate Integration The purpose of integrating the Navigate feature is to improve the traceability of transactions to their ledger entries.
Solution Analysis The user accesses the Navigate function from ledger entry pages and posted seminar documents as well as from the standard application. When the seminar managers want to view a complete summary of the ledger entries that are created for a posted seminar registration or ledger entry, they will use Navigate.
Solution Design As an integration topic, the design of this solution centers on the user interface, but some table modifications are necessary as well. Make the Navigate feature available from the Seminar Ledger Entries page and the Posted Seminar Registration page. Modify the Seminar Ledger Entries page by adding a Navigate command to the Actions menu, as shown in the following illustration.
FIGURE 5.5 THE SEMINAR LEDGER ENTRIES PAGE (123456721)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Posted Seminar Registration page is modified by adding a Navigate command to the Actions menu, as shown in the following illustration.
FIGURE 5.6 THE POSTED SEMINAR REGISTRATION PAGE (123456734)
Table Design This solution does not require new tables, but it does require new keys for two tables. These new keys are specified in the development instructions of the following lab.
5-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration
Lab 5.2 - Modifying Objects to Integrate with Navigate The Navigate function is a unique and extremely valuable feature of Microsoft Dynamics NAV systems. A complete and seamless integration of the new Seminar module into Microsoft Dynamics NAV 2009 requires integration into the Navigate function. Scenario Review how the Navigate function supports filtering and displaying data in other modules within Microsoft Dynamics NAV 2009. Using that information as a model, make the modifications necessary to have the Navigate function also handle Seminar module data. Test the results.
Step by Step The development steps to integrate the Navigate feature consist of adding keys to the ledger entry tables of the Seminar module, adding code to the Navigate page and adding commands to Action menus of pages as shown in the Solution Design section. 1. Add the secondary key Document No., Posting Date to the Seminar Ledger Entry table (123456732). 2. In the Navigate page (344), add the following global variables: Name
DataType
Subtype
SeminarRegHeader
Record
Seminar Registration Header
PstdSeminarRegHeader
Record
Posted Seminar Reg. Header
SeminarLedgEntry
Record
Seminar Ledger Entry
Length
3. Enter code in the FindRecords function trigger of the Navigate page so that the function performs the following tasks: o If the READPERMISSION property is TRUE on the Seminar Registration Header record, the program resets this record variable and filters the table to the records where the No. matches the DocNoFilter variable and the Posting Date matches the PostingDateFilter variable. Next, the program runs the function InsertIntoDocEntry.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o
The program then performs the same steps as above for the Posted Seminar Reg. Header table and the Seminar Ledger Entry table.
FIGURE 5.7 STEPS FOR POSTED SEMINAR REG. HEADER TABLE AND SEMINAR LEDGER ENTRY TABLE
4. Enter code in the ShowRecords function trigger of the Navigate form so that the function performs the following tasks: o When the Table ID is the Seminar Registration Header, the function runs the lookup form for the Seminar Registration Header table. o When the Table ID is the Posted Seminar Reg. Header, the function runs the lookup form for the Posted Seminar Reg. Header table. o When the Table ID is the Seminar Ledger Entry, the function runs the lookup form for the Seminar Ledger Entry table.
FIGURE 5.8 SHOW RECORDS FUNCTION TRIGGER
NOTE: The call to open the form passes the value 0 (zero) into the FORM RUN command. This will cause the system to open the default lookup form that is defined for the table. Ensure that the three tables which are added to the Navigate functionality have lookup forms defined.
5-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration 5. Open the Seminar Registration Header table (123456710), and see that both the LookupFormID and DrillDownFormID properties have the value Form 123456713. The name is confusing, as it does not display the name of the page. It will actually open a page object when the navigate function runs in the Role Tailored client. 6. Repeat this process for the Posted Seminar Reg. Header table (123456718), with lookup page ID 123456736, and the Seminar Ledger Entry table with lookup page ID 123456721 7. Add the Navigate command to the Actions menu on the Seminar Ledger Entries page (123456721). Look at the Item Ledger Entries page (38) for an example of how the Navigate function is provided in a standard object. Pay attention to the Image, Promoted and PromotedCategory properties of the Action menu item. 8. Enter code in the appropriate trigger so that when the user clicks the Navigate selection, the program runs the SetDoc function of the Navigate page and then runs the Navigate page. 9. Add the Navigate command to the Actions menu of the Posted Seminar Registration page (123456734) and to the Posted Seminar Reg. List page (123456736). 10. Enter code in the appropriate trigger so that when the user clicks the Navigate selection, the program runs the SetDoc function of the Navigate page and then runs the Navigate page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Testing Managing Integration Use the following steps to test completed functionality: 1. Click the Seminars menu item in the Navigation Pane. 2. In the menu tree, click each of the items and check that the appropriate page or report opens. Remember that there are some items yet to be developed. 3. Use the Posted Registrations menu item to open the Posted Seminar Registrations page. Click the Navigate button and see that the Navigate page opens with the same Document Number. 4. Select Seminar Ledger Entry in the subpage and click Show. The Seminar Ledger Entries page opens with the entries related to Posted Seminar Registration.
Summary The Seminar modules individual features are now working with one another. This was accomplished by integrating the previously created Seminar module features with one another by adding them to a common menu. The Navigate pane was added to the Seminar module to provide functionality and accessibility in a standard way. Also, the Navigate Window was integrated into the Seminar module. In the next chapter, reports are added to the Seminar module.
5-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration
Test Your Knowledge 1. What is the standard Microsoft Dynamics NAV shortcut for viewing Ledger Entries?
2. As a developer, at what level do you normally create MenuSuite objects?
3. From which types of pages is the Navigate feature typically available?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-15
C/SIDE Solution Development 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-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Integration
Solutions Test Your Knowledge 1. What is the standard Microsoft Dynamics NAV shortcut for viewing Ledger Entries? MODEL ANSWER: The standard Microsoft Dynamics® NAV shortcut key for viewing Ledger Entries is Ctrl + Shift + N. 2. As a developer, at what level do you normally create MenuSuite objects? MODEL ANSWER: As a developer working for a Microsoft Dynamics® NAV partner, you usually work with MenuSuite objects at the Partner level. As a developer working for an end user, you usually work with MenuSuite objects at the Company level. 3. From which types of pages is the Navigate feature typically available? MODEL ANSWER: The Navigate function is typically available for pages that show posted documents and from pages that show ledger entries.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
5-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting
CHAPTER 6: REPORTING Objectives The objectives are: •
Use report event triggers.
•
Use special report functions.
•
Create reports for both the Classic and RoleTailored clients.
•
Create a seminar participant list.
•
Create a confirmation certificate for a seminar participant.
•
Create a ProcessingOnly report that posts invoices.
Introduction The Seminar module thus far includes the master tables and pages, a means to create new seminar registrations, and routines to post the registrations. These features are integrated into the standard application so they can be accessed from a new Seminar Management menu in the Departments area. The next step is to create reports for the module.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Prerequisite Information Before analyzing and implementing the report functionality covered in this chapter, the following important concepts will be reviewed: •
Report request forms and request pages
•
Report triggers
•
Report functions
•
ProcessingOnly reports
Report Request Forms and Request Pages For reports that will run in the Classic client, the report will be initialized with a request form. For reports that run in the RoleTailored client, the report will be initialized with a Request Page. For reports designed to run in both the Classic and RoleTailored clients, they will have both a request form and a request page. In this instance, the request form and request page serve equivalent purposes but must be developed independently.
Report Triggers Each report object consists of a number of elements: •
The report itself
•
One or more DataItems
•
One or more sections for each DataItem for Classic reports
•
A request form or page with an optional tab for each DataItem and an optional Options tab
•
Controls that display data
Each of these elements has a fixed number of event triggers that are executed during report execution. It is important to understand the order in which some of the more frequently used triggers execute. The following list details the order in which these most common event triggers execute. 1. When the user starts the report, the OnInitReport trigger is called. This trigger is the first trigger that runs, and can perform processing that is necessary before any part of the report can run. If the request page is needed, the OnInitReport trigger runs before the request page is displayed. Typically, the OnInitReport trigger is used to initialize variables and to populate default values into the request page.
6-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting 2. If the OnInitReport does not end the processing of the report, the request page for the report runs, if defined. The user can choose to cancel the report from the request page. 3. If the user continues, the OnPreReport trigger is called. At this point, no data has been processed. Like the OnInitReport trigger, the OnPreReport trigger can terminate report processing. Typically, the OnPreReport trigger is used to process values that the user has entered into the request page. 4. Provided that the processing of the report is not ended in the OnPreReport trigger, the DataItems are processed. Each DataItem has its own OnPreDataItem, OnAfterGetRecord, and OnPostDataItem triggers. 5. Before any records are retrieved, the OnPreDataItem trigger is called. Likewise, the OnPostDataItem trigger is called after the last record has been processed. 6. Between the OnPreDataItem trigger and the OnPostDataItem trigger, the records of the DataItem are processed. Processing a record means executing the OnAfterGetRecord trigger for each record that is retrieved by the DataItem, and outputting the values of the records by means of the report's sections. C/SIDE also determines whether the current record should cause outputting of a special section: header, footer, group header or group footer. 7. If there is an indented DataItem, a DataItem run is initiated for this DataItem, and for each record in its parent DataItem. DataItems can be nested up to ten levels deep. 8. When there are no more records to be processed in a DataItem, control returns to the point from which the processing was initiated. For an indented DataItem this is the next record of the DataItem on the next higher level. If the DataItem is already on the highest level (indentation is zero), control returns to the report. 9. After the first DataItem at indentation level zero has been processed, the next DataItem at indentation level zero - if one exists - is processed in the same way. 10. When there are no more DataItems, the OnPostReport trigger is called. Use this trigger to do any post processing that is necessary, for example, cleaning up by removing temporary files. 11. Each report section in the Classic client has its own set of triggers to cover what should happen to what is displayed in the report. Section triggers are not supported in the RoleTailored client. Therefore, if reports are created that will run in both the Classic client and the RoleTailored client, be careful not to write any C/AL code in section triggers that is vital to the proper running of the report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Report Functions Certain functions can only be used in reports. These functions can be useful for complex reports. For a full listing of report functions, and which ones are supported on either the Classic client or in the RoleTailored client, refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help on the installation media or on MSDN. This developer help file also contains some very useful walkthroughs that will help you familiarize yourself with Report Designer. CurrReport.SKIP: Use this function to skip the current record of the current DataItem. If a record is skipped, it is not included in totals and it is not printed. Skipping a record in a report is much slower than never reading it at all, so use filters as much as possible. CurrReport.BREAK: Use this function to skip the rest of the processing of the DataItem currently being processing. The report resumes processing the next DataItem. All DataItems indented under the one that caused the break are also skipped. CurrReport.QUIT: This function skips the rest of the report. It is not an error, however. It is a normal ending for a report. CurrReport.PREVIEW: Use this function to determine whether a report is being printed in preview mode.
Classic Report Functions Certain functions can only be used in reports in the Classic client, and will not work on the report layout rendering in the RoleTailored client: CurrReport.PAGENO: Use this function to return the current page number of a report and/or to set a new page number. CurrReport.CREATETOTALS: Use this function to maintain totals for a variable in the same way as totals are maintained for fields by using the TotalFields property. This function must be used in the OnPreDataItem trigger of the DataItem in the sections where the totals are displayed. CurrReport.TOTALSCAUSEDBY: Use this function to determine which field caused a break to occur. The return value is the field number of the field that the DataItem is grouped on that changed and caused a Group Header or Group Footer section to print. This function is usually used in the OnPreSection trigger of Group Header and Group Footer sections. This function must always be used when grouping more than one field for a single DataItem. CurrReport.NEWPAGE: Use this function to force a page break when printing a report. This is usually found in the DataItem triggers.
6-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting CurrReport.SHOWOUTPUT: Use this function to return the current setting of whether a section should be outputted or not, and to change this setting. This function should only be used in the OnPreSection trigger of a section. If TRUE is passed to the function, nothing changes and the section prints as normal. If FALSE is passed to the function, the section is not printed for this iteration of the DataItem.
ProcessingOnly Report A processing-only report is a report object that does not print but instead only processes table data. Processing table data is not limited to processing-only reports. Reports that print can also change records. This section applies to those reports as well. It is possible to specify a report to be "Processing Only" by changing the ProcessingOnly property of the Report object. The report functions as it is supposed to (processing DataItems), but it does not generate any printed output. When the ProcessingOnly property is set, the request page for the report changes slightly, as the Print and Preview buttons are replaced with an OK button. The Cancel and Help buttons remain unchanged. Once the ProcessingOnly property is set, use the following guidelines to write processing-only reports: •
Decide which tables are read - these are the DataItems.
•
Design the report so that most of the code goes into the OnAfterGetRecord trigger.
•
Use the INSERT or MODIFY functions in the tables, as appropriate.
•
Use a dialog to show the user the progress and allow the user to cancel the report.
There are advantages to using a report to process data rather than a codeunit. •
The request page functionality that allows the user to select options and filters for DataItems is readily available in a report, but difficult to program in a codeunit.
•
Using the features of Report Designer ensures consistency.
•
Instead of writing code to open tables and to retrieve records, report DataItems can be used.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Reporting Lab Overview The client's functional requirements describe their reporting needs in the following way: The customer requires that a number of reports and statistics be available. These include: •
A list of the participants registered for a seminar.
•
A list of the participants that have successfully completed each seminar, for the purposes of providing certificates. (The certificates themselves are also produced by the system.)
•
The total costs for each seminar, broken down according to what is and what is not chargeable to the customer.
•
Statistics for different time periods, for example, for a month, for last year, for this year, and up to the current date.
There are three main reports that can be created to fulfill these requirements: •
A participant list
•
A certificate confirmation
•
A processing-only report that posts invoices
Each of these reports is implemented in a lab in this chapter.
Participant List Reporting A review of the client's specifications shows that reporting is a requirement of the Seminar Management module. Begin the Analysis and Design of the needed reports.
Solution Analysis The client's functional specifications require that a Participant List report be available. This is merely a list of participants that are enrolled for a given seminar. This report should be available from both the main Seminar Menu and the Seminar Registration form.
Solution Design To implement this report, it is necessary to create the following items:
6-6
•
The report itself.
•
The request form/page to set the parameters of the report.
•
The controls to access the report from a page.
•
A page from which seminar reports can be selected.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting GUI Design The Seminar Report Selection page displays the available seminar reports.
FIGURE 6.1 THE SEMINAR REPORT SELECTION PAGE (123456723)
Seminar Menu: Modify this menu by adding the following menu item to the Reports Group (under Order Processing): Menu Type
Menu Name
Group
Comment
Item
Seminar Reg.Participant List
Reports
Opens report 123456701 Seminar Reg.-Participant List.
Item
Seminar Reg.-Part. Certificate
Reports
Opens report 123456702 Seminar Reg.-Part. Certificate.
Add the following menu item to the Setup Group: Menu Type
Menu Name
Group
Comments
Item
Report Selections
Setup
Opens page 123456723 Seminar Report Selection.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Seminar Registration page should be modified as shown, by adding a promoted Print command to the Actions menu from which to start the Participant List report.
FIGURE 6.2 THE SEMINAR REGISTRATION PAGE (123456710)
Functional Design The information for the report comes from the Seminar Registration Header and Seminar Registration Line tables. When running this report, the user selects which Seminar Registration Headers are included. For each Seminar Registration Header, the program then prints information from each corresponding Seminar Registration Line.
Table Design Implementation of the Participant List report requires that one new table be created, called Seminar Report Selections. Also, the Seminar Registration Header table must be modified.
6-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting
Lab 6.1 - Creating the Participant List Scenario The initial need is for a Participant List report for the RoleTailored client. Also required is a way in which seminar reports can be selected and run.
Challenge Yourself! Create a Participant List report which lists all Registrations by Seminar. Use the typical NAV Header/Detail list format and logic. Then create the means by which seminar reports can be selected from a page.
Part A: Base Classic Client Report 1. Add a field to the Seminar Registration Header table (123456710) as follows: No.
Field Name
Type
40
No. Printed
Integer
Length
Comment Must not be editable.
In the next tasks, create a codeunit to increment the No. Printed field just added to the Seminar Registration Header table. 2. Create the Seminar Registration-Printed codeunit (123456702). Set the property to specify Seminar Registration Header as the source table for this codeunit. 3. Enter code in the appropriate trigger so that when the program runs this codeunit, it finds the Seminar Registration Header record, increases the No. Printed by 1, and modifies and commits the table. Now create the actual report in the next tasks. 4. Use the wizard in the Classic client Report Designer to create the Seminar Reg.-Participant List form-type report (123456701) based on the Seminar Registration Header (123456710) table. Add the following fields, No., <Separator>, Seminar No., Seminar Name, Starting Date, Duration, Instructor Name and Room Name to the report. Save the report. This will result in a Classic client report layout that displays the report title; Company Name; date and page information in a Seminar Registration Header section; and the selected fields in a Seminar Registration Header Body section. 5. 5. Set the properties for the Seminar Registration Header DataItem so that it is sorted by No. and so that the filter fields are No., and Seminar No.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 6. Add a DataItem for the Seminar Registration Line table. o Set the property so that the DataItem indents to the first level. o Set the property so that the DataItem sorts by Seminar Registration No. and Line No. o Set the DataItemLinkReference and the DataItemLink properties so that the DataItem links to the Seminar Registration No. in the line DataItem is equal to the No. field in the header DataItem. 7. Set the property for the report so the caption is Seminar Reg.Participant List. 8. Make sure that the following sections are defined: o A body section was automatically added when the DataItem was defined. o Add a header section for the Seminar Registration Line DataItem above its body section but below the body section for the Seminar Registration Header DataItem. 9. Add the Bill-to Customer No., Participant Contact No., and Participant Name fields to the Seminar Registration Line body section. Move the labels for these fields t the Seminar Registration Line header section. 10. Enter code in the appropriate trigger so that after the program gets the record of the Seminar Registration Header table, the program calculates the Instructor Name field.
6-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting The report layout has now been completed for the Classic client. When the "Dynamicsnav:////runreport?report=123456701" is run from a command prompt, the report will be rendered using the Classic client.
FIGURE 6.3 REPORT 123456701 SECTIONS IN THE CLASSIC CLIENT
FIGURE 6.4 REPORT 123456701 RENDERED IN THE CLASSIC CLIENT
NOTE: In order for the report to be rendered from within the RoleTailored client, a Visual Studio client report definition (RDLC) report layout will need to be created first. Without the RDLC report layout, the report will always be run by an instance of the Classic client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 11. Open Report 123456701 in design mode, and select Create Layout Suggestion from the Tools menu, which will create a suggested RDLC layout and open it in Visual Studio Report Designer. Every time that this routine is run, the system will replace whatever RDLC layout is currently defined for the report. Once in Visual Studio, save the layout, close Visual Studio without modifying the layout, and save the report. Accept the confirmation to save the layout definition inside the report object. 12. Open the RDLC layout by selecting Layout from the View menu. NOTE: There is only one Header section and only one Body section, regardless of the DataItems in the report. 13. Change the Color property of the title and of the line captions to Blue. 14. Change the FontSize property of the line captions to 8pt. 15. Save the report layout and close Visual Studio. 16. Save the report in the NAV Report Designer, and accept the modified layout.
Part B - RoleTailored Client Report The Classic client report is done. Now make the RoleTailored client report. NOTE: In order for the report to be rendered from within the RoleTailored client, a Visual Studio client report definition (RDLC) report layout will need to be created first. Without the RDLC report layout, the report will always be run by an instance of the Classic client. 1. Open Report 123456701 in design mode, and select Create Layout Suggestion from the Tools menu, which will create a suggested RDLC layout and open it in Visual Studio Report Designer. Every time that this routine is run, the system will replace whatever RDLC layout is currently defined for the report. Once in Visual Studio, save the layout, close Visual Studio without modifying the layout, and save the report. Accept the confirmation to save the layout definition inside the report object. 2. Open the RDLC layout by selecting Layout from the View menu. NOTE: There is only one Header section and only one Body section, regardless of the DataItems in the report. 3. Change the Color property of the title and of the line captions to Blue. 4. Change the FontSize property of the line captions to 8pt. 5. Save the report layout and close Visual Studio.
6-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting 6. Save the report in the NAV Report Designer, and accept the modified layout.
FIGURE 6.5 REPORT 123456701 VISUAL STUDIO RDLC LAYOUT
FIGURE 6.6 REPORT 123456701 RENDERED IN ROLETAILORED CLIENT
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Part C - Report Selections Table and Page Now the table and page can be created, from which the report can be selected and run. 1. Create the Seminar Report Selections table (123456705) with the following fields: No.
Field Name
Type
1
Usage
Options
2
Sequence
Code
3
Report ID
Integer
4
Report Name
Text
o
Length
Comment Options: S.Registration.
10
Numeric field. Relation to the ID field of the Object table where the Type=Report.
80
FlowField; CalcFormula looks up the Object Caption field of the AllObjWithCaption table where the Object Type=Report and the Object ID= the field number of the Report ID. Must not be editable.
The primary key for this table is Usage, Sequence.
2. Enter code in the appropriate trigger so that when the user enters or changes the value in the Report ID field, the program calculates the Report Name value. 3. Define a new function called NewRecord. 4. Enter code in the function trigger so that the function filters the Seminar Report Selection table to the corresponding Usage. If the function can find the last record in the record set and if the Sequence for the record is not blank, the function increments the Sequence. If the function cannot find the last record or if the Sequence is blank, the function sets the Sequence to 1. 5. Create the Seminar Report Selection page (123456723) with a Repeater group that includes the Sequence, Report ID, and Report Name fields as shown in the GUI design. NOTE: Report selection pages have the PageType Worksheet. Use page object 306 (Report Selection - Sales) as an example. 6. Set the properties for the Report ID text box so that the LookupFormID is Objects. 7. Set the properties for the Report Name text box so that there is no drill down (the property Drill Down is No).
6-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting 8. Define a global variable called ReportUsage with the data type Option and a single option of Registration. 9. Define a function called SetUsageFilter. Enter code in the function trigger so that the function sets the filtergroup to 2 (two), and if the ReportUsage is Registration, the function filters the table to where Usage is S. Registration. At the end, the function resets the filtergroup to 0 (zero). 10. Add a text box labeled Usage to the top of the page as shown in the GUI design by adding a field element just above the Repeater Group. Set the properties of the text box so that the option is Registration and the source expression is the ReportUsage variable. 11. Enter code in the appropriate trigger so that the program runs the SetUsageFilter function when the user enters or changes the value in the Usage text box before the program opens the page. 12. Enter code in the appropriate trigger so that after the program validates the Usage text box, the program updates the page. 13. Enter code in the appropriate trigger so that when the page opens a new record, the program runs the NewRecord function. 14. Now menu items can be added to the main Seminar Menu to allow the user to run the reports. Add the Report Selections menu item to the Setup menu item in the Seminar Menu as shown in the GUI design. 15. Add the reports as shown in the GUI design into the Partner Menu Suite under the Order Processing - Reports group. 16. The user should be allowed to run the participant list for a particular seminar registration from the registration page. To enable this, add a command button to the page to run a codeunit to print the report. Develop the codeunit first. Create the Seminar Document-Print codeunit (123456703). 17. Define a function called PrintSeminarRegistrationHeader that takes one parameter. This parameter is a record variable of the Seminar Registration Header table, called SeminarRegHeader. 18. Enter code in the function trigger so that the function filters the SeminarRegHeader to the No. of the SeminarRegHeader record. The function filters the Seminar Report Selection table to those records with a Usage of S. Registration and a Report ID that is not 0 (zero). The function finds the set of records, and for each record in the set, modally runs the report corresponding to the Report ID stored in the Seminar Report Selection record. 19. Add a Print command to the Actions menu of the Seminar Registration page (123456710) as shown in the GUI design. Enter code in the appropriate trigger so that when the user clicks this selection, the program runs the PrintSeminarRegistrationHeader function of the Seminar Document-Print codeunit. 20. Add the same Print command to the Actions menu of the Seminar Registration List page (123456713).
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Part D - Testing 1. If there are no Seminar Registration records, create one by selecting seminars, clicking order processing, and then clicking registrations from the main menu. Fill in all of the fields in the General and Seminar Rooms tabs and add at least two participants. 2. Use the Seminar Report Selection window to set up the Seminar Reg.-Participant List as the report to be run for Registration. To do so, select seminars, click setup, and then click report selections from the main menu. Select Registration as the Usage and 123456701 on the first line for the Report ID. The report name should be filled in automatically. 3. Open the Seminar Registration page again and view the record prepared in step 1 (one). Click the Print button. 4. The request page should open with the No. set to the current registration. Select Print or Preview to print and check the report. 5. Try printing the report with different parameters and a variety of registration data to verify that it is working correctly.
6-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting
Certificate Information Upon completion of some seminars, participants receive a seminar certificate.
Solution Analysis These certificates are generated in the form of a report. This report should only include the participants whose seminar registration is posted.
Solution Design This report must create a page for each participant in a given seminar registration. This requires data from the Seminar Registration Header and Seminar Registration Line tables. For each Seminar Registration Header selected by the user in the request page, the report should print one certificate for each participant, with information from the Seminar Name, Starting Date and Instructor Name fields on the Seminar Registration Header table and from the Participant Name field on the Seminar Registration Line table. The client has provided a model for how this report should appear. A sample certificate report follows.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-17
® NAV 20 009 C/SIDE E Solution n Development in Microsoft M D Dynamics
E FOR SEMIN NAR PARTIC CIPANT FIGURE 6..7 SAMPLE CERTIFICATE C
6-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting
Lab 6.2 - Creating the Certificate Confirmation Report Scenario The Seminar Manager needs to be able to print completion certificates for selected seminars and registrants.
Challenge Yourself! Create objects to print the requested certificates. Use the supplied GUI design as a guide.
Step by Step 1. Create report 123456702 Seminar Reg.-Part. Certificate with the DataItems Seminar Registration Header and Seminar Registration Line. 2. Set the properties for the Seminar Registration Header DataItem so that the table is sorted by No. The user should be able to filter on the No., Starting Date and Seminar Code fields when running the report. The DataItem should only print if there are records to be printed. 3. Set the properties for the Seminar Registration Line DataItem so that it is indented to the first level and so that the DataItem is sorted by Document No. and Line No. Set the link property and set the property so that there is a new page for each record. 4. Define a global record variable of the Company Information table, called CompanyInfo. 5. Enter code in the appropriate trigger so that before the program runs the Seminar Registration Header DataItem, it gets the CompanyInfo record and calculates the Picture. 6. Enter code in the appropriate trigger so that after the program gets the record for the Seminar Registration Header DataItem, it calculates the Instructor Name. 7. Enter code in the appropriate trigger so that after the program gets the record for the Seminar Registration Line DataItem, it skips to the next record if there is no Participant Name in this record. 8. The sections used in this report are two body sections and one footer section, all for the Seminar Registration Line DataItem. Set the property for the footer section so that the section prints at the bottom of every page. 9. Place a picture box in the first body section as shown in the sample report in Appendix B. The source for the picture box is the Picture field of the CompanyInfo record.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 10. Place the following labels on the report for the fixed text of the report as shown in the sample report in Appendix B: o The "Participant Certificate" title, with a font size of 30 and bold. o The "has participated in seminar" phrase, with a font size of 15. 11. Set the captions for the labels so that they display the correct information. 12. Place text boxes on the report for the variable text of the report: o The participant name, with a font size of 25 and bold. o The seminar name, with a font size of 20 and bold. o The "on " phrase, with a font size of 15. o The instructor's name, with a font size of 9. 13. Set the source expressions for the text boxes so that they display the correct information. 14. Add a shape to the report in the footer section. Set the properties for the shape so that the shape style is that of a horizontal line. This time just let the report be rendered by the Classic client.
Testing 1. Select seminars, click order processing, click reports, and then click seminar reg.-part. certification from the main menu. 2. Select a registration and Print or Preview to verify that the report is functioning correctly.
6-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting
Invoice Posting When a seminar is finished, customers are invoiced for the participation of their registered participants. These invoices are implemented as reports, should allow for multiple participants, and can include project and resource information.
Solution Analysis The process to create invoices will be implemented as a ProcessingOnly Report. This type of Report object is used to process and modify data, without rendering any report for display purposes. This ProcessingOnly Report will create an invoice for each customer within a filter specified by the user, with lines for each participant in a registered seminar that falls within the filter set by the user. The user should also have the option of either creating the invoices or creating and posting them at the same time.
Solution Design Use the Seminar Ledger Entries to access all charges to be invoiced for posted seminars. The report creates Sales Headers and Sales Lines as appropriate, and if the user has selected the option to post the invoices as well, the report runs the posting process for sales invoices.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 6.3 - Creating the Invoice Posting Report Scenario Once a seminar has been completed, the registrations must be posted in preparation for billing.
Challenge Yourself! Create a ProcessingOnly report that will generate Microsoft Dynamics NAV standard format invoices ready for billing and, optionally, posting.
Step by Step This report is different from the previous two in that it is not a report to be printed but is instead a ProcessingOnly Report. 1. Create the Create Seminar Invoices report (123456700). Set the property to specify that this report is for processing-only. 2. Create a DataItem for the Seminar Ledger Entry table and set the properties for the DataItem as follows: o Specify the view of the DataItem to be sorted by Bill-to Customer No., Seminar Registration No., Charge Type and Participant Contact No. o Specify that the user should be able to filter on the Bill-to Customer No., Seminar No. and Posting Date. o Specify the variable name of the DataItem as SeminarLedgerEntry. 3. Define the following global variables for the report:
6-22
Name
DataType
Subtype
SalesHeader
Record
Sales Header
SalesLine
Record
Sales Line
SalesSetup
Record
Sales & Receivables Setup
GLSetup
Record
General Ledger Setup
Customer
Record
Customer
Job
Record
Job
JobLedgerEntry
Record
Job Ledger Entry
JobPostingGroup
Record
Job Posting Group
CurrencyExchRate
Record
Currency Exchange Rate
SalesCalcDiscount
Codeunit
Sales-Calc. Discount
SalesPost
Codeunit
Sales-Post
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Length
Chapter 6: Reporting Name
DataType
Window
Dialog
PostingDateReq
Date
DocDateReq
Date
CalcInvoiceDiscount
Boolean
PostInvoices
Boolean
NextLineNo
Integer
NoOfSalesInvErrors
Integer
NoOfSalesInv
Integer
Subtype
Length
4. Define the following text constants for the codeunit: Name
ConstValue
Text000
Please enter the posting date.
Text001
Please enter the document date.
Text002
Creating Seminar Invoices...\\
Text003
Customer No.
Text004
Registration No. #2##########\
Text005
The number of invoice(s) created is %1.
Text006
Not all the invoices are posted. A total of %1 invoices are not posted.
Text007
There is nothing to invoice.
#1##########\
5. Define a function called FinalizeSalesInvoiceHeader. Set the property to specify that this is a local function. 6. Define a function called InsertSalesInvoiceHeader. Set the property to specify that this is a local function. 7. Enter code in the FinalizeSalesInvHeader function trigger so that the function performs the following tasks: o If the CalcInvoiceDisc variable is TRUE (which means the user checked this option), the function runs the Sales-Calc. Discount codeunit with the Sales Line record and finds the Sales Header. o The function then performs a commit.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o o
The function clears the SalesCalcDiscount and SalesPost variables and increments the NoOfSalesInvoice by one. If the PostInvoice variable is TRUE (which means the user checked this option), the function clears the SalesPost variable. If running the Sales-Post codeunit with the SalesHeader returns FALSE, the function should increment the NoOfSalesInvErrors by one.
8. Enter code into the InsertSalesInvHeader function trigger so that the trigger performs the following tasks: o Initializes a new Sales Header record with a Document Type of Invoice and a blank No. and inserts it into the database. o Validates that the Sell-To Customer No. of the new record equals the Bill-to Customer No. of the ledger entry. o If the Bill-to Customer No. value is not the same as that of the Sell-To Customer No., the program validates that the Bill-to Customer No. of the new record equals the Bill-to Customer No. of the ledger entry. o Validates that the Posting Date of the new record is the PostingDateReq. o Validates that the Document Date of the new record is the DocDateReq. o Validates that the Currency Code of the new record is blank. o Modifies and commits the new record. o Sets the NextLineNo variable to 10000. 9. Enter code into the appropriate trigger so that just before the DataItem is run, the program performs the following tasks: o Shows an error if the PostingDateReq or DocDateReq is empty by using the text constants Text000 and Text001 respectively. o Opens a dialog window with the text constants Text002, Text003, and Text004. 10. Enter code in the appropriate trigger so that after the program gets a record for the DataItem, the program performs the following tasks: o Gets the Job Ledger Entry corresponding to the Seminar Ledger Entry record. o If the No. of the Customer record is not the same as the Bill-to Customer No., the program gets the Customer record corresponding to the Bill-to Customer No. o If the Customer record is blocked for All or Invoice, the NoOfSalesInvErrors increments by 1 (one). o If the Customer is not blocked for All or is only blocked for Invoice, the program proceeds with the tasks that follow. - If the Bill-to Customer No. is different from that on the current Sales Header record, the program updates the dialog window with the new Bill-to Customer No.
6-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting -
o o o
o
o
o
o
o o
If the No. on the Sales Header is not blank, it runs the FinalizeSalesInvoiceHeader function. The program then runs the InsertSalesInvoiceHeader function and sets the Document Type and Document No. fields on the Sales Line to be those of the Sales Header.
Updates the dialog window with the Sales Registration No. Sets the Type on the Sales Line according to the Type on the Job Ledger Entry. If the Type on the Job Ledger Entry is G/L Account, the program tests that the Job Posting Group on the corresponding Job record is not blank. - The program tests that the G/L Exp. Sales Acc. field on the corresponding Job Posting Group record is not blank. - The program sets the No. of the Sales Line to the G/L Exp. Sales Acc. value. If the Type on the Job Ledger Entry is not G/L Account, the program sets the No. of the Sales Line to the No. on the Job Ledger Entry. Fills the Sales Line fields as follows: - Document Type and Document No. from the Sales Header - Line No. from the NextLineNo variable - Description from the Seminar Ledger Entry - Work Type Code and Unit of Measure Code from the Job Ledger Entry - Unit Price from dividing the Total Price from the Job Ledger Entry by the Quantity If the Currency Code on the Sales Header is not blank, the program tests that the Currency Factor is blank and calculates the Unit Price for the Sales Line by running the ExchangeAmtLCYToFCY function of the Currency Exchange Rate table. Fill the Sales Line fields as follows: - Unit Cost (LCY) from the Total Cost of the Job Ledger Entry divided by the Quantity - Quantity and Job No fields from the Job Ledger Entry Inserts the Sales Line record. Increments the NextLineNo by 10000.
11. Enter code in the appropriate trigger so that when the program posts the DataItem, it performs the following tasks: o Closes the dialog window. o If the No. of the Sales Header is blank, the program displays a message saying there is nothing to invoice.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o
If the No. of the Sales Header is not blank, run the FinalizeSalesInvoiceHeader function. The program displays a message showing the number of errors that occurred, if any, or the number of invoices created.
12. Access the Request Form Designer by clicking on View, then on Request Form. Place two new text boxes and labels on the request form. The sources for these text boxes are the variables PostingDateReq and DocDateReq. 13. Place two new check boxes and labels on the request form. The sources for these check boxes are the variables CalcInvDiscount and PostInvoice. 14. Set the property for the request form so that the form saves the values after the form is closed. 15. Enter code in the appropriate trigger so that when the request form is opened, if the PostingDateReq and DocDateReq variables are not filled, they are set to the work date. Set the CalcInvDisc value to the value of the Calc. Inv. Discount field in the Sales Setup. 16. Access the Request Page Designer by clicking on View, then on Request Page. Add an Options group to the Request Page and include the same fields as for the Request Form. Enter the same code as for the Request Form into the appropriate page trigger, so that the same logic runs for the page in the RoleTailored client as would for the form in the Classic client.
Testing To test this portion of the seminar module, complete the steps described in previous exercises. In particular, it is important that the Job and Customer associated with the registrations being tested have been set up correctly. 1. Select seminars, click periodic activities, and then click periodic activities from the main menu. 2. The Create Seminar Invoices request page opens. Enter data so that one or more posted registrations meet the criteria. If there are no posted registrations, create one. Click OK to run the ProcessingOnly Report. 3. Look at the Sales Invoices that were created. See that the header and lines were created correctly based on the Seminar information. Expect to have one invoice per Bill-to Customer with a line for each contact registered. Check that the data flowed correctly from the registration (and the associated jobs) to the invoice. 4. Try running the Create Seminar Invoices process with the Post Invoices Option marked and unmarked and verify that the Sales Invoices are posted as indicated.
6-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting
Summary In this chapter, three reports were created. The first, Participant List was a normal report which will run in both Classic and RoleTailored clients. The second, Certificate Confirmation, was designed to run in the Classic client only, but this design will work properly for a RoleTailored client as well. The third report was a processing-only report to enable the creation of invoices for customers with participants in completed seminars. In the next chapter, statistics are added to the Seminar module.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. Place these triggers in the order in which they would execute in normal report processing: Step: _____: OnPostReport _____: OnAfterGetRecord _____: OnPostDataItem _____: OnPreDataItem _____: OnPreReport _____: OnInitReport 2. What report function would you use to skip the processing of one record in a DataItem?
3. What are the advantages of using processing-only reports in some situations as opposed to codeunits?
6-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting 4. a) What does the following line of code do and in what trigger would you expect it to appear? b) Will this work in a RoleTailored client report? CurrReport.SHOWOUTPUT(CurrReport.TOTALSCAUSEDBY = FIELDNO("Posting Date"));
5. a)What do you have to do to print FlowField data when running a report? b)What trigger do you use for this code?
6. In what trigger do you first have access to the values the user entered on the request form?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-29
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 7. What do you have to do to make a report run within the context of the RoleTailored client?
6-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting
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-31
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. Place these triggers in the order in which they would execute in normal report processing: Step: 6
: OnPostReport
4
: OnAfterGetRecord
5
: OnPostDataItem
3
: OnPreDataItem
2
: OnPreReport
1
: OnInitReport
2. What report function would you use to skip the processing of one record in a DataItem? MODEL ANSWER: The CorrReport.SKIP function is used to skip one record in a DataItem. 3. What are the advantages of using processing-only reports in some situations as opposed to codeunits? MODEL ANSWER: In Codeunits, you would have to write all the code to build the data record looping mechanism. Report objects have this mechanism built in by default, and it is much easier to get user input by using a report object. 4. a) What does the following line of code do and in what trigger would you expect it to appear? b) Will this work in a RoleTailored client report? CurrReport.SHOWOUTPUT(CurrReport.TOTALSCAUSEDBY = FIELDNO("Posting Date")); MODEL ANSWER: a) This line of code determines whether a section will be displayed in the report, and it would typically be written in the OnPreSection trigger. b) No.
6-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Reporting 5. a)What do you have to do to print FlowField data when running a report? b)What trigger do you use for this code? MODEL ANSWER: a) To print the value of a FlowField, you have to calculate it first, unlike form or page objects, which calculate FlowFields automatically. b) The command to calculate a FlowField is CALCFIELDS, and it would typically be written in the OnAfterGetRecord trigger of a DataItem. 6. In what trigger do you first have access to the values the user entered on the request form? MODEL ANSWER: The first trigger that runs after the user is done with the request form is the OnPreReport trigger. This trigger is typically used to evaluate the user's input, before proceeding to the DataItems. 7. What do you have to do to make a report run within the context of the RoleTailored client? MODEL ANSWER: The RoleTailored client needs an RDLC report layout to be able to render a report. To run a report within the context of the RoleTailored client, you have to first create a Visual Studio RDLC report layout. Without an RDLC report layout, the system will start a Classic client session to render the report object in classic format.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-33
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
6-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: Statistics
CHAPTER 7: STATISTICS Objectives The objectives are: •
Create a page that calculates price sums efficiently.
•
Make the page available from the Seminar pages.
•
Use FlowFilters to easily calculate statistics for different time periods.
Introduction In this chapter statistics are added to the Seminar Management module. Seminar managers at CRONUS International Training Academy require immediate and flexible financial reporting. Microsoft Dynamics NAV 2009 can meet this business need through the use of FlowFilters and FlowFields.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Prerequisite Information FlowFilters are useful for limiting calculations so that they include only the values in a column that have specific properties. For example, on the Seminar Statistics page, users may want to sum the total price of a seminar four different times, for four different time periods (such as week, month, current year, and prior year). This is possible if the application is designed to take advantage of SumIndexField Technology (SIFT) using FlowFilter fields in connection with the FlowFields. FlowFilters are used to determine how much information the system includes when it calculates the contents of FlowFields.
Using FlowFilters and FlowFields A FlowField is defined by setting the FieldClass property of the field to FlowField. The functionality of the FlowField is thereby defined by the value of the CalcFormula property of that field. The CalcFormula can include filter values which are based on constant and/or variable parameters. A FlowFilter is a specific type of filter field that is defined in the same table that has the FlowField to which it applies. Thus, FlowFilters can be applied to the source tables on which FlowFields are based. To implement a statistics page using the FlowFields and FlowFilter fields in a master table, look at Table 18 Customer and Page 151 Customer Statistics. The columns of the Customer Statistics Sales FastTab show the Sales (LCY) for four different time periods: •
This Period
•
This Year
•
Last Year
•
To Date
The data shown in these fields is generated by means of a FlowField, Sales (LCY), and a number of FlowFilters in the Customer table. The CalcFormula shown in the Sales (LCY) field properties uses a number of FlowFilters, but to simplify, just consider the Date Filter. In the OnAfterGetRecord trigger of the Customer Statistics page, the Date Filter is set for each of the desired time periods using the Date Filter-Calc codeunit. The CALCFIELDS function is then used for each Date Filter to calculate a value for the Sales (LCY). Use similar logic when creating the Seminar Statistics page. For more information on SIFT, FlowFields, and FlowFilters, refer to the Microsoft Dynamics NAV 2009 Developer and IT Pro Help.
7-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: Statistics
Seminar Statistics The purpose of the seminar statistics feature is to allow the user to quickly and easily get an overview of the price statistics for a specific seminar.
Solution Analysis FlowFields and FlowFilters can be used on the customer solution to provide statistics described in the functional requirements in Chapter 1, Business Case Diagnosis and Analysis. The client's functional requirements provide the following regarding statistical requirements: "Statistics for different time periods, such as: for a month, for last year, for this year, and up to the current date." This description indicates that the client wants to be able to open a Statistics page from a Seminar page. This page calculates the statistics for the total price and shows it for the four time periods listed. Seminar managers are to have access to the seminar statistics from a Seminar Detail page. This page calculates the total price statistics for the seminar for the time periods indicated in the function requirements.
Solution Design The Seminar Statistics page is to be accessible from the Related Information menu on the Seminar Card and Seminar List pages. It automatically calculates the statistics for the selected seminar using the information from the Seminar Ledger Entry.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Seminar Statistics page displays statistical information for one seminar, as shown in the following figure.
FIGURE 7.1 THE SEMINAR STATISTICS PAGE (123456714)
Seminar Card (Page 123456700): The Seminar menu selection on the Related Information button on this page is modified to include a new menu item for seminar statistics. Seminar List (Page 123456701): The Seminar menu selection on the Related Information button on this page is modified to include a new menu item for seminar statistics. The solution requires that FlowFields and FlowFilters are added to the Seminar table (123456700). Also, a key of Seminar No., Posting Date, Charge Type, Chargeable is added to the Seminar Ledger Entry table 123456732. The Total Price, Total Price (Chargeable) and Total Price (Not Chargeable) in the Seminar table is calculated using values from the Seminar Ledger Entry, for four different time periods. An array of four dimensions is used to store the totals for each of these three prices. The standard DateFilter-Calc codeunit is used to calculate date filters for the time periods. With the date filters, the Seminar table can be filtered and used to calculate the price fields to be shown on the page for each of the four time periods.
7-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: Statistics
Lab 7.1 - Creating FlowFields for Sums Scenario FlowFields are needed to support the planned Statistics page.
Challenge Yourself! Implement FlowFields for sums in the Seminar solution.
Step by Step Follow these steps to implement FlowFields for sums in this solution 1. Add a secondary key of Seminar No., Posting Date, Charge Type, Chargeable to the Seminar Ledger Entry table (1123456732). Set the property for the key so that the Total Price field is the sum index field. 2. Add fields to the Seminar table (123456700) as shown in the following table. No.
Field Name
Type
Length
Comment
20
Date Filter
Date
FlowFilter
21
Charge Type Filter
Option
FlowFilter; Options: Instructor, Room, Participant, Charge
25
Total Price
Decimal
FlowField; refer to step 3 below for the CalcFormula. Must not be editable. AutoFormatType=1
26
Total Price (Not Chargeable)
Decimal
FlowField; refer to step 4 below for the CalcFormula. Must not be editable. AutoFormatType=1
27
Total Price (Chargeable)
Decimal
FlowField; refer to step 5 below for the CalcFormula. Must not be editable. AutoFormatType=1
3. Set the CalcFormula for the Total Price field so that it calculates the sum of the Total Price field on the Seminar Ledger Entry table for the records where the Seminar No. corresponds to the No. field, where the Posting Date corresponds to the Date Filter, and where the Charge Type corresponds to the Charge Type Filter.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 4. Set the CalcFormula for the Total Price (Not Chargeable) field so that it calculates the sum of the Total Price field on the Seminar Ledger Entry table for the records where the Seminar No. corresponds to the No. field, where the Posting Date corresponds to the Date Filter, where the Charge Type corresponds to the Charge Type Filter, and where the records are not Chargeable. 5. Set the CalcFormula for the Total Price (Chargeable) field so that it calculates the sum of the Total Price field on the Seminar Ledger Entry table for the records where the Seminar No. corresponds to the No. field, where the Posting Date corresponds to the Date Filter, where the Charge Type corresponds to the Charge Type Filter, and where the records are Chargeable.
7-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: Statistics
Lab 7.2 - Creating the Seminar Statistics Page Scenario A Seminar Statistics page is required.
Challenge Yourself! Following the approach used for other statistics pages and using the table changes just completed, create a Seminar Statistics page and make it accessible from the Seminar Card and List pages.
Step by Step Follow these steps to implement the statistics page: 1. Create the Seminar Statistics page (123456714), based on the Seminar table. A statistics page has a PageType of Card, and has the LinksAllowed property set to No. Do not add any controls to this page yet. 2. Define the following global variables for the page: Name
DataType
Subtype
Length
DateFilterCalc
Codeunit
DateFilter-Calc
SeminarDateFilter
Text
30
SeminarDateName
Text
30
CurrentDate
Date
TotalPrice
Decimal
TotalPriceNotChargeable
Decimal
TotalPriceChargeable
Decimal
I
Integer 3. Set the Dimensions property for all the variables except DateFilterCalc, CurrentDate, and I so that each variable is an array of four dimensions. 4. Set the property for the page so that it is not editable. 5. Enter code in the appropriate trigger so that after the page gets the record, the program performs the following tasks: o Filters the table to the selected seminar.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o
If the CurrentDate is not the work date, the program sets the CurrentDate variable to the work date. - Runs the CreateAccountingPeriodFilter function of the DateFilter-Calc codeunit with parameters of the first dimensions of the SeminarDateFilter and SeminarDateName, the CurrentDate, and 0 (zero). - Runs the CreateFiscalYearFilter function of the DateFilter-Calc codeunit with parameters of the second dimensions of the SeminarDateFilter and SeminarDateName, the CurrentDate, and 0. - Then runs the CreateFiscalYearFilter function of the DateFilter-Calc codeunit with parameters of the third dimensions of the SeminarDateFilter and SeminarDateName, the CurrentDate, and the value -1.
HINT: There is similar code on the Customer Statistics page. o
o
o
For each of the dimensions, filters the table to records where the Date Filter corresponds to the value in the appropriate dimension of the SeminarDateFilter and calculates the Total Price, Total Price (Not Chargeable), and Total Price (Chargeable) fields. Sets the value for the appropriate dimension of the TotalPrice, TotalPriceNotChargeable, and TotalPriceChargeable to the values in the corresponding fields. Filters the table to those records where the Date Filter is before the CurrentDate.
6. Add a ContentArea Container to the page, and add an indented Group with label General to the ContentArea. 7. Add a Group with no label and subtype FixedLayout, which is the frame for the statistics area of this page. The values will be populated by defining columns for all four (4) dimensions. 8. Add a Group labeled This Period. Indented underneath this group, add an unlabeled field for SeminarDateName[1], a field labeled Total Price for TotalPrice[1], a field labeled Total Price (Not Chargeable) for TotalPriceNotChareable[1], and a field labeled Total Price (Chargeable) for TotalPriceChargeable[1].
7-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: Statistics 9. Repeat step 8 for three more groups labeled This Year, Last Year, and To Date. Be sure each of these three groups has appropriately increasing dimension values.
FIGURE 7.2 SEMINAR STATISTICS PAGE (123456714) IN PAGE DESIGNER
10. The last steps are to make the page accessible from the two seminar pages. Add the selections described in the table of the Related Information menu of the Seminar Card page (123456700) between the Comments and the Extended Texts menu items. Additional Seminar menu button action items: Options
Comment
Ledger E&ntries (Ctrl+Shift+N)
Opens page 123456721 Seminar Ledger Entries for the selected Seminar. Set the Image property to CustomerLedger.
<Separator> &Statistics (Ctrl+Shift+J)
Opens page 123456714 Seminar Statistics for the selected seminar. Set the Image property to Statistics.
<Separator> 11. Add the same menu selections to the Seminar List page (123456701) that are described in step 10.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution Testing To test the statistics page, it is necessary to have entries in the Seminar Ledger Entry table with the related posted seminar registrations. Follow these steps to verify the solution implementation: 1. Open the Seminar Card and view a seminar that has some posted registrations. Verify that the seminar has ledger entries by selecting seminar, clicking entries, and then selecting ledger entries from the Seminar Card. 2. Select seminar, and then click statistics to open the Seminar Statistics window. 3. Verify that the totals shown are correct for the different rows and columns. It may be convenient to apply a table filter to the Seminar Ledger Entries window and compare the results with the amounts shown in the Seminar Statistics window.
Summary This chapter focused on creating a statistics page for seminars that sums the total price in four different time periods. This statistics page is made available from the seminar pages' Related Information menu. This functionality is added though the use of FlowFields and FlowFilters, which use SIFT technology to provide filtered statistics quickly and easily.
7-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: Statistics
Test Your Knowledge 1. What is the purpose of a FlowFilter field?
2. How are FlowFilters used in calculations of FlowFields?
3. What are the advantages of using FlowFields to make calculations?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 4. What is the Microsoft Dynamics® NAV standard shortcut for opening a Statistics page?
7-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: Statistics
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-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. What is the purpose of a FlowFilter field? MODEL ANSWER: A FlowFilter is a special type of filter field that is defined in the same table that has the FlowField to which it applies. FlowFilters can be included in the CalcFormula of the FlowField to allow user defined filters to be applied in the calculation of the FlowField. When the user sets a filter in a FlowFilter, the system includes the FlowFilter value as a filtering constraint when calculating the contents of related FlowFields. 2. How are FlowFilters used in calculations of FlowFields? MODEL ANSWER: FlowFilters are set as filter values in the CalcFormula of FlowFields, and are used to limit the information that is retrieved when the system calculates the value of a FlowField. 3. What are the advantages of using FlowFields to make calculations? MODEL ANSWER: The advantages of using FlowFields are: a) to make it easier to develop and use fields with calculated values, and b) to make such calculations process faster. Calculating FlowFields takes just a few lines of C/AL code, because the filters and parameters are defined in the field's CalcFormula property. Writing code to calculate those values directly from their source tables takes considerably more effort to develop and in some cases, may take considerably more processing of data to calculate. 4. What is the Microsoft Dynamics® NAV standard shortcut for opening a Statistics page? MODEL ANSWER: The standard shortcut key for opening a Statistics page is Ctrl+Shift+J.
7-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions
CHAPTER 8: DIMENSIONS Objectives The objectives are: •
Describe Global, Shortcut and Budget dimension types and their functions.
•
List the basic rules of Dimension Setup.
•
List functions that help populate the dimension tables.
•
Implement dimensions on the master record level.
•
Describe the flow of dimension values for posted documents.
•
Describe how shortcut dimension fields are used.
Introduction Dimensions are used to control how analysis occurs. A two-dimensional analysis can be analysis of sales for a geographic area. However, by using more than two dimensions when creating an entry, a more complex analysis can be performed. For example an analysis of sales for each sales campaign for each customer group in each geographic area can be created. Dimensions are values added to an entry to act as markers for the program, which allows entries with similar dimension values to be grouped for analysis purposes. Many different types of entries in the program can have dimensions, including the following: •
Master records
•
Transaction document headers and lines
•
Journal lines
•
Ledger entries
•
Posted documents and their lines
Each dimension can have an unlimited number of dimension values. For example, a dimension called Department can have dimension values of Sales, Administration, Purchasing, and so on. Users define and tailor these dimensions and values to their company's needs.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Prerequisites Dimensions will play a key role in the development of the Seminar Management module.
Dimension Types There are three types of dimensions: •
Global
•
Shortcut
•
Budget
Global: When setting up dimensions in the G/L Setup, two of them can be global dimensions. These dimension types can be used throughout the program as a filter for G/L entries and on reports, account schedules, and batch jobs. Global dimensions are the only dimensions that are stored as part of the tables they describe. For instance, the G/L Entry table has two fields for the global dimensions. Shortcut: Enter shortcut dimensions on journal and document lines. These lines have eight fields that are designated for dimensions. The first two are always the global dimensions, but the remaining six can be selected from those set up as shortcut dimensions in the G/L Setup. Dimensions that are not set up as shortcut dimensions can also be specified, but these must be set up in a separate Dimensions window for the header or line. Shortcut dimensions that are not set up as global dimensions are not stored as actual fields of the tables they describe. Instead, they are stored in a separate table. Budget: Four dimensions can be defined for each budget. When a global, shortcut, or budget dimension is set up, the program automatically renames all fields that use the dimension type with the code caption specified when the dimension is setup. Where dimensions are stored depends on the type of entry. The following table shows different tables that contain dimensions with the types of entries with which they are associated.
8-2
Dimension Table
Type of Entry
352 Default Dimension
Master records
355 Ledger Entry Dimension
Ledger entries
356 Journal Line Dimension
Journal lines
357 Document Dimension
Document headers and lines
358 Production Document Dimension
Production orders, lines, and components
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions Dimension Table
Type of Entry
359 Posted Document Dimension
Posted document headers and lines
361 G/L Budget Dimension
Budget entries
Dimension Setup Dimensions are set up under the Administration area in the Departments, under Administration\Application Setup\Financial Management\Dimensions. For each dimension, a code, a name, a code caption, and a filter caption are defined.
FIGURE 8.1 DIMENSIONS PAGE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Global dimensions and shortcut dimensions are set up under General Ledger Setup, under the Dimensions FastTab. For the standard CRONUS International Ltd. demonstration database, the global dimensions have been set to the "Department" and "Project" dimensions, as shown in the following illustration.
FIGURE 8.2 GENERAL LEDGER SETUP - DIMENSIONS FASTTAB
Global Dimensions 1 and 2, if set up in the system, will now link to these two dimensions. For example, the Global Dimension 1 Code field in the Customer table will now have a caption of Department Code, because this dimension is set up as the Global Dimension 1 Code in General Ledger Setup.
Code Walkthrough - Dimension Management Codeunit Codeunit DimensionManagement (408) contains functions that help populate the dimension tables. Dimensions are stored in separate tables, and are identified by the table ID of the table that the dimension describes. The TypeToTableID functions in the DimensionsManagement codeunit are used to determine the correct table ID to store in the dimension value tables. They take one option parameter and then return the table ID of the table related to that parameter. For example, if "G/L Account" is passed in, the function returns table ID 15. These functions are used, through other functions, to populate the dimension tables where the table ID is needed. Without them, it is be necessary to write a similar case statement every time the table ID of an option field is needed.
8-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions Notice the SetupObjectNoList function. This function sets a temporary record object with a list of tables that use dimensions. This function is used in table 352, in the OnLookup trigger of the Table ID field. To include the master tables, the SetupObjectNoList function must be modified. Other functions of note in this codeunit are ValidateDimValueCode and SaveDefaultDim. ValidateDimValueCode takes in two parameters, the field number and the dimension value. The function checks to see that the dimension is valid, and returns an error if it is not. SaveDefaultDim saves the dimension in the default dimension table. In general, there are functions that correspond to each type of Dimension table for getting default dimensions, as well as updating, saving, deleting, inserting, and validating the consistency and combinations of dimensions.
Dimensions in Master Tables, Pages, and Codeunits The purpose of implementing dimensions on the master record level is to enable analysis of transactions that involve records from the master tables.
Solution Analysis The dimension values flow from the master records into the transactions in which they are involved. For example, the ledger entries that are a result of posting a transaction for a customer will have the same value for Department Code as that customer. In accordance with Microsoft Dynamics NAV standards, many master records are associated with default dimensions, including two Global Dimensions. The master record dimensions flow to the transactions in which the master data is used. These document dimensions eventually flow to the ledger entries and posted document dimensions.
Solution Design - DimensionManagement Codeunit Many enhancements to a system include creating new master tables. Enabling dimensions for new master tables requires changes to the master tables and pages and codeunits that manage dimensions. Entries for master records are included in the Default Dimension table (352). This table and the DimensionManagement codeunit must be modified so that they accept entries from the master tables. When the user creates a new record in a master table, the program inserts or updates the default dimensions. Likewise, when the user deletes a record, the program automatically deletes the associated dimensions. When the user enters a value in a dimension field, theValidateShortcutDimCode function is used to validate the entry. The DimensionManagement codeunit has a function called ValidateDimValueCode that helps with this.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 When an option field is part of a link to a master table, the DimensionManagement codeunit needs to know how to translate option values to table IDs. This is done through a number of functions, all starting with "TypeToTableID." For example, the function TypeToTableID1 function translates a specific set of option values into table IDs that are then entered into the TableID field of the appropriate dimension table. The option values of the Type parameter are the same as the option values of the field that is passed into the function. The following will likely have to be modified to support the use of dimensions within a new enhancement: •
The SetupObjectNoList function includes the master tables. The SetupObjectNoList function must be expanded to include every master table.
•
The TableIDArray variable dimension value must be expanded to include the new master table. The value for the expanded TableIDArray element variable must be set to the table ID of the new master table, much like the existing values are set for standard Microsoft Dynamics NAV master tables.
Solution Design - Global Dimension Fields The master table has fields defined where Global Dimensions 1 and 2 are stored. A fast and proper way to create these fields is to copy them from a core Microsoft Dynamics NAV master table, such as the Customer table. There are three setup steps in the master table: 1. Each field must be defined with the proper table relationship to the Dimension Value table, so that the Global Dimension No. field is a filter for the value 1 or 2. This is to correspond to Global Dimension 1 and Global Dimension 2, respectively. 2. The master table must be expanded to include a function that validates the dimension, named ValidateShortcutDimCode. Use the OnValidate trigger of the new Global Dimension fields to call the ValidateShortcutDimCode function. 3. The table triggers must have proper function calls to the DimensionManagement codeunit to update the dimension values when records are inserted into and deleted from the master table. These function calls drive the dimension values related to master tables. The function calls manage the synchronization of the actual fields in the master table and their corresponding records in the Dimension Value table. To examine these function calls in an existing master table, open the Customer table (18) in the Object Designer. Search the C/AL editor for all instances of the DimMgt variable.
8-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions Solution Design - User Interface Access to Dimensions is added to the Card page under the Related Information menu. Use the shortcut key of Ctrl+Shift+D to open the Default Dimensions page that is related to the current master record.
FIGURE 8.3 THE DIMENSIONS SELECTION ON THE RELATED INFORMATION MENU ON THE CUSTOMER CARD PAGE
Dimensions in Documents Dimension values that are related to master records flow into each transaction in which they are involved. For example, when a customer is selected on a sales order, that customer's dimensions are copied from the master record into the document dimension. Similarly, when an Item, or a Resource, or a G/L Account (remember the TypeToTableID functions) is entered into an order detail, its dimension values will flow into the document dimension on the order's line records. When these documents are posted, their dimension values flow into the journal tables, the ledger entry tables and the posted document tables.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution Design - Shortcut Dimension Fields Transaction documents and lines use shortcut dimension codes. Enabling dimensions in transaction documents means setting up the shortcut dimension codes for the header and lines, and writing code so that the dimensions from the seminar, seminar room, and instructor chosen for the seminar registration are also included. This also enables dimensions on the posted seminar registration tables and pages. Just as is done with relating dimensions to master records, the document tables must be expanded with the correct dimension fields. Also, the code in the table needs to be expanded to include the logic used to manage dimension values. To see how this works in the standard application, look at how dimensions are handled in the Sales Header table (36) and the Sales Line table (37). Both tables have a Shortcut Dimension 1 Code field and a Shortcut Dimension 2 Code field. In addition to the fields, the document tables need to include calls to the appropriate functions in the DimensionMangement codeunit. Just as with the master table, document tables require the following added to the C/AL code behind the table: •
The table must be expanded to include a function that validates the dimension, called ValidateShortcutDimCode. Call this function from the OnValidate trigger of the Shortcut Dimension Fields.
•
The table's OnInsert and OnDelete triggers must have calls to the DimensionManagement codeunit to update the dimension values when records are inserted into and deleted from the master table.
From the OnValidate trigger of the field that controls which dimensions are attached to the documents, there should be a call to the CreateDim function. This will attach the dimensions to the document from the associated master record. This is the same model as the logic which is executed in the Sales Header table when the Bill-to Customer is changed.
GUI Design Standard Microsoft Dynamics® NAV allows for up to eight shortcut dimensions, two of which are reserved as Global Dimensions. The remaining six shortcut dimensions can be entered directly into the user interface in selected areas.
8-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions One example is the Sales Order, where values can be entered into the shortcut dimension fields directly. In addition to the two global shortcut dimension fields, there are controls to enter values directly into the remaining six shortcut dimension fields. These fields are not physically present as fields in the underlying table, but are displayed on the page from an associated table.
FIGURE 8.4 CUSTOMIZE LINES FOR THE LINE'S FASTTAB OF THE SALES ORDER PAGE
NOTE: There are a series of dimension fields available, ranging from the Department Code to Shortcut Dimension 8 Code. These dimension fields are the same as those set up as shortcut dimensions in General Ledger Setup. To see how this works in standard Microsoft Dynamics NAV, inspect the object for the Sales Order Subform page (46). The shortcut dimension fields are located at the bottom of this page designer. The code in the page triggers function calls to the dimension functions in the table, which in turn calls functions in the Dimension Management codeunit. There is additional code to display the right caption, and code to validate the dimension when entered into the page. NOTE: The SourceExpr properties of the shortcut dimension fields point to the two shortcut dimension fields in the underlying table and to the ShortcutDimCode variable, which is set by the function calls in the page and validation triggers.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Dimensions in Posting To enable the transfer of dimensions in the posting process, shortcut dimension fields are added to the journal and ledger entry tables. Then code in the posting routines transfer the dimensions from document headers and lines to the posted document headers and lines in the appropriate journal and ledger entry tables. For dimensions that are not set up as global dimensions, the system will create values in the dimension value tables related to the posted documents and the ledger entries. Managing the flow of dimensions from unposted documents to journal lines, ledger entries and posted documents is done by a number of function calls in the posting routines. The best way to understand how this is done is to create a transaction and to debug the posting process, and focus on the dimension logic. The DimensionManagement codeunit has a number of functions that transfer dimension values from one place to another, and each function has its own specific purpose. For example, there is a function called CopyDocDimToJnlLineDim that copies the dimensions that are entered for the unposted document into the journal line. Then during the posting routine for that journal line, there will be another function call to the DimensionManagement codeunit to transfer the dimension from the journal line into the ledger entry.
8-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions
Lab 8.1- Using The Debugger Interface To View The Dimension Process Dimensions have been created. Now use the debugger interface to view the internal processes of a specific instance in the dimension process. Scenario The debugger interface lab uses dimensions to illustrate a scenario in which the debugger is used to understand a process in Microsoft Dynamics NAV 2009. This lab is intended as an instructor-led, walk-through that students can follow along if they wish. The C/SIDE debugger runs only from within the Classic client, the client from which all C/AL development is done. This lab uses the standard Microsoft Dynamics NAV CRONUS International Ltd. company dimension setup. For more information about debugging in the RoleTailored client, see the the Microsoft Dynamics NAV 2009 Developer and IT Pro Help.
Challenge Yourself! Use the debugger interface to view the dimension process.
Define Dimensions 1. To open the following Dimensions screen: o Open the Financial Management menu o Select the Setup option o Select the Dimensions option
FIGURE 8.5 FINANCIAL MANAGEMENT MENU TO SETUP OPTION TO DIMENSIONS
2. The following fields are used: o Code, to identify the dimension o Name, to describe the dimension
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o o
Code Caption, the caption used for shortcut dimensions Filter Caption, used when dimensions are part of a filter
General Ledger Setup 1. From the Financial Management menu, select the Setup option. 2. Select the General Ledger Setup. 3. Shortcut dimensions are defined on the Dimensions tab of this form, as show in the next image.
FIGURE 8.6 GENERAL LEDGER SETUP / DIMENSIONS
NOTE: Department and Project are selected as the global dimensions (the same as the first two shortcut dimensions).
Dimensions In Master Records To illustrate dimensions in master records, look at dimensions as they are used for the Customer table.
8-12
•
The first task is to prepare the Customer Card form to display the global dimension fields, create a new customer, and assign dimensions to the customer.
•
The debugger interface will be used to observe how the code is processed when a dimension is assigned to the customer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions Design Walkthrough The Customer table, like any other master table in Microsoft Dynamics NAV, has two fields to store global dimensions, as shown in the following image.
FIGURE 8.7 TABLE 18 CUSTOMER - TABLE DESIGNER
•
Both fields have a table relationship to the Code field of the Dimension Value table.
•
Global Dimension No. equals 1 for the Global Dimension 1 Code field and it equals 2 for the Global Dimension 2 Code field.
•
The CaptionClass property of the field (which is set to '1,1,1' for the Global Dimension 1 Code field, and to '1,1,2' for the Global Dimension 2 Code field) determines the caption of the field when it is displayed by another object. The code that translates these captions is in Codunit1.
The OnValidate trigger for both of the dimension fields has a call to the ValidateShortcutDimCode function of the Customer table. This function validates the dimension value, and saves the dimension value into the Default Dimension table. This function validates the dimension value, and saves the dimension value into the Default Dimension table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The Default Dimension table is where all dimension values for maser records are stored. Both the validation and save tasks are done in functions of the DimensionManagement codeunit (408), as shown in the following image.
FIGURE 8.8 VALIDATION AND SAVE DONE IN DIMENSION MANAGEMENT CODEUNIT 408
The ValidateDimValueCode function checks to see if the selected dimension is indeed the correct global dimension, that this dimension can indeed be selected for this table, and that the value itself is a permitted value for the dimension. The SaveDefaultDim function saves the dimension into the Default Dimension table, including a link to the current master record, by way of table ID and key value. The purpose of the Default Dimension table is that in every dimension it can be accessed from the same source. The purpose of having the dimension in its own field in the master tables (at least for up to two global dimensions) is to provide quicker access without retrieving the dimension value from another table.
Customer Card Neither of the global dimension fields is displayed on the default Customer Card form. To be able to debug the process, the fields must be added to the form. 1. Open the Customer Card form in design mode. 2. Add the two global dimension fields to the Communication tab. The only purpose of this change is to allow direct entry of a dimension value and in turn allow the tracing of the resulting processing using the debugger.
8-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions The next image shows the Customer Card in design, with the two added dimension fields on the Communication tab.
FIGURE 8.9 CUSTOMER CARD IN DESIGN WITH ADDED DIMENSION FIELDS ON THE COMMUNICATION TAB
NOTE: The field name and the caption are different from each other for both fields. The field names are Global Dimension 1 Code and Global Dimension 2 Code. Their captions are Department Code and Project Code. If returning to the Dimensions form and changing the Code Caption value of one field to the Something Code, then this becomes the caption of the associated fields in the field menu.
Create New Customer To illustrate, begin by creating a new customer. 1. Open the customer card from the Sales option in the Sales & Marketing menu. 2. Click F3 and enter a new customer. 3. Ensure that this new customer has valid posting groups so that it can be used when a new order is created later in this chapter.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The next few images show the General, Invoicing, and Communication tabs of the new customer:
FIGURE 8.10 GENERAL TAB OF CUSTOMER THE CARD
FIGURE 8.11 INVOICING TAB OF THE CUSTOMER CARD
8-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions
FIGURE 8.12 COMMUNICATION TAB OF THE CUSTOMER CARD
Debugging Process The debugger is used to display C/AL code in parallel with the code's interpretation and execution by Microsoft Dynamics NAV. Debugger output is displayed when certain conditions are met. By default, the debugger runs in the background, and only displays with the code reaches a breakpoint. This happens when an error occurs, when a user defined breakpoint is reached, or when Breakpoint on Triggers is turned on when the code enters a new trigger. 1. The debugger is activated from the Debugger section on the Tools menu. 2. When the debugger section is displayed, the current values of the debugger are shown, as in the following image.
FIGURE 8.13 SETTING DEBUGGER TO ACTIVE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 3. Notice that two debugger settings are available: o Active (Shift+Ctrl+F11) which sets the debugger to run in the background o Breakpoint on Triggers (Shift+Ctrl+F12) which sets the debugger to interpret each new trigger as a breakpoint. This option is used when the developer wants to debug the entire process from the start. By default, this option is turned off, and the debugger will break when an error is caused or when the code hits a user-defined breakpoint. 4. Turn on the Breakpoint on Triggers and set the debugger to Active. 5. Return to the Customer card and click in the Department Code field. 6. Immediately, the debugger opens up in the CaptionClassTranslate function of codeunit 1. The CaptionClassTranslate function builds the caption for the Global Dimension 1 Code field, based upon the CaptionClass. These values will be looked at closer later in this Lab exercise. 7. Look closely at the Debugger Tool. The following image shows the entire debugger screen, with its most important parts visible.
FIGURE 8.14 THE DEBUGGER SCREEN
8-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions 8. The Code section of the debugger screen (shown in the following image) is the most prominent area of the debugger screen.
FIGURE 8.15 CODE SECTION OF THE DEBUGGER SCREEN
This is where the C/AL code that is currently being executed is displayed. When viewing the active code window, the yellow arrow points at the line of code that is about to be executed. The code section is where a developer spends most of his or her time, stepping through the code one line at a time, while tracking values. The purpose of the debugger is to walk through the code and determine if the code is doing what it is supposed to do. If the code is not performing as expected, the debugger helps the developer find exactly where it is failing. 9. The Variables section of the debugger screen (shown in the following image) displays all variables that are currently in scope, listing the name, value and type for each variable. Notice at the bottom of the variables section, there are tabs for Locals, Globals, Text Constants and a tab that displays all variables.
FIGURE 8.16 THE VARIABLES SECTION OF THE DEBUGGER SCREEN
The developer checks values of the variables that are used during code execution, making the variables section the second most frequently visited section of the debugger.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 When variable values change, the values are displayed in red immediately after the line of code is executed. Notice that in the previous image of the debugger's variable section, the Text021 text constant and the CommaPosition variable are displayed in red. This means the line of code just executed modified these values. The Call Stack section of the debugger screen (shown in the following image) displays the trail of triggers that is being executed. As the code steps deeper into triggers, the system places these triggers on top of the stack.
FIGURE 8.17 THE CALL STACK SECTION OF THE DEBUGGER SCREEN
Notice in the above image that the yellow arrow points at the current trigger (the DimCaptionClassTranslate trigger), which is called from the CaptionClassTranslate trigger. As the call stack shows the yellow arrow by the DimCaptionClassTranslate function, the code section displays the yellow arrow by the line of code that is about to be executed. The developer can double-click the triggers in the call stack to display the last line of code that is executed in that trigger, to see how the code got to this point, and how the current trigger is called. The results of double-clicking on the second trigger in the call stack are shown in the following image:
FIGURE 8.18 RESULT OF DOUBLE-CLICKING THE SECOND TRIGGER IN CALL STACK
8-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions Double-clicking the triggers in the call stack is a powerful way to investigate how the code is executed up to the current point in code. Notice in the previous image, there is a green arrow next to the second trigger in the call stack, and there is also a green arrow by the line of code in that trigger. This shows how the next trigger is called. As both triggers are in the same object, both are in the same window. 10. The Watch section of the debugger screen can be used to monitor the value of selected variables. To get a variable into the Watch section, it must be pulled in by right-clicking the variable, and then selecting Add Watch, as shown in the next image.
FIGURE 8.19 ADD WATCH SECTION TO THE DEBUGGER SCREEN
In the above image, the GLSetupRead variable is about to be added to the Watch section. Once the variable is in the Watch section, it will remain there until removed by the developer. Even when other objects are debugged, the Watch section will still display the variable along with a message that it is "uninitialized." As in the Variables section, the Watch section is used to see the value of selected variables. The difference between the Variables section and the Watch section is that the number of variables in the Watch section is completely under the control of the developer during runtime. The Watch section can be an efficient way to monitor variables because as long as the number of variables in the Watch section is limited, the developer does not have to browse the variable windows for the specific variable wanted. Also, the developer can add a Watch section entry for a local variable and a global variable at the same time, and then monitor his or her values in the same section.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Following is an example of the Watch section, immediately after the GLSetupRead variable changes in code.
FIGURE 8.20 THE WATCH SECTION AFTER THE GLSETUPREAD VARIABLE CHANGED
11. The Output window of the debugger screen reports errors when they happen. This is a redundant action, as the debugger also displays an actual error message. To minimize the Output window and maximize the remaining sections on the debugger screen, resize the screen as shown in the following image, or close the Output window by clicking the X in the corner.
FIGURE 8.21 RESIZE DEBUGGER SCREEN TO MINIMIZE THE OUTPUT SECTION
8-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions The preceding image shows the debugger screen with the minimized Output window at the bottom of the screen. Notice that the Watch window still displays the GLSetupRead variable, even though it is now out of scope. Also, the call stack shows three triggers in two objects, and that window menu lists two windows, both of which show C/AL code that is executed in the Code section. 12. Stepping Through The Code. After viewing all the important debugger screen windows, it is now time to actually step through the process. There are three essential ways to execute code in the debugger: o Step Into (F8). The Step Into command enters into the current line of code. It executes the current line of code and if this is a call to another trigger, it will jump right to that trigger's C/AL code. o Step Over (Ctrl+F8). The Step Over command executes the current line of code, and then jumps right to the following line of code. If the current line of code is a call to another object that the developer does not need to step through one line at a time, it can "step over" the current line and continue debugging the following lines. This is very useful for avoiding tedious step-bystep processing of functions not of interest at the moment. o Go (F5). Go pushes the debugger into the background until the next breakpoint, or until the start of a new trigger if the Breakpoint on Triggers is turned on. 13. Setting Breakpoints is a way to make debugging more efficient. Many processes run through large numbers of objects. It can be quite time consuming to step through the code one line at a time. When the area of code is known, and the developer does not want to step through all of the code, a breakpoint can be defined in the area of interest. The developer can then let the debugger run with Breakpoint on Triggers turned off. This action will allow the debugger to run in the background, displaying the code when it reaches the defined breakpoint.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Breakpoints are set by putting the cursor on the line of code in question and pressing F9, which can be done in one of two ways: •
In the C/AL editor at design time.
•
In the debugger, when the code is in the object that is currently on display in the code section.
FIGURE 8.22 SETTING BREAKPOINT WITH F5
The previous image shows a yellow arrow pointing to the current line of code. Note the maroon circle in the margin to the left of the last line of code in the current trigger. The developer is not interested in any of the code in this trigger, and wishes to quickly jump to the last line of code. By setting the breakpoint, and then pressing F5, the debugger is instructed to jump right to the next breakpoint. A useful debugging strategy is to set a breakpoint immediately after a function call, especially if the developer is not certain what that function call is going to do. This allows the developer to step into the function, see what it is actually going to do, and still have a way to quickly jump back to the original object by pressing F5. 14. Aborting a process. Turning off the debugger and pressing F5 will cause the current debugging process to complete. However, it may be useful at times to abort the current transaction altogether to start a new debugging session with the same data.
8-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions To abort a debugging process select Stop Debugging (Shift+F5) from the dropdown Debug menu to stop the Debugger and roll back the current transaction.
FIGURE 8.23 ABORT WITH STOP DEBUGGING (SHIFT+F5)
15. Returning to Dimensions. At various sections of the debugger while processing dimensions-related code, it seems that the debugger is continuously going back into the same object. It seems as though some sort of interaction between the debugger and the Classic client is causing an endless loop. It appears that when the debugger gives control back to the Classic client for a split second, such as when starting to process the new dimension value, the debugger activates the Customer card, then jumps back into translating the caption class for the Global Dimension Code fields. The one way to step through the code in a controlled fashion is to set a manual breakpoint, then turn off the debugger, and press F5. This action will return the Customer card form in the Classic client. 16. Setting the Breakpoint. o Open the Customer table in the Object Designer. o Browse to the Global Dimension 1 Code field o Press F9
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 This will open the C/AL editor with the cursor on the OnValidate trigger of this field. •
Put breakpoints on C/AL code of the Global Dimension 1 Code and the Global Dimension 2 Code fields, as shown in the next image.
FIGURE 8.24 SETTING BREAKPOINTS IN THE C/AL CODE OF DIMENSION 1 CODE AND DIMENSION 2 CODE FIELDS
•
Now turn the debugger back on, and ensure that Breakpoints on Triggers is turned off.
17. Debug Entering a Department Code. o Open the Customer card, go to the Communication tab. o Look up the dimension value table, and select one of the values. o When the value is selected into the field, press Enter to accept the value into the field. This causes the OnValidate code of the Global Dimension 1 Code field to execute. o Because the debugger is running, and because a manual breakpoint is set, the debugger breaks on this line of code, and then it displays the debugger window. o Step through the code one step at a time, by pressing F8. Notice how it jumps from the OnValidate trigger into the ValidateShortcutDimCode function in the Customer table, and into the ValidateDimValueCode function in the Customer table, and then into the ValidateDimValueCode function in the Dimension Management codeunit. o Try double-clicking either one of the triggers to see where the code is executed, which type of arrow is displayed, and what the meaning is of these arrows. o Pick any variable, add it to the Watch window and observe how its value changes. o Try to follow along and see when the Default Dimension record is created for the current customer. When does the system verify that the value that is being entered is a valid dimension value? 18. Debugging is a task that developers do on a daily basis, quite possibly more so than actually writing code. It is one task that every developer should master. It is important to build debugging skills, to become efficient with the various sections, and to learn when to step into a line of code.
8-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions
Summary This chapter explored the role of dimensions in Microsoft Dynamics NAV and demonstrated how to implement dimensions in the existing features of the Seminar Management module. As a result, the student can now work with dimensions as a development tool in Microsoft Dynamics NAV. This chapter also introduced the debugger interface which is applied to dimensions and is used as a tool to follow the flow of dimensions C/AL code.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. What is a dimension and what is its purpose in Microsoft Dynamics NAV?
2. In what tables are the dimensions for the following entry types stored? Categories (Tables): _____ Item 1: "Master" data entries (like Customer or Seminar) _____ Item 2: Transaction document header and lines (like Sales Line or Seminar Registration Header) _____ Item 3: Journal lines _____ Item 4: Ledger entries _____ Item 5: Posted documents 3. Describe the flow of information and how dimensions are transferred from the master data through transaction documents to ledger entries and posted documents.
8-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: Dimensions
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-29
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. What is a dimension and what is its purpose in Microsoft Dynamics NAV? MODEL ANSWER: A dimension is a value that is entered into a transaction to enable transactions with similar values to be grouped together for analysis. 2. In what tables are the dimensions for the following entry types stored? Categories (Tables): 352
Item 1: "Master" data entries (like Customer or Seminar)
357 Item 2: Transaction document header and lines (like Sales Line or Seminar Registration Header) 356
Item 3: Journal lines
355
Item 4: Ledger entries
359
Item 5: Posted documents
3. Describe the flow of information and how dimensions are transferred from the master data through transaction documents to ledger entries and posted documents. MODEL ANSWER: Dimension values are transferred from the master record to the transaction when the master record is selected into the document. The dimension values are then transferred from the document to the Journal Lines, Ledger Entries and Posted Documents by logic in the posting routines.
8-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces
CHAPTER 9: INTERFACES Objectives The objectives are: •
Use automation servers to perform tasks with other applications.
•
Install and use custom controls in C/AL.
•
Use file handling functions to import or export data.
•
Design and implement an e-mail capability.
•
Use the XMLport to generate exported data in XML format.
Introduction This chapter deals with some of the methods that are used to interface Microsoft Dynamics® NAV to external software or hardware. One method to extend Microsoft Dynamics NAV is to use Component Object Model (COM) and file handling. First the essentials of COM are discussed, both from the Automation Server and Custom Controls (OCX) perspectives. Then, automation is used to add e-mail confirmation functionality to the seminar solution. Finally, file handling is used to generate an XML participant list. These are examples of how Microsoft Dynamics NAV solutions can be extended to provide enhanced functionality.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Prerequisite Information In C/SIDE, developers use (COM) technologies in one of two ways: by using custom controls (OCXs) or by using automation (C/SIDE in the role of an automation controller or client) to perform tasks with other applications.
Using an Automation Server To create the Seminar Management e-mail confirmations, use C/SIDE as an automation server. Using an automation server consists of five basic steps: 1. Declare the creatable (top-level) interface (class) of the automation server as the 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 C/AL code. The syntax and semantics for these methods and properties are documented for each automation server. 5. (optional) Destroy the top-level object with the CLEAR function. If you do not destroy this object, it is automatically destroyed when the variable goes out of scope. It is recommended to create a separate codeunit for code that uses automation because of performance issues, and because an object using automation can only be compiled on a machine on which the automation server is installed. By default, the automation server resides on the Microsoft Dynamics NAV Server tier, and not on the client computer. For Microsoft Dynamics NAV 2009, the CREATE function is now expanded with a third optional parameter. This parameter is used to specify whether you want to create the instance of the automation variable on the client tier or on the Microsoft Dynamics NAV Server tier. The automation server must be installed and/or registered on the tier where it runs. The data being transferred must be in text format.
Using custom (or OCX) Controls Microsoft Dynamics NAV supports custom controls (which are also known as OLE controls or ActiveX controls) with a few limitations: •
9-2
Only non-visual controls are supported. A control cannot be used to add graphical elements to a C/SIDE object (for example, you cannot add a third-party control to a form). The control can, however, display information and interact with the user in a window of its own.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces •
Exception handling is not supported. C/SIDE does not allow the retrieval of information about exceptions from a control or automated server through the Invoke method of the IDispatch interface and the EXCEPINFO structure.
A custom control must be physically installed on the target machine and registered with the operating system. For the RoleTailored client, the control must be registered on the Microsoft Dynamics NAV Server tier. OCX controls cannot live on the client tier; they must always live on the service tier. To use a custom control, declare it as a global or local variable with a data type of OCX. Then select the desired custom control from a list by clicking the lookup button in the Subtype field. If the desired control is not in the list, the control can be installed and registered manually. To install and register a custom control: 1. Copy the custom control from the distribution media to the hard disk. The C/FRONT folder contains a readme.txt file with more information. 2. Click Tools, and then Custom Controls. 3. Click the Control button, and select Browse to open a standard Windows dialog to locate the OCX that is to be registered. 4. After locating and selecting the custom control, click Open. 5. The custom control is now registered with the system. A confirmation message will be received once the registration is complete. Click OK to return to the Custom Controls window and then the custom control just added appears on the list. To declare the control as a variable: 1. In Object Designer, create a new blank form that is not based on any table. 2. Click View, and the C/AL Globals to open the C/AL Globals window. 3. In the Name field enter cfront, and in the DataType field select OCX. 4. In the Subtype field, click the AssistButton to open the Custom Control List window. 5. Locate the control just installed, select and click OK. 6. Declare the additional variables. Once the control is declared a variable, its methods and properties can be accessed. To view the methods and properties available, use the C/AL Symbol menu. Methods can be run just as any other function is run in C/AL, and properties can be read and set the same as any other object properties.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Installing Automation Objects Code for automation objects runs on Microsoft Dynamics NAV Server. Ensure that files generated on the computer that are running Microsoft Dynamics NAV Server, and that code is running in the correct places for the automation to run successfully. The following scenarios demonstrate how to change the automation objects created to support Microsoft Dynamics NAV Server. NOTE: COM objects need to be installed only on the computer that is running Microsoft Dynamics NAV Server. COM does not need to be installed on every client.
Using a COM Component to Generate an Excel File for a User Use the CREATE function with C/AL code running on Microsoft Dynamics NAV Server to create the automation object, and run its SAVE function to save it to that computer. When the RoleTailored client needs access to the file, use the FILE.DOWNLOAD function to send it from the computer that is running Microsoft Dynamics NAV Server to the client. To ensure that this works correctly, the COM DLL must be stored and registered in the computer that is running Microsoft Dynamics NAV Server.
Using a COM Component to Carry out External Processing With CAL code running on the Microsoft Dynamics NAV Server, use the CREATE function to create an automation object, and then call a method on the object. When the method is run, any return value is passed back to the code. To ensure that this works correctly, the COM DLL must be stored and registered on the computer that is running Microsoft Dynamics NAV Server.
Using a COM Component to Read from an MSMQ Message With C/AL code running on a computer that is running Microsoft Dynamics NAV Server, use the CREATE function to create an automation object and the READ function to read it from the message queue. For the RoleTailored client, the Microsoft Dynamics NAV Server processes the result of the READ function.
9-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces NOTE: If the queue location is specified locally (such as ./myqueue), the code reads from a message queue called myqueue on the computer that is running Microsoft Dynamics NAV Server, and not from a message queue on the client.
File-Handling File-handling is useful for importing or exporting text-based data files that require parsing to interpret on input, or special formatting when output. For example, file-handling can be used to import data that is not record oriented or where the records exceed the size of text strings (250 characters) that can be handled in Microsoft Dynamics NAV text variables. Through File variables, import data from or export data to any file accessible through the operating system.
The File Data Type To gain access to an external file from within C/SIDE, first declare a variable of type File. This is a complex data type, which has numerous functions used to open, read, write, and close external files. Each File variable can be used to access one file at a time. This makes is necessary to declare one File variable for each file that must be accessed simultaneously. This chapter discusses some of the frequently used file methods. Refer to the Developer and IT Pro Help for a comprehensive list of the File type variable.
Opening Files for Import or Export Before a file can be opened for use, it must be set up properly. First determine whether it will be used for reading (import) or for writing (export). Although theoretically a file can be open for writing and then can be read, this is normally not done in Microsoft Dynamics NAV. The following bulleted list contains the File functions used to prepare a file for opening and closing it. As with other functions, these are called through the File variable. For example, if the File variable is named ImportFile, then using the Open method looks like this: ImportFile.OPEN(Name) ;
•
WRITEMODE(NewWriteMode): Sets the read/write status of a File variable before opening the file. If NewWriteMode is TRUE, the file can be written. If NewWriteMode is FALSE, then the file can only be used for reading. Note that another way to use this method is: IsWriteMode := WRITEMODE;. With this function (used after the file is open) it can be determined whether a file is available for writing or not.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
9-6
•
TEXTMODE(NewTextMode): Sets the type of data to be read or written. If TRUE, the file is opened in Text mode, and if FALSE, it is opened in Binary mode. This method can only be used before opening the file. Note that another way to use this method is: IsTextMode := TEXTMODE;. With this function (used only after the file is open), it can be determined whether a file is being read or written in text mode or binary mode.
•
QUERYREPLACE(NewQueryReplace): Use this function for opening a file using the CREATE method. If NewQueryReplace is TRUE and the file already exists, C/SIDE asks the user before a replace is allowed. If NewQueryReplace is FALSE, and the file already exists, C/SIDE erases the old file and replaces it with a new (empty) one, without asking the user. If the file does not already exist this function has no effect. This function is not supported in the RoleTailored client.
•
OPEN(FileName): Use this function to open an already existing file. Be sure to set the WRITEMODE and the TEXTMODE before opening a file. FileName is the full path name of the file. When used as a statement (without using the return value) and the file indicated by FileName does not exist, OPEN causes a run-time error. If OPEN is used as an expression (using the return value) and the file indicated by FileName does not exist, OPEN returns FALSE, but if the file does exist, it is opened, and OPEN returns TRUE. If you are running the RoleTailored client and you call OPEN on a file variable that refers to an open file, the function will not automatically close the existing file and open the new file. You must explicitly call the CLOSE Function (FILE) to close the existing file. If you call OPEN on a file that is already open, a runtime error occurs.
•
CREATE(FileName): Use this function to create and open a file. Be sure to set the WRITEMODE, the TEXTMODE, and QUERYREPLACE before creating a file. FileName is the full path name of the file. If CREATE is used as a statement (without using the return value) and the file indicated by FileName cannot be created (for example, the path does not exist), a run-time error occurs. If CREATE is used as an expression (using the return value) and the file indicated by FileName cannot be created, CREATE returns FALSE. But if the file is created, it is opened and CREATE returns TRUE. If the file already exists, it is cleared and opened. Whether the user is warned about this or not depends on the parameter to the QUERYREPLACE method called before calling CREATE. If you are running the RoleTailored client and you call CREATE on a file variable that refers to an open file, the function will not automatically close the existing file and create the new file. You must explicitly call the CLOSE Function (FILE) to close the existing file. Otherwise, a runtime error occurs. If you are running the Classic client and you call CREATE on a file variable that refers to an open file, the function will CLOSE the existing file and CREATE the new file. A runtime error does not occur.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces •
CLOSE: Use this function to close access to the file through this file variable. After CLOSE is called, the file variable cannot be used again to access a file unless it is reopened or recreated. If CLOSE is called and the file is not open, a run-time error occurs.
Methods of Reading Files There are two methods for reading or writing data in external files. The method is set using the previously described TEXTMODE method. There are two possible settings: •
TEXT (TEXTMODE=TRUE): Each file access reads or writes a line of text. The variable used can be of any type and it is converted to (if writing) or from (if reading) text during the processing.
•
BINARY (TEXTMODE=FALSE): Each file access reads or writes a single variable. The variable is read or written in its internal format. For example, text is written as a null terminated string whose length is the defined length of the Text variable. Since TEXTMODE is limited to one variable per line, note that the file cannot contain more than 250 characters per line. Binary mode does not have this limitation, since it does not have lines. However, the internal format can only be read if it is written in the same manner from Microsoft Dynamics NAV. The one variable type that is useful when using Binary mode is the Char type, which enables reading or writing one byte at a time.
Reading or Writing Data in External Files The following methods are used to read or write data in external files (once the file variable is open): •
[Read :=] READ(variable): Read a variable from the file. The optional return value indicates the number of bytes read. In Text mode, a line of text is read and the text is evaluated into the variable passed in as a parameter. In Binary mode, the variable is read in its internal format, and thus the number of bytes read depends on the size of the variable.
•
WRITE(variable): Write a variable to the file. In Text mode, the variable is formatted to text and written out as a line of text. In Binary mode, the variable is written using its internal format.
E-mail Confirmation E-mail confirmation provides the ability to send e-mail from Microsoft Dynamics NAV in an automated fashion. A solution for providing e-mail confirmation to seminar participants is designed and implemented for the Seminar Management system.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Solution Analysis The client’s functional requirements in Chapter 1 describe e-mail confirmation as: "The solution must allow e-mail notification to be sent to the Customer's participants in several situations, such as registration confirmation." This feature enables seminar managers to send e-mail confirmations to all participants registered for a seminar, stating that that they are registered, and to remind them of the starting date.
Solution Design Before attempting to implement a solution, it is vital to create a design, or plan. In this case, GUI changes are necessary to make the feature accessible to seminar managers, and functions are needed to execute the e-mail confirmation logic.
GUI Design E-mail confirmation will be available from the Seminar Registration page. This requires the Seminar Registration page to be modified by adding a new Functions section menu to the Actions menu as shown in the following image.
FIGURE 9.1 THE SEMINAR REGISTRATION PAGE (123456710)
9-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces The e-mail confirmation functionality will also be available from the Seminar Registration List page. Therefore, a Functions section is added to the Actions menu of this list page as well. This can be seen in the following image.
FIGURE 9.2 THE SEMINAR REGISTRATION LIST PAGE (123456713)
Functional Design To send e-mails, use an Automation variable with the subtype of an automation server class that can create and send e-mails. This automation server is the Navision Attain ApplicationHandler, and the class used is MAPIHandler. The implementation requires a new codeunit that can create and send the e-mails.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 9.1 - Creating E-mail Confirmations There are many instances where it is good practice to have email communications with clients or other contacts. The extent to which this process can be automated reduces the effort involved in generating such communications. Scenario Before the scheduled date of a seminar, it is good practice to send out registration confirmation emails to all the registrants. There are multiple ways to accomplish sending out emails in Microsoft Dynamics NAV. This time it will be done using an Automation control, MAPIHandler.
Challenge Yourself! Create a codeunit that uses MAPIHandler to send out emails to seminar registrants. Allow the user to specify the contents of the email and to whom it will be sent. Add the new email function to an action menu for easy access.
Step by Step Begin by creating a codeunit to create the e-mail: 1. Create a codeunit called Seminar Mail (123456705). 2. Declare global record variables for the Seminar Registration Header, Seminar Registration Line, Customer, and Contact tables. 3. Declare an Integer type variable called NumberOfErrors for storing the number of errors. 4. Declare a Boolean type variable called MailSent for storing the result of the MAPIHandler's Send command. 5. Declare a variable called MAPIHandler, of type Automation and of subtype Navision Attain ApplicationHandler and of class MAPIHandler. 6. Define text constants for the different sections of the e-mail confirmation, including the subject line, the greeting, the confirmation sentence, and the signature. 7. Define a function called NewConfirmationMessage that has a parameter of a record variable for the Seminar Registration Line table, which is passed by reference. 8. Enter code in the function trigger so that the function performs the following tasks: o Creates an instance of the MAPIHandler (using the CREATE function).
9-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces o
o
Creates the e-mail message by assigning the appropriate elements of the message to the properties of the MAPIHandler variable. Assigns the ToName field using the Contact record, the CCName using the Customer record, and the Subject Uses the AddBodyText method of the MAPIHandler to create each line of the e-mail message.
NOTE: Rather than using Automation Controller and MAPIHandler, emails could be sent out using the SMTP Mail codeunit (Codeunit object 400). Compare the functions in the SMTP Codeunit to the properties and methods in the MAPIHandler Automation controller. To view all the properties and methods available in the MAPIHandler Automation controller, open the C/AL Symbol Menu by pressing F5 or clicking View, C/AL Symbol Menu, and locate the MAPIHandler variable in the left most column. o o
Sends the message using the Send method of the MAPIHandler. Uses the ErrorStatus property of the MAPIHandler to check the number of errors. If there are none, set the Confirmation Date of the Seminar Registration Line to today’s date.
9. Define a function called SendAllConfirmations with a parameter of a record variable for the Seminar Registration Header. 10. Enter code in the function trigger so that the function runs the NewConfirmationMessage function for each Seminar Registration Line associated with the Seminar Registration Header that passed to it. 11. With the code in place, the remaining step is to make the functionality available to the user. Add a new menu selection to the Seminar Registration page (123456710) as follows: Menu Button
Options
Comments
Functions
Send E-mail Confirmations
Runs code to Send E-mail Confirmations.
12. Enter code in the appropriate trigger so that when the user selects the Send E-mail Confirmations menu item, the program runs the SendAllConfirmations function. 13. Add a new menu selection to the Actions menu on the Seminar Registration List page (123456713) as follows: Menu Button
Options
Comments
Functions
Send E-mail Confirmations
Runs code to Send E-mail Confirmations.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 14. Enter code in the appropriate trigger so that when the user selects the Send E-mail Confirmations menu item, the program runs the SendAllConfirmations function.
Using an XMLport XMLports are used to export and import data from and to Microsoft Dynamics NAV. XMLports can be coded to work either with structured XML document files or, in Microsoft Dynamics NAV 2009, to work with text files. The Text file formats are often some variation on CSV or "comma delimited" formats. The XML data structure is an industry standard, used to communicate between different applications, including those from different vendors. It provides a common format which is widely used in networked data exchanges. Only a basic knowledge of XML is needed to design and work with XMLports. Design XMLports in the XMLport Designer, which is opened from the Object Designer.
XMLport Triggers There are three event triggers that execute for an XMLport object: •
OnInitXMLport: This trigger executes when the XMLport is loaded and before any table views and filters are set.
•
OnPreXMLport: This trigger executes after the table views and filters are set and before the XMLport is run.
•
OnPostXMLport: This trigger executes after all the data items in an XMLpost are processed.
There are also event triggers for every field in an XMLport which are dependent on whether the XMLport is importing or exporting. For more information on those triggers, consult the Microsoft Dynamics NAV 2009 Developer and IT Pro Help.
Solution Analysis The client's functional requirements for the Seminar Management system in Chapter 1 describe the need for a participant list in an XML format: "...the participant list for a seminar must be exportable as an XML file."
Solution Design Generating a Seminar Management participant list in XML can be accomplished using an XMLport.
9-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces GUI Design The following menu item must be added to the Partner Menu MenuSuite (80): Menu Type
Menu Name
Group
Comments
Item
Create XML List
Periodic Activities
Runs report 123456705 XML Sem. Reg.-Participant List.
Functional Design To implement this solution, it is necessary to understand the basics of how XMLports work. XMLports have three basic sections: •
A title, in this case, "Seminar Registration - Participant List."
•
Heading information, in this case, from the Seminar Registration Header including the No., Seminar Code, Seminar Name, Starting Date, Duration, Instructor Name, and Room Name fields.
•
Line information, in this case one for each registered participant from the Seminar Registration Line, including Customer No., Contact No., and Name fields.
The following table shows the basic sections that are necessary for this solution: Section
Sample Section
Title
<Seminar_Registration_-_Participant_List>
Heading for Heading information
<Seminar>
Heading information
REG0001 <Seminar_Code>Sem0002 <Seminar_Name>Solution Dev <Starting_Date>01.08.11 10 A Hill Room 1
Heading for Line information
<Participant>
Line information
10000 CT100210 Stephanie Bourne
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 9.2 - Creating the XML Sem. Reg. - Participant List XML formatted data has become a widely accepted standard for communicating data between systems. Scenario The Seminar Management system requires listings of registrations to be exported in an XML format to be input into another application. To accomplish this task, the XMLport tools will be used.
Challenge Yourself! Create the necessary object(s) to export Seminar registrant data into an XML formatted file. Add the new XML export function to an action menu for easy access.
Step by Step Begin by creating the XMLport: 1. Create a new XMLport called Sem. Reg.-XML Participant List (123456700). 2. Define the data items for the XMLport, using the previous Functional Design section as a reference for which tables to get information from. Add code to calculate the FlowFields so that the Instructor Name and Participant Name appear in the XML file. Now implement a way that the user can run this XMLport. To enable the user to select filters, create a new report. 3. Create a new Processing Only report called Sem. Reg.-XML Participant List (123456705). 4. This report has one data item, the Seminar Registration Header table. Set the name of this datatype to SEMREGHEADER. 5. Create global variables for TestOutStream (datatype Outstream) and TestFile (datatype File). 6. In the OnPreReport trigger, insert this code, substituting the file path: TestFile.CREATE('C:\XML_Part_List.XML') ; TestFile.CREATEOUTSTREAM(TestOutStream) ; XMLPORT.EXPORT(123456700,TestOutStream,SEMREGHEADER) ; TestFile.CLOSE ; MESSAGE('XML Completed') ;
9-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces 7. All that remains is to add the menu item to the Seminar main menu. Add the new menu item to the Periodic Activities folder in the Partner MenuSuite.
Sample XML Participant List The resulting XML participant list might look like this: - <Seminar_Registration_-_Participant_List> - <Seminar> REG00001 <Seminar_Code>SEM0002 <Seminar_Name>Solution Development <Starting_Date>01.08.01 10 Annette Hill Room 1 - <Participant> 10000 CT100140 David Hodgson - <Participant> 10000 CT100156 John Emory - <Participant> 10000 CT000001 Mindy Martin
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 - <Participant> 10000 CT100210 Stephanie Bourne
Summary This chapter used COM automation to send e-mail messages to seminar participants and an XMLPort was used to create an XML file of participants in a seminar. At this point in the course, the Seminar Management solution is complete. The next chapter addresses the deployment of custom solutions.
9-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces
Test Your Knowledge 1. In what two ways can COM objects be used in C/SIDE?
2. When a variable is used for an automation server, what data type is assigned to the variable?
3. What C/AL function is used to create an instance of an automation server class?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 4. In what situations are the file handling functions used?
5.
Ideally, where is code placed that uses automation?
6. What event triggers exist for XMLports?
9-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces 7. What is the purpose of using XML?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-19
C/SIDE Solution Development 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-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Interfaces
Solutions Test Your Knowledge 1. In what two ways can COM objects be used in C/SIDE? MODEL ANSWER: COM objects can be used in C/SIDE by using custom, non-visual, OCX controls and by using automation server objects. 2. When a variable is used for an automation server, what data type is assigned to the variable? MODEL ANSWER: The data type for automation server variables is "Automation." 3. What C/AL function is used to create an instance of an automation server class? MODEL ANSWER: To instantiate an automation type variable, the C/AL keyword CREATE is used. 4. In what situations are the file handling functions used? MODEL ANSWER: When data needs to be imported and that data needs to be parsed, character by character when imported. When there is a need to build output textual data character by character, and when the data to be imported or exported has a record length too long for Microsoft Dynamics NAV to handle internally. 5.
Ideally, where is code placed that uses automation? MODEL ANSWER: Code that uses automation is placed in separate codeunits. That way, other objects that call functionality using unregistered automation objects will compile.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 6. What event triggers exist for XMLports? MODEL ANSWER: OnInitXMLport OnPreXMLport OnPostXMLport 7. What is the purpose of using XML? MODEL ANSWER: To communicate with another system in a standard structured data format.
9-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services
CHAPTER 10: WEB SERVICES Objectives The objectives are: •
Aware of how Microsoft Dynamics® NAV supports Web services.
•
Evaluate the benefits of Web services over other integration options in Microsoft Dynamics NAV.
•
Understand how to expose codeunit and page objects as Web services.
•
Consume Web services using functions developed through Visual Studio and Infopath.
Introduction The World Wide Web Consortium (W3C), which is regarded by the industry as the keeper of Web standards (including XML and Web services), describes Web services as follows "Web services provide a standard means of interoperating between different software applications, running on a variety of platforms and/or frameworks. Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions thanks to the use of XML. They can be combined in a loosely coupled way in order to achieve complex operations. Programs providing simple services can interact with each other in order to deliver sophisticated added-value services." (source: http://www.w3.org/2002/ws/activity (http://www.w3.org/2002/ws/activity) "Web Services" as of January 2009) MSDN Online has the following description of XML Web services: "XML Web services are the fundamental building blocks in the move to distributed computing on the Internet. Open standards and the focus on communication and collaboration among people and applications have created an environment where XML Web services are becoming the platform for application integration. Applications are constructed using multiple XML Web services from various sources that work together regardless of where they reside or how they were implemented." (source: http://msdn.microsoft.com/en-us/library/ms996507.aspx (http://msdn.microsoft.com/en-us/library/ms996507.aspx) "XML Web Services Basics" Web Services Technical Articles as of January 2009)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Web services are a standardized way for independent software systems to communicate with one another over standard Internet protocols. XML is used to define the interface as well as the data that is exchanged by the interface. Web services architecture is designed to allow programs to communicate with each other that may be written in different languages or even on different platforms, in a language-independent, platform-independent manner. Different software manufacturers may have different implementations of Web services, and there may be minor differences in the way that their interfaces are developed. A few things, however, are common to most of these definitions: •
Functionality is exposed through a standard web protocol, such as HTTP or SOAP (Simple Object Access Protocol, an XML based protocol)
•
The interface is described by using a common Web services Description Language (WSDL), which uses XML.
•
Public Web services are registered with Universal Discovery Description and Integration (UUDI).
Microsoft Dynamics NAV 2009 allows business logic to be published as Web services, which makes integrating Microsoft Dynamics NAV with other systems much easier than previously. Instead of having to develop additional components to integrate with Microsoft Dynamics NAV business logic, it is now possible to publish entire codeunits and pages as Web pages. Implementation of the Web services capability requires use of the three tier configuration. To learn more about Web Services and Microsoft products, visit http://msdn.microsoft.com/en-us/library/ms996507.aspx for additional information.
Web Services Overview Web services use XML to describe machine-readable metadata. This metadata is used to describe the message interchange formats that a Web service supports, and the valid message exchange patterns of the Web service itself, as well as the capabilities and requirements of a service. Web Services Description Language (WSDL), an XML-based language for defining Web services, is used to express the interchange formats and message exchange patterns of the Web services. Many major software development environments, such as Microsoft Visual Studio, can be used to build applications that use Web services. Because Web services are XML based, Web services can be built across platforms and programming languages.
10-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services Web Services Architecture With Microsoft Dynamics NAV 2009 it is possible to publish codeunits and pages as Web services, providing access to internal business logic in a standard format, using standard protocols. External systems can read and write data on pages and call codeunits as defined by the common Web service protocols, with correct authentication and authorization. With the Web services that can be published with Microsoft Dynamics NAV 2009, it is possible to provide the same functionality to an external application that is used within the application. The credentials of the application used to consume a Web service in Microsoft Dynamics NAV 2009 must be set up with the proper permissions to access the information. 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 10.1 MICROSOFT DYNAMICS NAV 2009 THREE-TIER ARCHITECTURE
Microsoft Dynamics NAV Web Services There are several simple types of Web services that can be published by Microsoft Dynamics NAV. All Web services can run C/AL code and validation triggers.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The simplest Web service type uses the page object. By publishing a page object, Microsoft Dynamics NAV constructs a Web service that has a set of default database methods, such as Create, Read, Update and Delete operations. Publishing Pages as Web services provides indirect access to the validation triggers in the underlying tables. Another Web service type uses codeunits and the functions that are defined within those codeunits. Publishing a codeunit provides the functions in the codeunit as methods of 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. Pages and/or codeunits can be published as a Web service simply by inserting a reference to the page or codeunit into the Web service table, and marking it as a published Web service. They are immediately published and available for Web service requests over the network. It could not be simpler. The Microsoft Dynamics NAV Business Web Services server application is implemented as a Windows service that can simply be installed on the server. The complexity normally faced in manually setting up the framework, and managing the WSDL description is taken care of by this service. 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 configuration: •
Computer name that runs Microsoft Dynamics NAV Service: NAV_SRV_01
•
Web Service port: 7047
•
Microsoft Dynamics NAV 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_SRV_01:7047/DynamicsNAV/WS/CRONUS_International_ Ltd/Page/MyCustomer (http://nav_srv_01:7047/DynamicsNAV/WS/CRONUS_International _Ltd/Page/MyCustomer)
Microsoft Dynamics NAV manages Web service requests exactly like it handles requests from end-users within the Classic client or the RoleTailored client. 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.
10-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services This guarantees that the integrity of the Microsoft Dynamics NAV data is not compromised by using Web services. It also means code which validates data, or invokes business logic for systems using the Web services that are provided by Microsoft Dynamics NAV do not have to be replicated.
Writing C/AL Code for Web Services 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 created. The exception can be caught and handled, but the Web service task will not be completed. When writing code for Web services, avoid using any end-user confirmation dialog pages or message pages. On occasion, standard business logic includes some degree of user interaction. That must be avoided when the logic is published as a Web service. To detect such a situation, the GUIALLOWED function can be used, and then default responses can be implemented in the business logic. When code is executed from a Web service, this keyword is always set to FALSE, just as it is when code is executed from within the Microsoft Dynamics NAV Application Server (NAS). For instance, standard business logic might include a confirmation like this: OK := CONFIRM(‘Do you wish to continue?’);
If this functionality were to be published as a Web service, it is extended as follows: IF GUIALLOWED THEN OK := CONFIRM(‘Do you wish to continue?’) ELSE OK := TRUE;
When GUIALLOWED equals TRUE, meaning a user is running this code from the Classic client or the RoleTailored client, the user has a choice. If GUIALLOWED equals FALSE, meaning the code is executed as a Web service or by NAS, a default value is assumed for the CONFIRM function.
Web Service Opportunities Integration with other systems and communicating with different applications other than Microsoft Dynamics NAV is often a challenge. In many cases, customers need to integrate their Microsoft Dynamics NAV system with other systems in use within their organization. In some instances, they may have a requirement to exchange data with entities outside their organization, entities which may use another system or even a different platform and operating system.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Historical Integration Option Historically, Microsoft Dynamics NAV offers some integration possibilities by using the following technologies: •
C/Front
•
C/ODBC
•
OCX
•
Automation
•
NAV Application Server (NAS
These integration options have their own pros and cons, and choosing the best technology is case dependent. With the release of Microsoft Dynamics NAV 2009, Web services have been added to provide a new method of integrating with the system. Because Web services use industry standard protocols and technologies, there are many more possibilities. As a developer in Microsoft Dynamics NAV, it is very important to understand Web services. It is intended to be the new basis for cooperative efforts with developers from other technologies. To be able to use Web service properties in the right context will be a very important and useful skill.
Suitable Candidates for Web Services Web services are suited for communication across platforms and programming languages. Microsoft Dynamics NAV 2009 makes is easy to integrate with other systems and benefit from the flexibility that Web services offers. The following are candidates for Web services: •
Solutions to execute business logic or read data from Microsoft Dynamics NAV.
•
Solutions to write data to Microsoft Dynamics NAV and use the system to validate the data with the existing business logic.
•
Solutions to extend Microsoft Dynamics NAV with additional information (such as: customer information, exchange rates, or product information), and have that extension be accessed from other systems.
Creating, Exposing and Consuming Web Services Microsoft Dynamics NAV supports page objects, codeunits, and XMLport objects passed as parameters in a codeunit function to be published as Web services.
10-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services Reusable with Graphic An example of the usage of Web services in Microsoft Dynamics NAV is publishing a Web service that lists all customers and has that Web service immediately available for authorized requests over the network. Web services allow for easy communication and data exchange in a secured environment. The first labs in this chapter will look at very simple Web services, by reviewing how pages and codeunits can be published as Web services, and by creating a few simple console applications to consume these Web services.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 10.1 - Creating a Web Service Web services provide a new, industry standard way of providing access to Microsoft Dynamics NAV data and the associated processes. It is logical to expect that in the future, seminar registrations will be handled at some level via Internet access. Because Web services is a new capability, some experimentation is required to learn more about how to expose Web services so they may be used by an external application. Scenario In this lab, you will learn how to: •
Register a codeunit Web service.
•
Register a page Web service.
•
Publish the Web services.
The following steps show how to create a simple codeunit, with a function that converts an input string to all upper case characters.
Step by Step In the Microsoft Dynamics NAV Classic Client: 1. 2. 3. 4. 5.
Click Tools > Object Designer. The Object Designer opens. Click the Codeunit button to pen 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. 7. In the Parameters tab, enter the following: o Name: InputString o DataType: Text o Length: 250 8. Click the Return Value tab, and enter 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:
10-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services OutputString := UPPERCASE(InputString);
11. Save the codeunit by clicking File > Save As. The Save As dialog box opens. 12. Enter 123456710 in the ID and "Capitalize" in the Name and then click OK. The codeunit now looks like the following image.
FIGURE 10.2 THE CAPITALIZE CODEUNIT
13. Close the C/AL editor. 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: 14. Click the Form button to open the Form list. 15. Select form 810, Web Services and then click Run. The Web Services form opens. 16. Type the lines as shown in the following table. The first line registers the codeunit Web service that is created in the previous steps. The second line registers a page Web service, the Customer page. Object Type
Object ID
Service Name
Codeunit
92010
CapitalizeCU
Page
21
CustomerPage
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 17. Check the Published check box on both lines to publish the Web services. The Web Services form now looks like the following image:
FIGURE 10.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. 18. Close the Web Services form. Microsoft Dynamics NAV Web Services generate and publish the WSDL automatically on the Server. The following steps show how to browse to the WSDL document to ensure the Web services are available. 19. Start Internet Explorer. 20. In the Address bar, enter 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 name is case sensitive. The example used "localhost" instead of the computer name.
10-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 21. The page lists the Web services registered and published in previous steps.
FIGURE 10.4 THE WEB SERVICES LISTED IN INTERNET EXPLORER
22. Close Internet Explorer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 10.2 - Create a Console Application to Consume the Codeunit Web Service Now that Web service functions have been published (aka “exposed”), the next step is to create an application to use (aka “consume”) that published service in an external application. Scenario In this lab you will learn to create a console application to consume the Capitalize codeunit Web service. The following steps show how to create a console application in Visual Studio to consume the codeunit Web service.
Step by Step 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. Enter "UseCapitalizeCU" as the Name of the console application. 5. Click OK. Visual Studio now generates the default files and references that make up the UseCapitalizeCU project, including a code module with the proper name space and general construct to enter the C# code. To be able to use the published Web service in C# code, the Web service must be added as a Web reference into the project in Visual Studio: 6. In the Solution Explorer, right-click the References node in the project and then click Add Web Reference. The Add Web Reference window opens. NOTE: Adding a Web Reference directly from the References node in the object explorer is a function of the .NET framework version 2.0. Visual Studio 2008 is installed with a higher version of the .NET framework (by default), and this selection is not available directly from the Reference node. If this is the case, select "Service Reference" and then click the "Add Web Reference" button in the Service Reference Settings window. This will open the same dialog box that can be used to define the Web reference. 7. Enter the following in the URL bar: http://localhost:7047/DynamicsNAV/WS/CRONUS_International_L td/Services
NOTE: This address is the same as that address used when checking the WSDL by using Internet Explorer.
10-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 8. Click GO. The CapitalizeCU service is displayed together with other services that are available.
FIGURE 10.5 THE ADD WEB REFERENCE WINDOW
9. Click View Service for the CapitalizeCU service and then click Add Reference.
FIGURE 10.6 THE CAPITALIZECU WEB SERVICE DESCRIPTION
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The namespace and the main constructs for the console application are created, and the proper reference to the Web service is added to the project. What remains is to write the code that consumes the Web service. The following steps show how to write C# code to consume the Web service. For detailed information about C# syntax, refer to the proper documentation, which is available from the online help system in Visual Studio, as well as many references on the Internet, such as MSDN online and other online communities. NOTE: Many people are working on Web service projects who may have run into similar problems, and often offer to share their solutions in online communities. Online communities should be used since they are excellent resources for peer support. 10. Find the program.cs tab. If it is not displayed in the code section, it can be opened by double-clicking it in the project explorer. In the UseCapitalizeCU namespace above the line where the Program class starts, add the Web reference, by typing the following: using localhost; // using the web reference
11. In the Main function, write the code that consumes the Web service: // Create a new instance of the service CapitalizeCU ws = new CapitalizeCU(); // Authenticating against Microsoft Dynamics NAV ws.UseDefaultCredentials = true; // Declare the variables to use string InputString =""; string OutputString =""; Console.WriteLine("Enter a lowercase sentence, and press [ENTER]"); InputString = Console.ReadLine(); // Call the codeunit Web service OutputString = ws.Capitalize(InputString); // Write output to the screen Console.WriteLine("Result: {0}", OutputString); // Keep the console window up until you press ENTER Console.ReadLine();
10-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 12. Click File, Save All to save all the changes in the project.
FIGURE 10.7 THE CODE IN VISUAL STUDIO
13. Press F5 to run the application. The console window opens. 14. Write something with lower case characters, such as: "this is a lowercase sentence." 15. Press ENTER. The console application now looks like the following image:
FIGURE 10.8 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.' 16. Press ENTER to close the console window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Page Web Services When a page object is published as a Web service, it exposes a number of very familiar standard methods. These methods are the basic database operations (Create, Read, Update and Delete) for the page’s source table. They correspond to familiar table triggers which fire when these database operations are executed. Page Web services enable quick access to standard Microsoft Dynamics NAV business logic that is contained within the page object, and indirectly, also the business logic that is implemented in the source table. •
The Create method accepts an XML document that represents a table record as a parameter, and returns the record after it is finished. As the record is inserted into the table, the code in the OnInsert trigger of the table is executed, invoking exactly the same processing logic that is invoked by either the Classic client or the RoleTailored client.
•
The Update method accepts a record for the underlying table as a parameter and returns the modified record. As the record is modified, the code in the OnModify trigger of the table is executed.
•
The Delete method takes the key value of the record as a parameter, and returns TRUE or FALSE. It executes the OnDelete code of the underlying table.
•
The Read method accepts the primary key of the table as a parameter, and returns the record. This method is comparable to the GET method in C/AL. The ReadMultiple method takes a number of optional parameters, with the filter as the most important one, and it returns a list of records. This method is comparable to the FINDSET method in C/AL.
In addition to the standard database operations, page Web services also expose additional functionality, such as access to individual fields, and metadata that describe these fields. For more detailed information, please refer to the Microsoft Dynamics NAV Developer and IT Pro Help, which has extensive information about Web services.
10-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services
Lab 10.3 - Create a Console Application to Consume the Seminar Card Page Web Service Codeunits published as a Web service provide access to all of the functions in the codeunit. Pages published as a Web service provide access to a set of functions that in turn access table data. Such accesses are controlled by the data validation rules that are built into the target table. The next step is to create an external application to consume Web services exposed by means of a published page. Scenario In Lab 10.1, two Web services were exposed and published. Lab 10.2 shows how to create a console application to consume the codeunit Web service. This lab shows how to create a console application to consume the page Web service. The application uses the standard database operation methods.
Step by Step 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. Enter "UseSeminarPage" as the Name. 4. Click OK. The UseSeminarPage project initiates with default files and references, and the placeholder for the C# code that will be added later. The next step is to add the page Web service published as "Seminar" as a Web reference into the project. Begin in Visual Studio.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 5. Refer to Lab 10.2 for detailed instructions on how to add a Web Reference to the console application. 6. Instead of using the CapitalizeCU service, click View Service for the Seminar service and then click Add Reference.
FIGURE 10.9 THE SEMINAR WEB SERVICE DESCRIPTION
The namespace and the code placeholders are generated, and the reference to the Seminar Web service is already added to the project. The following steps show how to write the C# code to consume the page Web service. In Visual Studio: 7. Find the Program.cs tab, or open it from the project explorer. In the UseSeminarPage namespace, above the line where the Program class starts, add the Web reference, by entering the following C# code: using localhost; // using the web reference
8. In the Main function, write the C# code that consumes the Web service: // Create instance of service and set credentials Seminar_Service ws = new Seminar_Service(); ws.UseDefaultCredentials = true; // Create instance of a Seminar and ask for the name Msg("Enter a name for the new Seminar and press [ENTER]"); Seminar MySeminar = new Seminar(); MySeminar.Name = Console.ReadLine(); // Insert Seminar ws.Create(ref MySeminar); PrintSeminar(MySeminar);
10-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services Msg("The Web service inserted a new Seminar. Press [ENTER] to continue."); Console.ReadLine(); // Create filter for searching for seminars List<Seminar_Filter> filter = new List<Seminar_Filter>(); Seminar_Filter nameFilter = new Seminar_Filter(); nameFilter.Field = Seminar_Fields.Name; nameFilter.Criteria =""; // no actual filter specified yet filter.Add(nameFilter); Msg("Seminar List after inserting the new Seminar"); PrintSeminarList(ws, filter); Console.ReadLine(); // Modify Seminar Msg("Enter a new name for the Seminar and press [ENTER]"); MySeminar.Name = Console.ReadLine(); ws.Update(ref MySeminar); PrintSeminar(MySeminar); Msg("The Web service modified the name of the new Seminar. Press [ENTER] to continue"); Console.ReadLine(); Msg("List after modifying the Seminar"); PrintSeminarList(ws, filter); Console.ReadLine(); // Delete Seminar ws.Delete(MySeminar.Key); Msg("List after deleting the Seminar"); PrintSeminarList(ws, filter); Console.ReadLine(); Msg("Press [ENTER] to exit program."); Console.ReadLine();
9. Note that the code contains calls to a number of functions which will need to be added following the Main function: static void PrintSeminarList(Seminar_Service service, List<Seminar_Filter> filter) { Msg("Printing Seminar List"); //Conduct the actual search Seminar[] list = service.ReadMultiple(filter.ToArray(), null, 100); foreach (Seminar s in list) { PrintSeminar(s); } Msg("End of List, press [ENTER] to continue"); } static void PrintSeminar(Seminar s) {
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Console.WriteLine("No: {0} Name: {1}", s.No, s.Name); } static void Msg(string msg) { Console.WriteLine(msg); }
10. Click File, Save All to save all the changes in the project. The C# code to consume the Seminar Web service is now complete. The next steps show how to test the console application. In Visual Studio: 11. Press F5 to run the application in debug mode. The console window opens, asking for the name of the new Seminar. Enter the name and press ENTER.
FIGURE 10.10 INSERT A NEW SEMINAR NAME
10-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 12. The application inserts a new Seminar record with the name that is just entered. Note that the next available number from the default Seminar No. Series is used as the primary key value of the new Seminar.
FIGURE 10.11 INSERT A NEW SEMINAR
13. Press ENTER to continue. The application prints a list of Seminars. Note that the new Seminar is listed.
FIGURE 10.12 SEMINAR LIST
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 14. Press ENTER to continue. Enter a new name for the Seminar and press ENTER again. The application modifies the new Seminar name to the name that is just entered.
FIGURE 10.13 MODIFY THE NEW SEMINAR NAME
15. Press ENTER to continue. The application prints the Seminar list after modification. Note that the Seminar's name has changed.
FIGURE 10.14 SEMINAR LIST AFTER MODIFICATION
10-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 16. Press ENTER to continue. The application deletes the new Seminar and prints a new list. Note that the new Seminar is no longer listed.
FIGURE 10.15 SEMINAR LIST AFTER DELETION
17. Press ENTER to close the console window. NOTE: When the console application is run again, it creates another new Seminar, verifying that the Web service uses standard Microsoft Dynamics NAV logic that creates the next number from the default numbering series.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 10.4 - Create an Infopath Form to Consume a New Page Web Service for Seminar Participants As with most tasks, there is more than one way to accomplish the task of consuming a page’s exposed Web services. A console application was using in Lab 10.3. Now an Infopath form will be used to consume a different page based Web service. Scenario This lab will create a new Web service that is based on page 123456711 – Seminar Registration Subpage, which shows records from the Seminar Registration Line table. This Web service will accept a filter for the Seminar Registration Number field, and returns a list of participants. The goal is to create a form in Infopath to consume the new Web service. This Microsoft® Office program can be used to test a Web service.
Step by Step In Microsoft Dynamics NAV: 1. Open page 123456711 - Seminar Registration Subpage. 2. Add a line to the repeater group of the "Seminar Registration No." field. This field will enable the Web service to be able to filter on this field. Ensure that the field cannot be modified on the page by a RoleTailored client user, by setting Visible, Enabled and Editable properties to FALSE. 3. Enter a comment in the Documentation trigger to document the change in the object. 4. Save and close the object. This page is now ready to be published as a Web service. 5. Open Form 810 - Web Services. 6. Enter a new line for Page 123456711, and enter SeminarParticipant as its Service Name. 7. Check the Published field. The Web service is now published, and ready to be consumed. To ensure that the Web service is available, open a Web browser and type in the following URL: http://localhost:7047/DynamicsNAV/WS/CRONUS_International_L td/Page/SeminarParticipant
The Web service's WSDL is now displayed in the browser, indicating this Web service is available to be consumed.
10-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 8. Open Microsoft Office Infopath 2007 from the Microsoft Office menu. When Infopath opens, it displays the Getting Started wizard. If this does not display, open the wizard by selecting Fill Out a Form from the File menu.
FIGURE 10.16 GETTING STARTED IN INFOPATH
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 9. There is no existing template that meets the requirement. Click Design a Form Template on the left-hand side of the Getting Started wizard. This opens a dialog called Design a Form Template. 10. Click the Web Service icon and then click OK. This will start the Data Connection Wizard.
FIGURE 10.17 SELECT WEB SERVICE
11. Select Receive data, and then click Next. 12. Enter the URL for the SeminarParticipant Web service and click Next. http://localhost:7047/DynamicsNAV/WS/CRONUS_International_L td/Page/SeminarParticipant
10-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services Infopath will now connect to the Web service and retrieve the available methods for selection, as shown in the following image.
FIGURE 10.18 SELECT WEB SERVICE METHOD IN INFOPATH
13. Select ReadMultiple, and then click Next. 14. Accept Main Query as the name for the data connection, and then click Finish.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Infopath now has sufficient information to create a form based on the Web service. By default, Infopath will display a heading area at the top of the page, a box for query fields, a button called Run Query, and a box for the results with the data connection on the right-hand side. The following image shows the default empty form in Infopath.
FIGURE 10.19 DEFAULT EMPTY FORM IN INFOPATH
15. Click the title area and enter Seminar Participant List. 16. Expand the queryFields node, so that everything in this node is visible. Notice that some of the selections have a red asterisk, which means these elements are mandatory elements, and they will need to be entered into the query section to the left. 17. Drag the following fields from queryFields node into the box labeled Drag query fields here: o Field - When this field is dropped into the query area, a dropdown list will appear. Select Drop-Down List Box (Repeating). The user can enter filter criteria for any field that is available in the Web service. o Criteria - This will provide an area for the user to enter filter criteria for the selected field. o setSize - This is a mandatory element and sets the maximum number of records that is returned by the Web service. Fields from the dataFields node can be dragged into the results box. By default this will put fields in a single display structure. The requirement is to display a list of participants, so now create a list box to display the records. 18. Click the box labeled Drag data fields here.
10-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 19. From the Insert menu, select Repeating Table. This will start a new wizard that will help bind data to the repeating table. 20. Expand all in the dataFields node. Notice that the actual fields from the Seminar Registration Line table are available as elements of a node called SeminarPartcipant, which is the name entered for the new Web service. 21. Select SeminarParticipant, and then click Next, as shown in the following image.
FIGURE 10.20 SELECT SEMINARPARTICIPANT
22. In the next form, select the required fields and then click Finish. Be sure the following fields are selected: o Bill_to_Customer_No o Participant_Contact_No o Paticipant_Name o Register_Date
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-29
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 o o
Confirmation_Date Registered
FIGURE 10.21 SELECT FIELDS
After clicking Finish, Infopath creates the repeating table with all the selected fields, as shown in the following image. The form is now ready to run and consume the Web service.
FIGURE 10.22 FINISHED INFOPATH FORM DESIGN
23. Preview the form by using one of the following methods: o Click the Preview button in the toolbar o Select Preview and then Form from the File menu o Press Ctrl+Shift+B
10-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services When the form starts in preview mode, the system may display a warning message that the network connection is not available. Select Try to Connect and the form will display.
FIGURE 10.23 NETWORK CONNECTION WARNING
24. Select the Seminar_Registration_No field from the drop-down list (this was the field added to the Seminar Registration Subpage earlier in this Lab). 25. Enter a valid Seminar Registration No. into the Criteria text box. When an invalid value is entered into the Criteria textbox, Infopath will return an error message saying Infopath cannot run the specified query. 26. Enter a numeric value into the Set Size textbox. This is a mandatory field (meaning that Infopath will display an error message if no value is entered), and signifies the maximum number of records that are returned. 27. Click the Run Query button. Infopath will immediately display a security notice, as shown in the following image.
FIGURE 10.24 SECURITY NOTICE
28. Click Yes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-31
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Infopath will now connect to the Web service and retrieve any participants that are registered for the Seminar Registration No. that were entered into the Criteria box. The following image shows the form with possible values.
FIGURE 10.25 INFOPATH FORM IN RUNTIME
NOTE: This lab shows how to create a very simple form in Infopath to consume a Web service. Infopath forms can be used in other applications, such as SharePoint. A set of Infopath forms can be created to consume a variety of Web services, and those forms can be made available on the SharePoint Intranet site.
10-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services
Summary This chapter discussed the following: •
Web service capabilities in Microsoft Dynamics NAV 2009 as a new integration option.
•
Some benefits of Web services.
•
A description of how Web services are supported in Microsoft Dynamics NAV 2009.
•
How to create a simple console application in Visual Studio to consume a Web service.
•
How to create a simple form in Microsoft Office Infopath to consume a Web service.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-33
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. What are Web services?
2. What is the common language called that describes Web services?
3. Which two object types in Microsoft Dynamics NAV can be published as Web services?
10-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services 4. How are Microsoft Dynamics NAV objects published as a Web service?
5. Which general database operations are provided by page Web services?
6. Name two technologies that can be used to consume Web services?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-35
C/SIDE Solution Development 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-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Web Services
Solutions Test Your Knowledge 1. What are Web services? MODEL ANSWER: Web services are a standardized way for independent software systems to communicate with each other over standard Internet protocols. 2. What is the common language called that describes Web services? MODEL ANSWER: Web Services Description Language, or WSDL 3. Which two object types in Microsoft Dynamics NAV can be published as Web services? MODEL ANSWER: Pages and Codeunits 4. How are Microsoft Dynamics NAV objects published as a Web service? MODEL ANSWER: By entering a reference to them in the Web Services form, and putting a checkmark into the Published field. 5. Which general database operations are provided by page Web services? MODEL ANSWER: Create, Read, Update and Delete 6. Name two technologies that can be used to consume Web services? MODEL ANSWER: Microsoft Visual Studio and Microsoft Office Infopath
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-37
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
10-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server
CHAPTER 11: OPTIMIZING FOR SQL SERVER Objectives The objectives are •
Distinguish between the two database options available in Microsoft Dynamics® NAV 2009.
•
Comprehend the advantages of both the Classic Database Server and the SQL Server for Microsoft Dynamics NAV 2009.
•
Work with and store tables and indexes.
•
Use collation options and descriptions.
•
Understand the SQL Server Data Replication process of distributing data.
•
Know backup options available and best practices for backup.
•
Introduction to SQL Server Query Optimizer.
•
Understand the areas within Microsoft Dynamics NAV that are to be optimized.
•
Understand how the Microsoft Dynamics® NDBCS driver allows the Microsoft Dynamics NAV clients to communicate with SQL Server.
•
Understand the value of optimizing cursors to maximize performance.
•
Understand the performance impact of locking, blocking and deadlocks.
•
Understand how SIFT data is stored in SQL Server.
Introduction There are two server options to choose from when using Microsoft Dynamics NAV: the “classic” or “native” Database Server, and Microsoft SQL Server. Each has advantages and disadvantages. This chapter covers some of the differences between the two, and discusses Microsoft Dynamics NAV with Microsoft SQL Server in more detail. Microsoft Dynamics NAV with Microsoft SQL Server option is the required database option for installations that use the Microsoft Dynamics NAV RoleTailored client and/or the three tier operating mode for Web services.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Classic Database Server for Microsoft Dynamics NAV The Classic Database Server can be characterized as an Indexed Sequential Access Method (ISAM) server. The data is stored in B+ tree structures, with the primary key used to store the data physically on a disk and the secondary keys used to find a range of records and point to the data location based on the primary key. The Classic Database Server does not provide advanced data retrieval mechanisms -- it is necessary to specify which index is to be used, or the data is retrieved by scanning the primary key. There is no read-ahead mechanism (apart from the backup system). Records are sent to the client one by one, while commands are sent to the server are sent in batches to reduce network traffic. There are a very limited number of commands executed at the server level (MODIFYALL for example), so virtually all the data manipulation is done at the client level. The Classic Database Server supports explicit and implicit record locking. Implicit locking takes place when a modification of a record is performed on a table, at which time the Microsoft Dynamics NAV Server issues a table-lock, which it holds until the transaction is complete. This sometimes compromises concurrency. However, there are two important and advantageous features built into the Classic Database Server: •
SumIndexField Technology (SIFT)
•
Data versioning
SIFT is designed to improve performance when carrying out activities like calculating customer balances. In traditional database systems this operation involves a series of database calls and calculations. SIFT makes calculating sums for numeric table columns extremely fast, even in tables that contain thousands of records, because the SIFT data is stored in the indexes. Therefore, the read operation is minimized. Data versioning is designed to insure that reading operations can be performed in a consistent manner. For example, when a Balance Sheet is printed, it will balance without the need to issue locks on the G/L Entry table. Conceptually this works as though the server creates a snapshot of the data. During a data update, the modified data is kept private until a commit appears, and then the new data is made public, with a new version number. Data versioning allows optimistic concurrency, which can improve performance.
11-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server
SQL Server for Microsoft Dynamics NAV SQL Server is a comprehensive database platform providing enterprise-class data management with integrated business intelligence (BI) tools. SQL Server can be characterized as a set-based engine. This means that SQL Server is very efficient when retrieving a set of records from a table, but less so when records are accessed one at a time. Access to SQL Server from Microsoft Dynamics NAV is accomplished with the Microsoft Dynamics NDBCS driver, which is discussed later in this chapter. When SQL Server receives a query (in the form of a T-SQL statement), it uses the SQL Query Optimizer to create and execute the query. The Query Optimizer evaluates the query and makes decisions about how to execute the query, in what is known as the execution plan. For example, it decides which index to use, whether to use parallel execution, and so forth. Query Optimizer assumes that the client generates queries according to its own logic, and that these queries are not optimized for SQL Server. The primary criteria that Query Optimizer uses to decide which execution plan to use is the performance cost of executing the query. SQL Server stores data in B+ tree structures. One index is used to store the data physically on a disk, and other indexes are used to find a range and point to the data in the main index. This main index is called the Clustered Index. On SQL Server, any index can be defined as the main (clustered) index, but on the Classic Database Server this is always the primary key of the table. Unlike the Classic Database Server, SQL Server can do server-side processing, but – for the most part – Microsoft Dynamics NAV does not use this ability. Microsoft Dynamics NAV uses the same strategy for database access as it does with the Classic Database Server, so a limited number of commands are executed on a server-side basis (such as DELETEALL). Both Microsoft Dynamics NAV clients retrieve data record by record. Because SQL Server is set-based, it does not provide a fast way to do this retrieval. SQL Server uses mechanism called cursors for record-level access. Compared to retrieving sets of records, however, cursors are very expensive. How to reduce this overhead where possible is discussed later in this chapter. SIFT was originally implemented on SQL Server by using extra summary tables called SIFT Tables, that were maintained through table triggers directly in the table definitions on SQL Server. When an update was performed on a table containing SIFT indexes, a series of additional updates were necessary to update the associated SIFT tables. This imposed an extra performance penalty – one that grew as the number of SIFT indexes on a table increased. In Microsoft Dynamics NAV Version 5.0 Service Pack 1, Microsoft replaced SIFT tables with V-SIFT, which are indexed views. This chapter will discuss both mechanisms. Microsoft Dynamics NAV developers will likely be involved with older versions, where they may encounter performance issues related to the SIFT tables. It is important for Microsoft Dynamics NAV developers to know how SIFT tables worked prior to V5.0SP1 and how to troubleshoot performance issues that are related to these tables.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The SQL data versioning that is proprietary to the Classic Database Server is implemented as follows on SQL Server: Microsoft Dynamics NAV Classic adds the timestamp column to every table and reads data using the timestamp and the READUNCOMMITED isolation level. When a record is modified, the system reads the record again, only this time with the UPDLOCK isolation level, and modifies the data with a filter on the original timestamp. This prevents data that is read as “dirty” from being stored incorrectly. The downside is that this method allows users to view (and potentially modify) data processed by other users before their transaction is committed. To prevent this, a lock should be issued prior to the read. This ensures that the data is read with the READCOMMITED isolation level and also guarantees that no other user can modify the same set of data that is just read (and locked). The downside of locking is reduced concurrency, as some users may be blocked for the duration of the activity lock. On the plus side, SQL Server provides much more sophisticated locking options than does the Classic Database Server. This includes record-level locking, which vastly improves the efficiency of parallel operations performed on the same set of tables.
Representation of Microsoft Dynamics NAV Tables and Indexes in SQL Server By default, Microsoft Dynamics NAV provides unique data for each company in its database. On the Classic Database Server, the company name is stored as an invisible column in each physical table. On SQL Server, each company in the Classic database has its own copy of each table.
Reusable with Code Sample Each table in the Classic Database Server has a corresponding table in the SQL Server for every company in the database, with a name in the following format: Table Name Format
Example
$< Table Name>
CRONUS International Ltd_$G_L Entry
It is possible, however, to share data across companies, by setting the DataPerCompany table property to FALSE. In Microsoft Dynamics NAV terms, this is called data common to all companies. When the DataPerCompany property is turned off, there is just one table in SQL Server that is accessed from every company in the database. The naming convention for these common tables on SQL Server is the same, but without the "$" portion. Microsoft Dynamics NAV Classic uses naming conventions complying with SQL Server, such as not using special characters. Some special characters are allowed in the C/SIDE table designer, and they are translated to comply with the character set that is used on SQL Server.
11-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server The table will have a number of indexes, representing the keys that are designed and enabled in the C/SIDE table designer. The indexes have generic names in the following format: Index name format
Example
$
$1, $2, and so on
However, the primary key index uses the following name format: Primary key name format
Example
$< Table Name>$0
CRONUS International Ltd_$G_L Entry$0
Microsoft Dynamics NAV clusters the primary key index by default. Also, by default, Microsoft Dynamics NAV adds the remainder of the primary key to every secondary index, making the indexes unique. This conforms to the “best practices” defined for SQL Server. Developers can make additional changes to the way indexes are defined on SQL Server using the MaintainSQLIndex, SQLIndex, and Cluster properties on the keys defined in the C/SIDE table designer. To obtain a list of indexes and their definition in SQL Server, run the sp_helpindex stored procedure in a query window, as follows: sp_helpindex "CRONUS International Ltd_$G_L Entry" GO
The query outputs the index name, if the index is clustered or unique, whether or not there is a primary key constraint, and also the index keys defined in the index. There are some differences between the Classic Database Server and SQL Server terminology, as the following list describes: SQL Server Terminology
Classic Database Server Terminology
Primary key constraint
Primary key
Clustered index
No equivalent
Non-clustered index
Secondary key
Index key
Field in a key definition
SQL Server allows non-unique indexes; however, because SQL Server makes the indexes unique internally by adding extra index keys, it is a good practice to initially make them unique. Additionally, SQL Server allows a table not to have a clustered index. This is called a “heap” and can be used for archiving, because data is stored as it comes. However, heaps are not recommended for tables that are read, because reading from an unstructured source is too slow.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Collation Options SQL Server supports several collations. A collation encodes the rules governing the proper use of characters for either a language, such as Macedonian or Polish, or an alphabet, such as Latin1_General (the Latin alphabet used by Western European languages). Each SQL Server collation specifies three properties: •
The sort order to use for Unicode data types (nchar, nvarchar, and ntext). A sort order defines the sequence in which characters are sorted, and the way characters are evaluated in comparison operations.
•
The sort order to use for non-Unicode character data types (char, varchar, and text).
•
The code page used to store non-Unicode character data.
SQL Server collations can be specified at any level. Each instance of SQL Server has a default collation defined, which is the default collation for all objects in that instance of SQL Server, unless otherwise specified. Each database can have its own collation, which can be different than the default collation. Separate collations can even be specified for each column, variable or parameter. In Microsoft Dynamics NAV Classic, however, the collation can only be specified at the database level. It is a good practice to set the collation as generic as possible, for the language that is most common to the users. If all users speak the same language, set up SQL Server with a collation supporting that language. For example, if all users speak French, define a French collation on SQL Server. If the users speak multiple languages, define a collation that best supports the requirements of the various languages. For example, if the users generally speak western European languages, the Latin1_General collation is a good collation to use. Collation settings are defined in Microsoft Dynamics NAV Classic when a database is created, and can be changed afterward, with some limitations. The Windows Locale option can be used to match collation settings in instances of SQL Server 2000 and above. If different versions of SQL Server are used, collations should match settings that are compatible with the sort orders in earlier versions of SQL Server.
Windows Locale The default settings for Windows Locale (that is Windows collation) should only be changed if users’ installation of SQL Server must match the collation settings used by another instance of SQL Server, or must match the Windows Locale of another computer.
11-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server Collation Description Select the name of a specific Windows collation from the drop-down list. Note that when the Validate Code Page field is checked, only valid subsets of collations are available in the list based on the Windows Locale. For example, the following are subsets for the Latin1_General (1252) locale consecutively: •
Afrikaans, Basque, Catalan, Dutch, English, Faeroese, German, Indonesian, Italian, Portuguese
•
Danish, Norwegian
Sort Order Select Sort Order options to use with the collation selected - these are Binary, Case-sensitive and Accent-sensitive. Binary is the fastest sorting order, and is case-sensitive. If Binary is selected, the Case-sensitive and Accent-sensitive options are not available.
SQL Collations The SQL Collations option is used for compatibility with earlier versions of Microsoft SQL Server. Select this option to match settings compatible with SQL Server version 7.0, SQL Server version 6.5, or earlier.
SQL Server Data Replication Data replication is the process of distributing data from a source database to one or more destination databases. SQL Server provides data replication in a number of ways, with precise control over what data is replicated, and also when and how replication occurs. Some of the main reasons to use replication include: •
Load balancing: Replication enables users to disseminate data to a number of servers and then distribute the query load among those servers.
•
Offline processing: Users can manipulate data from their database on a machine that is not always connected to the network.
•
Redundancy: Replication enables developers to build a failover database server that is ready to pick up the processing load at a moment’s notice.
In any replication scenario, there are two main components: •
Publishers are database servers that make data available to other servers. Any given replication scheme has only one publisher.
•
Subscribers are database servers that are the destination servers for replication. There can be one or more subscribers in a replication scenario.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Microsoft SQL Server supports the following types of database replication: •
Snapshot replication. Each snapshot replaces the scheme and the data of the entire database. All subscribers have identical copies of the database, but it generates high levels of network traffic. Another disadvantage is that it only runs periodically, so that subscribers do not have current data.
•
Transactional replication. Selected transactions are marked for replication, and sent to subscribers separately. A benefit of transactional replication is that individual transactions can be replicated rather than the entire database. Transactional replication can occur continuously or periodically.
•
Merge replication. In this scenario, subscribers are allowed to make changes to the data, such as in offline copies of a database. Merge replication does not use distributed transactions, and therefore, transactional consistency cannot be guaranteed.
Data Replication for Microsoft Dynamics NAV Although SQL Server provides very advanced options when it comes to replication, not all of those options are suitable for Microsoft Dynamics NAV databases. In general, SQL Server replication should only be used when subscribers are used for reporting purposes or for failovers, so snapshot or transactional replication could be used for Microsoft Dynamics NAV databases. Unless it is limited to staging tables for integration purposes, merge replication is not recommended for Microsoft Dynamics NAV databases, because transactional integrity cannot be guaranteed. Another issue that affects replicated databases is that under some circumstances, the replication mechanism changes the TimeStamp column in the Microsoft Dynamics NAV tables to GUIDs on the replicated tables, making the database unusable by Microsoft Dynamics NAV. Additionally, developers must not use replication on SIFT tables, as these are maintained by table triggers. Therefore, developers should consider log shipping before committing to a replication strategy for resilience reasons. If developers do use replication, they should ensure that it is properly tested for functionality and performance impact. There is more overhead if developers run replication on their server, so the subsystems must be sized accordingly. To summarize, replication should be used sparingly with Microsoft Dynamics NAV databases, and only if there is no other mechanism to distribute and/or share data, such as log shipping, using views, using DTS/SSIS (SQL Server Integration Services), dataports, and so on.
11-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server
Backup Options There are various backup options with Microsoft Dynamics NAV on SQL Server. While the Microsoft Dynamics NAV client side backup option still exists (manually doing a backup through Tools, Backup), there are more elegant tools in SQL Server. The Microsoft Dynamics NAV backup and restore functionality remains for migration tasks such as users wanting to move data from one server with one collation into a different server with non-compatible collation, or for example if users want to use multiple database files and spread the data into those while restoring the Microsoft Dynamics NAV backup. Note that restoring the Microsoft Dynamics NAV backup is fully logged. Because it is considered to be one single transaction, it requires a massive amount of space in the log file of at least two to three times the size of the combined data files. SQL Server itself offers a number of options for disaster recovery. To start with, users can choose what recovery model the database will be using, either Simple or Full. Bulk-Logged is another option, but it is rarely used and is similar to Full, because only bulk operations logs are simplified. After choosing the recovery model, developers start planning their backup strategies using full, differential, and log backups, or a combination of those.
Simple Recovery Model The simple recovery model uses the log file only to record open transactions. After committing the transaction to the database, the log space is reclaimed. The benefit is that the log file can be quite small and simpler, and therefore faster. The disadvantage is that in the case of a disaster, users can only recover transactions to the end of the previous backup. Then they have to redo all transactions again. When using Simple Recovery, the backup interval should be long enough to keep the backup overhead from affecting production work, yet short enough to prevent the loss of significant amounts of data.
Full Recovery Model The Full Recovery and Bulk-Logged Recovery models provide the greatest protection for data. These models rely on the transaction log to provide full recoverability and to prevent work loss in the broadest range of failure scenarios. The disadvantage is the size of the log file and amount of data logged; the advantage is that if users have a disaster, they can recover to any point of time, provided that the log itself is not damaged.
Full Backup and Restore Full database backup backs up the entire database, including the transaction log. When users restore this backup, they have a fully operational database from the time of the backup. This type of backup requires the most space.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Differential Backup and Restore In general, a differential backup includes the data that is modified since the most recent full database backup. Differential backups are used primarily in heavily used systems where a failed database must be brought back online quickly. Differential backups are smaller than full database backups; therefore, they have less of an effect on the system while they run.
Transaction Log Backup and Restore A transaction log backup includes all transactions from the transaction log since the most recent transaction log backup. A log file backup by itself cannot be used to restore a database. A log file is used after a database restore to recover the database to the point of the original failure, or to any specific point in time. Transaction log backups are not available when using the Simple recovery model.
Reducing Recovery Time Using full database backup, differential database backup, and transaction log backup together can reduce the amount of time it takes to restore a database back to any point in time after the database backup is created. In a typical backup procedure, full database backups are created at longer intervals, differential database backups at medium intervals, and transaction log backups at shorter intervals. An example is to create full database backups weekly, differential database backups one or more times per day, and transaction log backups every ten minutes. If a database needs to be recovered to the point of failure, such as due to a system failure, perform the following steps: 1. Back up the currently active transaction log. This operation fails if the transaction log is damaged. 2. Restore the most recent full database backup. 3. Restore the most recent differential backup that is created after the most recent full database backup is created. 4. Apply all transaction log backups, in sequence, created after the most recent differential backup is created, finishing with the transaction log backup created in Step 1. Note that if the active transaction log cannot be backed up, it is possible to restore the database only to the point when the last transaction log backup is created. Changes made to the database since the last transaction log backup are lost and must be redone manually.
11-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server Consider Customer Requirements Which recovery model to select and how to set up the backup strategy is determined by the customer’s preferences. It depends on the customer’s attitude toward data loss, as well as the available system resources. If the customer wants to minimize recent data loss, then it is necessary to select the full recovery model. In addition it might be necessary to set up a database backup plan that includes full backup as well as frequent differential and transaction log backups. Since this comes at a performance price, this also requires additional storage space. If the customer is willing to accept the loss of an entire day’s worth of transactions, as is the case in many Microsoft Dynamics NAV Classic implementations, then it might be better to select the simple recovery model, and only schedule less frequent full backups. Because SQL Server makes it easy to set a more comprehensive backup strategy, most customers will opt for the more comprehensive approach.
Practice Disaster Recovery Assume that the customer has set up a backup strategy that includes full backups, differential backups, as well as transaction log backups. Unless it is known how to restore a database from those backups, and the infrastructure is ready to replace the production database, they are completely meaningless. Whether the customer employs internal Information Technology (IT) staff, or has external consultants on call, it is important that both the staff and infrastructure are ready to react to disaster. Plan for a simulated system breakdown, and use the backup files to restore the production database, including client connectivity. These drills will ensure that the staff is well prepared to restore the production database when disasters happen for real.
SQL Server Query Optimizer Query Optimizer is the heart of SQL Server when making a decision on how to execute a query. SQL Server collects statistics about individual columns (singlecolumn statistics) or sets of columns (multi-column statistics). Statistics are used by the query optimizer to estimate the selectivity of expressions, and thus the size of intermediate and final query results. Good statistics allow the optimizer to accurately assess the cost of different query plans, and choose a high-quality plan. All information about a single statistics object is stored in several columns of a single row in the sysindexes table, and in a statistics binary large object (statblob) kept in an internal-only table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 SQL Server maintains some information at the table level. These are not part of a statistics object, but SQL Server uses them in some cases during query cost estimation. This data is stored at the table level: •
Number of rows in the table or index (rows column in sys.sysindexes)
•
Number of pages occupied by the table or index (dpages column in sys.sysindexes)
SQL Server collects the following statistics about table columns and stores them in a statistics object (statblob): •
Time the statistics are collected
•
Number of rows used to produce the histogram and density information (described hereafter)
•
Average key length
•
Single-column histogram, including the number of steps
A histogram is a set of up to 200 values of a given column. All or a sample of the values in a given column are sorted; the ordered sequence is divided into up to 199 intervals so that the most statistically significant information is captured. In general, these intervals are of nonequal size. Users can view the statistical information when they run the DBCC SHOW_STATISTICS command. For example, they can run it for index $6 in the Cust. Ledger Entry table, as follows: DBCC SHOW_STATISTICS ("CRONUS International Ltd_$Cust_ Ledger Entry","$6") GO
The result set has three sections, similar to the following:
11-12
Updated
Rows
Rows Sampled
Steps
Density
Average key length
Jun 14 2009 2:51PM
26046
26046
3
0.0
26.237772
All density
Average Length
Columns
0.33333334
4.0
Document Type
1.0416667E2
11.866083
Document Type, Customer No_
5.165289E-4
19.866083
Document Type, Customer No_, Posting Date
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server RANGE_HI_KEY
RANGE_ROWS
EQ_ROWS
DISTINCT_ RANGE_ ROWS
AVG_RANGE_ROWS
1
0.0
23689.0
0
0.0
2
0.0
10.0
0
0.0
3
0.0
2341.0
0
0.0
4
0.0
6.0
0
0.0
Imagine that a user is filtering on the "Document Type" column in the "Cust. Ledger Entry" table, for example looking for all "Credit Memo" type entries. The "Credit Memo" type entries have a value of "Document Type" equal to three. Microsoft Dynamics NAV issues a query similar to this: SELECT * FROM "CRONUS International Ltd_$Cust_ Ledger Entry" WHERE "Document Type" = 3 GO
The query optimizer analyzes usefulness of every index in the table so that the query is executed at minimal cost, minimizing first the cost of data retrieval, followed by costs of sorting, and so on. When analyzing this particular index (index $6) from the data retrieval aspect, the query optimizer makes the majority of its decisions based on the statistics in the following way. "Document Type" is filtered, but there are only three distinct values in the index (refer to the "All density" column in the preceding table) indicating that 0.3334 of the table is within the filtered set. Additionally, since the histogram exists on the "Document Type," it will look up the information (RANGE_HI_KEY = 3) and see that there are about 2341 rows in the set, indicating that 0.0898 of the table is within the filtered set (2341 rows out of a total of 26046 rows). Based on this, the query optimizer decides that there is no point in using this index to do this operation because it needs to load the index, scan the range, and look up the data in the clustered indexes to return the results. Since there is no other better way to read the data, it decides to do Clustered Index Scan instead. As a rule of thumb, if the selectivity is close and better than one percent, the index will be considered beneficial. Be careful with this simple rule, because operations such as SELECT TOP 1 (asking for the first record in a set) escalate the index benefit, and the index will probably be used.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Continuing this example, filtering on a more unique value makes the index help with selectivity, such as: SELECT * FROM "CRONUS International Ltd_$Cust_ Ledger Entry" WHERE "Document Type" = 4 GO
The query optimizer knows – in this example -- that only six out of 26046 records qualify (refer to the previous histogram or RANGE_HI_KEY = 4) and makes use of the index. It looks in the non-clustered index followed by the bookmark lookup to the clustered index to get the relevant records. SELECT * FROM "CRONUS International Ltd_$Cust_ Ledger Entry" WHERE "Document Type" = 4 GO
If users further filter on the next index key, like this: SELECT * FROM "CRONUS International Ltd_$Cust_ Ledger Entry" WHERE "Document Type" = 3 AND "Customer No_" = '10000' GO
The combined selectivity is used, and a plan is calculated, which may result in a decision to use this index. However, if users do not filter on an index key or use the <> (not equal operator) or use the OR operator, there is no way that SQL Server can combine the subqueries. Thus, this may result in bad behavior. For example: SELECT * FROM "CRONUS International Ltd_$Cust_ Ledger Entry" WHERE "Customer No_" = '10000' AND (("Document Type" = 2) OR ("Document Type" = 4)) GO
In this example, the query optimizer decides to use the index, doing a nonclustered index seek, but has to traverse the area of “Document Type” = 3. Because the set is read from beginning to end, it has a similar effect, as if the user did a table scan. Similarly, if the user leaves one of the index keys unfiltered, all the subtree index entries have to be scanned. There is one simple rule with regards to performance: "Scan is bad. Seek is good." Developers need to avoid scans as much as they can, ensuring that indexes are of a good selectivity and that the queries do not have scan-like behavior. 11-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server On the other side of the spectrum, is an index that is overly complex and designed to fully match the entire query, for example with eight index keys. It might be that if the index has only four index keys, SQL Server will have to scan a slightly larger set to provide the required several records, but at the extreme cost of having to maintain the composite index, delaying every modification in the table, because SQL Server has to update the index accordingly. In a majority of cases, users have to optimize the transaction speed. If users over-index the tables, then users have to pay a price in terms of performance. It might be that a specific report is slow when fewer composite indexes are used, but it is worth it, since processing (such as posting inventory) will be quicker. Additionally, if a relatively small set is to be ordered by a different column, it is not necessary for the index to fully support the sorting; SQL Server can efficiently sort small result sets quickly. The above demonstrates that the way that indexes are designed and used can severely impact SQL Server performance. Adhere to the following principles: •
Minimize the number of indexes for faster table updates.
•
Design indexes with index keys of good selectivity.
•
Put index keys with higher selectivity toward the beginning of an index.
•
Put index keys that are more likely to be filtered toward the beginning of an index.
•
If the filtered index keys point to approximately 50 records, there is no need to add extra index keys to support index selectivity or sorting; SQL Server returns the set sorted as desired.
•
It is better to use more composite indexes than a lot of simple indexes; in other words, it is better to "combine" index use rather than have many "specific" indexes.
•
There is no point of indexing "empty" (not used) columns, since that just creates an extra overhead for no benefit.
•
Ensure that users filter on unique values in indexes; otherwise SQL Server performs similarly to table scans.
•
Do not make "over selective" index keys. If users index on DateTime fields, for example, they will force creation of a unique index leaf in the index for each record in the table.
•
Put date fields toward the end of the index, since this is not always filtered. If an index is always filtered on a unique value, then it is a good index.
To determine whether an index is good, imagine a telephone book or list of personal details designed to find people by name and surname, or date of birth, or social security number. Compare to a phone book indexed by gender, for example. When it comes to designing indexes, choose those that support a high level of selectivity. Common sense applies.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Optimizing a Microsoft Dynamics NAV Application There are a number of areas where users need to focus when optimizing Microsoft Dynamics NAV applications. These areas are, in order of importance (based on the processing costs): •
SIFT
•
Indexes
•
Cursors
•
Locks
•
Suboptimum code
•
GUI
Optimizing SIFT Tables SIFT tables are used in Microsoft Dynamics NAV version 5.0 and older, to implement SIFT on the SQL Server, and store aggregate values for SumIndexFields for keys in the source tables. Starting with version 5.0 Service Pack 1, these SIFT tables are replaced by indexed views. Separate SIFT tables are no longer part of Microsoft Dynamics NAV on SQL Server. This discussion section is included because Microsoft Dynamics NAV developers are likely to run into issues concerning SIFT tables in implementations of older versions of Microsoft Dynamics NAV. The overhead of the separate SIFT tables is massive and should be carefully considered for activation. Microsoft Dynamics NAV by default activates the SIFT tables when users create a new index with SumIndexFields. Users should review all their existing SIFT indexes and decide if they really need to keep them activated. Users can de-activate the creation and maintenance of a SIFT table by using the MaintainSIFTIndex property in the Microsoft Dynamics NAV key designer. If they make the property false, and there is no other maintained SIFT index supporting the retrieval of the cumulative sum, Microsoft Dynamics NAV asks SQL Server to calculate the sum itself. For example, if users have a Sales Line table and put Amount in the SumIndexFields for the primary key (“Document Type, Document No., Line No.”), a new SIFT table “CRONUS International Ltd_$37$0” is created and maintained. When a CALCSUM is used to display a FlowField in Microsoft Dynamics NAV showing the sum of all Sales Lines for a specific Sales Header (Order ORD-980001), the resulting query looks like the following: SELECT SUM(s29) FROM "CRONUS International Ltd_$37$0" WHERE "bucket" = 2 AND "f1" = 1 AND "f3" = 'ORD-980001'
11-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server If users disable the SIFT table by clearing the MaintainSIFTIndex checkbox, Microsoft Dynamics NAV still works, and the resulting query looks like the following: SELECT SUM("Amount") FROM "CRONUS International Ltd_$Sales Line" WHERE "Document Type" = 1 AND "Document No_" = 'ORD-980001'
This is a very light load on CPU overhead compared to the massive costs of maintaining the SIFT table. SIFT tables are extremely beneficial when users need to sum up a larger number of records. With that in mind, users can check existing SIFT tables and see if they need some of the level of details. There is no need, for example, to store a cumulative sum of just a few records. Users can use the property SIFTLevels and disable specific levels by clearing the checkbox Maintain for a specific bucket, thus reducing the overall overhead of the SIFT table while still keeping the SIFT table in place for summing the larger number of records. However, there is no need, for example, to keep cumulative sums on the top level buckets if they are used, such as a total of Quantity on "Location Code" in the Item Ledger Entry table, since users always filter on "Item No."
Optimizing Indexes The second largest typical Microsoft Dynamics NAV overhead is the processing load to maintain indexes. The Microsoft Dynamics NAV Classic database is over-indexed, since customers require certain reports to be ordered in different ways, and the only way to sort is to create a key for each sequence. However, SQL Server can sort data directly and quite fast if the set is small, so there is no need to keep indexes for sorting purposes only. For example, in the Warehouse Activity Line table, there are a number of keys that begin with "Activity Type" and "No." fields, such as the following: “Activity Type,No.,Sorting Sequence No.” “Activity Type,No.,Shelf No.” “Activity Type,No.,Action Type,Bin Code” etc.
The issue here is that these indexes are not needed on SQL Server, because the Microsoft Dynamics NAV code always filters on "Activity Type" and "No." when using these keys. In SQL Server, the Query optimizer looks at the filter and realizes that the clustered index is "Activity Type,No_,Line No_." It also determines that the set is small, that there is no need to use an index to retrieve the set and return it in that specific order. It uses only the clustered index for these operations. Since the entire functionality is not used by customers, if they never pick the stock by "Sorting Sequence No.," then there is no need to maintain the index.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Developers need to analyze the existing indexes with a focus on use and benefits compared to the processing overhead, and determine what action is needed. Choose between disabling the index entirely using they key property Enable, or the KeyGroups property, or by using the MaintainSQLIndex property. Indexes that remain active can change structure by using the SQLIndex property. Developers can also make the table clustered by a different index.
Enabled Property The Enabled property turns a specific key on and off. If a key is not enabled and is referenced by a C/AL code or CALCSUMS function, a run-time error will be received.
KeyGroups Property Make one or more keys a member of a predefined key group. This allows the key to be defined, but only enabled when it is going to be used. Use the KeyGroups property to select the predefined key groups. Choose the KeyGroups option on the Database Information window (select File, click Database, click Information, and then click Tables). There are key groups already defined, such as Acc(Dim), Item(MFG), but more can be created and assigned to keys. The purpose of key groups is to set up a group of special keys that are infrequently used (such as for a special report that is run once every year). Since adding many of keys to tables eventually decreases performance, using key groups makes it possible to have the necessary keys defined, but only active when needed.
MaintainSQLIndex Property This property determines whether an SQL Server index corresponding to the Microsoft Dynamics NAV key should be created (when set to Yes) or dropped (when set to No). A Microsoft Dynamics NAV key is created to sort data in a table by the required key fields. However, SQL Server can sort data without an index on the fields to be sorted. If an index exists, sorting by the fields matching the index is faster, but modifications to the table will be slower. The more indexes there are on a table, the slower the modifications become. In situations where a key must be created to allow only occasional sorting (for example, when running infrequent reports) users can disable this property to prevent slow modifications to the table.
11-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server SQLIndex Property This property allows users to define the fields that are used in the SQL index. The fields in the SQL index can be the following: •
Different than the fields defined in the key in Microsoft Dynamics NAV - there can be fewer fields or more fields.
•
Arranged in a different order.
If the key in question is not the primary key and the SQLIndex property is used to define the index on SQL Server, the index that is created contains exactly the fields that users specify and is not necessarily a unique index. It will only be a unique index if it contains all the fields from the primary key. If the SQL index is defined for the primary key, it must include all the fields defined in the Microsoft Dynamics NAV primary key. Extra fields can be added and these fields can be rearranged to suit individual needs.
Clustered Property Use this property to determine which index is clustered. By default the index corresponding to Microsoft Dynamics NAV primary key is made clustered.
Implicit/Explicit Locking There are further considerations to make when working with Microsoft Dynamics NAV on SQL Server. Microsoft Dynamics NAV is designed to read without locks and locks only if needed, following optimistic concurrency recommendations. If records are going to be modified, that intent should be indicated to the driver (use explicit locking), so that the data is read properly.
Implicit Locking The following table demonstrates implicit locking. The C/AL pseudo-code on the left is mapped to the equivalent action on SQL Server: Sample code
Result
TableX.FIND(‘-’);
SELECT * FROM TableX WITH (READUNCOMMITTED) (the retrieved record timestamp = TS1)
TableX.Field1 := Value;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Sample code
Result
TableX.MODIFY;
SELECT * FROM TableX WITH (UPDLOCK, REPEATABLEREAD) (the retrieved record timestamp = TS2) performs the update UPDATE TableX SET Field1 = Value WITH (REPEATABLEREAD) WHERE TimeStamp <= TS1
The reason for such a complex execution is that: •
The data is read with the READUNCOMMITED isolation level, but because users are going to update, they need to ensure that they read committed data and issue an update lock on it to prevent other users from updating the same records.
•
The data is originally read uncommitted; users need to lock the record and also ensure that they update the record with an original TimeStamp. If somebody else changes the record, that person receives an error: "Another user has modified the record since users retrieved from the database…."
Explicit Locking If users indicate to the database driver that their intention is to modify the record by using explicit locking, they can eliminate the bad behavior entirely, as shown by the following pseudo code: Sample code
Result
TableX.LOCKTABLE ;
Indicates to the driver explicit lock
TableX.FIND(‘-’);
SELECT * FROM TableX WITH (UPDLOCK) (the retrieved record timestamp = TS1)
TableX.Field1 := Value; TableX.MODIFY;
UPDATE TableX SET Field1 = Value WITH (REPEATABLEREAD) (the retrieved record timestamp is guaranteed to be TS1)
11-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server Problems with NEXT In some situations, the NEXT command causes the biggest performance problem in Microsoft Dynamics NAV, and users should pay particular attention to avoid these situations. The problem is that the database driver is using a cursor, and there is no way to change the isolation level in the middle of the data retrieval. Also, if users change the condition of the set, then the set has to be retrieved again. There are a number of scenarios that cause problems with NEXT. Instead, FETCH should be used, but if the set is wrong, a new SELECT statement needs to be executed. This imposes a serious performance penalty in SQL Server and in some situations leads to very lengthy execution. Performance problems occur if users perform a NEXT on a set, but they did one of the following: •
Changed filter
•
Changed sorting
•
Changed key value
•
Changed isolation level
•
Performed NEXT "in the middle of nowhere" on a record that they got through GET for example.
The following code examples demonstrate this problem: Code
Result
SETCURRENTKEY( FieldA); SETRANGE(FieldA, Value); FIND(‘-‘)
Set or part of the set is retrieved, first record loaded
REPEAT FieldA := NewValue; MODIFY; UNTIL NEXT = 0;
Record position is now outside the set Record is put outside the set The system is asked to go to NEXT from position, but from outside the set
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 "Jumping" through data - NEXT "in the middle of nowhere" Code
Result
SETRANGE(FieldA,Valu e); FIND(‘-’);
Set based on filter on FieldA
REPEAT … New set based on filter on FieldA AND FieldB SETRANGE(FieldB,Field B); … FIND(‘+’);
Record position is end of the set
… SETRANGE(FieldB);
Filter removed
… UNTIL NEXT = 0
The system is asked go to NEXT from undefined position
Non-cursor to cursor Code
Result
SETRANGE(FieldA,Valu e); FINDFIRST;
Non-cursor fetch
REPEAT … UNTIL NEXT = 0;
The system is asked to go to NEXT on nonexisting set
SETRANGE(FieldA,Valu e); Solutions To eliminate performance problems with NEXT, consider these solutions:
11-22
•
Use a separate looping variable.
•
Restore original key values, sorting, and filters before the NEXT statement.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server •
Read records to temporary tables, modify within, and write back afterwards.
•
FINDSET(TRUE,TRUE).
Note also that FINDSET(TRUE,TRUE) is not a "real solution;" it is merely a reduction of the costs and should be used only as a last resort.
Suboptimum Coding and Other Performance Penalties Taking performance into consideration often influences programming decisions. For example, if users do not use explicit locking, or if they program bad loops and provoke problems with NEXT, they often pay a big price in terms of performance. Users also need to review their code and see how many times the code is reading the same table, or use COUNT for checking if there is a record (IF COUNT = 0, IF COUNT = 1), or use MARKEDONLY instead of pushing records to a temporary table and read them from there. Additionally, there are features in the application that need to be avoided or minimized. For example, the advance dimensions functionality is cost demanding. Users should review the application setup for the performance aspect and make corrective actions if they can. The Classic Database Server setup can also make a big difference, such as object cache size, but a big overhead may come from the “Find As You Type” feature. When "Find As You Type" is enabled, the system is forced to do another query for each keystroke. The GUI overhead can be slowing the client down, if, for example, a dialog is refreshed 1000 times in a loop. GUI overhead can also cause increased server trips. When users use the default SourceTablePlacement = <Saved> on forms, it costs more than using Last or First. Users should review all forms showing data from large tables to look for performance problems.
Overview of NDBCS NDBCS, or the Microsoft Dynamics NAV Database Driver for Microsoft SQL Server, translates Microsoft Dynamics NAV data requests into Transaction-SQL (T-SQL). This translation allows the Microsoft Dynamics NAV clients to communicate with SQL Server. For example, consider the following C/AL statements: GLEntry.SETCURRENTKEY("G/L Account No.","Posting Date"); GLEntry.SETRANGE("G/L Account No.",’7140’); IF GLEntry.FIND('-') THEN;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 This code causes the following information to be sent from Microsoft Dynamics NAV to the NDBCS driver: Function Name
Parameter
Data
FIND/NEXT
Table
G/L Entry
FIND/NEXT
Search Method
-
FIND/NEXT
Key
G/L Account No.,Posting Date,Entry No.
FIND/NEXT
Filter
G/L Account No.:7140
The NDBCS driver often uses cursors. Cursors are used in SQL Server if records from a set record-by-record rather than by retrieving an entire set. There are different types of cursors which have different capabilities. For example, the forward-only cursor allows fast reading from top to bottom, while the dynamic cursor allows retrieval in either direction. (There are two other types of cursors: static cursors and keyset-driven cursors.) The NDBCS driver translates the preceding example into a set of T-SQL statements that uses a dynamic cursor, and looks like the following: SELECT * FROM "CRONUS International Ltd_$G_L Entry" WITH (READUNCOMMITTED) WHERE (("G_L Account No_"='7140')) ORDER BY "G_L Account No_","Posting Date","Entry No_" OPTION (FAST 5)
If explicitly indicating that the records will be modified using the GLEntry.LOCKTABLE command followed by the C/AL code above, the following is sent to the driver: Function Name
Parameter
Data
LOCKTABLE
Table
G/L Entry
FIND/NEXT
Table
G/L Entry
FIND/NEXT
Search Method
-
FIND/NEXT
Key
G/L Account No.,Posting Date,Entry No.
FIND/NEXT
Filter
G/L Account No.:7140
In this case the driver will do the same, but it will use a different isolation level, like the following: WITH (UPDLOCK, ROWLOCK)
A loop can be added, like the following: IF GLEntry.FIND('-') THEN REPEAT UNTIL GLEntry.NEXT = 0;
11-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server As a result, the following is sent to the driver when the first NEXT command is executed: Function Name
Parameter
Data
FIND/NEXT
Table
G/L Entry
FIND/NEXT
Search Method
>
FIND/NEXT
Key
G/L Account No.='7140',Posting Date='01/01/00',Entry No.='77'
The second NEXT produces the following: Function Name
Parameter
Data
FIND/NEXT
Table
G/L Entry
FIND/NEXT
Search Method
>
FIND/NEXT
Key
G/L Account No.='7140',Posting Date='01/02/00',Entry No.='253'
The important facts are that the NDBCS driver: •
Does not know what the code intends to do (whether it wants to browse forward or backward through the table, or just want the first record).
•
Builds dynamic cursors with many different optimizations, such as reading ahead using FETCH 5, FETCH 10, and so on, using read ahead through SELECT TOP 49 * FROM, dropping dynamic cursor and using forward-only cursor, and so on.
Optimization of Cursors By default, the way the dynamic cursors are used is not very efficient. Because cursors have a big impact on performance, handling them in a different way can yield significant improvements. For example, there is no reason to create a cursor at all for retrieving a single record. When they are necessary, however, they can still be efficient. Optimizing cursors can be done with the following four Microsoft Dynamics NAV commands: •
ISEMPTY
•
FINDFIRST
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 •
FINDLAST
•
FINDSET
ISEMPTY By default, determining if a set is empty uses cursors. For example: Customer.SETRANGE(Master, TRUE); IF NOT Customer.FIND('-') THEN ERROR('Customer master record is not defined');
This code determines if a record exists, but causes the NDBCS driver to generate T-SQL that uses cursors. However, the ISEMPTY command has a different effect: Customer.SETRANGE(Master, TRUE); IF Customer.ISEMPTY THEN ERROR('Customer master record is not defined');
When executed, the code above results in this T-SQL command: SELECT TOP 1 NULL FROM …
Note that the NDBCS driver uses NULL, which means that no record columns are retrieved from the database (as opposed to ‘*’, which would get all columns). This makes it an extremely efficient command that causes just a few bytes to be sent over the network. This can be a significant improvement as long as subsequent code does not use the values from the found record.
FINDFIRST Retrieving the first record in a table can also be an unnecessarily expensive command. Consider this code: Customer.SETRANGE(Master, TRUE); IF NOT Customer.FIND('-') THEN ERROR('Customer master record is not defined');
The FINDFIRST command retrieves the first record in a set. Like ISEMPTY, FINDFIRST does not use cursors: Customer.SETRANGE(Master, TRUE); IF NOT Customer.FINDFIRST THEN ERROR('Customer master record is not defined');
When executed, this T-SQL is generated: SELECT TOP 1 * FROM ... ORDER BY ...
11-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server Warning: If doing a REPEAT/UNTIL NEXT loop, do not use this command, because the NEXT will have to create a cursor for fetching the subsequent records.
FINDLAST Retrieving the last record in a table can also be an unnecessarily expensive command. Consider this code: Message.SETCURRENTKEY(Date); IF Message.FIND('+') THEN MESSAGE('Last message is dated ’ + FORMAT(Message.Date));
The FINDLAST command retrieves the last record in a set. Like FINDFIRST, FINDLAST does not use cursors: Message.SETCURRENTKEY(Date); IF Message.FINDLAST THEN MESSAGE('Last message is dated ’ + FORMAT(Message.Date));
This command retrieves the last record in the set, and does not use cursors. When executed, this T-SQL is generated: SELECT TOP 1 * FROM ... ORDER BY ... DESC
Warning: If doing a REPEAT/UNTIL NEXT(-1) loop, do not use this command, because the NEXT will have to create a cursor for fetching the subsequent records.
FINDSET The FINDSET allows browsing through a set of records. In previous versions, retrieving a set in a loop could only be done this way: IF FIND('-') THEN REPEAT UNTIL NEXT = 0;
FINDSET can be used in the following manner without any arguments (FINDSET arguments are explained later in this chapter), like this: IF FINDSET THEN REPEAT UNTIL NEXT = 0;
Unlike the FIND(‘-‘) command, FINDSET does not use cursors. When executed, the T-SQL result looks like this: SELECT TOP 500 * FROM ...
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The REPEAT/UNTIL NEXT browses through the records locally on the client machine. This is the recommended way to retrieve sets quickly -- without any cursor overhead.
Maximum Record Set Size There is a parameter in Microsoft Dynamics NAV that is used to set up the maximum of how many records are retrieved from the database (File, Database, Alter, Advanced tab, Caching, Record Set = 500). If the set is bigger than the maximum, Microsoft Dynamics NAV will continue working but it will replace the reading mechanism with a dynamic cursor. If there is an indication that this is going to happen, use the ‘old’ FIND(‘-‘) command as opposed to FINDSET. Use FINDSET for forward direction only; it will not work for REPEAT/UNTIL NEXT(-1). Also, if the LOCKTABLE command is used prior to the FINDSET, the set is locked, and records can be modified within the loop. A good example of an efficient use of cursors (using the ‘old’ FIND command), is for the read of a big set of records, for example all G/L Entries for a specific account, probably with more than 500 records in the set: GLEntry.SETRANGE("G/L Account No.", "6100"); IF GLEntry.FIND('-') THEN REPEAT UNTIL GLEntry.NEXT = 0;
A good example of using the new FINDSET command (as opposed to using the ‘old’ FIND command), is for the read of a small set of records, such as all sales lines in a sales order, probably always with less than 500 records. This can be done this way: SalesLine.SETRANGE("Document Type","Document Type"::Order); SalesLine.SETRANGE("Document No.",'S-ORD-06789'); IF SalesLine.FINDSET THEN REPEAT TotalAmount := TotalAmount + SalesLine.Amount; UNTIL SalesLine.NEXT = 0;
FINDSET(TRUE) This variation of FINDSET locks the set that is read, so it is equivalent to a LOCKTABLE followed by FIND(‘-). FINDSET(TRUE) and can be used like this: IF FINDSET(TRUE) THEN REPEAT UNTIL NEXT = 0;
11-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server Unlike the commands discussed previously, this command does use a dynamic cursor. The main purpose of this command is to raise the isolation level before starting to read the set because the resulting records are to be modified. FINDSET(TRUE) uses the read-ahead mechanism to retrieve several records instead of just one. It is recommended that LOCKTABLE be used with FINDSET for small sets, and that the FINDSET(TRUE) command be used for sets larger than 500 records (the Record Set parameter). A good example of using the FINDSET(TRUE) command is for the read of a big set of records and the need to modify those records. For example, when going through all G/L entries for a specific account, and changing a field value based on the record condition, the filtered set will probably have more than 500 records. This might be done this way: GLEntry.SETRANGE("G/L Account No.", "6100"); IF GLEntry.FINDSET(TRUE) THEN REPEAT IF (GLEntry.Amount > 0) THEN BEGIN GLEntry."Debit Amount" := GLEntry.Amount; GLEntry."Credit Amount" := 0 END ELSE BEGIN GLEntry."Debit Amount" := 0; GLEntry."Credit Amount" := -GLEntry.Amount; END; GLEntry.MODIFY UNTIL GLEntry.NEXT = 0;
A good example of using the LOCKTABLE and FINDSET command (as opposed to using the FINDSET(TRUE) command) is for the read of a small set of records and the need to modify those records. For example, when going through all sales lines for a specific order, and changing several fields' values, the filtered set will probably have less than 500 records. This can be done this way: SalesLine.SETRANGE("Document Type","Document Type"::Order); SalesLine.SETRANGE("Document No.",'S-ORD-06789'); SalesLine.LOCKTABLE; IF SalesLine.FINDSET THEN REPEAT SalesLine."Qty. to Invoice" := SalesLine."Outstanding Quantity; SalesLine."Qty. to Ship" := SalesLine."Outstanding Quantity; SalesLine.MODIFY UNTIL SalesLine.NEXT = 0;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-29
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 FINDSET(TRUE, TRUE) This variation of the FINDSET(TRUE) allows the modification of the Key value of the sorting order of the set. It can be used like this: IF FINDSET(TRUE,TRUE) THEN REPEAT UNTIL NEXT = 0;
The command, like FINDSET(TRUE), uses a dynamic cursor. The main purpose of this command is to raise the isolation level before you starting to read the set because the set needs to be modified. It does not use the read-ahead mechanism. Instead it retrieves one record at a time because the set is expected to be invalidated within the loop. Avoid using this command, since the loop code should be changed to a more efficient method of working, such as using a different variable for browsing through the set. A good example of using the FINDSET(TRUE,TRUE) command (as opposed to using FIND command) is for the read of a set of records and the need to modify a key value. This should be avoided by any means. If there is not a way to avoid this, use FINDSET(TRUE,TRUE). For example, going through all sales lines for a specific order, and changing key value, the filtered set will probably have less than 500 records in the set. This can be done this way: SalesLine.SETRANGE("Document Type","Document Type"::Order); SalesLine.SETRANGE("Document No.",'S-ORD-06789'); SalesLine.SETFILTER("Location Code",''); IF SalesLine.FINDSET(TRUE,TRUE) THEN REPEAT IF SalesLine.Type = SalesLine.Type::Item THEN SalesLine."Location Code" := 'GREEN'; IF SalesLine.Type = SalesLine.Type::Resource THEN SalesLine."Location Code" := 'BLUE'; SalesLine.MODIFY UNTIL SalesLine.NEXT = 0;
Note that the example above can be easily changed into more efficient code, using FINDSET as opposed to FINDSET(TRUE,TRUE), using a separate variable to modify the records. This can be done this way: SalesLine.SETRANGE("Document Type","Document Type"::Order); SalesLine.SETRANGE("Document No.",'S-ORD-06789'); SalesLine.SETRANGE("Document Type","Document Type"::Order); SalesLine.SETRANGE("Document No.",'S-ORD-06789'); SalesLine.SETFILTER("Location Code",''); SalesLine.LOCKTABLE; IF SalesLine.FINDSET THEN REPEAT SalesLine2 := SalesLine; IF SalesLine.Type = SalesLine.Type::Item THEN SalesLine2."Location Code" := 'GREEN';
11-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server IF SalesLine.Type = SalesLine.Type::Resource THEN SalesLine2."Location Code" := 'BLUE'; SalesLine2.MODIFY UNTIL SalesLine.NEXT = 0;
Locking, Blocking, and Deadlocks When data is read from the database, Microsoft Dynamics NAV uses the READUNCOMMITTED isolation level, meaning that any other user can modify the records that are currently being read. This is often referred to as optimistic concurrency. Data that is read is considered “dirty” because it can be modified by another user. When the data is updated, the Microsoft Dynamics NAV driver must compare the timestamp of the record. If the record is ‘old,’ the Microsoft Dynamics NAV error “Another user has modified the record after you retrieved it from the database” is displayed. Optimistic concurrency allows for better performance because data can be accessed simultaneously by multiple queries. The tradeoff is that care must be taken when writing code that modifies the data. This requires that locking and blocking be employed to synchronize access, but deadlock – a condition where one or more competing processes are stalled indefinitely – can occur. The following subtopics discuss strategies for synchronizing data access while avoiding deadlock.
Locking The isolation level can be changed to a more restrictive setting, such as UPDLOCK. In this level, records that are read are locked, meaning that no other user can modify the record. This is referred to as pessimistic locking, and causes the server to protect the record in case there is a need to modify it -- making it impossible for others to modify. An example of a lock of a customer record can be demonstrated by this code: Customer.LOCKTABLE; Customer.GET('10000'); Customer.Blocked := TRUE; Customer.MODIFY; COMMIT;
// Customer 10000 is locked
// Lock is removed
If the record is not locked, the following situation can occur: User A
User B
Customer.GET(' 10000');
Comment User A reads record without any lock
Customer.GET(' 10000');
User B reads same record without any lock
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-31
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 User A
User B
Comment
…
Customer.Block ed := TRUE; Customer.MOD IFY; COMMIT;
User B modifies record
Customer.Block ed := FALSE; Customer.MOD IFY; ERROR
User A gets an error: “Another user has modified the record...”
SUCCESS
Blocking When other users try to lock data that is currently locked, they are blocked and have to wait. If they wait longer than the defined timeout, they receive a Microsoft Dynamics NAV error: "The XYZ table cannot be locked or changed because it is already locked by the user with User ID ABC." If necessary, change the default timeout with File, Database, Alter, Advanced tab, Lock Timeout checkbox and Timeout duration (sec) value. Based on the previous example where two users try to modify the same record, the data that is intended to be modified can be locked, preventing other users from doing the same. Here is an example: User A
User B
User A reads record with lock
Customer.LOC KTABLE; Customer.GET( '10000'); Customer.LOC KTABLE; Customer.GET( '10000');
User B tries to read same record with a lock
…
… blocked, waiting …
User B waits and is blocked, because the record is locked by user A
Customer.Bloc ked := TRUE; Customer.MOD IFY;
… blocked, waiting …
User A successfully modifies record.
COMMIT;
Lock is released. …
11-32
Comment
Data is sent to user B
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server User A
SUCCESS
User B
Comment
Customer.Bloc ked := FALSE; Customer.MOD IFY;
User B successfully modifies record.
COMMIT;
Lock is released.
SUCCESS
Deadlocks There is a potential situation when blocking cannot be resolved by the server in a good way. The situation arises when one process is blocked because another process has locked some data. The other process is also blocked because it tries to lock the first process data. Only one of the transactions can be finished; SQL Server terminates the other and sends an error message back to the client: "Your activity was deadlocked with another user …" For example, consider a case where two users are working simultaneously and trying to get each other’s blocked records, as shown in this pseudo code: User A
User B
Comment
TableX.LOCK TABLE; TableY.LOCK TABLE;
TableX.LOCK TABLE; TableY.LOCK TABLE;
Indicates that the next read will use UPDLOCK
TableX.FINDF IRST;
TableY.FINDF IRST;
A blocks Record1 from TableX. B blocks Record 1 from tableY.
…
…
User A
User B
Comment
TableY.FINDF IRST;
TableX.FINDF IRST;
A wants B’s record, while B wants A’s record. A conflict occurs. SQL Server detects deadlock and arbitrarily chooses one over the other, so one will receive an error.
"Your activity was deadlocked with another user" ERROR
SUCCESS
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-33
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 SQL Server supports record level locking, so there may be a situation where these two activities bypass each other without any problems, such as with this pseudo code (note that User A is fetching the last record compared to the situation above): User A
User B
Comment
TableX.LOCKT ABLE; TableY.LOCKT ABLE;
TableX.LOCK TABLE; TableY.LOCK TABLE;
Indicates that the next read will use UPDLOCK
TableX.FINDFI RST;
TableY.FIND FIRST;
A blocks Record1 from TableX. B blocks Record 1 from tableY.
…
…
TableY.FINDL AST;
TableX.FIND LAST;
SUCCESS
SUCCESS
No conflict, as no records are in contention.
Note that there would be a deadlock if one of the tables is empty, or contained one record only. To add to this complexity, there may be a situation where two processes read the same table from opposite directions and meet in the middle, such as with this pseudo code: User A
User B
Comment
TableX.LOCKT ABLE; TableY.LOCKT ABLE;
TableX.LOC KTABLE; TableY.LOC KTABLE;
Indicates that the next read will use UPDLOCK
TableX.FIND(‘’);
TableY.FIND (‘+’);
A reads from top of TableX. B reads from bottom of TableX.
User A
User B
REPEAT
REPEAT
…
…
UNTIL NEXT = 0;
UNTIL NEXT(-1) = 0;
…after some time… A wants B’s record, while B wants A’s record. A conflict occurs.
"Your activity was deadlocked with another user"
SQL Server detects deadlock and chooses one of the users for failure.
SUCCESS
11-34
Comment
ERROR
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server There are also situations where a block on index update may produce the conflict, and situations where updating SIFT tables can cause a deadlock. These situations can be complex and hard to avoid. However, the transaction chosen to fail is rolled back to the beginning, so there should be no major issue. However, if the process is written with several partial commits, then there might be “dirty” data in the database as a side-product of those deadlocks that can become a major issue for the customer.
Avoiding Deadlocks A large number of deadlocks can lead to major customer dissatisfaction, but deadlocks cannot be avoided entirely. To reduce the number of deadlocks, do the following: •
Process tables in the same sequence.
•
Process records in the same order.
•
Keep the transaction length to a minimum.
If the above is not possible due to the complexity of the processes, as a last resort revert to serializing the code by ensuring that conflicting processes cannot execute in parallel. The following code demonstrates how this can be done: User A
User B
Comment
TableX.LOCKTA BLE; TableY.LOCKTA BLE; TableA.LOCKTA BLE;
TableX.LOCKTA BLE; TableY.LOCKTA BLE; TableA.LOCKTA BLE;
Indicates that the next read will use UPDLOCK
TableA.FINDFIR ST;
…
User A locks Record1 from TableX
User A
User B
Comment
TableA.FINDFIR ST;
User B tries to lock Record1 from TableX
…
Blocked
User B is blocked
TableY.FINDFIR ST; TableX.FINDFIR ST;
Blocked
User A processes tables in opposite order
COMMIT;
Block is released OK on read table A
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-35
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 User A
User B
Comment
TableX.FINDFIR ST; TableY.FINDFIR ST;
User B processes tables in opposite order
COMMIT; SUCCESS
SUCCESS
By serializing the transactions, a higher probability of timeouts can be experienced, so keeping the length of transactions short becomes even more important. This also demonstrates that you can combine the various principles and methods can be combined together, depending on the situation and complexity; one method works for one customer while the other works for another. It is also recommended to adhere to some of the following “golden rules:” •
Test conditions of data validity before the start of locking.
•
Allow some time gap between heavy processes so that other users can process.
•
Never allow user input during an opened transaction.
If the transaction is too complex or there is limited time, consider discussing with the customer the possibility of over-night processing of heavy jobs, thus avoiding the daily concurrency complexity and avoiding the high costs of rewriting the code.
How SIFT Data is Stored in SQL Server SIFT tables are used in Microsoft Dynamics NAV version 5.0 and older, to implement SIFT on SQL Server, and store aggregate values for SumIdexFields for keys in the source tables. Starting with version 5.0 Service Pack 1, these SIFT tables are replaced by indexed views. SIFT tables themselves are no longer part of Microsoft Dynamics NAV. This section is preserved, however, because developers working with Microsoft Dynamics NAV are likely to run into issues concerning SIFT tables in implementations of older versions of Microsoft Dynamics NAV, and it is essential to have a good understanding of their inner working. A SumIndexField is always associated with a key, and each key can have a maximum of 20 SumIndexFields associated with it. When the MaintainSIFTIndex property of a key is set to Yes, Microsoft Dynamics NAV regards this key as a SIFT key and creates the SIFT structures that are needed to support it.
11-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server Any field of the Decimal data type can be associated with a key as a SumIndexField. Microsoft Dynamics NAV then creates and maintains a structure that stores the calculated totals that are required for the fast calculation of aggregated totals. In the SQL Server Option for Microsoft Dynamics NAV, this maintained structure is a normal table, but is called a SIFT table. These SIFT tables exist on SQL Server, but are not visible in the table designer in C/SIDE. As soon as the first SIFT table is created for a base table, a dedicated SQL Server trigger is also created and is then automatically maintained by Microsoft Dynamics NAV. This is known as a SIFT trigger. A base table is also a standard Microsoft Dynamics NAV table, as opposed to an extra SQL Server table that is created to support Microsoft Dynamics NAV functionality. One SIFT trigger is created for each base table that contains SumIndexFields. This dedicated SQL Server trigger supports all the SIFT tables that are created to support this base table. The purpose of the SIFT trigger is to implement all the modifications that are made on the base table whenever a SIFT table is affected. This means that the SIFT trigger automatically updates the information in all the existing SIFT tables after every modification of the records in the base table. The name of the SIFT trigger has the following format: _TG. For example, the SIFT trigger for table 17, G/L Entry is named "CRONUS International Ltd_$G/L Entry_TG." Regardless of the number of SIFT keys that are defined for a base table, only one SIFT trigger is created. A SIFT table is created for every base table key that has at least one SumIndexField associated with it. No matter how many SumIndexFields are associated with a key, only one SIFT table is created for that key. The name of the SIFT table has the following format: $$. For example, one of the SIFT tables created for table 17, G/L Entry is named "CRONUS International Ltd_$17$0." The column layout of the SIFT tables is based on the layout of the SIFT key along with the SumIndexFields that are associated with this SIFT key. But the first column in every SIFT table is always named "bucket" and contains the value of the bucket or the SIFT level for the precalculated sums that are stored in the table. To view the structure, look at the SIFTLevels property for a key in Microsoft Dynamics NAV. After the bucket column is a set of columns with names that start with the letter "f." These are also known as f- or key-columns. Each of these columns represents one field of the SIFT key. The name of these columns has the format, f, where Field No. is the integer value of the Field No. property of the represented SIFT key field. For example, column f3 in “CRONUS International Ltd_$17$0” represents the G/L Account No. field (it is field number three in the base table G/L Entry).
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-37
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Finally, there is a group of columns with names that start with the letter "s" followed by numbers. These are known as s-columns. These columns represent every SumIndexField associated with the SIFT key. The name of these columns has the format, s. Field No. is the integer value of the Field No. property of the represented SumIndexField. The precalculated totals of values for the corresponding SumIndexFields are stored in these fields of the SIFT table. With regards to performance, SIFT tables are one of the biggest Microsoft Dynamics NAV performance problems on SQL Server, as one record update in the base table produces a potentially massive stream of Input/Output (I/O) requests with updates to the records in the SIFT tables, possibly blocking other users during that time.
11-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server
Lab 11.1 - Find As You Type in the Client Monitor An important part of being able to do SQL Optimization is being familiar with the tools that are used to diagnose Microsoft Dynamics NAV SQL Server activity. The Client Monitor is one such tool, an important one. Scenario As discussed in this chapter, the Find As You Type option can cause many performance problems on SQL Server (or any other server). In this lab you will learn to use the Client Monitor to look at the SQL Statements that are generated by Microsoft Dynamics NAV, when the Find As You Type database option is turned on. The Client Monitor is a tool that logs the details of every action that is taken by the user. It logs which object is used, the duration of each step, the SQL Statements that are generated, among many more. In this lab, you will focus on the SQL Statements.
Step by Step The Client Monitor is a tool that runs from the Classic client. In Microsoft Dynamics NAV: 1. Open the File menu, and select Alter from the Database submenu. 2. Go to the Options tab, and ensure that the Allow Find As You Type property is turned on.
FIGURE 11.1 ALLOW FIND AS YOU TYPE IN ALTER DATABASE
3. Click OK to accept the values in the Alter Database Form. The Client Monitor logs everything, and it takes very little to generate thousands of lines. When analyzing the Client Monitor results it can be quite overwhelming to have to wade through large numbers of seemingly irrelevant entries. To make analysis easier, it is recommended to prepare the transaction as much as possible, so that there are as few irrelevant lines as possible. Ensure that the action of interest is ready to be executed before starting the client monitor.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-39
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The goal is to log what happens when a user is trying to find a particular customer from the Customer List form, by typing the name into the Find dialog. As the user is typing, the system will query the database for the customer name. The Client Monitor will log all the queries that are generated. 4. Open the Customer Card. 5. Press F5 to open the Customer List form. 6. Select Client Monitor from the Tools menu.
FIGURE 11.2 CLIENT MONITOR STARTED
7. Click Start and move back to the Customer List form. 8. With the cursor on the Name field, press Ctrl+F to open the Find dialog. 9. Ensuring that the Find As You Type box is checked, type in "Cronus." 10. Go back to the Client Monitor and click Stop. At this point, the Client Monitor should be populated with a number of lines. Take a moment to investigate some of the entries, and to become familiar with the type of information that can be found. The focus is to find the SQL Statements that are generated when searching for a customer name. 11. Move the cursor to the Parameter field. Drop-down the Option list and look at the available options.
11-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server 12. Press F7 to enter a filter. 13. Select SQL Statement and click OK.
FIGURE 11.3 CLIENT MONITOR FILTERED BY SQL STATEMENT
Searching for the name Cronus, with the Find As You Type option activated, generated a total of 32 SQL Statements. Take a closer look at the actual SQL Statements in the Data field, starting with the one at the top. Go down the list of statements until the following is reached: SELECT TOP 1 *,DATALENGTH("Picture") FROM "CRONUS International Ltd_$Customer" WHERE (("Name" LIKE '%[cCçÇ]%')) ORDER BY "No_"
Note that the WHERE clause includes the keyword LIKE. This is a query that tells SQL Server it is not sure whether the name contains a lower case or an upper case letter c, or that it might contain an accent. These LIKE queries are very costly queries for SQL Server, because it does not contain exact matches, and it therefore has to scan the table. Move a little further down the list until the following is reached: SELECT *,DATALENGTH("Picture") FROM "CRONUS International Ltd_$Customer" WHERE "No_"='01454545' AND (("Name" LIKE '%[cCçÇ][rR]%'))
The WHERE clause now includes variations of the characters in the string ‘cr,’ the first two letters of the name typed. The same type of LIKE query is also found for the strings ‘cro,’ ‘cron,’ all the way through to ‘cronus.’ Each character that is typed generated another LIKE query. A number of additional queries are generated to select records in a number of different ways. The Microsoft Dynamics NAV executable generates these queries to support the Find As You Type option, assuming that the user does not really know what he or she are looking for.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-41
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 While this option can be of functional value to the users, and sometimes they are adamant about keeping this option, it is also very costly. When many users are searching for records at the same time, overall performance can be severely affected. The next few step, involve turning off the Find As You Type option, and looking at the same data in the Client Monitor. First clear the Client Monitor. 14. Remove all filters from the Client Monitor, by pressing Ctrl+Shift+F7 15. Select all records and press F4 to delete all the lines. 16. Open the Alter Database form and go to the Options tab. 17. Remove the checkmark from the Allow Find As You Type field and click OK. 18. Turn on the Client Monitor and go back to the Customer List form. 19. Open the Find dialog. When the Find dialog opens, it has the name of the current field pre-populated. Note that Find As You Type is cleared and that it cannot be edited.
FIGURE 11.4 FIND AS YOU TYPE DISABLED
When typing the letters into the Find What text box, note that the system is not jumping through the records. To actually search for the string that is entered into the Find What text box, the Find First button or the Find Next button must be clicked. 20. Enter the string ‘cronus’ and click Find First. This should cause the system to jump to the same customer found previously. 21. Go back to the Client Monitor and click Stop. 22. Filter the Client Monitor’s Parameter field on SQL Statement.
11-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server This time, there is only one LIKE query, for the full string. In addition to the LIKE query, the system also generated some other queries. However, by searching just once, there are only six queries, a significantly lower number of queries than with the Find As You Type option turned on. The LIKE query is still not a very good query for performance, but by turning off the Find As You Type option, a large number of queries are eliminated from the system. With many users searching the system, this can make a big difference in performance.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-43
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Lab 11.2 - Using the Client Monitor to Analyze Performance Once the basic setup and usage of the Client Monitor has been conquered, the next step is to learn how to take advantage of Microsoft Dynamics NAV built-in data analysis tools (such as filtering) to do additional analysis of the results created by Client Monitor. Such techniques are especially useful for analyzing the timing (such as duration) of various NAV processing activities. Scenario The Client Monitor is one of the most useful tools within the Microsoft Dynamics NAV client to analyze how the system is performing. Since it logs individual steps in the code, and it logs every query that is sent to SQL Server, it is possible to determine the details of what does and does not work well in each individual implementation. In this lab you will post a sales invoice while running the Client Monitor. Then you will look at the duration of the steps to analyze the performance.
Step by Step The Client Monitor is a tool that runs from the Classic client. From Microsoft Dynamics NAV: 1. Ensure that the Client Monitor is cleared, by deleting all entries from the form. 2. Create a Sales Order for any item in the system. In this example, a Sales Order for Customer number 10000 is created, with an order for five Side Panels (Item number 70000).
FIGURE 11.5 SALES ORDER
11-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server 3. Turn on the Client Monitor. 4. Ship and Invoice the Sales Order. 5. Stop the Client Monitor. As discussed previously, the Client Monitor logs every step of the client process, to a level of detail where it is almost possible to identify individual lines of code. For every step it creates an entry, and logs a number of parameters that are relevant for that particular step. Lab 11.1 looked at the SQL Statement parameter. Not every step has a line for this parameter, because not every step generates a SQL statement. Different reasons for using the Client Monitor make different parameters interesting to look at. For this lab, you will look at the Elapsed Time (ms) parameter (milliseconds), to identify the steps that take the longest time. 6. Filter the Client Monitor where the Parameter field equals Elapsed Time (ms). 7. Filter the Number field for values greater than 100.
FIGURE 11.6 CLIENT MONITOR DURATION GREATER THAN 100
The results in the figure above may be slightly different from the results that you are seeing. Depending on a number of variables, performance varies greatly from one machine to the next. The screenshot above is taken from a standard Cronus International demonstration company in a Virtual PC image. The Client Monitor shows five results with a duration that is longer than 100 milliseconds (ms). It might be necessary to filter the Elapsed Time field on a different value for any results to show in this screen. To learn what actually happens during these steps, all lines for each entry need to be investigated. As indicated before, the results in this example might be different from the results in your system. The next steps are taken in this example, and they are an illustration of how to analyze individual Client Monitor results.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-45
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 The next step is to look at entry number 339: 8. Set a filter on the Entry No. field where it equals 339. 9. Remove the filter from the Number field and from the Parameter field. Now all the Client Monitor lines that are part of Entry number 339 can be seen, as shown in the following image.
FIGURE 11.7 CLIENT MONITOR FOR STEP 339
This Client Monitor entry provides some interesting information:
11-46
•
The step took 101 ms, which is one tenth of a second. For one single step this is not a very high number, but if this had been a sales order with 100 lines, this step might have been repeated 100 times, and it could have taken a total of 10 seconds. Ideally, no step should take more than 10-30 ms, and everything that has a longer duration warrants a closer inspection of the code.
•
The Function Name is FIND/NEXT, which tells us that this step is a C/AL code statement that does either a FIND or a NEXT. As discussed in this chapter, some types of FIND and NEXT commands can cause performance problems, so this provides an important clue about what might be going on.
•
The Source Object is Codeunit 80 Sales-Post, which identifies the object that contains this FIND/NEXT statement.
•
The Source Trigger/Function further identifies exactly which trigger is being executed.
•
The Source Text specifies the exact line of code that is executed.
•
The SQL Statement shows which query is sent to SQL Server to support this C/AL statement.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server What this does NOT tell us, is the context of the code. For this, it is necessary to look at the actual object to determine the context in which this code is written this way. Typically, FIND(‘+’) is not ideal for performance. Possible replacements could include FINDLAST, or ISEMPTY. The preliminary conclusion is that this code needs to be investigated further, and possibly rewritten to increase performance. The next step is to open the codeunit and look at the actual code.
FIGURE 11.8 CREATE PREPAYMENT LINES IN CODEUNIT 80
As shown in the figure, the CreatePrepaymentLines function does contain the line of code identified by the Client Monitor, which is highlighted in green. At first glance all that this line of code seems to do is determine whether records exist in this filter, and EXIT if there are not. So the first thing that comes to mind is to replace this code with ISEMPTY. Further down, however, one of the field values is used to set the value of the NextLineNo variable. This particular FIND(‘+’) statement should be replaced by FINDLAST. Another line of code is highlighted, a FIND(‘-‘) statement. Looking at the REPEAT statement directly following this statement, this code is going to loop through a set of records. This FIND(‘-‘) statement should be replaced by a FINDSET statement, and further code review should be done to determine the value of its parameters.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-47
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Summary This chapter covered the essential points of insuring optimal performance in Microsoft Dynamics NAV applications, particularly when using SQL Server. The two database options were compared, revealing that they are different database types and therefore have different performance characteristics. The specific ways in which SQL Server is implemented were discussed in detail to reveal why some operations are expensive in terms of performance, and others are cheap and just as effective. The labs showed how to use the Client Monitor to analyze what happens inside the code. This tool should be used sparingly in a production environment, since the tool itself consumes a large number of system resources.
11-48
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server
Test Your Knowledge 1. What are two important proprietary Classic Database Server features that are simulated on SQL Server? Explain how these features are simulated.
2. Explain the difference between the concepts of clustered index and primary key.
3. What is the purpose of collation?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-49
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 4. What is the purpose of database replication, and which replication mechanism on SQL Server can be used for Microsoft Dynamics NAV?
5. What elements are important when defining the backup strategy? List four elements of the most comprehensive backup strategy.
6. How can a SQL Server index be disabled from the table designer in C/SIDE, without disabling the key?
11-50
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server 7. Why is the Find As You Type option bad for performance on SQL Server?
8. What can be done to help avoid deadlocks?
9. How is SIFT stored on SQL Server?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-51
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 10. What tools in C/SIDE can be used to troubleshoot performance issues?
11-52
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server
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-53
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. What are two important proprietary Classic Database Server features that are simulated on SQL Server? Explain how these features are simulated. MODEL ANSWER: SIFT, which is simulated on SQL Server by indexed views, and prior to version 5.0 SP1 by additional SIFT tables. Data Versioning, which is simulated on SQL Server by including a datetime value for each record in the database. 2. Explain the difference between the concepts of clustered index and primary key. MODEL ANSWER: The Clustered Index is the index that is used by SQL Server to physically store the data. If the clustered index is set to any particular field, then SQL Server will physically store the records in the table in the order of that field. The Primary Key is the key that defines the uniqueness of a record. Primary key field values uniquely identify a record in the table. It is possible to set an index other than the primary key index as a table’s clustered index. 3. What is the purpose of collation? MODEL ANSWER: The collation of a database determines which character set is used to store the values in the database. It determines the way that data is sorted, and can affect the way that data is retrieved from the database. 4. What is the purpose of database replication, and which replication mechanism on SQL Server can be used for Microsoft Dynamics NAV? MODEL ANSWER: Database replication is the process of distributing data from one source database to one or more destination databases. It provides for load balancing, offline processing and redundancy. For Microsoft Dynamics NAV, it is recommended to only allow data to be modified in the source database. For this reason, it is recommended to use snapshot or transactional replication, and not to use merge replication.
11-54
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Optimizing For SQL Server 5. What elements are important when defining the backup strategy? List four elements of the most comprehensive backup strategy. MODEL ANSWER: The defining elements of a backup strategy are the recovery model, the customer’s attitude toward data loss, and available system resources. The most comprehensive backup strategy includes the following: • The Recovery Model is set to full • There is a periodic full database backup • There is a periodic differential database backup • There is a periodic transaction log backup 6. How can a SQL Server index be disabled from the table designer in C/SIDE, without disabling the key? MODEL ANSWER: By turning off the MaintainSQLIndex property of the key. 7. Why is the Find As You Type option bad for performance on SQL Server? MODEL ANSWER: Because the Microsoft Dynamics NAV executable generates a LIKE query for each character that is typed into the Find dialog box, which causes large overhead. 8. What can be done to help avoid deadlocks? MODEL ANSWER: To help avoid deadlocks, the following can be done: • Lock tables in the same order for different types of transactions • Process records in the same order for different types of transactions • Keep transaction length to a minimum • Serialize the transaction, by locking a general table at the start of every transaction 9. How is SIFT stored on SQL Server? MODEL ANSWER: Prior to version 5.0 SP1, SIFT is stored on SQL Server in separate SIFT tables, and SIFT totals are updated by table triggers on SQL Server. From version 5.0 SP1 forward, SIFT is stored on SQL Server by indexed views.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-55
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 10. What tools in C/SIDE can be used to troubleshoot performance issues? MODEL ANSWER: The Client Monitor, and Code Coverage.
11-56
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment
CHAPTER 12: DEPLOYMENT Objectives The objectives are: •
Apply the essential elements of a successful deployment phase.
•
Know of and understand the types of data generally imported into Microsoft Dynamics® NAV
•
Know of and understand the partner's role for ongoing support both during and after the initial deployment phase.
•
Evaluate the difference between updates and upgrades.
•
Understand processes for upgrading executables and objects.
•
Follow the basic steps involved in a typical Microsoft Dynamics NAV upgrade project.
•
Know of the tools available to assist with upgrades.
Introduction The deployment phase marks the end of the implementation phase. During deployment, the final preparations are made and the solution is installed at the client site. There are a number of preconditions for this phase which include: •
The new solution must be completely developed and tested.
•
Any errors must be identified and resolved.
•
The various analysis and design documents must be updated for any changes.
•
The infrastructure must be in place.
•
The users must be trained and knowledgeable about the new module they will be using after deployment.
•
The user documentation must be prepared and ready for use.
Once these preconditions are in place, the Seminar module can be deployed.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-1
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Deployment Tasks Before going live with the new module at the client site, there are a few tasks that must be completed. Individual project plans dictate when each of these tasks are scheduled, and those plans can and will differ from one project to the next. This section discusses some of the essential elements of a proper Deployment phase, without dictating when they occur. Although it is not the developer’s responsibility to ensure each of these tasks are completed, it is important to be aware of all these tasks.
Steering Committee Approval Conduct a final walk-through of the new module with the Steering Committee to obtain their final approval for delivery. Typically, this walkthrough is presented by key users for the user organization, as a show of their support and approval of the modifications that are in the system. Ideally the Microsoft Dynamics NAV partner is represented in this meeting by senior project team members.
Configuration Checklist Go through a checklist of all the configuration elements that must be in place before the module can be used. For the Seminar module, ensure that the various new number series are created and that the seminar setup is properly completed.
Data Conversion During data conversion, perform the transfer of existing customer data into the new Seminar module. This includes master table data as well as ledger entries and transaction documents.
Importing Document and Ledger Data There are generally three types of data that are imported into Microsoft Dynamics NAV: •
Master and/or supplemental table data
•
Transaction document data
•
Ledger data
Importing the master data is fairly straightforward, and usually does not require a large amount of code to be written.
12-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment Importing transaction documents is more complicated. Documents can be open or posted. Because of the complex nature of the header and line data, and because the amount of data per line can sometimes be beyond the limits of individual object types, it is not recommended to import open documents that are partially processed. Historical data stored in the ledger entries is usually sufficient. However, if it is necessary to import open orders, use an XML Port to import two files, one for the headers and one for the lines. To ensure that open documents post correctly, individual fields must be validated, so that information that is entered by the system is populated behind the scenes. If some orders are partially shipped, only import the portion of the order that is still open. If necessary, import historical, or posted, documents. The process for doing this is simpler because the fields do not need to be validated since they are for viewing only. NOTE: When importing historical transaction data, the most important thing to remember is to never import directly into a Ledger table. Instead, import the data into an appropriate Journal table. The journal entries can be imported into the Journal table to be reviewed and posted manually later or, they can be posted as they are imported. Notice that the validation of some fields changes the values of other fields. For instance, when the Account No. field is validated, the validation code fills in the Description field. If the Description is already imported, the imported value is lost. To solve this problem, create a global variable and put that variable's identifier into the SourceExpr property of the Dataport field rather than the actual field name. Then, after calling the validation of the Account No. field, transfer the Description from the variable to the field. Always fill in the Source Code field with a unique value for each import routine. This makes it possible to see where certain data in the journals and ledger entries came from. When importing document or ledger data, code is written to check that the data follows Microsoft Dynamics NAV business rules to initialize the records, and to fill in any missing data. No matter what the specifics are for the data import step, it is critical to thoroughly test all components of this step. Testing includes not only doing the imports, but testing subsequent processing and checking results against specifications and, if possible, against processing results in the source system.
Go Live At go live time, the system becomes available to users for normal daily transactions. After the system is up and running, pass the administration of the module over to a client manager.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-3
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Project Evaluation As the final deployment task, perform a project evaluation with the project team to assess the key aspects of the project planning and implementation. Some of the factors to evaluate are: •
Evaluation of the effectiveness and necessity of modifications made
•
Cooperation with the client and within the project team
•
Utilization of the project team skills
•
Project planning
•
“Highlights” and “lowlights” of the different project phases
•
Client satisfaction
•
Budget results, in terms of both resources and costs
Ongoing Support Phase After deployment, the project enters the ongoing Support phase. Microsoft Dynamics NAV developers perform three primary activities during this phase: •
Fixing issues that come up as the system is used.
•
Implementing new customer requirements.
•
Updating or upgrading for new releases.
Each new development project should follow the Microsoft Dynamics NAV Implementation methodology used in developing the Seminar module. An Upgrade project is an excellent example of a smaller project with a relatively predictable list of tasks. Examine what is involved in an upgrade process.
Reasons to Upgrade The customer benefits from upgrading for these reasons:
12-4
•
Access to new features: Customers can gain access to new features, such as record links and SMTP (Simple Mail Transfer Protocol) support.
•
Improvements to existing features: When a new version comes out, there are usually improvements to some features. If customers want to take advantage of one or more of these improvements, they need to upgrade.
•
Improved performance and removal of problems: Performance is improved and problems are removed with each upgrade.
•
Allow upgrades to new operating systems and hardware: For example, to be able to implement Windows Vista® as the client operating system, the version of Microsoft Dynamics NAV must be recent enough to support that platform.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment •
Better support due to being on the current version: Customers tend to receive better support when they are on the current version. As versions become obsolete, fewer people have expertise in that version.
•
An opportunity to fix up old problems, change processes, train staff: All these things could be done without the upgrade, but often are not. The fact of the upgrade provides the excuse to remediate many of the old problems.
A solution provider benefits from upgrading for these reasons: •
Better customer relations: Customer relations are built on providing services to the customer. An upgrade is an opportunity to provide a service to an existing customer that is NOT in response to a customer complaint. It also provides a chance to talk with customers and find out what new needs they may have.
•
Easier to support when the customer is using the current version: In many cases, the solution to a problem a customer has is found in a newer version. In other cases, it may be hard to support an old product when nobody at an organization can remember it.
•
Removal of problems before the customer notices them: When customers find a problem that turns out to be caused by a bug, they often want the problem to be fixed for free, and even if they get that, they may be irritated with the solution center and with the product. If an upgrade fixes a bug that customers have not run into yet, they pay for it with the upgrade, and there is one less opportunity for them to be dissatisfied.
•
Opportunities for additional sales: Microsoft Dynamics NAV often includes new features that the customer may be interested in using. However, to get these new features, the customer must upgrade, which generates service revenue. More importantly, the reengagement with the customer opens up discussions about how the customer's business has changed and the ways to use the Microsoft Dynamics NAV system to improve the customer's business.
Definitions Before discussing the types of upgrades, it is important to understand the following terms: •
Executables: The Microsoft Dynamics NAV programs that run under the operating system and include the client, the server, the C/ODBC drivers, and so on. They can be identified in the Windows Explorer as files that end with ".exe" or ".dll" file extensions.
•
Application: The application is the collection of functionalities within the product made up of the sum of the Microsoft Dynamics NAV objects.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-5
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 •
Functional Area: A module within the application, like Financial Management or Resource Planning. Functional areas can often be identified by the fact that there is a separate selection for them in the Departments area of the application.
•
Granule: A set of objects that contains a set of features. Some specialty granules are purchased and are added to the license individually, giving access to bits of functionality that are defined by the granule.
•
Feature: A small set of functions that are part of the application. The General Ledger is a functional area within the application, Account Schedules is a granule, and Date Comparison is a feature of Account Schedules.
•
Bug: A piece of the program that does not work as specified by the design. Note that if a piece of the program is not working as expected by the customer or the partner that does not make it a bug. It is only considered a bug if it does not work as designed by Microsoft.
•
Enhancement: An enhancement is when an existing feature is made to work better in some way: easier to use, faster, performing additional functions, and so on. If a feature is merely made to work as it is originally intended, then that is a bug fix, not an enhancement.
•
Add-on: An add-on is typically the addition of completely new functionality to the system. Some examples are an equipment rental module, a shipping module which integrates with shippers such as UPS and FedEx, a route management and dispatching module for a freight delivery business.
•
Upgrade versus Update: When the new product release is a major change, affecting the application logic, revising the data structure or requiring a restructuring of the infrastructure, that is generally referred to as an Upgrade. When the release is minor it is referred to as an Update. An Update can often be installed with minimal effort at minimal cost.
Upgrades and Updates Microsoft releases a number of types of upgrades to the system. These may be called patches, hotfixes, service packs, updates, or releases. What is important to an installation is the effect of the upgrade on the installation and the effort required to complete the installation upgrade.
12-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment A good way to categorize upgrades is to base it on what is required to do the installation. There are three levels of installation difficulty. •
Minimal – Just backup the system and install the Upgrade. This is the case when there is no affect on customized objects or data structure.
•
Medium – Customized objects are affected and the new objects provided as part of the Upgrade must be customized prior to installation.
•
Full Upgrade – The data structure is affected. Generally, when the data structure changes, it is likely that a volume of objects also are changed. In this case, a full-system Upgrade needs to be performed with a combination of objects upgrade, extensive testing and a fulldata conversion.
Updates The following are types of software updates which may need to be installed, and would fall into the Minimal or Medium upgrade categories because the Microsoft Dynamics NAV data structure will likely not be affected: •
Hotfix: A single cumulative package composed of one or more files used to address a problem in a product. Hotfixes address a specific customer situation and may not be distributed outside that customer organization.
•
Update: A broadly released fix for a specific problem addressing a non-critical, non-security related bug. This can include critical updates and feature packs.
•
Critical Update: A broadly released fix for a specific problem that addresses a critical, non-security related bug.
•
Service Pack: A tested, cumulative set of all hotfixes, security updates, critical updates, and updates, as well as additional fixes for problems found internally since the release of the product. Service packs may also contain a limited number of design changes and/or new features.
•
Feature Pack: New product functionality that is first distributed outside the context of a product release, and is usually included in the next full product release. Depending on the contents of the Feature Pack, the processing of implementing it could either be an update or an upgrade.
A Release is most often a scheduled product change, such as moving from Microsoft Dynamics NAV V5.0SP1 to Microsoft Dynamics NAV 2009. This type of software update is always considered a full upgrade, requiring careful planning and execution for the safe movement of current data into an upgraded system. Although the upgrade toolkit is usually released well after a new version of the main product, it is considered to be part of a release.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-7
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Upgrades Planning The most important step in the upgrade process is to plan for it in advance. Each installation of Microsoft Dynamics NAV is inevitably confronted with the need to implement an update, a hotfix, or even a full upgrade to a new version. Start this planning when making the initial implementation plans. Many times, an upgrade can be very difficult because of a decision made when first implementing the customer's system. The way that customizations are designed and developed can significantly affect the effort required to upgrade. The ease of upgrading the system at a later date should always be taken into account when design decisions are made. Throughout the implementation process, keep customers informed of upgrade considerations. Explain why a certain design may make the upgrade more difficult. When appropriate, suggest an alternative design with pros and cons, so that the customer can make an informed design decision. For example, instead of modifying the way that payment terms are implemented in the standard product, it may be better to build a completely new payment terms system that fits the customer requirements exactly. When a new Microsoft Dynamics NAV version is released, the upgraded standard payment terms can be implemented without complications, and the customer's customized system can remain intact as well. There is no overstating the importance of keeping good records of what happens and why during the implementation process. It is important to keep track of all modifications made to every customer's installation, so that: •
The appropriate decisions can be made about whether to install an improvement (update or upgrade).
•
Better estimates can be made about how long an upgrade will take.
•
Customers can be assisted to make informed decisions about whether they want certain new features.
•
It can be identified when an upgrade will override an existing customization.
Customizations As stated before, the way that customizations are developed is the biggest factor in the ability to upgrade. It is essential to follow a solid implementation and development methodology, for the success of an initial implementation, as well as any future ability to upgrade. When discussing a design to meet a certain customer requirement, it is important to consider how that design might impact the ability to perform a successful upgrade. Discuss these considerations with the customer, and explain why the ability to upgrade is affected by certain design considerations. This will give the customer the opportunity to make those types of design decisions in an informed manner, and take responsibility for the choices that are made. It will contribute to the customer’s acceptance of the initial implementation. 12-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment Using low impact programming techniques are also part of good modification design. Only make changes to the base application when necessary, and then make them in a way that is easy to upgrade. In addition, document every change. This is not optional - it is essential. A smooth upgrade is virtually impossible without knowing what is on the customer's system and why. If the customer has purchased the development tools, and they add modifications to the application without using proper methodology, that can lead to additional problems. Microsoft Dynamics NAV Partners should provide such customers with the same programming documentation and modification techniques used by the Partner. Also, encourage the customer to take the Microsoft C/AL development certification courses as well as refer them to the User Experience Guidelines for Microsoft Dynamics NAV 2009 and the Microsoft Dynamics NAV 2009 Developer and IT Pro Help.
Scheduling An upgrade plan always starts with scheduling. Once it is decided that an upgrade will be done, start planning a schedule with the customer. There are several reasons for this. •
The Microsoft Dynamics NAV Server (or SQL Server) must be stopped as a service and restarted every time an update or an upgrade is performed, no matter how small. Even if there is not an executables upgrade, there are object caches which must be refreshed. In addition, a backup must be performed before every upgrade, no matter how small. From a planning and backup point of view, treat every upgrade as though a new system is being implemented.
•
Because of the need to stop the server for a period of time, it may be necessary to install the upgrade during off-hours, or even over a weekend, particularly if there is a data conversion as part of the upgrade.
•
There are several things that can be done to relieve some of these time issues and make the upgrade less painful for the customer, but they require planning and scheduling. First, enlist the support of the customer's Information Technology (IT) Department for anything that they can do. For example, the customer's IT Department can see that the server is stopped and that backups are performed in advance. Furthermore, they can also distribute executable changes, and communicate with the users about the upgrade. Second, do as much as possible before arriving. For example, upgrade all objects, write and test the data upgrade routines, and finally test the installation. All this testing should be done with the direct involvement of the customer, having the customer sign-off on all test results. When all this is done, prepare everything at the customer's site for execution of the upgrade/update.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-9
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Upgrading the Executables If there is an upgrade to the executables (the Microsoft Dynamics NAV programs that run on the operating system), this part of the upgrade is done first. It can be scheduled separately from any other steps. For example, the executables portion of a release can be done one weekend, and the upgrades for the objects or data might not be scheduled two or three months later. Upgrading the executables on the client machines is easy, since it normally just involves de-installing the old version and installing the new version on the client machines. Of course, the more machines there are, the more time consuming this process becomes, and the need for proper scheduling increases. Ensure that remote installations and laptops are included in the executables upgrade schedule. Sometimes, the internal database structure can change. When this happens, make a Microsoft Dynamics NAV backup under the old system, and then restore from the backup after installing the new system. If the upgrade is from a two tier system to a three tier system, there are additional tasks to be addressed. The Microsoft Dynamics NAV Service Tier server must be installed and there is the possibility of additional infrastructure changes, such as another server box). Refer to the Microsoft Dynamics NAV 2009 installation documentation for additional information. The first step is to determine what is being upgraded. This can be an upgrade of the Microsoft Dynamics NAV Server and the client. Or it can also involve other executables, like N/ODBC. Often, a new customer license is required. If so, be sure to order one, and test it, before proceeding. Read the Upgrade Toolkit documentation carefully to determine what exactly is upgraded. Note that there are special instructions when upgrading the Microsoft Dynamics NAV with Microsoft SQL Server.
Microsoft Dynamics NAV Classic Server Follow these instructions if an upgrade to the Microsoft Dynamics NAV Classic Server is needed: 1. If a backup is needed, make the backup while the old system is still running. This must be a complete backup - all companies, data common to all companies, and application objects. Then have everybody log off the system, and stop the Classic Database Server. Now, make a complete backup copy of all Microsoft Dynamics NAV files (executables and database) on removable media or another device. This backup is used if anything goes wrong with the upgrade.
12-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment 2. Install the new server components. This normally involves uninstalling the old system and installing the new system. Normally, there is a client also located on the server machine. If so, and if there is an upgrade to the client executables, then those executables will need to be replaced as well. If it is possible to retain the complete old installation and install the new system on a separate system, this will provide the best possible backup. This approach allows a fallback to the old system in the simplest possible fashion. 3. If there is a new license involved in the upgrade, copy it into both the server directory (the one which contains server.exe) and the client directory (the one which contains fin.exe). 4. If a Microsoft Dynamics NAV backup is required due to a database structure change, delete the old database, bring up the Microsoft Dynamics NAV client on the server machine, and create the new database (using the same name and location as before). Restore the complete Microsoft Dynamics NAV backup into this new database. Stop the server machine client. 5. Start the server, and Start the client. Log on to the server from the client. Run a few simple tests to ensure that the system is been properly restored and that basic functionality still runs. 6. If there are executable upgrades for clients, stop the server and upgrade all of the clients. This is covered in the next section. Once this is done, restart the server.
Microsoft Dynamics NAV Clients If there are executable changes for a client, the steps are: 1. Stop the client (exit Microsoft Dynamics NAV). Uninstall the application and install the new version. 2. If there are other executable upgrades, like N/ODBC, C/FRONT, and so on, then install them now as well. The upgrade toolkit includes specific instructions. 3. If a new customer license is required, copy it into the client directory at this time. Then bring the client up. Repeat the above steps for each client machine in the installation. If there are many clients, enlist the customer's help in doing this part of the upgrade. The steps are simple, but must be repeated on each client computer. If the server executables are also being upgraded (including the Microsoft Dynamics NAV Service Tier): 1. 2. 3. 4. 5.
Stop all clients. Upgrade the server(s). Upgrade all clients. Restart the server(s). Restart all clients.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-11
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Upgrading the Objects The object upgrade is the most difficult part of any upgrade, no matter what the category of software update/upgrade. This is because the following occurs: 1. Microsoft Dynamics NAV makes worldwide changes to the application objects. 2. The regional localization team makes changes to these same application objects to localize them. 3. The partner makes custom changes to these same application objects. In fact, if customers have the design tools, they can make their own changes to these same application objects. Each regional localization team is responsible for merging Microsoft Dynamics NAV changes with the localizations for a specific set of countries. This is why it takes time between the worldwide release of a version and the local country release of that same version. Merge these changes with the changes made during customization. Following the rules for documenting customizations is always a good idea. Version tags and modification flag rules are reviewed as the upgrade steps are followed. (For a review of versioning, consult the C/SIDE Introduction in Microsoft Dynamics® NAV 2009 training manual.) The basic upgrade process is to go through each individual application object to be reviewed. For this example, use the Customer Table (18) as a stand-in for any application object. For each object, there are three potential versions. •
The old base version, which is on the distribution from which the 'old' installation was performed. It is important to document what version was installed.
•
The new base version, which is on the distribution from which the 'new' system will be installed.
•
The old customized version, which is what is currently running on the customer's system.
What is desired when the upgrade is finished is a new customized version of the object, which includes all of the customizations, plus all of the changes made for this upgrade. For each version issue, there are four options:
12-12
•
There are no changes to this object. The base object did not been changed from the 'old' base version, and no customizations are made to the object. In this case, the object on the customer's system does not change during the upgrade.
•
The object is customized, and no changes are made to the base object from the old version to the new version. Again, in this case, the object on the customer's system remains unchanged.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment •
The base object changed from the old version to the new version, but this object is not customized. In this case, the new base object replaces the object on the customer's system.
•
The possibility that causes the problems - customizations are made to the object, and the base object also changed. In this case, both changes will need to be merged into the new customized version. One way to merge objects in this case is to first determine which version changed the object the most, and use that version. Then, change that object so that it includes all of the changes made by the other version. Following are two examples: o
o
Example 1: The new base object contains more changes than those made during customization. In this case it is easiest to start with the new base object, then apply the customizations on that object, and then replace the object. Example 2: The customizations made contain more changes than those for the new base object. When this happens, start with the customized object from the customer system, and apply the changes in the base object to that object.
A Typical Upgrade Go through the typical steps to upgrade objects. In this situation, a few small changes are made for the customer. Assume that all of the recommendations for version tags are followed –all modified objects are tagged with an additional version tag (use CR01), and that all modification flags are turned off. In addition, the customer has no design tools; therefore, it is not necessary to go to the customer site to pick up the objects, since the customer has not changed them. A copy of the customer's database is kept in-house. This copy just has objects, with either no data or minimal (CRONUS) test data. There may also be a copy of the target version application. In most installations, customers will at least have purchased one of the designer granules. Most customers have the report and form designers in their license, and there may be extensive modifications made by the customer. The version list and “modified flag,” are unreliable attributes to determine whether an object is modified. In most cases, to determine the true extent of a customer’s modifications, an object upgrade must involve at least one pass through the code of all objects, comparing the production system to the code of the ‘old’ base version, line by line, marking all modified objects accordingly. The method described in this section is just one example of how to perform an object upgrade. In addition to this method, other methods might be used. There is no real “best way” to do it, since this depends largely on the developer’s preferences and his or her choice of tools.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-13
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 Step by Step 1. Make a working copy of the customer's database (objects only). Create a Microsoft Dynamics NAV backup, create a new database, and then restore application objects only. At this point, the database is created with the new executables, and contains the old customized objects. Call this database TARGET. 2. Get the base objects from the new version's base database. a. To do this, go into the Object Designer and click the All button. b. Then put the cursor in the Version Tag column, and set a filter to the localized code for the new version, as well as the new W1 base version tag. This filters out all but the modified base objects. c. Then select all objects (Ctrl+A) and export. Export as a Microsoft Dynamics NAV object file, with an extension of .fob. 3. Go back into the TARGET database and import the object file into the Object Designer. Normally, there will be conflicts, but even if there are not, bring up the Object Import Worksheet anyway. Check all of the objects, find the conflicts, and write down the object type and ID in a conflict list. NOTE: It is possible to copy the list from the import worksheet into Excel. Skip any objects that have a conflict for this step. For the remaining objects, there is no conflict, and the new objects simply replace the old ones since the old ones are not customized. 4. Review the four possibilities again: a. First, an object might not have changed in either the customized version or the new base version. In this case, only the changed objects are imported, so the object did not import. These do not show up in the Import Worksheet. b. Second, the object might only have changed in the customized version, but not in the new base version. In this case, the object is not imported, since only new base objects are imported. Again, these do not show up in the Import Worksheet. c. Third, the object might have changed only in the new base version, but not in the customized version. These objects are in the Import Worksheet, but they show up with no conflicts. They can just be imported. d. Fourth, the object might have changed in both the customized version and the new base version. These objects are in the Import Worksheet. In this case, they show up with a conflict. Skip these objects (do not import them) and write them down in a conflicts list.
12-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment 5. Review the conflicts list. a. Look up each object in the conflicts list in the change log, the documentation that describes the changes that came with the new version. Remember to check all the improvements, since it might be modified more than once. b. Look at the change log in the Latest Improvements page, where they are all together in one log, and start at the bottom with the version in the Import Worksheet. This makes all of the changes easier to find. 6. For each object in the Conflicts List, consider if the upgrade modification is small. More to the point, is it smaller than (or even almost as small as) the change made for the customization? If the answer to this question is yes, then use the change log that came with the new version to implement the improvement on the customized object in the working copy database. If the answer to this question is no, then import the new base object into the working copy database, and then use the change log to implement the customization on the new base object. If there is no change log, use the compare tool, such as that in the Microsoft Dynamics Developer's Toolkit, which will create a change log. This makes it easier to decide which change is smaller. Either way, set the version tag to reflect both new versions. This shows both the new localized version tag and the customization version tag. There is one exception to these rules. If this is a table object, the upgrade may have added a new field in a number range that is not allowed in the developer license that is used for the upgrade. In this situation, if at all possible, import the object and then implement the customization on the new object using the change log. If this is not practical, the only alternative is to set the action to "Merge Existing<-New" and import the new base object. This brings in the new field(s). Then, apply the remainder of the change log. 7. Complete step 6 for every object in the conflicts list. 8. As an optional step, change the version that is displayed on the Help About screen. Note that this step is optional only for an improvement. If this is a Service Pack or a minor or major release, this step must be performed. In the Object Designer, open codeunit 1 and look for the function called ApplicationVersion. Change the displayed version to the new version to display, reflecting the latest base version tag in all the objects. Change the text between the single quote marks to this text. After updating codeunit 1 and saving it, update the version tag of this object as well, to the same version as put in those quotes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-15
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 9. The next step is to compile all objects. Do this to ensure there are no conflicts with existing objects that show up. In the Object Designer, click the All button, select all objects, and press F11 to compile them. When done, any objects that did not compile are marked. These can be viewed with View, Marked Only. 10. Now, create the Upgraded Objects file. In the Object Designer, click the All button, and then filter the Version Tag column. Once this is done, clear all the Modification Flags. 11. Select all the filtered objects (use Ctrl+A) and export them as a Microsoft Dynamics NAV Object File, a file that has the extension .fob. This is the Upgraded Objects file. 12. Install the Upgraded Objects on the customer site. First, bring this file to the customer site. When the objects are loaded, especially table objects, sometimes tables are automatically converted or rekeyed, which takes a long time when there is a large amount of data. At the customer site, stop the server. Make a backup copy of the database (enlist the support of the customer's IT Department for this step). Start the client that is located on the Server Machine, and open the customer's database in Local mode. Now go into the Object Designer and import the Upgraded Objects .fob file. Remember, even if there are now conflicts, they are already resolved. Therefore, when the Import Worksheet is displayed, just click the Replace All button, and then do the import. Once this is completed, compile all objects, and then stop the local client. Restart the server, and the customer can continue working on the newly upgraded system. In most situations, the upgrade process will first be done on a copy of the production database, so that the customer can perform an acceptance test of the new upgraded system. The production database should not be upgraded until after the customer signs off on the upgraded test system. This testing phase is an absolutely critical part of the upgrade process.
Tools for Upgrading the Objects Microsoft Dynamics NAV provides several tools to help with performing upgrades. Each one may be best for different circumstances.
Import Worksheet The Import Worksheet can be a useful tool. It is the best tool for rapidly determining object conflicts. It can also be used to add new objects and fields in the base number ranges that there are no permissions for. It is the best tool to use to install the upgraded objects on the customer's system. It is important to understand the limitations of the Import Worksheet. It is not always completely accurate in assessing object conflicts, and it does not always catch all conflicts.
12-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment The only way to determine in any truly reliable way whether there are any differences between two objects is to compare the objects manually or by using a tool to compare objects.
Microsoft Dynamics NAV Developer Toolkit Microsoft provides the Microsoft Dynamics NAV Developer Toolkit to perform a number of tasks. One of the most powerful tools is the where-used-analyses for objects and their attributes. In addition, it also includes compare and merge functionality. Given the fact that this is all done automatically, and it is subject to automated interpretation of differences, it is recommended every difference be manually reviewed to ensure that the merge process provides a satisfactory result.
External Text Compare Tools The most reliable way to merge objects together is by using a tool to compare the object in text format and merging the differences manually. There are a number of commercially available text compare tools, as well as a number of open source tools. But the Microsoft supported tool set is the Developer Toolkit.
Developer Experience The single most important tool for upgrading objects is the developer’s experience. It takes practice and experience to understand the structure of objects, and even more practice and experience to determine how to deal with individual object differences.
A Major Release When a major release is merged with extensive customization, there is a high probability that object conflicts will be found. The more object conflicts found, the higher the probability that changes in base version and customizations are not merged quite properly. Manual review of code and testing are required to identify and resolve such issues. When planning, include sufficient time to test the upgraded system. Make sure that there are no obvious problems. Use the customer license to do the testing. This assures that the tests faithfully replicate the customer's operating environment and also checks for problems in the new license. Test the object upgrade on a copy of the complete customer database (including data). One particularly difficult situation is when the new base version includes a major functionality change that conflicts with a customization made in the same functional area. Sometimes this happens when a modification is made to the way a function is accomplished, and sometimes because a certain functional area is completely redesigned by Microsoft. The change can be so major that the changes cannot be merged, either with the merge tool or manually. If this is the case, re-implement the customization from scratch in any object where there is a conflict. This will satisfy the customer's requirements by means of reimplementing on top of the new base object rather than merging from the old customizations.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-17
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 It is also important to re-evaluate the relevance of the customization when moving to a new version. Perhaps Microsoft Dynamics NAV has added a feature that could replace all or some of the customization. Perhaps the customer's business processes have changed. Before upgrading, review the customization's functionality and discuss with the customer which parts will be upgraded. If a customization does not interfere with the operation of the upgraded system, it is often safer and more cost effective to move the customization into the new version during the upgrade process. This makes testing easier and also has the effect of minimizing design changes in the course of the upgrade. Then, after the upgrade is complete and operating satisfactorily, the now obsolete modifications can be removed and customer processes changed to fit the standard Microsoft Dynamics NAV data flow.
Field Name Changes When major field name changes are made, these changes ripple down into every other object that refers to the changed field, at least in any automatic change log generated. This can create huge change logs where in fact there is no actual change to many objects. When a field name is changed, it is changed automatically on the card form, on the list form, on reports, and so on. However, when an automatic change log is generated, it shows that the card form changed, the list form changed, the reports changed, and so on. This makes it harder to do upgrades for developers who like to use an automatically generated change log. The solution is to make the field name changes first. Before extracting the new base objects from the new database, make the customized field name changes to the tables only. For any object being updated, be sure the modified flag is checked, even if just changing the table name. When extracting the new objects, get all objects whose Version Tag or Modified Flag changed. Use the Marking facility to do this. First, filter all objects with a Modified Flag on, select all of them, and press Ctrl+F1. Then, remove that filter, filter on all objects with the new Version Tag, select all of them, and press Ctrl+F1. Now, remove that filter, use View, Marked Only, and then select all filtered objects.
Customer has Design Tools If the customer has Design Tools, it may be that the customer does not follow the same development rules the partner follows. These include rules about setting the Version Tags and Modification Flags, internal object documentation, developing on line, and using a project log. When a customer does not follow standardized development rules, it is often very difficult to tell what changes are made and why they are made. There are two ways to forestall this problem. First, work with the customer to help them agree with a set of development rules. Explain how following those rules makes upgrading easier. Customers are generally eager to do anything that they can do to help lower the development bill, now and later. If a set of development rules is too complex, just get them to follow one rule: leave the Modification Flags alone. This rule is easy to follow, since it does not require the customer to do anything.
12-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment The second part of the solution is that certain steps in the upgrade process will be changed. Be sure to create a new database and restore the application objects only from the Microsoft Dynamics NAV backup obtained from the customer site. After this, go through and give the customer's changed objects (the ones with the Modification flag on) their own additional Version Tag, something different from the version tag. Use new letters, based on the customer name. For example, if Cannon Group is the customer, make their Version tag CG0, and then add a "CG01" at the end of every modified object with an existing version tag. If the customer created a new object, set the Version tag to "CG01." Before starting the object upgrade, make sure that the following essential elements are in place: •
The latest objects from the customer’s system are available, and these objects all compile. Resolve all compilation errors before starting the object upgrade.
•
Take a full backup of the customer’s production database. This is the baseline for the object upgrade.
•
The customer and the partner agree to a complete freeze in development until the upgrade is completed.
For step 6, which is described in the section titled "A Typical Upgrade" (updating each object on the conflicts list), take into account customer changes. At the least, generate a new change log from the working copy. After compiling all objects, but before exporting, schedule time for the customer contact to come in and check out the upgraded system. It is easier to see if a customer change was lost this way. Finally, when exporting the objects, be sure to get all objects with either the new base Version Tag, or the customer's new Version Tag. Use the marking technique to do this. The rest of the steps are the same.
More Than One Upgrade to Do Here is a common situation. The customer has not upgraded for a while, and has skipped a release and two service packs. Now, with the latest release, the customer sees a feature the customer wants, and the customer wants to be upgraded. The problem is that there is no direct upgrade path except from one version to the next version. The solution requires multiple upgrades at once. Simply do the upgrade steps 2 through 10 (which are described in the section titled "A Typical Upgrade") for each upgrade version in between. Once upgraded to the final version, remember to export all objects with any version tag higher than what the customer had, so the customer gets all changed objects.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-19
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 However, data upgrades are usually too complex to combine. Therefore, schedule a separate upgrade for each data upgrade needed. This usually corresponds to a release. When combining object upgrades, export the modified objects for each data upgrade. Note that technically, all the data upgrades can be done at once, even if they are not combined. It is highly recommended that thorough testing be performed between data upgrades if the data upgrades at the customer site are to be combined.
Data Upgrade Data upgrade is usually necessary every time there is a release. It is rarely needed with an update. Data conversion routines (usually codeunits) are included in an Upgrade Toolkit which is generally released a few weeks after release of the product. Take advantage of this time lag to become familiar with the new product and any new features. When the data conversion routines are available, try not to modify them. It is best if any new data conversion routines needed due to customizations can be written separately, and then run in series after the ones provided by Microsoft. However, occasionally, it is necessary to modify the data conversion routines, because otherwise they do not work with the customizations. This step requires care. Write (or modify) data conversion routines at the same time as creating the upgraded objects are being created. However, these routines must be run on the customer site for the customer's live data to be upgraded.
Preparation There are some additional steps to prepare for a data upgrade. First, when making the working copy, make an additional copy to use to create the phase one conversion objects. Phase one objects must be created using the old, un-upgraded database. When the upgrade of the objects is complete, make another copy of the database, this one to be used to create the phase two conversion objects. Phase two objects must be created on a new, upgraded database. Also, create a complete copy of the customer's database. This is for testing the upgrade process. Get the customer database from the customer site so that the data is complete and current.
The Conversion Process The conversion process is highly dependent on the particular configuration of the system and the old and target versions involved. The Upgrade Toolkit provides the steps involved for each possibility. Please note that all of these steps outlined in the Upgrade Toolkit can take a significant amount of time, especially if the customer has substantial data. Gauge the amount of time when doing the test run. Be sure that the customer can be down long enough for the entire database and object upgrade. This work will probably be done on weekends or holidays.
12-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment
Summary The Seminar Management module has deployed successfully, and all preparations for the ongoing maintenance phase are also ready. The client has identified some additional requirements, which can be found in Appendix A, Additional Exercises, but the project is now complete.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-21
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. List four essential preconditions for deployment
2. Which three types of data are generally imported into Microsoft Dynamics NAV?
3. List four reasons to upgrade Microsoft Dynamics NAV
12-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment 4. What can be done to minimize the impact of customizations to the ability to perform a full object upgrade?
5. What are the two general types of upgrades?
6. What are the general steps to perform a technical upgrade?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-23
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 7. What three versions of the database objects are needed to create the new customized database?
8. Which tool is used to perform the data upgrade?
12-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment
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
12-25
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. List four essential preconditions for deployment MODEL ANSWER: Essential preconditions include: • The new solution is fully developed • The new solution is fully tested and approved by the customer • Errors are identified and resolved • Documentation is updated to reflect the current state of the solution • The infrastructure to support the new solution is in place • The users are trained to use the new solution • User documentation is completed and ready to be used 2. Which three types of data are generally imported into Microsoft Dynamics NAV? MODEL ANSWER: • Master data (Items, Customers, Vendors, and so on) • Supplemental data (Prices, Units of Measure, and so on) • Transactional data (Sales, Purchases, Inventory, and so on) • Ledger data, although it is preferred to import data into journals and post those journals 3. List four reasons to upgrade Microsoft Dynamics NAV MODEL ANSWER: • New system features • Improvements to existing features • Removal of problems • Improved performance • Support for new operating systems and hardware • Better support for the current version • An opportunity to clean up old problems, change processes, train staff
12-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: Deployment 4. What can be done to minimize the impact of customizations to the ability to perform a full object upgrade? MODEL ANSWER: To minimize the impact of customizations on the ability to upgrade, customizations must be designed in such a way that they have the least significant impact on the way that standard functionality works. Instead of changing the way that the application works, customizations should be designed to expand on standard functionality as much as possible. 5. What are the two general types of upgrades? MODEL ANSWER: The first type of upgrade is the executable upgrade, or “technical upgrade”. The database objects are left intact, without modifications, and only the program files are upgraded to a newer version. The second type of upgrade is a full upgrade, also referred to as an “object upgrade.” This includes a technical upgrade, and also includes an effort to implement the database objects of the new version, by merging objects from the new version with customizations that are made to the old version. 6. What are the general steps to perform a technical upgrade? MODEL ANSWER: • Close all clients • Bring down the database (after taking a full backup) • Uninstall the old version of the server and install the new version • Start the new server back up and convert the database • Uninstall the old version of the client software on all clients and install the new versions • Start the new clients 7. What three versions of the database objects are needed to create the new customized database? MODEL ANSWER: • The uncustomized base objects of the old version • The customized objects of the old version, which are the objects from the customer’s production system • The uncustomized base objects of the new version
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-27
C/SIDE Solution Development in Microsoft Dynamics® NAV 2009 8. Which tool is used to perform the data upgrade? MODEL ANSWER: The Upgrade Toolkit is used to perform the data upgrade. It might be necessary to create additional logic to the Upgrade Toolkit to address customized data.
12-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement