boc330 en col91 fv part ltr

124
Crystal Reports 2008: Report Design III - Report Processing Strategies Learner’s Guide BOC330

Upload: amondaca

Post on 27-Oct-2014

276 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Boc330 en Col91 Fv Part Ltr

Crystal Reports 2008: Report Design III -Report Processing Strategies

Learner’s GuideBOC330

Page 2: Boc330 en Col91 Fv Part Ltr

Copyright© 2009 SAP® BusinessObjects™. All rights reserved. SAPBusinessObjects owns the followingUnited States patents,whichmay cover products that are offered and licensed by SAPBusinessObjects 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. SAPBusinessObjects and its logos, BusinessObjects, Crystal Reports®,Rapid Mart™, Data Insight™, Desktop Intelligence™, RapidMarts®, Watchlist Security™, Web Intelligence®, and Xcelsius®are trademarks or registered trademarks of Business Objects,an SAP company and/or affiliated companies in the UnitedStates and/or other countries. SAP® is a registered trademarkof SAPAG inGermany and/or other countries. All other namesmentioned hereinmay be trademarks of their respective owners.

Page 3: Boc330 en Col91 Fv Part Ltr

C O N T E N T S

About this CourseCourse introduction.....................................................................................................ixCourse description.........................................................................................................xCourse audience.............................................................................................................xPrerequisites...................................................................................................................xLevel, delivery, and duration.......................................................................................xApplicable certifications and designations................................................................xCourse success factors..................................................................................................xiCourse setup..................................................................................................................xiCourse materials...........................................................................................................xiLearning process..........................................................................................................xii

Lesson 1Report ProcessingLesson introduction.......................................................................................................1Multi-pass reporting......................................................................................................2

The Report Processing Model ..............................................................................2What is processed in pre-pass 1...........................................................................3Pass 1 processing....................................................................................................4Pre-pass 2 processing.............................................................................................4Pass 2 processing....................................................................................................5Pass 3 processing....................................................................................................5Activity: Sorting and totaling in the multi-pass process..................................6

Applying evaluation time functions...........................................................................9Evaluating time functions.....................................................................................9Using evaluation time functions .........................................................................9Creating a manual running total........................................................................10Activity: Using evaluation time functions........................................................11

Using a dynamic array................................................................................................13Static vs. dynamic arrays.....................................................................................13Creating a dynamic array....................................................................................13Activity: Creating an array dynamically..........................................................14

Quiz: Report processing..............................................................................................16Lesson summary..........................................................................................................17

iiiTable of Contents—Learner’s Guide

Page 4: Boc330 en Col91 Fv Part Ltr

Lesson 2Using SubreportsLesson introduction.....................................................................................................19Defining subreports.....................................................................................................20

Subreports.............................................................................................................20Identifying typical uses for subreports.............................................................20Processing considerations for subreports.........................................................21Comparing linked vs. unlinked subreports.....................................................22How subreport linking works............................................................................22On-demand subreports.......................................................................................23Activity: Defining subreports.............................................................................23

Creating an unlinked subreport................................................................................24Using a pre-existing report as a subreport.......................................................24Using the Report Wizard to create a subreport...............................................25Activity: Using the Report Wizard to create a subreport...............................26Modifying a subreport.........................................................................................27Activity: Modifying a subreport........................................................................30

Creating a linked subreport.......................................................................................32Creating links to subreports ..............................................................................32Activity: Creating a linked subreport................................................................34

Creating on-demand subreports................................................................................36Creating an on-demand subreport ...................................................................36Adding captions to subreports...........................................................................37Activity: Creating on-demand subreports........................................................38

Using shared variables with subreports...................................................................41Using shared variables with a subreport .........................................................41Activity: Using shared variables with subreports...........................................42

Linking unlinkable data..............................................................................................43Linking unlinkable data with subreports.........................................................43Creating links to unlinkable data.......................................................................43Activity: Linking unlinkable data with subreports.........................................44

Quiz: Using subreports...............................................................................................46Lesson summary..........................................................................................................47

Lesson 3Creating Complex FormulasLesson introduction ....................................................................................................49Using Print State functions.........................................................................................50

Defining Print State functions............................................................................50Activity: Using Print State functions.................................................................51

Using loop control structures.....................................................................................53Defining control structures.................................................................................53Loop control structures ......................................................................................53

Report Processing Strategies—Learner’s Guideiv

Page 5: Boc330 en Col91 Fv Part Ltr

Activity: Using loop control structures.............................................................55Using loop control structures with arrays...............................................................57

Determining the size of an array........................................................................57Activity: Determining the size of an array (1)..................................................58Activity: Determining the size of an array (2)..................................................59Looping through an array...................................................................................60Activity: Looping through arrays......................................................................61

Quiz: Creating complex formulas.............................................................................63Lesson summary..........................................................................................................64

Lesson 4Using Custom FunctionsLesson introduction.....................................................................................................65Describing a custom function....................................................................................66

Custom functions.................................................................................................66Advantages of custom functions .......................................................................66Sample uses of custom functions ......................................................................67The work flow for custom functions ................................................................67Report custom functions vs. repository custom functions ............................68

Using custom functions..............................................................................................69Using an existing custom function....................................................................69Defining default argument values for custom functions...............................70Optional values.....................................................................................................71Activity: Using a Crystal-defined custom function.........................................72Creating custom functions with Crystal syntax..............................................73Custom function syntax rules.............................................................................74Evaluation time.....................................................................................................75Creating custom functions..................................................................................75Using the Extract Custom Function from the Formula dialog box ..............76Activity: Creating a custom function in the Extractor....................................77Categorizing custom functions..........................................................................78Saving custom functions in the repository.......................................................79Activity: Saving a custom function in the BusinessObjects EnterpriseRepository.............................................................................................................79Modifying repository custom functions...........................................................80Refreshing a report's repository custom functions.........................................81Activity: Modifying repository custom functions (1).....................................82Activity: Modifying repository custom functions (2).....................................83Activity: Modifying repository custom functions (3).....................................85

Quiz: Using custom functions....................................................................................87Lesson summary..........................................................................................................88

vTable of Contents—Learner’s Guide

Page 6: Boc330 en Col91 Fv Part Ltr

Lesson 5Using XML and Web Services DataLesson introduction.....................................................................................................89Using XML and web services data............................................................................90

Data source scenarios .........................................................................................90Connecting to an XML data source...................................................................90The XML and Web Services dialog box ...........................................................91Connecting to a local XML data source ...........................................................93Connecting to an HTTP(S) data source ............................................................93Activity: Connecting to an XML data source...................................................95Connecting to a web service data source..........................................................95Activity: Creating a report using a web service...............................................96

Using a transform in XML reporting........................................................................99Exporting XML reports with transforms..........................................................99Importing an XML transform.............................................................................99Exporting to XML format .................................................................................100Activity: Exporting to XML format.................................................................101

Quiz: Using XML and Web Services Data .............................................................102Lesson summary........................................................................................................103

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

Report Processing Strategies—Learner’s Guidevi

Page 7: Boc330 en Col91 Fv Part Ltr

A G E N D AReport Processing Strategies

Introductions, Course Overview...........................................30 minutes

Lesson 1Report Processing........................................................................1.5 hours❒ Multi-pass reporting❒ Applying evaluation time functions❒ Using a dynamic array

Lesson 2Using 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 3Creating Complex Formulas.....................................................1.5 hours❒ Using Print State functions❒ Using loop control structures❒ Using loop control structures with arrays

Lesson 4Using Custom Functions.................................................................1 hour❒ Describing a custom function❒ Using custom functions

Lesson 5Using XML and Web Services Data.....................................45 minutes❒ Using XML and web services data❒ Using a transform in XML reporting

viiAgenda—Learner’s Guide

Page 8: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guideviii

Page 9: Boc330 en Col91 Fv Part Ltr

About this Course

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

ixAbout this Course—Learner’s Guide

Page 10: Boc330 en Col91 Fv Part Ltr

Course descriptionCrystal Reports 2008® is a powerful, dynamic, actionable reporting solution that helps youdesign, explore, visualize, and deliver reports via the web or embedded in enterpriseapplications. This one-day instructor-led course is designed to give you comprehensive skillsand in-depth knowledge required to plan and create reports that will help you analyze andinterpret 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 designdecisions and create more efficient reports.

Course audience

The Report Processing Strategies course builds on knowledge and skills acquired thoughexperience using Crystal Reports or from previous courses.

Prerequisites

To be successful, learnerswho 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 Reportscertification.

Report Processing Strategies—Learner’s Guidex

Page 11: Boc330 en Col91 Fv Part Ltr

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• Learner’s Guide

The Learner’s Guide contains an agenda, learner materials, and practice activities.

The Learner’s Guide is designed to assist students who attend the classroom-based courseand 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 ourevaluation process. Provide feedback on the course content, instructor, and facility. Yourcomments will assist us to improve future courses.

