Sei sulla pagina 1di 124

Crystal Reports 2008: Report Design III Report Processing Strategies

Learners Guide BOC330

Copyright

2009 SAP BusinessObjects. All rights reserved. SAP BusinessObjects owns the following United States patents, which may cover products that are offered and licensed by SAP BusinessObjects and/or affliated companies: 5,295,243; 5,339,390; 5,555,403; 5,590,250; 5,619,632; 5,632,009; 5,857,205; 5,880,742; 5,883,635; 6,085,202; 6,108,698; 6,247,008; 6,289,352; 6,300,957; 6,377,259; 6,490,593; 6,578,027; 6,581,068; 6,628,312; 6,654,761; 6,768,986; 6,772,409; 6,831,668; 6,882,998; 6,892,189; 6,901,555; 7,089,238; 7,107,266; 7,139,766; 7,178,099; 7,181,435; 7,181,440; 7,194,465; 7,222,130; 7,299,419; 7,320,122 and 7,356,779. SAP BusinessObjects and its logos, BusinessObjects, Crystal Reports, Rapid Mart, Data Insight, Desktop Intelligence, Rapid Marts, Watchlist Security, Web Intelligence, and Xcelsius are trademarks or registered trademarks of Business Objects, an SAP company and/or affiliated companies in the United States and/or other countries. SAP is a registered trademark of SAP AG in Germany and/or other countries. All other names mentioned herein may be trademarks of their respective owners.

C O N T E N T S
About this Course
Course introduction.....................................................................................................ix Course description.........................................................................................................x Course audience.............................................................................................................x Prerequisites...................................................................................................................x Level, delivery, and duration.......................................................................................x Applicable certifications and designations................................................................x Course success factors..................................................................................................xi Course setup..................................................................................................................xi Course materials...........................................................................................................xi Learning process..........................................................................................................xii

Lesson 1

Report Processing
Lesson introduction.......................................................................................................1 Multi-pass reporting......................................................................................................2 The Report Processing Model ..............................................................................2 What is processed in pre-pass 1...........................................................................3 Pass 1 processing....................................................................................................4 Pre-pass 2 processing.............................................................................................4 Pass 2 processing....................................................................................................5 Pass 3 processing....................................................................................................5 Activity: Sorting and totaling in the multi-pass process..................................6 Applying evaluation time functions...........................................................................9 Evaluating time functions.....................................................................................9 Using evaluation time functions .........................................................................9 Creating a manual running total........................................................................10 Activity: Using evaluation time functions........................................................11 Using a dynamic array................................................................................................13 Static vs. dynamic arrays.....................................................................................13 Creating a dynamic array....................................................................................13 Activity: Creating an array dynamically..........................................................14 Quiz: Report processing..............................................................................................16 Lesson summary..........................................................................................................17

Table of ContentsLearners Guide

iii

Lesson 2

Using Subreports
Lesson introduction.....................................................................................................19 Defining subreports.....................................................................................................20 Subreports.............................................................................................................20 Identifying typical uses for subreports.............................................................20 Processing considerations for subreports.........................................................21 Comparing linked vs. unlinked subreports.....................................................22 How subreport linking works............................................................................22 On-demand subreports.......................................................................................23 Activity: Defining subreports.............................................................................23 Creating an unlinked subreport................................................................................24 Using a pre-existing report as a subreport.......................................................24 Using the Report Wizard to create a subreport...............................................25 Activity: Using the Report Wizard to create a subreport...............................26 Modifying a subreport.........................................................................................27 Activity: Modifying a subreport........................................................................30 Creating a linked subreport.......................................................................................32 Creating links to subreports ..............................................................................32 Activity: Creating a linked subreport................................................................34 Creating on-demand subreports................................................................................36 Creating an on-demand subreport ...................................................................36 Adding captions to subreports...........................................................................37 Activity: Creating on-demand subreports........................................................38 Using shared variables with subreports...................................................................41 Using shared variables with a subreport .........................................................41 Activity: Using shared variables with subreports...........................................42 Linking unlinkable data..............................................................................................43 Linking unlinkable data with subreports.........................................................43 Creating links to unlinkable data.......................................................................43 Activity: Linking unlinkable data with subreports.........................................44 Quiz: Using subreports...............................................................................................46 Lesson summary..........................................................................................................47

Lesson 3

Creating Complex Formulas


Lesson introduction ....................................................................................................49 Using Print State functions.........................................................................................50 Defining Print State functions............................................................................50 Activity: Using Print State functions.................................................................51 Using loop control structures.....................................................................................53 Defining control structures.................................................................................53 Loop control structures ......................................................................................53

iv

Report Processing StrategiesLearners Guide

Activity: Using loop control structures.............................................................55 Using loop control structures with arrays...............................................................57 Determining the size of an array........................................................................57 Activity: Determining the size of an array (1)..................................................58 Activity: Determining the size of an array (2)..................................................59 Looping through an array...................................................................................60 Activity: Looping through arrays......................................................................61 Quiz: Creating complex formulas.............................................................................63 Lesson summary..........................................................................................................64

Lesson 4

Using Custom Functions


Lesson introduction.....................................................................................................65 Describing a custom function....................................................................................66 Custom functions.................................................................................................66 Advantages of custom functions .......................................................................66 Sample uses of custom functions ......................................................................67 The work flow for custom functions ................................................................67 Report custom functions vs. repository custom functions ............................68 Using custom functions..............................................................................................69 Using an existing custom function....................................................................69 Defining default argument values for custom functions...............................70 Optional values.....................................................................................................71 Activity: Using a Crystal-defined custom function.........................................72 Creating custom functions with Crystal syntax..............................................73 Custom function syntax rules.............................................................................74 Evaluation time.....................................................................................................75 Creating custom functions..................................................................................75 Using the Extract Custom Function from the Formula dialog box ..............76 Activity: Creating a custom function in the Extractor....................................77 Categorizing custom functions..........................................................................78 Saving custom functions in the repository.......................................................79 Activity: Saving a custom function in the BusinessObjects Enterprise Repository.............................................................................................................79 Modifying repository custom functions...........................................................80 Refreshing a report's repository custom functions.........................................81 Activity: Modifying repository custom functions (1).....................................82 Activity: Modifying repository custom functions (2).....................................83 Activity: Modifying repository custom functions (3).....................................85 Quiz: Using custom functions....................................................................................87 Lesson summary..........................................................................................................88

Table of ContentsLearners Guide

Lesson 5

Using XML and Web Services Data


Lesson introduction.....................................................................................................89 Using XML and web services data............................................................................90 Data source scenarios .........................................................................................90 Connecting to an XML data source...................................................................90 The XML and Web Services dialog box ...........................................................91 Connecting to a local XML data source ...........................................................93 Connecting to an HTTP(S) data source ............................................................93 Activity: Connecting to an XML data source...................................................95 Connecting to a web service data source..........................................................95 Activity: Creating a report using a web service...............................................96 Using a transform in XML reporting........................................................................99 Exporting XML reports with transforms..........................................................99 Importing an XML transform.............................................................................99 Exporting to XML format .................................................................................100 Activity: Exporting to XML format.................................................................101 Quiz: Using XML and Web Services Data .............................................................102 Lesson summary........................................................................................................103

Answer Key
Quiz: Report processing............................................................................................107 Activity: Defining subreports .................................................................................108 Quiz: Using subreports.............................................................................................109 Quiz: Creating complex formulas...........................................................................110 Quiz: Using custom functions..................................................................................111 Quiz: Using XML and Web Services Data .............................................................112

vi

Report Processing StrategiesLearners Guide

Report Processing Strategies


Introductions, Course Overview...........................................30 minutes
Lesson 1

Report Processing........................................................................1.5 hours


Multi-pass reporting Applying evaluation time functions Using a dynamic array Lesson 2

Using Subreports.............................................................................2 hours


Defining subreports Creating an unlinked subreport Creating a linked subreport Creating on-demand subreports Using shared variables with subreports Linking unlinkable data

Lesson 3

Creating Complex Formulas.....................................................1.5 hours


Using Print State functions Using loop control structures Using loop control structures with arrays Lesson 4

Using Custom Functions.................................................................1 hour


Describing a custom function Using custom functions Lesson 5

Using XML and Web Services Data.....................................45 minutes


Using XML and web services data Using a transform in XML reporting

AgendaLearners Guide

vii

viii

Report Processing StrategiesLearners Guide

About this Course


Course introduction
This section explains the conventions used in the course and in this training guide.

About this CourseLearners Guide

ix

Course description
Crystal Reports 2008 is a powerful, dynamic, actionable reporting solution that helps you design, explore, visualize, and deliver reports via the web or embedded in enterprise applications. This one-day instructor-led course is designed to give you comprehensive skills and in-depth knowledge required to plan and create reports that will help you analyze and interpret important nformation. As a business benefit, you will find that your increased understanding of report processing, formulas, custom functions and subreports will help you make more effective report design decisions and create more efficient reports.

Course audience
The Report Processing Strategies course builds on knowledge and skills acquired though experience using Crystal Reports or from previous courses.

Prerequisites
To be successful, learners who attend this course should have attended the following offerings: Crystal Reports: Report Design I Fundamentals of Report Design Crystal Reports: Report Design II - Business Reporting Solutions To be successful, learners who attend this course should have the following experience: Knowledge of Windows conventions Basic computer skills Experience using a web browser Basic database concepts

Level, delivery, and duration


This advanced instructor-led offering is a one-day course.

Applicable certifications and designations


This is a recommended course in the Business Objects Certified Professional - Crystal Reports certification.

Report Processing StrategiesLearners Guide

Course success factors


Your learning experience will be enhanced by: Activities that build on the life experiences of the learner Discussion that connects the training to real working environments Learners and instructor working as a team Active participation by all learners

Course setup
Refer to the setup guide for details on hardware, software, and course-specific requirements.

Course materials
The materials included with the course materials are: Name card Learners Guide The Learners Guide contains an agenda, learner materials, and practice activities. The Learners Guide is designed to assist students who attend the classroom-based course and outlines what learners can expect to achieve by participating in this course. Evaluation form At the conclusion of this course, you will receive an electronic feedback form as part of our evaluation process. Provide feedback on the course content, instructor, and facility. Your comments will assist us to improve future courses.

About this CourseLearners Guide

xi

Additional resources include: Sample files The sample files can include required files for the course activities and/or supplemental content to the training guide. Online Help Retrieve information and find answers to questions using the online Help and/or users guide that are included with the product.

Learning process
Learning is an interactive process between the learners and the instructor. By facilitating a cooperative environment, the instructor guides the learners through the learning framework.

Introduction
Why am I here? Whats in it for me? The learners will be clear about what they are getting out of each lesson.

Objectives
How do I achieve the outcome? The learners will assimilate new concepts and how to apply the ideas presented in the lesson. This step sets the groundwork for practice.

Practice
How do I do it? The learners will demonstrate their knowledge as well as their hands-on skills through the activities.

Review
How did I do? The learners will have an opportunity to review what they have learned during the lesson. Review reinforces why it is important to learn particular concepts or skills.

Summary
Where have I been and where am I going? The summary acts as a recap of the learning objectives and as a transition to the next section.

xii

Report Processing StrategiesLearners Guide

Lesson 1

Report Processing
Lesson introduction
Understanding how reports are processed by Crystal Reports will help you optimize your reports for efficient processing. After completing this lesson, you will be able to: Describe multi-pass reporting Use evaluation time functions Use a dynamic array

Report ProcessingLearners Guide

Multi-pass reporting
Crystal Reports uses a three-pass reporting method to generate reports. In this unit you will learn what happens during each step of this process. After completing this unit, you will be able to: Describe the Report Processing Model Describe what a pass is Describe the stages of the Report Processing Model

The Report Processing Model


There are five stages of processing when a report is run against a database. This is referred to as multi-pass processing or the Report Processing Model. A pass is a process that Crystal Reports uses each time the data is read or manipulated. The five stages of processing are: Pre-pass 1 Pass 1 Pre-pass 2 Pass 2 Pass 3

The Report Processing Model

As a general rule Crystal Reports processes the easier report components of the report first and the more complex ones later. Depending on the complexity of the report Crystal Reports may make one, two, or three passes over the data. This feature allows for complex reporting and formula manipulation.

Report Processing StrategiesLearners Guide

Crystal Reports processes a report top to bottom and left to right. Formulas placed in the top left of the Report Header process first and those placed in the lower right of the Report Footer process last. Understanding the Report Processing Model is important as it helps you make report design decisions that optimize processing. The Performance Information dialog box on the Report menu provides you with information about how many passes a report requires.

To find out how many passes a report requires


1. Preview or refresh the report. 2. Click the Report menu. 3. Click the Performance Information menu option. 4. Select the Processing node.

What is processed in pre-pass 1


When previewing a report, the first elements to be evaluated are constant formulas. Constant formulas are those that have a constant value for the entire report. They do not change from record to record. For example, 100*30 is a constant formula. Constant formulas are evaluated at the beginning of the print generation process and are never evaluated again. This process is known as BeforeReadingRecords. If you place a constant formula field (that is, 100*30) in the Details section, the result would be 3000 for each record displayed.

Report ProcessingLearners Guide

If no database or group field is included in the formula, the formula is evaluated before the program reads database records.

Pass 1 processing
After the BeforeReadingRecords process, Crystal Reports begins reading the database records. During the record reading process, the following occurs: Record retrieval Where possible, record selection and sorting are pushed down to the database in this step. Evaluation of recurring formulas Recurring formulas are those that contain database fields but do not contain references to subtotals or summary information. This evaluation time is known as WhileReadingRecords. Formulas that contain references to subtotals or summary information are processed in the second pass. Application of the record selection locally If the record selection is too complex to be pushed down to the database, Crystal Reports applies it in this step. Referencing the SQL query generated by Crystal Reports indicates whether the record selection formula has been pushed down to the database or if additional selection needs to be made once records are retrieved. Sorting, grouping, and totaling In this step, Crystal Reports sorts the records, separates them into groups, and then calculates the subtotals and summaries needed for each group. Crosstab, chart, and map generation Only crosstabs, charts, and maps that are based entirely on database fields and recurring formulas are generated in pass 1. If these objects include running totals and/or PrintTime formulas, they are generated in pass 2. Storage of saved data After the totaling process is complete, all of the records and totals are stored in memory and to temporary files. Unless the report is refreshed, Crystal Reports does not read the database again, but instead uses this saved data during all subsequent processing.

