Crxi Startup Guide
Crxi Startup Guide
January 2005
1
Crystal Reports XI Startup Guide
Overview
What is the Crystal Reports XI Startup Guide?
The Crystal Reports XI Startup Guide (hereafter known as “the guide”) is intended to get
competent .NET developers who are new to Crystal Reports XI or familiar with older versions,
up to speed quickly, using the product in a variety of reporting scenarios. The guide presents a
scenario-driven approach to designing and building reports with Crystal Reports XI. The guide
walks through six different reporting scenarios. The scenarios increase in difficulty and are
described below:
Scenario Description
Basic A Tabular report, designed using the Wizard, utilizing a standalone report
file deployed as part of a Windows application. In this scenario, data from a
single table is retrieved using OLE DB.
The scenarios are designed to illustrate the many powerful features of Crystal Reports XI,
including:
2
• Integration with Visual Studio.NET 2003 (all scenarios.)
• Deployment in different application environments. The Basic, Intermediate and Dynamic
scenarios demonstrate reporting in a Windows environment. The remaining scenarios
illustrate reporting in a Web environment.
• Ability to report from multiple data sources, including typed datasets, views, tables and
stored procedures. Typed datasets are used as data sources in the Sub-report and Document
scenarios. Techniques using views and stored procedures are shown in the Intermediate,
Visual, Sub-report and Document scenarios.
• Manual and Wizard-based methods for building reports. The Basic and Sub-report scenarios
generate reports using the report Wizards. The Intermediate, Dynamic, Visual and Document
scenarios create reports manually.
• Support for different report media, including report files and ReportDocument objects
(Intermediate, Sub-report, and Document scenarios).
• The Intermediate and Visual scenarios illustrate techniques for grouping and drill-down
reporting capabilities.
• The Dynamic scenario illustrates how to create dynamic cascading prompts and how to
handle data-driven images dynamically by file reference in place of database “BLOBs.”
• The Document scenario describes how to export files to different formats, including Acrobat
(PDF) and the new Editable RTF format.
Prerequisites
The guide provides the most benefit to developers familiar with Visual Basic .NET (VB .NET)
and the Microsoft ® Visual Studio .NET™ 2003 environment. All of the samples in this guide
retrieve data from the Northwind database available with SQL Server. SQL Server is commonly
used by developers writing applications with Microsoft ® Visual Studio .NET™ 2003. The
techniques demonstrated to generate reports with SQL Server data are portable to other databases,
although minor modifications may be required.
Sample Code
This guide discusses developing reporting solutions with Crystal Reports XI in depth. All of the
sample code in the guide was developed using Microsoft ® Visual Studio .NET™ 2003 and was
written in VB .NET.
The samples used in the guide build on one another, starting with the “Basic” scenario. In cases
where details are given about a common process in a previous scenario, the current scenario will
reference the previous discussion, rather than restating the process.
Completed versions of all the samples covered in this Guide are supplied in the zip file
accompanying this guide. The completed source code is divided into two projects: one for
sample reports running in a Windows application, and one for sample Web applications.
Extracting the contents main folder within the zip file the root directory of drive C:\ on your PC
will allow the samples to execute without modification. If you’d prefer to extract the contents
elsewhere, you may do, as long as you make corresponding changes to the sample code in each
scenario described in this document. The Windows samples are located in the
CRXIWindowsSamples project and can be run directly from Visual Studio. The Web samples are
located in the CRXIWebSamples project. To run the Web samples you will first have to create a
Virtual Directory called “CRXIWebSamples” on your machine pointing to the physical directory
that contains the web application files. The section How to Create a Virtual Directory to Run the
Web Sample later in this section describes how to create a virtual directory. If you prefer to
3
follow along through the Guide and create the samples yourself, extraction of the source code
from the zip file and creation of the virtual directory will not be required.
Regardless of whether you build the projects yourself or use the source code supplied in the zip
file, you must run two SQL scripts which are also contained in the zip file and extract a .udl data
link file. The samples use the Northwind database available with SQL Server 2000. All sample
reports designed to run in a Windows application use the included data link file “Northwind.udl”
as a data source at design time. All sample Web-based reports connect to the database by
supplying provider and login details using the “Database Expert” Wizard provided by Crystal
Reports XI. Creating a connection to the database is described in Appendix A.
Scripts Required to Run the Sample Reports
Certain of the sample reports rely on custom stored procedures to run. In addition, all of the Web-
based reports use a special SQL Server user account to connect to the database. Also, a new table
is used in the Dynamic scenario.
Prior to creating any of the sample reports, run the CreateSQLUserForSamples.sql script file to
create the CRReports SQL Server user account and grant it access to the Northwind database.
This script must be run by an account in the sysadmin fixed server role. Refer to the SQL Server
Books Online documentation for more information about creating SQL Server accounts.
All of the stored procedures required to run the sample reports and the T-SQL code needed to
create and populate the new table required by the Dynamic scenario are found in the
SqlScriptForSampleReports.sql file. As noted in the script file and the stored procedure
comments, only an account with execute permissions in the database will be able to create the
stored procedures. Be sure to use a login account with sufficient privileges when running the
script files.
4
How to create a Virtual Directory to run the Web samples:
To create the virtual directory on your machine necessary to run the Web application samples
included wit this Guide, follow the instructions below:
1. Bring up the Internet Information Services (IIS) applet from Administartive Tools
(available from within Control Panel). In the applet, right-click the Default Web Site
node in the tree view control on the left (you will need to expand the local computer and
Web Sites nodes for the Default Web Site node to be visible), and select Virtual
Directory from the New submenu to start the Virtual Directory Creation Wizard. In the
welcome page, click Next >.
2. Enter “CRXIWebSamples” in the Alias textbox and click Next >. The alias name will be
used to access your web application.
3. Browse to the local folder on your machine that contains the Web application files you
want the virtual directory to point to and click Next >.
4. In the Access Permission page, leave the default settings then cick Next > and Finish.
5
New Features and Procedures in Crystal Reports XI
Throughout the document, new features added to Crystal Report XI will be identified through the
use of blue text and the appearance of the Crystal Reports XI icon in the right margin next to the
text that discusses the new feature. Occasionally within the paper, Web hyperlinks may appear in
blue text as well. Unlike the new feature text highlights, these hyperlinks are underlined and the
Crystal Reports icon will not appear next to them in the right margin.
6
Basic Reporting Scenario
The Basic Reporting scenario illustrates the simplicity of adding reporting capabilities to a
Windows application. This scenario generates a report using the design-time wizards in Crystal
Reports XI. No code is necessary to generate this report. This scenario displays a report of
Customers from the Northwind database in a Windows application.
To create the sample report, open Crystal Reports XI. The Start Page will appear as shown below.
Under the New Reports area of the Start Page you can either select one of the four available
wizards to guide you through the creation/designing of your report, or you can build your report
from scratch by selecting the Blank Report option.
7
You’ll next need to specify which columns from the table should appear on the report. Click the
Next > button to select the columns to display. Select the following columns:
• CompanyName
• ContactName
• City
• Country
After selecting the columns, click the > button. The Standard Wizard form should look like the
following:
8
Click on the Next > button three times to bypass the next two optional pages, Grouping and
Record Selection. On the final page, Template, you have the option of choosing a template for the
report. The Wizard provides a list of different templates that can be applied to the report. Choose
the Gray Scale template from the list of available templates:
9
Click the Finish button to generate the report file. The report will be shown in Preview view
[under the preview tab]. Save the report as TabularReport.rpt by selecting “File | Save As….”
from the menu. Then click on the Design tab to view the report in design view as shown below
10
The template included the Report Title special field on the report. To give the report a title, go to
“File | Summary Info”. In the Title textbox, enter “Customer Listing Report” as shown below.
Uncheck the Save Preview Picture checkbox and click OK to close the Document Properties
dialog box. Then click on the Preview tab to see the report in Preview view with the newly added
title:
11
Save and Close the report. At this point, the report is created and ready to run.
The last few steps involve setting up a Windows application and form to display the report.
Open Visual Studio .NET and create a new Visual Basic Windows Application Project. Name the
new application “CRXIWindowsSamples”. Once the project is created, add a new Windows form
to the project and name it Basic.vb. Delete the default Windows form (Form1.vb) from the
project through the Solution Explorer. In the properties window, change the Text property of the
Basic form to “Basic Report Scenario”.
Next, add the TabularReport.rpt report to the project. Right-click on the project name in the
Solution Explorer window and select “Add | Add Existing Item…” from the context menu.
Change the “Files of Type” drop down to Crystal Reports (*.rpt). Browse to the
TabularReport.rpt file and select it.
Select the Basic form so that a CrystalReportViewer control can be added to it. The
CrystalReportViewer control displays a Crystal Reports report at runtime. Find the
CrystalReportViewer control in the Toolbox (it is normally located under the Windows Forms
tab). Drag and drop the control from the toolbox onto the Basic form. Set the following properties
of the CrystalReportViewer control:
12
Dock Fill
There is one more property to set before this is a complete solution. The CrystalReportViewer’s
“ReportSource” property binds the report viewer control to a specific report. Click on the
ReportSource property in the Properties window. A drop down will appear allowing for the
selection of the report file to bind to the viewer control. The TabularReport.rpt file should be
located in the CRXIWindowsSamples’s project folder. The report will be loaded at runtime into
the report viewer.
Note: this scenario and the Dynamic scenario make use of stand-alone .rpt files. Such reports are
always accessed externally and consequently it is important to make sure the file path to the
report assigned to the ReportSource property is correct and that the report has not been deleted or
misplaced into the wrong directory. All other scenarios make use of embedded reports. An
embedded report is imported into the project and a corresponding wrapper class representing the
report is generated. Once the project is compiled, both the report and the wrapper class are
embedded into the assembly.
The application is now ready to run. In Solution Explorer right click on the
CRXIWindowsSample project node and select Properties. Change the Startup Object to the Basic
form, click OK, and then press F5 to start the application and display the report. The report
output should look similar to the following (you may wish to maximize the form to display the
report at full size):
13
The following list summarizes the steps taken in this section to create the sample report.
• Create a new Crystal Report
• Lay out the report using the Standard Report Wizard
o Connect to the database
o Add a table to the report
o Select the columns from the table to appear on the report
o Set the report template
o Add a title to the report
• Create a Windows Forms application in Visual Studio .NET
• Add the existing report created in Crystal Reports XI to the project
• Add a CrystalReportViewer control to a Windows form in the project
• Bind the report to the viewer by setting the viewer’s ReportSource property to the report file
Scenario Conclusion
The Basic scenario illustrates how easy it is to add reporting to a Windows application. However,
most real-world reporting requirements are more involved than simply listing values from a table.
The “Intermediate” scenario walks through the creation of a report that is more commonly seen in
application development, the master-detail report.
14
Intermediate Reporting Scenario
The Intermediate reporting scenario demonstrates how to manually create a master-detail report
with drill-down capabilities. This scenario also shows how to bind the report to a
ReportDocument object and deploy it as part of a windows application.
The report demonstrated in this section uses the “Products by Category” view from the
Northwind database. The view returns category (master) and products (detail) data from the
database. The report is grouped by category name, calculating the total number of products
available under each category. Clicking on a category name expands the category and displays
the list of products under the category. Each product is displayed with the number of units in
stock.
To create the sample report, open Crystal Reports XI. The report used for the Intermediate
Reporting scenario is created manually using the Blank Report option. When the Start Page loads,
choose the Blank Report option under the New Reports area. A blank report form loads in the
designer tab and the Database Expert Wizard starts. Note: the Database Expert Wizard may also
be started by selecting “Database | Database Expert…” from the menu.
Review the section Database Connection Used by Windows Based Reports in Appendix A to
establish the connection to the database using a data link file. Once a connection is established,
expand the Northwind node from the available data sources list. Continue to expand the list down
to the Views node. With the Views node expanded, double click the Products by Category node.
15
At this point the view should be listed under the Selected Tables list. Click OK to close the
wizard.
Next, save the form as MasterDetail.rpt by selecting “File | Save As….” from the menu. The
blank report should look similar to the following:
16
Build a Report from Scratch
All of the fields available from the Products by Category view are available from the Field
Explorer window. If this window is auto hidden (as is the case in the screenshot above), make
sure to make it visible.
17
Building a report from scratch involves dragging fields from the Field Explorer onto the report
designer. The following fields should be added to build the sample report.
• Add title, print date and print time objects to the Report Header Section:
o Add a Text Object whose text is “Product by Category Drill Down Report”. Text
object fields can be added to a report by selecting “Insert | Text Object” from the
menu or by selecting the Text Object button on the bottom-most toolbar.
18
o Insert a Print Date field object by dragging a Print Date field from the Field Explorer
window (under the Special Fields node).
o Insert a Print Time field object by dragging a Print Time field from the Field
Explorer window.
• Add database fields to the report’s Details section:
o Individually drag the ProductName, QuantityPerUnit, and UnitsInStock fields from
the Field Explorer (under the Database Fields node) and drop them onto the report’s
Details section.
o Right click on the Details section. From the context menu, choose the Hide (Drill-
Down OK) option. Setting this option configures the report to drill down into the
Details section at runtime.
• Insert a new group and add fields to the Group Header section:
o Select the “Insert | Group…” option from the menu. The Insert Group dialog will
appear. Select the field that the report uses to group on,
Products_by_Category.CategoryName, from the drop down list. Click OK to add the
group to the report.
o To display a total of the units in stock for each category, right-click on the
UnitsInStock field in the Details section and select “Insert | Summary…” from the
menu. The Insert Summary dialog will begin. Select
Products_by_Category.UnitsInStock from the Choose a field to summarize drop
down list. Select Sum from the Calculate this summary drop down list. Click OK to
add the field to the report.
19
The field will be placed in the Report Footer section. Click on it and drag it to the
Group Header section.
o Remove the text field headings from the report’s Page Header section.
After all of the fields have been added to the report, position them so that the report appears
similar to the figure below.
20
To preview the report, click the Print Preview , or Refresh Report Data buttons on the
toolbar, or press F5. A list of categories is displayed, along with the total products in stock for
each category on the Preview tab that appears to the right of the Design tab.
21
To drill down on any one of the categories (for example, Dairy Products), double click that
category. A third tab will appear, showing all products that make up the selected category, the
quantity per product, and the units in stock for each product.
Save and Close the report. At this point, the report is created and ready to run.
Open the CRXIWindowsSamples application. Add a new Windows form to the project and name
it “Intermediate.vb”. In the properties window, change its Text property to “Intermediate Report
Scenario”.
Next, add the MasterDetail.rpt report to the project. Right-click on the project name in the
Solution Explorer window and select “Add | Add Existing Item…” from the context menu.
Change the “Files of Type” drop down to Crystal Reports (*.rpt). Browse to the
MasterDetail.rpt file and select it.
The report now needs to be bound to the CrystalReportViewer control. Unlike the Basic report
scenario, which bound the report to the control at design time, this scenario binds the report to a
control at runtime. Drag and drop the CrystalReportViewer control from the toolbox onto the
Intermediate form. Set its DisplayGroupTree property to “False” and its Dock property to “Fill”,
but do not set its ReportSource property.
This scenario uses the ReportDocument component to bind the report to the CrystalReportViewer
control. The ReportDocument component exposes properties and methods of a report at runtime.
Access to report sections, options (report options, print options, etc.) and login credentials is
available through the ReportDocument class that implements the component.
22
The ReportDocument component, sensibly, is located on the Components tab of the Toolbox.
Drag it from the toolbox and drop it onto the Intermediate form. This will open a dialog box,
prompting you for a typed ReportDocument class. Reports embedded in the project, like the
MasterDetail report, are available from the drop down. Select the MasterDetail report and click
OK.
This creates a strongly typed ReportDocument instance named masterDetail1 and adds it to the
form. The final step is to bind the ReportDocument to the report viewer. Add the following code
to the Intermediate’s Form_Load event.
The application is now ready to run. Change the Startup Object to the Intermediate form and
press F5 to start the application and display the report. The report output should look similar to
the following:
23
As within the Crystal Reports environment itself, when the report loads, a listing of products by
category is displayed along with the total products in stock for each category. Double clicking on
a category name, for example Beverages, drills-down into the category, showing all of the
products that make up the category and the units in stock for each product, as shown below.
24
25
The following list summarizes the steps taken in this section to create the sample report.
• Create a new Crystal Report
• Manually lay out the report using the Blank Report option
o Connect to the database
o Add a view to the report
o Select columns from the view to appear on the report
o Add a group header section to the report
o Insert a summary field to the group header section of the report
o Drag and drop fields from the Field Explorer to the report’s details section
o Permit drilling down on the details section by selecting the Hide (Drill-Down
OK) option from the section’s context (right-click) menu.
• Add the existing report created in Crystal Reports XI to the Windows project
• Drag a ReportDocument component from the Toolbox and drop it on a form in the
project.
• Add code to the form’s Form_Load event to bind the report to the viewer by setting the
viewer’s ReportSource property to the strongly typed ReportDocument object instance.
Scenario Conclusion
The “Intermediate” scenario illustrates the grouping and drill-down features available to a Crystal
Reports report. The ReportDocument object, introduced in this scenario, provides programmatic
access to a report. In future scenarios it will play a more prominent role in the report generation
process.
The sample reports shown so far have been textual listings of data from the database using tables
and views as data sources. Neither report used parameter values to filter their data. The
“Dynamic” scenario expands on the Intermediate scenario by introducing two new features that
greatly enhance the flexibility of your reports and the level of selection for the user. Following
the Dynamic scenario, the “Visual” scenario builds on the first three reports by adding graphical
output and retrieving data by calling a stored procedure.
26
Dynamic Reporting Scenario
The Dynamic reporting scenario illustrates a few new features – Dynamic and Cascading Prompts
and Dynamic Graphic Location - introduced in Crystal Report XI.
The Dynamic and Cascading Prompts features provide the capability of selecting and passing
dynamic values retrieved from the database to parameters used to filter the records displayed on
the report. The report changes its behavior depending on the values entered by the user.
Prompts are the elements that let users select a value for a parameter. They can include a static or
dynamic list of values that the user can choose from. The user sets a value for a prompt in the
prompting dialog box. The selected value is then assigned by Crystal Reports’ prompting engine
to the corresponding parameter used by the report.
Dynamic prompts can include multi-level lists. Prompts, populated with values retrieved from the
database, are arranged in a cascading fashion where a value selected in a drop-down list
constrains values displayed in subsequent drop-down lists. This scenario includes a two-level
cascading prompt. The user is first prompted for a country and then, based on that selection, will
be prompted with a list of cities within the selected country. Once a city is selected, it is assigned
to a parameter and used in the report’s selection formula to limit the customer data shown in the
report. All countries and cities displayed are dynamically retrieved from the Customers table in
the Northwind database.
We’re almost ready to start building our report, but in this scenario we’d also like to explore the
display and use of data-driven graphic images, Using Crystal Reports XI, doing this no longer
requires storage of the images as “BLOBs” within the database. Instead, the Dynamic Graphic
Location feature lets you store the file path of an image as a string field in the database and store
the actual images in the file system of your Web server or the user’s PC. This feature is
implemented though the use of a conditional formatting formula that links to your image object
by reference.
Now let’s put all these features together in a new report. First, open Crystal Reports XI. From the
Start Page, choose the Blank Report option under the New Reports area. The Database Expert
Wizard starts.
Review the section Database Connection Used by Windows Based Reports in Appendix A to
establish the connection to the database using a data link file. Once the connection is established,
expand the Northwind node from the available data sources list. Continue to expand the list down
to the Tables node. With the Tables node expanded, select both the Customer and CustomerStatus
tables and click on the > button. At this point, the table names should be listed under the Selected
Tables list. The CustomerStatus table contains a column with image names, representing the
status of each customer. The table was not part of the original Northwind database, but was added
by a database script that you ran earlier.
27
7
The Links tab is added to the Database Expert when more than one table is selected from the
database. From the Links tab, select the By Key radio button in the Auto-Link section. The link is
used to match up records from the Customers table with those from the CustomerStatus table,
using the CustomerID field in the CustomerStatus table as a foreign key into the Customers table.
Click OK to close the Database Expert.
28
Next save the form as DynamicCustomerList.rpt by selecting “File | Save As…” from the
menu.
Perform the following steps to create the initial design for your report:
• Add the CompanyName, ContactName, Phone and Fax database fields by dragging them
from the Field Explorer onto the Details section in the report designer.
• Add a Text Object to the Report Header section and set its text to “Customers Contact
List”. Change the font size to 18.
• Insert Print Date and Print Time field objects in the Report Header section by dragging
them from the Special Fields node in the Field Explorer.
29
Insert a Picture object in the report’s Details section by selecting “Insert | Picture…” from the
menu.
Browse to the Images folder as described below and select “warning.bmp” file. Placing this
specific image in the report only creates a “placeholder” that will later be replaced with an image
whose name is retrieved from the database. “warning.bmp” will also be the default image for
data rows for which no dynamic image can be determined.
30
Note:
If you have unzipped the sample files to a folder called CRXI_NET_StartUpGuide in the root
directory of the C: drive, the full path to the Images folder will be:
C:\CRXI_NET_StartUpGuide\SampleCode\Images. If you have extracted the samples files to
a different folder name, then adjust the above path accordingly in order to locate the image file.
Place the image to the left of the CompanyName field, as shown below. (Until you position the
image on the report, the mouse pointer is displayed as an hourglass.)
After inserting the image, right click it and from the context menu select “Format Graphic…” to
open the Format Editor.
31
Change the Object Name property to “Customer Status Image”.
32
So far everything about this image is static. In order to make it dynamic, click on the Picture tab
and click the Conditional Formula button to the right of Graphic Location label.
33
In the Formula Workshop window, add the path to the dynamic image object by selecting the
string field in the database that contains the image file name and prefixing it with the path to the
folder that contains the image files.
If your image files are located in a folder different from our default scenario, you will need to
modify the path prefix string with the path to that folder (e.g.
“C:\CRStuff\CRXI_NET_StartUpGuide\SampleCode\Images” if you extracted the zip file’s
sample code folder to C:\CRStuff, or “C:\crimages\” if you copied the images to their own folder
called crimages under the root directory.).
34
Click Save and close to save the formula and click OK to close the Format Editor.
Now let’s move from image handling to the use of the Dynamic Cascading Prompts feature.
Right click on the Parameter Fields node in Field Explorer and select New… from the context
menu to open the Create New Parameter dialog box.
In the dialog box, enter “Customer City” in the Name field, click the Dynamic radio button in the
List of Values area, and enter “Select Country and City to display related customers” as the
Prompt Group Text.
Next click the Insert button in the Choose a Data Source area of the dialog. This area is used to
define the fields that make up your cascading list of values. Select Country in the expanded Value
column of the grid. With Country selected, in the Options area, set the Prompt Text property
value to “Select a Country”.
Now click the blank field under Country and select City to create the second level of your
cascading prompt. Click the cell under the Parameters column to bind the user-selected City value
to this parameter field.
In the Options area, set the Prompt Text property value to “Select a City”.
35
Click OK. A new parameter, Customer City – City, is added in the Field Explorer under the
Parameter Fields node.
To allow the parameter to be incorporated into the record selection, open the Select Expert by
clicking on the Select Expert button on the toolbar.
36
From the Choose Field dialog box select City under the Customers table node and click OK.
The Select Expert dialog box appears. Select is equal to from the left-hand drop-down list (which
at first will be the only drop-down list visible) and {?Customer City – City} (the parameter field
you created earlier) from the right-hand drop-down list that then appears. Configuring the report
in this way assures the report will only include rows from the Customers table where the City
field’s value is equal to the user’s selection.
Click OK to close Select Expert. Save the report and click on Print Preview to run it.
When prompted, select UK from the Select a Country drop-down list in the Enter Values dialog
box. The Select a City drop-down list will then automatically be populated with cities in the UK.
Select London and click OK.
37
The report displays all the customers based in London with a corresponding image representing
the status of each customer.
Save and close the report. At this point, the report is created and ready to run.
The last few steps involve setting up a Windows application and form to display the report.
Open the “CRXIWindowsSamples” application. Add a new Windows form to the project and
name it “Dynamic.vb”. In the properties window, change its Text property to “Dynamic Report
Scenario”.
38
Next, add the DynamicCustomerList.rpt report to the project. To do so, right-click on the
project name in the Solution Explorer window and select “Add | Add Existing Item…” from the
context menu. Change the “Files of Type” drop down to Crystal Reports (*.rpt). Browse to the
DynamicCustomerList.rpt file and select it.
Select the Dynamic form so that the CrystalReportViewer control can be added to it. Drag and
drop a CrystalReportViewer control from the toolbox onto the form. Set its DisplayGroupTree
property to “False” and its Dock property to “Fill”. Finally, click on the ReportSource property
in the Properties window. From the drop-down list select DynamicCustomerList.rpt. The
application is now ready to run. In Solution Explorer, right-click on the CRXIWindowsSample
project node and select Properties. Change the Startup Object to the Dynamic form and press F5
to start the application and display the report. When the Enter Parameter Values dialog appears,
select UK from the Country drop-down list and London from the City drop-down list, then click
OK.
39
The report output should look similar to the following:
40
The following list summarizes the steps taken in this section to create the sample report.
• Create a new Crystal Report
• Manually lay out the report using the Blank Report option
o Connect to the database
o Add tables to the report
o Select columns from the tables to appear on the report
o Drag and drop fields from the Field Explorer to the report’s Details and Report
Header sections.
o Add a Text object to display a title for the report.
• Add the report created in Crystal Reports XI to the Windows project
• Add a new form to the project.
• Add a CrystalReportViewer control to the form
• Bind the report to the CrystalReportViewer by setting the CrystalReportViewer’s
ReportSource property to the report file
Scenario Conclusion
The “Dynamic” scenario illustrates the Dynamic and Cascading Prompts and Dynamic Graphic
Location new features introduced in Crystal Reports XI. These features add more sophisticated
criteria selection for the user when generating reports and add greater interface flexibility to your
application.
41
Visual Reporting Scenario
Visual elements, such as charts and geographic mappings make reports easier to read and provide
a quick summary of information to the user. Not only is charting a means of presenting data — it
is also an analysis tool. Users can drill-down on a chart or a map for detailed information. The
Visual Reporting scenario adds charting and geographic mapping components to a web-based
report.
Delivering reports over the Web is a powerful feature. With Web-based reporting, users have
access to data 24 hours a day, 7 days a week, regardless of their location. Deploying reports over
the Web is a straightforward and simple process, in fact it is not much more complicated than the
Basic, Intermediate and Dynamic Reporting scenarios described above.
This scenario also introduces the techniques for reporting off of a stored procedure, using the
GetCountryPurchases stored procedure that returns the total purchases for each category of
products grouped by country.
The sample code for the Visual report can be found in the CRXIWebSamples application. The
Visual.aspx Web form, its code-behind class and the Visual.rpt report file demonstrate all of the
techniques described here.
To create the sample report, open Crystal Reports XI. The report used for the Visual Reporting
scenario is created manually using the Blank Report option. From the Start Page, select the Blank
Report option under the New Reports area. A new tab, with a blank report form displayed in the
Design view, is added to the screen and the Database Expert dialog box opens up.
The process of selecting a provider and connecting to the database is described in the section
Database Connection Used by Web Based Reports in Appendix A .
After establishing the connection to the database, double click on the GetCountryPurchases
stored procedure to move it to the Selected Tables list and click the OK button.
Insert a new group on the report for countries. Select the “Insert | Group…” option from the
menu. The Insert Group dialog will appear. Select the field that the report uses to group on,
GetCountryPurchases.Country from the drop down list. Click OK to add the group to the report.
Next insert a Summary Report field to display the total purchases for each country. Select “Insert
| Summary…” from the menu. The Insert Summary dialog will begin. Select
GetCountryPurchases.Purchases from the Choose the field to summarize drop down list. Select
Sum from the Calculate this Summary drop down list. In the Summary Location drop down,
select Group#1:GetCountryPurchases;1.Country – A. Click OK to add the field to the report. The
field is placed in the Group Footer section.
42
Select “Insert | Map…” from the menu to insert a map on the report. The Map Expert starts. In the
Placement box, select Once per report from the Place map: drop down and choose the Header
radio button. In the Layout box, Group should be selected. In the Data box, select
GetCountryPurchases;1.Country from the On change of: drop down, and select Sum of
GetCountryPurchases;1.Purchases from the Show: drop down. The screenshot below shows how
this form should look:
43
Next, select the Type tab on the top of the Map Expert dialog box. Select Natural break from the
Distribution method drop down. Change the Color of highest interval: to Red and the Color of
Lowest interval: to Blue as shown below:
44
Next, select the Text tab of the Map Expert. Enter “Country Purchases” in the Map Title textbox
as shown:
Click Ok to add the map to the Report Header section of the report. Make the map larger and add
do the following:
• Add the following fields to the Report Header section below the map
o A Text Object whose text is “Total World Purchases:”
o A summary report field that calculates the Sum of
GetCountryPurchases;1.Purchases. This will display the total purchases made by
all countries in the world.
• Individually drag the CategoryName, and Purchases fields from the Field Explorer and
drop them onto the report’s Details section
• Insert a Text Object whose text is “Total:” to the left of the Purchases summary field in
the Group Footer section
45
Right-click on the CategoryName field in the Details section and select Format Field. The
Format Editor starts. On the Font tab, make the field bold, blue and a larger size as shown:
Click OK. To format the Purchases field the same way, you could repeat the above procedure.
However, if you had a lot of fields and wanted them all formatted the same way, this method
could prove tedious. Therefore, Crystal Reports XI has provided a Format Painter tool to help
with this process. After one field is formatted the way you want, select the field (in this case
CategoryName), and either choose “Format | Format Painter” from the menu, or click on the paint
brush icon on the toolbar. Next, hover over the field you want to change the format of (in this
case Purchases) and notice that the mouse pointer changes to a paint brush. Click the Purchases
field and notice that the Format Painter has copied the format of the CategoryName field to the
Purchases field.
46
Next, add a Gauge chart to the report. To do this, select “Insert | Chart…” from the menu. Place
the chart in the Group Header #1 section. On the Type tab, select Gauge in the Chart type list as
shown:
On the Data tab in the Layout box, choose Advanced. In the Data box, select the
GetCountryPurchases;1.CategoryName from the list of available fields and add it to the list box
under the On change of drop down by clicking the > button.
47
Next select the GetCountryPurchases;1.Purchases field and add it to the Show value(s): list box
by clicking the second > button as shown below:
On the Text tab, uncheck the Auto-Text option for Title and enter “Purchases by Category”.
Accept the default subtitle and click OK.
48
Save the report as Visual.rpt. Now the report should look like the following screenshot in design
view (viewing at 50% zoom level):
49
A few additional layout changes improve the effectiveness of the report.
Increase the size of the gauge chart to improve readability. Next, right-click on the chart and
choose “Chart Options…” from the menu. The Chart Options dialog loads. In the Appearance
tab, change the Circular Thickness to 20 and the Number of Gauges per row to 3 as shown in this
screenshot:
50
On the Legend tab, remove the chart’s legend by unchecking the Show Legend checkbox and
click OK.
51
The final layout change is to change the data labels. The labels use shorthand to represent values
in the thousands (K). Right-click on the chart, and choose the “Chart Expert…” option. On the
Axes tab, uncheck the Auto range checkbox select 1k in the Number format drop down. Check
the Auto range checkbox and click OK.
Finally, select “Report | Formula Workshop…” from the menu. Here you can view and edit
formulas on the report. As a simple example, add a tool tip to the total purchases in the Group
Footer field. To do this, expand the Formatting Formulas node. Next, expand the Group Footer #1
node as shown:
52
Right-click on SumofPurchases and select “New Formatting Formula…”. The New Formatting
Formula dialog appears. Select “Tool Tip Text” from the list and click Use Editor.
53
Click Save and close to save the formula and close the Formula Workshop.
Add a new section to Group Header #1 by clicking on the Section Expert icon on the
toolbar. The Section Expert dialog box appears with a list of all the sections in the report. Select
Group Header #1 and click on the Insert button. A new section named Group Header #1b: is
added to the report as shown below.
54
Click OK to close the Section Expert dialog.
Move the Group #1 Name text field to the newly added Group Header #1b section.
Now the report should look something like this:
55
To preview the report, select “View | Print Preview”, press F5, or select “Report | Refresh Report
Data” from the menu. The report should look like this:
56
The report loads with a map of the world. Next to the map is a legend, color coded from Red to
Blue. For example, the legend tells us that there are two countries that had purchases from
$244,000 to $264,000, signified by Red. On the map, each country is color coded as well. Click
on the map to select it. Hovering over each country displays the country name and the purchase
total. The green countries are countries which are not in the database; hovering over them will
just display their names.
The group tree displays a list of all the countries in the database. Right-click on Argentina and
select Drill Down. The Purchases by Category report for Argentina displays as shown:
57
Each category is displayed as a gauge chart showing the total purchases for that category for
Argentina. Below the charts, a tabular listing of the categories and purchase amounts appears.
Hovering over the Total purchases for Argentina displays the tool tip that states that Argentina
had $8,119.10 purchases out of a total $1,354,458.59 spent by all the countries of the world.
58
This scenario makes use of the CrystalReportPartsViewer control. The
CrystalReportPartsViewer control is a Web control that allows you to display specified parts of
a report at a time, and can be used in wireless applications. Report parts are hyperlinks that link to
specific parts of the report. To configure the report to use this control, we must define report parts
in the report.
Switch back to Design view. Go to “File | Report Options…” on the menu to open the Report
Options dialog box. (If you are prompted with a dialog box alerting you that your drill-down tab
has to be closed to proceed, select Yes). Here you set the Initial Report Part Settings. In the
Object Name textbox, type “Map1” as shown below.
The object name defines what the initial object will be when the report is rendered using the
CrystalReportPartsViewer control. In this case, the world map is the first thing that should be
displayed, and its default name is “Map1”. Click OK to close the Report Options box.
Next, right-click on the map and select “Format Map…” and the Format Editor dialog box
appears. Click on the Hyperlink tab. In the DHTML Viewer Only section, select the Report Part
Drilldown option. A Hyperlink information box will appear at the bottom. Select the Group
59
Header #1 and click the >> button. This will move Graph1 to the Fields to Display list. This
defines the hyperlink for the map. When a country is clicked on the map, the gauge chart for that
country will be displayed. The chart’s default name is “Graph1”.
Click OK to close this dialog. Save the Visual.rpt report and close it.
Putting it Together
To display this report on a Web page, start by creating a new ASP.NET Web application. Name
the new application “CRXIWebSamples”. Once the project is created, delete the default Web
form “WebForm1.aspx”. Add a new Web form to the project and name it “Visual.aspx”. Change
its pageLayout property to FlowLayout and set the Title property to “Visual Report Scenario”.
Add the Visual.rpt report to the project. Right-click on the project node in the Solution Explorer
window and select “Add | Add Existing Item…” from the context menu. Change the “Files of
Type” drop down to Crystal Reports (*.rpt). Browse to the Visual.rpt file and select it.
The report now needs to be bound to the CrystalReportPartsViewer control. Like the Intermediate
scenario, this scenario binds the report to a control at runtime. Find the
60
CrystalReportPartsViewer control in the Toolbox (it is normally located under the Web Forms
tab). Drag and drop the control from the toolbox onto the Visual web form.
This scenario uses the ReportDocument control to bind the report to the
CrystalReportPartsViewer control. The ReportDocument class exposes properties and methods of
a report at runtime. Access to report sections, options (report options, print options, etc.) and
login credentials is available through the ReportDocument class.
The ReportDocument component is located on the Components tab of the Toolbox. Drag the
component from the toolbox and drop it onto the Visual form. This will open a dialog, prompting
for the typed ReportDocument class. Reports embedded in the project, like the Visual report, are
available from the drop down. Select the Visual report, uncheck the Generate cached strongly-
typed report checkbox and click OK.
This creates a strongly typed ReportDocument named visual1 and adds it to the form. The final
step is to bind the ReportDocument to the report parts viewer. Add the following lines of code to
Visual’s Page_Load event:
The ReportDocument’s SetDatabaseLogin method passes login credentials to the views used for
the report. If the login credentials are not set in this manner, or are invalid, an in-browser login
form will appear and the user must supply database login information to continue; use of the
SetDatabaseLogin method avoids burdening the user in this way. Note that the user name – the
first parameter passed to the SetDatabaseLogin method - is not case sensitive, but the password
is.
61
To see the report in action, set the Visual.aspx page as the startup page by right-clicking on the
file in the Solution Explorer window and selecting the Set as Start Page option from the context
menu. Run the application by pressing F5. The report initially loads with the world map
displayed as shown in this screenshot:
Clicking on a country displays the purchases by category for that country. Clicking on Venezuela
displays this page:
62
The following list summarizes the steps taken in this section to create the sample report.
• Create a new Crystal Report
• Manually layout the report using the Blank Report option:
o Connect to the database
o Add stored procedure to the report
o Add a group section to the report
o Insert a summary field to the group footer section of the report
o Add a map to the report
Specify the data to display on the map
Format the map
o Drag and drop fields from the Field Explorer to the report’s details section
Format a field manually
Format a field using the Format Painter tool
Use Formula Workshop to specify a formatting formula for a field
o Add a gauge chart to the report
Specify the data to display in the chart
Format the chart
o Insert a new section after the Group Header #1 section
o Define report parts in the report
63
• Create a Web application project in Visual Studio .NET
• Add the existing report created in Crystal Reports XI to the project
• Add a CrystalReportPartsViewer control to the Web form in the project
• Drag a ReportDocument component from the Toolbox and drop it on the form
• Add code to the web form’s Page_Load event to bind the report to the parts viewer by
setting the parts viewer’s ReportSource property to the strongly typed ReportDocument
object. The code should also set the database login credentials.
Scenario Conclusion
The Visual reporting scenario builds on the previous scenario by adding geographic mapping and
charting to the report and by using a stored procedure to get its data. Colorful maps and charts
permit users to make snap decisions from report data and drill down on specific data. In addition,
Report Parts were defined in the report and the ReportPartsViewer control was used to display the
report parts in a Web form. While charting is a great way to enrich a report, the next scenario,
Sub-report, further enhances reporting by embedding a report within a report.
64
Sub-report Reporting Scenario
Two separate reports can be combined into one using the sub-report features provided by Crystal
Reports. A sub-report is a report embedded within a report. A sub-report is not required to be
related to the container report (main report).
Sub-reports can be unlinked or linked. Unlinked sub-reports are not related to the main report in
any way. Linked reports are related to the main report. When linking reports, a parameter field is
used to coordinate the data between the two reports. The sub-report uses the parameter in a
selection formula to display only the data associated with the main report’s link field.
Performance can be a concern when linking a sub-report to a main report because a sub-report is
created for each record in the main report.
Performance suffers if the sub-report contains large amounts of data. To prevent performance
degradation, a sub-report can be configured to run “on-demand”. On-demand sub-reports are
displayed as hyperlinks in the main reports. Sub-report data is only retrieved when a user clicks
on the hyperlink.
This scenario expands on the customer listing report created in the Basic scenario by linking the
report to a sub-report of orders. Sub-reports are displayed on-demand, using a hyperlink. The
reports are created as standalone report files and deployed as part of a Web application. Data for
the sub-report is collected using an ADO.NET typed DataSet.
The sample report uses the GetCustomers_sp stored procedure to retrieve customer data for the
main report (Customers.rpt) and the GetOrdersForCustomer_sp to retrieve order data for the sub-
report (CustomerOrders.rpt).
The report and sub-report in this scenario get their data from typed ADO.NET DataSets. In
Crystal Reports XI, DataSet performance has been dramatically increased. Tests have shown that
the new driver is faster, uses less private memory, and less working set memory than previous
versions of Crystal Reports.
Open the CRXIWebSamples application. Create a typed DataSet based on the GetCustomers_sp
as follows. Right-click on the CRXIWebSamples project in the Solution Explorer and select “Add
| Add New Item” and select the DataSet object from the ensuing dialog. Name the DataSet
“CustomersDS.xsd” as shown below.
65
Click Open to add the DataSet to the project. The CustomersDS opens in design mode. Open the
Server Explorer window. Starting with the Servers node, drill down to the GetCustomers_sp node
(as shown below).
66
After locating the GetCustomers_sp node, drag it from the Server Explorer window and drop it
onto the CustomersDS DataSet. Dropping the stored procedure onto the DataSet creates a typed
DataSet whose schema is defined by the columns returned by GetCustomers_sp. Name the
DataTable “CustomerData”. The DataSet should be similar to the following screen shot when
viewed in design view.
67
Next, create a second DataSet for the order data following the same process. The order DataSet is
based on the GetOrdersForCustomer_sp and named “OrdersDS”. Again, after adding the stored
procedure to the designer, name the DataTable “OrdersData”. The OrdersDS DataSet should look
like the DataSet depicted below.
68
Open Crystal Reports XI and create a new report using the Standard Report Wizard. The
Customers report lists the customers in the customer table and will contain a linked sub-report.
When specifying the data source for the report, this time set it to the CustomersDS that was just
created. To do this, expand the ADO.NET (XML) node. In the file path of the dialog that appears,
browse to the CustomersDS.xsd file located in the CRXIWebSamples’s project folder as shown:
69
Click the Finish button. Next, under the CustomersDS node, double click on the CustomerData
DataTable to move it to the Selected Tables list as shown:
70
On the next screen select the CustomerId, CompanyName, ContactName, City, and Country
fields. You may wish to add print date and page number fields to the Page Header and Page
Footer sections, respectively. Save the report as Customers.rpt.
Next, create the sub-report, CustomerOrders.rpt. This report will show the orders associated
with a given customer. Select “File | New…” from the menu. Using the Standard Report Wizard,
select the OrderData DataTable from the list of available data sources by browsing to the
OrdersDS.xsd DataSet in the CRXIWebSamples’s project folder as shown above. Select all
available fields to display on the report from the Wizard. Save and close the report file.
Report Layout
The main report, Customers.rpt should look similar to the one pictured below.
71
The next step is to embed the sub-report within the main report. With the Customer.rpt open,
select “Insert | Subreport…” from the menu.
A dialog window opens to guide the process of adding the sub-report. The source of the sub-
report can be an existing report, or a new report. Select the Choose an existing report radio button
and browse to the CustomerOrders.rpt report. This main report will use on-demand linking so
place a check in the On-demand Subreport (similar to a hyperlink) checkbox to set up on-
demand linking as shown:
72
Next, click the Link tab. The Link tab provides the details of how the two reports are related to
one another. The reports used in this scenario are related by CustomerID.
From the Available Fields list, select the CustomerData.CustomerID field and click the > button
to add the field as a link field.
Report linking uses a parameter field to associate the sub-report with the main report. From the
Subreport parameter field to use drop down, select the ?Pm-CustomerData.CustomerId value.
Check the Select data in subreport based on field checkbox and select the CustomerID value
from the drop down. The dialog window should look like the following screen shot.
Click OK to accept the values and close the dialog. Drop the sub-report object into the Details
section of the report. Expand the height of the Details section if necessary. The following screen
shot shows how the customers report should look after the sub-report has been embedded within
it.
73
To make the report more presentable, increase the font size of the database field objects to a
comfortable size.
Right-click on the sub-report object embedded in the main report and select the “Format
Subreport…” option from the menu. On the Common tab, change the Object Name field to
“CustomerOrders” as shown:
Next, click on the Subreport tab. Change the Subreport Name field to “Customer Orders” as
shown:
74
By default the hyperlink text used to display the on-demand sub-report is the report name.
Luckily, this text can be changed to something more meaningful. To change the hyperlink text,
click on the Formula button to the right of the On-demand subreport caption option. This opens
the Formula Workshop window. For this sample, the hyperlink text will be the static text “View
Orders”. Enter “View Orders” (quotes included) in the formula editor textbox on the bottom of
the form, as shown below. Click the Save and close button to save the report formula.
Afterwards, save your changes and close customer.rpt
75
The reports are set up and ready to run. The next step is to set up a Web form that will contain the
report. Add the two reports, Customers.rpt and CustomerOrders.rpt to the CRXIWebSamples
project. Add a new Web form to the project and name it “Subreport.aspx”. Change its
pageLayout proberty to FlowLayout and set the Title property to “Subreport Report Scenario”.
Add a CrystalReportViewer control and set its DisplayGroupTree property to False. Add a
ReportDocument component to the form based on the Customers typed report (uncheck the
Generate cached strongly-typed report check box before clicking OK).
Putting it Together
With the reports and form created, the final steps involve getting the data and binding the reports
to the data. Code in the Web form’s Page_Load event fills two typed ADO.NET DataSets. These
datasets provide the data for the main and sub-report.
After the DataSets are filled, they are assigned as data sources to the main report and sub-report
ReportDocuments using the SetDataSource method. The main report ReportDocument object is
the one added to the form at design time, customers1. The ReportDocument exposes the
ReportObjects collection from its ReportDefinition property. The ReportObjects collection
contains all of the objects in the report, including text objects and field objects. Another item in
the ReportObjects collection is the Subreport object embedded in the report. The sub-report
object is retrieved from the ReportObjects collection and assigned to a Subreport object with the
following line of code.
subreportObject = customers1.ReportDefinition. _
ReportObjects.Item("CustomerOrders")
76
Next, the sub-report object’s name can be retrieved from the SubreportObject and assigned to a
local variable.
subreportName = subreportObject.SubreportName
The code could then call the main (customers1) ReportDocument’s OpenSubreport method. The
OpenSubreport method opens a sub-report embedded in the main report and returns a
ReportDocument Object corresponding to the named sub-report. The ReportDocument object
returned is assigned to the ReportDocument variable “CustomerOrders”.
CustomerOrders = customers1.OpenSubreport(subreportName)
The CustomerOrders ReportDocument represents the sub-report embedded in the main report.
We’ll need to set its data source to the typed DataSet dsOrders.
CustomerOrders.SetDataSource(dsOrders)
Similar code will be needed to set the main report’s data source to the typed DataSet dsCust, and
then set the CrystalReportViewer’s ReportSource to the typed ReportDocument customers1. The
complete code listing for the Page_Load event is shown below.
' get all of the data for the report and sub-report
Const db_connection As String = _
"data source=localhost;initial catalog=northwind;" _
& "user id=crreports;password=crreports;"
77
.SelectCommand.CommandType = _
CommandType.StoredProcedure
.TableMappings.Clear()
.SelectCommand.CommandText = _
"GetOrdersForCustomer_sp"
End With
CrystalReportViewer1.ReportSource = customers1
78
dsOrders.Dispose()
dsCust.Dispose()
daNorthwind.Dispose()
End Sub
The report is now ready to run. To run the report, set the SubReport.aspx page as the startup page
by right-clicking on it in the Solution Explorer window and selecting the Set as Start Page
option from the menu, then hit F5. When the report runs, the user is first presented with a list of
customers. Underneath each customer is a hyperlink labeled View Orders.
If the user clicks on the hyperlink, the CustomerOrders sub-report loads and is displayed in the
browser.
79
Note that the CrystalReportViewer control includes a Print button in Web applications as well as
Windows applications. This allows users to print the report directly to their local printers with full
layout fidelity since the browser’s own Print button need not be used. In previous versions of
Crystal Reports (Crystal Reports 9 and earlier), this button was only available in the Windows
Forms CrystalReportViewer control.
The following list summarizes the steps taken in this section to create the sample report.
• Create two strongly typed DataSets and add them to the CRXIWebSamples project
o Drop a stored procedure on the DataSet at design time from the Server Explorer
• Create a new Crystal Report for the main report
• Create a new Crystal Report for the sub-report
• Use the Standard Report Wizard to format each report and set the appropriate data
sources
• Add the two reports to w Wen application project
• Add a new Web form to the project
o Add the CrystalReportViewer control to the form
o Drag a ReportDocument component from the Toolbox and drop it on the web
form. Set its typed ReportDocument class property to the proper typed report
document object (corresponding to the main report)
o Add code to the form’s Page_Load event to retrieve data using the typed
DataSets
o Add code to get a ReportDocument object, representing the embedded sub-
report, from the main ReportDocument object
o Add code to the form’s Page_Load event to set the sub-report and main report
data sources to the respective DataSets and bind the CrystalReportViewer control
to the typed ReportDocument object
80
Scenario Conclusion
This scenario described the steps to take to embed one report within another. Robust reporting
solutions can be created by combining two separate reports into one. Crystal Report’s sub-report
feature embeds a sub-report within a container report seamlessly. Sub-reports can be linked or
unlinked. For performance considerations, linked reports should be configured to run on-demand.
The scenario also explained how to use ADO.NET typed datasets as report data sources.
The next scenario continues to generate reports based on ADO.NET typed datasets. It also
describes how to export reports to PDF and Editable RTF formats with Crystal Reports XI.
81
Document Reporting Scenario
The Document scenario illustrates how Crystal Reports can be used to generate documents, such
as contracts or invoices, which are viewable in PDF format (and later, in Editable RTF format).
The sample Web form and report can be found in the CRXIWebSamples project. This report is
created without the help of the Crystal Wizards.
This scenario differs from the previous ones because it does not use the CrystalReportViewer
control. Rather, the report is exported directly to PDF (and later to Editable RTF) where it is
streamed to the Web browser and displayed in Internet Explorer. A scenario such as this has all
sorts of useful implementations, including business-to-business applications where legal
documents must be dispatched.
This scenario uses the same process to export the report to Editable RTF format. This new format
does not use frames and converts all object contents in the report to standard free-flowing text.
Also, images are inlined with the text, allowing for easy document editing.
The exporting features provided by Crystal Reports are highlighted by the sample invoice
document created here. The sample code retrieves data using the custom parameterized stored
procedure, GetInvoiceForCustomer_sp .
The report in this scenario gets its data from a typed ADO.NET DataSet.
In the CRXIWebSamples project, create a typed DataSet based on the
GetInvoiceForCustomer_sp. The process to create a typed DataSet is shown in the Sub-report
scenario section above. The invoice DataSet is based on the GetInvoiceForCustomer_sp stored
procedure. After adding the stored procedure to the DataSet designer, name the DataSet
“InvoiceDS”. The InvoiceDS DataSet should look like the DataSet depicted below.
82
Open Crystal Reports XI and create a new report, InvoiceDoc.rpt. From the Start up Page,
choose the Blank Report option. The data source for this report is the typed DataSet, InvoiceDS
created above. As shown previously in the Sub-report scenario, when the Database Expert
launches, expand the ADO.NET (XML) node. In the file path of the dialog that appears, browse
to the InvoiceDS.xsd file located in the CRXIWebSamples’s project folder .Select
GetInvoicesForCustomer_sp and click the > button to add it to the list of selected tables. The
following screen shot shows the results of this operation.
83
Report Layout
Click OK to close the Database Expert dialog. Drag the following fields from the Field Explorer
window onto the report. Fields added to the report will be displayed with a green check to the left
of their names in the Field Explorer, as shown below.
• Add the following fields to the Report Header section
o ShipName
o ShipAddress
o ShipCity
o ShipRegion
o ShipPostalCode
o ShipCountry
o CustomerName
o Address
o City
o Region
o PostalCode
o Country
o Salesperson
84
o OrderDate
o ShippedDate
• Add the following fields to the Details section
o ProductName
o UnitPrice
o Quantity
o Discount
o ExtendedPrice
• Move the text field headings from the Page Header section to the Report Header section
Arrange the fields on the report as shown below. Insert a new Group. Select ShipName as the
field to group on. Insert a subtotal field which sums the ExtendedPrice field. Place the subtotal
field in the Group Footer section.
85
Save the report as InvoiceDoc.rpt and close the report.
In the CRXIWebSamples project, create the form that will display the InvoiceDoc report in the
browser. Add a new Web form to the project and name it “Document.aspx”. Add five controls to
the form; two labels, two drop down lists, and one button. Set the following properties for the
controls.
Button
Property Name Value
(ID) btnRunReport
Text Run
Label
Property Name Value
(ID) lblCustomer
Text Customer:
Label
Property Name Value
(ID) lblOrderID
Text Order ID:
86
DropDownList
DropDownList
Property Name Value
(ID) ddlOrders
Next, add the InvoiceDoc.rpt report to the project. Drag a ReportDocument object from the
Toolbox and drop it on the Document.aspx form. Choose the InvoiceDoc typed ReportDocument
object from the drop down and uncheck the Generate cached strongly-typed report option.
Click OK to add the ReportDocument to the form.
Putting it Together
At this point, the report and the form are set up. The remaining steps involve populating the
customer and order id controls with data from the database, binding the data returned from the
stored procedure to the ReportDocument object, and exporting the report. The following listing
87
shows the Document.aspx Page_Load event. Code in this event populates the ddlCustomer
control with customer names from the database.
daCustomers.Fill(dsCustomers)
ddlCustomer.DataSource = dsCustomers
ddlCustomer.DataTextField = "CompanyName"
ddlCustomer.DataValueField = "CustomerID"
ddlCustomer.DataBind()
daCustomers.Dispose()
dsCustomers.Dispose()
End If
End Sub
After populating the ddlCustomer control, the code populates the ddlOrderID control based on the
first customer returned from the database. The GetOrdersForCustomer method, shown below,
populates the ddlOrderID control.
88
Private Sub GetOrdersForCustomer()
daOrders.SelectCommand.Parameters.Add( _
"@CustomerID", ddlCustomer.SelectedValue)
daOrders.Fill(dsOrders)
ddlOrders.DataSource = dsOrders
ddlOrders.DataTextField = "OrderID"
ddlOrders.DataValueField = "OrderID"
ddlOrders.DataBind()
daOrders.Dispose()
dsOrders.Dispose()
End Sub
The GetOrdersForCustomer method populates the ddlOrderID DropDownList with all of the
order IDs related to a specific customer. The customer parameter comes from the value selected
in the ddlCustomer DropDownList. In addition to being called from the Page_Load event,
GetOrdersForCustomer is also called from the ddlCustomer’s SelectedIndexChanged event,
ensuring that whenever a new customer is selected from the list of customers, the related orders
are retrieved and displayed in the ddlOrderID control. The code in the SelectedIndexChanged
event is shown below.
End Sub
Code behind the btnRunReport button gets the selected customer and order id from the
ddlCustomer and ddlOrderID controls respectively. Those values are used as parameters for the
GetInvoicesForCustomer_sp procedure. The results of executing the stored procedure are
returned in the InvoiceDS typed dataset and then bound to the InvoiceDoc1 ReportDocument
object. These steps are accomplished in the first half of the button’s click event, shown in the
following code.
89
Private Sub btnRunReport_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnRunReport.Click
The remaining code in the click event formats the report as PDF and displays it in the browser.
Here is where the report in this scenario differs significantly from the reports described in other
scenarios. The CrystalReportViewer object is not used to display the results. Instead, the report
results are exported to the browser in PDF format.
The report is exported to the browser using the ExportToHttpResponse method of the
ReportDocument (invoiceDoc1) object. The first parameter of the ExportToHttpResponse method
is of the type ExportFormatType. The ExportFormatType parameter sets the report’s exported
format type. In addition to PDF, export formats include Crystal Report, Excel, ExcelRecord,
HTML32, HTML40, RichText, Text, WordForWindows and the new EditableRTF format
(shown later in this scenario). The second parameter specifies the Response object of the page.
The third parameter, asAttachment, indicates whether the report will be exported as an attachment
of the response while the fourth parameter, attachmentName indicates the file name to export the
report to. In this case the report is not being exported as an attachment.
This method exports the report to PDF format using one line of code without using a temporary
file or exporting to a stream first. This method handles setting the MIME settings for you which
will start the Adobe Reader plug-in in Internet Explorer or Acrobat on the user’s PC.
invoiceDoc1.ExportToHttpResponse( _
ExportFormatType.PortableDocFormat, _
Response, False, "")
End Sub
90
Before running the sample report, set the Document.aspx page as the start up page by right-
clicking on the Document.aspx page in the Solution Explorer window and selecting Set as Start
Page - as shown below.
Press the F5 key to run the report. After the form loads (shown below), select a customer and an
order id and click the Run button.
The report loads as a PDF document (shown below – you must have the Adobe Reader or the full
Acrobat product installed on your PC for the report to display properly) instead of a Crystal
Reports document.
91
Set the report’s export format type in the ExportFormatType parameter to EditableRTF (instead
of PortableDocFormat) as in the code below.
Press the F5 key to run the report. After the form loads, select a customer and an order id and
click the Run button.
Click on Open when prompted with the File Download dialog box to open the document in the
browser as an editable text document. If you have installed Windows XP Service Pack 2 on your
machine, the File Download dialog box will look like the following screen shot (other machines
will display a similar, but less detailed option dialog):
If you have Microsoft Word installed on your machine the document will open up as a Word
document – as in the screen shot shown below. (Otherwise it will open up as a WordPad
document.)
92
Add some text to your document to test the inline editing feature of the Editable RTF format as
shown below.
93
Again, it’s important to realize that in previous versions of Crystal Reports, while you could
export to RTF, the generated document would be, for all intents and purposes, un-editable. This
is because the text was inserted into the document as textboxes , rather than standard free-flowing
text. The new Editable RTF format addresses this shortcoming.
The following list summarizes the steps taken in this section to create the sample report.
• Add a strongly typed DataSet to the CRXIWebSamples project
o Drop a stored procedure on the DataSet at design time from the Server
Explorer.
• Create a new Crystal Report
• Manually lay out the report using the Blank Expert
o Set the report’s Data Source to the typed Dataset
o Drag and drop fields from the Field Explorer to the report’s Details section
• Add the report to the project
• Add a new Web form to the project
o Add controls to the form to run the report
o Drag a ReportDocument component from the Toolbox and drop it on the web
form. Set its typed ReportDocument class property to the proper typed report
document object.
o Add code to the form’s Page_Load event to populate the DropDownList
controls.
94
o Add code to the button’s click event to retrieve data using the typed DataSet.
Set the ReportDocument’s data source to the populated typed DataSet
o Add code to export the ReportDocument to a PDF file using the
ReportDocument’s ExportToHttpResponse method.
o Alternately, add code to export the ReportDocument to an Editable RTF.
Scenario Conclusion
Generating legal or other documents is a powerful feature in any application. The “Document”
scenario was designed to walk through the steps required to produce such documents using
Crystal Reports. Crystal Reports’ exporting features facilitate this process.
Furthermore, reports based on ADO.NET DataSets are a common requirement. This scenario
reinforced the methods used for reporting on DataSets that were introduced in the Sub-report
scenario.
The reporting scenarios discussed above have all focused on developing robust reports using
Crystal Reports XI. Designing and developing reports is only half of a complete solution. Reports
are worthless if they cannot be deployed. The next section discusses deployment issues found in
different .NET application environments and provides solutions to common deployment
problems.
95
Deployment
By default, reports that are added to a .NET application are added as embedded resources. This
means that the reports are compiled into the application’s assembly. The reports will not be
loaded from separate files. Embedding reports eliminates the need to distribute separate report
files with the application. Applications take advantage of embedded reports through strongly
typed ReportDocument objects. However, there is a disadvantage to embedding reports in the
assembly. Changes made to reports require the application to be recompiled and redeployed.
To prevent reports from being compiled into the assembly, select the report in the Solution
Explorer and right-click on the report name. Choose the Properties option. From the Properties
window, change the Build Action property from Embedded Resource to None.
Reports not compiled into the assembly are loaded using the ReportDocument’s Load() method
or are referenced in the CrystalReportViewer’s ReportSource property. Also, the report files must
be manually added to the setup project to be distributed with the application. When reports are
not compiled into the assembly, the application cannot use strongly typed ReportDocument
objects, but can modify and redeploy a report without recompiling the application.
Beyond the issue of embedded reports, developers must take care to properly redistribute the
Crystal Reports runtime files in order for their reports to execute and render properly on the end-
users PC, or customer’s Web server, as the case may be. The remainder of this section discusses
different methods of deploying the appropriate runtime files.
Deployment Scenarios
There are two scenarios for deploying Crystal Reports XI runtime files:
• Merge Modules – Use merge modules if you want to include the Crystal Reports XI
runtime files along with the install package for the application
• Server install – Use server install if you only want to deploy the files as a standalone task
Merge Modules
Application deployment has been greatly simplified in Crystal Report XI. At most, only two
merge modules are needed by developers who want to include Crystal Reports runtime files along
with their application.
96
A merge module is a simplified installer file, that can be “merged” into the .msi files generated
when you create a Visual Studio .NET setup project for your application. Crystal Reports merge
modules need to be added to the setup project to successfully deploy an application that provides
reporting functionality. Different versions of Crystal Reports require different merge module
files.
In Crystal Reports XI deployment has been simplified, usually requiring only a single merge
module, or at most two (if map objects are used in the report files). Also, more deployment
configuration options for database drivers, export drivers, and the crystalreportviewers11 IIS
virtual directory are available.
There are two different Crystal Reports merge modules to choose from. The merge modules for
Crystal Reports XI are:
The Crystal Reports XI merge modules are automatically installed to the following directory:
C:\Program Files\Common Files\Merge Modules. Latest versions can be downloaded from the
following webpage: http://support.businessobjects.com/mergemodules.
Server Install (Interactive Install)
The Server Install is a self-contained setup package provided for Web server installations. The
CrystalReports11_NET_EmbeddedServerInstall.msi file installs all Crystal Reports runtime files
on the computer. The server install is typically used to install the runtime files on Web servers
97
running ASP.NET Web applications using Crystal Reports. In this way, the Crystal Reports
runtime can be installed once per machine, and the runtime does not need to be included with
each application deployment.
The Server Install is also located in the following directory: C:\Program Files\Common
Files\Merge Modules. The server install can be used to install the runtime for .NET windows
applications, but the CrystalReports11_NET_EmbeddedServerInstall.msi file will need to be run
on each client computer.
The Server Install can only be used for applications developed using the Crystal Reports XI
Developer or Advanced editions. It is not available with the free bundled version of Crystal
Reports that comes packaged with Visual Studio .NET.
Note that the Server Install is not the same as a Report Application Server (RAS) install. In a
RAS install, a .NET Windows application or an ASP.NET Web application can be used as a
client to view reports that are processed by a remote server which hosts a Crystal Enterprise
Embedded (RAS) Server. Since the reports are being hosted by RAS, no Crystal Reports runtime
files need to installed on the server. However, the client application still requires runtime files to
be installed. The crystal11_net_embeddedreporting.msm merge module is required to be included
as part of the setup package.
License Key
A Crystal Reports keycode is used to validate the licensing for the application. Both the
crystal11_net_embeddedreporting.msm merge module and the
CrystalReports11_NET_EmbeddedServerInstall.msi server installer require a valid keycode to be
specified. The license key value was emailed when Crystal Reports was registered and can also
be located by using the License Manager installed on the computer with Crystal Reports XI.
Selecting the ‘Business Objects 11’ program group in the ‘Start | Programs’ menu can access the
‘Business Objects License Manager’. Enter the license key value into the Add key code property
when adding crystal11_net_embeddedreporting.msm to your setup project.
Application Deployment
This section discusses the steps needed to create a setup project to deploy the reporting
application, assuming the standalone Server Install will not be used. The steps for deploying a
Windows application are similar to those for deploying a Web application. Areas where the
procedures differ are called out.
• Right click on the solution in the Solution Explorer window. Choose Add | New
Project… from the menu.
• For a Web application, choose the Setup and Deployment Projects folder in the left
pane, then select the Web Setup Project icon in the right pane.
98
• For a Windows application, choose the Setup and Deployment Projects folder in
the left pane, then select the Setup Project icon in the right pane.
• Right-click on the Setup Project file in the Solution Explorer window and choose
Add > | Project Output… from the menu.
99
• For Web applications, select the Primary output and Content Files items from the
list and click OK.
• For Windows applications, select the Primary output option from the list and click
OK
100
• The following project dependencies will be detected and added to your project
automatically when Primary output is selected:
o crystal11_net_embeddedreporting.msm
o dotnetfxredist_x86_enu.msm (excluded from the project by default)
• If you will be installing on a PC or server that already has the .NET Framework,
select the dotnetfxredist_x86_enu.msm dependency, right-click it and select
‘Exclude’ (if not already checked) so that these files are not installed on the target
machine. If the target machine dows not have the Framework, make sure this merger
file is included in the project.
101
If map objects are used in your report, add the CrystalReports11_maps.msm merge
module. Right-click the setup project in the Solutions Explorer window and select Add > |
Merge Module… from the menu. Select the CrystalReports11_maps.msm file from the
dialog box.
102
To deploy the application, right click on the setup project in the Solution Explorer window and
choose the Build option. Once the project is built, an .msi file will be generated, ready to deploy
to the target PC or server.
103
Conclusion
This document introduced integrating Crystal Reports XI with Visual Studio .NET 2003 through
six common reporting scenarios. The scenarios built upon one another. Each scenario described
one or more features and discussed how to implement each feature in a report.
The Basic scenario created a simple Windows report listing customers from the sample database.
Report Wizards did most of the work designing the report. Data was retrieved directly from the
customers table.
Drill down capabilities were the highlighted feature in the Intermediate scenario. Drill down
enables users to view the detail records that make up a summary record. This report introduced
the idea of retrieving data from views and the ReportDocument object. The ReportDocument
object exposes properties and methods to programmatically manipulate report at run time.
The “Dynamic” scenario illustrated the Dynamic and Cascading Prompts and Dynamic Graphic
Location new features introduced in Crystal Reports XI. These features added more sophisticated
criteria selection for the user when generating reports and flexibility in the application. This
scenario included a two-level cascading prompt. The user was first prompted for a country and
then, based on that selection, was prompted with a list of cities within the selected country. Once
a city was selected, it was assigned to a parameter and used in the report’s selection formula to
limit the data shown in the report. All countries and cities displayed were dynamically retrieved
from the Customers table in the Northwind database. Also, the Dynamic Graphic location feature
demonstrated how to store the file path of an image as a string field in the database and store the
actual images in the file system of a Web server or the user’s PC. This feature was implemented
through the use of a conditional formatting formula that linked to image objects by reference.
The Visual scenario showed off some of Crystal Reports charting strengths with a geographic
map of purchases by country. By drilling down on a country, gauge charts displayed the
purchases by category for that country. Data was retrieved from a SQL Server stored procedure.
This scenario introduced Web-based reporting using the CrystalReportPartsViewer control.
The Sub-report scenario demonstrated embedding a report within a report. Performance
considerations were accounted for by configuring the sub-report to load “on-demand,” at the click
of a hyperlink.
The Document scenario highlighted Crystal’s exporting features. Legal documents were created
by exporting a report to PDF format and displaying the PDF data in a Web browser. Also, the
same report was exported as an Editable RTF text document allowing for easy editing by the user.
Features of the ReportDocument object were used to export the report in PDF and Editable RTF
formats in the browser, eliminating the need to use temporary files or export to a stream first
Finally, the guide walked through the steps required to deploy applications with reporting
capabilities. Reports embedded in the application assembly ease deployment but may hinder
maintenance, while stand alone report files impede deployment but ease maintenance. In either
case, merge modules or server installs are necessary to properly install the Crystal Reports run
time dependency files during deployment.
This Startup Guide touched on many features available with Crystal Reports XI. These features
are designed to ease reporting development and deployment for programmers and enhance report
presentation and functionality for end users.
For More Information
• Knowledgebase articles and additional sample code can be obtained at the Business
Objects DevZone for .NET developers:
http://www.businessobjects.com/products/dev_zone/net/default.asp
104
Appendix A
Database Connection Used by Windows Based Reports
For simplicity, all Windows reports connect to the database using a data link file. The file,
“Northwind.udl”, accompanies the sample code. The file connects to the Northwind database on a
local workstation. It uses Windows authentication to connect to the database. The information in
the data link file may need to be adjusted depending on the development environment.
For sample Windows applications, connecting to the database is done using the data link file.
Connecting the report to the database occurs during report creation, either with the help of a
report Wizard or manually. In either case, the following steps will connect the report to the
database using the data link file.
Click on the OLE DB (ADO) item in the list of available data sources under the Create New
Connection node.
A new form will appear, prompting for the selection of an OLE DB provider. Instead of selecting
a provider, check the Use Data Link File checkbox. Browse to the Northwind.udl file included
with the sample code and click Finish.
105
After selecting the connection information, click the Finish button.
Now that the connection is established, begin selecting the report’s data source as described in the
scenarios above.
Database Connection Used by Web Based Reports
The connection used by the Web based report samples is similar to the one used by the Windows
report samples. The biggest difference is in the method used to authenticate the user. The
Windows sample reports use Windows authentication to connect to SQL Server. Windows
authentication is not a scalable solution for a Web application. Scalability is limited because each
user that accesses the Web site needs a Windows account. This may be okay for an Intranet
application where the number of users is small. But in an Internet application, Windows
authentication doesn’t work well. Rather than using Windows authentication to connect to SQL
Server, the sample Web reports use SQL Server authentication.
With SQL Server authentication, SQL Server performs the authentication itself by checking to
see if a SQL Server login account has been set up and if the specified password matches the
password on file. If so, authentication is successful.
Authentication can be performed in a variety of methods depending on the server environment.
An article describing best practices for accessing SQL Server from ASP.NET applications can be
found on Microsoft’s MSDN Site.
106
The samples authenticate with a SQL Server login named “crreports”. This account only has
access to the Northwind database. This idone to avoid use of the system administrator account,
a.k.a. “sa”. For security reasons, using this account is not a good practice.
For sample Web applications, connecting to the database is done using the Database Expert.
Connecting the report to the database occurs during report creation, either with the help of a
report wizard or manually.
Click on the OLE DB (ADO) item in the list of available data sources.
Expand the OLE DB (ADO) node. Select the OLE DB Provider for SQL Server from the list of
providers.
107
108
Click the Next > button to enter the connection information.
109