xiAbout this Course—Learner’s Guide

Page 12: Boc330 en Col91 Fv Part Ltr

Additional resources include:• Sample files

The sample files can include required files for the course activities and/or supplementalcontent to the training guide.

• OnlineHelp

Retrieve information and find answers to questions using the onlineHelp and/or user’sguide that are included with the product.

Learning process

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

Introduction

Why am I here? What’s 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 theactivities.

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.

Report Processing Strategies—Learner’s Guidexii

Page 13: Boc330 en Col91 Fv Part Ltr

Lesson 1Report Processing

Lesson introductionUnderstanding how reports are processed by Crystal Reports will help you optimize yourreports for efficient processing.

After completing this lesson, you will be able to:

• Describe multi-pass reporting• Use evaluation time functions• Use a dynamic array

1Report Processing—Learner’s Guide

Page 14: Boc330 en Col91 Fv Part Ltr

Multi-pass reportingCrystal Reports uses a three-pass reporting method to generate reports. In this unit you willlearn 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 toas multi-pass processing or the Report Processing Model. A pass is a process that CrystalReports 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 andthe more complex ones later.

Depending on the complexity of the report Crystal Reportsmaymake one, two, or three passesover the data. This feature allows for complex reporting and formula manipulation.

Report Processing Strategies—Learner’s Guide2

Page 15: Boc330 en Col91 Fv Part Ltr

Crystal Reports processes a report top to bottom and left to right. Formulas placed in the topleft of the Report Header process first and those placed in the lower right of the Report Footerprocess last.

Understanding the Report Processing Model is important as it helps you make report designdecisions that optimize processing.

The Performance Information dialog box on the Reportmenu provides you with informationabout 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 Informationmenu 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. Constantformulas are those that have a constant value for the entire report. They do not change fromrecord to record. For example, 100*30 is a constant formula.

Constant formulas are evaluated at the beginning of the print generation process and are neverevaluated again. This process is known as BeforeReadingRecords. If you place a constantformula field (that is, 100*30) in theDetails section, the result would be 3000 for each recorddisplayed.

3Report Processing—Learner’s Guide

Page 16: Boc330 en Col91 Fv Part Ltr

If no database or group field is included in the formula, the formula is evaluated before theprogram 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 tosubtotals or summary information. This evaluation time is known as WhileReadingRecords.Formulas that contain references to subtotals or summary information are processed in thesecond pass.

• Application of the record selection locally

If the record selection is too complex to be pushed down to the database, Crystal Reportsapplies it in this step.

Referencing the SQL query generated by Crystal Reports indicates whether the recordselection formula has been pushed down to the database or if additional selection needs tobe made once records are retrieved.

• Sorting, grouping, and totaling

In this step, Crystal Reports sorts the records, separates them into groups, and then calculatesthe subtotals and summaries needed for each group.

• Crosstab, chart, and map generationOnly crosstabs, charts, and maps that are based entirely on database fields and recurringformulas are generated in pass 1.

If these objects include running totals and/or PrintTime formulas, they are generated inpass 2.

• Storage of saved data

After the totaling process is complete, all of the records and totals are stored inmemory andto temporary files. Unless the report is refreshed, Crystal Reports does not read the databaseagain, 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, orhierarchical grouping. The records are not read in this process, instead Crystal Reports onlylooks at group instances from pass 1, and takes the Top N as appropriate, or orders the groupsbased on the hierarchical grouping settings specified.

Report Processing Strategies—Learner’s Guide4

Page 17: Boc330 en Col91 Fv Part Ltr

Pass 2 processing

Crystal Reports enters the secondpass through the data to format pages. The pages are formattedon demand. This means that Crystal Reports does not format a page until it is requested by theuser, 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 knownas 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, andcharts 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 isimportant to keep in mind when adding subreports to your reports as each subreport addsprocessing 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/orprinting when the user requests it.

Subtotals, grand totals, and summaries may appear to be incorrect if the report has a groupselection formula. This occurs because the grand totals and summaries are calculated duringpass 1, but the group selection formula filters the data again in pass 2. Running total fields canbe 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 subreportsto ensure that your main report remains a single-pass report. With on-demand subreports, CrystalReports must still make a second pass through the data; however, this second pass does not beginuntil you drill down on the subreport. Consequently, you can increase the performance of reportsthat 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 usethe total page count, or Page N of M special fields.

5Report Processing—Learner’s Guide

Page 18: Boc330 en Col91 Fv Part Ltr

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 Year’s Sales. Label the grand total asGrand 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 onelabeled Running Total equals $830,862.92, which is a difference of $19,767.71.

Report Processing Strategies—Learner’s Guide6

Page 19: Boc330 en Col91 Fv Part Ltr

Why are they different?

Your report should look similar to this:

8. Remove theTopN sort and create a group selection formula that only includes those groupswhose 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 onelabeled 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:

7Report Processing—Learner’s Guide

Page 20: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guide8

Page 21: Boc330 en Col91 Fv Part Ltr

Applying evaluation time functionsEvaluation time functions can control howdata is presented by controllingwhen it is calculatedor 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 howmuch information the formula needs. However, there may be times when you want to guideCrystal Reports as to when your formulas will be processed. Evaluation time functions can beused for this purpose.

Typically, evaluation time functions are the first line of a formula so the entire formula isevaluated at the appointed time.

There are four evaluation time functions. Three of themmatch with pre-passes or passes fromthe 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. Theformula is evaluated before the program reads database records. When this function is usedin a formula, the Formula Checker returns an errormessage if you attempt to include elementsin the formula (database fields, groups, and so on) that must be evaluated at a later time (whilereading or while printing records).

WhileReadingRecords

WhileReadingRecords forces the formula to be evaluated while the program reads databaserecords. This happens during Pass 1.

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

9Report Processing—Learner’s Guide

Page 22: Boc330 en Col91 Fv Part Ltr

WhilePrintingRecords

WhilePrintingRecords forces the formula to be evaluated while the program prints databaserecords. This happens during Pass 2.

This function can also force a formula that includes no database fields and no group fields toprocess while printing records instead of before reading records. It also forces a formula thatincludes 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 separateformulas in your report may have the same evaluation time (BeforeReadingRecords,WhileReadingRecords, or WhilePrintingRecords), or they appear in the same section of thereport and, therefore, are automatically evaluated while records are printing. In such cases, itis often unclear which formula is evaluated first.

In many situations, it is irrelevant which formula is evaluated first. However, some situationsmay require that one formula be evaluated after another. For instance, one formula may setthe value of a variable while the other formula reads the value of that variable. TheEvaluateAfter function can be used to force the second formula to be evaluated after the firstformula has completed.

Creating a manual running total

One common use of evaluation time functions is employing a manual running total. Manualrunning totals accomplish the same result as the running total expert but offer more flexibilitybecause of the ability to add more conditions to the running total.

Manual running totals are created using three formulas. Where you place these formulasdetermines 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 typicallyplaced in a headers section, such as, Page Header, Report Header, or Group Header. WhilePrintingRecords; Global NumberVar nRT := 0;

Report Processing Strategies—Learner’s Guide10

Page 23: Boc330 en Col91 Fv Part Ltr

Evaluate

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

Display

The Display formula shows the current value of the variable on the report. This formula istypically 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 formula’s 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 Year’s Sales. Formula Name: Evaluate. Global Currencyvar salesRT:= salesRT + {Customer.Last Year’s Sales}

5. Insert @Evaluate in theDetails section beside Last Year’s 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 formulain the Report Footer. Are they the same? Why? Why not?

10.Add theWhilePrintingRecords 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 formulain the Report Footer. Are they now the same? Why? Why not?

13.Place the Reset formula in theGroup Header section.

11Report Processing—Learner’s Guide

Page 24: Boc330 en Col91 Fv Part Ltr

14.Place theDisplay formula in theGroup Footer section and format field as Bold.

15.Save the report as EvalTimeMRT3.rpt.

Your report should look like this:

Report Processing Strategies—Learner’s Guide12

Page 25: Boc330 en Col91 Fv Part Ltr

Using a dynamic arrayArrays 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 variablename, the collection of data items is given a single variable name. This collection is called anarray. The individual data items contained in an array are known as the array elements. Theelements 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 andremain the same every time the report is run, regardless of the data included on the report. Ina 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 arraywithin Crystal Reports, youmust:• 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, andcreates a counter variable.

The Redim x[n] function is used here to set the size of the array. Re-dimension the array x tosize 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, orGroup Header. WhilePrintingRecords; Global DataType Array Array_Name;

13Report Processing—Learner’s Guide

Page 26: Boc330 en Col91 Fv Part Ltr

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

Populate

The populate formula populates the elements of the array. This formula is typically placed inthe 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 afooter 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 anyfields in this report.