Pre-pass 2 processing
During pre-pass 2, Crystal Reports orders the groups in the report for Top N, Bottom N, or hierarchical grouping. The records are not read in this process, instead Crystal Reports only looks at group instances from pass 1, and takes the Top N as appropriate, or orders the groups based on the hierarchical grouping settings specified.

Report Processing StrategiesLearners Guide

Pass 2 processing
Crystal Reports enters the second pass through the data to format pages. The pages are formatted on demand. This means that Crystal Reports does not format a page until it is requested by the user, or until it is required for the total page count in pass 3. During page formatting, Crystal Reports does the following: Group selection formulas Crystal Reports enters the second pass through the data to format pages. For example:
GroupName ({Customer.Country}) = "Canada"

Running totals Calculation of formulas marked WhilePrintingRecords These are formulas that contain references to subtotals or summary information, also known as PrintTime formulas. The evaluation time is known as WhilePrintingRecords. Crosstabs, charts, and maps Crosstabs, charts, and maps that include running totals and/or PrintTime formulas, and charts that are based on crosstabs are generated in pass 2. OLAP grids Subreports Each subreport must repeat the entire multi-pass process to produce each report. This is important to keep in mind when adding subreports to your reports as each subreport adds processing overhead to a report. Generation of pages on-demand Page on-demand allows for pages on a report to be in a form ready for viewing and/or printing when the user requests it. Subtotals, grand totals, and summaries may appear to be incorrect if the report has a group selection formula. This occurs because the grand totals and summaries are calculated during pass 1, but the group selection formula filters the data again in pass 2. Running total fields can be used instead of summaries to total data in reports with a group selection formula.
Note: Although subreports appear in pass 2 in the flow chart, you can use on-demand subreports to ensure that your main report remains a single-pass report. With on-demand subreports, Crystal Reports must still make a second pass through the data; however, this second pass does not begin until you drill down on the subreport. Consequently, you can increase the performance of reports that contain subreports by using on-demand subreports.

Pass 3 processing
In the third and final pass, the total page count is determined. This applies to reports that use the total page count, or Page N of M special fields.

Report ProcessingLearners Guide

Activity: Sorting and totaling in the multi-pass process


Objectives
Create a grand total using the Running Total Expert. Create a TopN report. Create a group selection formula.

Instructions
1. Open the report titled Multi-pass.rpt in the course resources. 2. Insert a subtotal and grand total of Last Years Sales. Label the grand total as Grand Total. 3. Create a grand total using the Running Total Expert and place it beside the grand total. Label this grand total as Running Total. Both grand totals will be $850,630.63. 4. Save the report as Multi-pass-Totals.rpt to My Documents. Note: You will save all subsequent activity reports to this area. Your report should like similar to this:

5. Create a TopN report where N is equal to 3 and exclude Others. 6. Save the report as Multi-pass-TopN.rpt. 7. Compare the two grand totals. The one labeled Grand Total equals $850,630.63. The one labeled Running Total equals $830,862.92, which is a difference of $19,767.71.

Report Processing StrategiesLearners Guide

Why are they different? Your report should look similar to this:

8. Remove the TopN sort and create a group selection formula that only includes those groups whose subtotals are greater than $100,000. 9. Save the report as Multi-pass-Group Selection.rpt. 10.Compare the two grand totals. The one labeled Grand Total equals $850,630.63. The one labeled Running Total equals $758,862.92, which is a difference of $91,767.71. Why are they different? Your report should look similar to this:

Report ProcessingLearners Guide

Report Processing StrategiesLearners Guide

Applying evaluation time functions


Evaluation time functions can control how data is presented by controlling when it is calculated or presented. After completing this unit, you will be able to: Describe evaluation time functions Use evaluation time functions Create a manual running total

Evaluating time functions


In general, Crystal Reports sets an appropriate evaluation time for your formula, based on how much information the formula needs. However, there may be times when you want to guide Crystal Reports as to when your formulas will be processed. Evaluation time functions can be used for this purpose. Typically, evaluation time functions are the first line of a formula so the entire formula is evaluated at the appointed time. There are four evaluation time functions. Three of them match with pre-passes or passes from the Report Processing Model and the fourth is user defined.
BeforeReadingRecords (Pre-pass 1) WhileReadingRecords (Pass 1) WhilePrintingRecords (Pass 2) EvaluateAfter

Using evaluation time functions


BeforeReadingRecords

The BeforeReadingRecords function forces a formula to be evaluated during Pre-pass 1. The formula is evaluated before the program reads database records. When this function is used in a formula, the Formula Checker returns an error message if you attempt to include elements in the formula (database fields, groups, and so on) that must be evaluated at a later time (while reading or while printing records).
WhileReadingRecords WhileReadingRecords forces the formula to be evaluated while the program reads database

records. This happens during Pass 1. When this function is used in a formula, the Formula Checker returns an error message if you attempt to include elements in the formula (groups, page number fields, and so on) that must be evaluated at a later time (while printing records).This function can also be used to force a formula that includes no database fields and no group fields to process while reading records instead of before reading records.

Report ProcessingLearners Guide

WhilePrintingRecords WhilePrintingRecords forces the formula to be evaluated while the program prints database

records. This happens during Pass 2. This function can also force a formula that includes no database fields and no group fields to process while printing records instead of before reading records. It also forces a formula that includes database fields to process while printing records instead of while reading records.
EvaluateAfter

This function forces one formula to be evaluated after another. For example, two separate formulas in your report may have the same evaluation time (BeforeReadingRecords, WhileReadingRecords, or WhilePrintingRecords), or they appear in the same section of the report and, therefore, are automatically evaluated while records are printing. In such cases, it is often unclear which formula is evaluated first. In many situations, it is irrelevant which formula is evaluated first. However, some situations may require that one formula be evaluated after another. For instance, one formula may set the value of a variable while the other formula reads the value of that variable. The EvaluateAfter function can be used to force the second formula to be evaluated after the first formula has completed.

Creating a manual running total


One common use of evaluation time functions is employing a manual running total. Manual running totals accomplish the same result as the running total expert but offer more flexibility because of the ability to add more conditions to the running total. Manual running totals are created using three formulas. Where you place these formulas determines the result. Manual running totals use a variable and the evaluation time function WhilePrintingRecords. The three formulas are: Reset Evaluate Display

Reset
The Reset formula initiates the variable and assigns it the value of zero. This formula is typically placed in a headers section, such as, Page Header, Report Header, or Group Header.
WhilePrintingRecords; Global NumberVar nRT := 0;

10

Report Processing StrategiesLearners Guide

Evaluate
The Evaluate formula increases the value of the variable. This formula is typically placed in the Details section.
WhilePrintingRecords; Global NumberVar nRT := nRT + (value);

Display
The Display formula shows the current value of the variable on the report. This formula is typically placed in a footer section, such as, Page Footer, Report Footer, or Group Footer.
WhilePrintingRecords; Global NumberVar nRT;

Activity: Using evaluation time functions


Objective
Demonstrate how the multi-pass reporting process affects a formulas evaluation time.

Instructions
1. Open the report titled EvalTimeFunctions.rpt in the course resources. 2. Create a formula to reset the running total. Formula Name: Reset.
Global Currencyvar salesRT:= 0;

3. Place the @Reset formula in the Report Header section. 4. Create a manual running total field that sums Last Years Sales. Formula Name: Evaluate.
Global Currencyvar salesRT:= salesRT + {Customer.Last Years Sales}

5. Insert @Evaluate in the Details section beside Last Years Sales. 6. Create a formula to display the running total. Formula Name: Display .
Global Currencyvar salesRT;

7. Place the @Display formula in the Report Footer section. 8. Save the report as EvalTimeMRT1.rpt. 9. Compare the last Details section value for the Evaluate formula with the Display formula in the Report Footer. Are they the same? Why? Why not? 10.Add the WhilePrintingRecords evaluation time to the beginning of each of the formulas.
WhilePrintingRecords;

11.Save the report as EvalTimeMRT2.rpt. 12.Compare the last Details section value for the Evaluate formula with the Display formula in the Report Footer. Are they now the same? Why? Why not? 13.Place the Reset formula in the Group Header section.

Report ProcessingLearners Guide

11

14.Place the Display formula in the Group Footer section and format field as Bold. 15.Save the report as EvalTimeMRT3.rpt. Your report should look like this:

12

Report Processing StrategiesLearners Guide

Using a dynamic array


Arrays can be used to store a collection of values. They can be created statically or dynamically. After completing this unit, you will be able to: Describe static vs. dynamic arrays Create a dynamic array

Static vs. dynamic arrays


When there are two or more data items, instead of giving each data item a separate variable name, the collection of data items is given a single variable name. This collection is called an array. The individual data items contained in an array are known as the array elements. The elements in the array are numbered by their position in the array, referred to as an index. There are two types of arrays: static and dynamic. In a static array the elements are set and remain the same every time the report is run, regardless of the data included on the report. In a dynamic array the elements of the array change based on the data included on the report. The values included in a dynamic array reflect the actual values contained in your database.

Creating a dynamic array


Regardless of the type of array you are using, to use an array within Crystal Reports, you must: Declare the array Assign a value to the array Reference elements of the array When using a dynamic array there are two important items to keep in mind: The array must be processed during the second pass. The placement of the formulas on the report. Similar to a manual running total, a dynamic array is created using three formulas: Declare Populate Display

Declare
The declare formula declares the array, defines the number of elements within the array, and creates a counter variable. The Redim x[n] function is used here to set the size of the array. Re-dimension the array x to size n, where x is an array and n is a positive whole number specifying the new size of n. This formula is typically placed in a headers section, such as, Page Header, Report Header, or Group Header.
WhilePrintingRecords; Global DataType Array Array_Name;

Report ProcessingLearners Guide

13

Redim Array_Name[n]; Global NumberVar Counter_Name := 0;

Populate
The populate formula populates the elements of the array. This formula is typically placed in the Details section.
WhilePrintingRecords; Global NumberVar Counter_Name := Counter_Name +1; Global DataType Array Array_Name; Array_Name[Counter_Name]:= {field};

Display
The display formula shows the final result of the array. This formula is typically placed in a footer section, such as Page Footer, Report Footer, or Group Footer.
WhilePrintingRecords; Global DataType Array Array_Name; Join(Array_Name, ,)

Activity: Creating an array dynamically


Objective
Create a dynamic array that holds Supplier Countries.

Instructions
1. Create a new report using the Supplier table from the Xtreme database. Do not include any fields in this report. 2. Create a formula called DeclareArray that declares an array to store Countries of Supplier table. 3. Set this array to store the number of countries found in the data. Tip: Use DistinctCount to determine the size of the array. 4. In the same formula, declare a counter assigned to zero.
Global NumberVar nCounter := 0;

5. Create a second formula called PopulateArray that checks to see if the Country for the current record is already in the array. If not, it increments the counter and assigns the next element in the array to the Country field value. 6. Create a third formula called DisplayCountries. The result of this formula should be a string that says We have suppliers in followed by a list of all the array elements. Each element should be separated by a comma. 7. Add these fields to your report so that you only see the result of the array in the report footer. 8. Save this report as DynamicArray.rpt. Your report should look similar to this:

14

Report Processing StrategiesLearners Guide

Report ProcessingLearners Guide

15

Quiz: Report processing


1. Why is understanding the multi-pass report processing architecture important? 2. What are some common uses of evaluation time functions? 3. Which evaluation time function does not correspond to one of the passes? 4. Which evaluation time function should be used when a formula contains global variables? 5. What happens in pre-pass 2? 6. When working with Manual Running Totals, why is placement of the formulas on the report so important? 7. What is page on-demand and what role does it have in the multi-pass process?

16

Report Processing StrategiesLearners Guide

Lesson summary
After completing this lesson, you are now able to: Describe multi-pass reporting Use evaluation time functions Use a dynamic array

Report ProcessingLearners Guide

17

18

Report Processing StrategiesLearners Guide

Lesson 2

Using Subreports
Lesson introduction
Subreports enable you to create one report that provides all the information you need instead of creating multiple reports. You can create freestanding reports based on tables that are not related to those of the main report, or you can link the subreports to the main report data. After completing this lesson, you will be able to: Define subreports Create an unlinked subreport Create a linked subreport Create an on-demand subreport Use shared variables in a subreport Link unlinkable data

Using SubreportsLearners Guide

19

Defining subreports
This lesson examines subreports. You will learn and practice applying subreports and features to your reports. After completing this unit, you will be able to: Define subreports Identify typical uses for subreports Describe processing considerations for subreports Compare linked vs. unlinked subreports Describe how subreport linking works Define on-demand subreports

Subreports
A subreport is a report within a report. The process for creating a subreport is similar to the process of creating a regular report. A subreport can have most of the characteristics of a report, including its own record selection criteria. The differences between a subreport and a main or primary report are that a subreport: Is inserted as an object in a primary report; it cannot stand on its own (although a subreport can be saved as a primary or main report) Can be placed in any report section and the entire subreport will print in that section Cannot contain a subreport

Identifying typical uses for subreports


Subreports are typically used to: 1. Combine unrelated reports into a single report. You may wish to combine unrelated reports into a single report. For example, you may want to create a single report that presents: Sales grouped by sales representative Sales grouped by item While both reports deal with sales data, there is no real linear relationship between the reports. Subreports can be used to combine unrelated reports like the above example into a single report. While the reports could be based on the same data set, they do not have to be. They could each be based on entirely different data sets. 2. Coordinate data that cannot otherwise be linked. Tables can be linked in a report as long as the following criteria are met: The link fields are both database fields.

20

Report Processing StrategiesLearners Guide

The link fields contain similar data. The link fields are the same length. Linking tables is rarely a problem. However, there are some circumstances in which you cannot coordinate data from different tables because the data does not meet the linking criteria. 3. Present different views of the same data within a single report. Subreports can be used to provide a different view of the data in the primary report. For example, you might want to show summary values at the top of a report and details at the bottom. This can be done in a variety of ways. The two easiest methods are: Creating the summary report as the primary report and the details report as the subreport. In this method, the details subreport would be placed in the Report Footer section. Creating the details report as the primary report and the summary report as the subreport. In this method, the summary report would be placed in the Report Header section. 4. Perform one-to-many lookups from a field that is not indexed on the lookup field.
Note: This may not always be the most efficient means for one-to-many lookups.

