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!
; END ELSE BEGIN ; END;
This lesson will describe a number of typical scenarios from Classic reports that require design changes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-3
Report Design in Microsoft Dynamics® NAV 2009 Redesign Section Triggers Verify that the report does not have code on any section triggers. If a report does have code on a section trigger, determine how to achieve the same functionality by moving or modifying the code or by using new report layout functionality:
Code that evaluates the visibility of a section These occurrences can often be replaced by adding a variable on the request page and using an expression that includes this variable in the Visibility property of the table row or control.
Code that evaluates the format of controls Code that evaluates the format of specific controls can be replaced by using expressions in different properties and property collections: BackgroundColor, Color, Font, Size, and TextAlign.
Code that calculates information In this case you can move the code into a separate function in the Classic report or even in the RDLC layout. The following code example shows a function that calculates percentages. Shared Pct as Decimal Public Function CalcPct(Amount1 as Decimal, Amount2 as Decimal) as Decimal If Amount2 <> 0 Then Pct = Amount1 / Amount2 * 100 Else Pct = 0 End If REM Rounding precision = 0.1 Return ROUND(10*Pct)/10 End Function
If adding the function to the RDLC Layout, remember to set the Value property of the textboxes that use the function to the following expression: =Code.CalcPct(AmountParameter,ProfitParameter).
Check the Value of Printed Variables In a Classic client report layout, when a Boolean value appears on a report, the value is printed as "yes" or "no" in the target language. In a client report definition (RDLC) report layout, when a Boolean value appears on a report, the value is printed as "true" or "false" in the target language. In some cases, you may want to change the printed value of a Boolean variable in an RDLC report layout to "yes" or "no" instead of "true" or "false." For example, you may have Classic and RDLC report layouts and require the same wording in both layouts.
3-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report This can be achieved in two ways: either you change the SourceExpr property of the textbox showing the Boolean variable to FORMAT(BooleanVariable), or you set the Value property of the textbox in the RDLC report layout to an expression like =IiF(Fields!BooleanVariable.Value = False, "No", "Yes"). The same applies to Date values. When creating a client report definition (RDLC) layout for a report, you must modify date values so that they are formatted correctly. You can use a similar procedure as for the Boolean variables to verify or change the format of a date. Either you set the format in the classic report using the FORMAT() instruction, or you can use an expression to define the format of the date yourself. Date formats defined in the Classic design will overrule date formats specified in Visual Studio.
Check Option Fields In the Classic client you can use both the numeric value and the text representation to check the value that is selected for an option variable. Be aware that the RDLC report layout does not provide this functionality: strings will be handled as normal strings. It is highly recommended to work with the numeric value of the option variables in the RDLC report layouts, so that multi-language functionality will not be an issue.
Working with Report Expressions Expressions are widely used in a report for various purposes. They can be used for data manipulation (retrieve, calculate, format, group, sort and filter data) and formatting purposes. In SQL Server Reporting Services and also in client-side reporting, expressions are used to provide dynamic flexibility for controlling the content and appearance of a report. In most cases, expressions are used to get the following kinds of functionality in your report: •
Aggregations on data to show the sum, average, percentage, or product of a particular row set.
•
Conditional formatting, where text or background formatting changes based on logic you define.
•
Conditional text, where a report title varies depending on who is running the report.
•
Concatenated text from multiple dataset fields and constants.
•
Data filtering (after it is retrieved from the data source).
•
Data grouping and sorting.
•
Dynamic page header and page footer content.
On the report design surface, expressions appear as simple or complex expressions.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-5
Report Design in Microsoft Dynamics® NAV 2009 Simple expressions contain a reference to a single dataset field or built-in field. Simple expressions are created for you automatically (for example, when dragging a field from a dataset onto a text box), or you can type them directly into a data region cell or text box on the design surface. Complex expressions can contain multiple built-in references, operators, and function calls combined with simple expressions. An expression is written in Microsoft® Visual Basic®. An expression begins with an equal sign (=) and consists of references to dataset fields, constants, operators, functions, and other built-in report collections. During report processing, each expression evaluates to a single value that replaces the expression when a report is rendered. Knowing how to create and use expressions is a fundamental skill that will enable you to create rich full-featured reports.
How to Create Expressions You can create expressions in a report definition in two ways: either by using the Expression window, or by typing the expression syntax directly into a textbox, a property in the Properties window, or a group, sort and filter expression field. Using the Expression window has many advantages over manually entering the expressions. Apart from a large work area, it offers context-sensitive global collection item choices, statement completion, and syntax checking. Expressions are created using Microsoft Visual Basic language syntax. You can create expressions either by entering the expression manually or by composing an expression in the Expression window. In this window you can use a number of built-in collections to create your expressions.
3-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The Expression Editor When you open the Expression window, the following dialog box is displayed.
FIGURE 3.1 THE EXPRESSION WINDOW
The Expression window can be used to add and edit expressions. It is divided into a number of panes. The top pane, the expression pane, shows the current expression for the selected textbox or property. You can edit the expression in the pane by using the keyboard and by double-clicking items in the bottom panes. The bottom middle pane, the Item pane, contains all items that are available in the selected category. The contents of the pane are updated whenever a new category is selected in the Category pane. For example, the Globals category contains items such as ExecutionTime, UserId and Language. At the right side you can have one big pane, the Field pane, or two smaller panes (the Description and the Example pane). Which panes appear depends on the selected Category. The Field pane contains all elements that are available in the selected Item and Category. The contents of the Field pane are updated whenever you select a new Item. If the selected Item does not contain any fields, the Field pane will be replaced by the Description and Example panes. The Description pane shows a description of the selected Item, while the Example pane displays an example of the selected item.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-7
Report Design in Microsoft Dynamics® NAV 2009 For example, when selecting the Program Flow category (under Common Functions), the Item category will show the three functions in the category. The Description pane will show a small description of the selected Item, and the Example pane illustrates the syntax of the selected function. When building an expression, you can double-click any element in the bottom panes to have it inserted automatically in the expression pane. As the expression pane suggests, expressions can be built further using Microsoft Visual Basic language syntax. The expression pane supports features such as IntelliSense, statement completion, colored syntax and syntax checking, so that you can easily detect syntax errors. You can move and resize the Expression Editor to have a larger work surface. In some windows (for example, on the Sorting tab in the Table Properties window) you can create multiple expressions that will be combined during report processing. However, the Expression window allows you to edit only one expression at a time.
Accessing the Expressions Window The Expression editor can be accessed in various ways, depending on the current position in the Visual Studio Report Designer. You can open the Expression Editor for the following items:
3-8
•
A text box on a report.
•
A property in the Properties page.
•
A Groups tab on data region properties.
•
A Sorting tab on data region properties.
•
A Filter tab for datasets, data regions, or data region groupings.
•
A document map label on a data region group.
•
A parent group on a data region group.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report On the design surface, you can right-click any textbox control and select Expression, as shown in the following figure.
FIGURE 3.2 THE EXPRESSION WINDOW
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-9
Report Design in Microsoft Dynamics® NAV 2009 Several properties in the Properties window, such as Visibility, BackgroundColor and Value, support both fixed options and expressions as a first option in the drop-down list. Select <Expression> in the drop-down list to enter an expression in the Value column for a property.
FIGURE 3.3 THE PROPERTIES WINDOW
Expressions can also be entered in various dialog boxes such as the Grouping and Sorting Properties and the Table Properties window. In these windows, expressions can either be selected directly from a drop-down list, or they can be entered by clicking the fx button to set specific properties. For example, in the Table Properties window, on the General tab, the fx button is available to define Tooltips.
Valid Expression References The previous section explained that you can build an expression using a variety of functions from different built-in categories. In Chapter 2, you already worked with the ReportItems collection. The following table shows the types of references that you can include in a report expression.
3-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The table indicates which of these references are built-in, and which references you must identify to the report processor so that the function calls can be resolved during report processing. Items
Description of functions and how to reference them
Reporting Functions
Built-in. Functions that provide aggregate values on report items, and other utility functions that support aggregation. The Aggregate implementation is supplied by each data provider.
Reporting Collections
Built-in. Globals, User, Fields, ReportItems, Datasets.
Custom Code
Built-in. Add your Visual Basic code through the Report Properties menu, Code tab. You can define public constants, variables, subroutines, and functions for your use in each report definition.
Visual Basic Run-time Library
Built-in.
System.Math
Built-in.
System.Convert
Built-in.
.NET Framework (common language runtime) Classes
Add fully qualified references in your expression. For example, System.Text.StringBuilder.
Besides using the built-in functions, you can add additional functions to your report, by adding code or external references to your report. To add custom code to your report, select Report, and then select Report Properties in Visual Studio Report Designer. On the Code tab, you can add the custom code (variables, functions, procedures, and so on) to enrich your report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-11
Report Design in Microsoft Dynamics® NAV 2009 When you open Visual Studio Report Designer to create a report for the RoleTailored client, a number of functions are automatically added to the Code tab.
FIGURE 3.4 THE CODE TAB OF THE REPORT PROPERTIES WINDOW
The functions that are added all relate to presentation and formatting of data. Functions that are part of the Classic report layout are not converted automatically to functions on the Code tab. Although you can add any code to the report using the Code tab, it is highly recommended not to include code that is part of the report's business logic. If the report is used by both Classic client and RoleTailored client users, you will have to duplicate the code and it then becomes more difficult to maintain the source code. Expression always start with the "=" sign. This indicates that the statement following the equal sign is an expression that will be evaluated by the reporting engine. Most expressions consist of a single constant value. For example, the FontName property of a textbox can have a number of constant values, such as Arial, Tahoma, Verdana, and so on. The Width property is less restrictive: the values are not predefined. You can also use a combination of functions, variables and constants to build a more complex expression. To refer to a collection or element from an expression, use the standard Visual Basic syntax. For example, to refer to the value of a specific field (in the Fields collection), use the =Fields("FieldName").Value expression. An alternative way of referencing the same value is to use =Fields!FieldName.Value. In this case the (parent) collection and the (child) element are concatenated by an exclamation mark. An element and its properties are always separated by a "." (period). Syntax errors are detected and indicated automatically. However, syntax errors do not keep you from importing the RDLC data into Microsoft Dynamics NAV.
3-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report When you try to save and compile the report in the Object Designer, some errors in the RDLC report layout might be indicated. For example, if a wrong syntax for the IIF() statement is used, or if the Value property of a textbox in the Page Header section is set to a data field from the dataset, you will get an error message. Other errors might appear when the report is run. NOTE: Apart from the items in the table above, it is also possible to add custom assemblies and classes to reports. However, only trusted managed assemblies are supported. More information on creating trusted managed assemblies can be found on http://msdn.microsoft.com.
Understanding and Using Simple and Complex Expressions The previous lesson described how expressions are widely used in reports for various purposes. Knowing how to create and use expressions is a fundamental skill that will enable you to create rich full-featured reports. This lesson will describe the different data collections that can be used in expressions.
Using Constant Collections in Expressions The Constants collection is mostly used in simple expressions. Simple expressions consist of the "=" sign, followed by a single value. They are often used to set properties throughout the report. The content of the Constant category depends on the selected property. When you select the Color property of a text box, it contains the possible colors. When you select the Hidden property (in the Visibility property collection), the category contains two constants: True and False.
Using Global Collections in Expressions Reporting Services provides the following global collections that you can reference from expressions: Constants, DataSets, DataSources, Fields, Globals, Parameters, ReportItems, and User. (Since the RoleTailored client uses clientside reporting, the Parameters and DataSources collections will either always be empty or not available in Visual Studio Report Designer.)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-13
Report Design in Microsoft Dynamics® NAV 2009 The following table describes each global collection and notes when you can reference the collection from an expression. Global Collection
Description
Fields
Represents the collection of fields of the dataset that are available to the report. Available after data is retrieved from Microsoft Dynamics NAV into the dataset.
ReportIte ms
Represents the collection of text boxes for the report item, such as the text boxes contained within a table data region, page header, or page footer. Available during report processing.
User
Represents a collection of data about the user running the report, such as the language setting or the user ID. Always available. User!UserID is frequently used to filter results in reports. User!Language is used to make specific settings dependent on the language of the user.
DataSets
Represents the collection of datasets referenced from the body of a report definition. Does not include data sources used only in page headers or page footers.
Globals
Represents global variables useful for reports, such as the report name or page number. Always available.
The next lesson describes in more detail some of the frequently used functions.
Using Report Functions in Expressions ReportViewer provides built-in functions that you can use in report expressions. Built-in functions can be used in expressions that you include in client report definition (.rdlc) files and in report definition (.rdl) files that are processed on a SQL Server Reporting Services report server. Support for the functions is provided by the ReportViewer controls and Reporting Services. You can use built-in functions within expressions to manipulate the data within report items, properties, and other areas in the report. Built-in functions are used to aggregate data in datasets, data regions, and groups, and return other data. You can use aggregate functions in expressions for any report item. All data used for an aggregate calculation must be the same data type. To convert data that has multiple numeric data types to the same data type, use conversion functions like CInt(), CDbl() or CDec().
3-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The following table describes the aggregate functions that are supported by Reporting Services. Function
Description
Aggregate
Returns a custom aggregate of the specified expression, as defined by the data provider.
Avg
Returns the average of all non-null values from the specified expression.
Count
Returns a count of the non-null values from the specified expression.
CountDistinct
Returns a count of all non-null distinct values from the specified expression.
CountRows
Returns a count of rows within the specified scope.
First
Returns the first value from the specified expression.
Last
Returns the last value from the specified expression.
Max
Returns the maximum value from all non-null values of the specified expression.
Min
Returns the minimum value from all non-null values of the specified expression.
RowNumber
Returns a running count of all rows in the specified scope.
RunningValue
Uses a specified function to return a running aggregate of the specified expression.
StDev
Returns the standard deviation of all non-null values of the specified expression.
StDevP
Returns the population standard deviation of all non-null values of the specified expression.
Sum
Returns a sum of the values of the specified expression.
Var
Returns the variance of all non-null values of the specified expression.
VarP
Returns the population variance of all non-null values of the specified expression.
Reporting Services provides the following additional aggregate functions that you can use within expressions. Function
Description
InScope
Indicates whether the current instance of an item is within the specified scope.
Level
Returns the current level of depth in a recursive hierarchy.
Previous
Returns the previous instance from the specified scope.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-15
Report Design in Microsoft Dynamics® NAV 2009 Each aggregate function uses the Scope parameter, which defines the scope in which the aggregate function is performed. A valid scope is the name of a grouping, dataset, or data region. Only groupings or data regions that directly or indirectly contain the expression can be used as a scope. For expressions within data regions, Scope is optional for all aggregate functions. If omitting the Scope parameter, the scope of the aggregate is the innermost data region or grouping to which the report item belongs. •
Specifying a scope of Nothing sets the scope to the outermost data region to which the report item belongs.
•
For expressions outside of data regions, Scope refers to a data table or business object.
•
If a report contains more than one dataset, Scope is required.
•
If a report contains only one dataset and Scope is omitted, the scope is set to the dataset.
•
The Nothing keyword cannot be specified for report items outside of a data region.
•
The Scope parameter cannot be used in page headers or footers.
Expression Examples Expressions are frequently used in reports. These include expressions to change the appearance of data in a report, change properties of report items, and affect how data is retrieved (filtering and sorting expressions). Many expressions in a report contain functions. You can format data, apply logic, and access report metadata using these functions: •
String Functions
•
Date and Time Functions
•
Conversion Functions
•
Decision Functions
•
Report Functions
This lesson describes some expressions that can be used for common tasks in a report.
String Functions String functions can be used to manipulate string values in a report. You can use a number of functions to do the following tasks:
3-16
•
Concatenate fields and constants by using concatenation operators and Visual Basic constants.
•
Format dates and numbers.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report •
Return substrings.
•
Change the format of strings.
Concatenate Fields and Constants by Using Concatenation Operators and Visual Basic Constants The following expression returns two fields, each on a separate line in the same text box:
=Fields!FirstName.Value & vbCrLf & Fields!LastName.Value
Format Dates and Numbers Format dates and numbers in a string with the Format() function. The following expression displays values of the StartDate and EndDate fields in long date format:
=" Between " & Format(Fields!StartDate.Value, "D") & " And " & Format(Fields!EndDate.Value, "D")
If the text box contains only a date or number, use the Format property of the text box to apply formatting instead of the Format function within the text box.
Return Substrings The Right(), Len(), and InStr() functions are useful for returning a substring, for example, trimming DOMAIN\username to just the user name. The following expression returns the part of the string to the right of a backslash (\) character from a report global named UserID:
=Right(User!UserID, Len(User!UserID) - InStr(User!UserID, "\"))
Change the Format of Strings The Regex functions from the .NET Framework System.Text.RegularExpressions are useful for changing the format of existing strings, for example, formatting a telephone number. The following expression uses the Replace function to change the format of a ten-digit telephone number in a field from "nnn-nnn-nnnn" to "(nnn) nnn-nnnn":
=System.Text.RegularExpressions.Regex.Replace(Fields!Phone. Value, "(\d{3})[ -.]*(\d{3})[ -.]*(\d{4})", "($1) $2-$3")
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-17
Report Design in Microsoft Dynamics® NAV 2009 Date and Time Functions Date functions are used to analyze and format a date in a report. To format a date, you can either select a predefined format or define a custom format yourself using a number of date and time functions, such as : DatePart, Year, Month, MonthName, Day, Weekday, WeekdayName, Hour, Minute, Second. You can also perform date calculations (using functions such as DateDiff() and DateAdd()) and convert a string to a date using CDate(). Now() returns a Date value containing the current date and time according to your system.
Examples The Today function provides the current date. This expression is used in a text box to display the date on the report, or in a parameter to filter data based on the current date. =Today()
The DateAdd() function is useful for supplying a range of dates based on a single parameter. The following expression provides a date that is six months after the date from a field named StartDate. =DateAdd(DateInterval.Month, 6, Fields!StartDate.Value)
The Year() function displays the year for a particular date. You can use this to group dates together or to display the year as a label for a set of dates. This expression provides the year for a given group of sales order dates. The Month() function and other functions are also used to manipulate dates. For more information, see the Functions (http://msdn.microsoft.com/enus/library/3ca8tfek(VS.85).aspx) topic in the Visual Basic documentation. =Year(Fields!OrderDate.Value)
Conversion Functions You can use Visual Basic functions to convert a field from one data type to a different data type. Conversion functions are used to convert the default data type for a field to the data type needed for calculations or to combine text. Examples are CInt, CStr, CDate, CDec, CDbl, CBool, CLng, CSng, CShort. The following expression converts the constant 500 to type Decimal: =CDec(500)
3-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Decision Functions Decision functions allow evaluating a logical or relational condition and return a specific value based on the result of the evaluation. The IIF() function returns one of two values depending on whether the expression is true or not. The following expression uses the IIF() function to return a Boolean value of True if the value of LineTotal exceeds 100. Otherwise it returns False: =IIF(Fields!LineTotal.Value > 100, True, False)
You can use multiple IIF() functions (also known as "nested IIFs") to return one of three values depending on the value of PercentCompleted. The following expression can be placed in the fill color of a text box to change the background color depending on the value in the text box. =IIF(Fields!PercentCompleted.Value >= 10, "Green", IIF(Fields!PercentCompleted.Value >= 1, "Blue", "Red"))
Values that are greater than or equal to 10 display with a green background, values between one and nine display with a blue background, and a value that is less than one displays with a red background. A different way to get the same functionality is to use the Switch() function. The Switch() function is useful when you have three or more conditions to test. The Switch() function returns the value associated with the first expression in a series that evaluates to true: =Switch(Fields!PercentCompleted.Value >= 10, "Green", Fields!PercentCompleted.Value >= 1, "Blue", Fields!PercentCompleted.Value = 1, "Yellow", Fields!PercentCompleted.Value <= 0, "Red",)
Values greater than or equal to ten display with a green background, values between one and nine display with a blue background, a value equal to one displays with a yellow background, and a value that is zero or less displays with a red background. The following piece of code tests the value of the ImportantDate field and returns "Red" if it is more than a week old, and "Blue" otherwise. This expression can be used to control the Color property of a text box in a report item: =IIF(DateDiff("d",Fields!ImportantDate.Value, Now())>7,"Red","Blue")
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-19
Report Design in Microsoft Dynamics® NAV 2009 Test the Null Value In the following example, you test the value of the PhoneNumber field. If the field is null (Nothing in Visual Basic), "No Value" is returned; otherwise the phone number value is returned. This expression can be used to control the value of a text box in a report item. =IIF(Fields!PhoneNumber.Value Is Nothing,"No Value",Fields!PhoneNumber.Value)
The following expression can be used to control the Hidden property of an image report item. In the following example, the image specified by the field [LargePhoto] is displayed only if the text value of the field is not null. =IIF(IsNothing(Fields!LargePhoto.Value),True,False)
Report Functions Reporting Services provides built-in functions for use in expressions to calculate aggregate data in datasets, data regions, and groups, and to retrieve other data values, such as the first or last value on a report page. Two of the most important functions are the Sum() and the RowNumber() function.
Sum() The Sum() function can total the values in a group or data region. This function can be useful in the header or footer of a group. The following expression displays the sum of data in the Order group or data region: =Sum(Fields!LineTotal.Value, "Order")
You can also use the Sum() function for conditional aggregate calculations. For example, if a dataset has a field that is named State with possible values Not Started, Started and Finished, the following expression, when placed in a group header, calculates the aggregate sum for only the value Finished:
RowNumber() The RowNumber() function, when used in a text box within a data region, displays the row number for each instance of the text box in which the expression appears. This function can be useful to number rows in a table. It can also be useful for more complex tasks, such as providing page breaks based on number of rows. The scope that you specify for RowNumber() controls when renumbering begins. The Nothing keyword indicates that the function will start counting at the first row in the outermost data region. To start counting within nested data regions, use the name of the data region. To start counting within a group, use the name of the group. =RowNumber(Nothing)
3-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The following piece of code is used to evaluate whether the record in a data region control called table1 is on an odd or even row number. =IIF(RowNumber("table1") Mod 2 = 0, "LimeGreen", "Transparent")
It can be used to work with alternating background colors.
Appearance of Report Data You can use expressions to manipulate how data appears on a report. For example, you can display the values of two fields in a single text box, display information about the report, or affect how page breaks are inserted in the report.
Page Headers and Footers When designing a report, you may want to display the name of the report and page number in the report footer. The following expression provides the name of the report and the time it is run. It can be placed in a text box in the report footer or in the body of the report. The time is formatted with the .NET Framework formatting string for short date: =Globals!ReportName & ", dated " & Format(Globals!ExecutionTime, "d")
The following expression, placed in a text box in the footer of a report, provides the page number and total pages in the report: ="Page " & Globals!PageNumber & " of " & Globals!TotalPages
Page Breaks In some reports, you may want to place a page break at the end of a specified number of rows instead of, or in addition to, on groups or report items. To do this, create a group that contains the groups or detail records you want, add a page break to the group, and then add a group expression to group by a specified number of rows. The following expression uses the Ceiling() function. When placed in the group expression, it assigns a number to each set of 25 rows. When a page break is defined for the group, this expression results in a page break every 25 rows. =Ceiling(RowNumber(Nothing)/25)
To allow the user to set a value for the number of rows per page, create a variable RowsPerPage (the number can be added as a variable to the request options page) and base the group expression on the variable, as shown in the following expression: =Ceiling(RowNumber(Nothing)/Fields!RowsPerPage.Value)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-21
Report Design in Microsoft Dynamics® NAV 2009 On the Group Header, remember to check the Page Break at End option. A similar technique is also used in the Sales Invoice report, to have multiple copies of the report printed. This will be explained in the next lesson.
Properties Expressions are not only used to display data in text boxes. They can also be used to change how properties are applied to report items. You can change style information for a report item, change its visibility, or use dynamic URLs. •
Formatting
•
Visibility
•
URLs
Formatting The following expression, when used in the Color property of a text box, changes the color of the text depending on the value of another field, in this case the Profit field: =IIF(Fields!Profit.Value < 0, "Red", "Black")
To refer to the value of the current field, use the Fields!FieldName syntax, or use the Visual Basic object Variable Me. The following expression, when used in the Color property of a textbox, changes the color of the text depending on the value of the proper field: =IIF(Me.Value < 0, "Red", "Black")
The following expression, when used in the BackgroundColor property of a report item in a data region, alternates the background color of each row between pale green and white: =IIF(RowNumber(Nothing) Mod 2, "PaleGreen", "White")
If using an expression for a specified scope (for example the table called Employees in the report, it might be necessary to indicate the dataset for the aggregate function: Therefore, replace the Nothing value by the name of the data region control that corresponds to the scope.
Visibility You can show and hide items in a report using the visibility properties for the report item. In a data region such as a table, you can initially hide detail rows based on the value in an expression.
3-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The following expression, when used for initial visibility of detail rows in a group, shows the detail rows for all sales exceeding 90 percent in the PctQuota field: =IIF(Fields!PctQuota.Value>.9, False, True)
The following expression, when set in the Hidden property of a table, shows the table only if it has more than 12 rows: =IIF(CountRows()>12, True, False)
The following expression, when set in the Hidden property of a column, shows the column only if the field exists in the report dataset after the data is retrieved from the data source: =IIF(Fields!Column_1.IsMissing, True, False)
URLs You can customize URLs by using report data and also conditionally control whether URLs are added as an action for a text box. The following expression, when used as an action on a text box, generates a customized URL that specifies the dataset field EmployeeID as a URL parameter. ="http://adventure-works/MyInfo?ID=" & Fields!EmployeeID.Value
The following expression conditionally controls whether to add a URL in a text box. This expression depends on a variable named IncludeURLs that allows a user to decide whether to include active URLs in a report. This expression is set as a Hyperlink action (select Properties, Navigation tab) on a text box. =IIF(Fields!IncludeURLs.Value, "http://adventureworks.com/productcatalog?ItemID=" & Fields!Item_No ,Nothing)
Custom Code You can use custom code in a report. Custom code is either embedded in a report or stored in a custom assembly which is used in the report. To add code to a report in Visual Studio Report Designer, select Report, then Report Properties. On the Code tab, you can create your own custom code (functions and variables) to enrich the report functionalities. It is recommended not to add custom code that executes business logic; instead, use it to add presentation related code.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-23
Report Design in Microsoft Dynamics® NAV 2009 Custom code is used to create workarounds because of the inability to use databound fields in the Page Header and Footer sections. In previous chapters, you used the ReportItems collection to retrieve data in the Page Header from a text box in the Body section. In a similar way, you can define custom functions and variables to do the following tasks: •
Collect data from the dataset and load it into custom (array) variables.
•
Retrieve the data from the arrays and display it in the controls.
This will be described in the next lesson about the Sales Invoice report. As an example, one of the most common calculations in reports tends to be division. When dividing numeric variables, you have to be careful with NULL and 0 (zero) values because dividing a variable by NULL or by 0 results in a runtime error and or, NaN being returned in the reports. (NaN stands for Not a Number; it is a value or symbol that is generated as the result of an operation on invalid input terms, especially in floating-point calculations. A typical example is calculating the square root of a negative number.) To avoid this, you can create a function that checks the terms and returns the numeric result or, if there is an accidental error, a user-friendly value. The sample division function can look like this: Public Shared Function Divide(Num1 as double, Num2 as double) AS object IF ISNOTHING(Num2) Or Num2 = 0 Then Divide ="n/a" ELSEIF Num1 = 0 THEN Divide = 0 ELSE Divide = Num1 / Num2 END IF End Function
You can then call this function from an expression like this: =Code.Divide(1, 0) Instead of calling the Code.Divide function, use an expression with an IIf() statement in each textbox where you want to calculate the division. Adding custom code increases the maintainability of your report code.
3-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report A similar example calls an embedded method called FixSpelling(), which substitutes "Bicycle" for all occurrences of the text "Bike" in the SubCategory field. The example assumes that the following function is embedded on the report's Code tab. Public Function FixSpelling(ByVal s As String) As String Dim strBuilder As New System.Text.StringBuilder(s) If s.Contains("Bike") Then strBuilder.Replace("Bike", "Bicycle") Return strBuilder.ToString() Else : Return s End If End Function
To have the values replaced at runtime for each record in the report, set the Value property of the SubCategory field to: =Code.FixSpelling(Fields!SubCategory.Value) The following example calls an embedded code method called ToUSD(), which converts the StandardCost field value to a dollar value: =Code.ToUSD(Fields!StandardCost.Value)
Custom Variables The following example shows how to define some custom constants and variables. Public Public Public Public
Const MyNote ="Authored by John Doe" Const NCopies As Int32 = 2 Dim MyVersion As String ="123.456" Dim MyDoubleVersion As Double = 123.456
Although custom constants and variables do not appear in the Expression Editor Constants view (which only displays built-in constants), you can add references to them from any expression, as shown in the following examples. These are treated as Variants. =Code.MyNote =Code.NCopies =Code.MyVersion =Code.MyDoubleVersion
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-25
Report Design in Microsoft Dynamics® NAV 2009 Adding Database Pictures to the Header Chapter 2 mentioned it is possible to add database pictures to the page header using code and expressions. The following steps show how to do this. 1. 2. 3. 4.
In Visual Studio Report Designer, add a textbox to the Body section. In the Properties window, set the Name to CompanyPicture. In the Properties window, set the Hidden property to True. In the Properties window, set the Color property to Red. (This way you can distinguish the hidden from the visible controls.) 5. In the Properties window, set the Value property to: =Convert.ToBase64String(Fields!CompInfo_Picture.Value) 6. Select Report, Report Properties. 7. On the Code tab, add the following custom variable and functions to the Report. Shared PictureData as Object Public Function GetPicture() as Object Return PictureData End Function Public Function SetPicture(NewData as Object) if NewData>"" PictureData = NewData end if End Function
8. 9. 10. 11. 12. 13. 14. 15. 16.
3-26
Close the Report Properties window. Add an Image control to the Page Header section. In the Properties window, set the Source property to Database. In the Properties window, set the MIME Type property to image/bmp. In the Properties window, set the Value property to: =Convert.FromBase64String(Code!GetPicture()) Add a textbox control to the Page Header. Attention: the textbox must be placed above the Image control added in step 9. In the Properties window, set the Hidden property to True. In the Properties window, set the Color property to Red. In the Properties window, set the Value property to: =Code!SetPicture(ReportItems!CompanyPicture.Value).
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Notice that this is an advanced way of using expressions. Simply stated, the following techniques are used: 1. The database picture, which appears in the dataset, is stored in a hidden textbox in the body section. A picture cannot be displayed in a textbox, so the picture must be converted to a text string. 2. At the top of the Page Header section, a second hidden textbox is displayed which retrieves the value from the first hidden textbox using the ReportItems collection and stores it in a custom variable PictureData (using the SetPicture() function). 3. The Image control retrieves the picture from the variable (using the GetPicture() custom function) and converts the string value back into a picture. When the report is run, the hidden textbox in the header, which is located above the image control, is rendered before the image control, causing the SetPicture() function to be executed before the GetPicture(). The previous procedure is used in a considerable number of reports, to retrieve data that is printed in the Page Header section.
Anatomy of the Sales Invoice Report In Microsoft Dynamics NAV the Sales Invoice Report (report 206) is used to print sales invoices. From a functional point of view this is not very extraordinary, but from a technical point of view the Sales Invoice report is rather difficult to understand. This lesson provides an overview of the anatomy of the Sales Invoice Report. Because the Sales Invoice Report is built similar to other reports in Microsoft Dynamics NAV, it is important to understand how it is designed. This lesson will focus on the RDLC report layout. The Classic report layout is covered in depth in the Microsoft Official Courseware C/SIDE Solution Development.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-27
Report Design in Microsoft Dynamics® NAV 2009 The Data Model Looking at the logical design for the Sales Invoice Report, you find the following data model:
FIGURE 3.5 THE DATA MODEL OF REPORT 206
The two primary tables used in creating a sales invoice are the Sales Invoice Header and the Sales Invoice Line tables. In this report, some supporting variables are used to access information from tables that do not fit into the data model. Supplemental tables, such as Payment Terms, Shipment Method, Salesperson/Purchaser and Company Information, are used to expand the code fields used in the invoice tables to more descriptive text. The Company Information table is used to retrieve information about the company that is preparing the invoice. The report also uses a virtual table: Integer. The Integer table is used for the logical loops that are run through during report execution.
The Triggers If you compare the report to the Microsoft Dynamics NAV 5.0 SP1 release and look at the triggers of the data items in the report, not much new code is added. In the next paragraphs, the code changes for each data item are explained.
CopyLoop - OnPreDataItem The CopyLoop data item is executed for each Sales Invoice Header. The function of this data item is to have multiple copies of the report printed in one report run. Although the CopyLoop is not the top-level data item in the report, it controls the printing of the entire report. All printed sections in the Classic report depend on this data item and are repeated for each copy loop. (The Sales Invoice Header data item is mainly only used for filtering and data retrieval purposes; it has no 3-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report printed sections.) If a sales invoice has more than one page, all pages are printed in the PageLoop cycle, which is subordinated to the CopyLoop cycle. If two copies of the report are to be printed, all pages of the invoice will be printed before the invoice is printed a second time. If multiple reports are to be printed, all copies of the first invoice will be printed before the next invoice is printed. Because the RoleTailored client supports only one body section, the layout of the Classic report cannot be built in Visual Studio Report Designer in the same way as it is designed in the Classic client. To have the pages of the invoice grouped by invoice header, a new integer variable OutputNo is introduced. The variable is used to control the number of copies of a report and is used to group the pages and copies of the report. To make the variable available in the dataset, it is added in a hidden textbox to the sections of the Classic report. In the OnPreDataItem trigger of the CopyLoop data item, a piece of code is added which initializes a new Integer variable, OutputNo. IF ISSERVICETIER THEN OutputNo := 1;
The ISSERVICETIER statement is used to distinguish code for the RoleTailored client from code that is executed for the Classic report. In this case, the variable will only be initialized for the RDLC report layout.
CopyLoop - OnAfterGetRecord In the OnAfterGetRecord trigger, two pieces of code using the ISSERVICETIER function are added. IF Number > 1 THEN BEGIN CopyText := Text003; IF ISSERVICETIER THEN OutputNo += 1; END; CurrReport.PAGENO := 1; IF ISSERVICETIER THEN BEGIN TotalSubTotal := 0; TotalInvoiceDiscountAmount := 0; TotalAmount := 0; TotalAmountVAT := 0; TotalAmountInclVAT := 0; TotalPaymentDiscountOnVAT := 0; END
The first piece of code is used to increment the OutputNo value for each copy of the report. For the first copy of the report, OutputNo will equal one, for the second copy, OutputNo will be two, and so on. The OutputNo value is used to group the data in the report. All pages will appear in the same order as in the Classic client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-29
Report Design in Microsoft Dynamics® NAV 2009 The second piece of code is used to reset a number of variables to zero for each copy of the report. The variables are used to display the different subtotals in the RDLC report layout. In the Classic client, the different totals are calculated using the CREATETOTALS statement. CREATETOTALS maintains group and grand totals for the specified variables or fields. To print the totals, you must place controls that have the variable(s) or field(s) that are the arguments of CREATETOTALS as their source expressions in the appropriate Footer or GroupFooter sections. In the Classic client, a number of footer sections are used to display the totals However, the different totals are calculated and stored internally in the Classic report and are by default not available in the RDLC report layout. To make the values available in the dataset, they must be stored in additional variables. In addition, the variables must be reset after each copy of the report. (In the Classic client, subtotals are automatically reset to zero.)
Sales Invoice Line - OnAfterGetRecord As already mentioned in the previous paragraph, the subtotals of the Classic report are calculated and stored in extra variables for the RDLC report layout. To calculate the totals, the following piece of code is added: IF ISSERVICETIER THEN BEGIN TotalSubTotal +="Line Amount"; TotalInvoiceDiscountAmount -="Inv. Discount Amount"; TotalAmount += Amount; TotalAmountVAT +="Amount Including VAT" - Amount; TotalAmountInclVAT +="Amount Including VAT"; TotalPaymentDiscountOnVAT += -("Line Amount" - "Inv. Discount Amount" - "Amount Including VAT"); END
This code is used to calculate the subtotals for the RDLC report layout only. The totals are added as invisible controls to the footer sections in the Classic report and converted to dataset fields.
3-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The RDLC design Look at the RDLC layout of the report. There are many controls and tables both in the header and in the body section.
FIGURE 3.6 RDLC REPORT LAYOUT OF THE SALES INVOICE
Some of the controls have red text and are invisible controls. The Hidden property in the Visibility property collection is set to True.
The Body Section In the top left corner of the Body section you see two hidden tables. The right table has three columns and contains the logo from the Company Information table. Each cell corresponds to a Picture control from the classic design. The picture is converted to text for it to be stored in a textbox, using the Convert.ToBase64String() function. The left table contains four columns. Each column contains specific information that is available through variables in the Classic report. The first column contains all fields for the customer's address. The second column includes information regarding the company address. The third column contains much information coming from the Company Information table. The fourth column contains all kinds of information related to the Sales Invoice Header: fields from the Sales
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-31
Report Design in Microsoft Dynamics® NAV 2009 Invoice Header (such as Due date), fields from the Salesperson/Purchaser table, and other elements. The following table shows the names and values of the four text boxes.
3-32
Name
Value Expression
CustAddr
=Fields!CustAddr_1_.Value + Chr(177) + Fields!CustAddr_2_.Value + Chr(177)+ Fields!CustAddr_3_.Value + Chr(177)+ Fields!CustAddr_4_.Value + Chr(177)+ Fields!CustAddr_5_.Value+Chr(177)+ Fields!CustAddr_6_.Value + Chr(177)+ Fields!CustAddr_7_.Value+Chr(177)+ Fields!CustAddr_8_.Value
CompanyAddr
=Fields!CompanyAddr_1_.Value + Chr(177) + Fields!CompanyAddr_2_.Value + Chr(177)+ Fields!CompanyAddr_3_.Value + Chr(177)+ Fields!CompanyAddr_4_.Value + Chr(177)+ Fields!CompanyAddr_5_.Value + Chr(177)+ Fields!CompanyAddr_6_.Value
CompanyInfo
=Fields!CompanyInfo__Phone_No__Caption.Value + Chr(177) + Fields!CompanyInfo__Phone_No__.Value + Chr(177) + Fields!CompanyInfo__Fax_No__Caption.Value + Chr(177) + Fields!CompanyInfo__Fax_No__.Value + Chr(177)+ Fields!CompanyInfo__VAT_Registration_No__Caption.V alue + Chr(177)+ Fields!CompanyInfo__VAT_Registration_No__.Value + Chr(177)+ Fields!CompanyInfo__Giro_No__Caption.Value + Chr(177)+ Fields!CompanyInfo__Giro_No__.Value + Chr(177)+ Fields!CompanyInfo__Bank_Name_Caption.Value + Chr(177)+ Fields!CompanyInfo__Bank_Name_.Value + Chr(177)+ Fields!CompanyInfo__Bank_Account_No__Caption.Value + Chr(177)+ Fields!CompanyInfo__Bank_Account_No__.Value
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Name
Value Expression
SalesHdrInfo
=Fields!Sales_Invoice_Header___Bill_to_Customer_No__ Caption.Value + Chr(177) +Fields!Sales_Invoice_Header___Bill_to_Customer_No__. Value + Chr(177) + Fields!VATNoText.Value + Chr(177) + Fields!Sales_Invoice_Header___VAT_Registration_No__. Value + Chr(177) + Fields!ReferenceText.Value + Chr(177) + Fields!Sales_Invoice_Header___Your_Reference_.Value + Chr(177) + Fields!Invoice_No_Caption.Value + Chr(177) + Fields!Sales_Invoice_Header___No__.Value + Chr(177) + Fields!OrderNoText.Value + Chr(177) + Fields!Sales_Invoice_Header___Order_No__.Value + Chr(177) + Fields!Sales_Invoice_Header___Posting_Date_Caption.Val ue + Chr(177) + Fields!Sales_Invoice_Header___Posting_Date_.Value + Chr(177) + Fields!Sales_Invoice_Header___Due_Date_Caption.Value + Chr(177) + Fields!Sales_Invoice_Header___Due_Date_.Value + Chr(177) + Fields!Sales_Invoice_Header___Prices_Including_VAT_C aption.Value + Chr(177) + Cstr(Fields!PricesInclVAT_YesNo.Value) + Chr(177) + First(Fields!FORMAT__Sales_Invoice_Header___Docume nt_Date__0_4_.Value) + Chr(177) + First(Fields!STRSUBSTNO_DocumentCaption_CopyText _.Value) + Chr(177) + Fields!SalesPersonText.Value + Chr(177) + Fields!SalesPurchPerson_Name.Value + Chr(177) + Fields!PageCaption.Value
In each expression, Chr(177) is used to separate the different data parts in each group. When the GetData() function is called, data in the group is split by using the Split function with Chr(177) as a separator. This kind of hidden information is placed in a table header row and not in a table detail row (because it is only needed once). Using a table detail row can impact report execution time. Further down in the Body section you see a number of tables that are used to display the various blocks of information that need to be included in the report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-33
Report Design in Microsoft Dynamics® NAV 2009 The table3 table contains information regarding the dimensions of the sales invoice header. The table is only printed when the Show Internal Information option is checked in the request options page. In the DimensionLoop of the report, all dimensions for the posted sales invoice header will be run through and stored in a text variable. The first header row in the table will be printed the first time the DimensionLoop cycle is run through. The second header row will be printed in all other loops. The Table_Lines table contains all details of the Sales Invoice Line table. The table has one header row, two group header rows, two detail rows and thirteen group footer rows. The header row contains the field captions. The two group header rows display the details of the Sales Invoice Line. The Visibility property for these rows is set in a way that the first row header is printed for sales invoice lines where the Type field is and the second header is printed for the other sales invoice lines. The two detail rows contain details regarding the posted shipments and the dimensions for the sales invoice line. Again visibility options are defined to show or hide the rows when necessary. The thirteen group footer rows are used to show the different subtotals. The table properties are set to repeat the table header row on each page. The Table_VAT table contains all VAT related specifications from the VATCounter data item. The first two (header) rows of the table contain captions. The detail row shows all details for the VATCounter data item. The table footer row displays the totals for the VAT Amount Specifications. The Table_VATLCY table contains all VAT related specifications from the VATCounterLCY data item. The first three (header) rows of the table contain captions and information about the exchange rates of the amounts. The detail row shows all details for the VATCounter data item. The table footer row displays the totals for the VAT Amount Specifications in local currency. The Table_PaymentShipment contains two detail rows showing the description for the Payment Terms and Shipment Method of the Sales Invoice Header. The table contains a more descriptive text than the corresponding Payment Terms Code and Shipment Method Code. Finally, the Table_ShipToAddress table contains shipping information for the sales invoice header. It contains two header rows (with a table caption and some customer information) and nine detail rows (including the Ship-To Address information).
The List Ccontrol All tables in the body section are placed inside a list control. A list is a data region that presents data arranged in a freeform fashion. You can arrange report items to create a form with text boxes, images, and other data regions placed anywhere within the list. The list is considered as a big form and will be printed as such. When deleting a list control, all controls that are placed inside a list control will be deleted too.
3-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The Header Section At the top of the Header section, there are seven hidden controls. The purpose of these seven controls is to retrieve information that is stored somewhere (hidden) in the Body section and to load it into custom variables. To do this, the text boxes use the custom functions SetData() and SetPicture() that are defined in the report. The SetData() function has two parameters. The first parameter, NewData, is the data value that is stored in the custom variable. The second parameter, Group, is an integer that refers to the custom data variable that is used. Public Function SetData(NewData as Object,Group as integer) If Group = 1 and NewData > "" Then Data1 = NewData End If If Group = 2 and NewData > "" Then Data2 = NewData End If If Group = 3 and NewData > "" Then Data3 = NewData End If If Group = 4 and NewData > "" Then Data4 = NewData End If End Function
The SetPicture() function has the same syntax and the same purpose. It retrieves the hidden pictures from the body section and loads them into the shared PictureData variables. The custom data variables are defined as shared variables of the type Object. Shared Shared Shared Shared ... Shared Shared Shared
Data1 Data2 Data3 Data4
as as as as
Object Object Object Object
PictureData1 as Object PictureData2 as Object PictureData3 as Object
An object is a more complex data type. Unlike simple data types (such as integer, string, Boolean, and so on), it can contain more complex data values, such as data that can be broken down into smaller pieces. In this case, the data variables can be considered as arrays: they contain multiple values. Shared means they are available throughout the entire report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-35
Report Design in Microsoft Dynamics® NAV 2009 When the report is run and the header section is rendered, it starts with the textboxes at the top. As a result of evaluating the expression that is set in the Value property of the textboxes, the data is retrieved from the hidden textboxes in the Body section and loaded into the custom variables. As a first parameter, the function takes an element from the ReportItems collection. After the hidden textboxes, the three image controls are rendered. The Value property of the Image controls is set to: =Convert.FromBase64String(Code.GetPicture(x)) where x represents an integer between 1 and 3 (both included)). The function GetPicture() retrieves the value of the PictureData custom variable and converts it back from text to picture. Now, the other text boxes in the page header will be rendered. Public Function GetData(Num as Integer, Group as integer) as Object if Group = 1 then Return Cstr(Choose(Num, Split(Cstr(Data1),Chr(177)))) End If if Group = 2 then Return Cstr(Choose(Num, Split(Cstr(Data2),Chr(177)))) End If if Group = 3 then Return Cstr(Choose(Num, Split(Cstr(Data3),Chr(177)))) End If if Group = 4 then Return Cstr(Choose(Num, Split(Cstr(Data4),Chr(177)))) End If End Function
Each of these textboxes is using the GetData() function, which has two parameters. The first parameter, Num, is an integer value that refers to the element in the custom data variable. The second parameter, Group, refers to the data variable that is used. There are four groups: one for the customer address, one for the shipping address, one for the company information and one for the sales invoice header. In the GetData() function, the data is extracted from the variable using the Choose() and Split() functions. The Split() function takes a string argument, divides the string into elements by using the space character as the delimiter, and returns a string array. It has two parameters: the string to split (CStr(Data1)) and the space delimiter (Chr(177)). The CStr() function is used to convert the custom variable to string. The string array is then passed as a second parameter to the Choose() function.
3-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report The Choose() function selects and returns a value from a list of arguments. The first parameter, Num, determines which element will be retrieved from the string array. For example: =Code.GetData(1,2)
will return element 1 in the custom variable Data2. This corresponds to the Company Name (the first element in the CompanyAddr array in the Classic report). After the header is rendered, the Body section will be rendered.
Print Header Information on Multiple Pages Sometimes you must include hidden fields in the body of the report to successfully create a client report definition (RDLC) report layout. Typically, you add hidden fields to the table in the body section of the RDLC report layout. However, if there is more than one table in the report, the header information is not displayed on pages that display the subsequent tables. Instead, it is only displayed on the page with the first table. For reports such as document reports (invoices, credit memos) that have multiple tables and require header information on each page, you must ensure to: •
Create hidden text boxes in one table to get the data.
•
Create a function to save the data, which you call from one or more hidden fields in the header section.
•
Create a function to retrieve the data, which you call from one or more displayed text boxes in the header section.
The same applies to tables that span multiple pages. For information to be passed from one page to the next, you might include it as a hidden column in the data region control that spans multiple pages. An alternative solution is to include the information in a hidden textbox in the body section (outside the data region control), and make the textbox travel along with the data region control. To do this, select the textbox properties, check the Repeat report item with data region on every page and specify the data region control that can span multiple pages. Remember that headers and footers in client report definition (RDLC) report layouts have the following limitations: •
Expressions in a header or footer can refer to only one report item.
•
Data-bound fields in a header or footer will give an error. You must put the data-bound field in a text box in the body section, and either save the data to a global variable, or use ReportItem!.
•
There can be only one header, one body, and one footer in a report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-37
Report Design in Microsoft Dynamics® NAV 2009 When you create a layout suggestion, data-bound fields in the header are automatically moved to hidden fields in the body of the report. However, in some cases, it might be necessary to create additional hidden text boxes in the body section of a report so that in the new layout, you can reference that report item in the header or footer.
The Number of Copies Option For document type reports, often the request form displays an option for the number of copies to print. In a client report definition (RDLC) report layout, a copy is the same as a new document that must start on a new page. You must add code to set and update the copy number, group the data based on the copy number, and then specify a page break at the end of the group.
To Add Code to the Report for the Number of Copies Previously, this chapter described the code that is added to the data item trigger in the Classic report that is required to initialize and increment the copy number. Also mentioned earlier is that the OutputNo must be added to the sections of the report.
To Group Data Based on Copy Number 1. In the Classic client, on the View menu, click Layout. 2. In Microsoft Visual Studio, in the report.rdlc file, right-click the row to group on, and then click Edit Group. 3. In the Grouping and Sorting Properties window, on the General tab, under Group on, select the next blank line to add a grouping, and then select =Fields!OutputNo.Value from the drop-down list. 4. In the Grouping and Sorting Properties window, click the Sorting tab. 5. Select a blank line, and then select =Fields!OutputNo.Value from the drop-down list.
To Specify the Page Break To specify the page break for the report, proceed as follows: 1. Right-click the List control and select Properties. 2. On the General tab, click the Edit Details Group button. 3. In the Grouping and Sorting Properties window, check the Page break at end option. 4. Click OK to close the Grouping and Sorting Properties window. 5. Click OK to close the List Properties window.
3-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Reset Page Numbers On some reports, you might want to group sets of data together and reset the page number after each group. For example, in the standard application, report 206, Sales Invoice, displays sales invoices that are grouped by sales invoice number. To reset the page number to one for each group of data, you must modify code on the client report definition (RDLC) report layout.
To Reset Page Numbers: 1. In the Classic client, on the Tools menu, click Object Designer. 2. In Object Designer, click Report, select a report to modify, and then click Design. 3. On the View menu, click Layout. 4. In Microsoft Visual Studio, in the Report.rdlc file, on the Report menu, select Report Properties. 5. In the Report Properties window, select the Code tab. 6. Add the following code in the Custom code text box:
REM Reset Page Number: Shared offset As Integer Shared newPage As Object Shared currentgroup1 As Object Shared currentgroup2 As Object Shared currentgroup3 As Object Public Function GetGroupPageNumber(ByVal NewPage As Boolean, ByVal pagenumber As Integer) As Object If NewPage Then offset = pagenumber - 1 End If Return pagenumber - offset End Function Public Function IsNewPage(ByVal group1 As Object, ByVal group2 As Object, ByVal group3 As Object) As Boolean newPage = False If Not (group1 = currentgroup1) Then newPage = True currentgroup1 = group1 Else If Not (group2 = currentgroup2) Then newPage = True currentgroup2 = group2 Else If Not (group3 = currentgroup3) Then newPage = True
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-39
Report Design in Microsoft Dynamics® NAV 2009 currentgroup3 = group3 End If End If End If Return newPage End Function
7. In Visual Studio, in the Report.rdlc file, right-click the textbox in the header that displays the page number, and then select Expression. 8. In the Expression window, enter the following expression: =Code.GetGroupPageNumber(ReportItems!NewPage.Value,Globals !PageNumber) 9. In the Body section of the layout, create a new textbox called NewPage. 10. Right-click the NewPage textbox created in step 8 and then select Properties. 11. In the Properties window, on the General tab, enter the following in the Value field. =Code.IsNewPage(Fields![,,]) For example, if you are grouping by document type, then grouping field1 is Document_Type.Value. To use more than three groupings, you can modify the code in the IsNewPage function. To use less than three groupings, you can either modify the code in the IsNewPage function or use a static value for one or more of the function parameters.
Summary This chapter described how to create and use expressions in a report for different purposes (formatting, visibility options, data retrieval and grouping). The chapter also described how to add custom code and custom variables to a report. Lastly, it provided a better understanding of how the sales invoice report works.
3-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report
Test Your Knowledge 1. Which decision functions can be used in expressions in Visual Studio Report Designer? (Select all that apply) ( ) Iif() ( ) Switch() ( ) Case() ( ) Select Case() 2. Can nested IiF() statements be used? ( ) No. ( ) Yes, but only up to two levels ( ) Yes ( ) None of the answers is correct. 3. Which function is used to identify the row number in a data region control? ( ) Row ( ) RowNo ( ) RowNumber ( ) NoRow 4. Which expression returns the name of the Windows user (without the domain name) that is running an RDLC report? ( ) =Right(USERID, Len(USERID)) ( ) =Right(User!UserID, Len(User!UserID) - InStr(User!UserID, "\")) ( ) =Right(Report!UserID, Len(Report!UserID) - InStr(Report!UserID, "\")) ( ) This is not possible as the RoleTailored Client does not use Windows accounts. 5. What is not true about expressions? ( ) Expressions can be used for sorting. ( ) Expressions can be used to determine the visibility of controls. ( ) Expressions can be used for formatting. ( ) Expressions cannot be used to insert page breaks in a report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-41
Report Design in Microsoft Dynamics® NAV 2009 6. What is true about Custom Code in a report? (Select all that apply) ( ) Functions that are defined in the Classic report are automatically added to the RDLC report layout when using the Create Layout Suggestion option. ( ) Custom Code is available in the Expression window using the Code collection. ( ) Custom Code can be added in various places in Visual Studio Report Designer. ( ) Custom Code must be added using Visual Basic syntax.
3-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report
Lab 3.1a - Adding Conditional Formatting to a Report - I In this lab you will further design the Item Catalog created in Lab 2.4. You will use expressions to change visibility options and formatting. Scenario The RDLC report layout of the Item Catalog is already designed. Now it is time to further fine-tune the report. You need to add conditional formatting to make the report more user-friendly: •
Table headers need to be printed with a LightGrey background.
•
The Picture column needs to have a caption.
•
Rows need to be printed with alternating colors.
•
Negative inventory values need to be displayed in bold and in red.
•
The Image control needs to be hidden automatically when an item has no picture.
The result needs to look like this:
FIGURE 3.7 THE CRONUS ITEM CATALOG
In Lab 3.1b you will use expressions to add other functionality.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-43
Report Design in Microsoft Dynamics® NAV 2009 Challenge Yourself! Change the Item Catalog built in Lab 2.4, so that the column headers are printed with a LightGrey background and so that it uses alternating background colors (PaleGreen and Transparent) for the items. Ensure that negative inventory totals are displayed in bold and in red. Change the report so that the visibility of the Picture field is no longer able to be toggled by the Item No. Instead, ensure the image control is hidden automatically for items that do not have a picture. Next, change the report so that the column captions are printed on every page. In Lab 3.1b additional formatting will be added.
Need a Little Help? 1. 2. 3. 4. 5. 6.
Change the Background Color for the Header Row. Change the Background Colors for the Detail Row. Change the Color of Negative Inventory Values to Red. Change the Visibility Option for the Picture Field. Repeat the Column Captions on Each Page. Run the Report.
Step by Step In this lab, the following steps need to be executed:
Change the Background Color for the Header Row 1. Open report 123456704 in Visual Studio Report Designer. 2. On the Header row of the table control, select the cell above the Image control. 3. In the Properties window, set the Value property to Picture. 4. In the header row of the table control, select the textboxes containing the No. Description, Base Unit of Measure, Unit Price, Inventory and Picture field captions. 5. In the Properties window, set the BackgroundColor property to LightGrey.
Change the Background Colors for the Detail Row 1. On the detail row of the table control, select the textboxes containing the No. Description, Base Unit of Measure, Unit Price and Inventory fields. 2. In the Properties window, in the BackgroundColor property, select <Expression...>.
3-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report 3. In the Expression window, enter the following expression: =Iif(RowNumber(Nothing) Mod 2 = 0, "PaleGreen", "Transparent") 4. Click OK to close the Expression window.
Change the Color of Negative Inventory Values to Red 1. On the detail row, select the textbox containing the Inventory field. 2. In the Properties window, in the Color property, select <Expression...>. 3. In the Expression window, enter the following expression: =Iif(Fields!Item_Inventory.Value < 0, "Red", "Black"). 4. Click OK to close the Expression window. 5. In the Properties window, expand the Font property collection. 6. In the FontWeight property, select <Expression...>. 7. In the Expression window, enter the following expression: =Iif(Fields!Me.Value < 0, "Bold", "Normal"). 8. Click OK to close the Expression window.
Change the Visibility Option for the Picture Field 1. 2. 3. 4. 5.
On the detail row, select the Image control. In the Properties window, expand the Visibility property collection. Clear the ToggleItem property. In the Hidden property, select <Expression...>. In the Expression window, enter the following expression: =Iif(Len(Convert.ToBase64String(Fields!Item_Item_Picture.value)) > 0, False, True). 6. Click OK to close the Expression window.
Repeat the Column Captions on Each Page 1. Right-click any cell in the table and choose "Select 'table1'." 2. Right-click the shaded border of the selected table and choose Properties. The Table Properties window will appear. 3. On the General tab, check the Repeat header rows on each page option. 4. Click OK to close the Table Properties window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-45
Report Design in Microsoft Dynamics® NAV 2009 Run the Report 1. 2. 3. 4.
3-46
Exit Visual Studio. Save and import the RDLC changes. Save and compile the report in the Report Designer. Run the report from the Start, Run menu.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report
Lab 3.1b - Adding Conditional Formatting to a Report - II In this lab you will further design the Item Catalog created in Lab 3.1. You will use expressions to change visibility options and formatting. Furthermore, you will introduce a request options page and work with multiple headers and detail rows. Scenario The Item Catalog report is used by two types of users: first it is used by the salespeople of CRONUS International Ltd. during the daily order process. Therefore, detailed inventory information and pictures are included. Secondly, a copy of the report is sometimes handed out to customers. In that case, less detailed inventory information is required. To support both requests with one and the same report, you need to change the report so that the user has the option to print the inventory as a numeric value or as an icon indicating the inventory status: •
Inventory > 0: show a green checkmark.
•
Inventory = 0: show a blue question mark.
•
Inventory < 0: display a red cross.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-47
Report Design in Microsoft Dynamics® NAV 2009 The result needs to look like this:
FIGURE 3.8 THE CRONUS ITEM CATALOG
Challenge Yourself! Change the report from Lab 3.1a so that you can either have the exact inventory displayed (as a numeric value) or an embedded icon showing the inventory status: •
Inventory > 0: show a green checkmark.
•
Inventory = 0: show a blue question mark.
•
Inventory < 0: display a red cross.
The icons are provided on the training DVD. When printing the report, the user gets a "Graphic Inventory" option, which determines what will be printed. When printing the "Graphic Inventory", no pictures are printed; the background colors alternate between LightBlue and Transparent.
Need a Little Help? 1. 2. 3. 4. 5. 6. 7.
3-48
Add a Boolean Variable to the Classic Design. Change the Classic Section Design. Design the Request Options Page. Embed the Images in the Report. Add an Additional Table Header Row. Add an Additional Table Detail Row. Adjust the New Table Detail Row.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report 8. 9. 10. 11. 12. 13.
Add an Image Control for the Inventory field. Set the Value Property of the Inventory field. Change the Visibility of the Table Header Row. Change the Visibility of the Table Detail Row. Change the Alternating Colors for the Table Detail Row. Run the Report.
Step by Step In this lab, the following steps need to be executed:
Add a Boolean Variable to the Classic Design 1. Open the Classic report 123456704 in the Object Designer. 2. Select View, C/AL Globals. 3. On the Variables tab, on a blank line, enter GraphicalInventory in the Name column. Select Boolean in the DataType column. 4. Click OK to close the C/AL Globals window. 5. Save and compile the Classic report.
Change the Classic Section Design 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
Open the Classic report in the Object Designer. Select View, Sections. In the Toolbox window, select the Textbox control. Click the Item Header section to insert a new textbox in the report. Right-click the new textbox and select Properties. In the Properties window, set the SourceExpr property to GraphicalInventory. In the Properties window, set the ForeColor property to 255. In the Properties window, set the Visible property to No. Close the Section Designer. Save and compile the Classic report.
Design the Request Options Page 1. Open the Classic report in the Object Designer. 2. Select View, Request Page.The Request Options Page Designer will be opened. As the report did not contain a request page yet, the window is blank. 3. On the first blank line, enter My Request Page in the Caption column.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-49
Report Design in Microsoft Dynamics® NAV 2009 4. On the same line, select Container in the Type and ContentArea in the SubType column. 5. On the second line, enter Options in the Caption column. In the Type and SubType column, select Group. 6. On the third line, enter Graphical Inventory in the Caption column. Choose Field n the Type column. In the SourceExpr column, enter GraphicalInventory. 7. Click the Close button in the top right corner to close the Request Options Page Designer. 8. Save and compile the Classic report.
Embed the Images in the Report 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.
Open the report in Visual Studio Report Designer. Select Report, Embedded Images. In the Embedded Images window, click the New Image button. Browse to the folder containing select image058.gif. Click Open to import the image. In the Name column, change the name of the image to InvGreen. In the Embedded Images window, click the New Image button. Browse to the folder containing image174.gif. Click Open to import the image. In the Name column, change the name of the image to InvRed. In the Embedded Images window, click the New Image button. Browse to the folder containing image714.gif. Click Open to import the image. In the Name column, change the name of the image to InvBlue. Click OK to close the Embedded Images window.
Add an Additional Table Header Row 1. Click the cell containing the Item No. caption in the table header row. 2. Right-click the row handle for the table header row and select Insert Row Below. 3. In the first header row, select the first five cells and press Ctrl+C to copy the selection to the clipboard.. 4. Select the first cell on the newly added header row and press Ctrl+V. 5. Select the sixth cell on the header row. 6. In the Properties window, set the BackgroundColor property to Transaparent.
3-50
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Add an Additional Table Detail Row 1. Click a cell in the table detail row. 2. Right-click the row handle for the table detail row and select Copy. 3. Right-click the row handle for the table detail row again and select Paste. The table detail row will be duplicated.
Adjust the New Table Detail Row 1. Select the cell containing the image control on the newly added table detail row. 2. Delete the Image control. 3. Select the cell containing the Inventory field on the newly added table detail row. 4. Press Delete to clear the table cell.
Add an Image Control for the Inventory field 1. In the Toolbox window, select the Image control. 2. Drag it to the Inventory column on the second detail row. 3. In the Properties window, set the Source property to Embedded.
Set the Value Property of the Inventory field 1. Select the newly added Image control. 2. In the Properties window, set the Value property to the following expression: =Switch(Fields!Item_Inventory.Value < 0, "InvRed", Fields!Item_Inventory.Value = 0, "InvBlue", Fields!Item_Inventory.Value > 0, "InvGreen")
Change the Visibility of the Table Header Row 1. Click the cell containing the Item No. caption in the first table header row (the row including the Picture caption). The table row handle will now be displayed. 2. Click the row handle for the first table header row to select the entire table row. 3. In the Properties window, expand the Visibility property collection. 4. In the Hidden property, select <Expression...>. 5. In the Expression window, enter the following expression: =Iif(Fields!GraphicalInventory.Value = 0, False, True). 6. Click OK to close the Expression window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-51
Report Design in Microsoft Dynamics® NAV 2009 7. Click the cell containing the Item No. caption in the second table header row (the row that does not include the Picture caption). The table row handle will now be displayed. 8. Click the row handle for the second table header row to select the entire table row. 9. In the Properties window, expand the Visibility property collection. 10. In the Hidden property, select <Expression...>. 11. In the Expression window, enter the following expression: =Iif(Fields!GraphicalInventory.Value = 0, True, False). 12. Click OK to close the Expression window.
Change the Visibility of the Table Detail Row 1. Click the cell containing the Item No. field in the first table detail row. The table row handle will now be displayed. 2. Click the row handle for the first table detail row to select the entire table row. 3. In the Properties window, expand the Visibility property collection. 4. In the Hidden property, select <Expression...>. 5. In the Expression window, enter the following expression: =Iif(Fields!GraphicalInventory.Value = 0, false, true). 6. Click OK to close the Expression window. 7. Click the cell containing the Item No. in the second table detail row (the row that does not include the Picture field). The table row handle will now be displayed. 8. Click the row handle for the second table detail row to select the entire table row. 9. In the Properties window, expand the Visibility property collection. 10. In the Hidden property, select <Expression...>. 11. In the Expression window, enter the following expression: =Iif(Fields!GraphicalInventory.Value = 0, true, false). 12. Click OK to close the Expression window.
Change the Alternating Colors for the Table Detail Row 1. On the second detail row of the table control, select the textboxes containing the No. Description, Base Unit of Measure and Unit Price fields. 2. In the Properties window, in the BackgroundColor property, select <Expression...>. 3. In the Expression window, enter the following expression: =Iif(RowNumber(Nothing) Mod 2 = 0, "LightBlue", "Transparent"). 4. Click OK to close the Expression window.
3-52
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Run the Report 1. 2. 3. 4.
Exit Visual Studio. Save and import the RDLC changes. Save and compile the report in the Report Designer. Run the report from the Start, Run menu.
The Request Page of the report now shows an option called "Graphical Inventory". If you check the option, the result looks like the figure at the beginning of the lab.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-53
Report Design in Microsoft Dynamics® NAV 2009
Lab 3.2 - Using Custom Code in the Visual Studio Report Designer In this lab, you will use custom code to get the report finished. You will add controls to the body section and use the information in the header section. In addition, you will replace the embedded company logo by the company logo stored in the Microsoft Dynamics NAV database. Scenario In Lab 3.1b you introduced the Graphical Inventory option, to solve multiple end-user requests with one and the same report. You have created multiple header and detail rows that are printed depending on the selected option. As a side-effect of this, you notice that when printing the report with Graphical Inventory information, the company information in the header section is suddenly missing. In addition, you will replace the embedded company logo by the picture that is stored in the Microsoft Dynamics NAV database. You will solve these issues using custom code and variables.
Challenge Yourself! In this lab you will replace the embedded company logo by the company logo that is stored in the Company Information table. In addition, you will use custom functions to load the company information from the Body section and retrieve it in the Header section. Hidden controls need to be added to the Body and Page Header sections. Also, you will add the report execution time (as a long date), the current page number and the total number of pages to the report.
Need a Little Help? 1. 2. 3. 4. 5. 6. 7. 8.
Add Custom Code to the Report. Delete the Embedded Company Logo from the Report. Delete the Hidden Table Columns in the Body Section. Add a Hidden Table Control to the Body Section. Rearrange the Existing Controls in the Header Section. Add a Hidden Control for the Company Logo to the Header Section. Add the Database Picture to the Page Header Section. Add a Hidden Textbox Control for the Company Information to the Page Header Section. 9. Change the Controls in the Header Section to use the Custom Code. 10. Add the Report Execution Time, the Page Number and the Total Number of Pages to the Header Section. 11. Run the report.
3-54
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Step by Step In this lab, the following steps need to be executed:
Add Custom Code to the Report 1. Open report 123456704 in Visual Studio Report Designer. 2. Select Report, Report Properties. 3. On the Code tab, add the following custom functions and variables:
Shared CompData as Object Shared PictureData as Object Public Function SetData(NewData as Object, Group as integer) If Group = 1 and NewData > "" Then CompData = NewData End If End Function Public Function SetPicture(NewData as Object) If NewData > "" Then PictureData = NewData End If End Function Public Function GetData(Num as Integer,Group as integer) if Group = 1 then Return Cstr(Choose(Num, Split(Cstr(CompData),Chr(177)))) End If End Function Public Function GetPicture Return PictureData End Function
4. Click OK to close the Report Properties window.
Delete the Embedded Company Logo from the Report 1. Select Report, Embedded Images. 2. Select the Cronus Company logo, and click the Delete button to remove the picture.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-55
Report Design in Microsoft Dynamics® NAV 2009 Delete the Hidden Table Columns in the Body Section 1. In the body section, select the six hidden columns in the table control by clicking the table column handles. 2. Press Delete to delete the columns.
Add a Hidden Table Control to the Body Section 1. In the Toolbox window select the Table control, and drag it to the body section. 2. Remove the Table Detail row, the Table Footer row and the third column. 3. Select the first cell on the header row of the new table. 4. In the Properties window, set the Name property to CompInfoArray. 5. In the Properties window, set the Color property to Red. 6. In the Properties window, set the Value property to the following expression: =Fields!CompInfo_Name.Value & Chr(177) & Fields!CompInfo_Address.Value & Chr(177) & Fields!CompInfo__Post_Code_.Value & Chr(177) & Fields!CompInfo_City.Value & Chr(177) & Fields!CompInfo__Country_Region_Code_.Value & Chr(177) & Fields!CompInfo__VAT_Registration_No__.Value. 7. Select the second cell on the header row of the new table. 8. In the Properties window, set the Name property to CompLogoArray. 9. In the Properties window, set the Color property to Red. 10. In the Properties window, set the Value property to the following expression: =Convert.ToBase64String(Fields!CompInfo_Picture.Value). 11. Right-click one of the two cells and choose "Select 'table2'." 12. In the Properties window, set the Height property for the newly added table to 0.5. 13. In the Properties window, set the Hidden property to True. 14. Place the newly added table control above the "table1" control.
Rearrange the Existing Controls in the Header Section 1. Select all controls in the Page Header. 2. Press the Down arrow on the keyboard to move them two grid units down.
3-56
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report Add a Hidden Control for the Company Logo to the Header Section 1. In the Toolbox window, select the Textbox control and drag it to the top of the Page Header section, above all other existing controls. 2. In the Properties window, set the Hidden property to True. 3. In the Properties window, set the Color property to Red. 4. In the Properties window, set the Value property to the following expression: =Code.SetPicture(ReportItems!CompLogoArray.Value).
Add the Database Picture to the Page Header Section 1. Select the Image control in the page header section. 2. In the Properties window, set the Source property to Database. 3. In the Properties window, set the MIME Type property to image/bmp. 4. In the Properties window, set the Value property to the following expression: =Convert.FromBase64String(Code.GetPicture).
Add a Hidden Textbox Control for the Company Information to the Page Header Section 1. In the Toolbox window, select the Textbox control and drag it to the top of the Page Header section, above all other existing controls. 2. In the Properties window, set the Hidden property to True. 3. In the Properties window, set the Color property to Red. 4. In the Properties window, set the Value property to the following expression: =Code.SetData(ReportItems!CompInfoArray.Value, 1).
Change the Controls in the Header Section to use the Custom Code 1. In the Page Header section, select the textbox containing the Company Name (the first textbox under the Item Catalog textbox). 2. Change the Value property to =Code.Getdata(1,1). 3. Select the textbox containing the company address. 4. Change the Value property to =Code.Getdata(2,1). 5. Select the textbox containing the company post code. 6. Change the Value property to =Code.Getdata(3,1). 7. Select the textbox containing the company city.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-57
Report Design in Microsoft Dynamics® NAV 2009 8. 9. 10. 11. 12.
Change the Value property to =Code.Getdata(4,1). Select the textbox containing the company country/region code. Change the Value property to =Code.Getdata(5,1). Select the textbox containing the VAT Registration No. Change the Value property to =Code.Getdata(6,1).
Add the Report Execution Time, the Page Number and the Total Number of Pages to the Header Section 1. In the Toolbox window, select the Textbox control and drag it to the Page Header section, under the Image control. 2. In the Properties window, set the Value property to the following expression: ="Page " & Globals!PageNumber & "/" & Globals!TotalPages. 3. In the Toolbox window, select the Textbox control and drag it to the Page Header section, under the control created in step 1. 4. In the Properties window, set the Value property to the following expression: ="Date Printed: " & FormatDateTime(Globals!ExecutionTime, DateFormat.LongDate).
3-58
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report
Quick Interaction: Lessons Learned Take a moment and write down three Key Points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-59
Report Design in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. Which decision functions can be used in expressions in Visual Studio Report Designer? (Select all that apply) (√) Iif() (√) Switch() ( ) Case() ( ) Select Case() 2. Can nested IiF() statements be used? ( ) No. ( ) Yes, but only up to two levels (•) Yes ( ) None of the answers is correct. 3. Which function is used to identify the row number in a data region control? ( ) Row ( ) RowNo (•) RowNumber ( ) NoRow 4. Which expression returns the name of the Windows user (without the domain name) that is running an RDLC report? ( ) =Right(USERID, Len(USERID)) (•) =Right(User!UserID, Len(User!UserID) - InStr(User!UserID, "\")) ( ) =Right(Report!UserID, Len(Report!UserID) - InStr(Report!UserID, "\")) ( ) This is not possible as the RoleTailored Client does not use Windows accounts. 5. What is not true about expressions? ( ) Expressions can be used for sorting. ( ) Expressions can be used to determine the visibility of controls. ( ) Expressions can be used for formatting. (√) Expressions cannot be used to insert page breaks in a report.
3-60
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Adding Code to a Report 6. What is true about Custom Code in a report? (Select all that apply) ( ) Functions that are defined in the Classic report are automatically added to the RDLC report layout when using the Create Layout Suggestion option. (√) Custom Code is available in the Expression window using the Code collection. ( ) Custom Code can be added in various places in Visual Studio Report Designer. (√) Custom Code must be added using Visual Basic syntax.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-61
Report Design in Microsoft Dynamics® NAV 2009
3-62
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations
CHAPTER 4: DESIGN CONSIDERATIONS Objectives The objectives are: •
Work with and understand how green bar and dashboard reports are built.
•
Work with and understand how reported layouts will be rendered when exporting to Excel or PDF.
•
Use some tips and tricks that can be useful when designing reports.
Introduction This chapter contains a more in-depth analysis of some advanced report features; such as dashboard reports and green bar reports. In addition, the chapter covers the different export possibilities and the rendering differences. The lessons require that you are familiar with the techniques taught in previous chapters.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-1
Report Design in Microsoft Dynamics® NAV 2009
Report Patterns and Recipes This lesson describes some of the typical challenges that you can encounter when developing reports. It shows how to combine the techniques from previous chapters to build more advanced reports.
Green Bar Matrix The term "green bar report" refers to a continuous paper form that was commonly used to print reports. The paper form had pre-printed white and light green areas to increase the readability. A green bar report actually is a report that prints rows or row groups with alternating background colors. In Chapter 3 is explained how you can define alternating background colors in table controls by setting the BackgroundColor property to an expression: =IIF(RowNumber("table1") Mod 2 = 0, "LimeGreen", "Transparent")
The expression uses the RowNumber() function and the Mod operator to calculate the correct background color. . If you want to create a green bar report using the Matrix control, the technique illustrated in Chapter 3 with the table control will not work. This is because every row in a matrix control must be a group. There is currently no GroupNumber() function on which to base a green bar calculation. In addition, some cells in the matrix may contain no data at all, which causes the group number calculation to be wrong for the empty cells. To work around this, you need to effectively calculate the group number in the row header and then use that value inside the data cells. This can be done either by using a small custom code function or by using the RunningValue function.
Method 1: The Custom Code Function The first method uses a small custom code function: Private bOddRow As Boolean Public Function AlternateColor(ByVal OddColor As String, ByVal EvenColor as String, ByVal Toggle As Boolean) As String If Toggle Then bOddRow = Not bOddRow End If If bOddRow Then Return OddColor Else Return EvenColor End If End Function
4-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations The function has three parameters: a color for odd rows, a color for even rows and a Boolean toggle parameter. The toggle parameter is used to indicate the start of a new row. Typically it will be set to True on the first cell and set to False on all other cells of the matrix row. With each new value that is printed in the column (after each row group), the Toggle parameter changes and the function returns another color. As a result, all cells in a row group will have the same color.
Method 2: The RunningValue() Function The second method uses the RunningValue() function: =IIF(RunningValue(Fields!Item__No__.Value,CountDistinct,Not hing) Mod 2, "PaleGreen", "White")
The RunningValue() function returns a running aggregate of the specified expression. The function has three parameters: a group expression, an aggregate function and a scope. The first parameter contains a group expression that you want to perform the aggregate function on. The expression cannot contain aggregate functions. The second parameter is the aggregate function that you want to apply to the group expression. This function cannot be RunningValue, RowNumber, or Aggregate. The third parameter, scope, refers to the dataset, grouping, or data region that contains the report items to which to apply the aggregate function. If a dataset is specified, the running value is not reset throughout the entire dataset. If a grouping is specified, the running value is reset when the group expression changes. If a data region is specified, the running value is reset for each new instance of the data region. In this second method, the result of the previous expression is stored in an invisible text box named Color. Next, the BackgroundColor property of the other cells will be set to refer to the invisible text box using the following expression: =ReportItems!Color.Value
The next demonstrations show how to use both methods.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-3
Report Design in Microsoft Dynamics® NAV 2009 Demonstration: Create a Green Bar Matrix with a Custom Code Function Ellen asks Mort to improve the readability of the report. Instead of having the item number and item name displayed on an orange background, she asks Mort to have the inventory amounts printed with alternating background colors. She also prefers a lighter pastel background color (PaleGreen). 1. Open report 123456701 in Visual Studio Report Designer. 2. Select Report, Report Properties. 3. On the Code tab, add the following code:
Private bOddRow As Boolean Public Function AlternateColor(ByVal OddColor As String, ByVal EvenColor as String, ByVal Toggle As Boolean) As String If Toggle Then bOddRow = Not bOddRow End If If bOddRow Then Return OddColor Else Return EvenColor End If End Function
4. Click OK to close the Report Properties window. 5. Select the cell containing the Customer No. and Customer Name fields. 6. In the Properties window, change the BackgroundColor property to the following expression: =Code.AlternateColor("White", "PaleGreen", True). 7. Select the cell containing the Inventory amounts. 8. In the Properties window, change the BackgroundColor property to the following expression: =Code.AlternateColor("White", "PaleGreen", False). 9. Exit Visual Studio, import the new RDLC layout in the object, save the object and run it.
4-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations The result will look similar to this:
FIGURE 4.1 THE GREEN BAR MATRIX WITH THE CUSTOM CODE FUNCTION
In the previous figure, Mort notices that the item number and name are still printed in the same alternating background color. To solve this, he inserts a hidden column. 1. Open report 123456701 in Visual Studio Report Designer. 2. Right-click the cell containing the Customer No. and Customer Name fields and choose Select 'matrix1'. 3. Right-click the shaded border around the matrix control and choose Add Row Group. 4. In the Grouping and Sorting Properties window, set the Group on field to the same expression as the cell containing the Item No. and Name. In this case, select =Fields!Item__No__.Value. 5. Click OK to close the window. 6. Select the newly added row group cell. 7. In the Properties window, set the Hidden property to True. 8. In the Properties window, set the BackgroundColor property to the following expression: =Code.AlternateColor("White", "PaleGreen", True) 9. Select the cell containing the item number and item description.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-5
Report Design in Microsoft Dynamics® NAV 2009 10. In the Properties window, set the BackgroundColor property to Transparent. 11. Resize the column width to the minimal size. 12. Exit Visual Studio, import the new RDLC layout in the object, save the object and run it. The result will look similar to this:
FIGURE 4.2 THE GREEN BAR MATRIX WITH A HIDDEN COLUMN
Demonstration: Create a Green Bar Matrix with RunningValue() In this demonstration you will use the RunningValue function to create a green bar matrix. 1. Open report 123456701 in Visual Studio Report Designer. 2. Select the row header cell (the cell containing the Customer No. and Customer Name fields). 3. Press Delete to clear the cell. 4. In the Toolbox window, select the Rectangle control. 5. Click the empty cell to insert a rectangle in the cell. 6. In the dataset, select the Item__No__ element and drag it inside the rectangle. 7. Right-click the Item__No__ text box and select Expression. 8. In the Expression window, enter the following expression: =Fields!Item__No__.Value & " ; " & Fields!Item_Description.Value.
4-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations 9. In the Toolbox window, select the Textbox control and drag it inside the rectangle. 10. In the Properties window, change the Name property of this text box to Color. 11. In the Properties window, change the Hidden property of the Color text box to True. 12. In the Properties window, change the Value property to the following expression: =IIF(RunningValue(Fields!Item__No__.Value,CountDistinct,Not hing) Mod 2, "White", "PaleGreen")
13. Select the rectangle control. 14. In the Properties window, change the BackgroundColor property to the following expression: =ReportItems!Color.Value. 15. Select the Item_Ledger_Entry_Quantity matrix cell. 16. In the Properties window, change the BackgroundColor property to the following expression: =ReportItems!Color.Value 17. Exit Visual Studio, import the RDLC report layout, save and compile the Classic report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-7
Report Design in Microsoft Dynamics® NAV 2009 The result will look similar to this:
FIGURE 4.3 THE GREEN BAR MATRIX WITH THE RUNNINGVALUE FUNCTION
If you want to define alternating background colors for the inventory matrix cells only, you can skip steps 13 and 14.
Dashboards Essentially, a dashboard report is a way to visually present critical data in summary form so that you can make quick and effective decisions, in much the same way that a car dashboard works. With the new reporting solution you can build your own dashboard reports to consolidate information from different areas in a single (report) interface. Also, extra features such as interactive analysis and views, charts and indicators can be added.
4-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations In many cases, a dashboard presents information from different tables by means of charts. Often, a dashboard is filtered so it only shows a subset of data. Instead of showing full details on all records in the different tables, it is used to show only the Top X for specific areas. The following figure shows a typical example of a sales dashboard:
FIGURE 4.4 CUSTOMER PERFORMANCE DASHBOARD
The dashboard contains two charts that give instant access to the top five (5) of the customers based on Total Sales and Balance Due (in local currency (LCY)). Furthermore it contains a chart with the total amount of outstanding orders in LCY. At the bottom of the report, a toggle button is used to show or hide the order details.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-9
Report Design in Microsoft Dynamics® NAV 2009 Dashboard Report Structure The basic structure of a dashboard report typically includes multiple data items without any indentation.
FIGURE 4.5 REPORT DESIGNER WINDOW
In some cases, indented data items can be added to perform additional data processing or grouping. The report will have the necessary sections with the corresponding fields so that the necessary fields are made available in Visual Studio Report Designer.
Dashboard Report Design Dashboard reports often use charts and images to present data. Adding a chart in a report can be done by inserting chart controls in the body section. When the chart control is added to the report, you can further design it. To do so, right-click the chart control and select Properties to open the Chart Properties window.
4-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations Chart Properties The Chart Properties window contains seven tabs allowing you to customize the chart.
FIGURE 4.6 CHART PROPERTIES WINDOW
On the General tab, you can select a chart type and subtype. In addition, you can specify a Title for the chart (and the format of this title). The Palette option allows you to choose a color palette for the chart. Also, you can define the Chart Area and the Plot Area styles. All information related to the underlying data can be found on the Data tab. It contains the name of the dataset, and the data values, categories and series of the chart. Data values, categories and series can be added to the chart by dragging fields from the dataset to the chart. (You can use the Data tab to manage them here.) The X Axis and Y Axis tabs contain options to format the data, labels, gridlines, and so on, that are shown on both the X axis (horizontal) and Y axis (vertical) of the chart. On the Legend tab, you can find an option to include a chart legend. Here you can change the layout, the position and the style of the legend. The 3D effects tab allows adding 3D effects to the chart. You can change horizontal and vertical rotation, transparency and shading.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-11
Report Design in Microsoft Dynamics® NAV 2009 Finally, on the Filters tab, you can add some general data region control filters to limit the information that is shown in the chart. For more information on formatting charts, refer to Get More Out of SQL Server Reporting Services Charts (http://msdn.microsoft.com/enus/library/aa964128.aspx).
The Top X Filter A filter can be added to a dataset, data region, or group when including or excluding specific values for calculations or display. Dataset filters cannot be added in Visual Studio Report Designer, as the dataset is provided by Microsoft Dynamics® NAV 2009. However data region and group filters can be added in Visual Studio Report Designer. Filters are applied at run time first on the dataset, and then on the data region, and then on the group, in top-down order for group hierarchies. In a table, matrix, or list, filters for row groups, column groups, and adjacent groups are applied independently. In a chart, filters for category groups and series groups are applied independently.
Setting Filters on a Data Region Control The following steps show how to add a filter to a data region control. 1. Open a report in Visual Studio Report Designer. 2. Right-click the data region on the design surface, and then click Properties to open the Properties window. 3. Click the Filters tab. This displays the current list of filter equations. By default, the list is empty. 4. Click an empty line. A new blank filter equation appears. 5. In Expression, type or select the expression for the field to filter. To edit the expression, click the expression (fx) button. 6. In the Operator box, select the operator that you want the filter to use to compare the values in the Expression box and the Value box. The operator you choose determines the number of values that are used from the next step. 7. In the Value box, type the expression or value against which you want the filter to evaluate the value in Expression. 8. Click OK.
Setting Filters on a Chart Category Group The following steps show how to add a filter to a chart category group. 1. Open a report in Visual Studio Report Designer. 2. Right-click the data region control and select Properties.
4-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations 3. 4. 5. 6. 7. 8. 9.
10. 11.
Click the Data tab. In the Category group field, select the group to filter. Click the Edit button. Click the Filters tab. This displays the current list of filter equations. By default, the list is empty. Click an empty line. A new blank filter equation appears. In Expression, type or select the expression for the field to filter. To edit the expression, click the expression (fx) button. In the Operator box, select the operator that you want the filter to use to compare the values in the Expression box and the Value box. The operator you choose determines the number of values that are used from the next step. In the Value box, type the expression or value against which you want the filter to evaluate the value in Expression. Click OK.
In the customer dashboard example, the filter is specified on category group level.
FIGURE 4.7 GROUPING AND SORTING PROPERTIES WINDOW
Setting Filters on a Chart Series Group The following steps show how to add a filter to a chart series group. 1. Open a report in Visual Studio Report Designer. 2. Right-click the data region control and select Properties. 3. Click the Data tab.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-13
Report Design in Microsoft Dynamics® NAV 2009 4. In the Series group field, select the group to filter. 5. Click the Edit button. 6. Click the Filters tab. This displays the current list of filter equations. By default, the list is empty. 7. Click an empty line. A new blank filter equation appears. 8. In Expression, type or select the expression for the field to filter. To edit the expression, click the expression (fx) button. 9. In the Operator box, select the operator that you want the filter to use to compare the values in the Expression box and the Value box. The operator you choose determines the number of values that are used from the next step. 10. In the Value box, type the expression or value against which you want the filter to evaluate the value in Expression. 11. Click OK. For examples of filter equations, refer to Filter Equation Examples (Reporting Services) (http://msdn.microsoft.com/en-us/library/cc627464.aspx).
The Order Details List The order details are displayed under the Outstanding Orders chart. By default all details are hidden. When clicking the Show Order Details label, the details will be shown. This is done by defining the Hidden and ToggleItem properties for the row cells.
4-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations Charts in Tables Instead of showing fields as numbers, you can insert charts in the table to display the values. Functions can be used, such as the Avg() function, to calculate specific values. You can then use the calculated value as a data value for each chart. At the same time, the "ALL" expression is used as a category group expression.
FIGURE 4.8 GROUPING AND SORTING PROPERTIES WINDOW
Report Rendering Considerations Reporting Services provides interactive reporting features that allow you to work with a report at run time. Not all of the report output formats support the full range of interactive features.
Excel Rendering Reporting Services supports the rendering of reports for Microsoft® Office Excel®. If you plan to render reports to Excel, be aware of some of the unique attributes of the Excel rendering extension. For example: •
Each page in the report becomes an Excel worksheet. Excel does not support the concept of page height and width, so only explicitly defined page breaks will occur.
•
Specifying worksheet names is not supported.
•
The rendering extension builds a tabular structure out of the report.
•
Excel does not support background images for individual cells.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-15
Report Design in Microsoft Dynamics® NAV 2009 •
Excel does not support nested containers other than lists.
•
Charts are rendered as pictures, not as Excel charts.
•
Rectangles are converted to groups of cells. If rectangles contain other items, the rectangle becomes a region of cells, and the border and background color of the rectangle are applied to the region of cells.
Using Tables Instead of Lists for Excel-specific Reports A table uses a fixed column width. This matches very well with the tabular format of Excel reports. The items in the report table will line up as you expect them to when rendered in Excel. In contrast, a list is a freeform style. Items in the list are positioned in the worksheet relative to their location in the report. This can lead to unexpected results. If your report uses a list, be sure to check the rendering to Excel to see if the results are acceptable. Even with tables, if you have a header that spans multiple columns in a report, the Excel rendering extension may need to merge cells or introduce new columns. This can affect the ability to sort and manipulate data in the Excel spreadsheet. If you are planning to render to Excel, try to ensure that the left or right edges of the report item line up to minimize cell merging.
Maximum Number of Pages in Long Reports To prevent Excel from generating an error, keep track of the number of pages in lengthy reports. Specifically, each page in a report becomes a worksheet in Excel. However, Excel can only support a maximum number of worksheets for each workbook, limited by available memory. If the report pages exceed that limit, Excel generates an error.
Color Differences in Rendering to Excel Excel supports a predefined set of colors. When you render a report, the Excel rendering extension maps the report colors to the best match in the natively supported colors in Excel.
4-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations PDF Rendering The portable document format (PDF) rendering extension creates reports that can be viewed with Adobe Acrobat readers. The rendering extension does not require Adobe software to render the report. However, PDF viewers such as Adobe Acrobat are required for viewing or printing a report in PDF format. When designing reports for PDF output, take into account the following considerations: •
Fonts are not embedded in the PDF reports.
•
Document maps are rendered as PDF bookmarks. In the document maps, the hierarchy is ignored. (All bookmarks will be on the same level.)
•
Specify page width, page height and margins of the PDF, if necessary.
•
The rendering extension creates PDF 1.3 files that are compatible with Adobe Acrobat 4.0 and later versions.
Installing the Appropriate Fonts on the Client Computer The PDF extension does not embed the fonts in the report. To view a report in the correct font, you need to ensure that all necessary fonts are installed on the client computer that is used to view the report. Otherwise, font substitution will most likely occur.
SAVEASEXCEL and SAVEASPDF In Microsoft Dynamics NAV 2009 two new C/AL functions have been introduced
SAVEASEXCEL The SAVEASEXCEL function can be used on the Report type and on Report variables to save a report as a Microsoft Office Excel file. It has the following syntax: [Ok :=] Report.SAVEASEXCEL(Number, FileName, [, Record]) [Ok :=] Report.SAVEASEXCEL(FileName)
When SAVEASEXCEL is called, the report is generated and saved to "FileName." A Saving to Excel window is displayed, which shows the progress of the process. If you click Cancel, the report will not be generated or saved as an Excel file. Also, the Request Form will not be shown. The return value informs you whether the report is saved successfully. If the report cannot be saved for a specific reason, the function will return False.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-17
Report Design in Microsoft Dynamics® NAV 2009 SAVEASPDF The SAVEASPDF function allows saving a report as a PDF file. It has the same syntax as the SAVEASEXCEL function. No PDF software is required to create PDF files. The SAVEASPDF and SAVEASEXCEL functions cannot be used on the Classic client. However the functions can be used in codeunits that are exposed as Web services. Other applications can call the Web services to have reports generated.
Useful Tips This lesson describes several techniques that can be useful when creating clientside reports in Visual Studio. It assumes that you are familiar with the content from the previous chapters.
CanGrow and CanShrink Whether you are designing reports for the Classic or the RoleTailored client, one of the challenges that typically arises is the column size. Especially in reports with multiple columns it can be quite a task to have all information available on one line. The width and height of a textbox can be defined at design time by setting the Width and Height properties. Since both properties are not available in run-time, you cannot use a complex expression to make a text box fit the widest or longest value. The width must be defined using a single expression in design-time and will be respected in run-time. This does however not apply to the height of a column. Although the Height property cannot be bound to a complex expression either, you can control the height of a text box using the CanGrow and CanShrink properties. The CanGrow and CanShrink properties indicate whether the size of a text box can increase or decrease vertically according to its content. If both properties are set to False, the text box will not grow. The static size of the text box as defined in Visual Studio Report Designer will be used, regardless of the length of its value. If you set CanGrow to True, the text box will expand vertically if the text box is not wide enough to show the value. To allow the text box to shrink based on its contents, you can change the CanShrink property for the text box. If you set CanGrow to True for one text box in a table row, all other cells on the same row might expand vertically too (even if CanGrow for these text boxes is set to False). Unfortunately, CanGrow and CanShrink behave differently for each rendering extension (http://msdn.microsoft.com/en-us/library/cc627537.aspx).
4-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations Check Boxes Boolean fields can be displayed in multiple ways. You can use "True/False," "Yes/No," even work with "1/0" or any other combination. You can either use the proper data value of the field or work with expressions to translate the intrinsic value to a different and multi-language enabled presentation. Visual Studio Report Designer does not include a separate check box control. However there is a way to simulate the check box control in reports. For a field to be displayed as a check box, you can change the font of the text box to Wingdings. In addition, you can set the Value property of the text box to an expression similar to: =IIF(Fields!Customer__Print_Statements_.Value = "1", Chr(0254), "o")
New Lines To include line breaks in an expression, you can use the vbCrLf constant: = Fields!Customer_Name.Value & vbCrLf & Fields!Customer_Address.Value & vbCrLf & Fields!Customer__Post_Code_.Value & space(2) & Fields!Customer_City.Value & vbCrLf & Fields!Customer__Country_Region_Code_.Value
You can use this to format text as a block in a textbox. In the previous expression, the address fields will be formatted as a block inside a textbox. If the line break is the last character in a textbox, it will be ignored. (If you have multiple line breaks, only the last one will be ignored.) Other VB constants such as vbTab are not supported inside a textbox. To insert a number of spaces, you can use the Space() function.
Use Rectangles to Keep Objects Together Rectangles can be used either as graphical elements or as containers of objects. As object containers, they keep objects together on a page and control how objects move and push each other. To keep multiple objects together on a page, put the objects within a rectangle. You can then put a page break before or after the rectangle by using the PageBreakAtStart or PageBreakAtEnd properties for the rectangle.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-19
Report Design in Microsoft Dynamics® NAV 2009 Using Rectangles to Control Item Growth and Displacement or Visibility Items within a rectangle become peers of each other and are governed by the rules of how peer items are positioned on the page as they move or grow. For example: •
Items will push or displace each other within the rectangle.
•
Items will not push or displace items outside the rectangle, because they are not their peers.
•
If necessary, a rectangle will grow to accommodate the items it contains.
You can use this logic to your advantage when dealing with objects that expand. For example: •
If you want to leave a blank space in your report for a table to expand into, group the blank space and the table in the same rectangle. When the table grows, it will push the blank space.
•
If you want to prevent a matrix from pushing items off the right edge of the page, put the matrix within a rectangle with blank space to its right. Now, the matrix is no longer a peer to the other item on the page and will not be able to push it until the matrix can no longer be contained within its rectangle.
If you have multiple controls that need to be hidden together, put them inside a rectangle and define the Visibility for the rectangle. The following code sample shows or hides the rectangle (and all controls inside the rectangle) based on the value of a Boolean variable (HideRectangle) on the request options page: =IIF(First(Fields!HideRectangle.Value = True), True, False)
To see if a control is placed inside a rectangle control, check the control's Parent property. The property cannot be edited directly in the Properties window. To change the Parent property, drag the control to another place. Default value for all controls is the section that they are placed in.
Avoid Blank Pages Sometimes, you will see blank pages when outputting reports to a physical page format such as PDF or print. Generally, this will happen when the size of the report body exceeds the size of the page.
4-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations For rendering formats that render physical pages (such as PDF), you can set the page height and page width properties for the report to control the pagination. 1. Select Report, Report Properties in Visual Studio Report Designer. 2. In the Report Properties window, click the Layout tab:
FIGURE 4.9 THE REPORT PROPERTIES WINDOW WITH THE DEFAULT PAGE SIZE AND MARGINS
Here you can define the page height and page width along with the different report margins. To ensure that all the contents fit on a single page, the body width plus the margins need to be less than the defined page width. However, some report items can grow horizontally and can cause the width of the body to exceed the page width. Typical examples are matrix data region controls and images set to automatically Autosize or Fit. One thing that is important to know is that setting the Body size at design time is not generally useful in controlling pagination. The body is simply the container for the collection of objects on the report. The design time size of the body represents the smallest amount of space that will be taken up by the report. However, if any objects grow as they are filled with data, the body will expand to contain them. Mostly, the body will grow taller (tables, lists, and text boxes are a few of the items that will cause vertical growth) but can also grow wider (matrices and autosized images can cause horizontal growth).
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-21
Report Design in Microsoft Dynamics® NAV 2009 When the runtime size of the body (plus the page header and footer size, if they are defined) exceeds the specified page size (minus the margins), a physical page break occurs. It is important to understand that controls on the page that do not look like they contain any information (a wide text box) can cause a blank page to be added to the report (when printed or viewed in Print Layout mode) if the control exceeds the page boundaries. Page breaks can also be specified explicitly before or after instances of report items (rectangles, groups, data regions). The Excel rendering format does not explicitly support pagination. The page size and margins are mapped into the Excel document for printing within Excel. For these reports, you will need to specifically include page breaks to break the report into multiple worksheets.
Use Page Breaks to Improve Performance for Large Reports If you do not specify a page size or page breaks for a report that returns a large amount of data, some report formats will try to render the report as a single page. For example, Excel has no default notion of a fixed page size. As a result, if you have a very large report, Excel will try to render it as a single worksheet. In general, using page breaks improves the performance for the users accessing the report, because they can view the first page while the rest of the report is being rendered.
Insert a Page Break Following a Specific Number of Rows in a Table You can use the Ceiling function to group the rows within a table and insert a page break at the end of each group. The Ceiling function returns the smallest number that is not less than the argument. For example, to add a page break after every 30 rows, you can use the following expression to group the rows: =Ceiling(RowNumber(Nothing)/30)
Add Alternating Bars to a Table It is possible for you to create a report that contains a table or matrix in which every other row is shaded. This bar effect makes it easier to visually track the different rows across a page. To more closely simulate the old “green bar” paper that was used at one time to run large reports on high-volume data center printers, you can make the alternating bars green. To achieve this effect, use the Iif() function to assign the background color conditionally, based on whether the row number is odd or even. For example: =IIF(RowNumber(Nothing) Mod 2,"PaleGreen","White")
4-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations Add Report Items to the Page Header For long reports, you may want to include text from the body of the report in the header. For example, a directory listing can list the first and last occurrence of the last name field in the header to indicate the range of names included on the page. To do this, you can include an expression using the First() function in a text box in the page header. To display the first occurrence of the LastName value on the page, the expression then resembles the following: =First(ReportItems!LastName.Value)
Likewise, use an expression with the Last() function to provide the last value of the LastName text box on the page. For example: =Last(ReportItems!LastName.Value)
Pagination One key design issue for long reports is controlling where the page breaks occur. Page breaks are controlled by two factors: •
Page size
•
Page breaks specifically included before or after objects
Page Size To control page size, set the page height and width properties for the report by using the following guidelines: •
For rendering formats that render physical pages (PDF), use the PageHeight and PageWidth properties for the report.
•
Some rendering formats, such as Excel, do not support page size. For these reports, it is necessary to specifically include page breaks to break the report into multiple pages.
If the report itself is wider than the defined page width then the report will break across multiple pages horizontally.
Page Breaks You can apply page breaks at the beginning or end of a rectangle, table, matrix, list, chart, or group. Reporting Services tries to keep all the data within the item or grouped together on the same page. To include page breaks specifically before or after items, use the PageBreakAtEnd and PageBreakAtStart properties for the item.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-23
Report Design in Microsoft Dynamics® NAV 2009 Setup Multiple Columns The Report Designer allows you to easily create multicolumn reports. Just like a newspaper, a multicolumn report can conserve space by displaying the report data in more than one column.
FIGURE 4.10 EXAMPLE OF A MULTICOLUMN REPORT
The trick to creating this kind of multi-column report is to ensure that the report data width does not exceed the column width. To view the report rendered correctly in multiple columns, ensure that you preview the report by clicking the Print Layout button. If you just preview the report, you cannot view the data flowing in columns because the preview mode does not take into consideration the page settings. Currently, Reporting Services supports defining multiple columns only at the report level. You cannot, for example, define a multicolumn layout by region, for example, a table region. To define the number of columns, select Report, Report Properties from the menu. On the Layout tab, you can specify the number of columns, the page size and the margins.
4-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations When setting up the column widths, you must ensure that you have enough page space to accommodate the number of columns, by using the following formula: Page width-(left margin + right margin) >= number of columns * column width + (number of columns - 1) * column spacing The Report Designer eliminates the trial-and-error fitting game by showing you the outline of the columns in layout mode. This allows you to easily see whether the report width exceeds the page width.
Summary This chapter illustrated how to use the techniques from the previous chapters to build some more advanced reports. It also explained the different export options in the ReportViewer control and how reports are rendered. The chapter also provided useful tips for building reports.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-25
Report Design in Microsoft Dynamics® NAV 2009
Test Your Knowledge Test your knowledge with the following questions. 1. What happens when a report is exported with a multi-level document map to PDF? ( ) The document map is not exported. ( ) The document map is exported without changes to the Bookmarks pane. ( ) Tthe document map is exported but the hierarchy is lost and all items appear on the same level in the Bookmarks pane. ( ) An error message is displayed since it is not possible to export reports with multi-level document maps. 2. What happens when a report with a chart is exported to Excel? ( ) The chart is converted to an Excel chart. ( ) The chart is converted to an image. ( ) The chart is converted to a table. ( ) An error message is displayed since it is not possible to export reports with charts. 3. Which two C/AL functions for exporting reports are added in Microsoft Dynamics NAV 2009? (Select all that apply) ( ) SAVEASHTML ( ) SAVEASPDF ( ) SAVEASXML ( ) SAVEASEXCEL 4. Which operator is used to filter a recordset to the three highest values? ( ) Max(3) ( ) Max N ( ) Top 3 ( ) Top N 5. Which operator is used to filter a recordset to the three lowest values? ( ) !Top N ( ) -Top N ( ) Bottom N ( ) <> Top N
4-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations
Lab 4.1 - Creating Green Bar Reports In this lab you will fine-tune the report created in Lab 1.2 by adding green bar functionality. Scenario Ellen asks Mort to improve the readability of the Inventory report. Instead of having the item number and item name displayed on an orange background, she wants to have the inventory amounts printed with alternating background colors. She also prefers a lighter pastel background color (LightSteelBlue).
Challenge Yourself! Create a green bar matrix report showing the item inventory by location. The rows need to have alternating backgrounds colors. To select the correct colors, use a function that returns either "LightSteelBlue" or "White" every time a new item number is printed.
Need a Little Help? To build the report, execute the following steps 1. Add a custom function to the report 2. Change the background color for the row header cells 3. Change the background color for the other row cells
Step by Step Add a Custom Function to the Report To add a custom function to the report, use the following procedure: 1. Open report 123456701 in Visual Studio. 2. Select Report, Report Properties 3. On the Code tab, add the following custom variable and function:
Private bOddRow As Boolean Public Function AlternateColor(ByVal OddColor As String, ByVal EvenColor as String, ByVal Toggle As Boolean) As String If Toggle Then bOddRow = Not bOddRow End If If bOddRow Then Return OddColor Else
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-27
Report Design in Microsoft Dynamics® NAV 2009 Return EvenColor End If End Function
4. Click OK to close the Report Properties window.
Change the Background Color for the Row Header Cell 1. Select the first cell on the second table row (the cell containing the Item No. and Description fields). 2. In the Properties window, select the BackgroundColor property. 3. Change the Value of the BackgroundColor property to the following expression: =Code.AlternateColor("White", "LightSteelBlue", True).
Change the Background Color for the Other Row Cells 1. Select the second cell on the second table row (the cell containing the Inventory field). 2. In the Properties window, select the BackgroundColor property. 3. Change the Value of the BackgroundColor property to the following expression: =Code.AlternateColor("White", "LightSteelBlue", False). 4. Exit Visual Studio, import the new RDLC layout in the object, save the object and run it.
4-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations The result will look similar to this:
FIGURE 4.11 GREEN BAR REPORT PREVIEW
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-29
Report Design in Microsoft Dynamics® NAV 2009
Lab 4.2 - Creating a Top X Report In this lab you will add Top X functionality to report 123456706, Resource Utilization - Chart. Scenario Prakash is looking for some available resources for one of the projects and wants to check the resource utilization. The current report 1106, Resource -Utilization, does not provide this information right away, since it is sorted by resource number and sorting cannot be changed. Prakash wants to see the existing report content replaced by two charts. The first one needs to show the three most utilized resources; the second chart needs to show the five least utilized resources. Finally, he asks Mort not to delete the current report content. Instead, he proposes to hide the content, and include a button or a label that can be clicked to show or hide the details dynamically. After creating a copy of the original report, Mort starts developing.
Challenge Yourself! Make a copy of report 1106, Resource - Utilization and save it as report 80006, Resource - Utilization Chart. Extend report 80006 so that it shows at the same time a Top 3 chart of the three most used and a Top 5 chart of the least used resources. Add a "Show Details" textbox that allows toggling the visibility of the current report content (the table control). The table needs to be displayed under the charts.
Need a Little Help? The following steps shows how to create the Top X Report. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.
4-30
Import report 123456706. Reorganize the body section. Include a "Show Details" Textbox to Show/Hide the Table. Format the Show Details Textbox. Hide the Current Report Content. Add a Top 3 Chart for the Most Utilized Resources. Add Data Elements to the Chart Control. Format the Top 3 Chart. Add a Top 5 Chart for the Least Used Resources. Add Data Elements to the Chart Control. Format the Top 5 Chart. Run the report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations Step by Step Import Report 123456706 To import the object in the demonstration database, use the following procedure: 1. 2. 3. 4. 5. 6. 7. 8. 9.
Open the Microsoft Dynamics NAV 2009 demonstration database. Open the CRONUS International Ltd. demonstration company Select Tools, Object Designer to open the Object Designer. Select File, Import. Browse to the report R123456706.fob. Click OK to start the import. In the dialog box, choose to open the Import Worksheet window. In the Action column, verify that the action is set to Create. Click OK to import the object in the database.
Reorganize the Body Section 1. 2. 3. 4. 5.
Open report 123456706 in Visual Studio Report Designer. Select the body section. Change the height of the body section to 4.72 inch. Select the table1 data region control. Move it to the bottom of the body section.
Add a Show Details Textbox 1. In the Toolbox window, select the Textbox control. 2. Click the body section to insert a textbox control. 3. Move the newly added textbox control to the left of the body section. Place it immediately under the Resource_TABLECAPTION__________ResFilter textbox.
Format the Show Details Textbox 1. Select the newly added textbox. 2. In the Properties window, set the Name property to ShowDetails. 3. In the Properties window, set the BackgroundColor property to LightGrey. 4. In the Properties window, set the Color property to Black. 5. In the Properties window, set the TextAlign property to Center. 6. In the Properties window, set the FontWeight property to Bold.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-31
Report Design in Microsoft Dynamics® NAV 2009 Hide the Current Report Content 1. 2. 3. 4. 5.
Open report 123456706 in Visual Studio Report Designer. In the body section, select the table1 data region control. Right-click the grey shaded border and select Properties. In the Properties window, set the Hidden property to True. In the Properties window, set the ToggleItem property to ShowDetails.
Add a Top 3 Chart for the Most Utilized Resources 1. 2. 3. 4.
In the Toolbox window, select the Chart control. Click the body section to insert the chart control. In the Properties window, change the Left property to 0 inch. In the Properties window, change the Top property to 0.79 inch.
Add Data Elements to the Chart Control 1. Double-click the chart control. 2. In the Website Data Sources window, select the Resource__No__ element. 3. Drag it to the Drop Category Fields Here area. 4. In the Website Data Sources window, select the Resource__Usage__Qty___ element. 5. Drag it to the Drop Data Fields Here area.
Format the Top 3 Chart 1. Right-click the chart control and select Properties. 2. In the Chart Properties window, on the General tab, enter the following text in the Title field: Top 3 - Resource Utilization. 3. In the Palette field, select Excel. 4. In the Chart Type field, select Column. 5. In the Chart Sub-type field, select Stacked. 6. On the Data tab, in the Category groups field, select the chart1_CategoryGroup1. 7. Click the Edit button. 8. On the Filters tab, select =Fields!Resource__Usage__Qty___.Value in the Expression field. 9. In the Operator column, select Top N. 10. In the Value column, enter =3.
4-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations 11. On the Sorting tab, in the Expression column, select =Fields!Resource__Usage__Qty___.Value. 12. In the Direction column, select Descending. 13. Click the OK button to close the Grouping and Sorting Properties window. 14. On the X Axis tab, check the Show Labels option. 15. On the X Axis tab, check the Side Margins option. 16. On the Y Axis tab, in the Title field, enter Usage (Qty). 17. On the Legend tab, uncheck the Show Legend option. 18. Click OK to close the Chart Properties window.
Add a Top 5 Chart for the Least Used Resources 1. 2. 3. 4.
In the Toolbox window, select the Chart control. Click the body section to insert the chart control. In the Properties window, change the Left property to 3.15 inch. In the Properties window, change the Top property to 0.79 inch.
Add Data Elements to the Chart Control 1. Double-click the chart control. 2. In the Website Data Sources window, select the Resource__No__ element. 3. Drag it to the Drop Category Fields Here area. 4. In the Website Data Sources window, select the Resource__Usage__Qty___ element. 5. Drag it to the Drop Data Fields Here area.
Format the Top 5 Chart 1. Right-click the chart control and select Properties. 2. In the Chart Properties window, on the General tab, enter the following text in the Title field: Bottom 5 - Resource Utilization. 3. In the Palette field, select Excel. 4. In the Chart Type field, select Column. 5. In the Chart Sub-type field, select Stacked. 6. On the Data tab, in the Category groups field, select the chart2_CategoryGroup1. 7. Click the Edit button. 8. On the Filters tab, select =Fields!Resource__Usage__Qty___.Value in the Expression field. 9. In the Operator column, select Bottom N.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-33
Report Design in Microsoft Dynamics® NAV 2009 10. In the Value column, enter =5. 11. On the Sorting tab, in the Expression column, select =Fields!Resource__Usage__Qty___.Value. 12. In the Direction column, select Ascending. 13. Click the OK button to close the Grouping and Sorting Properties window. 14. On the X Axis tab, check the Show Labels option. 15. On the Y Axis tab, check the Side Margins option. 16. On the Y Axis tab, in the Title field, enter Usage (Qty). 17. On the Legend tab, uncheck the Show Legend option. 18. Click OK to close the Chart Properties window.
Run the Report 1. 2. 3. 4. 5.
Exit Visual Studio. Save and import the RDLC changes. Save and compile the report in the Report Designer. Click Start, Run. In the Open field, enter: DynamicsNAV:////runreport?report=123456706 6. Click OK to run the report.
After you click the Show Details button, the report looks similar to this:
FIGURE 4.12 TOP X REPORT PREVIEW
4-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Design Considerations
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-35
Report Design in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. What happens when a report is exported with a multi-level document map to PDF? ( ) The document map is not exported. ( ) The document map is exported without changes to the Bookmarks pane. (•) Tthe document map is exported but the hierarchy is lost and all items appear on the same level in the Bookmarks pane. ( ) An error message is displayed since it is not possible to export reports with multi-level document maps. 2. What happens when a report with a chart is exported to Excel? ( ) The chart is converted to an Excel chart. (•) The chart is converted to an image. ( ) The chart is converted to a table. ( ) An error message is displayed since it is not possible to export reports with charts. 3. Which two C/AL functions for exporting reports are added in Microsoft Dynamics NAV 2009? (Select all that apply) ( ) SAVEASHTML (√) SAVEASPDF ( ) SAVEASXML (√) SAVEASEXCEL 4. Which operator is used to filter a recordset to the three highest values? ( ) Max(3) ( ) Max N ( ) Top 3 (•) Top N 5. Which operator is used to filter a recordset to the three lowest values? ( ) !Top N ( ) -Top N (•) Bottom N ( ) <> Top N
4-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports
CHAPTER 5: RUNNING REPORTS Objectives The objectives are: •
Use the features of the ReportViewer control.
•
Examine how to add a report to a page and the Departments section.
•
Examine how to create and run hyperlinks to reports from the command prompt, the Start menu, the Desktop and Microsoft Internet Explorer.
•
Understand how to create a hyperlink to a page in the RoleTailored client
•
Understand how to create a hyperlink to a page in a RoleTailored client report.
•
Explore where to find additional resources and information about reporting.
Introduction In Microsoft Dynamics® NAV 2009, reports can be incorporated into menus, or they can be called from, for example, a command button on a form or page. When designing reports, you will often want to run them before they are integrated into the application. In the previous chapters, reports were run from the Start menu. This chapter will show how to integrate the reports into the RoleTailored client interface and how to create hyperlinks to reports.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-1
Report Design in Microsoft Dynamics® NAV 2009
The ReportViewer Control Microsoft Visual Studio® 2005 and 2008 include report design functionality and ReportViewer controls so that you can add full-featured reports to custom applications. Reports can contain tabular, aggregated, and multidimensional data. ReportViewer controls are provided so that you can process and display the report in your application. There are two versions of the control. The ReportViewer Web server control is used to host reports in ASP.NET projects. The ReportViewer Windows Forms control is used to host reports in Windows® application projects. The ReportViewer control processes .rdlc files. Both controls can be configured to run in local processing mode or remote processing mode. How you configure the processing mode affects everything about the report from design to deployment. •
Local processing mode refers to report processing that is performed by the ReportViewer control in the client application. All report processing is performed as a local process using data that your application provides. To create the reports used in local processing mode, use the Report project template in Visual Studio.
•
Remote processing mode refers to report processing that is performed by a Microsoft SQL Server® 2005 Reporting Services report server. In remote processing mode, the ReportViewer control is used as a viewer to display a predefined report that is already published on a Reporting Services report server. All processing from data retrieval to report rendering is performed on the report server. To use remote processing mode, you must have a licensed copy of SQL Server 2005 Reporting Services.
Microsoft Dynamics NAV 2009 uses the ReportViewer 2008 Windows Forms control in local processing mode.
ReportViewer Toolbar The ReportViewer control includes a toolbar that provides navigation, search, export, and print functionality so that you can work with reports in a deployed application.
FIGURE 5.1 THE REPORTVIEWER TOOLBAR
5-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports Document Maps The ReportViewer toolbar includes an icon used to toggle a document map on a report. A document map is a navigation area that is attached to the left side of the report view area. It contains a list of links that users can click to navigate to a specific area of the report. Not all reports have a document map; you must define one in the report definition to use this feature. For more information about document maps and other interactive report features, refer to Chapter 2.
Stopping and Refreshing a Report You can use the Refresh and Stop buttons to trigger or stop report rendering. If you click Refresh for a server report that is processed remotely, the report server reprocesses the report with the most recent data. Note that report execution options that are configured on the report determine whether data is actually refreshed or retrieved from cache. The control does not check server report properties, so you must find out from the report server administrator whether the report is configured to use live data. Refresh behavior differs for local processing mode. Because locally processed reports use data that is provided by your application, it is assumed that application code is handling refresh operations. To use the Refresh button on the toolbar, you must provide code that handles the Refresh event. If you do not handle this event, clicking Refresh has no effect. As Microsoft Dynamics NAV 2009 uses local processing, the Refresh functionality will not be available. The Stop button can be used to stop a report when testing RDLC reports or when an RDLC report has slow performance.
Zooming the Report Page The ReportViewer toolbar provides standard zoom functionality so that you can enlarge or shrink the report.
Searching a Report The ReportViewer toolbar includes a search field so that you can find specific text within a report. Search for content in the report by typing a word or phrase that you want to find. The search is case-insensitive and begins at the page or section that is currently selected. Wildcards and Boolean search operators are not supported. Only visible content is included in a search operation. If the report uses show / hide functionality, hidden content is not exposed through search operations. To search for subsequent occurrences of the same value, click Next.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-3
Report Design in Microsoft Dynamics® NAV 2009 Previewing a Report and Setting Page Sizes The ReportViewer toolbar in the Windows Forms control includes commands for viewing a report in print layout and setting page sizes. When you click Print Layout, the ReportViewer toolbar is updated to show just the commands that you can use during preview. Print Layout is a toggle command. You can switch between preview and report session by clicking this button. When clicking Page Size, you can specify page dimensions that are used only for print output. The page dimensions are initialized with values from the report definition, but you can override the values for printing purposes. You cannot save the values with the report.
Exporting a Report The ReportViewer toolbar provides export formats so that you can save a report as an Excel or PDF application file. The same report can have a different appearance and functionality depending on the rendering format you select. Reports that have links, document maps, and bookmarks might not function properly once the report is saved to a file. Depending on how items are aligned in a report, the report layout in a different file format might include extra pages or white space that you did not expect.
Printing a Report The ReportViewer toolbar provides print support. Print support is implemented differently for each version of the control and the processing mode you use. Printing reports from the Windows Forms control uses the print functionality of the operating system.
Print a Report from the RoleTailored Client After a report is created and designed using Visual Studio, you can add the report to the interface of the RoleTailored client to make it available to the end-users. Reports can be added in several ways: in the Action Pane of a page, in the Role Center menu, in the Activities page of a Role Center or in the Departments section.
Adding Reports to a Page The following procedure explains how to make a report available in the RoleTailored client by adding the report to the promoted actions pane in the Item List page. 1. In the Microsoft Dynamics NAV Classic client, open Object Designer, and then click Page. 2. Select the page to display the report, for example, Page 31, Item List. 3. Click Design to open the page in Page Designer.
5-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 4. Select an empty line in the designer. Click View, and then Actions to open Action Designer. 5. Scroll down to the ActionContainer that has Reports as its subtype. 6. Select the line that has Inventory - List as its caption. 7. Press F3 to insert a new empty line (or select Edit, New). 8. On the new line, add an action to the list. 9. In the Caption field enter a name for the action: Inventory Matrix. 10. In the Type field, select Action. 11. Click View, and then Properties to open the Properties window for the new action. 12. In the Value field of the RunObject property, click the drop-down arrow and select report 123456701 in the Object List window. 13. In the Properties window, set the Promoted property to Yes, and set the PromotedCategory property to Report. 14. Compile and save the page. 15. Open the RoleTailored client and then open the Item List page.
FIGURE 5.2 THE NEW REPORT IS ADDED TO A PAGE.
The report is added to the list of promoted actions. Click the action to run the report. The report is also available in the Reports menu that appears right above the actions pane.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-5
Report Design in Microsoft Dynamics® NAV 2009 Demonstration: Adding Reports to a Role Center Menu Ellen wants the Inventory Matrix report to be available for her colleague John. Mort will add it to the menu of John's Role Center. 1. In the Microsoft Dynamics NAV Classic client, open Object Designer. 2. Click the Page button. 3. Select page 9009, Whse. Worker WMS Role Center. 4. Click Design to open the page in Page Designer. 5. Select an empty line in the designer. Click View, and then Actions to open Action Designer. 6. Scroll down to the Action that has Customer Labels as its Caption. 7. Click the Separator button to insert a separator. 8. Move the cursor one line down. 9. Press F3 to insert a new empty line (or select Edit, New). 10. On the new line, in the Caption field, enter a name for the action: Inventory Matrix. 11. In the Type field, select Action. 12. Click View, and then Properties to open the Properties window for the new action. 13. In the Value field of the RunObject property, click the drop-down arrow and select report 123456701 in the Object List window.
5-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 14. Compile and save the page. 15. Open the RoleTailored client. 16. In the navigation pane, click the Role Center page.
FIGURE 5.3 THE NEW REPORT IS ADDED TO THE ROLE CENTER MENU.
Now the report is added to the role center menu. Click the action to run the report.
Demonstration: Adding Reports to the Role Center Activities John is not that experienced with computers. He regularly calls Mort to ask where he can find the Inventory Matrix report. To help John, Mort will make the report accessible as a link on the Role Center page. 1. In the Microsoft Dynamics NAV Classic client, open Object Designer. 2. Click the Page button. 3. Select page 9056, Warehouse Worker Activities. 4. Click Design to open the page in Page Designer. 5. Scroll down to the Group that has Internal as its Caption. 6. Select View, Actions. 7. On the first empty line, in the Caption field, enter a name for the action: Print Inventory Matrix. 8. In the Type field, select Action.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-7
Report Design in Microsoft Dynamics® NAV 2009 9. Click View, and then Properties to open the Properties window for the new action. 10. In the Value field of the RunObject property, click the drop-down arrow and select report 123456701 in the Object List window. 11. Compile and save the page. 12. Open the RoleTailored client and then open the Role Center page.
FIGURE 5.4 THE NEW REPORT IS ADDED TO THE ACTIVITIES PAGE.
Now the report is added to the Internal group in the Role Center page. Click the action to run the report.
Adding Reports to a Departments Section In Microsoft Dynamics NAV 2009, navigation through the application is done through the use of the Navigation Pane, which is made of MenuSuite objects. MenuSuite objects contain the main menu content that is displayed in the Navigation Pane (in the Classic client) and in the Departments Page (in the RoleTailored client) and have a layered structure. In the Classic client, application objects, such as forms and reports, are accessed from the Navigation Pane. In the RoleTailored client, application objects, such as pages and reports, are accessed from either the Departments page or the Role Center page. The Departments item in the navigation pane of the RoleTailored client provides links to all the pages of the RoleTailored client. The links and pages under
5-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports Departments are generated automatically based on the menu suite of the RoleTailored client user. In this way, the Departments page in the RoleTailored client is similar to the Navigation Pane in the Classic client: •
It gives access to reports and forms or pages.
•
It is built using MenuSuite objects.
Unlike any other application objects, the ID of the MenuSuite is defined by C/SIDE depending on the target client and the MenuSuite level. The ID of a MenuSuite for the RoleTailored client is the ID of the MenuSuite for the Classic client with the same level, plus 1000, as shown in the following table. Level
MenuSuite Object in the Classic Client
MenuSuite Object in the RoleTailored Client
MBS
10 MBS
1010 Dept - MBS
Addon 1
51 Add-on 1
1051 Dept - Add-on 1
Compa ny
90 Company
1090 Dept - Company
To modify the Navigation Pane or the Departments Page, you can design the existing or create new MenuSuite objects in the classic client. When creating a new MenuSuite object, you have to select both the target client and the menu level.
FIGURE 5.5 THE DESIGN LEVEL WINDOW
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-9
Report Design in Microsoft Dynamics® NAV 2009 MenuSuites for the RoleTailored client are created and designed in the same way as MenuSuite objects for the classic client. However, when you create menu groups in the MenuSuite for the RoleTailored client, a new property Department Page is available.
FIGURE 5.6 THE GROUP PROPERTIES WINDOW
The Department Page property indicates whether to separate a menu page (containing the underlying menu groups and items) to be built for the group and whether the group needs to appear in the menu structure in the RoleTailored client. When adding menu items to a MenuSuite for the RoleTailored client, you have to specify the Department Category which the menu item belongs to. There are six categories: Lists, Tasks, Reports and Analysis, Documents, History, Administration. The property is used to automatically generate the navigation structure for the RoleTailored client.
Demonstration: Adding Reports to a Departments Section Prakash wants to print the Job Actual To Budget Chart Report (123456709). Instead of printing it through the use of the Start menu, he asks Mort to integrate the report in the Job menu on the Departments section. Mort will first create a new MenuSuite object. 1. In the Microsoft Dynamics NAV Classic client, open Object Designer. 2. Click the MenuSuite button. 3. Click the New button to open the Design Level window. 4. In the Design For field, select RoleTailored Client. 5. In the listbox, select the Dept - Partner level. 6. In the Navigation Pane Designer, select the Jobs menu. 7. Expand the Reports menu group and select the last report in the group: Jobs per Item. 8. Right-click the menu item and choose Create Item. 9. In the Object Type field, select Report. 10. In the Object ID field, click the drop-down arrow and select report 123456709 in the Object List window. 11. In the Caption field, change the caption to Job Actual to Budget Chart.
5-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 12. 13. 14. 15. 16.
In the Department Category field, select Reports and Analysis. Click OK to close the Create Item window. Compile and save the MenuSuite. Open the RoleTailored client and then open the Departments page. Click the Jobs item.
Now the new report is added to the Reports and Analysis category:
FIGURE 5.7 REPORT ADDED TO THE DEPARTMENTS SECTION
Hyperlinks to Reports Hyperlinks allow users to send or save quick links to specific pages in Microsoft Dynamics NAV. For example, you can create a hyperlink to a specific list page, such as Customers. This lesson explains how to create and run hyperlinks to reports.
Create Hyperlinks To create a hyperlink, type the Microsoft Dynamics NAV executable service and then type the syntax for the hyperlink. For example: Microsoft.Dynamics.Nav.Client.exe "DynamicsNAV://MyServer/DynamicsNAV/CRONUS International Ltd./RunPage?Page=22"
This example specifies a server name, service, company, and page ID. If entered correctly it opens the RoleTailored client on page 22, the customer list page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-11
Report Design in Microsoft Dynamics® NAV 2009 Building a URL When you build a hyperlink URL, it can be structured in the following three ways: •
DynamicsNAV://server/service/company/runpage?page=22&bookm ark=0ABA0700235752C7D1
•
DynamicsNAV://server/service/company/runreport?report=901
•
DynamicsNAV://server/service/company/navigate?node=Home/Item s
You can also specify the following additional parameters in a URL.
5-12
Parameter
Description
Personalization ID
Specifies the unique identification used in personalization to store settings in the User Metadata table. If a personalization ID is not found, the page is launched without personalization. Example: DynamicsNAV://localhost/DynamicsNAV/CRONUS International Ltd./runpage?page=22&personalization= 0000232e-0000-001a-0008-0000836bd2d2
Bookmark
Positions the cursor on a single record in a table. Only automatically generated bookmarks are used. If an incorrect bookmark is entered, you will get an error message. Example: DynamicsNAV://localhost/DynamicsNAV/CRONUS International Ltd./runpage?page=22&bookmark= 120000000089083237343
Mode
Used to open a page in a specific mode. Other modes include: view, edit, create, select, and delete. Example: DynamicsNAV://localhost/DynamicsNAV/CRONUS International Ltd./runpage?page=22&mode=View
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports Syntax for Creating Hyperlinks The following table shows some examples of hyperlinks and provides information about how to specify parameters. Parameters
Description
Syntax
Company Name
Allows you to switch a company (case sensitive).
DynamicsNAV://///RunPage?Page=<pageid> Example: Microsoft.Dynamics.Nav.Client.e xe "DynamicsNAV:////CRONUS International Ltd./RunPage?Page=22"
Navigate
Allows users to send or save quick links to specific pages.
DynamicsNAV://///navigate?nod e=<service> Example: Microsoft.Dynamics.Nav.Client.e xe DynamicsNAV://///navigate?nod e=Home/"User Setup"
RunPage
Allows you to run a specific page for testing purposes.
DynamicsNAV:////runpage?page =<page id> Example: DynamicsNAV:////runpage?page =42
RunReport
Allows you to run a specific report for testing purposes.
DynamicsNAV:////runreport?repo rt= Example: DynamicsNAV:////runreport?repo rt=50000
Server name
Allows you to switch servers.
DynamicsNAV://<ServerName>/ //RunPage?Page=<pageid> Example: Microsoft.Dynamics.Nav.Client.e xe DynamicsNAV://MyServer///Run Page?Page=22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-13
Report Design in Microsoft Dynamics® NAV 2009 Parameters
Description
Syntax
Server name optional port number
Allows you to specify an optional port number in the range 1-65535. The default port is 7046.
DynamicsNAV://<ServerName> <:Port>///RunPage?Page=<pagei d> Example: Microsoft.Dynamics.Nav.Client.e xe DynamicsNAV://MyServer:1234 ///RunPage?Page=22
Service instance
Allows you to specify a Service instance. You can find this value in the CustomSettings.config file.
DynamicsNAV:///<Service>//Ru nPage?Page=<pageid> Example: Microsoft.Dynamics.Nav.Client.e xe DynamicsNAV:///DynamicsNAV //RunPage?Page=22
If you omit a parameter, such as Server or Service, do not remove the accompanying forward slash, because this will change the overall structure of the hyperlink. When you type a company name as a parameter, put the hyperlink in quotation marks if there are blank spaces in the name.
Run Hyperlinks In Microsoft Dynamics NAV you can run hyperlinks in different ways. You can run the report from the Run window, from a Command Prompt, from a shortcut or from a browser window. This is useful if, for example, you need to run a specific report for testing purposes or know the ID of a report that is run often. The following demonstrations illustrate how to run hyperlinks.
Demonstration: Running a Report from the Run Window In the Classic client, users can create shortcuts to specific objects on the Windows Desktop. Mort starts to investigate whether this functionality also exists for the RoleTailored client. The first method was already used to test the reports in the previous chapters and labs. To run a report from the Run window, use the following steps: 1. On your machine, click Start and then Run. 2. In the Run dialog box, enter the following command: dynamicssnav:////runreport?report=.
5-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 3. Replace with the report ID that you want to use 111. 4. Click OK to run the report. The request options page, if any, will now be displayed in the RoleTailored client.
FIGURE 5.8 THE ROLETAILORED CLIENT WITH THE REQUEST OPTIONS PAGE
Demonstration: Running a Report from the Command Prompt To run a report from the Windows Desktop, you can create a shortcut to the report. To use a shortcut to run a report, follow these steps: 1. Click Start, Run. 2. In the Run window, enter cmd. 3. In the command prompt window, enter the following command:: "C:\Program Files\Microsoft Dynamics NAV\60\RoleTailored Client\Microsoft.Dynamics.Nav.Client.exe" DynamicsNAV:////runreport?report=111. 4. Press Enter.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-15
Report Design in Microsoft Dynamics® NAV 2009 Demonstration: Running a Report from a Shortcut To run a report from the Windows Desktop, you can create a shortcut to the report. To use a shortcut to run a report, follow these steps: 1. On your Windows Desktop, create a shortcut to the Microsoft.Dynamics.Nav.Client.exe. 2. Right-click the shortcut and select Properties. 3. In the Target field, add the hyperlink URL. The complete target will look like this: "C:\Program Files\Microsoft Dynamics NAV\60\RoleTailored Client\Microsoft.Dynamics.Nav.Client.exe" DynamicsNAV:////runreport?report=111. 4. Click OK to close the Properties window. 5. Double-click the shortcut to run the report.
Demonstration: Running a Report from a Browser Window The following steps show how to run a report from the browser window. 1. Open Microsoft Internet Explorer. 2. In the address bar; enter the following URL: DynamicsNav://localhost/DynamicsNAV/CRONUS International Ltd./runreport?report=111. 3. Press Enter to validate the URL. To run a report from the browser, the Microsoft Dynamics NAV 2009 RoleTailored client must be installed on the computer.
Demonstration: Adding a Report Hyperlink to a Web Page Kevin has asked Tim, the IT manager, to conduct a small feasibility study for building a Customer Portal. One of the primary goals of this portal is to provide all outbound sales documents electronically, so the customer can download the documents. In addition, customers must be able to print specific reports themselves. Tim checks whether it is possible to launch a RoleTailored client report from a Web page. 1. From the Start menu, open Microsoft Visual Studio 2008. 2. Select File, New, Web Site. 3. In the New Web Site window, select the ASP.NET Web Site template. 4. In the top right corner, leave the .NET Framework 3.5 option.
5-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 5. In the Location field, enter the following path: C:\Documents and Settings\%USERNAME%\My Documents\Visual Studio 2008\WebSites\HyperlinkTest (where %USERNAME% represents your Windows account). 6. In the Language field, select Visual Basic. 7. Click the OK button to create a new web site. 8. Click the Source button at the bottom of the window. 9. Place the cursor between the and tags. 10. Insert the following piece of code: The Customer Top 10 List
The result will look like this:
FIGURE 5.9 THE WEB SITE PAGE IN SOURCE VIEW
11. Press F5 to run the Web site. 12. If the Debugging Not Enabled dialog box is displayed, select the Run without debugging option and click the OK button. 13. Click the hyperlink.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-17
Report Design in Microsoft Dynamics® NAV 2009 Demonstration: Adding a Report Hyperlink to Favorites Now that Tim knows that links to a RoleTailored client report can be included on a Web page, he decides do to a little more testing. Tim wants to know whether links to reports can be added to the Favorites menu in Internet Explorer, and he begins to run the HyperlinkTest site just created. 1. Right-click the The Customer Top 10 List link. 2. Select Add to Favorites. 3. In the Add a Favorite window, enter the following name for the report: Customer - Top 10 List. 4. Click the New Folder button. 5. In the Create a Folder window, enter the following Folder Name: DynamicsNAV Reports 6. In the Create In dropdown list, select Favorites. 7. Click the Create button to create the folder and to return to the Add a Favorite window. Notice that the Create In field points to the newly created folder.
FIGURE 5.10 ADD A FAVORITE WINDOW
8. Click the Add button to close the Add a Favorite window. 9. In Internet Explorer, select Favorites, DynamicsNAV Reports. 10. Click the Customer Top 10 List link. The RoleTailored client will be launched and the request options page for the report is displayed. Tim is satisfied with the results of his tests. He decides to check one more thing. 1. In Internet Explorer, select Favorites, DynamicsNAV Reports. 2. Right-click the Customer Top 10 List link.
5-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 3. Select Properties. 4. In the Customer Top 10 List Properties window, click the Web Document tab.
FIGURE 5.11 CUSTOMER TOP 10 LIST PROPERTIES WINDOW
Tim sees that the URL field contains the editable link to the report.
Hyperlinks in E-mails Hyperlinks allow navigating between documents and offer instant access to the right information. This lesson describes to use hyperlinks in e-mail messages. When creating e-mails from C/AL code in the Classic client, you can use the Form.URL method and include it into the body of an e-mail. Whenever someone clicks the Link, the Classic Client is opened and the corresponding Form is shown. In Microsoft Dynamics NAV 2009, in the RoleTailored client, the Form.URL method is no longer supported. The RoleTailored client does not display forms; it uses Pages and Pages do not have an URL method. To create a link to a page, you have to create the URL as follows: dynamicsnav:////runpage?page=<Page No>&bookmark=.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-19
Report Design in Microsoft Dynamics® NAV 2009 Generating BookmarkURLs To get a BookmarkURL for a specific record, you need to use a RecordRef variable that points towards the specific record and use its RecordId property. The next challenge might be that your code is in a Codeunit and can sometimes be called from a form or a page. To make your code compatible with both environments, you can use the ISSERVICETIER function. If you call ISSERVICETIER from the Classic client, then the function returns FALSE. When called from the RoleTailored client, ISSERVICETIER returns TRUE. You can use the following piece of code to include bookmarks in the body of an e-mail:
FIGURE 5.12 C/AL EDITOR WINDOW
Notice the parameters of the FORMAT() function for the RecordRef variable. The usage of value 10 in this expression is a RoleTailored client feature only that will format RECORDID into a text representation that is compatible with the URL handler of reports and pages.
Hyperlinks in a Report With the integration between Microsoft Dynamics NAV 2009 and SQL Reporting Services it is possible to create reports that provide dynamic data. Microsoft Dynamics NAV 2009 reports can among other things include images, graphics, interactive sorting, and toggle on data columns, and it can link to other data in the system. This lesson illustrates how to set up a report to include a link to the customer card page, so that when it is run in preview mode it can look up any existing customer directly from the report. Including this functionality the report no longer serves as a static, printed list, but becomes a dynamic list that can be used for direct drill-down into system data.
5-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports Demonstration: Adding a Link in a Report When printing the Customer Top 10 List report, Michael notices that only the customer number and name are included in the list. To find the other customer information, Michael needs to open the Customer Card. He asks Mort whether it is not possible to include a link to the Customer Card in the report. Before he can include the link in Visual Studio, Mort needs to make a small change to the Classic report: he needs to add a variable and include the variable in a hidden textbox on a section.
Add a Variable and Code to the Report 1. In the Classic client, click Tools, and then select Object Designer. 2. In Object Designer, click Report, and then locate the Customer Top 10 List report by typing object ID 111. 3. Select the Customer - Top 10 List report and click the Design button. 4. In the Report Designer window, select the Customer data item, and then click View, C/AL Globals. 5. In the C/AL Globals window, on the Variables tab, add a new entry. 6. In the Name field, enter CustomerRecRef, and in the DataType field, select RecordRef. Close the C/AL Globals window. 7. In the Report Designer window with the Customer data item still selected, press F9 to open the C/AL Editor window. 8. On the OnPreDataItem() trigger, write the following line of code:
CustomerRecRef.OPEN(18);
9. In the Report Designer window, change focus to the Integer data item. 10. In the C/AL Editor window, on the OnAfterGetRecord() trigger, enter the following line of code at the bottom of the trigger:
CustomerRecRef.SETPOSITION(Customer.GETPOSITION);
11. Close the C/AL Editor window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-21
Report Design in Microsoft Dynamics® NAV 2009 Adding the Textbox Having created the variable CustomerRecRef, Mort must create a new textbox that will be used to get the value of the current customer represented in the dataset in Visual Studio once the layout is opened there. The textbox is not going to be visible on the report when it is run, but is only used for transformation purposes. The following steps illustrate how to add the textbox to the report. 1. With the Customer - Top 10 List report open in Report Designer, click View, and then select Sections. 2. In the Section Designer window, locate the BarText textbox and resize it to make room for a new small textbox. 3. Click View, and then select Toolbox. 4. From Toolbox, click Textbox and then click the report design to place it next to the BarText textbox. 5. Right-click the new Textbox and select Properties. 6. In the Properties window, on the SourceExpr property, enter the following expression: FORMAT(CustomerRecRef.RECORDID,0,10)
7. Close the Properties window. The usage of value 10 in this expression is a RoleTailored client feature only that will format RECORDID into a text representation that is compatible with the URL handler of reports and pages. 8. In the Properties window, set the Visible property to No. 9. Save and compile the report. Once the variable and the textbox are created using Microsoft Dynamics Report Designer, Mort can open the layout of the report and further modify it in Visual Studio. The following steps will add a link to the customer number on the report that opens the customer card for the selected customer. Notice that the newly created textbox is now part of the dataset in Visual Studio under Data Sources and its value is being referenced in the link you are adding. 1. In the Classic client, with the Customer - Top 10 List report open in Report Designer, click View, and then select Layout. 2. In Visual Studio, in the Body section of the report, locate the textbox Customer__No__. The value of the textbox is =Fields!Customer__No__.Value. 3. Right-click the textbox and select Properties.
5-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 4. In the Properties window, go to the Navigation tab. 5. Select the Jump to URL option and enter the following expression in the field: ="dynamicsnav:////runpage?page=21&mode=edit&bookmark="+Fiel ds!FORMAT_CustomerRecRef_RECORDID_0_10_.Value
The result will look like this:
FIGURE 5.13 TEXTBOX PROPERTIES WINDOW
Notice that the mode parameter is used. This will allow the user to edit the customer page. 6. Click OK to close the window. 7. Save the report in Visual Studio and return to the Classic client. 8. Save and compile the report in the Classic client. In the Classic client, Mort saves the Customer - Top 10 List report. A message informs him that the .rdlc file for this report has changed and asks if he wants to load the changes. He clicks Yes to save the changes in the database. 1. Select Tools, and then click Compile to compile the report. 2. On the Windows taskbar, click Start and then click Run.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-23
Report Design in Microsoft Dynamics® NAV 2009 3. In the Run window, enter the following string: dynamicsnav:////runreport?report=111 and click OK. 4. Click Preview to view the report. The report lists the top 10 list of customers.
FIGURE 5.14 CUSTOMER TOP 10 REPORT PREVIEW
If resting on the customer number you will get a link to open the specific customer on a separate customer card making it possible to drill down into the customer's data. Microsoft Dynamics NAV 2009 Service Pack 1 will offer Drill Through functionality, so you can create links to other reports.
Interesting Links This section contains a non-exhaustive list of hyperlinks and resources to useful information regarding Microsoft Dynamics NAV 2009 and reporting.
The Microsoft Dynamics NAV Reporting Blog This blog is written by members of the Microsoft Dynamics NAV Reporting Team and dedicated entirely to client-side reporting in Microsoft Dynamics NAV 2009.
5-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports The idea with this blog is to collect and share information and tips and tricks for the new reporting environment for Microsoft Dynamics NAV. Also this blog offers the ability to provide feedback directly to the Microsoft Dynamics Reporting Team. http://blogs.msdn.com/nav-reporting
The Microsoft Dynamics NAV Developer Blog This site is written by engineers in the Microsoft Dynamics NAV team worldwide. The blog contains technical articles about Microsoft Dynamics NAV 2009 in general. http://blogs.msdn.com/nav_developer/default.aspx
The Microsoft Dynamics NAV Sustained Engineering Team Blog The Microsoft Dynamics NAV Sustained Engineering Team Blog is mostly written by members of the Microsoft Dynamics NAV Sustained Engineering team. http://blogs.msdn.com/microsoft_dynamics_nav_sustained_engineering/
The Microsoft Dynamics NAV Team Blog This blog site of the Microsoft Dynamics NAV Product team contains technical articles and resources about Microsoft Dynamics NAV. http://blogs.msdn.com/nav/default.aspx
Microsoft Dynamics Developer Center Microsoft Developer Network (MSDN) Developer Centers and Resource Centers pull together content and resources around specific products and technologies. They connect you to code samples, community sites, technical articles and documentation, upcoming events, and much more. The Microsoft Dynamics Developer Center gives access to all kinds of development resources for each of the five Microsoft Dynamics products: (Microsoft Dynamics® AX, Microsoft Dynamics® CRM, Microsoft Dynamics® GP, Microsoft Dynamics NAV, and Microsoft Dynamics® SL). It offers general information such as product highlights, getting started and learning information. Furthermore it contains links to newsgroups, communities and (team) blogs. http://msdn.microsoft.com/en-us/dynamics/default.aspx
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-25
Report Design in Microsoft Dynamics® NAV 2009 Microsoft SQL Server Development Center The Microsoft SQL Server Development Center contains all kinds of resources and information regarding development in Microsoft SQL Server®. http://msdn.microsoft.com/en-us/sqlserver/default.aspx In the Microsoft SQL Server Reporting Services (SSRS) section of the SQL Server Developer Center, you can find all kinds of resources related to reporting in SSRS. To go directly to the SSRS section, click the following link: http://msdn.microsoft.com/en-us/sqlserver/cc511478.aspx
Microsoft Visual Studio Following is the home page of the Microsoft Visual Studio product family. http://www.microsoft.com/visualstudio/
Microsoft Visual Studio Express Editions This site contains resources for the Microsoft Visual Studio Express Editions. The page includes software downloads, samples and resources as well as information about Frequently Asked Questions (FAQ), system requirements, help resources, installation topics, and forums. http://www.microsoft.com/express/
Creating and Consuming a Codeunit Web Service This walkthrough provides an overview of how to create and consume a simple Web service with Microsoft Dynamics NAV. http://msdn.microsoft.com/en-us/library/dd339004.aspx
Microsoft Dynamics NAV 2009 Launch Portal The Launch Portal references tools, training, and content you can use to kick start your Microsoft Dynamics NAV 2009 readiness. This material supplements the communications and processes that are provided by your local Microsoft country or regional organization. A PartnerSource login is required. https://mbs.microsoft.com/partnersource/marketing/campaigns/prospect/launchm dnav.htm
5-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports Microsoft Dynamics NAV 2009 Developer and IT Pro Help The Microsoft Dynamics NAV 2009 Developer and IT Pro Help provides information about developing for, installing, and managing Microsoft Dynamics NAV 2009. http://go.microsoft.com/fwlink/?linkid=126283 Updates to the developer and IT Pro Help, with both new content and improvements to existing content can be downloaded from this page: http://go.microsoft.com/fwlink/?linkid=126282
User Experience Guidelines for Microsoft Dynamics NAV 2009 The Microsoft Dynamics NAV 2009 User Experience Guidelines (or “UX Guide” for short) is a tool to assist Microsoft Dynamics NAV Independent Software Vendors (ISVs) in building more user-friendly applications. By using the Microsoft UX Guide proactively during your development process, you can save time and avoid design violations. http://www.microsoft.com/downloads/details.aspx?FamilyID=8B5AB93F-480B4C14-868A-98F6B9BC3E86&displaylang=en
Microsoft Dynamics NAV Developer Documentation This page contains links to several technical articles related to development in Microsoft Dynamics NAV. http://msdn.microsoft.com/en-us/library/dd355683.aspx
The Microsoft Dynamics NAV Technical Community This site offers a wide variety of tools to help you connect and collaborate with other Microsoft Dynamics NAV users, developers and implementers. https://community.dynamics.com/nav/home.aspx
SQL Server 2008 Report Definition Language Specification This document specifies the structure and semantics of the SQL Server 2008 Report Definition Language (RDL), and XML Schema for presenting reports. http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=2 a20c7af-52e8-4882-bd24-9479b3c7517d
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-27
Report Design in Microsoft Dynamics® NAV 2009 Report Design Tips and Tricks This white paper covers best practices on report design and helps you avoid common mistakes when choosing a report layout and output format. Take advantage of existing product features to achieve the results you want. The paper includes report and code examples that implement functionality that is frequently requested (32 printed pages). http://msdn.microsoft.com/en-us/library/bb395166.aspx
Microsoft Most Valuable Porfessional (MVP) and Other Sites www.mibuso.com (http://www.mibuso.com) (MVP Site) www.waldo.be (http://www.waldo.be) (MVP Site) Dynamics User Group (http://dynamicsuser.net/) (Dynamics NAV Online User Community) http://www.dynamicsblog.at/ (Austrian Dynamics blog) http://blogs.msdn.com/german_nav_developer/ (German NAV Developers blog) http://www.plataan.be (Microsoft CPLS)
5-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports
Lab 5.1 - Add a Report to the RoleTailored Client In this lab you will add one of the reports built in previous chapters to the RoleTailored client interface. Scenario Prakash wants his Resource - Utilization (Chart) Report (report 123456706) to be available from the Role Center menu, so he and other project managers can access it from the RoleTailored client. He asks Mort to make it available in the menu on the Role Center page. In addition, he wants it to be accessible from the Resources page in the Departments section (under the Reports and Analysis category).
Challenge Yourself! Add report 123456706, created in Lab 4.2, to the Role Center menu for Prakash and the other project managers. Furthermore, create a new MenuSuite object to make the report available under the Reports and Analysis category in the Resources section of the Departments page.
Need a Little Help? The following steps show how to add the report to the RoleTailored client: 1. Add the Report to the Job Project Manager RC Page. 2. Create a New MenuSuite Object. 3. Change the MenuSuite Object to Add the Report to the Departments Section 4. Create a New Shortcut for the RoleTailored client. 5. Change the New Shortcut for the RoleTailored client. 6. Start the RoleTailored Client with the Project Manager profile (in Configuration Mode).
Step by Step Add the Report to the Job Project Manager RC Page 1. In the Microsoft Dynamics NAV Classic client, open Object Designer. 2. Click the Page button. 3. Select page 9015, Job Project Manager RC. 4. Click Design to open the page in Page Designer. 5. Select an empty line in the designer. Click View, and then Actions to open Action Designer. 6. Scroll down to the Action that has Jobs per Item as its Caption. 7. Click the Separator button to insert a separator.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-29
Report Design in Microsoft Dynamics® NAV 2009 8. Scroll down to the ActionContainer that has HomeItems as its Subtype. 9. Press F3 to insert a new empty line (or select Edit, New). 10. On the new line, in the Caption field, enter a name for the action: Resource - Utilization (Chart). 11. In the Type field, select Action. 12. Click View, and then Properties to open the Properties window for the new action. 13. In the Value field of the RunObject property, click the drop-down arrow and select report 123456706 in the Object List window. 14. Compile and save the page. 15. Open the RoleTailored client and then open the Role Center page.
Create a new MenuSuite Object 1. In the Microsoft Dynamics NAV Classic client, open Object Designer. 2. Click the MenuSuite button. 3. Click the New button to open the Design Level window. 4. In the Design for field, select RoleTailored Client. 5. In the listbox, select the Dept - Partner level. 6. Save the MenuSuite object.
Change the MenuSuite Object to Add the Report to the Departments Section 1. In the Navigation Pane Designer, select the Resource Planning menu. 2. Expand the Reports group. 3. Right-click the last report in the Reports group (Resource - Price List) and select Create Item. 4. In the Create Item window, select Report in the Object Type field. 5. In the Object ID field, click the dropdown arrow and select report 123456706 in the Object List window. 6. In the Caption field, change the caption to Resource - Utilization (Chart). 7. In the Department Category field, select Reports and Analysis. 8. Click OK to close the Create Item window. 9. Compile and save the MenuSuite.
5-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports Create a New Shortcut for the RoleTailored Client 1. Right-click the Windows Desktop and select New > Shortcut. 2. In the Create Shortcut window, click the Browse button. 3. In the Browse for Folder window, browse to the following path and application: C:\Program Files\Microsoft Dynamics NAV\60\RoleTailored Client\Microsoft.Dynamics.Nav.Client.exe 4. Click the OK button to close the Browse for Folder window. 5. In the Create Shortcut window, click the Next button. 6. Enter the following name for the shortcut: Project Manager Profile. 7. Click the Finish button.
Change the New Shortcut for the RoleTailored Client 1. Right-click the newly created shortcut. 2. Select Properties. 3. Change the Target field to: "C:\Program Files\Microsoft Dynamics NAV\60\RoleTailored Client\Microsoft.Dynamics.Nav.Client.exe" -configure profile:"Project Manager" 4. Click the Apply button. 5. Click the OK button.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-31
Report Design in Microsoft Dynamics® NAV 2009 Start the RoleTailored Client with the Project Manager Profile (in Configuration Mode) 1. On the Windows Desktop, double-click the Project Manager Profile icon. 2. On the Role Center page, click the Reports menu.
FIGURE 5.15 ROLE CENTER PAGE WINDOW
3. Click the Departments menu. 4. Click the Resource Planning section. Now the Resource - Utilization (Chart) Report is listed under the Reports and Analysis category (as the bottom report in the Reports group).
5-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports
Lab 5.2 - Call a Report from a Web Service In this lab, you will build a small codeunit and expose it as a Web service. Although this course is not a Web development course, you will see how to build a small Web application that consumes the Web service. This lab is for educational purposes only and does not focus on defining the right application security. Therefore, it is highly recommended not to implement the lab "as is" in a live production environment. Scenario While she is talking to customers, Susan regularly gets requests from customers who have questions about sales invoices and shipments. Currently, Susan carefully takes all the details and sends the case to the responsible representative, who handles it. At the same time, Rebecca gets several requests to resend lost or missing documents to the customers. To better and faster serve the customers, Susan and Rebecca want to quickly search a document (by number) and print a copy of it, so they can add it to the case or send it to the customers. Mort views this as an excellent opportunity to realize one of his dreams: a selfserving customer portal.
Challenge Yourself! Build a Web service that can check whether a specific posted sales document (invoice, credit memorandum and shipment) exists and that can print the specific document as a PDF. Build a small Web application that consumes this Web service; the user needs to specify a document type and a document number and click a Search button. When a wrong document number is entered, a small error message needs to appear to notify the user.
Need a Little Help? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
Create a New Codeunit. Add Global Variables to the Codeunit. Add the CheckInvoiceNo function to the Codeunit. Add code to the CheckDocNo function. Add the GenerateReport function to the Codeunit. Add code to the GenerateReport function. Expose the Codeunit as a Web Service. Create a New Web site. Add Controls to the Web site. Add the Web Service Reference.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-33
Report Design in Microsoft Dynamics® NAV 2009 11. Add Code to Consume the Web Service. 12. Run the Web Application.
Step by Step Create a New Codeunit 1. In the Microsoft Dynamics NAV Classic client, open Object Designer. 2. Click the Codeunit button. 3. Click the New button 4. Select File, Save As. 5. In the ID field, enter 123456701. 6. In the Name field, enter Get Sales Document WS. 7. Check the Compiled field. 8. Click OK.
Add Global Variables to the Codeunit 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.
5-34
Select View, C/AL Globals to open the C/AL Globals window. On the Variables tab, select the first (empty) line. In the Name field, enter FileName. In the DataType field, select Text. In the Length field, enter 250. Select the next line. In the Name field, enter SalesInvHdr. In the DataType field, select Record. In the Subtype field, click the button and select the Sales Invoice Header table from the Object List window. Select the next line. In the Name field, enter SalesCMHdr. In the DataType field, select Record. In the Subtype field, click the button and select the Sales Cr.Memo Header table from the Object List window. Select the next line. In the Name field, enter SalesShptHdr.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 16. In the DataType field, select Record. 17. In the Subtype field, click the button and select the Sales Shipment Header table from the Object List window.
FIGURE 5.16 THE C/AL GLOBALS WINDOW
18. Select File, Save to save and compile the codeunit.
Add the CheckDocNo function to the Codeunit 1. In the C/AL Globals window, click the Functions tab. 2. On the first empty line, enter CheckDocNo. 3. Place the cursor on the line containing the CheckDocNo function and click the Locals button to open the C/AL Locals window. 4. On the Parameters tab, select the first empty line. 5. In the Name field, enter DocType. 6. In the DataType field, select Integer. 7. Select the next line. 8. In the Name field, enter DocNo. 9. In the DataType field, select Code. 10. In the Length field, enter 20. 11. Click the Return Value tab. 12. In the Return Type field, select Integer. 13. Close the C/AL Locals window.
Add the GenerateReport Function to the Codeunit 1. In the C/AL Globals window, click the Functions tab. 2. On the first empty line, enter GenerateReport. 3. Place the cursor on the line containing the GenerateReport function and click the Locals button to open the C/AL Locals window. 4. On the Parameters tab, select the first empty line.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-35
Report Design in Microsoft Dynamics® NAV 2009 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.
In the Name field, enter DocType. In the DataType field, select Integer. Select the next line. In the Name field, enter DocNo. In the DataType field, select Code. In the Length field, enter 20. Click the Return Value tab. In the Return Type field, select Text. In the Length field, enter 250. Close the C/AL Locals window. Close the C/AL Globals window to return to the C/AL Editor.
Add Code to the CheckDocNo Function 1. In the C/AL Editor, enter the following code in the CheckDocNo() function trigger:
CASE DocType OF 110: BEGIN IF SalesShptHdr.GET(DocNo) THEN BEGIN EXIT(1) END ELSE EXIT(0); END; 112: BEGIN IF SalesInvHdr.GET(DocNo) THEN BEGIN EXIT(1) END ELSE EXIT(0); END; 114: BEGIN IF SalesCMHdr.GET(DocNo) THEN BEGIN EXIT(1) END ELSE EXIT(0); END; END;
5-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 2. Select File, Save to compile the codeunit. The function trigger will look like this:
FIGURE 5.17 THE CHECKDOCNO FUNCTION
Add Code to the GenerateReport Function 1. In the C/AL Editor, enter the following code in the GenerateReport() function trigger. // Determine the PDF File Name FileName := 'C:\'; FileName := FileName + FORMAT(CREATEGUID); FileName := DELCHR(FileName, '=', '{-}'); FileName := FileName + '.pdf'; // Print the Document IF DocType = 110 THEN BEGIN SalesShptHdr.SETRANGE("No.", DocNo); IF SalesShptHdr.FINDFIRST THEN REPORT.SAVEASPDF(208, FileName, SalesShptHdr); END; IF DocType = 112 THEN BEGIN SalesInvHdr.SETRANGE("No.", DocNo); IF SalesInvHdr.FINDFIRST THEN REPORT.SAVEASPDF(206, FileName, SalesInvHdr); END; IF DocType = 114 THEN BEGIN SalesCMHdr.SETRANGE("No.", DocNo); IF SalesCMHdr.FINDFIRST THEN REPORT.SAVEASPDF(207, FileName, SalesCMHdr); END; EXIT(FileName);
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-37
Report Design in Microsoft Dynamics® NAV 2009 2. Select File, Save to compile the codeunit. The function trigger will look like this:
FIGURE 5.18 THE GENERATEREPORT FUNCTION
3. Close the C/AL Editor. 4. Close Object Designer.
Expose the Codeunit as a Web Service 1. In the Navigation Pane, select Administration, IT Administration, General Setup, Web Services. 2. In the Web Services window, select a blank line. 3. In the Object Type field, select Codeunit. 4. In the Object ID field, enter 123456701.
5-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 5. In the Service Name field, enter Get_Sls_Doc. 6. Place a checkmark in the Published field. The codeunit will now be exposed as a Web service.
FIGURE 5.19 THE WEB SERVICES WINDOW
Test the Availability of the New Web Service 1. Open Internet Explorer. 2. In the browser bar, enter the following URL: http://localhost:7047/DynamicsNAV/WS/services.
FIGURE 5.20 WINDOWS INTERNET EXPLORER WINDOW
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-39
Report Design in Microsoft Dynamics® NAV 2009 The newly published Web service appears in the list with the Service Name specified in the Web Services window. If the list of Web services does not appear, check whether the service "Microsoft Dynamics NAV Business Web Services" is started.
Create a New Web Site 1. Select Start, All Programs, Microsoft Visual Studio 2008, Microsoft Visual Studio 2008. 2. Select File, New, Web Site. 3. In the New Web Site window, select the ASP.NET Web Site template. 4. In the top right corner, leave the .NET Framework 3.5 option. 5. In the Location field, enter the following path: C:\Documents and Settings\%USERNAME%\My Documents\Visual Studio 2008\WebSites\Lab52 (where %USERNAME% represents your Windows account). 6. In the Language field, select Visual Basic. 7. Click the OK button to create the new web site. The result should look similar to this:
FIGURE 5.21 A NEW BLANK WEB SITE
5-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports The ASP Editor window in the middle displays a tab for the default page of the Web site, which is called default.aspx. Notice the Design, Split and View buttons at the bottom of the ASP Editor window. 8. Click the Design button to switch to the design view.
Add Controls to the Web Site 1. In the Toolbox window, select the RadioButtonList control. 2. Drag it inside the element on the default.aspx page. The control remains selected on the design surface. 3. Press the right arrow to place the cursor next to the control. 4. Press Enter. 5. In the Toolbox window, select the Textbox control. 6. Drag it inside the element, under the RadioButtonList. 7. With the Textbox control selected, press the spacebar two times to insert two blank spaces after the control. 8. In the Toolbox window, select the Label control. 9. Drag it inside the element, right next to the Textbox. 10. With the Label control selected, press the right arrow key to place the cursor next to the control. 11. Press Enter.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-41
Report Design in Microsoft Dynamics® NAV 2009 12. In the Toolbox window, select the Button control. 13. Drag it inside the element, under the Textbox control. The result will look like this.
FIGURE 5.22 THE NEW WEB SITE WITH CONTROLS
Design the Controls on the Web Site 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 5-42
Select the Textbox control. In the Properties window, set the (ID) property to txtDocNo. Expand the Font property collection. Set the Name property to Verdana. Set the Size property to Small. Select the Label control. In the Properties window, set the (ID) property to lblErrorMsg. Set the ForeColor property to Red. Set the Text property to Error Message. Set the Visible property to False. Expand the Font property collection. Set the Bold property to True. Set the Name property to Verdana. Set the Size property to Small. Select the Button control. In the Properties window, set the (ID) property to cmdSearch. Set the Text property to Search. Expand the Font property collection. Set the Name property to Verdana.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39.
Set the Size property to Small. Select the RadioButtonList control. In the Properties window, set the (ID) property to rblDocType. Expand the Font property collection. Set the Name property to Verdana. Set the Size property to Small. Clik the > button on the top right corner of the RadioButtonList control. In the RadioButtonList Tasks pane, select Edit Items. In the ListItem Collection Editor window, click the Add button. In the ListItem properties window, set the Text property to Posted Invoice. Change the Value property to 112. Set the Selected property to True. Click the Add button. (The newly added item will appear in the Members list.) In the ListItem properties window, set the Text property to Posted Credit Memo. Change the Value property to 114. Click the Add button. (The newly added item will appear in the Members list.) In the ListItem properties window, set the Text property to Posted Shipment. Change the Value property to 110. Click the OK button to close the ListItem Collection Editor window. Select File, Save to save the file.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-43
Report Design in Microsoft Dynamics® NAV 2009 The result will look similar to this:
FIGURE 5.23 WEB SERVICE WINDOW
Add the Web Service Reference As consuming a Web Service is not in the scope for this training, it is recommended to check the online help of Microsoft Dynamics NAV 2009 or the MSDN Web site at http://msdn.microsoft.com/en-us/library/dd339004.aspx. 1. In the Solution Explorer window, right-click the Lab52 project and select Add Service Reference. 2. In the Add Service Reference window, click the Advanced button. 3. In the Service Reference Settings window, click the Add Web Reference button to open the Add Web Reference window. 4. In the URL field, enter http://localhost:7047/DynamicsNAV/WS/services.
5-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 5. Click the Go button. 6. In the left listbox, Discovery Page, click the View Service link for the Get_Sls_Doc service.
FIGURE 5.24 THE WEB SERVICE DESCRIPTION
7. Click the Add Reference button to add a reference to the web service.
Add Code to Consume the Web Service 1. Click the Default.aspx tab. 2. Double-click the Search button in Design view. 3. On the Default.aspx.vb tab, enter the following piece of code in the cmdSearch_Click procedure. Dim service As localhost.Get_Sls_Doc = New localhost.Get_Sls_Doc Dim pdfFileName As String Dim DocCheck As Integer service.UseDefaultCredentials = True service.Url ="http://localhost:7047/DynamicsNAV/WS/CRONUS_International _Ltd/Codeunit/Get_Sls_Doc" DocCheck = service.CheckDocNo(rblDocType.SelectedValue, txtDocNo.Text)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-45
Report Design in Microsoft Dynamics® NAV 2009 If DocCheck = 0 Then lblErrorMsg.Text = rblDocType.SelectedItem.Text & " " & txtDocNo.Text & " was not found." lblErrorMsg.Visible = True txtDocNo.Text ="" Else lblErrorMsg.Visible = False service.UseDefaultCredentials = True service.Url ="http://localhost:7047/DynamicsNAV/WS/CRONUS_International _Ltd/Codeunit/Get_Sls_Doc" Response.ContentType ="application/pdf" pdfFileName = service.GenerateReport(rblDocType.SelectedValue, txtDocNo.Text) Response.TransmitFile(pdfFileName) End If
The result will look like this:
FIGURE 5.25 THE CODE TO CONSUME THE WEB SERVICES
4. Click File, Save All to save the modified files.
Run the Web Application 1. On the Default.aspx page, press F5. 2. If the Debugging Not Enabled dialog box is displayed, select the Run without debugging option and click the OK button.
5-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports The result will look like this:
FIGURE 5.26 WEB SERVICE WINDOW
Test the Web Application To test the application, use this scenario: 1. Select the Posted Shipment option.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-47
Report Design in Microsoft Dynamics® NAV 2009 2. In the textbox, enter 103007. 3. Click the Search button.
FIGURE 5.27 WEB SERVICE WINDOW
5-48
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports 1. Select the Posted Invoice option. 2. In the textbox, enter 103007. 3. Click the Search button.
FIGURE 5.28 SALES INVOICE REPORT
Summary This chapter described how to create and run hyperlinks to reports for the RoleTailored client. It also explained how to create and use a Microsoft Dynamics NAV Web service that prints a report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-49
Report Design in Microsoft Dynamics® NAV 2009
Test Your Knowledge Test your knowledge with the following questions. 1. Which functionalities are available from the ReportViewer Control Toolbar? (Select all that apply) ( ) Find ( ) Save Page Setup ( ) Browse ( ) Sort 2. Which property determines whether a menu or menu group will be included as a page in the Departments page of the RoleTailored Client? ( ) Department Menu ( ) Department Page ( ) Department Level ( ) Department Category 3. Which department categories are available in the Create Item window? ( ) Lists, Tasks, Reports and Analysis, Documents, Departments, Home ( ) Lists, Tasks, Reports and Analysis, Documents, History, Setup ( ) Lists, Tasks, Reports and Analysis, Documents, History, Administration ( ) Lists, Tasks, Reports and Analysis, Documents, Departments, Periodic Activities 4. What is the RoleTailored client's equivalent for the Navigation Pane in the Classic Client? ( ) The Role Center Pages ( ) The Activities Pages ( ) The Action Pane ( ) The Departments Page 5. What is true about MenuSuites for the RoleTailored Client? (Select all that apply) ( ) They are stored as separate MenuSuite objects. ( ) They are stored inside the MenuSuite object for the Classic Client. ( ) They compromise the Departments page. ( ) They compromise the Navigation Pane.
5-50
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Running Reports
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
5-51
Report Design in Microsoft Dynamics® NAV 2009
Solutions Test Your Knowledge 1. Which functionalities are available from the ReportViewer Control Toolbar? (Select all that apply) (√) Find ( ) Save Page Setup (√) Browse ( ) Sort 2. Which property determines whether a menu or menu group will be included as a page in the Departments page of the RoleTailored Client? ( ) Department Menu (•) Department Page ( ) Department Level ( ) Department Category 3. Which department categories are available in the Create Item window? ( ) Lists, Tasks, Reports and Analysis, Documents, Departments, Home ( ) Lists, Tasks, Reports and Analysis, Documents, History, Setup (•) Lists, Tasks, Reports and Analysis, Documents, History, Administration ( ) Lists, Tasks, Reports and Analysis, Documents, Departments, Periodic Activities 4. What is the RoleTailored client's equivalent for the Navigation Pane in the Classic Client? ( ) The Role Center Pages ( ) The Activities Pages ( ) The Action Pane (•) The Departments Page 5. What is true about MenuSuites for the RoleTailored Client? (Select all that apply) (√) They are stored as separate MenuSuite objects. ( ) They are stored inside the MenuSuite object for the Classic Client. (√) They compromise the Departments page. ( ) They compromise the Navigation Pane.
5-52
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix
CHAPTER 6: APPENDIX Objectives The objectives are: •
Understand the way the Form Transformation Tool works
•
Prepare the form transformation process
•
Transform forms to pages
Introduction In Microsoft Dynamics® NAV 2009, the RoleTailored client is the new, rich client and pages are the new way to view, insert, modify, and delete data in the RoleTailored client. The RoleTailored client provides an intuitive and customizable user interface (UI) that you can modify to support the job functions of different work roles in your organization.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-1
Report Design in Microsoft Dynamics® NAV 2009
Understanding Form Transformation The RoleTailored client cannot run forms. You must transform your existing forms into pages. By transforming your forms into pages, you can reuse the business layout and logic of your forms. To transform your forms into pages you must use the transformation tool. The topics in this section describe form transformation, the principles behind form transformation, the different methods that you can use to accomplish the transformation from forms to pages, and an overview of the tool that you use to perform form transformation. The following illustration shows the process of transforming forms to pages:
FIGURE 6.1 TRANSFORMING FORMS TO PAGES
6-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Objectives Form Transformation enables you to: •
Transform forms to pages (basic transformation)
•
Tailor resulting pages for the RoleTailored client (UX transformation)
Form-to-page transformation is a basic transformation process that takes form objects from the Microsoft Dynamics NAV Classic application and creates page objects that you can use in the RoleTailored client. User experience (UX) transformation supplements basic form-to-page transformation by adding additional user interface elements to pages that take advantage of the new user experience in the RoleTailored client.
Basic Transformation Basic transformation is the conversion of a form, including its existing functionality and business logic, to a new page by mapping the form essentials— properties, controls and code—to the corresponding page components. The mapping logic is based on rules that are generically applied to all forms. This mapping logic enables you to automate the transformation process. The transformation tool includes built-in mapping rules. In addition to the built-in mapping rules, the transformation input files to the tool include modifiable rules. In addition to replacing existing elements on a form with the corresponding new elements on a page, mapping logic also extends to and includes rules that do the following: •
Ignore: The transformation tool ignores an existing element on a form without replacing it with a corresponding new element on a page. Typically, this occurs in one of the following cases: o o o
•
The RoleTailored client supports the equivalent behavior in a different way than the Classic client. The logic does not require input from the original form. There is not an equivalent element on a page in the RoleTailored client.
Add a property: The transformation tool adds properties to a page that were not on the original form. For example, PageType is a new page property that is a prerequisite to render a page. CardFormID is another new page property. You must assign a CardFormID to a list form that you will transform to a page. Other properties added to a page through transformation are a part of UX transformation.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-3
Report Design in Microsoft Dynamics® NAV 2009 The following tables list examples of generic rules that the transformation tool applies automatically during a basic transformation. Form control
Mapping rule
Page control
TableBox
Replace
Grid (Repeater)
TabControl
Replace
FastTab
Label
In most cases, the CaptionML value of the label is transformed to the CaptionML of the parent or adjacent control.
Caption of field control is used as label.
MatrixBox
Ignore
MatrixBox control is not available.
Form Property
Mapping rule
Page Property
Width
Ignore
None. Pages and controls have built-in rendering and resizing logic.
Xpos
Ignore
None. Pages and controls have built-in rendering and resizing logic.
ParentContr ol
Ignore
None. Pages and controls have built-in rendering and resizing logic.
ID
Replace
ID
Editable
Replace
Editable
RunObject
Replace
RunObject
Tooltip
Ignore
Not supported
NextContro l
Ignore
Not supported
Add new
PageType
Add new
CardFormID
For complete mapping information, see http://msdn.microsoft.com/enus/library/dd301238.aspx.
UX Transformation Through the UX transformation, the automatically generated pages can be tailored to make use of new user interface features in the RoleTailored client. You can either tailor pages through the transformation process or directly in the page object.
6-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix You can enhance a page as part of a UX transformation in the following ways: •
Adding FactBoxes and reports to pages.
•
Adding new actions that do not exist on the form.
•
Promoting frequently used actions and reports onto the Action Pane.
•
Assigning icons to actions.
•
Promoting fields to Fast Tab headers.
•
Adding home parts to a role center.
•
Modifying shortcut keys.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-5
Report Design in Microsoft Dynamics® NAV 2009 The following figure illustrates how a form looks before transformation and how the corresponding page looks after transformation.
FIGURE 6.2 SALES ORDER BEFORE AND AFTER TRANSFORMATION
The following changes were made to the sales order task page during UX transformation:
6-6
•
Three FactBoxes were added to the right side of the page: Customer Sales History, Sales Line Details, and Notes.
•
Frequently used actions, such as Post, Post and Print, and Release have been added to the Action Pane with the appropriate icons.
•
The Lines FastTab has been placed directly under the General FastTab.
•
Selected fields, such as Customer Bill-to No., Payment Terms Code, and Due Date have been marked with Essential importance so that they appear as a summary on the collapsed Invoicing FastTab.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Unlike basic transformation, UX transformation requires specific instructions for each form. You define these instructions in the transformation input files. For more information about transformation input files, see Understanding Form Transformation Input Files (http://msdn.microsoft.com/enus/library/dd355283.aspx).
Principles The form transformation tool was designed with the following principles: •
The tool converts all existing Microsoft Dynamics NAV forms into pages while retaining the same functionality as the original forms.
•
Basic conversion rules (built into the tool) assume that the user interface and code on the form are compliant with the standard application development guidelines.
•
The tool identifies deviations from the guidelines that may result in missing user interface (UI) elements or functionality of the original form. The tool logs these deviations for manual consideration.
•
If the rules for modifying the page UI are generic to all pages, then the tool incorporates them into the tool mapping logic. The tool regards rules that represent "manual" decisions about certain user experience (UX) behavior, layout, and business logic as additional input. You define this additional input manually.
These principles turn the transformation into a highly automated process that makes the migration path to the new architecture as efficient as possible. Fully automatic transformation is not possible for the standard global application or for add-ons and customized solutions. This may be caused by the following: •
Some control types in the Classic client are not available in the same form in the RoleTailored client. For example, the MatrixBox and Shape controls are not supported. To generate a page with the same functionality in the RoleTailored client, you have to either replace the original form with an alternate form containing controls that can be transformed, or modify the original form. One of the steps to prepare for form transformation is to redesign forms by either replacing or modifying forms.
•
The RoleTailored client has enhanced behavior hard-coded into its controls. Therefore, some code that was necessary in previous versions of Microsoft Dynamics NAV is now obsolete when using the new controls. This means that pages contain fewer triggers than forms.
•
Automation that has no UI and does some kind of processing which includes generating files as output (or consumes files as part of input) requires special consideration. To make this work, you must rewrite C/AL code to properly supply the input or output files needed for the automation.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-7
Report Design in Microsoft Dynamics® NAV 2009 •
Automation that uses dialog boxes to display messages or errors requires special consideration. The automation may have its own window (like an OCX) or it may interact with hardware that is local on the client (like a bar code reader or card scanner). These are now unsupported scenarios. Any solution to this problem may require a redesign that functions the same way but takes advantage of Web services, C/FRONT.NET, or another integration technology.
The more your forms deviate from the design guidelines of the standard application, the more challenging it will be to transform them successfully to pages so that they support the same functionality and are compliant with UX guidelines. If your goal is to retain one code base in the Classic client and the RoleTailored client, rather than moving all your application development onto the RoleTailored client, you will have to plan for some redesign efforts.
Methods When you decide to migrate an application to the new three-tiered architecture, you must also decide which migration method is best suited to your business needs. Migrating to the new architecture can be an iterative process. You may need to run the form transformation tool multiple times and carefully alter any problematic forms to ensure that pages can be created that have the required layout. It is important to remember that when you transform a form, the form does not change. For each form that you transform, a new page object is created with matching functionality that can be used by the RoleTailored client. You then have two objects—a form and a page. If you run the tool again and transform the same form, the new page that is created will overwrite the first page object. If, at a later date, you decide that you want to change the functionality of your application, you can implement the changes in one of the following ways: •
Implement changes on the form and then transform the form to a page.
•
Implement changes on the corresponding page.
•
Implement changes on both objects, depending on your business needs.
You can choose between the following methods when you move your application from the Classic client to the RoleTailored client:
6-8
•
Reactive Method
•
Proactive Method
•
Start from Scratch Method
•
Combined Method (all of the above)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix The method that you choose can vary from one implementation to another. A good development practice is to use a copy of the database to see which method or combination of methods achieves the best results for each implementation.
Reactive Method The following are the steps for the reactive method: •
Run the Transformation Tool. For more information, see How to: Run the Form Transformation Tool (http://msdn.microsoft.com/enus/library/dd338649.aspx).
•
Check the resulting pages and the log file. For more information, see Reviewing the Form Transformation Log Output File (http://msdn.microsoft.com/en-us/library/dd338760.aspx).
•
Redesign or modify any forms that did not transform successfully. For more information, see Preparing for Form Transformation by Redesigning Forms (http://msdn.microsoft.com/enus/library/dd338598.aspx).
•
Run the tool again to transform the forms that you have altered.
Proactive Method The following are the steps for the proactive method: 1. 2. 3. 4.
Redesign any forms that you know will not transform satisfactorily. Run the Transformation Tool. Check the resulting pages and the log file. Modify forms that are still causing problems.
Start from Scratch Method The following are the steps for the start from scratch method: •
Implement your entire application in the Page Designer and ignore the transformation tool.
Combined Method The following are the steps for the combined method: 1. Transform some forms to pages. 2. If desired, modify the resulting pages in Page Designer to get greater benefit from the new user experience (UX). 3. If desired, create some new pages without transforming the source forms.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-9
Report Design in Microsoft Dynamics® NAV 2009 Overview The Transformation Tool converts form objects in the Classic client to page objects that you can use in the RoleTailored client. The tool uses a set of rules that map objects in the Classic client to objects in the RoleTailored client. These rules are contained both in the transformation input files and in the transformation tool source files. In addition to the transformation input files, which specify the modifiable rules for transformation, the transformation tool uses schema files, a configuration file, and a coderules file to transform the source forms in the forms.xml file into pages. The transformation tool creates a pages.xml file, which contains the pages that you can view in the RoleTailored client, and a log output file. The following illustration shows the form transformation framework and how the transformation tool fits into that framework.
FIGURE 6.3 THE FORM TRANSFORMATION FRAMEWORK
As this illustration shows, transforming forms is an iterative process. You may need to run the transformation tool more than once on a given form to create a page with the functionality that you want. After you run the tool and view the transformed page, you may want to modify some of the rules that the tool uses and produce different page functionality or modify the user interface (UI) for the page. You change the rules by modifying the transformation input files. You can modify these files directly or you can use the Transformation Input Files (TIF) Editor to modify input files.
6-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Rules The set of rules that the transformation tool uses can be divided into three categories: •
Generic, built-in rules that are applicable to all forms.
•
Generic, modifiable rules that are applicable to all forms.
•
Non-generic, modifiable rules that are applicable to individual forms.
Built-in rules are part of the transformation tool itself. Modifiable rules are input to the tool in the transformation input files.
Generic, Built-In Rules Most transformation tool rules are used for basic form to page transformations, and are related to controls and properties. These rules ensure that the generated pages contain the same functionality as the original forms. Additionally, there are some rules that specify user interface (UI) behavior that is universal across all pages. For example, a table is always placed second in the control hierarchy of a page, which means that the Lines FastTab appears after the General FastTab and before other FastTabs. All rules in this category are built into the logic of the transformation tool. You cannot change these rules without modifying the source files.
Generic, Modifiable Rules Some transformation rules are specified manually. These rules can be modified and are applied by the tool to all form objects. Examples of generic, manuallyspecified rules are the following: •
Mapping triggers and methods
•
Mapping existing shortcuts
•
Adding new shortcuts
•
Promoting selected commands based on caption (rather than control ID)
•
Assigning icons to commands
These rules are contained in input files to the tool, and are applied when you run the tool. To modify these rules, you either use the TIF Editor or modify the transformation input .xml files directly. For more information about modifying the transformation input files, see the following topics: •
Understanding Form Transformation Input Files (http://msdn.microsoft.com/en-us/library/dd355283.aspx)
•
Specifying Form Transformation Rules with the Transformation Input Files Editor (http://msdn.microsoft.com/enus/library/dd338983.aspx)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-11
Report Design in Microsoft Dynamics® NAV 2009 Non-generic, Modifiable Rules Some rules are applicable to individual forms, not to the set of all forms. Two of these non-generic rules are required. All other rules in this category are optional and can be applied to pages that you want to modify. The required rules are the following: •
Assigning appropriate PageType properties to all pages.
•
Assigning appropriate CardFormID properties to list pages.
Examples of optional, non-generic rules are the following: •
Ignoring specific pages
•
Ignoring specific controls
•
Replacing one form with another (applicable if a redesigned form is a new form).
All rules in this category are specified manually and therefore, can be modified. Similar to the generic, modifiable rules, these rules are contained in input files to the tool, and are applied when you run the tool. To modify these rules, you either use the TIF Editor or modify the transformation input .xml files directly.
Input The transformation tool uses the following input: •
Forms.xml - All forms that you want to transform, exported as XML files from the Classic client.
•
CodeRules.txt – A set of rules that, through code pattern recognition, maps triggers and methods.
•
Transformation input files. The transformation input files are the following: o o o o o
6-12
TransformPages.xml MoveElements.xml MovePages.xml IgnorePages.xml DeleteElements.xml
•
Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config – An editable configuration file that provides the location of input and output files and defines the scope of logging.
•
XML schema files
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Output The transformation tool produces the following output: •
Pages.xml - Pages that can be displayed in the RoleTailored client.
•
Transformation.log – A file that logs progress information while the tool runs and provides information about issues detected by the tool. After you run the tool, inspect the log file to determine if you need to make changes to the input and run the transformation again. Use the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file to configure the output in the log file.
For more information about how to import and compile the pages in pages.xml, and how to view the new pages in the RoleTailored client, see How to: Import, Compile, and Run Transformed Pages (http://msdn.microsoft.com/enus/library/dd301270.aspx). For more information about the types of information in the log file and how to use the log file, see Reviewing the Form Transformation Log Output File (http://msdn.microsoft.com/en-us/library/dd338760.aspx).
Preparing Form Transformation The transformation process has two stages: •
Preparing for transformation
•
Transforming forms
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-13
Report Design in Microsoft Dynamics® NAV 2009 The following diagram illustrates the process of transforming forms to pages.
FIGURE 6.4 PREPARING FORM TRANSFORMATION
The topics in this section provide an overview of the steps that you need to take to prepare for transformation. If you take the time to prepare your forms for transformation, the transformation will be more efficient and complete. To prepare for transformation, you need to perform the following steps: 1. Install the form transformation tool. For more information, see How to: Install the Form Transformation Tool (http://msdn.microsoft.com/en-us/library/dd339024.aspx). 2. Redesign existing forms in the Classic client. It is not possible to transform some forms, such as Matrix forms. Redesigning forms smoothes the transformation process and helps to minimize errors when you run the tool and layout issues in the transformed page.
6-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix 3. Define the transformation input. Create mapping specifications by using the Transformation Input Files (TIF) Editor or by directly modifying the transformation input .xml files. You must assign each page a type. You can also specify additional layout and user experience (UX) changes.
Install the Form Transformation Tool You must copy the form transformation tool files before you can transform forms. The files that you must copy are located in the TransformationTool folder and the TransformationTool\TIF Editor folder on the installation DVD. The TransformationTool folder contains several files, including the .xml transformation input files. For more information about the transformation input files, see Understanding Form Transformation Input Files. The TIF Editor folder contains the TIF.fob and FormToPagetypeMapping.txt files. Before you begin this procedure, confirm the following: •
You have Microsoft Dynamics NAV 2009 installed with a developer license.
•
All Microsoft Dynamics NAV 2009 requirements are met.
To install the form transformation tool, copy the contents of the TransformationTool folder, which includes the TIF Editor folder, from the installation DVD. You can copy these to any location on the Microsoft Dynamics NAV 2009 server.
Redesigning Forms You may need to redesign some of your forms to make them preserve the business logic and layout when you transform the form to a page. Redesigning means that you have to either create a new form to replace the one that cannot be transformed, or modify the original form. Usually you only need to redesign a few forms in your application.
Why Redesign Your Forms? The following reasons may be why you may need to redesign some of your existing forms: •
Unsupported controls
•
Matrix-like layouts do not transform successfully
•
New user experience (UX) guidelines
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-15
Report Design in Microsoft Dynamics® NAV 2009 Unsupported Controls The RoleTailored client does not support certain control types that are used in the Classic client. The unsupported controls are the following: •
MatrixBox
•
Shape
You cannot map these controls in the Classic client to controls in the RoleTailored client. If a form contains one of these types of controls, then it will not transform. Matrix forms are examples of forms that use these types of controls. You must start at the beginning and design a new form.
Matrix-Like Layout Certain controls, when used together, create a matrix-like layout. Although the individual controls are supported, the matrix-like layout will not transform successfully. You must redesign forms with a matrix-like layout.
New UX Guidelines The RoleTailored client has new navigation principles and UX guidelines. This means that you must modify the behavior of some Classic client forms before they can be transformed, for example: •
In the RoleTailored client, the user must always be able to move from a list place to a card.
•
In the RoleTailored client, Journal forms must connect to their respective batch lists
•
In the RoleTailored client, separate list forms must be created for each document type.
Some forms in the standard application were redesigned to new forms for UX improvements. For more information, see http://msdn.microsoft.com/enus/library/dd338598.aspx.
Preparing Transformation Tool Input The transformation input files are XML files that define mapping rules. For most forms, before you transform forms to pages that you can use with the RoleTailored client, you must define the transformation input. Some simple forms do not require input, but for most forms, we recommend that you use the Transformation Input File (TIF) Editor to specify form transformation input files. You can also modify the transformation input .xml files directly instead of using the TIF Editor. This topic describes the TIF Editor and the workflow that you use to create and modify transformation input files by using the TIF Editor.
6-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Elements of the Transformation Input File Editor The user interface for the TIF Editor is a form that you run from Object Designer in the Classic client. The form that you run is form 177000, Transformation Forms. In this way, the TIF Editor offers a familiar environment for creating and modifying the transformation input in a tabular format rather than in the XML file. If you use the Microsoft Dynamics NAV Developers Toolkit, the TIF Editor also has data about form objects, which significantly improves efficiency and accuracy of the input data entry. The TIF Editor consists of the following objects: •
TIF.fob – A set of objects that make up the editor’s functionality.
•
FormToPageTypeMapping.txt - A list of form types, definitions, and their matching page types.
•
Schemas - TransformationInput.xsd, DeletePageElement.xsd, IgnorePage.xsd, IgnorePage.xsd, and MovePageElement.xsd
Transformation Input File Editor Workflow In your application, you may have forms that are the standard application forms, with or without customizations, and you may have Microsoft Certified Partner solution forms. The following steps summarize the workflow for the TIF Editor. Some steps in the workflow are optional, based on whether you have standard application forms or partner solution forms. 1. Install the TIF Editor. 2. If you have standard application forms, import the standard application transformation input files to view and modify transformation input specifications. 3. If you have partner solution forms, populate the TIF Editor with these forms. 4. Import the list of form types, definitions, and their matching page types, to be used for lookup. 5. Specify the page type for partner solution forms. The standard application forms already have the page type specified. 6. Specify the CardFormID for list forms that have associated cards and that are partner solution forms. The standard application forms already have the CardFormID specified. 7. Define additional input specifications for the form transformation. 8. Validate form transformation. 9. Export the input data out of the TIF Editor to create XML input files. The files are validated against the XML schemas.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-17
Report Design in Microsoft Dynamics® NAV 2009 Evaluating Client Files and Automation Before you move to the three-tiered architecture in Microsoft Dynamics NAV 2009, you must evaluate your files that reside on the client to determine whether you need to use different functions to upload or download those files. You must also evaluate your automation components to determine whether you need to use different functions, change code, or redesign them
Files In the Classic client, if the application creates a file, then that file is created on the local client computer. In the RoleTailored client, if the application creates a file, the file is created on Microsoft Dynamics NAV Server. If you need to store a file on the client computer, then you must write code to download the file from Microsoft Dynamics NAV Server to the client. Similarly, if the application must access a file that is stored on the client, then you must write code to upload the file from the client to Microsoft Dynamics NAV Server. The following examples demonstrate scenarios that access files: •
Reports or batch jobs in which the output is saved to a file
•
COM components that generate or consume files
The following table describes guidelines to determine what you must modify to work with files in the RoleTailored client.
6-18
Description of file
Change required
File is used for processing only
No change is required.
File is generated on the server and is provided to the user
Use the DOWNLOAD Function (FILE) or DOWNLOADFROMSTREAM Function (FILE) in C/AL.
File is provided from the client and sent to the server
Use the UPLOAD Function (FILE) or UPLOADINTOSTREAM Function (FILE) in C/AL.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Automation Components The following table describes guidelines to determine if you must modify your automation components for use in the RoleTailored client. Description of automation component
Change required
Component contains no UI and no client interaction and is for processing only
No change is required.
Component contains no UI and makes a file for a client
Use guidelines for files (see preceding table).
Component contains no UI and accesses local software or network resources, such as MSMQ
You may need to change code to make the computer resource path more explicit.
Component accesses client-local resources, for example, a Gantt server, or client-local hardware, for example, electronic scales
Component is not supported for use with the RoleTailored client. You must redesign using Web services.
Transforming Forms The transformation process has two stages: •
Preparing for transformation
•
Transforming forms
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-19
Report Design in Microsoft Dynamics® NAV 2009 The following illustration shows the process of transforming forms to pages.
FIGURE 6.5 FORM TRANSFORMATION
The topics in this section provide an overview of the steps that you need to take to transform forms to pages. The steps to transform forms are the following: 1. 2. 3. 4. 5.
Export your existing forms to an .xml source file. Configure the log file settings and the input and output file locations. Run the tool. Review the log file. If any forms did not transform successfully, you may need to make changes to your existing forms or to the input files and then retransform forms. 6. Import and compile the transformed pages into the Classic client so that you can view and use the pages in the RoleTailored client. 7. (optional) Transform the navigation pane in the Classic client to Departments in the RoleTailored client by transforming the MenuSuite object.
6-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Create Forms.xml Source File To transform forms to pages, you must create a source .xml file of the forms that you want to transform. The form transformation tool uses this source file as well as the transformation input .xml files and the schema files to transform forms to pages. This procedure describes how to create the source forms .xml file. Before you begin this procedure, confirm that you have completed the necessary preparation for transforming forms The following list of steps shows how to create the forms.xml input file. In the Classic client, click Tools, and then click Object Designer. 1. 2. 3. 4.
In Object Designer, click Form. Select the forms that you want to transform. Click the File menu, and then click Export. In the Export Objects window, browse to the location where you want to export the forms. We recommend that you export forms to the same folder where the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe file and the transformation input files reside. 5. In the File name text box, specify the name of the file. We recommend that you name the file Forms.xml. 6. In the Save As Type drop-down list, select XML Format (*.xml), and then click Save. NOTE: After you have save the forms to the Forms.xml file, the next step in the transformation process is to configure the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file. When you configure this file, verify that it specifies the correct name and location for the exported forms XML file.
Configuring the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.c onfig File Use the form transformation configuration file, Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config, for the following purposes: •
To define file names and path locations for input and output files. The form transformation tool references these files during execution.
•
To define the scope of logging by specifying what types of exceptions you want to include in the output log file.
If you have saved your files to the default locations and if you want to use the default scope of logging, then you do not need to modify the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-21
Report Design in Microsoft Dynamics® NAV 2009 File Locations By default, the location of the input and output files is the same as the location of the tool. The configuration file contains the following lines, which specify the names and locations for input and output files.
You can change this information in the configuration file if you want to use input files from a different folder or if you change the names of the input or output files.
Scope of Logging You can control the size and focus of your log file by including only the exceptions in which you are most interested. The following table describes the exception message types.
6-22
Message Type
Description
ChangeCodeManu ally
Transformation of a specified control or property could not be completed. Additional, typically manual, change or input is required to address the exception that is associated with this message.
CheckInputFile
There is an inconsistency in an input file.
CodeCannotBeTra nsformed
Code cannot be transformed automatically. Manual change to the form itself is needed.
DeleteTriggers
Specified trigger is not supported in the RoleTailored client and therefore, has been automatically deleted by the tool. Code from trigger will be moved to a new function and a call to this function will be typically be added to some other trigger.
Error
Any error. Typically, the transformation tool cannot recover after such an error.
General Information
Any information. Typically, no action is required.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Message Type
Description
IgnoreForms
Specified form was excluded from the transformation and no matching page was created.
IgnoreWarning
Verify that there is not an issue, and then ignore this warning.
InputInformation
Information about input files.
RemoveControls
Specified control on the form was not mapped to a matching control on a page.
RemoveProperties
Specified property on the form cannot be mapped to a matching property on a page.
TempCodeWash
Message that is triggered by a code transformation.
ValidateManually
Specified control or code has been changed during transformation. The change requires manual validation.
Warning
Any warning. Requires manual validation.
To configure which type of messages to include in the log file and the degree of message details, you assign a value code to each message type in the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file, and then set the TraceLevelSwitch value to specify the logging level. The following example from the configuration file shows the default value code assignments for each message type.
name="Error" value="1" /> name="CodeCannotBeTransformed" value="1" /> name="Warning" value="2" /> name="GeneralInformation" value="4" /> name="IgnoreForms" value="3" /> name="IgnoreWarning" value="2" /> name="InputInformation" value="1" /> name="DeleteTriggers" value="2" /> name="TempCodeWash" value="3" /> name="RemoveProperties" value="3" /> name="RemoveControls" value="3" /> name="ChangeCodeManualy" value="2" /> name="ValidateManualy" value="3" /> name="CheckInputFile" value="1" />
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-23
Report Design in Microsoft Dynamics® NAV 2009 Based on the preceding value codes, the default logging levels can be described as follows: •
1 Logs error messages and required information
•
2 Logs errors and warnings
•
3 Logs detailed error information
•
4 Logs verbose information
•
0 Logging is turned off
To specify the level of logging, you set the TraceLevelSwitch value. For example, in the following code, the logging level is set to 1, log error messages and required information.
You can modify the level of logging or the value code for each message type in the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file.
Run the Transformation Tool The following procedure describes how to run the form transformation tool to transform forms for the Classic client to pages that you can use in the RoleTailored client. Before you begin this procedure, you must do the following: •
Complete the necessary preparation for transforming forms.
•
Create the source forms.xml file.
•
Configure the input and output file locations and the level of logging.
The following list of steps shows how to run the form transformation tool. 1. Confirm that you have the following input files, and that the path to these input files is correct in the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file: o Forms.xml o CodeRules.txt o TransformPages.xml o IgnorePages.xml o MovePages.xml o DeleteElements.xml o MoveElements.xml o DeletePageElement.xsd o IgnorePage.xsd o MovePage.xsd o MovePageElement.xsd o TransformationInput.xsd 6-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix o o
Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config Microsoft.Dynamics.Nav.Tools.FormTransformation.exe
2. Navigate to the folder where Microsoft.Dynamics.Nav.Tools.FormTransformation.exe is located. 3. Double-click Microsoft.Dynamics.Nav.Tools.FormTransformation.exe. 4. Verify that the tool completes successfully and that you have the following output files in the folder specified in the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file: o Pages.xml o Transformation.log o TransformationLog.xml (contains the same information as Transformation.log) After you run the transformation tool, you must complete the following steps: •
Inspect the log file for errors.
•
If necessary, re-transform all or selected forms.
•
Import and compile pages.
Review the Form Transformation Log Output File After you run the form transformation tool, the pages that the tool created might not contain functionality that is equivalent to the original forms and might not display correctly in the user interface. You can use the information captured in the log file to help you to diagnose problems. By inspecting the log file, you can identify issues before you deploy the new page objects in the RoleTailored client. To resolve these issues, you must modify the input to the form transformation tool and run the tool again. This topic describes the information that is in the transformation log files. The same information is captured in the following log files: •
Transformation.log
•
TransformationLog.xml
For more information and examples of log messages, see Reviewing the Form Transformation Log Output File (http://msdn.microsoft.com/enus/library/dd338760.aspx).
Re-Transform Pages After you run the form transformation tool, you might discover errors or warnings in the transformation log file or issues with the page in the RoleTailored client. Form transformation is an iterative process. If the first transformation does not successfully convert all your forms into pages, then you may need to make changes and run the transformation tool again.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-25
Report Design in Microsoft Dynamics® NAV 2009 Before you begin this procedure, be sure that you have reviewed the Transformation.log file and that you understand any errors or warnings. To re-transform pages, execute the following list of steps: 1. If needed, make changes to the source form objects. . 2. If needed, make changes to the transformation input files. 3. If you have modified any source form objects, re-create the Formsl.xml source file. 4. Re-run the tool until you have transformed all your forms successfully.
Import, Compile and Run Transformed Pages After you have run the form transformation tool, you must import the Pages.xml file into Object Designer. Pages.xml contains all the metadata required to display your transformed forms as pages in the RoleTailored client. You must also compile all of the new page objects so they are compatible with the .NET Framework and the Microsoft Dynamics NAV architecture. After you import and compile the transformed pages, the Microsoft Dynamics NAV database contains both your original Classic client forms and your new page objects. You can run the RoleTailored client and view the transformed pages. Before you begin this procedure, you must successfully run the form transformation tool. 1. In the Classic client, click Tools, and then click Object Designer. 2. Click the File menu, and then select Import. 3. In the Import Objects window, in the Files of type drop-down list, select XML Format (*.xml), browse to the folder where the Pages.xml file is located, select Pages.xml, and then click Open. By default, the Pages.xml file, which was created when you ran the form transformation tool, is located in the same folder as the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe file and the transformation input files. If you changed the name or the location of the output .xml file in the Microsoft.Dynamics.Nav.Tools.FormTransformation.exe.config file, select the name of the file that you specified. 4. In Object Designer, click Page, and then select all the pages that you imported. 5. From the Tools menu, select Compile, and then click Yes. 6. Run the RoleTailored client to view your transformed pages. NOTE: To view a specific page in the RoleTailored client, run the following command from a Command Prompt window. DynamicsNAV:////runpage?Page=<PageID>
6-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix Transforming MenuSuite Objects In the Classic client, you access forms and reports from the navigation pane, which displays menus that are contained in a MenuSuite object. In the RoleTailored client, you navigate to pages and reports by using the following elements: •
Role Centers
•
Departments
You can transform a MenuSuite object that you use in the Classic client to a Departments page that you use in the RoleTailored client. The Departments page contains the entire suite of functionality as licensed and available to the company. In this way, the Departments page in the RoleTailored client is similar to the navigation pane in the Classic client. The Departments page is also a MenuSuite object with a layered item structure but is designed specifically for the RoleTailored client. In Microsoft Dynamics NAV 2009, when you create a new MenuSuite object, you must select either the Classic client or the RoleTailored client as the target. If you support both the Classic client and the RoleTailored client, you must maintain two sets of MenuSuite objects. The ID of a MenuSuite object for the RoleTailored client will be the Classic client ID plus 1000, as demonstrated in the following table. MenuSuite object in the Classic client
MenuSuite object in the RoleTailored client
10 MBS
1010 Dept - MBS
51 Add-on 1
1051 Dept - Add-on 1
You transform a MenuSuite object by using the Transformation Input File (TIF) Editor. The MenuSuite transformation creates a suggestion for a Departments page that is based on the navigation pane, transformation rules, and input. After you transform the MenuSuite object, you must verify whether you need to make additional updates to the transformed Departments page. The RoleTailored client has different functionality and different user experience (UX) requirements than the navigation pane in the Classic client. The additional updates that you make to the transformed Departments page can take advantage of the new functionality.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-27
Report Design in Microsoft Dynamics® NAV 2009 To reduce the number of these manual updates that you have to make after transformation, verify that you meet the following conditions before transforming a MenuSuite object. Condition
Reason
PageType is assigned to all form objects.
Form objects will be placed in a Department Category based on PageType.
CardFormID is assigned to all list form objects with a card.
Card Form IDs in MenuSuite will be replaced with the related list.
Microsoft Dynamics NAV Developer Toolkit is installed to provide data about which reports are ProcessingOnly reports.
ProcessingOnly reports are placed in the Tasks category on department pages. Other reports are placed in the Reports and Analysis category on department pages.
An example of a MenuSuite transformation can be found on How to: Transform a MenuSuite Object (http://msdn.microsoft.com/en-us/library/dd354979.aspx).
Summary More information is available on Transforming Forms to Pages (http://msdn.microsoft.com/en-us/library/dd338789.aspx).
6-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Appendix
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-29
Report Design in Microsoft Dynamics® NAV 2009
6-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Recommend Documents
Microsoft Dynamics NAV 2009 Application Design
Design and extend complete applications using Microsoft Dynamics NAV 20...
Microsoft Dynamics NAV 2009 Application Design
Design and extend complete applications using Microsoft Dynamics NAV 20...
MICROSOFT DYNAMICS® NAV 2009
FINANCE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this c...
Programming Microsoft® Dynamics™ NAV 2009
Develop and maintain high performance NAV applications to meet changing busin...
MICROSOFT DYNAMICS® NAV 2009
TRADE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this con...
MICROSOFT DYNAMICS® NAV 2009
COURSE 80043: INTRODUCTION
Microsoft Official Training Materials for Microsoft Dynamics ®...
Programming Microsoft® Dynamics™ NAV 2009
Develop and maintain high performance NAV applications to meet changing busin...
Programming Microsoft® Dynamics™ NAV 2009
Develop and maintain high performance NAV applications to meet changing busi...