2. Create a formula calledDeclareArray that declares an array to store Countries of Suppliertable.

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 thecurrent record is already in the array. If not, it increments the counter and assigns the nextelement in the array to the Country field value.

6. Create a third formula calledDisplayCountries. The result of this formula should be a stringthat says “We have suppliers in” followed by a list of all the array elements. Each elementshould be separated by a comma.

7. Add these fields to your report so that you only see the result of the array in the reportfooter.

8. Save this report as DynamicArray.rpt.

Your report should look similar to this:

Report Processing Strategies—Learner’s Guide14

Page 27: Boc330 en Col91 Fv Part Ltr

15Report Processing—Learner’s Guide

Page 28: Boc330 en Col91 Fv Part Ltr

Quiz: Report processing1. 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. WhenworkingwithManual Running Totals, why is placement of the formulas on the reportso important?

7. What is page on-demand and what role does it have in the multi-pass process?

Report Processing Strategies—Learner’s Guide16

Page 29: Boc330 en Col91 Fv Part Ltr

Lesson summaryAfter completing this lesson, you are now able to:

• Describe multi-pass reporting• Use evaluation time functions• Use a dynamic array

17Report Processing—Learner’s Guide

Page 30: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guide18

Page 31: Boc330 en Col91 Fv Part Ltr

Lesson 2Using Subreports

Lesson introductionSubreports enable you to create one report that provides all the information you need insteadof creating multiple reports. You can create freestanding reports based on tables that are notrelated 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

19Using Subreports—Learner’s Guide

Page 32: Boc330 en Col91 Fv Part Ltr

Defining subreportsThis lesson examines subreports. Youwill learn and practice applying subreports and featuresto 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 theprocess of creating a regular report. A subreport can havemost 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 maywant 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 thereports.

Subreports can be used to combine unrelated reports like the above example into a singlereport. While the reports could be based on the same data set, they do not have to be. Theycould 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.

Report Processing Strategies—Learner’s Guide20

Page 33: Boc330 en Col91 Fv Part Ltr

• 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 youcannot coordinate data from different tables because the data does not meet the linkingcriteria.

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. Forexample, you might want to show summary values at the top of a report and details at thebottom.

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 fastand 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 thedatabase and the amount of processing a report requires. When Crystal Reports processessubreports, it may call data from the database onto the client computer, depending on whatfunctions are used in the subreport’s formulas. Client-side processing requires additional harddisk 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 theDetails section of themain report causes the subreportto print once for each record returned on the main report. This slows report processing. If thesubreport 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 GroupHeader or Footer.If the subreport is linked to the main report on the grouped field, each time the groupchanges, the subreport reflects data for that group.

21Using Subreports—Learner’s Guide

Page 34: Boc330 en Col91 Fv Part Ltr

2. If you are passing values from the subreport to the main report with shared variables, youneed Crystal Reports to first evaluate the shared variable in the subreport before it calls itfrom themain report. To accomplish this, place the subreport in amain report section abovethe 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 coordinatedwith the data of the primaryreport. In unlinked subreports, there is no attempt to match up the records in one report withthe records in the other. An unlinked subreport does not have to use the same data as theprimary 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 basedon a single table or on multiple tables. Regardless of the underlying data sources, the reportsare treated as unrelated.

Linked subreports are just the opposite. Their data is coordinated. The program matches upthe records in the subreport with the records in the primary report. If you create a primaryreport with customer information and a subreport with order information and link them, theprogram creates a subreport for each customer and includes all the orders for that customer inthat subreport.

Tip: When you add an existing report with saved data as a linked subreport, the data is refreshedfrom 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 parameterfield.

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 equalto the parameter field value

When the report runs, the program finds the first primary field record it needs and passes thevalue in the link field to the parameter field in the subreport. The program then creates thesubreport 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.

Report Processing Strategies—Learner’s Guide22

Page 35: Boc330 en Col91 Fv Part Ltr

• When you run the report, the program finds the first customer record it needs and passesthe Customer ID value from that record to the subreport parameter field.

• The Orders subreport is processed. Since the subreport selection formula selects only thoserecords in which the Customer ID value is equal to the parameter field value, and since thatparameter 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, thoserecords that are orders for the first customer.

• When the subreport is finished, the program locates the second record it needs in the primaryreport, prints the customer data, and then passes this customer’s ID number to the parameterfield.

• The program then runs a subreport including only those order records for the secondcustomer.

• The process continues until the report is finished.

All of this parameter field manipulation takes place behind the scenes. You pick the fields thatlink the primary report with the subreport and the programdoes the rest. The values are passedwithout the parameter field prompting you for a value.

On-demand subreports

On-demand subreports can be especially useful when youwant to create a report that containsmultiple subreports. In this case, you can choose to have these subreports appear only ashyperlinks.

The actual data is not read from the database until the user drills down on the hyperlink. Onlydata for on-demand subreports that are actually viewed is retrieved from the database,makingthe subreports much more manageable.

Note: Data for an on-demand subreport is not saved unless the subreport is actually open in apreview 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 drillsdown on the hyperlink.

3. subreports are free-standing reports; the data is not in any way coordinated with thedata of the primary report.

23Using Subreports—Learner’s Guide

Page 36: Boc330 en Col91 Fv Part Ltr

Creating an unlinked subreportAt times, you may need to combine unrelated reports into a single report. For example, youwant to add a graph that shows the top selling products as a subreport to your Sales by Regionreport. This example can be easily created by inserting a subreport object displaying the topfive 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 reportand 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 thesubreport, 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 andchoose the report from the dialog box that opens.

4. From the Insert Subreport dialog box, clickOK.

Report Processing Strategies—Learner’s Guide24

Page 37: Boc330 en Col91 Fv Part Ltr

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 andclick once to place it.

The programplaces the subreport object into that section and increases the size of the sectionvertically, if required. The program creates a subreport design tab labeledwith the subreportname.

6. If you need to edit your report, click the subreport design tab and modify your subreportas 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 Previewwhile in thesubreport’sDesign tab, you can preview just the subreport. If you want to preview thesubreport as part of the main report, click Print Preview from the primary report’sDesigntab.

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 theprimary 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. SelectCreate a subreportwith the ReportWizard and enter a name in theNew report nametext box.

3. Click the Report Wizard button.

4. Follow the steps in the wizard to create your subreport.

5. ClickOKwhen you are finished with the wizard to return to the Insert Subreport dialogbox.

6. From the Insert Subreport dialog box, clickOK.

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 toplace it.

The programplaces the subreport object into that section and increases the size of the sectionvertically, if required. The program creates a subreport design tab labeledwith the subreportname.

25Using Subreports—Learner’s Guide

Page 38: Boc330 en Col91 Fv Part Ltr

8. Preview your subreport.

Two options exist when previewing your subreport. If you click Print Previewwhile in thesubreport’sDesign tab, you can preview just the subreport. If you want to preview thesubreport as part of the main report, click Print Preview from the primary report’sDesigntab.

Activity: Using the Report Wizard to create a subreport

Objective

• Create an unlinked subreport using the Report Wizard

Your company, Xtreme Bike Company, ismergingwith another bike company calledMountainBikes, Inc. Your company already uses a sales report that lists the customer sales informationfor each region.

The customer data comes from the Xtreme database, your company’s main data source. Younow have a new database containing data for Mountain Bikes Inc. that you want to include onthe 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 folderof the Activity Resources or in the Data_Sources folder in the course resources. Use anAccess/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 appearsafter 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:

Report Processing Strategies—Learner’s Guide26

Page 39: Boc330 en Col91 Fv Part Ltr

Modifying a subreport

Once you have created and inserted your subreport, youmaywant tomake somemodificationsto it.

Applying object formatting or section formatting within the subreport is the same as with anyother 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 andmake changes to the report just as youwould 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 themain report, right-click the subreport placeholder.

27Using Subreports—Learner’s Guide

Page 40: Boc330 en Col91 Fv Part Ltr

2. From the shortcut menu, click Format Subreport.

The Format Editor opens.

Report Processing Strategies—Learner’s Guide28

Page 41: Boc330 en Col91 Fv Part Ltr

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 subreportplaceholder.

29Using Subreports—Learner’s Guide

Page 42: Boc330 en Col91 Fv Part Ltr

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 thisreport 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:

Report Processing Strategies—Learner’s Guide30

Page 43: Boc330 en Col91 Fv Part Ltr

31Using Subreports—Learner’s Guide

Page 44: Boc330 en Col91 Fv Part Ltr

Creating a linked subreportFrequently, the data in a subreport supplements the data in the primary report. Youmight, forexample, have customer data in a primary report and then use subreports to show the ordersfor each customer. In such cases, you need to coordinate the data in the primary report withthe data in the subreport so that the orders in each subreportmatch upwith 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 canprovide supplementary data. For example, you may have a main report with a customer listper region and a subreport with a list of suppliers per region. You need to coordinate the datain 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 primaryreport that contain common data. When you indicate which field in the subreport you want tolink 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 subreport’s record selection.