Processing considerations for subreports


When using or considering the use of subreports, there are some factors that affect how fast and efficient your reports process. Consider the following:

Subreports require additional resources


Make sure you have enough resources, such as free disk space and memory, for the size of the database and the amount of processing a report requires. When Crystal Reports processes subreports, it may call data from the database onto the client computer, depending on what functions are used in the subreports formulas. Client-side processing requires additional hard disk space and increases network usage. If there are not enough resources on the computer, the report may stop processing and become corrupt, or the computer may return an error.

Subreport placement determines report processing time


The report section where you place a subreport affects the processing time of the whole report. For example, placing the subreport in the Details section of the main report causes the subreport to print once for each record returned on the main report. This slows report processing. If the subreport is placed in the Report Header, the subreport only prints once per report.

Subreport placement determines returned data


1. In reports that contain groups, a subreport can be inserted into the Group Header or Footer. If the subreport is linked to the main report on the grouped field, each time the group changes, the subreport reflects data for that group.

Using SubreportsLearners Guide

21

2. If you are passing values from the subreport to the main report with shared variables, you need Crystal Reports to first evaluate the shared variable in the subreport before it calls it from the main report. To accomplish this, place the subreport in a main report section above the section containing the formula that calls the shared variable. 3. Page Headers belong to individual pages and therefore cannot span more than one page. This can be an issue when a subreport is placed in the Page Header section of a main report. If the subreport is too large to fit on one page, the following message is displayed: The page size is not large enough to format the contents of an object.

Comparing linked vs. unlinked subreports


Unlinked subreports are freestanding; their data is not coordinated with the data of the primary report. In unlinked subreports, there is no attempt to match up the records in one report with the records in the other. An unlinked subreport does not have to use the same data as the primary report. It can use the same data source or a different data source entirely. In addition, the subreport is not limited to reporting on a single table. An unlinked subreport can be based on a single table or on multiple tables. Regardless of the underlying data sources, the reports are treated as unrelated. Linked subreports are just the opposite. Their data is coordinated. The program matches up the records in the subreport with the records in the primary report. If you create a primary report with customer information and a subreport with order information and link them, the program creates a subreport for each customer and includes all the orders for that customer in that subreport.
Tip: When you add an existing report with saved data as a linked subreport, the data is refreshed from the database. Unlinked subreports can preserve the saved data.

How subreport linking works


When you link a subreport to a primary report, the program creates the link using a parameter field. When a subreport link field is selected, the program creates: a parameter field in the subreport which is then used to retrieve values passed to it by the primary report a record selection formula for the subreport using the parameter field the selection formula limits the subreport to those records in which the link field is equal to the parameter field value When the report runs, the program finds the first primary field record it needs and passes the value in the link field to the parameter field in the subreport. The program then creates the subreport with record selection based on the parameter field value. Here is an example: You create a report that shows customer data and a subreport that shows order data. Then you link the two reports using the Customer ID field.

22

Report Processing StrategiesLearners Guide

When you run the report, the program finds the first customer record it needs and passes the Customer ID value from that record to the subreport parameter field. The Orders subreport is processed. Since the subreport selection formula selects only those records in which the Customer ID value is equal to the parameter field value, and since that parameter field value is equal to the Customer ID in the first record in the primary report, the subreport contains only those records that have the same customer ID. Namely, those records that are orders for the first customer. When the subreport is finished, the program locates the second record it needs in the primary report, prints the customer data, and then passes this customers ID number to the parameter field. The program then runs a subreport including only those order records for the second customer. The process continues until the report is finished. All of this parameter field manipulation takes place behind the scenes. You pick the fields that link the primary report with the subreport and the program does the rest. The values are passed without the parameter field prompting you for a value.

On-demand subreports
On-demand subreports can be especially useful when you want to create a report that contains multiple subreports. In this case, you can choose to have these subreports appear only as hyperlinks. The actual data is not read from the database until the user drills down on the hyperlink. Only data for on-demand subreports that are actually viewed is retrieved from the database, making the subreports much more manageable.
Note: Data for an on-demand subreport is not saved unless the subreport is actually open in a preview window.

Activity: Defining subreports


Objective
Fill in the blanks to define the different types of subreports. 1. subreports are subreports with coordinated data.

2. With subreports, the actual data is not read from the database until the user drills down on the hyperlink. 3. subreports are free-standing reports; the data is not in any way coordinated with the data of the primary report.

Using SubreportsLearners Guide

23

Creating an unlinked subreport


At times, you may need to combine unrelated reports into a single report. For example, you want to add a graph that shows the top selling products as a subreport to your Sales by Region report. This example can be easily created by inserting a subreport object displaying the top five products in a chart into a main report. After completing this unit, you will be able to: Use a pre-existing report as a subreport Use the Report Wizard to create a report Modify a subreport

Using a pre-existing report as a subreport


You can insert an existing report into another report as a subreport. Open the primary report and follow the "To use a pre-existing report as a subreport" procedure.

To use a pre-existing report as a subreport


1. With the primary report open, click Insert Subreport. The Subreport dialog box opens.

2. Select Choose an existing report and enter the name. If you do not know the name of the subreport, click the Browse button and locate it in the dialog box. 3. In the Report Name text box, enter the name and path of the report, or click Browse and choose the report from the dialog box that opens. 4. From the Insert Subreport dialog box, click OK.

24

Report Processing StrategiesLearners Guide

The program displays a rectangular object placement frame. 5. Move the top margin of the object frame into the section where you want the object and click once to place it. The program places the subreport object into that section and increases the size of the section vertically, if required. The program creates a subreport design tab labeled with the subreport name. 6. If you need to edit your report, click the subreport design tab and modify your subreport as you would any other report. You can suppress any sections in the subreport that you do not want to display. 7. Preview your subreport. Two options exist when previewing your subreport. If you click Print Preview while in the subreports Design tab, you can preview just the subreport. If you want to preview the subreport as part of the main report, click Print Preview from the primary reports Design tab.
Note: Subreports do not contain Page Header or Page Footer sections.

Using the Report Wizard to create a subreport


You can use the Report Wizard to create and insert a subreport into another report. Open the primary report and follow the procedure below.

To use the Report Wizard to create a subreport


1. With the primary report open, click Insert Subreport. The Insert Subreport dialog box opens. 2. Select Create a subreport with the Report Wizard and enter a name in the New report name text box. 3. Click the Report Wizard button. 4. Follow the steps in the wizard to create your subreport. 5. Click OK when you are finished with the wizard to return to the Insert Subreport dialog box. 6. From the Insert Subreport dialog box, click OK. The program displays a rectangular object placement frame. 7. Move the top margin of the object frame into the section you want the object and click to place it. The program places the subreport object into that section and increases the size of the section vertically, if required. The program creates a subreport design tab labeled with the subreport name.

Using SubreportsLearners Guide

25

8. Preview your subreport. Two options exist when previewing your subreport. If you click Print Preview while in the subreports Design tab, you can preview just the subreport. If you want to preview the subreport as part of the main report, click Print Preview from the primary reports Design tab.

Activity: Using the Report Wizard to create a subreport


Objective
Create an unlinked subreport using the Report Wizard Your company, Xtreme Bike Company, is merging with another bike company called Mountain Bikes, Inc. Your company already uses a sales report that lists the customer sales information for each region. The customer data comes from the Xtreme database, your companys main data source. You now have a new database containing data for Mountain Bikes Inc. that you want to include on the report.

Instructions
1. Open SubreportsWizard.rpt. 2. Using the Report Wizard, insert a subreport based on the Mountain Bikes Inc. database. Note: You need to create a connection to the MountainBike.mdb found in the Lesson 5 folder of the Activity Resources or in the Data_Sources folder in the course resources. Use an Access/Excel (DAO) connection. 3. Include the fields that give you the following information on your report: CONAME, CITY, LASTYRSALE. 4. Place the subreport in the Report Footer of the main report, so the subreport data appears after the main report data. 5. Save the report as SubreportsUnlinked.rpt. The last page of your report, showing the subreport data, should look similar to this:

26

Report Processing StrategiesLearners Guide

Modifying a subreport
Once you have created and inserted your subreport, you may want to make some modifications to it. Applying object formatting or section formatting within the subreport is the same as with any other report. You can also add formatting to the subreport placeholder. Items such as the border, fonts and subreport labels can be formatted or changed. To edit a subreport, access the subreport design tab and make changes to the report just as you would any other report. Any of the sections and objects on the report can be formatted.

To format a subreport
1. In either the design or preview tab of the main report, right-click the subreport placeholder.

Using SubreportsLearners Guide

27

2. From the shortcut menu, click Format Subreport. The Format Editor opens.

28

Report Processing StrategiesLearners Guide

3. You can now apply formatting using the tabbed dialog.

To edit a subreport
1. From either the design tab or the preview tab of the main report, right-click the subreport placeholder.

Using SubreportsLearners Guide

29

2. Click Edit Subreport. The subreport design tab opens. Note: Notice that the subreport design tab has the name of the subreport on the tab itself. It can be changed on the Subreport tab of the subreport Format Editor. 3. Now you can apply formatting to the subreport objects or sections.

Activity: Modifying a subreport


Objective
Format a subreport. The current report includes a subreport that needs to be better formatted. Any user of this report should not notice the difference between the main report and the subreport.

Instructions
1. Open SubreportsUnlinked.rpt. 2. Format the subreport so there is no distinction between the main report and the subreport. When previewed, they should appear as though they are one main report. 3. Save the report as SubreportsFormatted.rpt. The Report Footer of your main report should look similar to this:

30

Report Processing StrategiesLearners Guide

Using SubreportsLearners Guide

31

Creating a linked subreport


Frequently, the data in a subreport supplements the data in the primary report. You might, for example, have customer data in a primary report and then use subreports to show the orders for each customer. In such cases, you need to coordinate the data in the primary report with the data in the subreport so that the orders in each subreport match up with the correct customer. After completing this unit, you will be able to: Create linked subreports

Creating links to subreports


Often you need to add to the information in your main report. In this case, a subreport can provide supplementary data. For example, you may have a main report with a customer list per region and a subreport with a list of suppliers per region. You need to coordinate the data in the primary report so that the subreport shows the records for the appropriate suppliers. This example is a linked subreport. To link a subreport to a primary report, choose a field in the subreport and one in the primary report that contain common data. When you indicate which field in the subreport you want to link to, the program: 1. automatically creates a parameter field in the subreport for the field you are linking to. 2. uses the newly created parameter field in the subreports record selection. 3. passes the value to the subreports parameter field when you preview the main report and creates the subreport with a record selection based on the parameter fields value. The creation and use of the parameter field happens behind the scenes. You need only to indicate which field you want to use to link the subreport to the main report. Since the program creates a parameter field in the subreport, that parameter field is available for use elsewhere in the subreport. Select the parameter field from the fields list in the Formula Editor or from the Parameter list of the Field Explorer in the subreport.

To create a linked subreport


1. With the primary report open, click Insert Subreport. The Insert Subreport dialog box opens.

32

Report Processing StrategiesLearners Guide

2. Select one of the available options: Choose an existing report Browse to an already-created subreport. Create a subreport with the Report Wizard Enter a name for the report in the Report Name text box. Click the Report Wizard button. Create the subreport and return to the Insert Subreport dialog box. 3. To link the subreport to the main report, click the Link tab. 4. Select the subreport you want to link to from the For subreport drop-down list. Typically, this text box is grayed out because the subreport you just selected or created is the default. 5. Select the field you want to use as the link field in the primary report from the Available Fields list. 6. Click the > button. The selected field appears in the Field(s) to link to list. 7. Select the subreport field you want to link to the containing report from the Select data in subreport based on field list. The program creates a parameter field in the subreport that retrieves a value from the primary report. The record selection in the subreport is based on this value. Note: If you need to link on more than one field, repeat steps 5-7. 8. Click OK when done.

Using SubreportsLearners Guide

33

The program displays a rectangular placement field. 9. Drag the object frame into the position you want the subreport to appear in your main or primary report. When you run the report, the program coordinates the data from the primary report and subreport based on the field you linked on. Note: If you would like to edit the subreport links, highlight the subreport placeholder, right-click and choose Change Subreport Links.

Activity: Creating a linked subreport


Objective
Create a linked subreport.

Instructions
The current report includes a subreport that needs to be better integrated. Users of this report should not notice the difference between the main report and the subreport. 1. Open SubreportsFormatted.rpt. 2. Link the subreport to the main report for each region. Note: The Customer.Region field in the Xtreme database contains comparable information to the Customer.State field in the MountainBike.mdb. 3. Format the subreport so it blends in with the main report. 4. Blank sections and subreports should be suppressed. 5. Save the report as SubreportsLinked.rpt. Your report should look similar to this:

34

Report Processing StrategiesLearners Guide

Using SubreportsLearners Guide

35

Creating on-demand subreports


On-demand subreports are useful when you want to create a report that contains multiple subreports and where the subreport data is not shown or retrieved until requested. After completing this unit, you will be able to: Create an on-demand subreport Add captions to subreports

Creating an on-demand subreport


An on-demand subreport is represented by an object frame or placeholder in the preview window. The actual data is not read from the database until you drill down on the placeholder.
Note: If you save a report with saved data, the on-demand subreport data will not be saved, unless you have that subreport tab open in a review window at the time you save the report.

You can place a caption on the placeholder for a subreport such as Click here for more details. A formula can be used to display the caption in the subreport placeholder.

To create an on-demand subreport from an existing report


1. Select the subreport in your primary report. 2. From the Format menu, click Format Subreport. The Format Editor dialog box opens. 3. Click the Subreport tab. 4. Select the On-demand Subreport check box.

36

Report Processing StrategiesLearners Guide

5. Click OK. 6. Preview the report. Note: Remember that you can also specify a subreport to be on-demand when you create a new subreport by choosing the on-demand subreport option from the Insert Subreport dialog box.

Adding captions to subreports


Captions enable you to quickly organize your reports in a concise and visually manageable form. Captions can be used on the preview tab and the placeholder frame of an on-demand subreport. Placeholder frame captions only apply to on-demand subreports, while tab text captions apply to both on-demand subreports and regular subreports. Since the data from a regular subreport is visible on the preview tab, there is no need for a frame caption when you format a regular subreport. A tab text caption replaces the subreport file name caption on the Subreport Preview tab. You can write captions by using formulas. Both placeholder frame captions and Subreport Preview tab captions can include field names from the main report.

