Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Copyright
2009 SAP BusinessObjects. All rights reserved. SAP BusinessObjects owns the following United States patents, which may cover products that are offered and licensed by SAP BusinessObjects and/or affliated companies: 5,295,243; 5,339,390; 5,555,403; 5,590,250; 5,619,632; 5,632,009; 5,857,205; 5,880,742; 5,883,635; 6,085,202; 6,108,698; 6,247,008; 6,289,352; 6,300,957; 6,377,259; 6,490,593; 6,578,027; 6,581,068; 6,628,312; 6,654,761; 6,768,986; 6,772,409; 6,831,668; 6,882,998; 6,892,189; 6,901,555; 7,089,238; 7,107,266; 7,139,766; 7,178,099; 7,181,435; 7,181,440; 7,194,465; 7,222,130; 7,299,419; 7,320,122 and 7,356,779. SAP BusinessObjects and its logos, BusinessObjects, Crystal Reports, Rapid Mart, Data Insight, Desktop Intelligence, Rapid Marts, Watchlist Security, Web Intelligence, and Xcelsius are trademarks or registered trademarks of Business Objects, an SAP company and/or affiliated companies in the United States and/or other countries. SAP is a registered trademark of SAP AG in Germany and/or other countries. All other names mentioned herein may be trademarks of their respective owners.
C O N T E N T S
About this Course
Course introduction.....................................................................................................ix Course description.........................................................................................................x Course audience.............................................................................................................x Prerequisites...................................................................................................................x Level, delivery, and duration.......................................................................................x Applicable certifications and designations................................................................x Course success factors..................................................................................................xi Course setup..................................................................................................................xi Course materials...........................................................................................................xi Learning process..........................................................................................................xii
Lesson 1
Report Processing
Lesson introduction.......................................................................................................1 Multi-pass reporting......................................................................................................2 The Report Processing Model ..............................................................................2 What is processed in pre-pass 1...........................................................................3 Pass 1 processing....................................................................................................4 Pre-pass 2 processing.............................................................................................4 Pass 2 processing....................................................................................................5 Pass 3 processing....................................................................................................5 Activity: Sorting and totaling in the multi-pass process..................................6 Applying evaluation time functions...........................................................................9 Evaluating time functions.....................................................................................9 Using evaluation time functions .........................................................................9 Creating a manual running total........................................................................10 Activity: Using evaluation time functions........................................................11 Using a dynamic array................................................................................................13 Static vs. dynamic arrays.....................................................................................13 Creating a dynamic array....................................................................................13 Activity: Creating an array dynamically..........................................................14 Quiz: Report processing..............................................................................................16 Lesson summary..........................................................................................................17
iii
Lesson 2
Using Subreports
Lesson introduction.....................................................................................................19 Defining subreports.....................................................................................................20 Subreports.............................................................................................................20 Identifying typical uses for subreports.............................................................20 Processing considerations for subreports.........................................................21 Comparing linked vs. unlinked subreports.....................................................22 How subreport linking works............................................................................22 On-demand subreports.......................................................................................23 Activity: Defining subreports.............................................................................23 Creating an unlinked subreport................................................................................24 Using a pre-existing report as a subreport.......................................................24 Using the Report Wizard to create a subreport...............................................25 Activity: Using the Report Wizard to create a subreport...............................26 Modifying a subreport.........................................................................................27 Activity: Modifying a subreport........................................................................30 Creating a linked subreport.......................................................................................32 Creating links to subreports ..............................................................................32 Activity: Creating a linked subreport................................................................34 Creating on-demand subreports................................................................................36 Creating an on-demand subreport ...................................................................36 Adding captions to subreports...........................................................................37 Activity: Creating on-demand subreports........................................................38 Using shared variables with subreports...................................................................41 Using shared variables with a subreport .........................................................41 Activity: Using shared variables with subreports...........................................42 Linking unlinkable data..............................................................................................43 Linking unlinkable data with subreports.........................................................43 Creating links to unlinkable data.......................................................................43 Activity: Linking unlinkable data with subreports.........................................44 Quiz: Using subreports...............................................................................................46 Lesson summary..........................................................................................................47
Lesson 3
iv
Activity: Using loop control structures.............................................................55 Using loop control structures with arrays...............................................................57 Determining the size of an array........................................................................57 Activity: Determining the size of an array (1)..................................................58 Activity: Determining the size of an array (2)..................................................59 Looping through an array...................................................................................60 Activity: Looping through arrays......................................................................61 Quiz: Creating complex formulas.............................................................................63 Lesson summary..........................................................................................................64
Lesson 4
Lesson 5
Answer Key
Quiz: Report processing............................................................................................107 Activity: Defining subreports .................................................................................108 Quiz: Using subreports.............................................................................................109 Quiz: Creating complex formulas...........................................................................110 Quiz: Using custom functions..................................................................................111 Quiz: Using XML and Web Services Data .............................................................112
vi
Lesson 3
AgendaLearners Guide
vii
viii
ix
Course description
Crystal Reports 2008 is a powerful, dynamic, actionable reporting solution that helps you design, explore, visualize, and deliver reports via the web or embedded in enterprise applications. This one-day instructor-led course is designed to give you comprehensive skills and in-depth knowledge required to plan and create reports that will help you analyze and interpret important nformation. As a business benefit, you will find that your increased understanding of report processing, formulas, custom functions and subreports will help you make more effective report design decisions and create more efficient reports.
Course audience
The Report Processing Strategies course builds on knowledge and skills acquired though experience using Crystal Reports or from previous courses.
Prerequisites
To be successful, learners who attend this course should have attended the following offerings: Crystal Reports: Report Design I Fundamentals of Report Design Crystal Reports: Report Design II - Business Reporting Solutions To be successful, learners who attend this course should have the following experience: Knowledge of Windows conventions Basic computer skills Experience using a web browser Basic database concepts
Course setup
Refer to the setup guide for details on hardware, software, and course-specific requirements.
Course materials
The materials included with the course materials are: Name card Learners Guide The Learners Guide contains an agenda, learner materials, and practice activities. The Learners Guide is designed to assist students who attend the classroom-based course and outlines what learners can expect to achieve by participating in this course. Evaluation form At the conclusion of this course, you will receive an electronic feedback form as part of our evaluation process. Provide feedback on the course content, instructor, and facility. Your comments will assist us to improve future courses.
xi
Additional resources include: Sample files The sample files can include required files for the course activities and/or supplemental content to the training guide. Online Help Retrieve information and find answers to questions using the online Help and/or users guide that are included with the product.
Learning process
Learning is an interactive process between the learners and the instructor. By facilitating a cooperative environment, the instructor guides the learners through the learning framework.
Introduction
Why am I here? Whats in it for me? The learners will be clear about what they are getting out of each lesson.
Objectives
How do I achieve the outcome? The learners will assimilate new concepts and how to apply the ideas presented in the lesson. This step sets the groundwork for practice.
Practice
How do I do it? The learners will demonstrate their knowledge as well as their hands-on skills through the activities.
Review
How did I do? The learners will have an opportunity to review what they have learned during the lesson. Review reinforces why it is important to learn particular concepts or skills.
Summary
Where have I been and where am I going? The summary acts as a recap of the learning objectives and as a transition to the next section.
xii
Lesson 1
Report Processing
Lesson introduction
Understanding how reports are processed by Crystal Reports will help you optimize your reports for efficient processing. After completing this lesson, you will be able to: Describe multi-pass reporting Use evaluation time functions Use a dynamic array
Multi-pass reporting
Crystal Reports uses a three-pass reporting method to generate reports. In this unit you will learn what happens during each step of this process. After completing this unit, you will be able to: Describe the Report Processing Model Describe what a pass is Describe the stages of the Report Processing Model
As a general rule Crystal Reports processes the easier report components of the report first and the more complex ones later. Depending on the complexity of the report Crystal Reports may make one, two, or three passes over the data. This feature allows for complex reporting and formula manipulation.
Crystal Reports processes a report top to bottom and left to right. Formulas placed in the top left of the Report Header process first and those placed in the lower right of the Report Footer process last. Understanding the Report Processing Model is important as it helps you make report design decisions that optimize processing. The Performance Information dialog box on the Report menu provides you with information about how many passes a report requires.
If no database or group field is included in the formula, the formula is evaluated before the program reads database records.
Pass 1 processing
After the BeforeReadingRecords process, Crystal Reports begins reading the database records. During the record reading process, the following occurs: Record retrieval Where possible, record selection and sorting are pushed down to the database in this step. Evaluation of recurring formulas Recurring formulas are those that contain database fields but do not contain references to subtotals or summary information. This evaluation time is known as WhileReadingRecords. Formulas that contain references to subtotals or summary information are processed in the second pass. Application of the record selection locally If the record selection is too complex to be pushed down to the database, Crystal Reports applies it in this step. Referencing the SQL query generated by Crystal Reports indicates whether the record selection formula has been pushed down to the database or if additional selection needs to be made once records are retrieved. Sorting, grouping, and totaling In this step, Crystal Reports sorts the records, separates them into groups, and then calculates the subtotals and summaries needed for each group. Crosstab, chart, and map generation Only crosstabs, charts, and maps that are based entirely on database fields and recurring formulas are generated in pass 1. If these objects include running totals and/or PrintTime formulas, they are generated in pass 2. Storage of saved data After the totaling process is complete, all of the records and totals are stored in memory and to temporary files. Unless the report is refreshed, Crystal Reports does not read the database again, but instead uses this saved data during all subsequent processing.
Pre-pass 2 processing
During pre-pass 2, Crystal Reports orders the groups in the report for Top N, Bottom N, or hierarchical grouping. The records are not read in this process, instead Crystal Reports only looks at group instances from pass 1, and takes the Top N as appropriate, or orders the groups based on the hierarchical grouping settings specified.
Pass 2 processing
Crystal Reports enters the second pass through the data to format pages. The pages are formatted on demand. This means that Crystal Reports does not format a page until it is requested by the user, or until it is required for the total page count in pass 3. During page formatting, Crystal Reports does the following: Group selection formulas Crystal Reports enters the second pass through the data to format pages. For example:
GroupName ({Customer.Country}) = "Canada"
Running totals Calculation of formulas marked WhilePrintingRecords These are formulas that contain references to subtotals or summary information, also known as PrintTime formulas. The evaluation time is known as WhilePrintingRecords. Crosstabs, charts, and maps Crosstabs, charts, and maps that include running totals and/or PrintTime formulas, and charts that are based on crosstabs are generated in pass 2. OLAP grids Subreports Each subreport must repeat the entire multi-pass process to produce each report. This is important to keep in mind when adding subreports to your reports as each subreport adds processing overhead to a report. Generation of pages on-demand Page on-demand allows for pages on a report to be in a form ready for viewing and/or printing when the user requests it. Subtotals, grand totals, and summaries may appear to be incorrect if the report has a group selection formula. This occurs because the grand totals and summaries are calculated during pass 1, but the group selection formula filters the data again in pass 2. Running total fields can be used instead of summaries to total data in reports with a group selection formula.
Note: Although subreports appear in pass 2 in the flow chart, you can use on-demand subreports to ensure that your main report remains a single-pass report. With on-demand subreports, Crystal Reports must still make a second pass through the data; however, this second pass does not begin until you drill down on the subreport. Consequently, you can increase the performance of reports that contain subreports by using on-demand subreports.
Pass 3 processing
In the third and final pass, the total page count is determined. This applies to reports that use the total page count, or Page N of M special fields.
Instructions
1. Open the report titled Multi-pass.rpt in the course resources. 2. Insert a subtotal and grand total of Last Years Sales. Label the grand total as Grand Total. 3. Create a grand total using the Running Total Expert and place it beside the grand total. Label this grand total as Running Total. Both grand totals will be $850,630.63. 4. Save the report as Multi-pass-Totals.rpt to My Documents. Note: You will save all subsequent activity reports to this area. Your report should like similar to this:
5. Create a TopN report where N is equal to 3 and exclude Others. 6. Save the report as Multi-pass-TopN.rpt. 7. Compare the two grand totals. The one labeled Grand Total equals $850,630.63. The one labeled Running Total equals $830,862.92, which is a difference of $19,767.71.
Why are they different? Your report should look similar to this:
8. Remove the TopN sort and create a group selection formula that only includes those groups whose subtotals are greater than $100,000. 9. Save the report as Multi-pass-Group Selection.rpt. 10.Compare the two grand totals. The one labeled Grand Total equals $850,630.63. The one labeled Running Total equals $758,862.92, which is a difference of $91,767.71. Why are they different? Your report should look similar to this:
The BeforeReadingRecords function forces a formula to be evaluated during Pre-pass 1. The formula is evaluated before the program reads database records. When this function is used in a formula, the Formula Checker returns an error message if you attempt to include elements in the formula (database fields, groups, and so on) that must be evaluated at a later time (while reading or while printing records).
WhileReadingRecords WhileReadingRecords forces the formula to be evaluated while the program reads database
records. This happens during Pass 1. When this function is used in a formula, the Formula Checker returns an error message if you attempt to include elements in the formula (groups, page number fields, and so on) that must be evaluated at a later time (while printing records).This function can also be used to force a formula that includes no database fields and no group fields to process while reading records instead of before reading records.
WhilePrintingRecords WhilePrintingRecords forces the formula to be evaluated while the program prints database
records. This happens during Pass 2. This function can also force a formula that includes no database fields and no group fields to process while printing records instead of before reading records. It also forces a formula that includes database fields to process while printing records instead of while reading records.
EvaluateAfter
This function forces one formula to be evaluated after another. For example, two separate formulas in your report may have the same evaluation time (BeforeReadingRecords, WhileReadingRecords, or WhilePrintingRecords), or they appear in the same section of the report and, therefore, are automatically evaluated while records are printing. In such cases, it is often unclear which formula is evaluated first. In many situations, it is irrelevant which formula is evaluated first. However, some situations may require that one formula be evaluated after another. For instance, one formula may set the value of a variable while the other formula reads the value of that variable. The EvaluateAfter function can be used to force the second formula to be evaluated after the first formula has completed.
Reset
The Reset formula initiates the variable and assigns it the value of zero. This formula is typically placed in a headers section, such as, Page Header, Report Header, or Group Header.
WhilePrintingRecords; Global NumberVar nRT := 0;
10
Evaluate
The Evaluate formula increases the value of the variable. This formula is typically placed in the Details section.
WhilePrintingRecords; Global NumberVar nRT := nRT + (value);
Display
The Display formula shows the current value of the variable on the report. This formula is typically placed in a footer section, such as, Page Footer, Report Footer, or Group Footer.
WhilePrintingRecords; Global NumberVar nRT;
Instructions
1. Open the report titled EvalTimeFunctions.rpt in the course resources. 2. Create a formula to reset the running total. Formula Name: Reset.
Global Currencyvar salesRT:= 0;
3. Place the @Reset formula in the Report Header section. 4. Create a manual running total field that sums Last Years Sales. Formula Name: Evaluate.
Global Currencyvar salesRT:= salesRT + {Customer.Last Years Sales}
5. Insert @Evaluate in the Details section beside Last Years Sales. 6. Create a formula to display the running total. Formula Name: Display .
Global Currencyvar salesRT;
7. Place the @Display formula in the Report Footer section. 8. Save the report as EvalTimeMRT1.rpt. 9. Compare the last Details section value for the Evaluate formula with the Display formula in the Report Footer. Are they the same? Why? Why not? 10.Add the WhilePrintingRecords evaluation time to the beginning of each of the formulas.
WhilePrintingRecords;
11.Save the report as EvalTimeMRT2.rpt. 12.Compare the last Details section value for the Evaluate formula with the Display formula in the Report Footer. Are they now the same? Why? Why not? 13.Place the Reset formula in the Group Header section.
11
14.Place the Display formula in the Group Footer section and format field as Bold. 15.Save the report as EvalTimeMRT3.rpt. Your report should look like this:
12
Declare
The declare formula declares the array, defines the number of elements within the array, and creates a counter variable. The Redim x[n] function is used here to set the size of the array. Re-dimension the array x to size n, where x is an array and n is a positive whole number specifying the new size of n. This formula is typically placed in a headers section, such as, Page Header, Report Header, or Group Header.
WhilePrintingRecords; Global DataType Array Array_Name;
13
Populate
The populate formula populates the elements of the array. This formula is typically placed in the Details section.
WhilePrintingRecords; Global NumberVar Counter_Name := Counter_Name +1; Global DataType Array Array_Name; Array_Name[Counter_Name]:= {field};
Display
The display formula shows the final result of the array. This formula is typically placed in a footer section, such as Page Footer, Report Footer, or Group Footer.
WhilePrintingRecords; Global DataType Array Array_Name; Join(Array_Name, ,)
Instructions
1. Create a new report using the Supplier table from the Xtreme database. Do not include any fields in this report. 2. Create a formula called DeclareArray that declares an array to store Countries of Supplier table. 3. Set this array to store the number of countries found in the data. Tip: Use DistinctCount to determine the size of the array. 4. In the same formula, declare a counter assigned to zero.
Global NumberVar nCounter := 0;
5. Create a second formula called PopulateArray that checks to see if the Country for the current record is already in the array. If not, it increments the counter and assigns the next element in the array to the Country field value. 6. Create a third formula called DisplayCountries. The result of this formula should be a string that says We have suppliers in followed by a list of all the array elements. Each element should be separated by a comma. 7. Add these fields to your report so that you only see the result of the array in the report footer. 8. Save this report as DynamicArray.rpt. Your report should look similar to this:
14
15
16
Lesson summary
After completing this lesson, you are now able to: Describe multi-pass reporting Use evaluation time functions Use a dynamic array
17
18
Lesson 2
Using Subreports
Lesson introduction
Subreports enable you to create one report that provides all the information you need instead of creating multiple reports. You can create freestanding reports based on tables that are not related to those of the main report, or you can link the subreports to the main report data. After completing this lesson, you will be able to: Define subreports Create an unlinked subreport Create a linked subreport Create an on-demand subreport Use shared variables in a subreport Link unlinkable data
19
Defining subreports
This lesson examines subreports. You will learn and practice applying subreports and features to your reports. After completing this unit, you will be able to: Define subreports Identify typical uses for subreports Describe processing considerations for subreports Compare linked vs. unlinked subreports Describe how subreport linking works Define on-demand subreports
Subreports
A subreport is a report within a report. The process for creating a subreport is similar to the process of creating a regular report. A subreport can have most of the characteristics of a report, including its own record selection criteria. The differences between a subreport and a main or primary report are that a subreport: Is inserted as an object in a primary report; it cannot stand on its own (although a subreport can be saved as a primary or main report) Can be placed in any report section and the entire subreport will print in that section Cannot contain a subreport
20
The link fields contain similar data. The link fields are the same length. Linking tables is rarely a problem. However, there are some circumstances in which you cannot coordinate data from different tables because the data does not meet the linking criteria. 3. Present different views of the same data within a single report. Subreports can be used to provide a different view of the data in the primary report. For example, you might want to show summary values at the top of a report and details at the bottom. This can be done in a variety of ways. The two easiest methods are: Creating the summary report as the primary report and the details report as the subreport. In this method, the details subreport would be placed in the Report Footer section. Creating the details report as the primary report and the summary report as the subreport. In this method, the summary report would be placed in the Report Header section. 4. Perform one-to-many lookups from a field that is not indexed on the lookup field.
Note: This may not always be the most efficient means for one-to-many lookups.
21
2. If you are passing values from the subreport to the main report with shared variables, you need Crystal Reports to first evaluate the shared variable in the subreport before it calls it from the main report. To accomplish this, place the subreport in a main report section above the section containing the formula that calls the shared variable. 3. Page Headers belong to individual pages and therefore cannot span more than one page. This can be an issue when a subreport is placed in the Page Header section of a main report. If the subreport is too large to fit on one page, the following message is displayed: The page size is not large enough to format the contents of an object.
22
When you run the report, the program finds the first customer record it needs and passes the Customer ID value from that record to the subreport parameter field. The Orders subreport is processed. Since the subreport selection formula selects only those records in which the Customer ID value is equal to the parameter field value, and since that parameter field value is equal to the Customer ID in the first record in the primary report, the subreport contains only those records that have the same customer ID. Namely, those records that are orders for the first customer. When the subreport is finished, the program locates the second record it needs in the primary report, prints the customer data, and then passes this customers ID number to the parameter field. The program then runs a subreport including only those order records for the second customer. The process continues until the report is finished. All of this parameter field manipulation takes place behind the scenes. You pick the fields that link the primary report with the subreport and the program does the rest. The values are passed without the parameter field prompting you for a value.
On-demand subreports
On-demand subreports can be especially useful when you want to create a report that contains multiple subreports. In this case, you can choose to have these subreports appear only as hyperlinks. The actual data is not read from the database until the user drills down on the hyperlink. Only data for on-demand subreports that are actually viewed is retrieved from the database, making the subreports much more manageable.
Note: Data for an on-demand subreport is not saved unless the subreport is actually open in a preview window.
2. With subreports, the actual data is not read from the database until the user drills down on the hyperlink. 3. subreports are free-standing reports; the data is not in any way coordinated with the data of the primary report.
23
2. Select Choose an existing report and enter the name. If you do not know the name of the subreport, click the Browse button and locate it in the dialog box. 3. In the Report Name text box, enter the name and path of the report, or click Browse and choose the report from the dialog box that opens. 4. From the Insert Subreport dialog box, click OK.
24
The program displays a rectangular object placement frame. 5. Move the top margin of the object frame into the section where you want the object and click once to place it. The program places the subreport object into that section and increases the size of the section vertically, if required. The program creates a subreport design tab labeled with the subreport name. 6. If you need to edit your report, click the subreport design tab and modify your subreport as you would any other report. You can suppress any sections in the subreport that you do not want to display. 7. Preview your subreport. Two options exist when previewing your subreport. If you click Print Preview while in the subreports Design tab, you can preview just the subreport. If you want to preview the subreport as part of the main report, click Print Preview from the primary reports Design tab.
Note: Subreports do not contain Page Header or Page Footer sections.
25
8. Preview your subreport. Two options exist when previewing your subreport. If you click Print Preview while in the subreports Design tab, you can preview just the subreport. If you want to preview the subreport as part of the main report, click Print Preview from the primary reports Design tab.
Instructions
1. Open SubreportsWizard.rpt. 2. Using the Report Wizard, insert a subreport based on the Mountain Bikes Inc. database. Note: You need to create a connection to the MountainBike.mdb found in the Lesson 5 folder of the Activity Resources or in the Data_Sources folder in the course resources. Use an Access/Excel (DAO) connection. 3. Include the fields that give you the following information on your report: CONAME, CITY, LASTYRSALE. 4. Place the subreport in the Report Footer of the main report, so the subreport data appears after the main report data. 5. Save the report as SubreportsUnlinked.rpt. The last page of your report, showing the subreport data, should look similar to this:
26
Modifying a subreport
Once you have created and inserted your subreport, you may want to make some modifications to it. Applying object formatting or section formatting within the subreport is the same as with any other report. You can also add formatting to the subreport placeholder. Items such as the border, fonts and subreport labels can be formatted or changed. To edit a subreport, access the subreport design tab and make changes to the report just as you would any other report. Any of the sections and objects on the report can be formatted.
To format a subreport
1. In either the design or preview tab of the main report, right-click the subreport placeholder.
27
2. From the shortcut menu, click Format Subreport. The Format Editor opens.
28
To edit a subreport
1. From either the design tab or the preview tab of the main report, right-click the subreport placeholder.
29
2. Click Edit Subreport. The subreport design tab opens. Note: Notice that the subreport design tab has the name of the subreport on the tab itself. It can be changed on the Subreport tab of the subreport Format Editor. 3. Now you can apply formatting to the subreport objects or sections.
Instructions
1. Open SubreportsUnlinked.rpt. 2. Format the subreport so there is no distinction between the main report and the subreport. When previewed, they should appear as though they are one main report. 3. Save the report as SubreportsFormatted.rpt. The Report Footer of your main report should look similar to this:
30
31
32
2. Select one of the available options: Choose an existing report Browse to an already-created subreport. Create a subreport with the Report Wizard Enter a name for the report in the Report Name text box. Click the Report Wizard button. Create the subreport and return to the Insert Subreport dialog box. 3. To link the subreport to the main report, click the Link tab. 4. Select the subreport you want to link to from the For subreport drop-down list. Typically, this text box is grayed out because the subreport you just selected or created is the default. 5. Select the field you want to use as the link field in the primary report from the Available Fields list. 6. Click the > button. The selected field appears in the Field(s) to link to list. 7. Select the subreport field you want to link to the containing report from the Select data in subreport based on field list. The program creates a parameter field in the subreport that retrieves a value from the primary report. The record selection in the subreport is based on this value. Note: If you need to link on more than one field, repeat steps 5-7. 8. Click OK when done.
33
The program displays a rectangular placement field. 9. Drag the object frame into the position you want the subreport to appear in your main or primary report. When you run the report, the program coordinates the data from the primary report and subreport based on the field you linked on. Note: If you would like to edit the subreport links, highlight the subreport placeholder, right-click and choose Change Subreport Links.
Instructions
The current report includes a subreport that needs to be better integrated. Users of this report should not notice the difference between the main report and the subreport. 1. Open SubreportsFormatted.rpt. 2. Link the subreport to the main report for each region. Note: The Customer.Region field in the Xtreme database contains comparable information to the Customer.State field in the MountainBike.mdb. 3. Format the subreport so it blends in with the main report. 4. Blank sections and subreports should be suppressed. 5. Save the report as SubreportsLinked.rpt. Your report should look similar to this:
34
35
You can place a caption on the placeholder for a subreport such as Click here for more details. A formula can be used to display the caption in the subreport placeholder.
36
5. Click OK. 6. Preview the report. Note: Remember that you can also specify a subreport to be on-demand when you create a new subreport by choosing the on-demand subreport option from the Insert Subreport dialog box.
37
Using the Xtreme database, this formula would give you a caption like More Information About Pathfinders or More Information About Rockshocks for Jocks. 6. Click Check to check your formula for errors. If the program finds an error, a message box detailing the nature of the error is displayed. 7. After fixing any errors, click Close. The program returns you to the Format Editor. 8. Click OK to return to the report. Note: A tab text formula is only evaluated when you drill down on a subreport. If you preview a subreport separately from the primary report, the formula is not evaluated.
Instructions
The current report has a link between the main report and the subreport. The users dont want to see the subreport data all the time. They would rather click on a hyperlink to retrieve the Mountain Bike companys data. The users also want to see useful hyperlink titles and drill-down tabs. 1. Open SubreportsLinked.rpt. 2. Change the subreport to an on-demand subreport. 3. Edit the subreport and insert a text object that says No Information Available. 4. Conditionally suppress the text object so if the subreport returns no data No Information Available is displayed.
38
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:
39
If you click the Click here tab caption for BC, your report should look similar to this:
40
You then place this variable in the report footer of the subreport so the count is for all suppliers in that region. You can add a text object that indicates that this total reflects the total number of suppliers. Next, create a formula in the main report that references the shared variable. In this formula, you want to calculate the total number of customers in a region and then add that total to the subreport total. The result is the total number of contacts in the region. You are referencing the GT shared variable from the subreport and adding it to the total of the main report. The formula for the main report looks like this:
shared numbervar GT; count ({Customer.Customer Name}, {customer.Region}) + GT
Since the subreport must process first, this formula is placed in the main report group footer section under the subreport. Because of the multi-pass reporting sequence that Crystal Reports applies, subreports process near the end of Pass 2. You should split the section into an a and b section then place the subreport in a and the formula in b.
Tip: You can reference the shared variable in either the main report or in the subreport. If your report has several subreports, the shared variable can also be used in any or all of the subreports.
41
Instructions
The current report includes a subreport that is well integrated. The users would like to have subtotals for the customer count and last years sales amount. The current report includes a subreport that is well integrated. The users would like to have subtotals for the customer count and last years sales amount. 1. Open SubreportsShared.rpt. 2. Edit the subreport to create two formulas using shared variables to hold a count of customers and a total sales formula. 3. Create a formula in the main report that combines the count value from the subreport with a count of the customers from each group in the main report. 4. Create a formula in the main report that combines the sales value from the subreport with a sum of sales for each customer group in the main report. 5. Create a second Group Footer (GF 1b) and place the formulas within GF 1b. 6. Add the appropriate labels. 7. Save your report as SubreportsSharedVariables.rpt. Your report should look similar to this:
42
43
Note: The field type of the primary report field to link from determines which subreport fields are visible when choosing the field to link to. Therefore, it is important to make sure the formula in the subreport to be linked to is of the same type.
Instructions
You want to create a report that lists your customers within California and then for each customer lists the special events they attended in 1998. The problem here is that the data is unlinkable. The Customer ID field in the primary report is a number field, but in the events table, it is a string field. The customer data is stored in the Customer table within the Xtreme database. The Customer ID field is stored as a Number. The Events table within the Events.mdb contains the information on trade shows, and so on, but it stores the CustID field as a string. 1. Create the primary report using the Customer table from the Xtreme database. 2. Create a listing report of Californian customers displaying: Contact Name (combining the contacts first and last names), and Phone Number. 3. Insert a group on the Customer Name. 4. Create a subreport from Events.mdb displaying Event Type, Start Date, and City. Note: Use a Data Files connection to Events.mdb, which can be found in the Lesson 2 folder in Activity Resources or in the Data_Sources folder in the course resources. 5. Link from Customer.Customer ID to Events.CustID. 6. Format the report to be presentation quality. 7. Shade the subreport with a different color so it stands out. 8. Suppress any blank subreports. 9. Save the report as SubreportUnlinkableData.rpt. Your report should look similar to this:
44
45
46
Lesson summary
After completing this lesson, you are now able to: Define subreports Create an unlinked subreport Create a linked subreport Create an on-demand subreport Use shared variables in a subreport Link unlinkable data with subreports
47
48
Lesson 3
49
a null value. A null value is equal to nothing or not defined. You can use this function in a record selection formula to limit the report to records that have something other than a null value in the field specified. You can also use it to have the program take some action whenever it encounters a null value. Some databases support null data values and others do not. This function will not work if the active database(s) does not support null values. If the database(s) supports null values, the function can be used to reference the null values that get created as the result of a failed lookup while joining. Caution: If a field value is equal to null, it does not mean it is of zero value in the case of a number or blank in the case of a string. It is nothing or not defined. The following examples are applicable in both Basic and Crystal syntax:
IsNull({orders.ORDER AMOUNT})
If the order amount equals $500, the result is false, meaning the order amount is not null. If the order amount is equal to null, the result is true.
Not IsNull({orders.ORDER AMOUNT})
When used as a record selection formula, the report only includes those records that have something other than a null value in the {orders.ORDER AMOUNT} field. Tip: IsNull() returns FALSE if the string expression is only spaces. This situation can happen if a data entry person uses the spacebar thinking they are deleting a value in a field. You can use the TRIM function to catch these values (that is, consider them NULL). For example:
@IsNullTrimDemo // Using ISNULL and TRIM together to find blanks If ISNULL({tablename.fieldname}) Or TRIM({tablename.fieldname}) = Then True //or Value if true
50
NextIsNull() NextIsNull() is similar to IsNull() in that it tests for null values and returns a Boolean (T/F)
value. The difference is that it evaluates the specified field in the next record as opposed to the current record. You can use this function to test for the last item in a list and to take some action when you identify that last item. The following example is applicable to Crystal syntax:
If NextIsNull ({employee.EMPLOYEE ID}) Then "Last employee of record" Else ""
In an employee database with no null values in the Employee ID field, the NextIsNull() function flags the last employee on the list. Note: Using this function in a formula forces the formula to be evaluated at print time.
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:
51
52
For Loop
A For loop enables you to evaluate a sequence of expressions multiple numbers of times. This is unlike the If and Select expressions where the program passes through each expression at most once during the formula's evaluation. For loops are best when you know the number of times that the expression needs to be evaluated in advance. The syntax for For loops is demonstrated by the following example:
53
Suppose you want to reverse the {Customer.Customer Name} string. For example, City Cyclists becomes stsilcyC ytiC.
//Reverse a string version 1 Local StringVar str := ""; Local NumberVar strLen := Length ({Customer.Customer Name}); Local NumberVar I; For I := 1 To strLen Do ( Local NumberVar charPos := strLen - I + 1; str := str + {Customer.Customer Name}[charPos] ); str
Examine how this formula works assuming that the current value of the field {Customer.Customer Name} is Clean Air. The variable strLen is assigned to be the length of Clean Air, namely nine. The variable I is known as a For counter variable since its value changes with each iteration of the For loop. In other words, it is used to count the iterations of the loop. The For loop iterates nine times, during the first time, I is one, then I is two, then I is three and so on until finally I equals nine. During the first iteration, the ninth character of {Customer.Customer Name} is appended to the empty string variable str. Thus str equals r after the first iteration. During the second iteration, the eighth character of {Customer.Customer Name} is appended to str and so str equals ri. This continues until after the ninth iteration, str equals riA naelC which is the reversed string. Note: In practice, the above formula code would be well-documented with the use of comments to describe line-by-line what the formula does.
While Loop
Another looping mechanism is the While loop. A While loop can be used to execute a fixed block of statement for an indefinite amount of time. There are two different types of While loops: While...Do The While... Do loop evaluates the condition, and if the condition is true, then it evaluates the expression following the Do. When it has finished doing this, it evaluates the condition again and if the condition is true, it evaluates the expression following the Do again. It continues repeating this process until the condition is false. Do...While The Do... While loop evaluates the expression once no matter what. It then evaluates the condition, and if the condition is true, evaluates the expression again. This process continues until the condition is false.
54
The While loop supports an Exit While statement to immediately jump out of the loop. Its use is analogous to the use of Exit For in For loops. As with the For loop, the While loop when considered as an expression always returns the Boolean value True. The following is an example of a While...Do loop:
Local StringVar inString := "The 7 Dwarves"; Local NumberVar strLen := Length (inString); Local NumberVar result := -1; Local NumberVar I := 1; While I <= strLen And result = -1 Do ( Local StringVar c := inString [I]; If NumericText ) Then result := I; I := I + 1; );
The formula searches for the first occurrence of a digit in an input string. If a digit is found, it returns its position, otherwise it returns -1. In this case, the input string is set explicitly to a string constant, but it could be set equal to a String type database field instead. For example, for the input String, The 7 Dwarves, the formula returns 5, which is the position of the digit 7.
Option Loop
The Option loop statement can be used to specify the maximum number of loop condition evaluations per evaluation of a formula. This statement should only be used when the default maximum loop count of 100,000 is not sufficient for the given formula. Note: The Option Loop statement must be used before any other statements. Crystal syntax for the Option Loop is as follows:
Option Loop maxIterations
Where maxIterations = the maximum number of times you want the condition to be evaluated per evaluation of a formula. It must be a positive integer. For example:
//option loop example option loop 256; //make name upper case Local StringVar outString; Local StringVar inString := {Customer.Customer Name}; Local NumberVar I; For i:=1 to Length(inString) do outString := outString + upperCase(inString[i]); outString
If Customer.Customer Name is greater than 255, an error message is shown: A loop was evaluated more than the maximum number of times allowed.
55
Instructions
The Company wants to make its Customer ID more user-friendly. One proposal is to combine the letters of the customer name to create a new Account Code. 1. Open the CustomerList.rpt. 2. Create a formula that combines the first 15 LETTERS (only) from the customer name in uppercase. 3. If the customer name has less than 15 letters, add Xs until it has 15. For Example, Bike Planet would become BIKEPLANETXXXXX. Hint: Use a loop to check each character in the Customer Name is in range [A to Z]. 4. Save the report as UsingLoops.rpt. Your report should look similar to this:
56
Ubound
UBound returns a Number containing the largest available subscript for the given array. It is commonly used to obtain the size of an array before using a looping control mechanism to systematically manipulate elements of the array. The following example demonstrates Ubound using Crystal syntax:
Local DateVar Array dateArray; dateArray := [CDate(#12/25/1998#), CDate(#12/24/1999#)]; UBound (dateArray)
This formula returns two, the largest subscript element in the array. This function is designed to work like the Visual Basic function of the same name. Note: Unlike Visual Basic, only one-dimensional arrays are supported in Crystal Reports. Also, array indexes start at one in Crystal Reports and not zero as is the default in Visual Basic. UBound returns one for an un-initialized array variable, however, it causes an error to subscript an un-initialized array variable. The reason for this behavior is that at present Crystal Reports does not support arrays with zero elements. To work around this problem, always initialize your array variables. For example, initialize global array variables in a formula located in the report header and local array variables within the formula itself.
Split
Split takes a string that contains a number of substrings, breaks it up into a specified number of substrings and returns an array containing the substrings. The following examples are applicable to both Basic and Crystal syntax:
Split ("Chocolate Strawberry Pineapple")
Returns an array that contains three elements, "Chocolate", "Strawberry" and "Pineapple".
Split ("Chocolate//Strawberry//Pineapple", "//")
57
Returns an array that contains three elements, "Chocolate", "Strawberry" and "Pineapple".
Instructions
1. Open the DynamicArrays.rpt. 2. Use SPLIT and UBOUND functions to extract only the name of the file from the end of the FileName string. 3. Create another formula (use the same variables) which displays how deep in the directory structure the file is located. Tip: The Special field File Path and Name are identical to the formula function called Filename; both include the full path and file name. 4. Save the report as ArrayFunctions.rpt. Your report should look similar to this example, depending on where your setup (that is, the directory and the level of subfolders).
58
Instructions
Display a message for the number of countries via a parameter. 1. Open ParameterArray.rpt. 2. Create a formula to display the number of countries selected. Tip: Use online Help for more information about the IIF function if you are not already familiar with it. 3. Place the formula in the Report Header. 4. Refresh and prompt for new parameter values. 5. Test with only one country and with multiple countries. 6. Save the report as ParameterUBound.rpt. 7. Test with only one country and with multiple countries. The example report below shows results if Australia, New Zealand, Indonesia and Singapore are selected:
59
Using this code in a report where you want to extract regions results in this example. Notice the list of regions extracted at the top of the report (AL, AZ, CA, CT).
Note: This report is included as a sample in the course resources.
If the list needs to be reversed (that is, the last element should be displayed as the first item), then manual retrieval is impossible. Again using a loop is the preferred method. The code for the reversal example is:
numbervar index; stringvar display_region := ""; for index := count({?Selected Region}) to 1 step -1 do ( display_region := display_region + ", " + {?Selected Region}[index]
60
); mid(display_region,3);
Using this code in a report where you want to extract regions results in this example. Notice the list of regions extracted at the top of the report (DC, CT, CO, CA, BC, AZ, AR, AL).
Instructions
1. Create a new report including Customer Name, Region, and Last Years Sales. 2. Create a Sales Tax formula two ways: Use the Select Case control structure Use arrays and a loop Here are some sample tax rates (you do not need to do all regions, just a sample): Region Sales Tax Rate: CA - 7.25% IL - 6.25% NJ, PA - 6.00% NY - 8.50%
61
Others - assume zero 3. Compare the results and consider the advantages of each. 4. Save the report as Looping in Arrays.rpt. Your report should look similar to this:
62
63
Lesson summary
After completing this lesson, you are now able to: Use Print State functions Use loop control structures Use loop control structures with arrays
64
Lesson 4
65
Custom functions
Custom functions are procedures you create in Crystal Reports to evaluate, make calculations on, or transform data. When you use a custom function in a formula, all the operations in its definition are performed without having to specify them individually in the formula itself. Thus, the custom function provides a way to share and reuse formula logic which, in turn, makes it easier and less time consuming for users to create reports. Custom functions and formulas are alike in structure and are created in a similar interface. But it is important to understand the differences between them. Formulas are typically used to create calculated fields on a report, format text, manipulate strings, or extract part of date fields. Custom functions are business logic that you create to perform routine tasks in formulas. They are used as the basis for a formula but on their own, custom functions do not change the way data appears or is represented on a report. When you use a custom function in a formula, all the operations in its definition are performed without you having to specify them individually in the formula itself. Thus, the custom function provides a way to share and reuse formula logic which, in turn, makes it easier and less time consuming for users to create reports. For example, suppose you are designing a series of reports from a database that stores department information with three-letter code names, but you want the actual department names to appear in your reports. Creating a formula to transform the data would work, but youd have to copy the formula logic from report to report until youd completed the series. It is much easier if you extract the logic that does the data transformation and save it as a custom function. You can add that custom function to each report in your series without having to re-enter the text.
Note: Because custom functions are designed for use across multiple reports, a custom function cannot contain any database fields.
A custom function cannot be placed directly in a report. It must be used as a part of a formula.
66
Custom functions can replace sections of formula logic common to many different formulas that, in turn, may be used in many different reports. Custom functions can be shared between reports by storing them to the BusinessObjects Enterprise repository and adding them to reports as needed. Custom functions can reduce the need for users to write formulas themselves. You can provide them with the formula logic they need in a custom function. Existing formulas can be converted to custom functions using the Extract Custom Function from the Formula dialog box. Custom functions can have arguments, which makes them flexible. You can define help text and default argument values for custom functions, which makes it easier for users to use them. Custom functions, unlike User Function Libraries (UFLs) to which they are related, are saved as part of the report file (.rpt) and dont have any external dependencies. Custom functions are stateless. The same input always yields the same result. When you modify a custom function, you can update the repository copy and refresh each report without having to find and open the formulas that use the function.
67
Enter the custom function directly as part of your formula logic in the Formula Editor. Choose a custom function to supply formula logic in the Formula Expert. The custom function you include can be newly created for the report youre working on or added from the BusinessObjects Enterprise repository.
68
69
Note: Alternatively, you could select a custom function that is stored in the repository. If you select a repository custom function, that custom function is added to the current report and is added to the Report Custom Function list. If that custom function requires other custom functions from the repository, they can be added as well. 3. Toggle the properties of the function by clicking the Toggle properties button. 4. In the Function Arguments area, specify a value for each argument in the appropriate value field. You can enter constant values directly, or you can select predefined values or report fields from the associated list. 5. Click Save. You can now use this function in a formula just as you would use a function installed with Crystal Reports.
70
Optional values
An optional value can be specified for an argument when you create a custom function.
Note: Optional values are created in the Custom Function Editor and cannot be added through the Custom Function Properties dialog box.
For example, the following formula text provides an optional value of the current date for the function called FirstDayOfMonth:
Function FirstDayOfMonth (Optional dayInMonth As DateTime := CurrentDate) As Date
The advantage of having users select an optional value instead of a default value is that, for an optional value, the value used is not determined until the custom function is executed. The
71
value is determined by the custom function itself, so if you change the value in the custom function, all the formulas based on that function change too. In the Formula Expert, optional values are displayed with their current value (the current value may be different at the time the formula is executed). The Formula Expert uses the optional value for an optional argument if no value is entered or if the Reset Values button is clicked.
Instructions
1. Open CrystalCustomFunctions.rpt. 2. Browse several pages on the report. Notice that Regions for Canada and USA are abbreviated. 3. Delete the Region field. 4. Open the Formula Workshop. 5. Create a new formula called Region Name. 6. Click the Use Expert button. 7. In the box labeled Custom Function, expand Repository Custom Functions. 8. Under your Enterprise server name Crystal Geographic, select cdExpandRegionAbbreviation. The workshop screen updates. 9. In the Function Arguments area, locate the Value column. Here is where you select inputs for the custom function. 10.For the regionAbbreviation row, click in the Value cell, select Choose Other Field and then select Customer.Region. 11.For the country row, select Customer.Country from the list. 12.Click Save. Crystal Reports prompts you with a message about these changes to this action being undoable. 13.Click Yes. Click Yes again to save the underlying custom functions. These copies are now Report Custom Functions. 14.Close the Formula Workshop. 15.Add the formula to the report. 16.Save the report as FullRegions.rpt. Your report should look similar to this:
72
syntax
This optional element of a custom function provides a list of variables representing arguments that are passed into the function when the argument is called. Multiple variables are separated by commas. An empty argList is allowed; however, the parentheses surrounding argList are not optional and must be used even when argList is empty.
[Optional] simpleType [Range] [Array] varName [:=defaultValue]
Optional Optional indicates if the argument can be omitted when the custom function is called. If an argument is optional, all subsequent arguments must be optional as well. If you supply a value for an optional argument when calling the function, then you must supply values for each preceding argument. SimpleType This is required. You can use one of:
NumberVar CurrencyVar
73
Range This is optional. It specifies if the argument is a range variable. Note: You cannot use Boolean ranges. Array This is optional. It specifies if the argument is an array variable. varName This is required. This refers to the name of the variable representing the argument. :=defaultValue This is required for optional arguments. DefaultValue is a constant or constant expression; that is, its an expression involving no variables that can be simplified at compile time to a constant value. If an optional argument is omitted when calling a custom function, then the default value for the argument is used. expressions These are required. The value returned by the Crystal syntax custom function is the value of the last expression evaluated in the expression sequence. The syntax is the same as that in Crystal syntax formulas.
Scope
Variable declarations within a custom function are local scope by default. This contrasts with variable declarations in Crystal syntax formulas, where global scope is the default.
74
These restrictions are designed to make custom functions independent of the report they are being used in.
Variables
You can use local variables and argument variables in custom functions. If you need to use a shared or global variable in your custom function, you can pass it in as an argument.
Evaluation time
Formulas are not evaluated on demand or called (that is, one formula cannot call another formula to do some processing, even through the use of global variables). For example:
Rem Formula PrintSquare Global x As Number x = 5 formula = The square of & CStr(x,0) & is & ToText ({@square, 0) & . Rem Formula Square Global x As Number formula = x * x
In this example, formula PrintSquare uses formula Square, so Crystal Reports orders the evaluations. First Square is evaluated and then PrintSquare is evaluated. When Square is evaluated, the value of the global variable x is zero, since that is the value of an uninitialized number variable. In contrast, custom functions are evaluated on demand, or called. This uses a custom function from the previous example:
Rem Formula PrintSquare formula = The square of & CStr (5,0) & is & CStr(cf9Square (5),0) + . Rem Custom Function cf9Square Function cf9Square (x As Number) cf9Square = x * x End Function
75
Using the Extract Custom Function from the Formula dialog box
When you extract a custom function from an existing formula, the program copies the formula and replaces its fields with arguments.
Note: A custom function created using the Extractor can only return simple types, like strings and integers. It cannot return arrays. To create a custom function that can return arrays, use the Custom Function Editor.
76
Select Modify formula to use a new custom function to replace the text of the formula you selected in this step with the new custom function youre creating. 5. Click OK to save the custom function to the Report Custom Functions node of the Formula Workshop. Once the custom function has been extracted and saved, you can modify it or use it in report formulas as needed. Note: You cannot add new arguments to your custom function while you are creating it in the Extract Custom Function from Formula dialog box. To add new arguments, save the custom function and modify it in the Custom Function Editor.
Instructions
You want a function that accepts a date (or date/time) value and check to see if the date falls on a weekend. If so, change the date to the nearest weekday (that is, Saturday to Friday and Sunday to Monday). 1. Open the report Extractor.rpt from the course resources. 2. Open the formula workshop and display the WeekdayShipped formula. 3. You want to re-use this logic for Required Date using a Report Custom Function. In the workshop tree, click Report Custom Functions. 4. Click the New button, and make sure the box says Custom Function Name. 5. Give the custom function the name Nearest weekday. 6. Click Use Extractor. 7. In the middle of the window, in the first row under Argument Name, change v1 to YourDateValue. 8. Tab to the Description column and enter Date field or expression to be tested for weekend. 9. Click OK. 10.Use the workshop tree to compare your Report Custom Function to the original formula named, @WeekdayShipped. 11.Use your new Custom Function Nearest weekday in the following formula. Create a new formula called WeekdayRequired. 12.In the Formula Editor, from the Toolbar use the Expert button. 13.In the box labeled Custom Function, select Nearest weekday.
77
14.In the Function Arguments window under Value, from the list of available choices, select Choose Other Field. 15.Select Required Date from the Choose Field window, and then click OK. 16.Click Save and Close to save the formula and to close the formula workshop. 17.Place the formula WeekdayRequired onto the report. 18.Format the WeekdayRequired field to look like the other two fields on the report. 19.Save the report as NearestWeekday.rpt. Your report should look similar to this:
78
Note: If the Category box is not available, the custom function has been added to the BusinessObjects Enterprise repository and is therefore locked from editing. Right-click the custom function, and then click Disconnect from Repository. After adding a category, you can add the custom function back to the BusinessObjects Enterprise repository.
Instructions
1. Open NearestWeekday.rpt. 2. Open the Formula Workshop. 3. In the workshop tree, select the NearestWeekday Report Custom Function. 4. Click Toggle Properties Display on the toolbar.
79
5. Enter My Date Functions in the Category field. 6. Enter your name in the Author field. 7. Enter a summary describing the function in the appropriate field. 8. Click Save. 9. Click Add to Repository on the toolbar. The function is added to the repository. Notice that all of the fields in Properties cannot be edited now. 10.Click Toggle Properties Display again. Notice that the function cannot be edited. 11.Look at the workshop tree. Notice the icon next to the NearestWeekday custom function has changed. 12.Expand Repository Custom Functions. Notice the folder My Date Functions now contains NearestWeekday. 13.Close the Formula Workshop. 14.Save the report as AddToRepository.rpt. Your report should look similar to the following:
80
81
Instructions
1. Open AddToRepository.rpt, the report saved at the end of Activity: Saving a custom function to the repository. 2. Open the Formula Workshop. 3. Select Report Custom Functions from the Workshop Tree. 4. Right-click and select New to create a new custom function. 5. Enter ConvertUSDtoEuros in the name box, and then click Use Editor. 6. Enter the function text:
Function (currencyvar AmountUSD) //Accepts US Dollar Amount //Returns value in Euro //Edit here to update exchange rate local numbervar EurosPerDollar:=0.90; AmountUSD * EurosPerDollar
7. Save the function. 8. Create a new formula called OrderAmountinEuro. 9. Open the Expert by clicking the Use Expert button on the toolbar.
82
10.In the Custom Function Tree locate Report Custom Functions, and then select ConvertUSDtoEuros. 11.In the Function Arguments window, click the cell under Value. Select the Select Field or Enter Value option, and open the list. 12.In the Field Tree, select Choose Other Field, and then double-click Order Amount. 13.Click Save and Close. 14.Add OrderAmountinEuro to the report. 15.Format the Euro value appropriately. a. Right-click the field, and then click Format Field on the shortcut menu to open the Format Editor. b. On the Number tab, click Custom Style in the Style area (if required), and then click Customize. c. In the Custom Style dialog box, click the Currency Symbol tab. d. Highlight the currency symbol in the Currency Symbol edit field. e. On the number keypad area of your keyboard, press and hold the Alt key, enter 0128, and then release the Alt key. The Euro currency symbol appears. (The combination of numbers is the ASCII code for the Euro symbol and must be generated on the number keypad to appear.) f. Click OK twice. You have just written a custom function with the Formula Editor and used that custom function in a formula. In part 2 of the activity you will add the newly created custom function to the repository and use it on another report.
Instructions
1. Re-open the Formula Workshop. 2. Access the properties of the ConvertUSDtoEuros and add a category, author, and summary. 3. Add the function to the repository. Note: You now are unable to edit the function. 4. Close the Formula Workshop. 5. Save the report as ModifyFunction.rpt and then close the report.
83
6. Create a new report from the Customer table. In the Details section add the fields: Customer Name Last Year's Sales 7. Create a formula called Sales in Euros. 8. Click the Use Expert button on the toolbar to move to the properties of the formula to select the custom function. 9. From the Repository Functions use the ConvertUSDtoEuros function. 10.Choose Last Year's Sales as the Value field in the Function Arguments. When you save the formula, Crystal Reports copies the function from the repository. 11.Place the formula on the report. Format as needed. 12.Save the report as SalesInEuros.rpt. Your report should look similar to this:
Note: You have used the custom function, ConvertUSDtoEuros, on two reports. In part 3 of the activity, you will update the exchange rate for both reports.
84
Instructions
1. Open the Formula Workshop and under Report Custom Functions in the Workshop Tree select the ConvertUSDtoEuros function. 2. Right-click the function and select Disconnect from Repository. 3. Modify the exchange rate variable from 0.90 Euro to 0.70 Euro. 4. Save the formula. 5. Add the function back to the repository. 6. Click OK to the warning about modifying the function. 7. Use the Workshop Tree to confirm that the rate was changed in the repository. 8. Close the Formula Workshop. 9. Save the SalesInEuros.rpt. The report should look similar to this:
85
10.Close the SalesInEuros.rpt. 11.Re-open the ModifyFunction.rpt. 12.Under the File menu, click Options, and then click the Reporting tab. 13.Ensure the Update Connected Repository Objects on Open option is selected. OrderAmountinEuro should be updated with the new exchange rate. The report should look similar to this:
86
5. True or False. The Extractor is used when creating a formula based on a custom function.
87
Lesson summary
After completing this lesson, you are now able to: Describe a custom function Use custom functions
88
Lesson 5
89
90
4. Choose an XML data source access type: Local data source HTTP(S) data source Web Service data source
91
The following options can be selected: Use Local Data Source Select this option to connect to an XML file that you have on a local machine or a network drive. Local XML File Enter a full path and file name for your local data source, or select a file by searching for it in the Open dialog box. Use HTTP(S) Data Source Select this option to connect to an HTTP(S) data source (an XML file or XML stream that you can access from a Servlet, an ASP page, a JSP page, or another type of dynamically created web page). HTTP(S) XML URL Enter either an HTTP or an HTTPS URL for your HTTP(S) data source. When using HTTPS, user IDs and passwords that you enter in Crystal Reports are used to authenticate against the underlying HTTP provider. Specify Schema File Select this option if you want to apply a schema to the XML file you selected. Note: You must select this option and specify a schema unless the XML file contains embedded schema information. Validate XML
92
Select this option if you want the XML document validated against the schema, and you have indicated the XML file and schema. Use Web Service Data Source Select this option if you want to use a web service data source. This type of data source can be a service that you have on a local machine or a network drive that you can connect to by entering a path and file name, or it can be a service that you access from a servlet or a dynamically created web page. The URL you provide to such a source can be either HTTP or HTTPS.
93
to such a data source can be either HTTP or HTTPS. When using HTTPS, user IDs and passwords that you enter in Crystal Reports are used to authenticate against the underlying HTTP provider. The XML driver lets you type a URL and later add authentication credentials. If you have a schema (XSD) for your XML file or stream, you can specify the schema and its authentication credentials.
Note: When you use the XML driver, you can specify a schema (XSD) or Document Type Definition (DTD) of your choice, or you can use schema information embedded in the XML document. The schema is used to determine how to present the XML data within Crystal Reports. When you specify a schema to use with your XML file, the specified schema is used instead of schema information embedded in or referenced by the XML file itself.
94
Click Edit Value to change an existing parameter. Select the parameter you want to edit before you click this button. Click Remove Property to delete an existing parameter. Select the parameter you want to remove before you click this button. 9. Click Finish when you are done with the HTTP Parameters screen.
Instructions
1. Use the Customer.xml and the Customer.xsd files located in the course resources. 2. Create a new XML local data source connection that points to the Customer.xml file and the Customer schema file. 3. Create a new report that displays the Customer Name, City, and Region fields. 4. Format the report.
95
For Use Local WSDL, enter the full path and name of your web services file, or use the button adjacent to the field to search for it. For Use HTTP(S) WSDL, enter the URL that points to your web services file. If you are connecting to a Web Service secured using WS-Security, specify the policy file in this step as well. 3. Click Next. Depending on your selection in the previous step, you will see either a screen for specifying your web service, ports, and methods, or a screen for defining authentication for your web service URL. If you see the web service, ports, and methods screen, skip to step 6. 4. Enter authentication information if it is needed, and then click Next. 5. On the Web Service, Port and Method screen, choose a service, a port, and a method from the lists. 6. Click Finish. Once you can see the table created from your XML data source, you can use it to create a Crystal report in the same way you use any other data source.
Instructions
1. Launch Query as a Web Service and create a new query based on the eFashion universe. a. Click Start Programs BusinessObjects BusinessObjects Enterprise Query As A Web Service. b. In the Manage Hosts dialog box, click Add. c. In the Edit a Host dialog box, enter the appropriate information such as the name of the host machine, the URL of the host, the name of the CMS, your logon credentials, and authentication, if required, and then click OK. d. Close the Manage Hosts dialog box. e. In the Select your credentials window, enter the appropriate information such as the host machine, the name of the CMS, your logon credentials, and a password, if required, and then click OK. f. In the Query as a Web Service dialog box, select the appropriate folder (if required), and then click New Query. g. In the Web Service Name edit field of the Publish Query As A Web Service Wizard dialog box, enter a name for the query, and then click Next. h. In the Select a universe window, click the eFashion universe, and then click Next. i. Expand the Store class and add State, City, and Store name to the query.
96
j. Click Next, and then click Publish. k. Copy the WSDL URL to the Clipboard. l. Minimize or close the Query As A Web Service dialog box. 2. Create a new report from an XML and Web Services connection. a. Select the Use Web Service Data Source option and then click Next. b. Select Use HTTP(S) WDSL, paste the WDSL URL in the field, and then click Next. c. Enter your WSDL user ID and password and then click Next. d. Ensure the service, port, and method areas contain the correct information: Web Service: Query name Port: QueryAsAServiceSoap Method: runQueryAsAService e. Click Finish. f. Expand the runQueryAsAServiceResponse node. g. Select runQueryAsAServiceResponse/Table/Row and add to the Selected Tables area. h. In the parameters.runQueryAsAService.login area, enter your login name in the Enter a Value field. i. In the parameters.runQueryAsAService.password area, enter your password in the Enter a Value field, and then click OK. 3. Expand Database Fields in the Field Explorer. 4. Expand the runQueryAsAServiceResponse/table/row query result node and add the State, City, and Store name fields to the report. 5. Format the report, if desired. 6. Preview the report. 7. Save the report as Creating a report using a web service.rpt. Your report should look similar to this example.
97
98
99
This is the name that appears in the Manage XML Exporting Formats dialog box when you choose an XML format for exporting a report. 4. Click Import XML Transform to open the Open dialog box. 5. Browse through the folders to find a valid transformation and select it. 6. Indicate the extension for the exported report in the Specify the file type text field. Note: This only affects the extension of the file name. Changing the extension does not affect the file format. 7. Enter a description for the new format. This description appears in the Manage XML Exporting Formats dialog box when you choose an XML format for exporting a report. 8. Click OK twice. 9. Once the schema is imported click Save XML Transform As to save a copy of the transform to another location.
100
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.
Instructions
1. Import the Justice XML Data Model (JXDM) transform. 2. Select the jxdm.xsl file. In the Name field enter Justice Data Submission. In the Description field enter Justice data format. 3. Open offenses.rpt. 4. Export the data displayed in the sample offenses.rpt report to the standard Crystal Reports XML format. 5. Select Application as the destination. The exported report output is shown using the standard Crystal Reports XML format. 6. Close the XML output file and export the data displayed in the sample offenses.rpt to XML format, using the Justice Data Submission transform to conform the data to the Justice XML Data Model format. 7. Select Application as the destination. The offenses.rpt report has been exported to XML format, using the Justice Data Submission transform to conform the data to the Justice XML Data Model format. Note that the XML elements now show customized tags such as Offense, IncidentSubject, and PersonName, instead of GroupHeader, Section SectionNumber, and Field Name as seen with the standard XML format.
101
102
Lesson summary
After completing this lesson, you are now able to: Use XML and web services data Use a transform in XML exporting
103
104
Answer Key
This section contains the answers to the reviews and/or activities for the applicable lessons.
105
106
107
108
109
110
3. Can the manual running total formulas be converted to custom functions? Why? or Why not? Answer: No, the manual running total uses both Print State functions and global variables, neither of which are permitted in custom functions. 4. Rewrite the following formula so the business logic can be stored as a custom function.
{Customer.Last Year's Sales} * 10
Answer:
Function (currencyVar v1) v1 * 10
5. True or False. The Extractor is used when creating a formula based on a custom function. Answer: False. It is the opposite. When you are creating a custom function and already have a formula which performs the business logic you want to store for reuse, the Extractor is used. The Extractor logic extracts the logic from the formula.
111
112