3. passes the value to the subreport’s parameter field when you preview the main report andcreates the subreport with a record selection based on the parameter field’s value.

The creation and use of the parameter field happens behind the scenes. You need only toindicate 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 availablefor use elsewhere in the subreport. Select the parameter field from the fields list in the FormulaEditor 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.

Report Processing Strategies—Learner’s Guide32

Page 45: Boc330 en Col91 Fv Part Ltr

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 isthe default.

5. Select the field you want to use as the link field in the primary report from the AvailableFields 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 insubreport based on field list.

The program creates a parameter field in the subreport that retrieves a value from theprimary 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. ClickOKwhen done.

33Using Subreports—Learner’s Guide

Page 46: Boc330 en Col91 Fv Part Ltr

The program displays a rectangular placement field.

9. Drag the object frame into the position you want the subreport to appear in your main orprimary report.

When you run the report, the program coordinates the data from the primary report andsubreport 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 reportshould 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 informationto 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:

Report Processing Strategies—Learner’s Guide34

Page 47: Boc330 en Col91 Fv Part Ltr

35Using Subreports—Learner’s Guide

Page 48: Boc330 en Col91 Fv Part Ltr

Creating on-demand subreportsOn-demand subreports are useful when you want to create a report that contains multiplesubreports 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 previewwindow. 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, unlessyou 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 formore 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 Formatmenu, click Format Subreport.

The Format Editor dialog box opens.

3. Click the Subreport tab.

4. Select theOn-demand Subreport check box.

Report Processing Strategies—Learner’s Guide36

Page 49: Boc330 en Col91 Fv Part Ltr

5. ClickOK.

6. Preview the report.

Note: Remember that you can also specify a subreport to be on-demand when you createa new subreport by choosing the on-demand subreport option from the Insert Subreportdialog box.

Adding captions to subreports

Captions enable you to quickly organize your reports in a concise and visually manageableform. Captions can be used on the preview tab and the placeholder frame of an on-demandsubreport.

Placeholder frame captions only apply to on-demand subreports, while tab text captions applyto both on-demand subreports and regular subreports. Since the data from a regular subreportis visible on the preview tab, there is no need for a frame caption when you format a regularsubreport.

A tab text caption replaces the subreport file name caption on the Subreport Preview tab. Youcanwrite captions by using formulas. Both placeholder frame captions and Subreport Previewtab captions can include field names from the main report.

37Using Subreports—Learner’s Guide

Page 50: Boc330 en Col91 Fv Part Ltr

To add captions to subreports

1. Select the subreport.

2. From the Formatmenu, 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 appropriateFormula 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 InformationAbout 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. ClickOK to return to the report.

Note: A tab text formula is only evaluated when you drill down on a subreport. If youpreview 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 don’t wantto see the subreport data all the time. They would rather click on a hyperlink to retrieve theMountain Bike company’s data. The users alsowant to see useful hyperlink titles and drill-downtabs.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 InformationAvailable” is displayed.

Report Processing Strategies—Learner’s Guide38

Page 51: Boc330 en Col91 Fv Part Ltr

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:

39Using Subreports—Learner’s Guide

Page 52: Boc330 en Col91 Fv Part Ltr

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

Report Processing Strategies—Learner’s Guide40

Page 53: Boc330 en Col91 Fv Part Ltr

Using shared variables with subreportsYou 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 asubreport to themain report. For example, youwant to create a grand total by adding numbersfrom the main report to numbers from the subreport. Or you want to find out whether thesubreport 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 themain report.Themain 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 tothe total number or count of the subtotal from your main report to find out the total count ofcontacts your organization has. The first step is to insert a formula in the subreport to store thecount of suppliers. You need to declare or name the variable. In this case, the shared variableis “GT” for Grand Total. Then, assign the value of the shared variable. For this example, it isthe 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 suppliersin that region. You can add a text object that indicates that this total reflects the total numberof 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 thesubreport 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 footersection under the subreport. Because of themulti-pass reporting sequence that Crystal Reportsapplies, 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 yourreport has several subreports, the shared variable can also be used in any or all of the subreports.

41Using Subreports—Learner’s Guide

Page 54: Boc330 en Col91 Fv Part Ltr

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 havesubtotals for the customer count and last year’s sales amount. The current report includes asubreport that is well integrated. The users would like to have subtotals for the customer countand last year’s sales amount.1. Open SubreportsShared.rpt.

2. Edit the subreport to create two formulas using shared variables to hold a count of customersand a total sales formula.

3. Create a formula in the main report that combines the count value from the subreport witha 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 witha 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:

Report Processing Strategies—Learner’s Guide42

Page 55: Boc330 en Col91 Fv Part Ltr

Linking unlinkable dataMany corporations store data in a number of databases and it is possible that you will not beable to link the data because of limitations. If you want to link between different field types orfrom 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 andthe internal Sales activity database stores the Customer number as a string type field. Youcannot link the two databases together within Crystal Reports’ Visual Linking Expert becausethey are different data types. Using subreports, you can link different types with the use offormulas.

Creating links to unlinkable data

When you need to link unlinkable data, you can use subreports because subreports allow youto link to or from a formula field. All you need to do is create a formula field in the primaryreport or the subreport that returns the same result (that is, date type or length) as the databasefield value you want to link to. You then link from the main report and subreport to or fromthe 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 Numberfrom 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 theprimary 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 thedata in the subreport based on the link between the main report database field and thetype-converted formula field linked to in the subreport.

43Using Subreports—Learner’s Guide

Page 56: Boc330 en Col91 Fv Part Ltr

Note: The field type of the primary report field to link from determines which subreportfields are visible when choosing the field to link to. Therefore, it is important to make surethe 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 eachcustomer lists the special events they attended in 1998. The problem here is that the data isunlinkable. The Customer ID field in the primary report is a number field, but in the eventstable, it is a string field. The customer data is stored in the Customer table within the Xtremedatabase. The Customer ID field is stored as aNumber. The Events tablewithin the Events.mdbcontains 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 thecontact’s 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 aData Files connection to Events.mdb, which can be found in the Lesson 2 folderin 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:

Report Processing Strategies—Learner’s Guide44

Page 57: Boc330 en Col91 Fv Part Ltr

45Using Subreports—Learner’s Guide

Page 58: Boc330 en Col91 Fv Part Ltr

Quiz: Using subreports1. 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 mainreport) 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 amenu.What is the differencebetween 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?

Report Processing Strategies—Learner’s Guide46

Page 59: Boc330 en Col91 Fv Part Ltr

Lesson summaryAfter 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

47Using Subreports—Learner’s Guide

Page 60: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guide48

Page 61: Boc330 en Col91 Fv Part Ltr

Lesson 3Creating Complex Formulas

Lesson introductionCrystal 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

49Creating Complex Formulas—Learner’s Guide

Page 62: Boc330 en Col91 Fv Part Ltr

Using Print State functionsThis 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, ortransform data. Print State functions return a value based on the state of the report beingpreviewed.

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 containsa 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 havesomething other than a null value in the field specified. You can also use it to have the programtake some action whenever it encounters a null value.

Some databases support null data values and others do not. This function will not work if theactive database(s) does not support null values. If the database(s) supports null values, thefunction can be used to reference the null values that get created as the result of a failed lookupwhile joining.

Caution: If a field value is equal to null, it does not mean it is of zero value in the case of anumber 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 theorder 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 havesomething 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 happenif a data entry person uses the spacebar thinking they are deleting a value in a field. You canuse the TRIM function to catch these values (that is, consider them NULL). For example:

@IsNullTrimDemo// Using ISNULL and TRIM together to find blanksIf ISNULL({tablename.fieldname}) Or TRIM({tablename.fieldname}) = “” Then True //or Value if true

Report Processing Strategies—Learner’s Guide50

Page 63: Boc330 en Col91 Fv Part Ltr

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 thecurrent record.

You can use this function to test for the last item in a list and to take some action when youidentify 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:

51Creating Complex Formulas—Learner’s Guide

Page 64: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guide52

Page 65: Boc330 en Col91 Fv Part Ltr

Using loop control structuresControl structures allow you to vary the sequence and order inwhich 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 oncewhenthe formula is evaluated. The expressions are executed in a sequential fashion, from the firstexpression in the formula to the last. Control structures enable you to vary this rigid sequence.Depending uponwhich control structure you choose, you can skip over some of the expressionsor repeatedly evaluate some expressions depending on if certain conditions hold. Controlstructures are the primarymeans of expressing business logic and typical report formulasmakeextensive 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 formulasmuchmore power and flexibility. Loop control structuresevaluate 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. Thisis unlike the If and Select expressions where the program passes through each expression atmost once during the formula's evaluation. For loops are best when you know the number oftimes that the expression needs to be evaluated in advance.