Using SubreportsLearners Guide

37

To add captions to subreports


1. Select the subreport. 2. From the Format menu, click Format Subreport. The Format Editor opens. 3. Click the Subreport tab. 4. Enter either an on-demand subreport caption or a tab text caption by clicking the appropriate Formula button and opening the Formula Workshop. 5. Enter your formula in the Formula text box. For example, in the Crystal syntax, a caption formula would be:
"More Information About " + {Customer.CustomerName}

Using the Xtreme database, this formula would give you a caption like More Information About Pathfinders or More Information About Rockshocks for Jocks. 6. Click Check to check your formula for errors. If the program finds an error, a message box detailing the nature of the error is displayed. 7. After fixing any errors, click Close. The program returns you to the Format Editor. 8. Click OK to return to the report. Note: A tab text formula is only evaluated when you drill down on a subreport. If you preview a subreport separately from the primary report, the formula is not evaluated.

Activity: Creating on-demand subreports


Objective
Create an on-demand subreport and add captions to it.

Instructions
The current report has a link between the main report and the subreport. The users dont want to see the subreport data all the time. They would rather click on a hyperlink to retrieve the Mountain Bike companys data. The users also want to see useful hyperlink titles and drill-down tabs. 1. Open SubreportsLinked.rpt. 2. Change the subreport to an on-demand subreport. 3. Edit the subreport and insert a text object that says No Information Available. 4. Conditionally suppress the text object so if the subreport returns no data No Information Available is displayed.

38

Report Processing StrategiesLearners Guide

5. Change the hyperlink title to reflect the appropriate region being invoked. 6. Change the drill-down tab to reflect the appropriate region displayed. 7. Make sure the column headings appear in the drill-down page. 8. Save the report as SubreportsOnDemand.rpt. Your report should look similar to this:

If you click the Click here tab caption for AZ, your report should look similar to this:

Using SubreportsLearners Guide

39

If you click the Click here tab caption for BC, your report should look similar to this:

40

Report Processing StrategiesLearners Guide

Using shared variables with subreports


You may want to pass information such as grand totals from a subreport to the main report. This can be done using shared variables. After completing this unit, you will be able to: Use shared variables with subreports

Using shared variables with a subreport


To extend subreport functionality one step further, you may want to pass information from a subreport to the main report. For example, you want to create a grand total by adding numbers from the main report to numbers from the subreport. Or you want to find out whether the subreport returns data or not. Both of these tasks can be accomplished by using shared variables. The information from the subreport is stored in a shared variable and passed to the main report. The main report can then fetch or retrieve this information by referencing the shared variable. For example, you want to add the total number or count of suppliers from your subreport to the total number or count of the subtotal from your main report to find out the total count of contacts your organization has. The first step is to insert a formula in the subreport to store the count of suppliers. You need to declare or name the variable. In this case, the shared variable is GT for Grand Total. Then, assign the value of the shared variable. For this example, it is the count of companies. The formula for the subreport looks like this:
shared numbervar GT:= count({BikeCo.CONAME})

You then place this variable in the report footer of the subreport so the count is for all suppliers in that region. You can add a text object that indicates that this total reflects the total number of suppliers. Next, create a formula in the main report that references the shared variable. In this formula, you want to calculate the total number of customers in a region and then add that total to the subreport total. The result is the total number of contacts in the region. You are referencing the GT shared variable from the subreport and adding it to the total of the main report. The formula for the main report looks like this:
shared numbervar GT; count ({Customer.Customer Name}, {customer.Region}) + GT

Since the subreport must process first, this formula is placed in the main report group footer section under the subreport. Because of the multi-pass reporting sequence that Crystal Reports applies, subreports process near the end of Pass 2. You should split the section into an a and b section then place the subreport in a and the formula in b.
Tip: You can reference the shared variable in either the main report or in the subreport. If your report has several subreports, the shared variable can also be used in any or all of the subreports.

Using SubreportsLearners Guide

41

Activity: Using shared variables with subreports


Objective
Use shared variables and pass total information from the subreport to the primary report.

Instructions
The current report includes a subreport that is well integrated. The users would like to have subtotals for the customer count and last years sales amount. The current report includes a subreport that is well integrated. The users would like to have subtotals for the customer count and last years sales amount. 1. Open SubreportsShared.rpt. 2. Edit the subreport to create two formulas using shared variables to hold a count of customers and a total sales formula. 3. Create a formula in the main report that combines the count value from the subreport with a count of the customers from each group in the main report. 4. Create a formula in the main report that combines the sales value from the subreport with a sum of sales for each customer group in the main report. 5. Create a second Group Footer (GF 1b) and place the formulas within GF 1b. 6. Add the appropriate labels. 7. Save your report as SubreportsSharedVariables.rpt. Your report should look similar to this:

42

Report Processing StrategiesLearners Guide

Linking unlinkable data


Many corporations store data in a number of databases and it is possible that you will not be able to link the data because of limitations. If you want to link between different field types or from a formula field, you can use subreports. After completing this unit, you will be able to: Link unlinkable data with subreports Create links to unlinkable data

Linking unlinkable data with subreports


When linking two tables in Crystal Reports, the two tables must have a common database field (same data type and length). For example, your Oracle database stores the Customer number as a number type field and the internal Sales activity database stores the Customer number as a string type field. You cannot link the two databases together within Crystal Reports Visual Linking Expert because they are different data types. Using subreports, you can link different types with the use of formulas.

Creating links to unlinkable data


When you need to link unlinkable data, you can use subreports because subreports allow you to link to or from a formula field. All you need to do is create a formula field in the primary report or the subreport that returns the same result (that is, date type or length) as the database field value you want to link to. You then link from the main report and subreport to or from the formula field.

To link to unlinkable data in subreports


1. Create the primary report using a table that includes the field to be linked to. Example: Social Security Number 2. Create (or import) a subreport including a formula that extracts the Social Security Number from the Employee ID field. For this example, use {@EXTRACT}. 3. Place the subreport where you want it to appear in the primary report. 4. Link the subreport to the primary report by linking the Social Security Number field in the primary report ({file.SSN}) to the formula that extracts the number in the subreport ({@EXTRACT}). When you run the report, the program coordinates the data in the primary report with the data in the subreport based on the link between the main report database field and the type-converted formula field linked to in the subreport.

Using SubreportsLearners Guide

43

Note: The field type of the primary report field to link from determines which subreport fields are visible when choosing the field to link to. Therefore, it is important to make sure the formula in the subreport to be linked to is of the same type.

Activity: Linking unlinkable data with subreports


Objective
Use subreports to link unlinkable data.

Instructions
You want to create a report that lists your customers within California and then for each customer lists the special events they attended in 1998. The problem here is that the data is unlinkable. The Customer ID field in the primary report is a number field, but in the events table, it is a string field. The customer data is stored in the Customer table within the Xtreme database. The Customer ID field is stored as a Number. The Events table within the Events.mdb contains the information on trade shows, and so on, but it stores the CustID field as a string. 1. Create the primary report using the Customer table from the Xtreme database. 2. Create a listing report of Californian customers displaying: Contact Name (combining the contacts first and last names), and Phone Number. 3. Insert a group on the Customer Name. 4. Create a subreport from Events.mdb displaying Event Type, Start Date, and City. Note: Use a Data Files connection to Events.mdb, which can be found in the Lesson 2 folder in Activity Resources or in the Data_Sources folder in the course resources. 5. Link from Customer.Customer ID to Events.CustID. 6. Format the report to be presentation quality. 7. Shade the subreport with a different color so it stands out. 8. Suppress any blank subreports. 9. Save the report as SubreportUnlinkableData.rpt. Your report should look similar to this:

44

Report Processing StrategiesLearners Guide

Using SubreportsLearners Guide

45

Quiz: Using subreports


1. In which sections of the main report are subreports generally placed? 2. When a subreport is modified (edited), how does this affect the original report (not main report) on which the subreport was based? 3. When do on-demand subreports actually run? 4. When do subreports (not on-demand) refresh? 5. True or False. On-demand subreports can be linked or unlinked. 6. In what ways can data be passed from one report to another? 7. Can subreports have subreports themselves? 8. List some applications of subreports. 9. Why is placement of a linked subreport important? 10.When you right-click on a subreport, Crystal Reports displays a menu. What is the difference between the menu options Edit Subreport and Format Subreport? 11.Where should a shared variable initially be declared? 12.What might cause a subreport to display no data?

46

Report Processing StrategiesLearners Guide

Lesson summary
After completing this lesson, you are now able to: Define subreports Create an unlinked subreport Create a linked subreport Create an on-demand subreport Use shared variables in a subreport Link unlinkable data with subreports

Using SubreportsLearners Guide

47

48

Report Processing StrategiesLearners Guide

Lesson 3

Creating Complex Formulas


Lesson introduction
Crystal Reports offers power formula capabilities to expand the functionality of your report. After completing this lesson, you will be able to: Use Print State functions Use loop control structures Use loop control structures with arrays

Creating Complex FormulasLearners Guide

49

Using Print State functions


This unit examines and demonstrates Print State functions. After completing this unit, you will be able to: Define and demonstrate Print State functions

Defining Print State functions


Functions are built-in procedures or subroutines used to evaluate, make calculations on, or transform data. Print State functions return a value based on the state of the report being previewed. Two examples of Print State functions are: IsNull() NextIsNull()
IsNull() IsNull() evaluates the field specified in the current record and returns TRUE if the field contains

a null value. A null value is equal to nothing or not defined. You can use this function in a record selection formula to limit the report to records that have something other than a null value in the field specified. You can also use it to have the program take some action whenever it encounters a null value. Some databases support null data values and others do not. This function will not work if the active database(s) does not support null values. If the database(s) supports null values, the function can be used to reference the null values that get created as the result of a failed lookup while joining. Caution: If a field value is equal to null, it does not mean it is of zero value in the case of a number or blank in the case of a string. It is nothing or not defined. The following examples are applicable in both Basic and Crystal syntax:
IsNull({orders.ORDER AMOUNT})

If the order amount equals $500, the result is false, meaning the order amount is not null. If the order amount is equal to null, the result is true.
Not IsNull({orders.ORDER AMOUNT})

When used as a record selection formula, the report only includes those records that have something other than a null value in the {orders.ORDER AMOUNT} field. Tip: IsNull() returns FALSE if the string expression is only spaces. This situation can happen if a data entry person uses the spacebar thinking they are deleting a value in a field. You can use the TRIM function to catch these values (that is, consider them NULL). For example:
@IsNullTrimDemo // Using ISNULL and TRIM together to find blanks If ISNULL({tablename.fieldname}) Or TRIM({tablename.fieldname}) = Then True //or Value if true

50

Report Processing StrategiesLearners Guide

NextIsNull() NextIsNull() is similar to IsNull() in that it tests for null values and returns a Boolean (T/F)

value. The difference is that it evaluates the specified field in the next record as opposed to the current record. You can use this function to test for the last item in a list and to take some action when you identify that last item. The following example is applicable to Crystal syntax:
If NextIsNull ({employee.EMPLOYEE ID}) Then "Last employee of record" Else ""

In an employee database with no null values in the Employee ID field, the NextIsNull() function flags the last employee on the list. Note: Using this function in a formula forces the formula to be evaluated at print time.

Activity: Using Print State functions


Objective
Demonstrate the use of the IsNull() function.

Instructions
Create a list of products. For products that do not have a Size, display One Size Fits All. 1. Create a blank report. Connect to the Product table in the Xtreme sample database. 2. Place Product ID and Product Name on the report. 3. Create a formula that displays Product.Size field in uppercase. If there is no size (IsNull), display the string ONE SIZE FITS ALL. 4. Place the formula on your report. 5. Save the report as PrintState.rpt. Your report should look similar to this:

Creating Complex FormulasLearners Guide

51

52

Report Processing StrategiesLearners Guide

Using loop control structures


Control structures allow you to vary the sequence and order in which expressions are executed. After completing this unit, you will be able to: Define control structures Use control structures

Defining control structures


Formulas without control structures execute each expression in the formula exactly once when the formula is evaluated. The expressions are executed in a sequential fashion, from the first expression in the formula to the last. Control structures enable you to vary this rigid sequence. Depending upon which control structure you choose, you can skip over some of the expressions or repeatedly evaluate some expressions depending on if certain conditions hold. Control structures are the primary means of expressing business logic and typical report formulas make extensive use of them. The control structures in Crystal Syntax are:
If expressions Select expressions For loops While loops Option loops

Loop control structures


Control structures give your formulas much more power and flexibility. Loop control structures evaluate one expression over and over until meeting the condition for exiting the loop. In this section, the following loop control structures will be examined: For loops While loops Option loops
Note: Examples and activities are shown and practiced using Crystal syntax.

For Loop
A For loop enables you to evaluate a sequence of expressions multiple numbers of times. This is unlike the If and Select expressions where the program passes through each expression at most once during the formula's evaluation. For loops are best when you know the number of times that the expression needs to be evaluated in advance. The syntax for For loops is demonstrated by the following example:

Creating Complex FormulasLearners Guide

53

Suppose you want to reverse the {Customer.Customer Name} string. For example, City Cyclists becomes stsilcyC ytiC.
//Reverse a string version 1 Local StringVar str := ""; Local NumberVar strLen := Length ({Customer.Customer Name}); Local NumberVar I; For I := 1 To strLen Do ( Local NumberVar charPos := strLen - I + 1; str := str + {Customer.Customer Name}[charPos] ); str

Examine how this formula works assuming that the current value of the field {Customer.Customer Name} is Clean Air. The variable strLen is assigned to be the length of Clean Air, namely nine. The variable I is known as a For counter variable since its value changes with each iteration of the For loop. In other words, it is used to count the iterations of the loop. The For loop iterates nine times, during the first time, I is one, then I is two, then I is three and so on until finally I equals nine. During the first iteration, the ninth character of {Customer.Customer Name} is appended to the empty string variable str. Thus str equals r after the first iteration. During the second iteration, the eighth character of {Customer.Customer Name} is appended to str and so str equals ri. This continues until after the ninth iteration, str equals riA naelC which is the reversed string. Note: In practice, the above formula code would be well-documented with the use of comments to describe line-by-line what the formula does.

While Loop
Another looping mechanism is the While loop. A While loop can be used to execute a fixed block of statement for an indefinite amount of time. There are two different types of While loops: While...Do The While... Do loop evaluates the condition, and if the condition is true, then it evaluates the expression following the Do. When it has finished doing this, it evaluates the condition again and if the condition is true, it evaluates the expression following the Do again. It continues repeating this process until the condition is false. Do...While The Do... While loop evaluates the expression once no matter what. It then evaluates the condition, and if the condition is true, evaluates the expression again. This process continues until the condition is false.

54

Report Processing StrategiesLearners Guide

The While loop supports an Exit While statement to immediately jump out of the loop. Its use is analogous to the use of Exit For in For loops. As with the For loop, the While loop when considered as an expression always returns the Boolean value True. The following is an example of a While...Do loop:
Local StringVar inString := "The 7 Dwarves"; Local NumberVar strLen := Length (inString); Local NumberVar result := -1; Local NumberVar I := 1; While I <= strLen And result = -1 Do ( Local StringVar c := inString [I]; If NumericText ) Then result := I; I := I + 1; );

The formula searches for the first occurrence of a digit in an input string. If a digit is found, it returns its position, otherwise it returns -1. In this case, the input string is set explicitly to a string constant, but it could be set equal to a String type database field instead. For example, for the input String, The 7 Dwarves, the formula returns 5, which is the position of the digit 7.

Option Loop
The Option loop statement can be used to specify the maximum number of loop condition evaluations per evaluation of a formula. This statement should only be used when the default maximum loop count of 100,000 is not sufficient for the given formula. Note: The Option Loop statement must be used before any other statements. Crystal syntax for the Option Loop is as follows:
Option Loop maxIterations

Where maxIterations = the maximum number of times you want the condition to be evaluated per evaluation of a formula. It must be a positive integer. For example:
//option loop example option loop 256; //make name upper case Local StringVar outString; Local StringVar inString := {Customer.Customer Name}; Local NumberVar I; For i:=1 to Length(inString) do outString := outString + upperCase(inString[i]); outString

If Customer.Customer Name is greater than 255, an error message is shown: A loop was evaluated more than the maximum number of times allowed.

Activity: Using loop control structures


Objective
Use loop control structures to resolve the reporting problem.

Creating Complex FormulasLearners Guide

55

Instructions
The Company wants to make its Customer ID more user-friendly. One proposal is to combine the letters of the customer name to create a new Account Code. 1. Open the CustomerList.rpt. 2. Create a formula that combines the first 15 LETTERS (only) from the customer name in uppercase. 3. If the customer name has less than 15 letters, add Xs until it has 15. For Example, Bike Planet would become BIKEPLANETXXXXX. Hint: Use a loop to check each character in the Customer Name is in range [A to Z]. 4. Save the report as UsingLoops.rpt. Your report should look similar to this:

56

Report Processing StrategiesLearners Guide

Using loop control structures with arrays


Arrays in Crystal Reports are ordered lists of values that are all of the same type. These values are known as the array's elements. The elements of an array can be any simple type or range type. Arrays can be created using square brackets ([ ]). Arrays are most useful when used with variables and can be dynamic. This unit will cover some advanced topics for the use of arrays. After completing this unit, you will be able to: Determine the size of an array Loop through an array

Determining the size of an array


When accessing or manipulating arrays, it is often necessary to know how many elements there are in the array. A function called Ubound helps determine the size.