The syntax for For loops is demonstrated by the following example:

53Creating Complex Formulas—Learner’s Guide

Page 66: Boc330 en Col91 Fv Part Ltr

Suppose youwant to reverse the {Customer.Customer Name} string. For example, City Cyclistsbecomes stsilcyC ytiC.//Reverse a string version 1Local 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 iterationof 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 threeand 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 rafter the first iteration.

During the second iteration, the eighth character of {Customer.Customer Name} is appendedto str and so str equals ri. This continues until after the ninth iteration, str equals riA naelCwhich is the reversed string.

Note: In practice, the above formula codewould bewell-documentedwith the use of commentsto 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 fixedblock 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 evaluatesthe 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 untilthe 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.

Report Processing Strategies—Learner’s Guide54

Page 67: Boc330 en Col91 Fv Part Ltr

• The While loop supports an Exit While statement to immediately jump out of the loop. Itsuse 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 theBoolean 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, itreturns its position, otherwise it returns -1. In this case, the input string is set explicitly to astring 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 conditionevaluations per evaluation of a formula. This statement should only be used when the defaultmaximum 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 evaluatedper evaluation of a formula. It must be a positive integer.

For example://option loop exampleoption loop 256;//make name upper caseLocal StringVar outString;Local StringVar inString := {Customer.Customer Name};Local NumberVar I;For i:=1 to Length(inString) dooutString := outString + upperCase(inString[i]);outString

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

Activity: Using loop control structures

Objective

• Use loop control structures to resolve the reporting problem.

55Creating Complex Formulas—Learner’s Guide

Page 68: Boc330 en Col91 Fv Part Ltr

Instructions

The Company wants to make its Customer ID more user-friendly. One proposal is to combinethe 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 inuppercase.

3. If the customer name has less than 15 letters, add X’s until it has 15. For Example, BikePlanetwould 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:

Report Processing Strategies—Learner’s Guide56

Page 69: Boc330 en Col91 Fv Part Ltr

Using loop control structures with arraysArrays in Crystal Reports are ordered lists of values that are all of the same type. These valuesare known as the array's elements. The elements of an array can be any simple type or rangetype. Arrays can be created using square brackets ([ ]). Arrays are most useful when used withvariables 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 ormanipulating arrays, it is often necessary to knowhowmany elements thereare 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 iscommonly used to obtain the size of an array before using a looping control mechanism tosystematically 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 subscriptan un-initialized array variable. The reason for this behavior is that at present Crystal Reportsdoes not support arrays with zero elements. To work around this problem, always initializeyour array variables. For example, initialize global array variables in a formula located in thereport 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 numberof 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", "//")

57Creating Complex Formulas—Learner’s Guide

Page 70: Boc330 en Col91 Fv Part Ltr

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 theFileName string.

3. Create another formula (use the same variables) which displays “howdeep” in the directorystructure 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).

Report Processing Strategies—Learner’s Guide58

Page 71: Boc330 en Col91 Fv Part Ltr

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 alreadyfamiliar 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, NewZealand, Indonesia and Singaporeare selected:

59Creating Complex Formulas—Learner’s Guide

Page 72: Boc330 en Col91 Fv Part Ltr

Looping through an array

Each element of an array can be retrieved individually, or by using a function such as the JOINfunction, 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 thetask becomes unmanageable. Looping accomplishes this taskmore efficiently. In this example,the result of a parameter is stored as an array. To retrieve “every second element” using a Forloop 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. Noticethe 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 forthe “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]

Report Processing Strategies—Learner’s Guide60

Page 73: Boc330 en Col91 Fv Part Ltr

);mid(display_region,3);

Using this code in a report where you want to extract regions results in this example. Noticethe 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 Year’s 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%

61Creating Complex Formulas—Learner’s Guide

Page 74: Boc330 en Col91 Fv Part Ltr

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 Year’s Sales.

Report Processing Strategies—Learner’s Guide62

Page 75: Boc330 en Col91 Fv Part Ltr

Quiz: Creating complex formulas1. 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 doesLooping through an array have over the branching control structures (Select Case or IfThen 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

63Creating Complex Formulas—Learner’s Guide

Page 76: Boc330 en Col91 Fv Part Ltr

Lesson summaryAfter completing this lesson, you are now able to:

• Use Print State functions• Use loop control structures• Use loop control structures with arrays

Report Processing Strategies—Learner’s Guide64

Page 77: Boc330 en Col91 Fv Part Ltr

Lesson 4Using Custom Functions

Lesson introductionCustom functions are a means of storing pieces of logic to reuse within a single report ormultiple reports.

After completing this lesson, you will be able to:

• Describe a custom function• Use custom functions

65Using Custom Functions—Learner’s Guide

Page 78: Boc330 en Col91 Fv Part Ltr

Describing a custom functionCustom 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 calculationson, or transform data. When you use a custom function in a formula, all the operations in itsdefinition 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. Butit is important to understand the differences between them.

Formulas are typically used to create calculated fields on a report, format text, manipulatestrings, or extract part of date fields.

Custom functions are business logic that you create to perform routine tasks in formulas. Theyare used as the basis for a formula but on their own, custom functions do not change the waydata appears or is represented on a report.

When you use a custom function in a formula, all the operations in its definition are performedwithout you having to specify them individually in the formula itself. Thus, the custom functionprovides a way to share and reuse formula logic which, in turn, makes it easier and less timeconsuming for users to create reports.

For example, suppose you are designing a series of reports from a database that storesdepartment information with three-letter code names, but you want the actual departmentnames to appear in your reports. Creating a formula to transform the data would work, butyou’d have to copy the formula logic from report to report until you’d completed the series. Itis much easier if you extract the logic that does the data transformation and save it as a customfunction. You can add that custom function to each report in your series without having tore-enter the text.

Note: Because custom functions are designed for use across multiple reports, a custom functioncannot 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:

Report Processing Strategies—Learner’s Guide66

Page 79: Boc330 en Col91 Fv Part Ltr

• Custom functions can replace sections of formula logic common tomany different formulasthat, in turn, may be used in many different reports.

• Custom functions can be shared between reports by storing them to the BusinessObjectsEnterprise repository and adding them to reports as needed.

• Custom functions can reduce the need for users to write formulas themselves. You canprovide them with the formula logic they need in a custom function.

• Existing formulas can be converted to custom functions using the Extract Custom Functionfrom 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 makesit easier for users to use them.

• Custom functions, unlike User Function Libraries (UFLs) to which they are related, aresaved as part of the report file (.rpt) and don’t 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 eachreport 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, thefollowing 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 differentways toworkwith custom functions in Crystal Reports, this samplework 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 CustomFunction 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:

67Using Custom Functions—Learner’s Guide

Page 80: Boc330 en Col91 Fv Part Ltr

• 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 you’re working on oradded 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 theFormula Workshop. At that point, the custom function is available for use in your currentreport. If, however, you want to use the custom function in other reports, you can share it byadding 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 underthe Report Custom Functions node are available to use and reuse on the open report. Customfunctions listed under the Repository Custom Functions node are for use and reuse on allreports.

To use custom functions from the Repository Custom Functions node, they must be added tothe 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 andcan be changed from one report to another.

Report Custom FunctionsRepository Custom Functions

Available in the current report onlyAvailable across multiple reports

Are editableCannot be edited

Report Processing Strategies—Learner’s Guide68

Page 81: Boc330 en Col91 Fv Part Ltr

Using custom functionsOnce you understandwhat custom functions are and how they relate to formulas you are readyto 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 functionsthat are stored in the repository. In this lesson, you will build formulas based on these customfunctions.

In order for the sample custom functions to be available for use they must be installed via theBusiness View Manager.

Custom functions can be selected for use in formulas just as you’d 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 customfunctionwaswritten in a different syntax. For example, a Basic syntax formula can call a Crystalsyntax custom function.

Once a custom function has been created, you can select it from the Custom Functions folderof the Functions Tree in the Formula Editor. Once you’ve selected a custom function for usein your formula, you must specify the argument values as defined when the custom functionwas 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 andspecifies the argument values as prompted for by the expert. You can set default values forusers 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 withCrystal 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 thecustom function doing the calling. For example, a custom function written in Basic syntax cancall a custom function written in Crystal syntax.

69Using Custom Functions—Learner’s Guide

Page 82: Boc330 en Col91 Fv Part Ltr

Calling a custom function with optional arguments

When calling a custom functionwith optional arguments, you can omit the optional argumentsand 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 Reportmenu, 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. Ifyou select a repository custom function, that custom function is added to the current reportand is added to the Report Custom Function list. If that custom function requires othercustom 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 FunctionArguments area, specify a value for each argument in the appropriate valuefield. You can enter constant values directly, or you can select predefined values or reportfields from the associated list.

5. Click Save.

You can now use this function in a formula just as you would use a function installed withCrystal Reports.

Defining default argument values for custom functions

You candefine default argument values for a custom function in theCustomFunctionPropertiesdialog box. Users can choose from the default values in the Function Arguments area of theFormula Expert.

Report Processing Strategies—Learner’s Guide70

Page 83: Boc330 en Col91 Fv Part Ltr

To define default argument values

1. In the Formula Workshop, ensure Toggle properties display is selected on the toolbar.

2. Expand theReport CustomFunctions node of theworkshop tree view and select the customfunction you want to define default argument values for.

Note: The custom function must have arguments defined and must be in the report. Youcannot 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 editit.

3. Click theDefault Values field for the appropriate argument.

The name and functionality of the dialog box that appears depends on the argument fieldyou’ve 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 won’t let you add the same value twice.

The value you put in the first position becomes the default value for the argument. Forarguments that are not optional, this value is used by the Formula Expert if no value isentered or if the Reset Values button is clicked.

5. ClickOKwhen you’re done adding default values.

The default values are displayed separated by blanks in theDefault Values field of theCustom Function Properties dialog box. In the Formula Expert, the default values appearat 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 throughthe Custom Function Properties dialog box.

For example, the following formula text provides an optional value of the current date for thefunction 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 anoptional value, the value used is not determined until the custom function is executed. The

71Using Custom Functions—Learner’s Guide

Page 84: Boc330 en Col91 Fv Part Ltr

value is determined by the custom function itself, so if you change the value in the customfunction, all the formulas based on that function change too.

In the Formula Expert, optional values are displayedwith their current value (the current valuemay be different at the time the formula is executed). The Formula Expert uses the optionalvalue 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 thatdisplays the full name of each customer’s 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, selectcdExpandRegionAbbreviation.The workshop screen updates.

9. In the Function Arguments area, locate the Value column. Here is where you select inputsfor the custom function.

10.For the regionAbbreviation row, click in theValue cell, selectChooseOther Field and thenselect 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 beingundoable.

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:

Report Processing Strategies—Learner’s Guide72

Page 85: Boc330 en Col91 Fv Part Ltr

Creating custom functions with Crystal syntax

Crystal syntax custom functions are expression-oriented, like Crystal syntax formulas. You canuse 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 argumentsthat are passed into the function when the argument is called. Multiple variables are separatedby commas. An empty argList is allowed; however, the parentheses surrounding argList arenot 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 anargument is optional, all subsequent arguments must be optional as well. If you supply avalue for an optional argument when calling the function, then you must supply values foreach preceding argument.

• SimpleType

This is required. You can use one of:• NumberVar

• CurrencyVar

73Using Custom Functions—Learner’s Guide

Page 86: Boc330 en Col91 Fv Part Ltr

• 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, it’s an expression involving no variables that can be simplified at compile time to aconstant value. If an optional argument is omitted when calling a custom function, then thedefault value for the argument is used.

• expressions

These are required. The value returned by the Crystal syntax custom function is the valueof the last expression evaluated in the expression sequence. The syntax is the same as thatin Crystal syntax formulas.

Scope

Variable declarations within a custom function are local scope by default. This contrasts withvariable 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 globalor shared variable in as an argumentwhen calling a custom function fromwithin 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 andGridRowColumnValue.

Report Processing Strategies—Learner’s Guide74

Page 87: Boc330 en Col91 Fv Part Ltr

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

Variables

You can use local variables and argument variables in custom functions. If you need to use ashared 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 anotherformula to do some processing, even through the use of global variables).