Ubound
UBound returns a Number containing the largest available subscript for the given array. It is commonly used to obtain the size of an array before using a looping control mechanism to systematically manipulate elements of the array. The following example demonstrates Ubound using Crystal syntax:
Local DateVar Array dateArray; dateArray := [CDate(#12/25/1998#), CDate(#12/24/1999#)]; UBound (dateArray)

This formula returns two, the largest subscript element in the array. This function is designed to work like the Visual Basic function of the same name. Note: Unlike Visual Basic, only one-dimensional arrays are supported in Crystal Reports. Also, array indexes start at one in Crystal Reports and not zero as is the default in Visual Basic. UBound returns one for an un-initialized array variable, however, it causes an error to subscript an un-initialized array variable. The reason for this behavior is that at present Crystal Reports does not support arrays with zero elements. To work around this problem, always initialize your array variables. For example, initialize global array variables in a formula located in the report header and local array variables within the formula itself.

Split
Split takes a string that contains a number of substrings, breaks it up into a specified number of substrings and returns an array containing the substrings. The following examples are applicable to both Basic and Crystal syntax:
Split ("Chocolate Strawberry Pineapple")

Returns an array that contains three elements, "Chocolate", "Strawberry" and "Pineapple".
Split ("Chocolate//Strawberry//Pineapple", "//")

Creating Complex FormulasLearners Guide

57

Returns an array that contains three elements, "Chocolate", "Strawberry" and "Pineapple".

Activity: Determining the size of an array (1 of 2)


Objectives
Extract and display the filename and extension from a full directory path to a file. Extract and display how many directories deep the file is located.

Instructions
1. Open the DynamicArrays.rpt. 2. Use SPLIT and UBOUND functions to extract only the name of the file from the end of the FileName string. 3. Create another formula (use the same variables) which displays how deep in the directory structure the file is located. Tip: The Special field File Path and Name are identical to the formula function called Filename; both include the full path and file name. 4. Save the report as ArrayFunctions.rpt. Your report should look similar to this example, depending on where your setup (that is, the directory and the level of subfolders).

58

Report Processing StrategiesLearners Guide

Activity: Determining the size of an array (2 of 2)


Objective
Determine how many elements are in a parameter array.

Instructions
Display a message for the number of countries via a parameter. 1. Open ParameterArray.rpt. 2. Create a formula to display the number of countries selected. Tip: Use online Help for more information about the IIF function if you are not already familiar with it. 3. Place the formula in the Report Header. 4. Refresh and prompt for new parameter values. 5. Test with only one country and with multiple countries. 6. Save the report as ParameterUBound.rpt. 7. Test with only one country and with multiple countries. The example report below shows results if Australia, New Zealand, Indonesia and Singapore are selected:

Creating Complex FormulasLearners Guide

59

Looping through an array


Each element of an array can be retrieved individually, or by using a function such as the JOIN function, the entire collection can be retrieved. If only a few elements need to be retrieved, then each element needs an individual statement. If the retrieval required a sequential retrieval (for example, every second element), then the task becomes unmanageable. Looping accomplishes this task more efficiently. In this example, the result of a parameter is stored as an array. To retrieve every second element using a For loop the formula is:
numbervar index; stringvar display_region := ""; for index := 1 to count({?Selected Region}) step 2 do ( display_region := display_region + ", " + {?Selected Region}[index] ); mid(display_region,3);

Using this code in a report where you want to extract regions results in this example. Notice the list of regions extracted at the top of the report (AL, AZ, CA, CT).
Note: This report is included as a sample in the course resources.

If the list needs to be reversed (that is, the last element should be displayed as the first item), then manual retrieval is impossible. Again using a loop is the preferred method. The code for the reversal example is:
numbervar index; stringvar display_region := ""; for index := count({?Selected Region}) to 1 step -1 do ( display_region := display_region + ", " + {?Selected Region}[index]

60

Report Processing StrategiesLearners Guide

); mid(display_region,3);

Using this code in a report where you want to extract regions results in this example. Notice the list of regions extracted at the top of the report (DC, CT, CO, CA, BC, AZ, AR, AL).

Activity: Looping through arrays


Objective
Loop through an array calculating sales tax based on location.

Instructions
1. Create a new report including Customer Name, Region, and Last Years Sales. 2. Create a Sales Tax formula two ways: Use the Select Case control structure Use arrays and a loop Here are some sample tax rates (you do not need to do all regions, just a sample): Region Sales Tax Rate: CA - 7.25% IL - 6.25% NJ, PA - 6.00% NY - 8.50%

Creating Complex FormulasLearners Guide

61

Others - assume zero 3. Compare the results and consider the advantages of each. 4. Save the report as Looping in Arrays.rpt. Your report should look similar to this:

Calculate sales tax based on Region and Last Years Sales.

62

Report Processing StrategiesLearners Guide

Quiz: Creating complex formulas


1. What is the difference between For loops and While loops? 2. IsNull is a PrintState function. In what pass are PrintState functions evaluated? 3. You want a formula to return a value based on one piece of data. What advantages does Looping through an array have over the branching control structures (Select Case or If Then Else)? 4. True or False. The UBound function returns the value of the last element in an array. 5. A parameter that accepts multiple discrete values is: a. An array b. A variable c. A range d. A range array

Creating Complex FormulasLearners Guide

63

Lesson summary
After completing this lesson, you are now able to: Use Print State functions Use loop control structures Use loop control structures with arrays

64

Report Processing StrategiesLearners Guide

Lesson 4

Using Custom Functions


Lesson introduction
Custom functions are a means of storing pieces of logic to reuse within a single report or multiple reports. After completing this lesson, you will be able to: Describe a custom function Use custom functions

Using Custom FunctionsLearners Guide

65

Describing a custom function


Custom functions are business logic that you create to perform routine tasks in formulas. After completing this unit, you will be able to: Describe a custom function Describe the work flow for custom functions Describe BusinessObjects Enterprise repository custom functions vs. report custom functions

Custom functions
Custom functions are procedures you create in Crystal Reports to evaluate, make calculations on, or transform data. When you use a custom function in a formula, all the operations in its definition are performed without having to specify them individually in the formula itself. Thus, the custom function provides a way to share and reuse formula logic which, in turn, makes it easier and less time consuming for users to create reports. Custom functions and formulas are alike in structure and are created in a similar interface. But it is important to understand the differences between them. Formulas are typically used to create calculated fields on a report, format text, manipulate strings, or extract part of date fields. Custom functions are business logic that you create to perform routine tasks in formulas. They are used as the basis for a formula but on their own, custom functions do not change the way data appears or is represented on a report. When you use a custom function in a formula, all the operations in its definition are performed without you having to specify them individually in the formula itself. Thus, the custom function provides a way to share and reuse formula logic which, in turn, makes it easier and less time consuming for users to create reports. For example, suppose you are designing a series of reports from a database that stores department information with three-letter code names, but you want the actual department names to appear in your reports. Creating a formula to transform the data would work, but youd have to copy the formula logic from report to report until youd completed the series. It is much easier if you extract the logic that does the data transformation and save it as a custom function. You can add that custom function to each report in your series without having to re-enter the text.
Note: Because custom functions are designed for use across multiple reports, a custom function cannot contain any database fields.

A custom function cannot be placed directly in a report. It must be used as a part of a formula.

Advantages of custom functions


Consider these advantages when deciding if you want to use a custom function:

66

Report Processing StrategiesLearners Guide

Custom functions can replace sections of formula logic common to many different formulas that, in turn, may be used in many different reports. Custom functions can be shared between reports by storing them to the BusinessObjects Enterprise repository and adding them to reports as needed. Custom functions can reduce the need for users to write formulas themselves. You can provide them with the formula logic they need in a custom function. Existing formulas can be converted to custom functions using the Extract Custom Function from the Formula dialog box. Custom functions can have arguments, which makes them flexible. You can define help text and default argument values for custom functions, which makes it easier for users to use them. Custom functions, unlike User Function Libraries (UFLs) to which they are related, are saved as part of the report file (.rpt) and dont have any external dependencies. Custom functions are stateless. The same input always yields the same result. When you modify a custom function, you can update the repository copy and refresh each report without having to find and open the formulas that use the function.

Sample uses of custom functions


Although there are different ways to work with custom functions in Crystal Reports, the following two scenarios are ways in which they might be used: Create a formula based on an existing custom function. Create your own custom function and share this function with other reports.

The work flow for custom functions


Although there are different ways to work with custom functions in Crystal Reports, this sample work flow illustrates how they might be used:

Add a custom function to a report


There are three ways to add a custom function to a report: Select the custom function from the BusinessObjects Enterprise repository and add it to the report. Extract the custom function from an existing report formula using the Extract Custom Function from the Formula dialog box. Create the custom function directly in the Custom Function Editor.

Include a custom function in a report formula


There are two ways to include a custom function in a formula:

Using Custom FunctionsLearners Guide

67

Enter the custom function directly as part of your formula logic in the Formula Editor. Choose a custom function to supply formula logic in the Formula Expert. The custom function you include can be newly created for the report youre working on or added from the BusinessObjects Enterprise repository.

Add a custom function to the repository


Once you create a custom function, it is added to the Report Custom Functions node of the Formula Workshop. At that point, the custom function is available for use in your current report. If, however, you want to use the custom function in other reports, you can share it by adding it to the BusinessObjects Enterprise repository.

Report custom functions vs. repository custom functions


Custom functions are available via the Formula Workshop. In the Formula Workshop there are two nodes under which you will find custom functions; Report Custom Functions and Repository Custom Functions. Custom functions listed under the Report Custom Functions node are available to use and reuse on the open report. Custom functions listed under the Repository Custom Functions node are for use and reuse on all reports. To use custom functions from the Repository Custom Functions node, they must be added to the list of custom functions that the open report has access to. Once custom functions are added to the Report Custom Functions list they are editable and can be changed from one report to another.
Repository Custom Functions Report Custom Functions

Available across multiple reports Cannot be edited

Available in the current report only Are editable

68

Report Processing StrategiesLearners Guide

Using custom functions


Once you understand what custom functions are and how they relate to formulas you are ready to learn how to use them in a report. After completing this unit, you will be able to: Use an existing defined custom function Create custom functions with Crystal syntax Categorize custom functions Save custom functions in the repository Modify a repository custom function

Using an existing custom function


When the BusinessObjects suite is installed, there are a number of sample custom functions that are stored in the repository. In this lesson, you will build formulas based on these custom functions. In order for the sample custom functions to be available for use they must be installed via the Business View Manager. Custom functions can be selected for use in formulas just as youd select any other function. They can be used in any formula in your report, including report formulas, formatting formulas, record selection formulas, and so on. A formula can call any custom function, even if the custom function was written in a different syntax. For example, a Basic syntax formula can call a Crystal syntax custom function. Once a custom function has been created, you can select it from the Custom Functions folder of the Functions Tree in the Formula Editor. Once youve selected a custom function for use in your formula, you must specify the argument values as defined when the custom function was created. For the convenience of users, custom functions can also be used through the Formula Expert. In this expert, the user chooses the custom function on which to base his or her formula and specifies the argument values as prompted for by the expert. You can set default values for users to choose from.

Calling a custom function from within another custom function


Custom functions can be used in formulas, but they can also be used in other custom functions. For example, see the sample custom function cdExpandRegionAbbreviation that ships with Crystal Reports. You can find it in the BusinessObjects Enterprise repository. Note: The syntax of the custom function being called does not depend on the syntax of the custom function doing the calling. For example, a custom function written in Basic syntax can call a custom function written in Crystal syntax.

Using Custom FunctionsLearners Guide

69

Calling a custom function with optional arguments


When calling a custom function with optional arguments, you can omit the optional arguments and the default value is assumed for each optional argument left out. If you omit an optional argument, you must omit all arguments following.

To use a defined custom function


1. On the Report menu, click Formula Workshop. The Formula Workshop opens. 2. Choose a report custom function.

Note: Alternatively, you could select a custom function that is stored in the repository. If you select a repository custom function, that custom function is added to the current report and is added to the Report Custom Function list. If that custom function requires other custom functions from the repository, they can be added as well. 3. Toggle the properties of the function by clicking the Toggle properties button. 4. In the Function Arguments area, specify a value for each argument in the appropriate value field. You can enter constant values directly, or you can select predefined values or report fields from the associated list. 5. Click Save. You can now use this function in a formula just as you would use a function installed with Crystal Reports.

Defining default argument values for custom functions


You can define default argument values for a custom function in the Custom Function Properties dialog box. Users can choose from the default values in the Function Arguments area of the Formula Expert.

70

Report Processing StrategiesLearners Guide

To define default argument values


1. In the Formula Workshop, ensure Toggle properties display is selected on the toolbar. 2. Expand the Report Custom Functions node of the workshop tree view and select the custom function you want to define default argument values for. Note: The custom function must have arguments defined and must be in the report. You cannot define default argument values for custom functions stored only in the repository. As well, the custom function must be disconnected from the repository before you can edit it. 3. Click the Default Values field for the appropriate argument. The name and functionality of the dialog box that appears depends on the argument field youve selected. Note: You cannot create default values for range, array, or range array argument types. 4. Create your set of default values: Click Add to include a new value. Click Remove to delete a value. Click the arrow buttons to arrange the order of the values. Note: The dialog box wont let you add the same value twice. The value you put in the first position becomes the default value for the argument. For arguments that are not optional, this value is used by the Formula Expert if no value is entered or if the Reset Values button is clicked. 5. Click OK when youre done adding default values. The default values are displayed separated by blanks in the Default Values field of the Custom Function Properties dialog box. In the Formula Expert, the default values appear at the top of the list associated with the value field.

Optional values
An optional value can be specified for an argument when you create a custom function.
Note: Optional values are created in the Custom Function Editor and cannot be added through the Custom Function Properties dialog box.

For example, the following formula text provides an optional value of the current date for the function called FirstDayOfMonth:
Function FirstDayOfMonth (Optional dayInMonth As DateTime := CurrentDate) As Date

The advantage of having users select an optional value instead of a default value is that, for an optional value, the value used is not determined until the custom function is executed. The

Using Custom FunctionsLearners Guide

71

value is determined by the custom function itself, so if you change the value in the custom function, all the formulas based on that function change too. In the Formula Expert, optional values are displayed with their current value (the current value may be different at the time the formula is executed). The Formula Expert uses the optional value for an optional argument if no value is entered or if the Reset Values button is clicked.

Activity: Using a Crystal-defined custom function


Objective
Use one of the custom functions installed with Crystal Reports to create a formula that displays the full name of each customers region.

Instructions
1. Open CrystalCustomFunctions.rpt. 2. Browse several pages on the report. Notice that Regions for Canada and USA are abbreviated. 3. Delete the Region field. 4. Open the Formula Workshop. 5. Create a new formula called Region Name. 6. Click the Use Expert button. 7. In the box labeled Custom Function, expand Repository Custom Functions. 8. Under your Enterprise server name Crystal Geographic, select cdExpandRegionAbbreviation. The workshop screen updates. 9. In the Function Arguments area, locate the Value column. Here is where you select inputs for the custom function. 10.For the regionAbbreviation row, click in the Value cell, select Choose Other Field and then select Customer.Region. 11.For the country row, select Customer.Country from the list. 12.Click Save. Crystal Reports prompts you with a message about these changes to this action being undoable. 13.Click Yes. Click Yes again to save the underlying custom functions. These copies are now Report Custom Functions. 14.Close the Formula Workshop. 15.Add the formula to the report. 16.Save the report as FullRegions.rpt. Your report should look similar to this:

72

Report Processing StrategiesLearners Guide

Creating custom functions with Crystal syntax


Crystal syntax custom functions are expression-oriented, like Crystal syntax formulas. You can use either syntax formats listed below.
Function ([argList]) expressions Function ([argList]) ( expressions ) argList

syntax

This optional element of a custom function provides a list of variables representing arguments that are passed into the function when the argument is called. Multiple variables are separated by commas. An empty argList is allowed; however, the parentheses surrounding argList are not optional and must be used even when argList is empty.
[Optional] simpleType [Range] [Array] varName [:=defaultValue]

Optional Optional indicates if the argument can be omitted when the custom function is called. If an argument is optional, all subsequent arguments must be optional as well. If you supply a value for an optional argument when calling the function, then you must supply values for each preceding argument. SimpleType This is required. You can use one of:
NumberVar CurrencyVar

Using Custom FunctionsLearners Guide

73

StringVar BooleanVar DateVar TimeVar DateTimeVar

Range This is optional. It specifies if the argument is a range variable. Note: You cannot use Boolean ranges. Array This is optional. It specifies if the argument is an array variable. varName This is required. This refers to the name of the variable representing the argument. :=defaultValue This is required for optional arguments. DefaultValue is a constant or constant expression; that is, its an expression involving no variables that can be simplified at compile time to a constant value. If an optional argument is omitted when calling a custom function, then the default value for the argument is used. expressions These are required. The value returned by the Crystal syntax custom function is the value of the last expression evaluated in the expression sequence. The syntax is the same as that in Crystal syntax formulas.

Scope
Variable declarations within a custom function are local scope by default. This contrasts with variable declarations in Crystal syntax formulas, where global scope is the default.

Custom function syntax rules


Due to the independent nature of custom functions, there are some limitations: You cannot use report or database fields, including summary fields, in a custom function. You cannot use shared or global variables in a custom function, but you can pass a global or shared variable in as an argument when calling a custom function from within a formula. You cannot use recursion, either direct or indirect, in a custom function. You cannot directly use UFLs in a custom function. You cannot call Evaluation Time, Print State, or Document Properties functions. Also, you cannot use the functions: Rnd, CurrentFieldValue, DefaultAttribute and
GridRowColumnValue.

74

Report Processing StrategiesLearners Guide

These restrictions are designed to make custom functions independent of the report they are being used in.

Variables
You can use local variables and argument variables in custom functions. If you need to use a shared or global variable in your custom function, you can pass it in as an argument.

Evaluation time
Formulas are not evaluated on demand or called (that is, one formula cannot call another formula to do some processing, even through the use of global variables). For example:
Rem Formula PrintSquare Global x As Number x = 5 formula = The square of & CStr(x,0) & is & ToText ({@square, 0) & . Rem Formula Square Global x As Number formula = x * x

Using formula PrintSquare in a report, you get:


The square of 5 is 0.

In this example, formula PrintSquare uses formula Square, so Crystal Reports orders the evaluations. First Square is evaluated and then PrintSquare is evaluated. When Square is evaluated, the value of the global variable x is zero, since that is the value of an uninitialized number variable. In contrast, custom functions are evaluated on demand, or called. This uses a custom function from the previous example:
Rem Formula PrintSquare formula = The square of & CStr (5,0) & is & CStr(cf9Square (5),0) + . Rem Custom Function cf9Square Function cf9Square (x As Number) cf9Square = x * x End Function

Now if you use formula PrintSquare in your report, youll get:


The square of 5 is 25.

Creating custom functions


When creating a new custom function, you can enter its logic directly in the Custom Function Editor, or you can extract the logic from an existing report formula.

Using Custom FunctionsLearners Guide

75

To use the Custom Function Editor


1. In the Formula Workshop, click New and select Custom Function from the list. 2. Enter a name for your custom function in the Custom Function Name dialog box. 3. Click Use Editor. 4. Define your custom function in the Custom Function Editor. Using the Custom Function Editor is like using the Formula Editor to create a report formula. For information on how to use the Formula Editor, see Working with the Formula Editor. For more information on what syntax to use when writing a custom function, see Custom function syntax. Tip: Ctrl+Space will bring up a list of the available functions. If youve already started typing it will bring up a list of keywords that are possible matches for what youve already typed. 5. Check and save your custom function. Once the custom function has been saved, you can modify it or use it in report formulas as needed.

Using the Extract Custom Function from the Formula dialog box
When you extract a custom function from an existing formula, the program copies the formula and replaces its fields with arguments.
Note: A custom function created using the Extractor can only return simple types, like strings and integers. It cannot return arrays. To create a custom function that can return arrays, use the Custom Function Editor.

To extract a custom function from an existing formula


1. In the Formula Workshop, click New and select Custom Function from the list. 2. Enter a name for your custom function in the Custom Function Name dialog box. 3. Click Use Extractor. 4. In the Report Formula list, select the report formula whose logic you want to use in your custom function. Once youve selected a formula, the Return Type, Arguments, and Formula Text fields are completed with information that relates to that formula. These fields cannot be changed without selecting a different formula. The remaining fields are optional. Tip: You will probably want to create meaningful names for the arguments in your custom function. The program assigns generic names (v1, v2, v3, and so on) by default.

76

Report Processing StrategiesLearners Guide

Select Modify formula to use a new custom function to replace the text of the formula you selected in this step with the new custom function youre creating. 5. Click OK to save the custom function to the Report Custom Functions node of the Formula Workshop. Once the custom function has been extracted and saved, you can modify it or use it in report formulas as needed. Note: You cannot add new arguments to your custom function while you are creating it in the Extract Custom Function from Formula dialog box. To add new arguments, save the custom function and modify it in the Custom Function Editor.

Activity: Creating a custom function in the Extractor


Objective
Use the Extractor to create a custom function from a previously created formula.

Instructions
You want a function that accepts a date (or date/time) value and check to see if the date falls on a weekend. If so, change the date to the nearest weekday (that is, Saturday to Friday and Sunday to Monday). 1. Open the report Extractor.rpt from the course resources. 2. Open the formula workshop and display the WeekdayShipped formula. 3. You want to re-use this logic for Required Date using a Report Custom Function. In the workshop tree, click Report Custom Functions. 4. Click the New button, and make sure the box says Custom Function Name. 5. Give the custom function the name Nearest weekday. 6. Click Use Extractor. 7. In the middle of the window, in the first row under Argument Name, change v1 to YourDateValue. 8. Tab to the Description column and enter Date field or expression to be tested for weekend. 9. Click OK. 10.Use the workshop tree to compare your Report Custom Function to the original formula named, @WeekdayShipped. 11.Use your new Custom Function Nearest weekday in the following formula. Create a new formula called WeekdayRequired. 12.In the Formula Editor, from the Toolbar use the Expert button. 13.In the box labeled Custom Function, select Nearest weekday.

Using Custom FunctionsLearners Guide

77

14.In the Function Arguments window under Value, from the list of available choices, select Choose Other Field. 15.Select Required Date from the Choose Field window, and then click OK. 16.Click Save and Close to save the formula and to close the formula workshop. 17.Place the formula WeekdayRequired onto the report. 18.Format the WeekdayRequired field to look like the other two fields on the report. 19.Save the report as NearestWeekday.rpt. Your report should look similar to this:

Categorizing custom functions


Categorizing custom functions groups like custom functions together. Custom functions are grouped under subfolders of the Report Custom Functions list. When saved into the repository this folder structure is duplicated.

To categorize a custom function


1. In the Formula Workshop, select and expand Report Custom Functions. 2. Select the available custom function. If the Custom Function Properties window is not open on the right-hand side, use the Custom Function Properties toggle button to display it. 3. Once in the Custom Function Properties window enter a name in the Category box. 4. Click Save and Close.

78

Report Processing StrategiesLearners Guide

Note: If the Category box is not available, the custom function has been added to the BusinessObjects Enterprise repository and is therefore locked from editing. Right-click the custom function, and then click Disconnect from Repository. After adding a category, you can add the custom function back to the BusinessObjects Enterprise repository.

Saving custom functions in the repository


After creating a custom function and saving it, the custom function is saved as a Report Custom Function and therefore reusable only within the current report. To make custom functions available across multiple reports they must be saved in the BusinessObjects Enterprise repository. Saving the custom function into the repository is not a requirement but an option. With the custom functions created, you can now add them to the repository so they can be used in other reports. This is not a requirement for custom functions, but if you want to reuse them in other reports, it is.
Note: If you are using Crystal Reports without a repository, you can still use custom functions. They will be Report Custom Functions.

To add a custom function to the repository


1. In the Formula Workshop, select and expand Report Custom Functions, and then right-click the available custom function. Note: If you are not logged on to BusinessObjects Enterprise, you are prompted to do so at this point. 2. Click Add to Repository. Now, when you open the Repository Custom Functions list, you see the custom function added to the repository.
Note: If the custom functions have been categorized, these categories also appear under Repository Custom Functions.

Activity: Saving a custom function to the repository


Objective
Categorize and save a custom function to the repository.

Instructions
1. Open NearestWeekday.rpt. 2. Open the Formula Workshop. 3. In the workshop tree, select the NearestWeekday Report Custom Function. 4. Click Toggle Properties Display on the toolbar.

Using Custom FunctionsLearners Guide

79

5. Enter My Date Functions in the Category field. 6. Enter your name in the Author field. 7. Enter a summary describing the function in the appropriate field. 8. Click Save. 9. Click Add to Repository on the toolbar. The function is added to the repository. Notice that all of the fields in Properties cannot be edited now. 10.Click Toggle Properties Display again. Notice that the function cannot be edited. 11.Look at the workshop tree. Notice the icon next to the NearestWeekday custom function has changed. 12.Expand Repository Custom Functions. Notice the folder My Date Functions now contains NearestWeekday. 13.Close the Formula Workshop. 14.Save the report as AddToRepository.rpt. Your report should look similar to the following:

Modifying repository custom functions


Once custom functions are saved in the repository they cannot be edited. To make changes to them they must be disconnected from the repository and then re-saved.
Note: There is no version control for repository objects, so unless you save the custom function with a different name, the modified custom function will overwrite the previously saved one.

80

Report Processing StrategiesLearners Guide

To modify a repository custom function


1. In the Formula Workshop, expand the Report Custom Functions node. Note: If the function doesn't appear in the Report Custom Function list, right-click the function to be edited in the Repository Custom Function list and click Add to Report. 2. From the Report Custom Function list, right-click the custom function to be edited, and select Disconnect from Repository. The custom function is now editable. Note: A version of the custom function remains in the Repository Custom Function list. 3. Edit the custom function and re-save to the repository. Note: If the same custom function name is used, the modified function overwrites the function in the repository.

Refreshing a report's repository custom functions


Once a custom function has been modified and the updated version added to the repository, you can update any report that uses the custom function by opening it in the Report Designer.

To refresh a report's repository custom functions


1. On the File menu, click Options, and then click the Reporting tab. 2. Under Enterprise Settings, ensure Update Connected Repository Objects on Open is selected. 3. Click Open on the Standard toolbar in Crystal Reports and select the report whose custom functions need to be updated. 4. Click Open. The report's custom functions and all other updated repository objects are refreshed as the report opens. Tip: If you don't want to use this global option, you can also update a report's custom functions by selecting the Update Repository Objects option on the Open dialog box for an individual report.

Using Custom FunctionsLearners Guide

81

Activity: Modifying repository custom functions (1 of 3)


Objectives
Modify a custom function that has been saved in the repository. Part 1: Write a custom function with the Formula Editor and use that function in a formula.

Instructions
1. Open AddToRepository.rpt, the report saved at the end of Activity: Saving a custom function to the repository. 2. Open the Formula Workshop. 3. Select Report Custom Functions from the Workshop Tree. 4. Right-click and select New to create a new custom function. 5. Enter ConvertUSDtoEuros in the name box, and then click Use Editor. 6. Enter the function text:
Function (currencyvar AmountUSD) //Accepts US Dollar Amount //Returns value in Euro //Edit here to update exchange rate local numbervar EurosPerDollar:=0.90; AmountUSD * EurosPerDollar

7. Save the function. 8. Create a new formula called OrderAmountinEuro. 9. Open the Expert by clicking the Use Expert button on the toolbar.

82

Report Processing StrategiesLearners Guide

10.In the Custom Function Tree locate Report Custom Functions, and then select ConvertUSDtoEuros. 11.In the Function Arguments window, click the cell under Value. Select the Select Field or Enter Value option, and open the list. 12.In the Field Tree, select Choose Other Field, and then double-click Order Amount. 13.Click Save and Close. 14.Add OrderAmountinEuro to the report. 15.Format the Euro value appropriately. a. Right-click the field, and then click Format Field on the shortcut menu to open the Format Editor. b. On the Number tab, click Custom Style in the Style area (if required), and then click Customize. c. In the Custom Style dialog box, click the Currency Symbol tab. d. Highlight the currency symbol in the Currency Symbol edit field. e. On the number keypad area of your keyboard, press and hold the Alt key, enter 0128, and then release the Alt key. The Euro currency symbol appears. (The combination of numbers is the ASCII code for the Euro symbol and must be generated on the number keypad to appear.) f. Click OK twice. You have just written a custom function with the Formula Editor and used that custom function in a formula. In part 2 of the activity you will add the newly created custom function to the repository and use it on another report.

Activity: Modifying repository custom functions (2 of 3)


Objectives
Modify a custom function that has been saved in the repository. Part 2: Add the ConvertUSDtoEuros custom function to the repository and use it in a formula.

Instructions
1. Re-open the Formula Workshop. 2. Access the properties of the ConvertUSDtoEuros and add a category, author, and summary. 3. Add the function to the repository. Note: You now are unable to edit the function. 4. Close the Formula Workshop. 5. Save the report as ModifyFunction.rpt and then close the report.

Using Custom FunctionsLearners Guide

83

6. Create a new report from the Customer table. In the Details section add the fields: Customer Name Last Year's Sales 7. Create a formula called Sales in Euros. 8. Click the Use Expert button on the toolbar to move to the properties of the formula to select the custom function. 9. From the Repository Functions use the ConvertUSDtoEuros function. 10.Choose Last Year's Sales as the Value field in the Function Arguments. When you save the formula, Crystal Reports copies the function from the repository. 11.Place the formula on the report. Format as needed. 12.Save the report as SalesInEuros.rpt. Your report should look similar to this:

Note: You have used the custom function, ConvertUSDtoEuros, on two reports. In part 3 of the activity, you will update the exchange rate for both reports.

84

Report Processing StrategiesLearners Guide

Activity: Modifying repository custom functions (3 of 3)


Objectives
Modify a custom function that has been saved in the repository. Part 3: Update the exchange rate. You have used the custom function, ConvertUSDtoEuros, on two reports. To update the exchange rate you will disconnect one of the custom functions from the repository, modify it, and then add it back to the repository, overwriting the original.

Instructions
1. Open the Formula Workshop and under Report Custom Functions in the Workshop Tree select the ConvertUSDtoEuros function. 2. Right-click the function and select Disconnect from Repository. 3. Modify the exchange rate variable from 0.90 Euro to 0.70 Euro. 4. Save the formula. 5. Add the function back to the repository. 6. Click OK to the warning about modifying the function. 7. Use the Workshop Tree to confirm that the rate was changed in the repository. 8. Close the Formula Workshop. 9. Save the SalesInEuros.rpt. The report should look similar to this:

Using Custom FunctionsLearners Guide

85

10.Close the SalesInEuros.rpt. 11.Re-open the ModifyFunction.rpt. 12.Under the File menu, click Options, and then click the Reporting tab. 13.Ensure the Update Connected Repository Objects on Open option is selected. OrderAmountinEuro should be updated with the new exchange rate. The report should look similar to this:

14.Save and close the ModifyFunction.rpt.

86

Report Processing StrategiesLearners Guide

Quiz: Using custom functions


1. A custom function is: a. Placed in the report and used to create calculated fields on your report, format text, manipulate strings, or extract part of date fields b. Business logic that you create to perform routine tasks in formulas c. Placed directly in the report and changes how data is displayed 2. List two differences between Repository Custom Functions and Report Custom Functions. 3. Can the manual running total formulas be converted to custom functions? Why? or Why not? 4. Rewrite the following formula so the business logic can be stored as a custom function.
{Customer.Last Year's Sales} * 10

5. True or False. The Extractor is used when creating a formula based on a custom function.

Using Custom FunctionsLearners Guide

87

Lesson summary
After completing this lesson, you are now able to: Describe a custom function Use custom functions

88

Report Processing StrategiesLearners Guide

Lesson 5

Using XML and Web Services Data


Lesson introduction
In Crystal Reports, XML is both a data source and an export format. You can create a report from an XML or Web Service data source turning raw XML or Web Services Description Language (WSDL) data into report information. After completing this lesson, you will be able to: Use XML and web services data Use a transform in XML exporting

Using XML and Web Services DataLearners Guide

89

Using XML and web services data


This unit looks at how to create a report from an XML or web service data source, turning raw XML or Web Services Description Language (WSDL) data into report information. After you complete this unit, you will be able to: Describe the scenarios that XML files and web service data may be used in Describe the data source types available in the XML and Web Services driver

Data source scenarios


At times, you may need to create reports based on data stored locally as XML or stored in a web service environment. These are scenarios where XML files and web service data may be applicable: Scenario 1 Your IT infrastructure contains valuable data stored in a mainframe. It contains valuable information produced by business logic working closely with the data. You are tasked with producing reports on the information but there is no standard data connectivity available to access the information produced by the business logic. You are able to request that XML-format text files be produced containing the information you need. Scenario 2 Valuable information is available in a different part of your organization. You are not able to access the data directly but a web service has been provided, allowing the data to be retrieved. Scenario 3 You are a financial report designer and want to augment your companys sales data with industry standard measures. You have access to an industry sales data web service. Scenario 4 You need to write a report on data from another part of your organization. That group exported their data to XML and put the files on a web server.

Connecting to an XML data source


When you create a new connection in Crystal Reports by selecting the XML and Web Services driver, you can choose from several possible data source types: Local data source HTTP(S) data source Web Service data source

90

Report Processing StrategiesLearners Guide

To choose XML as your data source


1. In Crystal Reports, on the File menu, point to New, and then click Standard Report. 2. On the Report Creation Wizard's Data screen, expand Create New Connection node. 3. Expand the XML and Web Services node. The XML and Web Services dialog box appears.

4. Choose an XML data source access type: Local data source HTTP(S) data source Web Service data source

The XML and Web Services dialog box


In the XML and Web Services dialog box you can specify a connection based on a local XML source, XML data distributed via a virtual directory or HTTP, or establish a connection with a web service.

Using XML and Web Services DataLearners Guide

91

The following options can be selected: Use Local Data Source Select this option to connect to an XML file that you have on a local machine or a network drive. Local XML File Enter a full path and file name for your local data source, or select a file by searching for it in the Open dialog box. Use HTTP(S) Data Source Select this option to connect to an HTTP(S) data source (an XML file or XML stream that you can access from a Servlet, an ASP page, a JSP page, or another type of dynamically created web page). HTTP(S) XML URL Enter either an HTTP or an HTTPS URL for your HTTP(S) data source. When using HTTPS, user IDs and passwords that you enter in Crystal Reports are used to authenticate against the underlying HTTP provider. Specify Schema File Select this option if you want to apply a schema to the XML file you selected. Note: You must select this option and specify a schema unless the XML file contains embedded schema information. Validate XML

92

Report Processing StrategiesLearners Guide

Select this option if you want the XML document validated against the schema, and you have indicated the XML file and schema. Use Web Service Data Source Select this option if you want to use a web service data source. This type of data source can be a service that you have on a local machine or a network drive that you can connect to by entering a path and file name, or it can be a service that you access from a servlet or a dynamically created web page. The URL you provide to such a source can be either HTTP or HTTPS.

Connecting to a local XML data source


A local data source is an XML file on a local machine or a network drive that you can connect to by entering a path and file name. The XML driver lets you type a full path and file name, or you can select a file by searching for it in the Open dialog box. If you have a schema (XSD) for your XML file, you can specify it.

To connect to a local XML data source


1. In the XML and Web Services dialog box, select the Use Local Data Source option. 2. Enter the full path and name of your XML file, or use the button adjacent to the field to search for your file. 3. Choose Specify Schema File to apply a schema to the XML file you selected. You must select this option and specify a schema unless the XML file contains embedded schema information. Note: You define the location and name of your schema on the next screen. 4. Click Next. Depending on your selection in the previous step, you will see either a screen for specifying your schema, or you can click the Finish button. 5. To specify a schema file, choose either Use Local Schema or Use HTTP(S) Schema and complete the adjoining field. For Use Local Schema, enter the full path and name of your schema file (XSD), or use the button adjacent to the field to search for it. For Use HTTP(S) Schema, enter the URL that points to your schema file (XSD). 6. Click Next, and then click Finish.

Connecting to an HTTP(S) data source


An HTTP(S) data source is an XML file or XML stream that you can access from a Servlet, an ASP page, a JSP page, or another type of dynamically created web page. The URL you provide

Using XML and Web Services DataLearners Guide

93

to such a data source can be either HTTP or HTTPS. When using HTTPS, user IDs and passwords that you enter in Crystal Reports are used to authenticate against the underlying HTTP provider. The XML driver lets you type a URL and later add authentication credentials. If you have a schema (XSD) for your XML file or stream, you can specify the schema and its authentication credentials.
Note: When you use the XML driver, you can specify a schema (XSD) or Document Type Definition (DTD) of your choice, or you can use schema information embedded in the XML document. The schema is used to determine how to present the XML data within Crystal Reports. When you specify a schema to use with your XML file, the specified schema is used instead of schema information embedded in or referenced by the XML file itself.

To connect to an HTTP(S) data source


1. In the XML and Web Services dialog box, select the Use HTTP(S) Data Source option. 2. Enter the URL that points to your XML file. You can use HTTP or HTTPS to define your URL. 3. Choose Specify Schema File to apply a schema to the XML file you selected. You must select this option and specify a schema unless the XML file contains embedded schema information. Note: You define the location and name of your schema on the next screen. 4. Choose Validate XML if you want the XML document validated against the schema. Validation can only occur if both the XML instance and the schema are both specified. 5. Click Next. 6. Enter authentication information if it is needed, and then click Next again. Depending on your selection in step 2, you will see either a screen for specifying your schema, or a screen for defining HTTP parameters. If you see the HTTP Parameters screen, skip to step 8. 7. To specify a schema file, choose either Use Local Schema or Use HTTP(S) Schema and complete the adjoining field. For Use Local Schema, enter the full path and name of your schema file (XSD), or use the button adjacent to the field to search for it. For Use HTTP(S) Schema, enter the URL that points to your schema file (XSD). 8. On the HTTP Parameters screen, create parameters that can be added to your URL to limit the results that are returned in your XML file. Click Add Property to define a new value. The Edit Property Value dialog box appears. Use this dialog box to define a parameter name and a formula.

94

Report Processing StrategiesLearners Guide

Click Edit Value to change an existing parameter. Select the parameter you want to edit before you click this button. Click Remove Property to delete an existing parameter. Select the parameter you want to remove before you click this button. 9. Click Finish when you are done with the HTTP Parameters screen.

Activity: Connecting to an XML data source


Objectives
Create a connection to a local XML file Create a report based the XML data

Instructions
1. Use the Customer.xml and the Customer.xsd files located in the course resources. 2. Create a new XML local data source connection that points to the Customer.xml file and the Customer schema file. 3. Create a new report that displays the Customer Name, City, and Region fields. 4. Format the report.

Connecting to a web service data source


A web service data source can be a service on a local network or the Internet that returns an XML data set. Crystal Reports supports web services that communicate using SOAP. The URL you provide to such a source can be either HTTP or HTTPS. The schema for the response XML file is derived through the web services framework rather than specified manually. Web service data source interfaces are described using WSDL (Web Services Description Language), which is the standard format for describing a web service. After you specify a path to the WSDL, the driver lets you select which Service, Port, and Method you want to use. You may also have to enter authentication user ID and password. Web services may be secured using the WS-Security Web Service standard. The XML driver supports this standard by allowing a security credentials policy file to be used to specify the security information required to access the web service.

To connect to a web service data source


1. In the XML and Web Services dialog box, select the Use Web Service Data Source option, and click Next to continue. 2. To specify a web services file location, choose either Use Local WSDL or Use HTTP(S) WSDL and complete the adjoining field.

Using XML and Web Services DataLearners Guide

95

For Use Local WSDL, enter the full path and name of your web services file, or use the button adjacent to the field to search for it. For Use HTTP(S) WSDL, enter the URL that points to your web services file. If you are connecting to a Web Service secured using WS-Security, specify the policy file in this step as well. 3. Click Next. Depending on your selection in the previous step, you will see either a screen for specifying your web service, ports, and methods, or a screen for defining authentication for your web service URL. If you see the web service, ports, and methods screen, skip to step 6. 4. Enter authentication information if it is needed, and then click Next. 5. On the Web Service, Port and Method screen, choose a service, a port, and a method from the lists. 6. Click Finish. Once you can see the table created from your XML data source, you can use it to create a Crystal report in the same way you use any other data source.

Activity: Creating a report using a web service


Objective
Create a report using a web service.

Instructions
1. Launch Query as a Web Service and create a new query based on the eFashion universe. a. Click Start Programs BusinessObjects BusinessObjects Enterprise Query As A Web Service. b. In the Manage Hosts dialog box, click Add. c. In the Edit a Host dialog box, enter the appropriate information such as the name of the host machine, the URL of the host, the name of the CMS, your logon credentials, and authentication, if required, and then click OK. d. Close the Manage Hosts dialog box. e. In the Select your credentials window, enter the appropriate information such as the host machine, the name of the CMS, your logon credentials, and a password, if required, and then click OK. f. In the Query as a Web Service dialog box, select the appropriate folder (if required), and then click New Query. g. In the Web Service Name edit field of the Publish Query As A Web Service Wizard dialog box, enter a name for the query, and then click Next. h. In the Select a universe window, click the eFashion universe, and then click Next. i. Expand the Store class and add State, City, and Store name to the query.

96

Report Processing StrategiesLearners Guide

j. Click Next, and then click Publish. k. Copy the WSDL URL to the Clipboard. l. Minimize or close the Query As A Web Service dialog box. 2. Create a new report from an XML and Web Services connection. a. Select the Use Web Service Data Source option and then click Next. b. Select Use HTTP(S) WDSL, paste the WDSL URL in the field, and then click Next. c. Enter your WSDL user ID and password and then click Next. d. Ensure the service, port, and method areas contain the correct information: Web Service: Query name Port: QueryAsAServiceSoap Method: runQueryAsAService e. Click Finish. f. Expand the runQueryAsAServiceResponse node. g. Select runQueryAsAServiceResponse/Table/Row and add to the Selected Tables area. h. In the parameters.runQueryAsAService.login area, enter your login name in the Enter a Value field. i. In the parameters.runQueryAsAService.password area, enter your password in the Enter a Value field, and then click OK. 3. Expand Database Fields in the Field Explorer. 4. Expand the runQueryAsAServiceResponse/table/row query result node and add the State, City, and Store name fields to the report. 5. Format the report, if desired. 6. Preview the report. 7. Save the report as Creating a report using a web service.rpt. Your report should look similar to this example.

Using XML and Web Services DataLearners Guide

97

98

Report Processing StrategiesLearners Guide

Using a transform in XML reporting


You can export a Crystal report to an XML format by using XSLT transforms to render reports in almost any industry standard format. After you complete this unit, you will be able to: Define a transform Use a transform when exporting an XML report

Exporting XML reports with transforms


You can create XML data from your Crystal reports using Crystal Reports XML export. With this data, you can apply a style sheet or import it into another application. Because you can import your own schemas, you can specify any XML, HTML or other file format you need. If you do not have a specific XML schema you want to use to format your report, or if you want to perform transformations after exporting the report, you can use the built-in Crystal Reports XML schema, then transform the exported file. Crystal Reports can render reports in almost any industry-standard format. Exporting to XML using XSLT transforms allows for faster and easier integration with your industry-specific business processes, without custom coding. The XSLT transformations are embedded into the report file and will be triggered by the report viewers when exporting to XML. XML exports can also be invoked from within the report viewers. This feature provides a powerful, flexible hook for transforming Crystal Reports data and integrating it into other applications.

Importing an XML transform


If the schema provided with Crystal Reports does not meet your needs for the exported XML format, you can import an XML transform to produce XML in a different schema or create a different file type altogether. In this case you can use the XML Export Format Manager to import your XSLT into the report and optionally set it as the default schema for formatting the report during XML export. When exporting to custom XML formats, Crystal Reports first generates a Crystal Reports XML format file then applies your transform to it before providing the final results.

To import an XML transform


1. On the File menu, point to Export, and then click Manage XML Exporting Formats. The Manage XML Exporting Formats dialog box opens. 2. In the Manage XML Exporting Formats dialog box, click Add. The Add a New XML Format dialog box opens. 3. Type a name for your format.

Using XML and Web Services DataLearners Guide

99

This is the name that appears in the Manage XML Exporting Formats dialog box when you choose an XML format for exporting a report. 4. Click Import XML Transform to open the Open dialog box. 5. Browse through the folders to find a valid transformation and select it. 6. Indicate the extension for the exported report in the Specify the file type text field. Note: This only affects the extension of the file name. Changing the extension does not affect the file format. 7. Enter a description for the new format. This description appears in the Manage XML Exporting Formats dialog box when you choose an XML format for exporting a report. 8. Click OK twice. 9. Once the schema is imported click Save XML Transform As to save a copy of the transform to another location.

Exporting to XML format


In Crystal Reports, XML is both a data source and an export format. You can create a Crystal report from an XML data source, thus turning raw XML data into report information. When exporting a report, you can use the Crystal Reports XML schema built in to Crystal Reports, or create new XML-based export formats by embedding XSLT transforms into your report.

To export a report to XML


1. Open the report you want to export. 2. On the File menu, click Export Export Report. Tip: Another way to do this is to click the Export button on the Standard toolbar. The Export dialog box appears. 3. Select the export format type from the Format list. In this case, choose XML as the export format. 4. Select the destination. If you are exporting to an application, the appropriate type of application for the format's file type is shown. The Choose export file dialog box appears if you are exporting to a file. 5. Click OK. The XML Export Options menu opens. This menu allows you to select the Crystal Reports XML (default) format or any added transformation (XSLT). 6. Choose the XML exporting format and click OK.

100

Report Processing StrategiesLearners Guide

The report is exported to the directory you selected. Depending on the Export Option chosen, the exported report can now be accessed as raw XML data or as transformed XML.

Activity: Exporting to XML using a transform


Objectives
Import an XML transform (XSLT) Export a report to standard Crystal Reports XML format Export a report to XML using the imported transform

Instructions
1. Import the Justice XML Data Model (JXDM) transform. 2. Select the jxdm.xsl file. In the Name field enter Justice Data Submission. In the Description field enter Justice data format. 3. Open offenses.rpt. 4. Export the data displayed in the sample offenses.rpt report to the standard Crystal Reports XML format. 5. Select Application as the destination. The exported report output is shown using the standard Crystal Reports XML format. 6. Close the XML output file and export the data displayed in the sample offenses.rpt to XML format, using the Justice Data Submission transform to conform the data to the Justice XML Data Model format. 7. Select Application as the destination. The offenses.rpt report has been exported to XML format, using the Justice Data Submission transform to conform the data to the Justice XML Data Model format. Note that the XML elements now show customized tags such as Offense, IncidentSubject, and PersonName, instead of GroupHeader, Section SectionNumber, and Field Name as seen with the standard XML format.

Using XML and Web Services DataLearners Guide

101

Quiz: Using XML and Web Services Data


1. True or False. Crystal Reports requires that you have an XML schema to export to XML. 2. True or False. You can use web services to directly access a database located on a remote system. 3. True or False. For HTTP / HTTPS data sources the XML driver lets you select a file by searching for it in the Open dialog box. 4. Which of the following are valid scenarios for using XML or web services? a. An XML data file is made available on a web server for remote user access. b. When you need to report on data stored on a remote system you can use web services to bypass the need for having access rights to the remote system. c. Whn reporting on information stored in a mainframe without standard data connectivity that can provide XML text files.

102

Report Processing StrategiesLearners Guide

Lesson summary
After completing this lesson, you are now able to: Use XML and web services data Use a transform in XML exporting

Using XML and Web Services DataLearners Guide

103

104

Report Processing StrategiesLearners Guide

Answer Key
This section contains the answers to the reviews and/or activities for the applicable lessons.

Answer KeyLearners Guide

105

106

Report Processing StrategiesLearners Guide

Quiz: Report processing


Page 16
1. Why is understanding the multi-pass report processing architecture important? Answer: Multi-pass report processing architecture is important to help you make processing optimized report design decisions. 2. What are some common uses of evaluation time functions? Answer: Manual Running Totals, Dynamic Arrays 3. Which evaluation time function does not correspond to one of the passes? Answer: EvaluateAfter 4. Which evaluation time function should be used when a formula contains global variables? Answer: WhilePrintingRecords 5. What happens in pre-pass 2? Answer: During pre-pass 2, Crystal Reports orders the groups in the report for Top/Bottom N and for hierarchical grouping. 6. When working with Manual Running Totals, why is placement of the formulas on the report so important? Answer: Placement of these formulas allows you to separate evaluation and display of the running total. 7. What is page on-demand and what role does it have in the multi-pass process? Answer: Page on-demand only generates pages for display as needed. It occurs at the end of pass 2 and for reports without Total Page Count, eliminates the need for pass 3.

Answer KeyLearners Guide

107

Activity: Defining subreports


Page 23
1. Linked subreports are subreports with coordinated data. 2. With on-demand subreports, the actual data is not read from the database until the user drills down on the hyperlink. 3. Unlinked subreports are free-standing reports; the data is not in any way coordinated with the data of the primary report.

108

Report Processing StrategiesLearners Guide

Quiz: Using subreports


Page 46
1. In which sections of the main report are subreports generally placed? Answer: Report Header, Group Header, Group Footer, Report Footer; NOT Detail 2. When a subreport is modified (edited), how does this affect the original report (not main report) on which the subreport was based? Answer: The original report is not affected. 3. When do on-demand subreports actually run? Answer: On-demand subreports run when the user clicks the hyperlink. 4. When do subreports (not on-demand) refresh? Answer: Subreports are refreshed when the main report is refreshed. 5. True or False. On-demand subreports can be linked or unlinked. Answer: True 6. In what ways can data be passed from one report to another? Answer: Data can be passed from one report to another by a linked subreport with parameter and a linked subreport with shared variable. 7. Can subreports have subreports themselves? Answer: No 8. List some applications of subreports. Answer: You can combine otherwise unrelated reports into one report, present multiple views of the same data in one report, and link data that might not be otherwise linkable. 9. Why is placement of a linked subreport important? Answer: Placement affects what data the subreport returns. 10.When you right-click on a subreport, Crystal Reports displays a menu. What is the difference between the menu options Edit Subreport and Format Subreport? Answer: Edit Subreport displays the Design View tab of the subreport object, while Format Subreport displays the tabbed dialog box for changing the appearance of the subreport. 11.Where should a shared variable initially be declared? Answer: Either in the main report or subreport, depending on its purpose. 12.What might cause a subreport to display no data? Answer: The subreport has a record selection formula that is filtering out records that should be on the report.

Answer KeyLearners Guide

109

Quiz: Creating complex formulas


Page 63
1. What is the difference between For loops and While loops? Answer: For loops are executed a specific number of times; While loops are executed repeatedly until a condition (Boolean statement) is false. 2. IsNull is a PrintState function. In what pass are PrintState functions evaluated? Answer: Pass 2--WhilePrintingRecords. 3. You want a formula to return a value based on one piece of data. What advantages does Looping through an array have over the branching control structures (Select Case or If Then Else)? Answer: Looping through an array is easier to update (no need to add Else If or Case clauses; add to the array). Arrays can be set up as global variables and reused in other formulas. 4. True or False. The UBound function returns the value of the last element in an array. Answer: False. It returns the subscript (or index) of the last element in the array, usually the same as the number of elements in the array. 5. A parameter that accepts multiple discrete values is: Answer: a. An array

110

Report Processing StrategiesLearners Guide

Quiz: Using custom functions


Page 87
1. A custom function is: Answer: b. Business logic that you create to perform routine tasks in formulas 2. List two differences between Repository Custom Functions and Report Custom Functions. Answer:
Repository Custom Functions Report Custom Functions

Available across multiple reports Cannot be edited

Available in the current report only Are editable

3. Can the manual running total formulas be converted to custom functions? Why? or Why not? Answer: No, the manual running total uses both Print State functions and global variables, neither of which are permitted in custom functions. 4. Rewrite the following formula so the business logic can be stored as a custom function.
{Customer.Last Year's Sales} * 10

Answer:
Function (currencyVar v1) v1 * 10

5. True or False. The Extractor is used when creating a formula based on a custom function. Answer: False. It is the opposite. When you are creating a custom function and already have a formula which performs the business logic you want to store for reuse, the Extractor is used. The Extractor logic extracts the logic from the formula.

Answer KeyLearners Guide

111

Quiz: Using XML and Web Services Data


Page 102
1. True or False. Crystal Reports requires that you have an XML schema to export to XML. Answer: False. In Crystal Reports, you can export to XML without using an XML schema. 2. True or False. You can use web services to directly access a database located on a remote system. Answer: False. You are not able to access the data directly, but a web service can be provided allowing the data to be retrieved via that service. 3. True or False. For HTTP / HTTPS data sources the XML driver lets you select a file by searching for it in the Open dialog box. Answer: False. This option requires you to insert a URL to the file you want to import. 4. Which of the following are valid scenarios for using XML or web services? Answers: a. An XML data file is made available on a web server for remote user access. c. Whn reporting on information stored in a mainframe without standard data connectivity that can provide XML text files.

112

Report Processing StrategiesLearners Guide

Potrebbero piacerti anche