For example:Rem Formula PrintSquareGlobal x As Numberx = 5formula = “The square of “ & CStr(x,0) & “ is “ &

ToText ({@square, 0) & “.”

Rem Formula SquareGlobal x As Numberformula = 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 theevaluations. First Square is evaluated and then PrintSquare is evaluated. When Square isevaluated, the value of the global variable x is zero, since that is the value of an uninitializednumber variable.

In contrast, custom functions are evaluated on demand, or called. This uses a custom functionfrom the previous example:Rem Formula PrintSquareformula = “The square of “ & CStr (5,0) & “ is “ &

CStr(cf9Square (5),0) + “.”

Rem Custom Function cf9SquareFunction cf9Square (x As Number)

cf9Square = x * x

End Function

Now if you use formula PrintSquare in your report, you’ll 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 FunctionEditor, or you can extract the logic from an existing report formula.

75Using Custom Functions—Learner’s Guide

Page 88: Boc330 en Col91 Fv Part Ltr

To use the Custom Function Editor

1. In the Formula Workshop, clickNew 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 theCustomFunctionEditor 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 Customfunction syntax.

Tip: Ctrl+Spacewill bring up a list of the available functions. If you’ve already startedtyping it will bring up a list of keywords that are possible matches for what you’ve alreadytyped.

5. Check and save your custom function.

Once the custom function has been saved, you can modify it or use it in report formulas asneeded.

Using the Extract Custom Function from the Formula dialog box

When you extract a custom function from an existing formula, the program copies the formulaand replaces its fields with arguments.

Note: A custom function created using the Extractor can only return simple types, like strings andintegers. It cannot return arrays. To create a custom function that can return arrays, use theCustomFunction Editor.

To extract a custom function from an existing formula

1. In the Formula Workshop, clickNew 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 yourcustom function.

Once you’ve selected a formula, the Return Type,Arguments, and Formula Text fields arecompleted with information that relates to that formula. These fields cannot be changedwithout selecting a different formula.

The remaining fields are optional.

Tip: Youwill probably want to create meaningful names for the arguments in your customfunction. The program assigns generic names (v1, v2, v3, and so on) by default.

Report Processing Strategies—Learner’s Guide76

Page 89: Boc330 en Col91 Fv Part Ltr

SelectModify formula to use a new custom function to replace the text of the formula youselected in this step with the new custom function you’re creating.

5. ClickOK to save the custom function to theReport Custom Functions node of the FormulaWorkshop. Once the custom function has been extracted and saved, you can modify it oruse it in report formulas as needed.

Note: You cannot add new arguments to your custom function while you are creating it inthe Extract Custom Function from Formula dialog box. To add new arguments, save thecustom 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 fallson a weekend. If so, change the date to the nearest weekday (that is, Saturday to Friday andSunday to Monday).1. Open the report Extractor.rpt from the course resources.

2. Open the formula workshop and display theWeekdayShipped formula.

3. You want to re-use this logic for Required Date using a Report Custom Function. In theworkshop tree, click Report Custom Functions.

4. Click theNew button, and make sure the box says Custom Function Name.

5. Give the custom function the nameNearest weekday.

6. Click Use Extractor.

7. In the middle of the window, in the first row under Argument Name, change v1 toYourDateValue.

8. Tab to theDescription column and enter Date field or expression to be tested forweekend.

9. ClickOK.

10.Use the workshop tree to compare your Report Custom Function to the original formulanamed, @WeekdayShipped.

11.Use your new Custom Function Nearest weekday in the following formula. Create a newformula calledWeekdayRequired.

12.In the Formula Editor, from the Toolbar use the Expert button.

13.In the box labeled Custom Function, selectNearest weekday.

77Using Custom Functions—Learner’s Guide

Page 90: Boc330 en Col91 Fv Part Ltr

14.In the Function Argumentswindow under Value, from the list of available choices, selectChoose Other Field.

15.Select Required Date from the Choose Fieldwindow, and then clickOK.

16.Click Save and Close to save the formula and to close the formula workshop.

17.Place the formulaWeekdayRequired onto the report.

18.Format theWeekdayRequired 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 aregrouped under subfolders of theReport CustomFunctions list.When saved into the repositorythis 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 theCustomFunction Propertieswindow is not openon the right-hand side, use the Custom Function Properties toggle button to display it.

3. Once in the Custom Function Propertieswindow enter a name in the Category box.

4. Click Save and Close.

Report Processing Strategies—Learner’s Guide78

Page 91: Boc330 en Col91 Fv Part Ltr

Note: If theCategory box is not available, the custom function has been added to the BusinessObjectsEnterprise repository and is therefore locked from editing. Right-click the custom function, andthen clickDisconnect from Repository. After adding a category, you can add the custom functionback 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 CustomFunction and therefore reusable only within the current report. To make custom functionsavailable acrossmultiple reports theymust 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 beused in other reports. This is not a requirement for custom functions, but if you want to reusethem 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 FormulaWorkshop, select and expandReport CustomFunctions, and then right-clickthe available custom function.

Note: If you are not logged on to BusinessObjects Enterprise, you are prompted to do so atthis point.

2. Click Add to Repository.

Now, when you open the Repository Custom Functions list, you see the custom functionadded to the repository.

Note: If the custom functions have been categorized, these categories also appear under RepositoryCustom 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 theNearestWeekday Report Custom Function.

4. Click Toggle Properties Display on the toolbar.

79Using Custom Functions—Learner’s Guide

Page 92: Boc330 en Col91 Fv Part Ltr

5. EnterMy 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 beedited 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 functionhas changed.

12.ExpandRepository Custom Functions. Notice the folder My Date Functions now containsNearestWeekday.

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 tothem 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 functionwith a different name, the modified custom function will overwrite the previously saved one.

Report Processing Strategies—Learner’s Guide80

Page 93: Boc330 en Col91 Fv Part Ltr

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 thefunction 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, andselectDisconnect 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 thefunction 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 theReport Designer.

To refresh a report's repository custom functions

1. On the Filemenu, clickOptions, and then click the Reporting tab.

2. Under Enterprise Settings, ensure Update Connected Repository Objects on Open isselected.

3. ClickOpen on the Standard toolbar in Crystal Reports and select the report whose customfunctions need to be updated.

4. ClickOpen.

The report's custom functions and all other updated repository objects are refreshed as thereport opens.

Tip: If you don't want to use this global option, you can also update a report's customfunctions by selecting the Update Repository Objects option on theOpen dialog box foran individual report.

81Using Custom Functions—Learner’s Guide

Page 94: Boc330 en Col91 Fv Part Ltr

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 ofActivity: Saving a custom functionto the repository.

2. Open the Formula Workshop.

3. Select Report Custom Functions from theWorkshop Tree.

4. Right-click and selectNew 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 ratelocal numbervar EurosPerDollar:=0.90;AmountUSD * EurosPerDollar

7. Save the function.

8. Create a new formula calledOrderAmountinEuro.

9. Open the Expert by clicking the Use Expert button on the toolbar.

Report Processing Strategies—Learner’s Guide82

Page 95: Boc330 en Col91 Fv Part Ltr

10.In the Custom Function Tree locate Report Custom Functions, and then selectConvertUSDtoEuros.

11.In the Function Argumentswindow, click the cell under Value. Select the Select Field orEnter Value option, and open the list.

12.In the Field Tree, select Choose Other Field, and then double-clickOrder Amount.

13.Click Save and Close.

14.AddOrderAmountinEuro to the report.

15.Format the Euro value appropriately.a. Right-click the field, and then click Format Field on the shortcutmenu to open the Format

Editor.b. On theNumber 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 forthe Euro symbol and must be generated on the number keypad to appear.)

f. ClickOK twice.

You have just written a custom function with the Formula Editor and used that customfunction in a formula.

In part 2 of the activity you will add the newly created custom function to the repositoryand 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 theConvertUSDtoEuros custom function to the repository anduse it in a formula.

Instructions

1. Re-open the Formula Workshop.

2. Access the properties of theConvertUSDtoEuros 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.

83Using Custom Functions—Learner’s Guide

Page 96: Boc330 en Col91 Fv Part Ltr

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 selectthe 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 3of the activity, you will update the exchange rate for both reports.

Report Processing Strategies—Learner’s Guide84

Page 97: Boc330 en Col91 Fv Part Ltr

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 theexchange rate you will disconnect one of the custom functions from the repository, modifyit, and then add it back to the repository, overwriting the original.

Instructions

1. Open the Formula Workshop and under Report Custom Functions in theWorkshop Treeselect the ConvertUSDtoEuros function.

2. Right-click the function and selectDisconnect 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. ClickOK to the warning about modifying the function.

7. Use theWorkshop 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:

85Using Custom Functions—Learner’s Guide

Page 98: Boc330 en Col91 Fv Part Ltr

10.Close the SalesInEuros.rpt.

11.Re-open theModifyFunction.rpt.

12.Under the Filemenu, clickOptions, 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 shouldlook similar to this:

14.Save and close theModifyFunction.rpt.

Report Processing Strategies—Learner’s Guide86

Page 99: Boc330 en Col91 Fv Part Ltr

Quiz: Using custom functions1. 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 Whynot?

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.

87Using Custom Functions—Learner’s Guide

Page 100: Boc330 en Col91 Fv Part Ltr

Lesson summaryAfter completing this lesson, you are now able to:

• Describe a custom function• Use custom functions

Report Processing Strategies—Learner’s Guide88

Page 101: Boc330 en Col91 Fv Part Ltr

Lesson 5Using XML and Web Services Data

Lesson introductionIn Crystal Reports, XML is both a data source and an export format. You can create a reportfrom an XML or Web Service data source turning raw XML or Web Services DescriptionLanguage (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

89Using XML and Web Services Data—Learner’s Guide

Page 102: Boc330 en Col91 Fv Part Ltr

Using XML and web services dataThis unit looks at how to create a report from an XML or web service data source, turning rawXML 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 aweb 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 valuableinformation produced by business logic working closely with the data.

You are tasked with producing reports on the information but there is no standard dataconnectivity available to access the information produced by the business logic.

You are able to request that XML-format text files be produced containing the informationyou need.

• Scenario 2

Valuable information is available in a different part of your organization. You are not ableto access the data directly but a web service has been provided, allowing the data to beretrieved.

• Scenario 3

You are a financial report designer and want to augment your company’s sales data withindustry 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 andWeb Servicesdriver, you can choose from several possible data source types:• Local data source• HTTP(S) data source• Web Service data source

Report Processing Strategies—Learner’s Guide90

Page 103: Boc330 en Col91 Fv Part Ltr

To choose XML as your data source

1. In Crystal Reports, on the Filemenu, point toNew, 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 XMLsource, XML data distributed via a virtual directory or HTTP, or establish a connection with aweb service.

91Using XML and Web Services Data—Learner’s Guide

Page 104: Boc330 en Col91 Fv Part Ltr

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 networkdrive.

• Local XML File

Enter a full path and file name for your local data source, or select a file by searching for itin 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 thatyou can access from a Servlet, an ASP page, a JSP page, or another type of dynamicallycreated web page).

• HTTP(S) XML URL

Enter either anHTTP or anHTTPSURL for your HTTP(S) data source.When usingHTTPS,user IDs and passwords that you enter in Crystal Reports are used to authenticate againstthe 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 containsembedded schema information.

• Validate XML

Report Processing Strategies—Learner’s Guide92

Page 105: Boc330 en Col91 Fv Part Ltr

Select this option if you want the XML document validated against the schema, and youhave 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 canbe a service that you have on a local machine or a network drive that you can connect to byentering a path and file name, or it can be a service that you access from a servlet or adynamically created web page. The URL you provide to such a source can be either HTTPor 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 connectto by entering a path and file name. The XML driver lets you type a full path and file name, oryou can select a file by searching for it in the Open dialog box. If you have a schema (XSD) foryour 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 tosearch 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 embeddedschema information.

Note: You define the location and name of your schema on the next screen.

4. ClickNext.

Depending on your selection in the previous step, youwill see either a screen for specifyingyour schema, or you can click the Finish button.

5. To specify a schema file, choose either Use Local Schema or Use HTTP(S) Schema andcomplete 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. ClickNext, 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, anASP page, a JSP page, or another type of dynamically created web page. The URL you provide

93Using XML and Web Services Data—Learner’s Guide

Page 106: Boc330 en Col91 Fv Part Ltr

to such a data source can be eitherHTTPorHTTPS.WhenusingHTTPS, user IDs andpasswordsthat you enter in Crystal Reports are used to authenticate against the underlyingHTTPprovider.

The XML driver lets you type a URL and later add authentication credentials. If you have aschema (XSD) for your XML file or stream, you can specify the schema and its authenticationcredentials.

Note: When you use the XMLdriver, you can specify a schema (XSD) or Document TypeDefinition(DTD) of your choice, or you can use schema information embedded in the XML document. Theschema is used to determine how to present the XMLdatawithin Crystal Reports.When you specifya schema to use with your XML file, the specified schema is used instead of schema informationembedded 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 embeddedschema 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. ClickNext.

6. Enter authentication information if it is needed, and then clickNext again.

Depending on your selection in step 2, you will see either a screen for specifying yourschema, 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 andcomplete 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 limitthe 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.

Report Processing Strategies—Learner’s Guide94

Page 107: Boc330 en Col91 Fv Part Ltr

• Click Edit Value to change an existing parameter. Select the parameter you want to editbefore you click this button.

• Click Remove Property to delete an existing parameter. Select the parameter you wantto remove before you click this button.

9. Click Finishwhen 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 andthe 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 anXML data set. Crystal Reports supports web services that communicate using SOAP. The URLyou provide to such a source can be either HTTP or HTTPS. The schema for the response XMLfile is derived through the web services framework rather than specified manually.

Web service data source interfaces are described using WSDL (Web Services DescriptionLanguage), which is the standard format for describing a web service. After you specify a pathto the WSDL, the driver lets you select which Service, Port, and Method you want to use. Youmay also have to enter authentication user ID and password.

Web services may be secured using the WS-Security Web Service standard. The XML driversupports this standard by allowing a security credentials policy file to be used to specify thesecurity 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 clickNext 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.

95Using XML and Web Services Data—Learner’s Guide

Page 108: Boc330 en Col91 Fv Part Ltr

• For Use Local WSDL, enter the full path and name of your web services file, or use thebutton 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 aWeb Service secured usingWS-Security, specify the policy filein this step as well.

3. ClickNext.

Depending on your selection in the previous step, youwill see either a screen for specifyingyour web service, ports, and methods, or a screen for defining authentication for your webservice 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 clickNext.

5. On the Web Service, Port and Method screen, choose a service, a port, and a method fromthe lists.

6. Click Finish.

Once you can see the table created fromyour XMLdata source, you can use it to create a Crystalreport 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. LaunchQuery as a Web Service and create a new query based on the eFashion universe.a. Click Start ➤ Programs ➤ BusinessObjects ➤ BusinessObjects Enterprise ➤ Query

As AWeb Service.b. In theManage 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, andauthentication, if required, and then clickOK.

d. Close theManage Hosts dialog box.e. In the Select your credentialswindow, enter the appropriate information such as the host

machine, the name of the CMS, your logon credentials, and a password, if required, andthen clickOK.

f. In theQuery as aWeb Service dialog box, select the appropriate folder (if required), andthen clickNew Query.

g. In the Web Service Name edit field of the Publish Query As AWeb Service Wizarddialog box, enter a name for the query, and then clickNext.

h. In the Select a universe window, click the eFashion universe, and then clickNext.i. Expand the Store class and add State, City, and Store name to the query.

Report Processing Strategies—Learner’s Guide96

Page 109: Boc330 en Col91 Fv Part Ltr

j. ClickNext, and then click Publish.k. Copy the WSDL URL to the Clipboard.l. Minimize or close theQuery As AWeb 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 clickNext.b. Select Use HTTP(S) WDSL, paste the WDSL URL in the field, and then clickNext.c. Enter your WSDL user ID and password and then clickNext.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 clickOK.

3. ExpandDatabase 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.

97Using XML and Web Services Data—Learner’s Guide

Page 110: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guide98

Page 111: Boc330 en Col91 Fv Part Ltr

Using a transform in XML reportingYou can export a Crystal report to an XML format by using XSLT transforms to render reportsin 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. Withthis 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 fileformat you need. If you do not have a specific XML schema you want to use to format yourreport, or if you want to perform transformations after exporting the report, you can use thebuilt-in Crystal Reports XML schema, then transform the exported file.

Crystal Reports can render reports in almost any industry-standard format. Exporting to XMLusing XSLT transforms allows for faster and easier integration with your industry-specificbusiness processes, without custom coding. The XSLT transformations are embedded into thereport 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 apowerful, flexible hook for transforming Crystal Reports data and integrating it into otherapplications.

Importing an XML transform

If the schema provided with Crystal Reports does not meet your needs for the exported XMLformat, you can import an XML transform to produce XML in a different schema or create adifferent file type altogether.

In this case you can use the XML Export Format Manager to import your XSLT into the reportand optionally set it as the default schema for formatting the report during XML export.

When exporting to customXML formats, Crystal Reports first generates aCrystal Reports XMLformat file then applies your transform to it before providing the final results.

To import an XML transform

1. On the Filemenu, point to Export, and then clickManage XML Exporting Formats.TheManage XML Exporting Formats dialog box opens.

2. In theManage XML Exporting Formats dialog box, click Add.The Add a New XML Format dialog box opens.

3. Type a name for your format.

99Using XML and Web Services Data—Learner’s Guide

Page 112: Boc330 en Col91 Fv Part Ltr

This is the name that appears in theManage XML Exporting Formats dialog box when youchoose an XML format for exporting a report.

4. Click Import XML Transform to open theOpen 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 notaffect the file format.

7. Enter a description for the new format.This description appears in theManage XML Exporting Formats dialog box when youchoose an XML format for exporting a report.

8. ClickOK twice.

9. Once the schema is imported click Save XMLTransformAs to save a copy of the transformto another location.

Exporting to XML format

In Crystal Reports, XML is both a data source and an export format. You can create a Crystalreport 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 CrystalReports, or create new XML-based export formats by embedding XSLT transforms into yourreport.

To export a report to XML

1. Open the report you want to export.

2. On the Filemenu, 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 exportformat.

4. Select the destination.If you are exporting to an application, the appropriate type of application for the format'sfile type is shown. The Choose export file dialog box appears if you are exporting to a file.

5. ClickOK.The XML Export Options menu opens. This menu allows you to select the Crystal ReportsXML (default) format or any added transformation (XSLT).

6. Choose the XML exporting format and clickOK.

Report Processing Strategies—Learner’s Guide100

Page 113: Boc330 en Col91 Fv Part Ltr

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 Descriptionfield enter Justice data format.

3. Open offenses.rpt.

4. Export the data displayed in the sample offenses.rpt report to the standard Crystal ReportsXML 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 XMLformat, using the Justice Data Submission transform to conform the data to the Justice XMLData Model format.

7. Select Application as the destination.The offenses.rpt report has been exported to XML format, using the JusticeData Submissiontransform to conform the data to the Justice XML Data Model format. Note that the XMLelements now show customized tags such as Offense, IncidentSubject, and PersonName,instead of GroupHeader, Section SectionNumber, and FieldName as seenwith the standardXML format.

101Using XML and Web Services Data—Learner’s Guide

Page 114: Boc330 en Col91 Fv Part Ltr

Quiz: Using XML and Web Services Data1. 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 remotesystem.

3. True or False. For HTTP / HTTPS data sources the XML driver lets you select a file bysearching 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 servicesto bypass the need for having access rights to the remote system.

c. Whn reporting on information stored in amainframewithout standard data connectivitythat can provide XML text files.

Report Processing Strategies—Learner’s Guide102

Page 115: Boc330 en Col91 Fv Part Ltr

Lesson summaryAfter completing this lesson, you are now able to:

• Use XML and web services data• Use a transform in XML exporting

103Using XML and Web Services Data—Learner’s Guide

Page 116: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guide104

Page 117: Boc330 en Col91 Fv Part Ltr

Answer Key

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

105Answer Key—Learner’s Guide

Page 118: Boc330 en Col91 Fv Part Ltr

Report Processing Strategies—Learner’s Guide106

Page 119: Boc330 en Col91 Fv Part Ltr

Quiz: Report processingPage 16

1. Why is understanding the multi-pass report processing architecture important?

Answer: Multi-pass report processing architecture is important to help youmake processingoptimized 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/BottomN and for hierarchical grouping.

6. WhenworkingwithManual Running Totals, why is placement of the formulas on the reportso important?

Answer: Placement of these formulas allows you to separate evaluation and display of therunning 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 endof pass 2 and for reports without Total Page Count, eliminates the need for pass 3.

107Answer Key—Learner’s Guide

Page 120: Boc330 en Col91 Fv Part Ltr

Activity: Defining subreportsPage 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 drillsdown on the hyperlink.

3. Unlinked subreports are free-standing reports; the data is not in any way coordinated withthe data of the primary report.

Report Processing Strategies—Learner’s Guide108

Page 121: Boc330 en Col91 Fv Part Ltr

Quiz: Using subreportsPage 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 mainreport) 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 fromone report to another by a linked subreportwith parameterand 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 multipleviews 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 amenu.What is the differencebetween the menu options Edit Subreport and Format Subreport?

Answer: Edit Subreport displays theDesignView tab of the subreport object, while FormatSubreport 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 thatshould be on the report.

109Answer Key—Learner’s Guide

Page 122: Boc330 en Col91 Fv Part Ltr

Quiz: Creating complex formulasPage 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 executedrepeatedly 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 doesLooping through an array have over the branching control structures (Select Case or IfThen Else)?

Answer: Looping through an array is easier to update (no need to add Else If or Caseclauses; add to the array). Arrays can be set up as global variables and reused in otherformulas.

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, usuallythe same as the number of elements in the array.

5. A parameter that accepts multiple discrete values is:

Answer:a. An array

Report Processing Strategies—Learner’s Guide110

Page 123: Boc330 en Col91 Fv Part Ltr

Quiz: Using custom functionsPage 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:

Report Custom FunctionsRepository Custom Functions

Available in the current report onlyAvailable across multiple reports

Are editableCannot be edited

3. Can the manual running total formulas be converted to custom functions? Why? or Whynot?

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 havea formula which performs the business logic you want to store for reuse, the Extractor isused. The Extractor logic extracts the logic from the formula.

111Answer Key—Learner’s Guide

Page 124: Boc330 en Col91 Fv Part Ltr

Quiz: Using XML and Web Services DataPage 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 remotesystem.

Answer: False. You are not able to access the data directly, but aweb service can be providedallowing 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 bysearching 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 amainframewithout standard data connectivitythat can provide XML text files.

Report Processing Strategies—Learner’s Guide112