Professional Documents
Culture Documents
CR7 Techref VOL1
CR7 Techref VOL1
CR7 Techref VOL1
Seagate Software, Inc. 840 Cambie Street Vancouver, B.C., Canada V6B 4J2
1999 (manual and software) Seagate Software, Inc. All Rights Reserved. Seagate Software, Seagate, and the Seagate logo are registered trademarks of Seagate Technology, Inc., or one of its subsidiaries. Seagate Crystal Reports, Seagate Crystal Info, Seagate Info, the Seagate Crystal Reports logo, and Smart Navigation are trademarks or registered trademarks of Seagate Software, Inc. All other product names referenced are believed to be the registered trademarks of their respective companies.
Manual written by: ELUCIDEX 655 Stuart Road Bellingham, WA 98226 http://www.elucidex.com 1999
Seagate Crystal Web Reports Server Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Implementing the Web Reports Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Crystal Web Reports Server Administration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Web Reports Server Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Web Reports Server Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Seagate Crystal Report Engine Automation Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Visual InterDev Design-time ActiveX Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Editing Active Server Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Sample Web Site. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Crystal Smart Viewer Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Crystal Smart Viewer for HTML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Crystal Smart Viewer for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Crystal Smart Viewer for ActiveX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Introduction to the Crystal Report Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Before using the Crystal Report Engine in your application . . . . . . . . . . . . . . . . . . . . 65 Using the Crystal Report Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Crystal Report Engine API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Exporting reports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Handling Preview Window Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Distributing Crystal Report Engine Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Additional Sources of Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Using the Crystal Report Engine API in Visual Basic . . . . . . . . . . . . . . . . . . . . . . . . . 104 Crystal ActiveX Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Crystal Report Engine Automation Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Active Data Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Crystal Data Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Crystal Data Source Type Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Grid Controls and the Crystal Report Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
i
The Seagate Crystal Report Designer Component - Introduction . . . . . . . . . . . . . . . . 146 The Seagate Crystal Report Designer Component - Features . . . . . . . . . . . . . . . . . . . 146 The Report Designer Component vs. Seagate Crystal Reports . . . . . . . . . . . . . . . . . . 147 Installing the Report Designer Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Using the Seagate Crystal Report Designer Component . . . . . . . . . . . . . . . . . . . . . . 151 Working with data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 Report Designer Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Report Designer Object Model Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Report Distribution Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
VCL Component Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Programming Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 Programming Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 TCrpeString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 Using Variables with Formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 About Section Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 C++ Builder 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 Known Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Technical Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Index
ii
Volume1
NOTE: An alternative approach is to use Seagate Crystal Reports Automation Server with Active Server Pages. However this approach does not employ page caching and is not recommended for high traffic web sites. For further information refer to The Web Reports Server vs. Active Server Pages, Page 5.
Page On Demand
Page On Demand means report pages are delivered when demanded. Sometimes a user may only need one or two pages of information out of a 100 page report. Rather than tie up your network by frequently transferring massive amounts of data, the Web Reports Server delivers reports a page at a time as requested by the client. When a report page is requested for the first time the report is generated. The requested page is delivered to the client and stored in a cache. The next time the client requests the same page it is retrieved from the cache rather than being generated again (note, however, that cached reports can be updated either by the client, if allowed by the administrator, or periodically). By handling requests on a per page basis, the Web Reports Server can quickly handle large numbers of requests, limiting the delay in delivery for any one single request. Caching report pages also allows report information to be shared among clients more efficiently as multiple requests for the same report will not require that the report be generated multiple times.
Smart Navigation
When reports are displayed inside a browser, they can include a navigation tree that speeds access to the information your users need. The navigation tree works much like the directory structure presented in Windows Explorer but provides access to specific groups and records within the report. Smart search controls allow navigation to a specific data value. Rather than waste time flipping through pages of data to locate the information that is most important, users jump right to what they need through Smart Navigation.
NOTE: Commands can be passed to the Web Reports Server by way of HTML links or forms.
NOTE: If you are not using a Microsoft or other ISAPI compliant web server, the Automation Server and Active Server Pages are not available as a means of distributing reports from a web site.
As a web site administrator, you must decide when to use the Web Reports Server, and when to use the Automation Server in Active Server Pages. A simple means of deciding is to determine if you are a web developer, or a web administrator. If you are doing web development, writing scripts and applications to customize the functionality of your site, you may want to consider using the Automation Server and Active Server Pages. The Automation Server provides complete control over how reports are presented and delivered to a client. Powerful features are available at runtime such as changing the source of data used or manipulating existing report formulas. However, the Automation Server requires extensive programming inside the Active Server Page environment. Familiarity with a scripting language such as VBScript or JScript is required. For complete information on using the Automation Server for web sites, see Building Active Web Sites, Page 43. The Web Reports Server, on the other hand, can be set up quickly and easily. You simply store reports inside a directory accessible by your web server, then create standard HTML style links to the reports in your web pages. The Web Reports Server does allow some runtime changes to reports, such as record selection and the ability to change stored parameters. However, these options are limited in both scope and functionality. If your reports require little manipulation at runtime, and you need to produce a site quickly, use the Web Reports Server (see Web Reports Server Commands, Page 28).
The Reports Server Samples page appears. Here you can choose one of the Web Reports Server extensions and which Smart Viewer is used to display the reports.
After selecting a Web Reports Server extension and viewer, you can view any of five sample reports. This site demonstrates each of the Reports Server extensions and the Smart Viewers in a live environment. If you are unsure about which server extension or viewer you want to use on your own site, this page allows you to try each one and determine the best choice for your own needs.
NOTE: You may also choose to implement the Seagate Crystal Report Engine Automation Server inside Active Server Pages to distribute reports. This technique is substantially different from the Web Reports Server, though, and is discussed in Building Active Web Sites, Page 43.
The Web Reports Server extension for the Web Reports Server (CRWEB.DLL) implements both ISAPI and NSAPI programming interfaces. These interfaces provide powerful direct connections to Microsoft (ISAPI) and Netscape (NSAPI) web servers. If you are using a web server from either of these companies, you should consider using the Web Reports Server extension first. The web server CGI extension application (CRWEB.EXE) is designed to support the CGI standard. Since most web servers support CGI, the Web Reports Server can be installed with most any existing web server. Additionally, you may have security or other considerations that prevent you from choosing the web report server extension. Ultimately, the decision is straightforward. If you are using a Microsoft or Netscape web server, and no internal corporate or other business policies prevent you, you should use the ISAPI/NSAPI server extension. Otherwise, use the CGI web server application.
System Requirements
The Seagate Crystal Web Reports Server supports the following operating systems: Windows NT Server 4.0 or later with: Microsoft Internet Information Server (IIS) 2.0 or later, or Netscape Enterprise Server 2.0 or later Windows NT Workstation 4.0 or later with: Microsoft Personal Web Server, or Netscape FastTrack 2.0 or later Windows 95/98 with Microsoft Personal Web Server The Seagate Crystal Web Reports Server has been successfully tested with the following web server applications: Microsoft Internet Information Server (IIS) 2.0 or later Microsoft Personal Web Server Netscape Enterprise Server Netscape FastTrack 2.0 or later OReilly Lotus Domino Additionally, the CGI version of the Web Reports Server is compatible with many other CGI compliant web servers not listed here.
NOTE: Make sure that your web server has been stopped before beginning the install procedure.
When the splash screen appears, click Install Win 32 to begin installation. The Seagate Crystal Reports Setup window appears with the Welcome dialog on-screen (if the splash screen does not appear, run SETUP.EXE from the root directory of the CD).
2 3
Read the Welcome dialog, and click Next. The End User License Agreement appears. Read the license agreement completely and make sure you fully understand the Seagate Crystal Reports licensing requirements. Click Yes if you agree with the terms in the license. If you do not agree, you can not install Seagate Crystal Reports. In the next dialog that appears, enter your CD Key to install the software. Click Next to continue. Enter your name and organization. Click Next. In the Installation Type dialog box choose Typical to install all Crystal Components including Web Reports Server (recommended) or Custom to select the Components you specify. Continue at step 10 for the Typical installation or include steps 6 through 9 below if you are doing the Custom installation. If you do choose the Custom installation, then select Web Reports Server along with the following required components: Database Access, Developers Files, Exporting, MapInfo, Mapx, PGEditor, Sample Files, Seagate Crystal Reports Help.
4 5
NOTE: The Web Reports Server can also be installed through any of the other choices on the Choose Installation Type dialog, but you must then select Custom Installation in the Installation Options dialog box and specifically check the Web Report Servers check box in the Custom Installation Options dialog box. You may want to consider installing the entire Seagate Crystal Reports product on your web server system. With the entire product installed, problems with web reports can be quickly and easily analyzed by opening them inside the Report Designer directly on the web server system. 6 7 8 9
In the Installation Options dialog box, select a directory to install Seagate Crystal Reports files in, or accept the default directory. Select Custom installation, and click Next. The Custom Installation Options dialog box appears. Ensure Web Report Server is checked. Continue making any other changes to the custom installation options that you find necessary. This may include database drivers and export formats. Click Next in the Custom Installation Options dialog box.
10 Click Next to continue. If your web server is Netscape 2.0 or later, or IIS 2.0 or later then the Choose Web Server To Configure dialog box appears. 11 The Setup application attempts to detect the web server you are currently running. If it does, the dialog box will enable the check box for that particular server. If you have more than one web server running on the machine, Setup will allow you to configure all of the web servers to use the Web Reports Server. Check the check box for all web servers that you want to configure, and click Next. 12 The Web Server Startup Option Dialog Box will appear. If you want to install the Crystal Web Page Server and the Crystal Web Image Server as system services then click Yes. Click Next. A similar dialog box will appear. If you want to install the Seagate Query Server as a system service click Yes. Click Next. 13 The Choose Program Group dialog box will appear. Select a Program Group for your Seagate Crystal Reports program icons, and click Next. Setup will begin installing the necessary files for the Web Reports Server. 14 After the files have been installed the Web Reports Server Configuration dialog box will appear. If you make changes to the default configuration settings remember to click Apply before leaving the dialog box (by clicking OK). 15 Setup will now complete installation. After installation is completed a dialog box will appear indicating that your machine must be restarted before the new settings will take effect. Click OK and manually reboot your machine.
10
Installed Files
The following is a list of primary files installed for the Web Reports Server and their default installation directories.
q CRWEB.DLL: q CRWEB.EXE:
C:\Program Files\Seagate Software\Crystal Reports C:\Program Files\Seagate Software\Crystal Reports C:\Program Files\Seagate Software\Crystal Reports C:\Program Files\Seagate Software\Crystal Reports
q CRPGSVR.EXE:
q CRIMGSVR.EXE: q CRJM32.DLL:
NOTE: This is not a complete list of files installed when you install the Seagate Crystal Web Reports Server. It is only a list of principal Web Reports Server files. Refer to Crystal Reports on line Developers Help for the complete list.
Configuring NT Services
If you have installed the Seagate Crystal Web Reports Server on a Windows NT system, then The Seagate Crystal Web Page Server, Page 39, and The Seagate Crystal Web Image Server, Page 39 were installed under the System account. The following steps indicate how to correctly set up the Crystal Page Server and Crystal Image Server as NT Services under an NT Domain Administrator account.
1 2 3 4 5 6 7 8 9
While logged on as a Windows NT Domain Administrator, open the User Manager for Domains application. If you are not familiar with this application, refer to Microsoft Windows NT documentation. Select the New User command from the User menu in the User Manager for Domains. The New User dialog box appears. Enter a new user name to be used by the Web Reports Server. For instance: CRWEBUSER. Provide a password that you will remember. Toggle off the User Must Change Password at Next Logon check box. Toggle on the User Cannot Change Password check box. Toggle on the Password Never Expires check box. Click the Groups button, and make this user a member of the Administrators group. Click OK to close the New User dialog box, and exit the User Manager for Domains application.
10 Open the Services Control Panel. If you are not sure how to do this, refer to Microsoft Windows NT documentation. 11 Select Crystal Web Image Server in the Service list box, and click Startup. The Service dialog box appears. 12 Click Automatic in the Startup Type section of the dialog box. 13 Click This Account in the Log On As section of the dialog box.
11
14 Click the Browse button next to the This Account text box, then locate and select the user you just created (CRWEBUSER). 15 Enter the correct password for the user in the appropriate text boxes. 16 Click OK in the Service dialog box to save your changes. 17 Repeat steps 11 through 16 for the Crystal Web Page Server service. 18 Click Close in the Services control panel.
Select "Web Samples and Utilities Page" from the Crystal Reports Program Group menu or Open a browser (such as Internet Explorer or Netscape Navigator), and enter the following URL address: http://localhost/scrsamples The Seagate Crystal Reports Web Samples/Utilities Page appears in your browser.
2 3
Click the Reports Server Samples link. The Reports Server Samples page appears. Select whether the ISAPI/NSAPI Web Reports Server Extension, or the CGI Web Reports Server Extension, and click a viewer option supported by your web browser. A page appears with a list of five sample reports. Click the link for one of the sample reports. The report should be generated and displayed inside your browser using the viewer you selected.
If you have trouble getting the Web Reports Server running correctly on your web server, you may need to check the configuration on the web server itself. The following sections demonstrate how to do this in Microsofts Internet Information Server and Netscapes Enterprise Server.
1 2 3
Start the Internet Service Manager. Under Console Root, double-click the Internet Information Server to expose the machine you are using as the server. Right-click on the machine icon and choose Properties from the shortcut menu.
12
4 5 6 7 8
In the Properties dialog box, select WWW Service in the Master Properties section and click the Edit button. Click the Home Directory Tab to activate it. Click the Configuration button. Locate the extension .rpt and ensure that it points to the correct path for the file crweb.dll. By default, this file is installed in the default directory for Seagate Crystal Reports which you specified at runtime. Verify that the .cri extension also points to the correct path for the Web Reports Server extension.
Netscape Servers
To determine if the Crystal Web Reports Server is configured correctly on Netscape web servers, follow these steps:
Locate the MIME.TYPES file and the OBJ.CONF file. These files are normally located in the following directories:
q Netscape
Enterprise 3.51: <dir>\Netscape\SuiteSpot\https-<machinename>\config Enterprise 3.0: <dir>\Netscape\SuiteSpot\https-<machinename>\config Enterprise 2.0 and Netscape FastTrack: <dir>\Netscape\server\https-<machinename>\config
q Netscape
q Netscape
In MIME.TYPES, verify the following lines appear: type=magnus-internal/rpt type=magnus-internal/cri exts=rpt exts=cri
In OBJ.CONF, verify that the following line appears: Init fn="load-modules" funcs="CrystalReportServer" shlib="C:/Program Files/Seagate Software/Crystal Reports/crweb.dll"
In OBJ.CONF, under the heading <Object name="default"> verify that the following lines appear: NameTrans fn="pfx2dir" from="/viewer" dir="C:/Program Files/Seagate Software/Viewers" NameTrans fn="pfx2dir" from="/scrsamples" dir="C:/Program Files/Seagate Software/Crystal reports/sample" NameTrans fn="pfx2dir" from="/scrreports" dir="C:/Program Files/Seagate Software/Crystal Reports/Reports" Service fn="CrystalReportServer" method="(GET|POST)" type="magnus-internal/rpt" Service fn="CrystalReportServer" method="(GET|POST)" type="magnus-internal/cri"
5 6
If any of these lines are missing, add them to the appropriate file. Shut down the Netscape web server and reboot your web server system.
13
Virtual Directories
The following virtual directories should be set up on your web server pointing to the indicated paths:
q /viewer:
C:\Program Files\Seagate Software\Viewers C:\Program Files\Seagate Software\Crystal Reports\Reports C:\Program Files\Seagate Software\Crystal Reports\Sample
q /scrreports:
q /scrsamples:
Create a new directory on the server where your page will be located. For this example, we will use the directory c:\webroot\newsite
NOTE: For information on the location of your web servers root directory, refer to your web server software documentation. The directory shown here is intended only as an example. 2
Use your web server administration software to create a new virtual directory that points to the physical directory you just created. For this example, we will use the virtual directory http://localhost/newsite
Next, you must create a new physical directory and virtual directory for the reports your site will link to. http://localhost/scrreports/accounting
Using a simple text editor, such as Notepad, or your favorite HTML editor, create the following HTML code. <HTML> <HEAD> <TITLE>Index of Reports</TITLE> </HEAD> <BODY> <H1>Check out these reports!</H1> <HR>
14
<UL> <LI><A HREF="http://localhost/scrreports/accounting/hr.rpt"> Employee Profile </A></LI> <LI><A HREF="http://localhost/scrreports/accounting/mkpcat1p.rpt"> Product Catalog </A></LI> </UL> </BODY> </HTML>
5 6 7
Save the file as reportlist.htm in the c:\wwwroot\newsite directory. Open your web browser, and open the following URL: http://localhost/newsite/reportlist.htm Click one of the two links in your new web page to generate and display the report inside your browser.
In this example, you specified two RPT files using standard URL addresses. The RPT extension is analyzed by your web server, and is determined to be an extension that should be handled by the Web Reports Server application. The URL is handed off, and the Web Reports Server determines how to handle the requested RPT. When the report is displayed inside your browser, the Web Reports Server analyzes the type of browser you are using and delivers the report using a Smart Viewer it determines is appropriate. For example, if you are using Internet Explorer 4.0, you will see the report inside the Crystal Smart Viewer/ActiveX. If you are using Netscape Navigator 4.0, you will see the report inside the Crystal Smart Viewer/Java. As a web site designer, you can specify which viewer is used when the report is requested, overriding the default viewer used according to the browser. For example, the following URL forces the Java viewer to be used, even if you are running Internet Explorer or any other web browser: http://localhost/scrreports/accounting/mkpcat1p.rpt?init=java
NOTE: If the browser you are using does not support the technology used by the viewer specified, Java in this case, an error will occur or an empty web page will be displayed.
In this URL, INIT is a parameter recognized by the Web Reports Server. By setting the INIT parameter equal to java, you can force the Web Reports Server to use the Java viewer when displaying the report inside a browser. The Web Reports Server supports several parameters for controlling how reports are generated and displayed. For more information, see Web Reports Server Commands, Page 28.
15
NOTE: All changes made in the Web reports Server Configuration utility are stored in the Windows Registry. Any changes made in webconf.exe will not be effective until the web server is stopped and restarted.
16
Server Port
Use this text box to specify a TCP/IP port number for the Page Server to listen for requests and to return information. For valid values for this port, refer to your web server software or TCP/IP documentation. The default port, if available, is 2000. This port must match the port specified for Report (.rpt) files in the Server Mappings Tab, Page 22.
Virtual Path
This setting specifies the virtual path for the ActiveX and Java versions of the Seagate Crystal Smart Viewers. When you install the Web Reports Server, this path is set to: http://localhost/Viewer by default. If this path is not available, you must specify a different virtual path using your web server administration software.
17
The default physical path for the Crystal Smart Viewers, when you install Seagate Crystal Reports, is: C:\Program Files\Seagate Software\Viewers Use your web server administration software to set the virtual path to this directory, then specify that virtual path on the Page Server Tab for the Web Reports Server Configuration application.
Advanced Settings
Click the Advanced Setting button to access the Page Server - Advanced Settings dialog box.
Use this dialog box to make changes to the advanced configuration options of the Page Server. This dialog box exposes the following options:
Threads
The Page Server is a multi-threaded application that generates a new thread for processing every request it receives. Threads consume system memory and resources, though, and large numbers of threads can slow down the overall performance of a system. By specifying the maximum number of threads that can be generated by the Page Server, you control how much of the systems resources can be dedicated to responding to requests at any given time. If the number of requests received by the Page Server exceeds the number of threads specified, additional requests are held until threads are available. When determining a maximum number of threads, you should consider the available memory on the server system and the size of the reports that are commonly accessed. The larger the report, the more time that is required, thus tying up threads for longer periods.
18
Jobs
This option refers to the maximum number of report jobs that can be generated by the Job Manager. Every time a new report is requested, a new job is created. Set this to the maximum number of jobs that the Web Reports Server can have open at one time. More jobs allows faster report processing. However, each job require more memory resources, thus slowing down overall system performance. A balance must be found that allows fast report processing without slowing down the system. As a result once the maximum number of jobs has been exceeded older jobs are removed according do a Least Recently Used (LRU) algorithm.
Idle Time
Idle time is a period of time during which no actions occur. If a job, for instance, is unused for a large amount of time, it should be discarded by the Web Reports Server to allow those resources to be freed up for other jobs and requests. There are two types of idle time that you can set a maximum time for:
Close a job
A job refers to an actual report that has been generated and cached on the server. If no users request the report for the time specified, the report job will be closed and discarded. Thus, if someone requests the report after the job has been closed, a new job will need to be generated, causing an initial delay.
Close a client
Every request Id stored by the Page Server includes an Id for the client that made the request. If that client does not make any new requests or does not interact with an open report for the specified period of time, all requests corresponding to that client will be closed. If that client makes a new request after their client Id has been closed, they will experience a slight delay while the Page Server establishes a new request for them.
19
Server Port
Use this text box to specify a TCP/IP port number for the Image Server to listen for requests and to return information. For valid values for this port, refer to your web server software or TCP/IP documentation. The default port, if available, is 2001. This port must match the port specified for Crystal Image (.cri) files in the Server Mappings Tab, Page 22.
Threads
The Image Server is a multi-threaded application that generates a new thread for processing every image request it receives. Threads consume system memory and resources, though, and large numbers of threads can slow down the overall performance of a system. Use this option to specify a maximum number of threads that can be generated by the Image Server. If the number of requests received by the Image Server exceeds the number of threads specified, additional images are not generated until existing threads have been freed up.
20
NOTE: If a user exports to HTML format, the resulting report will not be available through the Web Reports Server.
21
Add button
Use the Add button to add a new file type mapping for the Web Reports Server. When you click Add, a dialog box appears asking for the file extension of the new file type, the TCP/IP hostname of the server, and the TCP/ IP port used by the application that handles that file type.
NOTE: In most cases, you do not need to add a file type mapping unless upgrading to another Seagate Software product.
22
Edit button
Use this button to change information about any of the file types listed in the Server Mappings list box. Select the item in the list, then click Edit. The Edit Mapping dialog box appears and allows you to make changes to the file extension, the TCP/IP host name of the server, or the TCP/IP port used by the application that handles that file type. For example, if the TCP/IP port used by the Page Server is changed on the Page Server Tab, Page 17, then you will also need to change the port setting for the .rpt file extension in the Server Mappings list box.
Delete button
Use Delete to remove any of the entries in the Server Mappings list box. Simply select the item in the list, and click Delete. You will be prompted to verify the delete before it is actually performed.
23
24
25
Smart Navigation
Smart Navigation, a feature of several of the Crystal Smart Viewers, presents your users with a tree control much like the tree control in Windows Explorer. The Web Reports Server dynamically analyzes a report when it is first requested, then populates the tree control with branches for each group in the report. Once displayed in your browser, the Smart Navigation Group Tree works like the Group Tree in the Seagate Crystal Reports Preview Tab. Simply expand and collapse branches in the Group Tree to find the section of the report you are most interested in. Click a branch to quickly jump to that part of the report. Web administrators can control access to Smart Navigation and the Group Tree by setting the Display Group Tree check box in the Smart Viewer options list box of the Report Viewing Tab, Page 23 in the Web Reports Server Configuration utility. The Configuration utility also allows you to control the maximum number of groups that are read and added to the Group Tree. If you choose to allow users to make use of the Smart Navigation Group Tree, keep in mind that generating the Group Tree forces the Web Reports Server to make an extra pass across the report, gathering group information and generating the Group Tree. This extra step in generating a report can tie up system resources and cause extensive delays in returning report data to the user, depending on the size of the report and how deep the grouping is. Consider the information your users need before deciding if Smart Navigation is right for your web site.
26
Although this method greatly reduces the amount of data sent across the network, it also affects the Group Tree. Group names are listed in the Group Tree as they normally would be. However, if you expand a group in the Group Tree, the detail information will not be available. The server sent only the group summaries to the client. Instead, a magnifying glass will appear beneath the group name in the Group Tree indicating that detail data can be retrieved. If the magnifying glass is clicked by the user, the Web reports Server will retrieve the detail data for that group and display detail groups or record names beneath the original group name. This process, however, requires querying the database. Keep in mind the time and resource requirements of such actions and design your reports and web site appropriately.
Database Location
When moving report files to a web server, be aware of changes in database location. If a report is created on one machine, then moved to the Web Reports Server machine, the relative location of the database information used to create the report may change. Installing the full Seagate Crystal reports package on your Web Reports Server system can often simplify report troubleshooting. By opening a report directly in the Report Designer, you can quickly determine the source of any problems accessing report data. For information on installation of the Web Reports Server, see Installing the Web Reports Server, Page 9. Running Page Server and Image server as NT services with Domain Admin privileges allows the database to be stored across the network and still be accessible.
27
reports are available throughout the company with point-and-click simplicity. information can be published on an extranet for easy access by stockholders and potential
q Corporate
investors. As a web server administrator, you must determine how data is accessed from your web site and exactly how much of the data is available. The Crystal Web Reports Server provides several commands that can be appended to URL requests in web page hyperlinks or passed via HTML Forms (this last option is recommended when accessing large sets of data). In addition, the Crystal Web Reports Server provides the option of automatically prompting users for security information, stored procedure parameters, and parameter field values. Use this section as your toolbox for designing Crystal Web Reports Server-enabled web sites.
NOTE: The features described here allow you to control access to report information on a limited basis. Although the commands described in this section provide a certain level of customization, you should consider using the Crystal Report Engine Automation Server, Page 111, to design web sites if you need more control over report data and formatting at runtime.
28
1 2
Select Web Samples and Utilities Page from the Seagate Crystal Reports Program Group menu Click on Web Reports Server Command Expert
29
The resulting URL and attached query string look like this: http://localhost/scrreports/Accounting/ wsale.rpt?sf={customer.Sales}>1000?init=html_page&rf=0&promptOnRefresh=0
INIT command
Specifies how the report should be displayed in the web browser. For example: init=java Possible values are:
q java q actx
- Crystal Smart Viewer for Java, Page 55 - Crystal Smart Viewer for ActiveX, Page 57 - Crystal Smart Viewer for HTML, Page 53 (with frames)
q html_frame q html_page
If the INIT command is not specified, the Crystal Web Reports Server will detect the type of browser requesting a report and will provide a default viewer for that browser. For instance, if the browser is Netscape Navigator 4.0, the Crystal Web Reports Server will display the report using the Crystal Smart Viewer for Java.
NOTE: Not all browsers support all methods of viewing reports. For instance, both the ActiveX viewer and Java viewer are unavailable in versions of Internet Explorer previous to 3.02. Internet Explorer also requires that Authenticode 2.0 be installed. Netscape Navigator does not support the ActiveX viewer at all, and does not support the Java viewer in versions prior to 3.0.
30
GF command
Specifies a group selection formula. This command is similar to SF command, Page 31 (selection formula). GF=<formula> <formula> is a selection formula in string format. For example: GF= Sum({customer.Sales},{customer.Region})>10000 Selects all groups in which the sum of all customer sales in each region is greater than 10,000.
SF command
Specifies a selection formula. SF=<formula> <formula> is a selection formula in string format. For example: http://server_name/reports/boxoffic.rpt?sf={studio.Studio}+%3d+Universal Selects all records where the studio is Universal.
NOTE: Reports that have the SF# or GF# commands applied will not have their pages shared. Caching will be by user.
NOTE: Although the Web Reports Server requires users to log on before it displays reports that access secured databases, security conflicts can arise if several people attempt to access the same report simultaneously. To prevent such conflicts, you should add security to your web site, preventing users from seeing and accessing secured reports. Forcing users to log on to the intranet site is a common solution to providing complete system security.
31
The following image is an example of a logon page that the Web Reports Server generates when encountering a report accessing secure data in a Microsoft SQL Server database. Depending on the type of data your reports are based on, the logon page that appears to your users may appear slightly different.
NOTE: If the database security has no password or a blank password, users will not be prompted by the Web Reports Server to log on. To ensure security, make sure databases have valid passwords.
To create hyperlinks in your web pages that handle user IDs and passwords automatically, use the USER# command, Page 33, and PASSWORD# command, Page 32. These commands will let you specify more than one user ID and password if the report connects to two or more secured databases. Keep in mind that if an incorrect user ID or password is sent, the Crystal Web Reports Server will prompt for user name and password again and prevent access to the report.
NOTE: The Crystal Web Reports Server applies a simple encryption algorithm to user names and passwords. If you are using a Microsoft web server, make sure your intranet or extranet site has the Secure Sockets Layer (SSL) encryption protocol installed and enabled to ensure complete security when accessing database information. Due to a documented problem in the Netscape web servers, SLL is not supported by the Web Reports Server on Netscape servers. For more information, refer to Netscape documentation.
PASSWORD# command
Specifies passwords for logging on to SQL, ODBC, or password-protected databases used by the report. PASSWORD#=<password> <password> is a string. For example: password0=secret
32
If the report accesses more than one password-protected database, multiple passwords can be passed by incrementing the index number. For example: password0=secret&password1=mystery&password2=unknown PASSWORD# is normally used in conjunction with the USER# command, Page 33. For example: user0=SmithJ&password0=secret&user1=JohnS&password1=mystery If the report contains subreports that require passwords for logging on to SQL or ODBC data sources, use the following syntax in the URL: password@subname#=<userid> subname is the name of the subreport. For example: user@Crosstab0=jimmys&password$Crosstab0=jimmyz
NOTE: Make sure passwords appear in the URL in the same order in which the password-protected databases appear in the report. Additionally if passwords are not passed using the URL address, the user will be prompted for logon information at runtime.
USER# command
Specifies user IDs for logging on to SQL or ODBC databases used by the report. USER#=<userids> <userids> is a string. For example: user0=SmithJ If the report accesses more than one password-protected database, multiple user IDs can be passed by incrementing the USER index number. For example: user0=SmithJ&user1=JohnS&user2=JSmith USER# is normally used in conjunction with the PASSWORD# command, Page 32. For example: user0=SmithJ&password0=secret&user1=JohnS&password1=mystery If the report contains subreports that require user IDs for logging on to SQL or ODBC data sources, use the following syntax in the URL: user#@subreportname For example: user0@Crosstab=jimmys&password0Crosstab=jimmyz
33
NOTE: If an existing report is inserted as the subreport, then the subreportname includes the file extension (for example, user0@subreportname.rpt). However, if the subreport was created inside the main report (with Insert | Subreport, and using the Report Expert to create the new report) then the name of the subreport usually does not contain a file extension (for example, user0@subreportname) unless one is added in the"Report Name" text box of the Insert | Subreport dialog box. NOTE: Make sure user IDs appear in the URL in the same order in which the password-protected databases appear in the report. Additionally, subreport user IDs must appear in the same order that the subreports appear in the report. If user IDs are not passed using the URL address, the user will be prompted for logon information at runtime. NOTE: Reports that have the USER# or PASSWORD# commands applied will not have their pages shared. Caching will be by user.
To prevent users from specifying their own values for parameter fields or stored procedures, use the PROMPT# command, Page 35 when specifying the URL of a report. PROMPT# lets you specify values for one or more parameter fields in a report. Alternately, you can design your own web based forms that accept user input and dynamically create the URL that includes the PROMPT# parameter and value.
NOTE: Users should not surround parameter values with quotation marks. All values are sent to the report as strings, regardless of the type of data. Parameters that expect numeric values interpret the string received when necessary.
34
The Crystal Web Reports Server does not validate any parameter values you specify for stored procedures or parameter fields. If the value you pass to the parameter is invalid, passing text information when a number is expected, for example, an error will not be returned to the web browser. In addition, the Crystal Web Reports Server does not allow you to change the format expected by parameters. Be sure to test any web site that accesses reports with stored procedures or parameter fields before allowing users to request such reports.
NOTE: Parameter fields and SQL stored procedures limit the effectiveness of report caching and job sharing. Since each report containing stored procedures or parameter fields may generate a different set of data every time it is requested, multiple requests for the same report may not be distributable among multiple users.
PROMPT# command
Specifies values for parameter fields in the report. parameter values are assigned to parameters in the order in which they exist in the report. PROMPT#=<value> <value> is a string. For example: prompt0=CA
NOTE: Do not use quotation marks around parameter values to indicate string values. All parameter values are passed to the report as strings. Intended numeric values are translated from strings to numbers by the report.
If the report contains more than one parameter field multiple values can be passed to parameters by incrementing the PROMPT index value. For example: prompt0=CA&prompt1=1000
NOTE: Make sure parameter values appear in the URL in the same order in which the parameter fields and stored procedures appear in the report. If parameter values are not passed using the URL address, the user requesting the report will be prompted to provide values at runtime. NOTE: Reports that have the PROMPT# command applied will not have their pages shared. Caching will be by user.
promptOnRefresh# command
Specifies whether report should prompt for parameter field values when refreshed. promptOnRefresh#=<value> <value> is 0 or 1. For example: promptOnRefresh=1
NOTE: Reports that have the promptOnRefresh command applied will not have their pages shared. Caching will be by user.
35
Report Exporting
The report server can export requested reports to the following formats,
q
q HTML q HTML
Crystal Reports(RPT) q Excel 2.1(XLS) q Excel 3.0(XLS) q Excel 4.0(XLS) q Excel 5.0(XLS) q Excel5.0(XLS)Extended q Rich Text Format(RTF) q Word Document(DOC) The report server will assign the CONTENT-TYPE header the appropriate MIME-TYPE, therefore the browser can be configured to launch the appropriate application after downloading the file. To issue a request to the report server to export a report, the query string must contain two commands. These commands are "CMD" and "EXPORT_FMT". The CMD command must always be assigned the value "EXPORT", and the "EXPORT_FMT" command is assigned the desired Export Format. The table below lists the supported export formats and their corresponding EXPORT_FMT representation.
q Seagate
36
For example: let's say that a user would like the report test.rpt downloaded to his browser in Microsoft Word format. The URL (ISO - Latin encoded) would be the following: http://mycomputer/test.rpt?cmd=EXPORT&EXPORT_FMT=U2FWORDW%3A0
37
The following diagram illustrates the components of the Web Reports Server.
ISAPI/NSAPI
The Web Reports Server extension implemented in CRWEB.DLL is both an ISAPI and NSAPI extension. By utilizing the API extensions exposed by Microsoft and Netscape web servers, CRWEB.DLL produces a faster, more robust system for report delivery to the web server. The ISAPI extension is supported by Microsoft Internet Information Server (IIS) versions 2.0 and later. Additionally, the Personal Web Server available for Windows NT Workstation, Windows 95, and Windows 98 also supports ISAPI extensions. The NSAPI programming interface is available on all Netscape web servers.
38
CGI
A second implementation of the Web Reports Server extension exists in the file CRWEB.EXE. This application conforms to the CGI standard. If you are using a web server other than a Microsoft or Netscape server, the CGI version of the Web Reports Server can easily be installed with your existing web server software.
NOTE: Crystal Image files are not used if the report is rendered as an Encapsulated Page File (EPF) for display inside the Crystal Smart Viewers for ActiveX, Java, or Java Beans.
NOTE: The Web Reports Server limits report caching features with reports based on SQL stored procedures or that include parameter fields. Such reports may generate a different set of data every time they are requested, due to the dynamic values passed to the parameter field or stored procedure. Thus, multiple requests for the same report may actually produce separate report jobs.
39
Report Formats
When the Page Server generates a report, it will translate it into either HTML pages or Encapsulated Page File (EPF) pages. The output depends on how the report will be viewed in the browser. If the browser requests viewing a report as HTML or HTML frames, the Page Server will generate HTML pages containing Crystal Images where appropriate. (Crystal Images are, in turn, interpreted by the Image Server. See The Seagate Crystal Web Image Server, Page 39.) If the browser requests to view a report inside the Java viewer or the ActiveX viewer, then the Page Server generates EPF pages. HTML and HTML frames can be viewed inside any browser that supports the HTML 3.02 standard. This general standard makes HTML reports ideal for sites that may use a wide range of browsers or in secure sites that do not allow ActiveX controls or Java applets. However, HTML is a limited display format, and reports may lose some of the design features available in Seagate Crystal Reports. EPF is a Seagate format based on the Encapsulated Postscript format (EPS). As a result, EPF reports can handle complex layout and design descriptions. When viewed inside the browser, EPF reports retain most if not all of the design and layout elements of the report originally created in Seagate Crystal Reports, providing a cleaner, more accurate display of the information. As a proprietary format, though, EPF reports can only be displayed inside the ActiveX or Java based Smart Viewers.
NOTE: EPF files do not retain formatting information set by printer drivers. Examples of such formatting include page size and page orientation.
Report Processing
When the Page Server gets a request for a new report, it must obtain a new request Id from the Job Manager and determine if the Job Manager needs to obtain a new job Id from the Report Engine. If a new job Id is required, the Report Engine must actually generate a new report. The interaction between the Page Server, the Job Manager, and the Report Engine has been designed to maximize performance in intranet and extranet environments. The Crystal Reports Job Manager must generate new request Ids for every request the Web Reports Server receives. If the Page Server determines that the requested report already exists in the cache, it will simply obtain a new request Id from the Job Manager, then match that request to the job Id of the existing report. If the report has not been cached, the Page Server must obtain a new job Id from the Job Manager, as well as a new request Id. If the Page Server demands a new report job Id from the Job Manager, the Job Manager will start the Report Engine and have it generate the new report. The Report Engine creates a job Id for the new report and returns it to the Job Manager which, in turn, returns both the job Id and the request Id to the Page Server.
Report Engine
The Report Engine is the component which actually generates reports. The Report Engine opens a requested RPT file, locates the necessary data, and produces a complete report file. If you are an application developer, this is the same Report Engine that you can add to your own applications (see Crystal Report Engine, Page 63 for more information). Every report produced by the Report Engine has a unique job Id to identify that report. The Page Server uses the job Id to determine what actual report must be used for a specific client request.
40
A new report Job is created. A cache is created, which will hold report pages as they are requested. A reference to the report job is created. The reference has a unique id (Request Id) by which the client can access the job in the future. is usually a refresh interval associated with a report job.This is the time interval (specified as the Database Refresh Time in the Configuration Manager) after which a new request for the same report will result in accessing the database for updated information. In other words if a new client requests the report after the refresh interval for the existing report job then new report job is created as a result.
q There
q If
a client referencing an existing report job selects refresh then a new report job is created and the client gets a reference to the new job.
Job Sharing
If the report contains saved data and there are no SF# and GF# commands or if a report does not have saved data and there ar no SF#,GF#,PASSWORD#,USER#,PROMPT# or promptOnRefresh# commands then the resulting report job can be shared. What this means is that requests for the same report (which occur within the same refresh interval) will result in references to the same report job. There are conditions under which a shared report job will no longer be shared:
q If
a client sharing an existing report job selects refresh then a new report job will be created and the client will receive a reference to the new report job. a client sharing an existing report job submits a page request that includes one of the commands listed previously then a new report job will be created and the client will receive a reference to the new report job.
q If
Page Caching
Associated with each report job is a cache to store requested pages. The pages are generated as requested, passed to the client and stored in the cache. If another client, who is sharing the same report job, requests a page which is already cached then that client will received the cached page. This can greatly reduce access time (subject to the traffic conditions of your network at any given time).
41
Job Examples
Reports with Saved Data
A report that is saved with data and does NOT have the sf or gf parameters applied to it, will have its pages shared by all users. If the report has the gf or sf parameters applied, the caching will be by user (same as Crystal Reports 6.0).
6. Four minutes after User C requested Report A1, User B selects his viewer's refresh button. User B, User A and User C will share cached pages because User B requested accessing the database inside the database refresh time interval. The database was accessed four minutes before by User C, and the database refresh time is 5 minutes. 7. If the report has the sf, gf, user#, password#, promptOnRefresh#, or prompt# parameters applied, the caching will be by user (same as Crystal Reports 6.0).
42
Volume 1
43
NOTE: For additional information on the objects, methods, and properties provided by the Seagate Crystal Report Engine Automation Serve, Please see Crystal Report Engine Object Model for the Automation Server, Volume 3, Chapter 6.
44
With a web project open in Visual InterDev, add a new Active Server Page. For more information on opening web projects and adding ASP pages, refer to the Visual InterDev documentation. For this example, the web project will be named MySite and the new ASP page will be named ReportPage.asp. Choose the ACTIVEX CONTROL command from the Insert|Into HTML menu. The Insert ActiveX Control dialog box appears. Click the Design-Time Tab to display design-time ActiveX controls that are registered on your system. Highlight the CrystalReport.DTC design-time control, and click OK. Close the Properties dialog box if it appears. The Visual InterDev Design-time ActiveX Control appears in the Microsoft Developer Studio window. Toggle the Use Existing Report check box on, if it is not on already. This disables most of the controls in the design-time control. If you have not added a data connection to your web project, this check box will automatically be toggled on and disabled. Click Browse to select the report you want displayed in your web site. The Select Report Name dialog box appears. Use this dialog box to locate and select the desired report. Enter a standard DOS path to the report. Do not use a URL address or a UNC path. Click Open when finished. The selected report appears in the Report Name text box of the design-time control. From the Viewer drop-down list, select the Crystal Smart Viewer you want to use to display the report.
2 3 4 5 6
7 8
10 When finished, close the window that contains the Visual InterDev Design-time ActiveX Control.
Once you close the design-time control, the ReportServer Active Server Page (RPTSERVER.ASP) is added to your project, along with the report file you selected in the design-time control. The ReportServer Active Server Page contains the VBScript code that communicates with the Crystal Report Engine Automation Server. This page is required by any web project that uses the Crystal Report Engine Automation Server to display reports. In addition, the design-time control adds several lines of VBScript code to your web page. This code is designed to work with the ReportServer Active Server Page and the Crystal Report Engine Automation Server to display the report selected inside the specified Crystal Smart Viewer. For information on how to edit this code, see Editing Active Server Pages, Page 47. To test your new Active Server Page, save the file to your web server, select the page in your Project Workspace window, and choose the PREVIEW IN BROWSER command from the File menu. Visual InterDev will open your web browser and display the Active Server Page that contains the instructions to open the report.
45
1 2 3 4
With a project open in Visual InterDev, choose the DATA CONNECTION command from the Project|Add To Project menu. The Select Data Source dialog box appears. To select an ODBC data source, click the Machine Data Source Tab. Select a data source from the Data Source Name list, and click OK, or click NEW to create a new data source. Once you click OK in the Select Data Source dialog box, the data source will be added to your project. Save your project.
NOTE: You may be required to specify logon information when you select a data source. For complete information on adding data sources to a web project, refer to your Visual InterDev documentation.
Now that your project contains a data source, the Visual InterDev Design-time ActiveX Control can be used to create an Active Server Page that dynamically creates and displays a report based on this data source.
1 2 3 4 5 6 7 8 9
Choose the NEW command from the File menu. The New dialog box appears. On the Files Tab of the New dialog box, select Active Server Page. Enter a name for the new Active Server Page in the File name text box, and click OK. The new Active Server Page is created and appears in the Microsoft Developer Studio. Make sure the comment <!-- Insert HTML here --> is highlighted, and choose the ACTIVEX CONTROL command from the Insert|Into HTML menu. The Insert ActiveX Control dialog box appears. Click the Design-Time Tab to display the design-time ActiveX controls that are registered on your system. Highlight the CrystalReport.DTC design-time control, and click OK. Close the Properties dialog box if it appears. The Visual InterDev Design-time ActiveX Control appears in the Microsoft Developer Studio window. Toggle the Use existing report check box off, if it is not off already. In the Data Connection drop-down list, select the database corresponding to the data source you added to your project.
10 In the Record Source drop-down list, select a database table from the database. 11 In the Columns list box, toggle the check box on for any field you want as a column in your report.
46
NOTE: If you are familiar with the SQL language, you may prefer to click the SQL option in the Source Type box and click the Builder button. The Builder button opens the Visual InterDev Query Builder, allowing you to design a SQL statement that retrieves data from your data source. 12 Select a Crystal Smart Viewer from the Viewer drop-down list. 13 Close the design-time control.
Once again, several lines of VBScript code are added to your Active Server Page. Microsoft IIS will run this code at runtime and will dynamically generate a report based on your data source.
47
In the VBScript code, the OpenReport call accesses the report file you specified in the design-time control, creating an instance of the Report object. A few lines below the OpenReport method, you will find the ReadRecords method. ReadRecords obtains data and generates the final report that will be displayed in the web browser. Using these two calls, you can modify the format and data displayed in the report. As stated before, the VBScript code provided by the design-time control creates a Report object through which your reports can be manipulated. For instance, the following code sets a record selection formula for the report at runtime: session(oRpt).RecordSelectionFormula = {customer.Region} =CA" Notice that the Report object is stored in the session object. For complete information on the session object, refer to the Microsoft documentation for Active Server Pages.
Session Timeout
By default, the session object provided by Visual InterDev for your project has a timeout value of 20 minutes. When designing web sites that use the Report Engine Automation Server and the Visual InterDev Design-time ActiveX Control, you will not be able to edit reports using Seagate Crystal Reports for 20 minutes after viewing them in a browser. Once your web site is designed and finished, this timeout period may be just fine. However, during the development process, you may want to alter the session timeout period. The Session object has a Timeout property that determines how long the session waits before timing out. During development, add a line of code to your Active Server Pages to set the Timeout property to a much shorter timeout period, such as 1 minute. The following code demonstrates this: session.Timeout = 1 Be sure to remove the line of code before making your web site available to other users.
48
Volume 1
49
Although changing these defaults is not necessary, there may be times when you need to manually write web pages that display a specific viewer despite the browser being used, or when you want to customize your web site by editing the code created by the design-time control. This chapter explains how to understand and work with the Crystal Smart Viewers directly in your web pages. If you are designing web sites using one or more of the Crystal Smart Viewers, be aware that only the Java Viewer can be directly assigned a report file through one of its parameters. This means that the Web Reports Server, in most cases, must provide the Smart Viewer for you, and any customization must be done through the The Web Reports Server Configuration Application, Page 16. If you develop sites using the Crystal Report Engine Automation Server, though, or if you connect to the Web Reports Server from Active Server Pages or Visual Basic, you have several options for configuring the Smart Viewers. For further information on using Crystal Smart Viewers inside Active Server Pages, refer to Customizing the Crystal Smart Viewer, Page 47. For further information on connecting to the Web Reports Server from Visual Basic, see Connecting to the Web Reports Server, Volume 3, Chapter 1.
NOTE: This chapter is intended as a supplement to the web design solutions presented in Seagate Crystal Web Reports Server Overview, Page 2, and Building Active Web Sites, Page 43. It is assumed that you are familiar with the concepts in at least one of those two chapters.
50
Features
View Graphs View embedded maps Smart Navigation Tree Drill down on graphs & summarized data Export to Word, Excel, HTML, RPT Change Record Selection Expert Search for specific data value View subreports Drill on out of place subreports
ActiveX
Yes Yes Yes Yes Yes Yes Yes Yes Yes
Java
Yes Yes Yes Yes Yes Yes Yes Yes Yes
Java Bean
Yes Yes Yes Yes Yes Yes Yes Yes Yes
HTML Frames
Yes Yes Yes
HTML Page
Yes Yes
Yes Yes
Yes Yes
If your reports make use of a particular reporting feature, verify that feature is available in the Smart Viewer you choose before designing your site.
51
Consider a report that is designed and formatted on the first machine, where printer settings are used to determine font size and the size and position of objects in the report. When the web server generates that report, the printer it is connected to may force the length and size of a font to change. However, the field and text objects will maintain a fixed size and position. Thus, generating the report on the web server may cause text to be clipped or may create extra blank spaces between fields. If, however, some report objects are formatted with the Can Grow formatting option, these objects will resize themselves as the size of the text font is resized by the new printer. Once resized, though, those objects may change the pagination. The Crystal Smart Viewer for Java and the Crystal Smart Viewer for HTML will display the report in a web browser as it is generated by the web server, so these formatting problems may affect how reports appear to users. The Crystal Smart Viewer for Java does not allow a user to print a report from the web browser due to restrictions in the Java language. The Crystal Smart Viewer for HTML will simply print the HTML page exactly as it appears in your web browser. In contrast, the Crystal Smart Viewer for ActiveX allows you to print a formatted report from a web browser. As a result, an additional level of formatting problems may appear in the printed report if the machine on which the web browser is running is connected to a third printer with different settings. When designing reports that will be viewed through one of the Crystal Smart Viewers, use report fonts common on all systems to prevent resizing and pagination problems, and always test reports on a client machine before distributing them to users.
NOTE: The Crystal Smart Viewer/Java Bean is intended primarily for application development and is, therefore, not discussed in this chapter. Instead, this chapter concentrates on the Smart Viewers intended for web site development and that can be distributed by the Web Reports Server or added using the Crystal Design-Time ActiveX control.
A common use of the Crystal Smart Viewers in application development is when designing N-tier applications that may use the Crystal Web Report Server, Page 1, the Seagate Crystal Report Engine Automation Server, Page 44, or the The Report Designer Component, Page 145, as a middle tier and the Smart Viewer as part of the client user interface. For more information on using the ActiveX and Java Bean versions of the Crystal Smart Viewers in application design, see Application Development with Crystal Smart Viewers, Volume 3, Chapter 1.
52
NOTE: If you drill-down on data and then click the Back button on a Netscape browser 3.x, you may encounter JavaScript errors. To prevent these errors, click the corresponding tab for the view you want retrieved, rather than the Back button.
Object Layout/Positioning
HTML 3.2 translation preserves relative positioning of objects and fields. However, absolute positioning, height, and width is browser dependent.
Objects Translated
Object
Field Objects Text Objects Graphic, Blob, Chart Objects OLE Objects Cross-Tab Objects Subreport Objects
Translated/Not Translated
Yes Yes Yes, as JPEG images. Yes, as JPEG images. Yes Yes
53
Object
Out of place subreports Map objects Line and Box Objects
Translated/Not Translated
No Yes, as JPEG images No
Other Limitations
Overlayed Report Objects
q HTML
3.2 does not support overlaying. Report objects which are partially overlayed (even a tiny fraction) will appear alongside each other.
all 4 sides of the object have a border, an HTML box is drawn around the report object.
either a bottom or top side of the object has a border, an HTML horizontal rule is drawn above or below the object accordingly (lone vertical borders are not translated). lines appear as solid lines. lines appear as thick solid lines.
the Tight Horizontal option is selected, HTML box width will be the approximate width of report object or width of data. the Tight Horizontal option is not selected, HTML horizontal rule width will be the width of report object. heights appear as Height of font only.
q If
q Border/rule
Drill-down
q Group q Chart q Map
drill-down is supported.
54
NOTE: If you drill-down on data inside the Java viewer, and then click the Back button on a Netscape browser 3.x, you may encounter JavaScript errors. To prevent these errors, click the corresponding tab for the view you want retrieved, rather than the Back button.
Parameters
The Crystal Smart Viewer for Java provides the following parameters:
CanDrillDown
Indicates whether or not the user can drill-down on summary data, graphs, or charts in the report. Use TRUE to allow drill-down, FALSE to prevent drill-down.
HasExportButton
Indicates whether or not an Export button appears on the Smart Viewer. The export button allows users to export reports displayed in the Smart Viewer to Microsoft Word, Microsoft Excel, HTML 3.2, or Seagate Crystal Reports format. Use TRUE to allow exporting, FALSE to prevent it. This setting can be overridden by settings made in the Web Reports Server Configuration utility. See the Export Report Allowed check box, Page 21.
55
HasGroupTree
Indicates whether or not the viewer generates a Group Tree for the report. Does not indicate whether or not the Group Tree is displayed. Use TRUE to generate a Group Tree, FALSE to prevent a Group Tree from being generated.
HasPrintButton
Indicates whether or not the viewer includes a print button allowing the viewed report to be printed. Use TRUE to allow printing, FALSE if printing is not allowed. Printing from the Java Smart Viewer requires a web browser or Java Virtual Machine that supports version 1.1 or later of the Java Developers Kit (JDK).
HasRefreshButton
Indicates whether or not a Refresh button is available in the viewer to allow the user to refresh report data. Use TRUE to allow users to refresh report data, FALSE to prevent users from refreshing report data.
HasTextSearchControls
Indicates that the viewer includes controls to allow searching for specific values in the report. Use TRUE to allow searching, FALSE to prevent search controls from being displayed.
ReportName
Specifies the report to be displayed inside the viewer. The path must be a URL on the same server as the HTML document and must be placed inside quotation marks.
ShowGroupTree
Indicates whether or not the Group Tree is displayed when the viewer first appears. If the HasGroupTree parameter is set to False, this parameter is ignored. If the Group Tree is hidden, the user can display it by clicking the Toggle Group Tree button in the viewer. Use TRUE to display the Group Tree, FALSE to hide the Group Tree.
Example
The following code demonstrates one means of embedding the Crystal Smart Viewer for Java in a web page. This JavaScript code determines browser version and then installs the appropriate version of the Java Smart Viewer. <SCRIPT LANGUAGE="JavaScript"><!-var _ns3 = false; var _ns4 = false; //--></SCRIPT> <COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!-var _info = navigator.userAgent; var _ns3 = (navigator.appName.indexOf("Netscape") >= 0 && _info.indexOf("Mozilla/3") >= 0); var _ns4 = (navigator.appName.indexOf("Netscape") >= 0 && _info.indexOf("Mozilla/4") >= 0 ); //--></SCRIPT></COMMENT>
56
<SCRIPT LANGUAGE="JavaScript"><!-if(_ns3==true) document.writeln( '<applet code=com.seagatesoftware.img.ReportViewer.ReportViewer codebase="/viewer/JavaViewer" id=ReportViewer width=100% height=95% archive="/viewer/JavaViewer/ReportViewer.zip">' ); else if (_ns4 == true) document.writeln( '<applet code=com.seagatesoftware.img.ReportViewer.ReportViewer codebase="/viewer/JavaViewer" id=ReportViewer width=100% height=95% archive="/viewer/JavaViewer/ReportViewer.jar">' ); else document.writeln( '<applet code=com.seagatesoftware.img.ReportViewer.ReportViewer codebase="/viewer/JavaViewer" id=ReportViewer width=100% height=95%>' ); //--></SCRIPT> <param name=Language value="en"> <param name=ReportName value="empprof.rpt"> <param name=ReportParameter value=""> <param name=HasGroupTree value="true"> <param name=ShowGroupTree value="true"> <param name=HasRefreshButton value="true"> <param name=HasPrintButton value="true"> <param name=HasExportButton value="true"> <param name=HasTextSearchControls value="true"> <param name=CanDrillDown value="true"> <param name=PromptOnRefresh value="true"> <param name=cabbase value="/viewer/JavaViewer/ReportViewer.cab"> </applet> This example will display the empprof.rpt report in the Crystal Smart Viewer for Java window. A Group Tree will be generated to allow Smart Navigation, but it will be hidden initially. The viewer does not allow a user to refresh the report data.
57
AuthentiCode Certification
The Crystal Smart Viewer for ActiveX is certified by Microsoft AuthentiCode 2.0. This certification requires Microsoft Internet Explorer 3.02 or later in order to open the ActiveX control. If you do not have a recent version of Internet Explorer, refer to the Microsoft web site to upgrade or use a different Crystal Smart Viewer when designing your web sites.
NOTE: For additional information on the OBJECT tag, refer to your Microsoft documentation.
When you install the Crystal Web Report Server, the Crystal Smart Viewer for ActiveX is installed under \Program Files\Seagate Software\Viewers\ActiveXViewer. Additionally, a virtual directory named /viewer is set up on your web server, which points to the \Program Files\Seagate Software\Viewers directory.
58
Parameters
The Crystal Smart Viewer for ActiveX provides several optional parameters to customize the look of the viewer and to control its functionality. Apply values to these parameters by using the standard PARAM tag in your HTML code:
DisplayGroupTree
Indicates whether the Group Tree is displayed when the viewer first appears. If the Has Group Tree parameter is set to false, this parameter is ignored. If the Group Tree is hidden, the user can display it by clicking the Toggle Group Tree button in the viewer.
qA qA
value of 1 (TRUE) displays the Group Tree. value of 0 (FALSE) hides the Group Tree.
EnableAnimationControl
Indicates whether the viewer displays the Animation Control. The Animation Control runs while a report is being generated and downloaded. Once the report completely arrives at the client web browser, the animation stops.
qA qA
value of 1 (TRUE) displays the Animation Control. value of 0 (FALSE) prevents the Animation Control from being displayed.
EnableDrillDown
Indicates whether a user can drill-down on summary values in a drill-down report. In a drill-down report that appears in the Crystal Smart Viewer for ActiveX, the mouse pointer becomes a magnifying glass over any group or value that can be drilled down on. Double-click the group or value to display a separate Drill-Down Tab inside the viewer.
qA qA
value of 1 (TRUE) indicates the user can drill-down on reports. value of 0 (FALSE) indicates the user is not allowed to drill-down on reports.
EnableExportButton
Indicates whether or not the Export button appears in the Smart Viewer. If the Export button appears, the user can export the displayed report to Microsoft Word, Microsoft Excel, HTML 3.2, or Seagate Crystal Reports format.
qA qA
value of 1 (TRUE) displays the Export button. value of 0 (FALSE) prevents the Export button from being displayed.
59
EnableGroupTree
Indicates whether the viewer generates a Group Tree for the report. Does not indicate whether or not the Group Tree is displayed. If HasGroupTree is set to 0, ShowGroupTree will automatically be set to 0.
qA qA
value of 1 (TRUE) generates a Group Tree. value of 0 (FALSE) prevents a Group Tree from being generated.
EnablePrintButton
Indicates whether the user can print the report to a printer. When the user clicks the Print button, the report is sent to a printer according to the settings selected by the Standard Print dialog box. If the Has Print Button is set to 0, then you can not print. For more information, see Printing from the Crystal Smart Viewers, Page 51.
qA qA
value of 1 (TRUE) displays the Print button. value of 0 (FALSE) prevents the Print button from being displayed.
EnableRefreshButton
Indicates whether a Refresh button is available in the viewer to allow the user to refresh report data.
qA qA
value of 1 (TRUE) allows users to refresh report data. value of 0 (FALSE) prevents users from refreshing report data.
EnableSearchControl
The Search control and button that appear in the Crystal Smart Viewer for ActiveX allow a user to easily search for and jump to instances of a specific value or field that appear in the report. The user enters the value of interest in the drop-down list, then clicks the Search button to find the first instance of that value. Clicking the button again finds successive instances of the value in the report.
qA qA
value of 1 (TRUE) displays the Search controls. value of 0 (FALSE) prevents the Search controls from being displayed.
EnableZoomControl
Use the Zoom Control to switch between levels of magnification in Crystal Smart Viewer for ActiveX. With the Zoom Control, you can magnify the report up to 400% of its original size, or reduce it down to 25% in order to see more of the report at once.
qA qA
value of 1 (TRUE) displays the Zoom Control. value of 0 (FALSE) prevents the Zoom Control from being displayed.
60
61
This example will display a Group Tree to allow Smart Navigation. Additionally, the user can drill-down on summary reports, refresh report data, and print the report to a printer. Notice that reports can not be directly assigned to the ActiveX viewer. For information on using the ActiveX viewer inside web pages, see Customizing the Crystal Smart Viewer, Page 47. For information on using the ActiveX viewer inside other applications and development environments, see Seagate Crystal Smart Viewer for ActiveX, Volume 3, Chapter 1.
62
Volume 1
63
NOTE: For more information regarding current runtime file requirements, see the Runtime File Requirements online Help.
From your application, you can access the Crystal Report Engine through any of several Crystal Report Engine development tools:
q Crystal q Crystal q Seagate q The q The
ActiveX Controls, Page 108 (CRYSTL16.OCX or CRYSTL32.OCX) Report Engine Automation Server, Page 111 (CPEAUT.DLL or CPEAUT32.DLL) Crystal Visual Component Library, Page 193 (UCRPE.DCU or UCRPE32.DCU)
Crystal Report Engine Class Library, Volume 2, Chapter 2 (PEPLUS.H and PEPLUS.CPP) Crystal NewEra Class Library, Volume 3, Chapter 7 Report Engine API, Page 68 (CRPE.DLL or CRPE32.DLL)
q Crystal
When your application runs, it links with the Crystal Report Engine to access report writing functionality. Reporting can be simple, producing only a single report that is sent to a printer or preview window with no options available to the user, or it can be complex, allowing the user to change such things as record selection, sorting, grouping, or export options.
NOTE: All references to CRPE32.DLL are for the 32-bit version. If you plan on using the 16-bit version, it is called CRPE.DLL.
Sample Applications
Seagate Crystal Reports comes with a number of sample applications that show you how to incorporate the capabilities of the Crystal Report Engine. Use these applications to further your understanding of the Crystal Report Engine and how to use it in various programming environments.
64
Exporting Reports
The Crystal Report Engine enables you to print to a printer or a preview window with simple function calls. In addition, you can export a file in multiple formats and to multiple destinations. For example:
q through q directly q to q to q to q to
HTML for updating a web site a Microsoft Exchange folder a Lotus Notes folder an ODBC data source
The report can be exported in any of several word processing, spreadsheet, database file, or data exchange formats including HTML.
Crystal Report Engine outputs existing reports. You can not create report files using the functionality of the Crystal Report Engine. Reports must be created using the Seagate Crystal Reports application described in the Seagate Crystal Reports Users Guide. Make sure you understand the report creation process before trying to print reports with the Crystal Report Engine.
NOTE: Visual Basic programmers can use the Active Data Driver, along with the Crystal Report Engine API or the Crystal Report Engine Automation Server to create reports dynamically at runtime. For more information, refer to Active Data Driver, Page 118.
q The
Crystal Report Engine provides a convenient add-on to your existing application development project. With just a few lines of code, you can produce a powerful report writing and distribution tool that would take thousands of lines of code and weeks to produce otherwise. Crystal Report Engine does not require the use of a fixed user interface. The Crystal Report Engine is designed to work with your existing development project and allows you to define the user interface your customers and users are familiar with and expect from your application.
q The
65
Step 2: Designing the user interface that drives the Crystal Report Engine
The interface you develop to allow users to print reports is limited only by your needs and your imagination. The kind of user interface you select is unimportant to the Crystal Report Engine. Common methods of using the Crystal Report Engine include a single menu command that produces a single report, a dialog box allowing several options for printing reports, or a completely separate front-end application that is called by your application. All are acceptable techniques, and each has its advantages. How you design your user interface can depend on any or all of the following:
q The q The q The
purpose of your application. types of reports your application will use. printing options you want to make available with those reports. your application will offer only one report or a choice of several reports.
q Whether
Consider your application and your reporting needs carefully, and design a User Interface that will use the Crystal Report Engine most efficiently.
66
ActiveX Controls, Page 108 Report Engine Automation Server, Page 111 Crystal Visual Component Library, Page 193
Crystal Report Engine Class Library, Volume 2, Chapter 2 Crystal NewEra Class Library, Volume 3, Chapter 7 Report Engine API, Page 68
q Crystal
Be aware that you can not use two or more of these tools in the same application. For example, you can not create a Visual Basic application that contains the Crystal ActiveX control and also makes calls to the functions in the Crystal Report Engine API. You must choose one tool to implement the Crystal Report Engine in your project and stick with that tool. When choosing a Crystal Report Engine tool, consider the following:
q What q What q Do
you need to implement the entire Crystal Report Engine or just a few features of it?
For example, the Crystal Class Library for NewEra is specifically designed for Informix NewEra. Therefore, if you are programming in Visual Basic, the Crystal Class Library for NewEra is not an option. The Crystal Report Engine Class Library, on the other hand, is based on the Microsoft Foundation Class Library for C++. To use the Crystal Report Engine Class Library, you must be using a C++ development tool, and you must be using the MFC library. If you are an experienced programmer, you might consider the Crystal Report Engine API or the Crystal Report Engine Class Library. Novice programmers, on the other hand, may want to take advantage of the easy-to-use features of the Crystal ActiveX control, or the Visual Component Library. The Crystal Report Engine API consists of a large number of functions exposed directly from the Crystal Report Engine DLL. These functions provide a wide range of power and flexibility for adding report writing features to your own applications.The rest of this chapter discusses the process required to use the Crystal Report Engine API in your own applications. Although the examples in the following sections concentrate on the C programming language, the concepts should be studied by anyone using the API functions in any language. Additional information specific to Visual Basic programmers using the API can be found in Using the Crystal Report Engine API in Visual Basic, Page 104. Additional information for Delphi programmers is located in Using the Crystal Report Engine API in Delphi, Page 68. If you wish to use a Crystal Report Engine development tool other than the Crystal Report Engine API, refer to the table of contents for this manual, or search for the name of the programming language or development environment you are using in Developers online Help.
67
NOTE: Many functions and records are defined differently for 16-bit and 32-bit systems. When referring to declarations in reference sections, make sure you are using the correct version of the function or record for the operating system environment you are working in.
68
Working with Parameter Values and Ranges, Page 83 Working with section codes, Page 84 Overview, Page 84 Encoding, Page 84 Decoding, Page 86 Section Map, Page 87 Section Codes in Visual Basic, Page 88 Crystal Report Engine API variable length strings, Page 89 Sample Code, Page 90 Code Evaluation, Page 91 Crystal Report Engine API structures, Page 92 Working with subreports, Page 93 Changing report formats, Page 94 The Crystal Report Engine API (REAPI) is the most direct method of adding the Crystal Report Engine to your application project. The Crystal Report Engine itself is a Dynamic Link Library (DLL), and, therefore, exports its functionality in the form of DLL functions. These functions make up the Crystal Report Engine API. The Crystal Report Engine DLL, CRPE.DLL (16-bit) or CRPE32.DLL (32-bit), was installed in your \WINDOWS\SYSTEM directory when you installed Seagate Crystal Reports. This assures that the DLL is available to any application on your system that uses the Crystal Report Engine.
NOTE: For complete information on distributing Crystal Report Engine and other runtime DLLs with your application, refer to the Runtime File Requirements online Help.
The process for loading a DLL and calling DLL functions is a well documented aspect of the Windows API. If you are not familiar with working with DLLs, please refer to Windows API documentation before attempting to use the Crystal Report Engine API. You may also want to consider one of the other methods described in this section for adding the Crystal Report Engine to your application. The rest of this section assumes an understanding of DLLs and how to use them in a Windows application. It also assumes a basic understanding of the C language. The examples here are written in C, and do not cover the LoadLibrary, GetProcAddress, or FreeLibrary calls. Many Windows development environments support direct calls to DLL functions, Visual Basic, Visual dBASE, and Delphi, for example. Refer to the documentation for your development environment for complete instructions on using a DLL. Your documentation may also cover instructions on how to translate C function calls to the language you use. Study your documentation, then review the steps described here for using the Crystal Report Engine in an application via the Crystal REAPI.
69
q GLOBAL.BAS
and GLOBAL32.BAS declare all Crystal Report Engine API functions for Visual Basic. For more information on using the Crystal Report Engine API with Visual Basic, see Using the Crystal Report Engine API in Visual Basic, Page 104. declares several Crystal Report Engine functions for Visual dBASE. Because of limits in the dBASE language, not all Crystal Report Engine functions are available to dBASE programmers. Refer to the individual function in Developers online Help for information on dBASE availability. and CRPE32.PAS declare all Crystal Report Engine API functions for Delphi. For more information on using the Crystal Report Engine API with Delphi, see Using the Crystal Report Engine API in Delphi, Page 68.
q CRPEDB.H
q CRPE.PAS
NOTE: Functions can be declared on an individual basis, but unless you will only be using a few of the Crystal Report Engine functions in your code, it is easiest to simply copy one of the previously mentioned code files into your project directory and add it to your project.
70
NOTE: You may also want to get in the habit of using PEOpenEngine and PECloseEngine in all Print-Only Links, as they are required steps to coding a Custom-Print Link. If your code includes these functions when you design a Print-Only Link, advancing the application to use a Custom-Print Link in the future will be much easier.
PEPrintReport Arguments
PEPrintReport is declared in CRPE.H as follows: short FAR PASCAL PEPrintReport ( char FAR *reportFilePath, BOOL toDefaultPrinter, BOOL toWindow, char FAR *title, int left, int top, int width, int height, DWORD style, HWND parentWindow); The following table describes each argument:
Parameter
reportFilePath
Description
The name of the report to be printed. Include the path if the report is not in the current directory. The report name can be hard-coded and unchangeable at runtime, or you can pass a string variable or character array as the result of a user choice. If toDefaultPrinter is set to TRUE (1), the report is sent to a printer. The toWindow argument should be set to FALSE. If toWindow is set to TRUE (1), the report is sent to a preview window. The toDefaultPrinter argument should be set to FALSE.
toDefaultPrinter toWindow
71
Parameter
title left
Description
The title that you want to appear in the window title bar. This argument can receive a string variable or a character array at runtime. The position, in current screen coordinates, at which you want the left edge of the preview window to appear if the report is being printed to a window. Current screen coordinate measurements can be set within your application. The position, in current screen coordinates, at which you want the top edge of the preview window to appear if the report is being printed to a window. Current screen coordinate measurements can be set within your application. The width of your preview window, in current screen coordinates, if the report is being printed to a window. Current screen coordinate measurements can be set within your application. The height of your preview window, in current screen coordinates, if the report is being printed to a window. Current screen coordinate measurements can be set within your application. The style setting, as defined in WINDOWS.H. Style settings can be combined using the bitwise OR operator. These are standard Windows styles. Refer to Windows API documentation for complete information on window styles. Use 0 for default style settings. Specifies the window handle for the parent window to be used for this preview window.
top
width
height
style
parentWindow
When designing a Print-Only Link using PEPrintReport, keep the following points in mind:
q If
toDefaultPrinter = True, and if you have specified a printer in the report using the Printer Setup command, PEPrintReport prints to the specified printer. Otherwise it prints to the Windows default printer. If you wish to override both the printer specified in the report and the Windows default printer, you will need to establish a Custom-Print Link and specify the printer using the PESelectPrinter function. toDefaultPrinter = True, you may enter null values for all of the remaining parameters except reportFilePath because they apply to printing to a preview window only. The title parameter requires a null string (i.e., ), while the rest of the parameters will accept 0 (zero). parentWindow is null, Seagate Crystal Reports creates a top level window. The top left corner specified is relative to the origin of the screen. parentWindow is the handle of an MDI frame window, Seagate Crystal Reports creates a preview window that is an MDI child window with the top left corner relative to the origin of the frame window's client area.
q If
q If
q If
72
q If
parentWindow is the handle of some other window, Seagate Crystal Reports creates a preview window that is a child of that window with the top left corner specified relative to the origin of the parent window's client area. can use the Windows constant CW_USEDEFAULT (-32768) as the value of left, top, width, and height to indicate a default position for the preview window.
q You
If the preview window is a top-level window and the window style is defined as 0 (i.e., the final two parameters in the PEPrintReport call are 0, 0) or, if the preview window is an MDI child window and the window style is defined as 0, Seagate Crystal Reports uses the following default style: (WS_VISIBLE | WS_THICKFRAME | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX) That is, the default window is a visible window with a thick frame that can be used for sizing the window. The window includes a system menu box, and maximize and minimize buttons.
73
case WM_COMMAND: switch (wParam) { case IDC_PRINTBUTTON: result = PEPrintReport ( boxoffic.rpt, FALSE, TRUE, My Report, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwndParent); if (result != 0) return FALSE; return TRUE; } break; }
or modify the report sort order, or modify the record selection and/or group selection formulas, existing report formulas, and evaluate Crystal Report Engine errors, or modify the database location, a report to a file, e-mail, Exchange or Lotus Notes folder, or ODBC data source, report sections,
q modify q set
q format q and
NOTE: The Crystal Report Engine allows you to add a selection formula and sort fields to a report at runtime, even if none existed in the report when it was designed. Report formulas created in the Seagate Crystal Reports Formula Editor, however, must be added when the report is created in Seagate Crystal Reports. A formula can be edited with the Crystal Report Engine, but can not be added to an existing report from the Crystal Report Engine. Design your reports carefully, and keep this in mind when you create your application.
74
NOTE: The steps described here apply to a single print job. It is possible to have more than one print job open at once.
Description
This step starts the Crystal Report Engine and prepares it to accept a print job. The Crystal Report Engine must be open before a print job can be established. You should open the Crystal Report Engine before the user has a chance to try to print a report. For example, if your application uses a dialog box as the user interface to the Crystal Report Engine, open the Crystal Report Engine immediately after the dialog box is created at runtime. Your dialog box can allow the user to establish a print job and make changes to the report while the Crystal Report Engine is already open. Every time the Crystal Report Engine is opened, it should be closed once your application is finished accessing it (Custom-Print Link Step 6: Close the Crystal Report Engine, Page 77). For example, if you open the Crystal Report Engine when a dialog box is created, close the Crystal Report Engine when that dialog box is destroyed.
75
Description
When you open a print job, the Crystal Report Engine returns a Job Handle for the print job. This handle is important to identifying the print job in the rest of your code. To establish a print job, PEOpenPrintJob, Volume 2, Chapter 1, requires the path and name of the report that is to be printed. This argument can be hard-coded into the function call, as in the example above, or you can prompt the user to choose a report for printing and pass a variable argument to the function. To close a print job, refer to Custom-Print Link Step 5: Close the print job, Page 77. In most cases, you should open the print job immediately before printing and close the print job as soon as the job is finished and the preview window is closed or printing is complete.
Description
The Crystal Report Engine must know where to send the final report. The report can be printed to a printer, displayed in a preview window, exported to a disk file, exported to another database, or exported to an e-mail address. The example above sends the report to the preview window. Although you can choose any of the several destinations for report output, you must establish a destination for the report to print. You can, however, write code in your application that allows your users to decide on a destination themselves.
NOTE: This step does not actually print the report, it only establishes a destination for the report when printed. The report is actually printed in Step 4 using the PEStartPrintJob function.
The following functions are available to establish a print destination:
q PEOutputToWindow,
Volume 2, Chapter 1 Printing a report to a window requires no other print destination code other than the function itself.
q PEOutputToPrinter,
Volume 2, Chapter 1 Printing a report to a printer requires no other print destination code other than the function itself. However, PESelectPrinter, Volume 2, Chapter 1, can be used to select a printer other than the default printer at runtime. The PESelectPrinter function uses the Windows structure DEVMODE, Volume 2, Chapter 1. For more information on this structure, refer to the Windows SDK.
q PEExportTo,
Volume 2, Chapter 1 The PEExportTo function works with the PEExportOptions Structure (page 95) and several DLLs that control a reports export destination and format. The information required by PEExportTo can be set in
76
your code at design time or it can work with options in your application to allow a user to specify export destination and format. If you would like to allow your users to set the destination and format of a report file, but you do not wish to program the interface to do this, use the PEGetExportOptions, Volume 2, Chapter 1 function to have the Crystal Report Engine provide dialog boxes that query the user for export information at runtime.
Description
This function actually sends the report to the output device indicated in Step 3. Once PEStartPrintJob, Volume 2, Chapter 1, is called, the Crystal Report Engine begins generating the report. The Crystal Report Engine displays a dialog box that indicates the status of the report being generated. If the report is sent to the preview window, the window will appear as soon as PEStartPrintJob is called. The preview window can be closed by a call to PECloseWindow, Volume 2, Chapter 1, by closing the Crystal Report Engine (as in Step 6), or by the user clicking the Close button. As a general rule, you should avoid making any formatting changes to a print job once you call PEStartPrintJob, especially if the report is being displayed in a preview window (via PEOutputToWindow). Formatting changes made to a report while it is still being generated and displayed in the preview window may produce undesired results, and can cause errors in the Crystal Report Engine.
Description
Once the print job has completed, it can be closed using PEClosePrintJob, Volume 2, Chapter 1. If you wish to make more changes to the report and print it again, you can do so before closing the job. However, once your application is finished with a report, it should close the print job to free up memory in the users system.
Description
This function closes the Crystal Report Engine entirely. No other Crystal Report Engine functions relating to print jobs may be called once the Crystal Report Engine is closed. Therefore, you should keep the Crystal Report Engine open until it is no longer needed in your application. For example, if the Crystal Report Engine is accessed through a dialog box in your application, you should wait to close the Crystal Report Engine until the dialog box is exited and destroyed by Windows.
77
Seagate Crystal Reports, you have created a report called ORDER.RPT and saved it to the C:\CRW directory. This report is a listing of customer orders, and it is the only report your application will need to print. your application, you have created a Print Report menu command that opens a dialog box. The dialog box allows the user to select whether the report is printed to the printer or sent to a preview window. If the report is to be sent to the preview window, a Boolean variable called ToWindow, declared and initialized in another section of code not seen here, is given the value of TRUE. If the report is to just be sent straight to the printer, ToWindow is given the value FALSE.
q In
q In
the Print Report dialog box, there is also a Print button that initializes the event procedure to generate and print the report. The Event code section below demonstrates how the Custom-Print Link can be coded in the Print button event procedure of your application. is called when the dialog box is created, and PECloseEngine is called when the dialog box is destroyed. For this reason, these two steps are not included in the Custom-Print Link that appears below.
q PEOpenEngine
The topic titled Event code demonstrates the basic custom-print event procedure. This code includes If statements that check to see if an error has occurred during the call to the Crystal Report Engine. When an error occurs, you can easily handle the error in a separate routine or function. The event code below calls the function ReportError whenever an error occurs. ReportError is not a Crystal Report Engine function but is meant simply as an example of how to handle Crystal Report Engine errors. The code for ReportError appears in the section Error code.
Event code
short hJob; BOOL bResult; /* print job handle */
hJob = PEOpenPrintJob(C:\\CRW\\ORDER.RPT); if (!hJob) { ReportError(hJob); return; } if (ToWindow) { bResult = PEOutputToWindow(hJob, My Report, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, NULL); } else { bResult = PEOutputToPrinter(hJob, 1); }
78
Error code
void ReportError(short printJob) { short HANDLE short char errorCode; textHandle; textLength; *errorText;
errorText = (char*)malloc(textLength); PEGetHandleString(textHandle, errorText, textLength); MessageBox( hWnd, errorText, Print Job Failed, MB_OK | MB_ICONEXCLAMATION);
return; }
79
Code Evaluation
Event code
The following is an evaluation of the sample event code that appears above. short hJob; BOOL bResult; /* print job handle */
This section declares two local variables that are important to the remainder of the code. The variable hJob will receive the handle to the print job that results from a PEOpenPrintJob call. This handle is required by most Crystal Report Engine functions. bResult will be given a TRUE or FALSE value as the result of several Crystal Report Engine calls. Any time bResult receives a FALSE value, an error has occurred. hJob = PEOpenPrintJob(C:\\CRW\\ORDER.RPT); This call opens the new print job according to the path and file name of the report that is to be printed. In this example, the report name is hard-coded in the Crystal Report Engine call. A user would have no choice as to which report is printed. This function could also accept a character array or a pointer to a character array as an argument, allowing you to give your users the opportunity to choose a specific report for printing. PEOpenPrintJob returns a handle to the new print job, hJob. This handle will be used in all of the subsequent Crystal Report Engine calls shown here. if (!hJob) { ReportError(hJob); return; } This if statement verifies whether a valid print job handle was received in the previous line of code. If PEOpenPrintJob returned a value of 0, the print job is invalid and an error is reported. For more information on processing Crystal Report Engine errors, see the Error code section that appears below. if (ToWindow) { bResult = PEOutputToWindow(hJob, My Report, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, NULL); } else { bResult = PEOutputToPrinter(hJob, 1); } ToWindow acts as a Boolean variable that provides information from the users decision as to whether this report will be printed to a preview window or to a printer. If ToWindow holds a TRUE value, then the user has decided to print the report to a preview window.
80
The if else code determines an output destination for the report based on the users earlier decision. The PEOutputToWindow function prepares the Crystal Report Engine to create a preview window while PEOutputToPrinter directs the Crystal Report Engine to print the report to the default printer. (The printer used by the Crystal Report Engine can be changed with the PESelectPrinter function.) The variable bResult receives a FALSE value if an error occurs in either function call. if (!bResult) { ReportError(hJob); PEClosePrintJob(hJob); return; } Once the appropriate destination function is called, you must verify its success and report an error if bResult is FALSE. ReportError is the error handling routine. It is an internal function designed to process any errors that occur during a print job. The function is passed the current value of the hJob handle for use in analyzing errors. Search for Crystal Report Engine Error Codes in Developers online Help for information on processing errors.
NOTE: ReportError is not a Crystal Report Engine function, but specific to the code appearing here; it is meant only as an example of how to handle Crystal Report Engine errors.
Since a print job has been opened, you must close it after the error is reported using PEClosePrintJob. See below for more information on this function. Finally, the if statement causes a return after the error has been reported, thus ending the print job session. if (!PEStartPrintJob(hJob, TRUE)) { ReportError(hJob); } PEStartPrintJob actually sends the print job to the printer or a preview window. If the report is printed to a window, PEStartPrintJob creates and opens the window according to the parameters set in the PEOutputToWindow function. If PEStartPrintJob fails (returns FALSE), an error is reported. PEClosePrintJob(hJob); Once the report has printed, this print job can be closed and another one can be started if needed. If the report has been printed to a preview window, PEClosePrintJob does not close the window. The preview window is closed when the Close button is clicked, the PECloseWindow function is called, or the PECloseEngine function is called. return; Now that the print job has finished, the event procedure can return, and the application can wait for the next user event to occur.
Error code
void ReportError(short printJob) {
81
Crystal Report Engine error processing can be most efficiently handled by a separate internal function, such as the one shown here, that is called during a print job. The Event code that is evaluated above calls the ReportError function whenever a Crystal REAPI function returns an error. The code for the ReportError function appears here as an example of how to access and evaluate Crystal Report Engine errors. The error number returned by PEGetErrorCode can be used to control how your application reacts to different types of Crystal Report Engine errors.
NOTE: The REAPI functions described here, PEGetErrorCode and PEGetErrorText, are specific to REAPI error handling. For complete descriptions of these functions, see Seagate Crystal Report Engine Reference, Volume 2, Chapter 1, or search for the functions by name in Developers online Help. The function PEGetHandleString is used to retrieve variable length strings generated by different REAPI functions.
short HANDLE short char errorCode; textHandle; textLength; *errorText;
Completely processing any Crystal Report Engine error requires at least four variables like those above. While only errorCode will be needed to retrieve the Crystal Report Engine error number, the other three variables will all be needed to retrieve the actual error text. errorCode = PEGetErrorCode(printJob); PEGetErrorCode returns a number associated with the error that has occurred. For a list of these error codes and their meanings, search for Crystal Report Engine Error Codes in Developers online Help or see CRPE Error Codes, Volume 2, Chapter 1. PEGetErrorText ( printJob, &textHandle, &textLength); errorText = (char*)malloc(textLength); PEGetHandleString(textHandle, errorText, textLength); The error text must be returned in the form of a handle to a variable length string. The handle is used, along with the PEGetHandleString function to obtain the actual error text and store it in a character array. This is a complicated process, and it should be examined carefully if your code is to work. MessageBox( hWnd, errorText, Print Job Failed, MB_OK | MB_ICONEXCLAMATION);
Once the error has been obtained, you can display error information to the user. This example simply opens a warning message box to alert the user of the problem. Using the error code and the error text, however, you can control Crystal Report Engine error messages any way that you find appropriate for your application. return; } Once error processing is finished, you can return to processing the print job. If an error has occurred during the print job, however, then the print job should be terminated immediately after the error is processed. Review the evaluation of the event code above for ideas on how to terminate a print job after an error.
82
Constant
PE_DR_HASRANGE PE_DR_HASDISCRETE PE_DR_HASDISCRETEANDRANGE
Description
Only ranges are present. Only discrete values are present. Both discrete values and ranges are present. See guidelines below.
The functions listed below are used to add and retrieve parameter discrete values and parameter ranges. The sequence of functions that you call in your application will depend on whether discrete values, ranges, or a combination of both are present.
PEXXXParameterCurrentValue(s)
PEGetNParameterCurrentValues, Volume 2, Chapter 1 PEGetNthParameterCurrentValue, Volume 2, Chapter 1 PEAddParameterCurrentValue, Volume 2, Chapter 1
PEXXXParameterCurrentRange(s)
PEGetNParameterCurrentRanges, Volume 2, Chapter 1 PEGetNthParameterCurrentRange, Volume 2, Chapter 1 PEAddParameterCurrentRange, Volume 2, Chapter 1
Use the following guidelines when deciding which sequence of functions to call. PEParameterValueInfo.hasDiscreteValues = PE_DR_HASRANGE The parameter field contains only ranges. All values will be treated as ranges. Use the PEXXXParameterCurrentRange(s) function calls. PEParameterValueInfo.hasDiscreteValues = PE_DR_HASDISCRETE The parameter field contains only discrete values. All values will be treated as discrete values. Use the PEXXXParameterCurrentValue(s) function calls. PEParameterValueInfo.hasDiscreteValues = PE_DR_HASDISCRETEANDRANGE The parameter field contains both discrete values and ranges. All values will be treated as ranges. Use the PEXXXParameterCurrentRange(s) function calls. You can also call PEAddParameterCurrentValue to add a discrete value, but the discrete value will be stored internally as a range and you will need to call PEGetNParameterCurrentRanges and then PEGetNthParameterCurrentRange when you want to retrieve it. If you try to retrieve the discrete
83
Overview
A report, by default, contains five areas: Report Header, Page Header, Details, Report Footer, and Page Footer. Each of those areas can contain one or more sections. When you add groups, subtotals, or other summaries to your report, the program adds Group Header and Group Footer areas as needed, and each of those areas can contain one or more sections as well. Since one report can have a totally different section configuration from the next, Seagate Crystal Reports uses calculated section codes to identify the sections in each report. In Seagate Crystal Report Engine API functions that affect report sections, the sectionCode parameter encodes the section type, the group number (if the section is a Group Header or Group Footer section), and the section number (if there are multiple sections in an area) together in a single value. The Seagate Crystal Report Engine API also includes macros for encoding section codes (PE_SECTION_CODE, for use with functions that require a section code) and for decoding section codes (PE_SECTION_TYPE, PE_GROUP_N, and PE_SECTION_N, for use with functions that return a section code). The examples that follow show how the encoding and decoding macros can be used.
NOTE: You can not pass the above values directly to a function as section codes. You must use the encoding macro to create a valid section code based on one of the above constants.
Encoding
The PE_SECTION_CODE macro allows you to define a section code to pass as a parameter in Seagate Crystal Report Engine functions that require a section code. The syntax for the macro is: PE_SECTION_CODE (sectionType, groupNumber, sectionNumber) The PE_AREA_CODE macro allows you to define a corresponding area code. The following syntax is used: PE_AREA_CODE(sectionType,groupN)
84
sectionType
This indicates the report area or section type that the section is in. For section type, use any of the following constants:
Value
1 2 3 4 5 7 8 0
Description
Report Header Section Page Header Section Group Header Section Detail Section Group Footer Section Page Footer Section Report Footer Section All Report Sections
groupNumber
Indicates which group the section is in. If the sectionType value indicated is PE_SECT_GROUP_HEADER or PE_SECT_GROUP_FOOTER, the groupNumber is a zero (0) based index for the group section. If the sectionType value is not one of these group section constants, the groupNumber value should always be zero.
sectionNumber
If the report area has been split into more than one section, sectionNumber indicates which section within the area you are using. This value is a zero (0) based index. In other words, the first section in an area is 0, the next section is 1, etc.
NOTE: The macro PE_SECTION_CODE calculates and returns the section code number; it does not return an error code.
The following example demonstrates how to obtain a section code using the PE_SECTION_CODE macro. The section code obtained here is for the second section in the Group Header 1 area: code = PE_SECTION_CODE(PE_SECT_GROUP_HEADER, 0, 1); PESetSectionFormat(job, code, &mySectionOptions); In this case you pass the section type (PE_SECT_GROUP_HEADER), the group number (since this is the first group, use the zero indexed group number 0) and section number (since this is the second section in the Group Header, use the zero indexed section number 1). The program uses the encoding macro and returns a section code which is then passed in the PESetSectionFormat call.
85
When using PE_ALLSECTIONS in your macro, code can be written in one of two ways: code = PE_SECTION_CODE(PE_ALLSECTIONS, 0, 0); // the code value returned is 0 - NOT an error code PESetSectionFormat(job, code, &mySectionOptions); or, you can eliminate using the macro all together: PESetSectionFormat(job, PE_ALLSECTIONS, & mySectionOptions)
NOTE: The maximum number of groups is 25 (possible values of 0 to 24). The maximum number of sections is 40 (possible values of 0 to 39).
Decoding
Some Seagate Crystal Report Engine functions return section codes. These values can be decoded using one of three macros: 1. PE_SECTION_TYPE (sectionCode), 2. PE_GROUP_N (sectionCode), or 3. PE_SECTION_N (sectionCode). Each macro accepts an encoded section code as a parameter. In the following example, you determine the number of sections in the report (using PEGetNSections), obtain the section code for each section (using PEGetSectionCode), and then decode the section code using the PE_SECTION_TYPE, PE_GROUP_N, and PE_SECTION_N macros. numSections = PEGetNSections(job); for (i = 0;i < numSections;i++) { code = PEGetSectionCode(job, loopSectionN); areaType = PE_SECTION_TYPE(code); groupN = PE_GROUP_N(code); sectionN = PE_SECTION_N(code); // Perform section specific code here } Once youve identified the area, group, and section you want, you can then set the section format using code similar to this: PESetSectionFormat(job, code, &mySectionOptions);
NOTE: Earlier versions of Seagate Crystal Reports used different section code constants. Those constants have been remapped to the new section code format so reports created with earlier versions of Seagate Crystal Reports can run with applications created with the current version.
86
Section Map
The following map shows the pattern of section code assignment:
Report Header
1000 1025 1050 1075 up to 1975 First Section in Report Header Area Second Section in Report Header Area Third Section in Report Header Area Fourth Section in Report Header Area 40th Section in Report Header Area
Page Header
2000 2025 2050 2075 up to 2975 First Section in Page Header Area Second Section in Page Header Area Third Section in Page Header Area Fourth Section in Page Header Area 40th Section in Page Header Area
GH1
3000 3025 3050 3075 First Section in First Group Header Area Second Section in First Group Header Area Third Section in First Group Header Area Fourth Section in First Group Header Area
GH2
3001 3026 3051 3076 First Section in Second Group Header Area Second Section in Second Group Header Area Third Section in Second Group Header Area Fourth Section in Second Group Header Area
Details
4000 4025 4050 4075 First Section in Details Area Second Section in Details Area Third Section in Details Area Fourth Section in Details Area
87
GF1
5000 5025 5050 5075 First Section in First Group Footer Area Second Section in First Group Footer Area Third Section in First Group Footer Area Fourth Section in First Group Footer Area
GF2
5001 5026 5051 5076 First Section in Second Group Footer Area Second Section in Second Group Footer Area Third Section in Second Group Footer Area Fourth Section in Second Group Footer Area
Page Footer
7000 7025 7050 7075 First Section in Page Footer Area Second Section in Page Footer Area Third Section in Page Footer Area Fourth Section in Page Footer Area
Report Footer
8000 8025 8050 8075 First Section in Report Footer Area Second Section in Report Footer Area Third Section in Report Footer Area Fourth Section in Report Footer Area
88
1 2 3
Call-up the function which produces the string. This returns the string handle and length. The length includes all characters in the string plus a terminating null byte. If necessary, allocate the string buffer. Call-up PEGetHandleString to copy the string from the handle into the buffer.
89
NOTE: PEGetHandleString frees the memory occupied by the string handle, so you can only call this function once for a given handle. NOTE: For experienced Windows programmers: text and name handles are Global Memory Handles for memory segments on the global heap. If you prefer, you can access these segments using the Windows GlobalLock, GlobalUnlock, and GlobalFree functions. Contents of name and text handles are null terminated ASCII strings. You must free the text handle with GlobalFree when you are done with it (PEGetHandleString does this for you, if you use it).
Sample Code
Use the following C code as an example of how to call a function that returns a variable length string. The code uses the PEGetNthSortField, Volume 2, Chapter 1, function which obtains the name of a field being used to sort the report and the direction of the sort. There are several other functions that return variable length strings, all of which are handled in a similar fashion. Examine this code carefully and try to incorporate it into your own application without modifying the basic procedure. Only experienced programmers should try making changes to this technique since small mistakes here can cause major errors in your application. If you expect to use several REAPI functions that return variable length strings, you may want to set this code up in a separate function to avoid repetition and errors. HANDLE short short char nameHandle; nameLength; direction; *fieldName;
PEGetNthSortField (printJob, sortFieldN, &nameHandle, &nameLength, &direction); /* allocate fieldName buffer */ fieldName = (char*)malloc(nameLength); PEGetHandleString ( nameHandle, fieldName, nameLength);
NOTE: If you retrieve a string handle but do not retrieve the string itself (i.e., you do not use PEGetHandleString), you should free up the string memory by calling GlobalFree (nameHandle).
90
Code Evaluation
HANDLE short short char nameHandle; nameLength; direction; *fieldName;
Any time you evaluate a function that returns a variable length string, you will need at least three variables: 1. a handle to the string, 2. a short integer to hold the length of the string, and 3. a character array or pointer to a character array. The direction variable in this example will hold the sort direction and is specific to PEGetNthSQLExpression, Volume 2, Chapter 1. It is important to note that although the PEGetNthSortField function is defined in the Crystal Report Engine as accepting a pointer to a handle (HANDLE*) and a pointer to a short (short*), nameHandle and nameLength are not defined as pointer variables. Instead, they are defined simply as a HANDLE and a short integer, then passed to PEGetNthSortField with the & operator. This technique automatically initializes the variables with the address of the variable itself. Since the PEGetNthSortField function requires the address in memory to place the information, this is the most convenient method to define and pass the variables. PEGetNthSortField (printJob, sortFieldN, &nameHandle, &nameLength, &direction); The PEGetNthSortField function places a handle to the sort field name in the nameHandle location and the length of the field name (all characters in the name plus a terminating null byte) in the nameLength location. These values will be used to extract the actual field name. /*allocate fieldName buffer*/ fieldName = (char*)malloc(nameLength); Now that you know the actual length of the field name you are trying to obtain, you can allocate exactly the right amount of memory to store that name. The malloc function does this.
PEGetHandleString, Volume 2, Chapter 1, uses the string handle to retrieve the field name and store it in fieldName. At the same time, nameHandle is invalidated. Now, the text can be used like any other character string.
NOTE: This code is meant as a basis for your own code. Although these elements shown here are necessary for extracting a variable length string from certain Crystal Report Engine functions, experienced programmers may wish to expand the code to trap errors or handle the string text differently.
91
The following is a list of the Crystal REAPI functions that return variable length strings: PEGetAreaFormatFormula, Volume 2, Chapter 1 PEGetErrorText, Volume 2, Chapter 1 PEGetFormula, Volume 2, Chapter 1 PEGetGroupOptions, Volume 2, Chapter 1 PEGetGroupSelectionFormula, Volume 2, Chapter 1 PEGetNthFormula, Volume 2, Chapter 1 PEGetNthGroupSortField, Volume 2, Chapter 1 PEGetNthParam, Volume 2, Chapter 1 PEGetNthSortField, Volume 2, Chapter 1 PEGetReportTitle, Volume 2, Chapter 1 PEGetSectionFormatFormula, Volume 2, Chapter 1 PEGetSelectedPrinter, Volume 2, Chapter 1 PEGetSelectionFormula, Volume 2, Chapter 1 PEGetSQLQuery, Volume 2, Chapter 1
NOTE: The term structure is used here to mean both C structures and other user-defined types or records in languages such as Visual Basic and Delphi. If you are unfamiliar with this type of data, refer to the documentation for the programming language you are using.
Each structure used by REAPI is defined and explained in Developers online Help with a link to the function that uses it. Functions that use structures also have hypertext links to the structure definitions. Some of the structures, PEMouseClickEventInfo(Other Declares), Volume 2, Chapter 1, for example, are complex, requiring other structures be passed as member values. Not all programming languages support this feature. If you are using a programming language that does not allow the use of a structure variable as a member variable defined inside other structures, declare the member variable as another data type, such as an integer or a variant data type, and assign it a value of 0 (zero) at runtime. The Crystal Report Engine will automatically provide default values or will request information from the user.
NOTE: Structure variables can not be created using Visual dBASE. Crystal Report Engine functions requiring structures as parameters are not available to dBASE.
92
can not open or close a print job while a subreport is open, and can only work with report sections that are actually in the subreport.
For example, subreports do not have page header sections like primary reports do, so you can not do anything with a subreport that requires a page header section. Most Crystal Report Engine functions require a print job handle as a parameter. When you supply the handle to a primary report, the functions act on the primary report. When you supply the handle to a subreport, the functions act on the subreport. Getting the handle requires a number of steps.
93
Exporting reports
The following topics are discussed in this section:
PEExportTo Overview, Page 95 PEExportOptions Structure, Page 95 Considerations when using the export functions, Page 97 Using the Professional Edition of Seagate Crystal Reports, you can give your applications the ability to export reports in a number of word processor and spreadsheet formats, and in a variety of popular data interchange formats as well. The program includes two export functions, PEExportTo, Volume 2, Chapter 1, and PEGetExportOptions, Volume 2, Chapter 1. PEExportTo can be used by itself or in conjunction with PEGetExportOptions.
q Use
PEExportTo by itself if you want your application to export reports in a fixed format to a fixed destination. Use this alternative, for example, if you want to preset the format and destination for a report and have the application export the report according to your specifications in response to user input. PEExportTo in conjunction with PEGetExportOptions to export reports in the format and destination your user selects from the Export dialog box at Print time.
q Use
94
PEExportTo Overview
The PEExportTo, Volume 2, Chapter 1 function uses a structure, PEExportOptions, Volume 2, Chapter 1, as part of its argument list. This structure passes format and destination data to the function. When using the PEExportTo function by itself, you hard code the format and destination data into the structure. Then, when you issue a call to PEStartPrintJob, Volume 2, Chapter 1, the program exports the report using the format and destination you specified in the code.
q Most
of the format and destination data that you need to enter can be taken from the table in the PEExportTo topic.
q To
hard code an export file name or e-mail header information, you will have to pass a second structure as an argument to the PEExportOptions structure. This second structure is defined in the *.h file that corresponds with the destination DLL you have selected.
When using the PEExportTo function in conjunction with the PEGetExportOptions function, you run the PEGetExportOptions function first to:
q retrieve q pass
the format and destination data that the user specifies in the Export dialog box, and
that data to the PEExportOptions structure (again, part of the PEExportTo argument list).
Then, when you issue a call to PEEnableEventInfo, Volume 2, Chapter 1, the program exports the report using the format and destination specified by the user.
PEExportOptions Structure
struct PEExportOptions { WORD StructSize; // the size of the structure. Initialize to sizeof PEExportOptions char formatDLLName [PE_DLL_NAME_LEN]; // Each export format is defined in a DLL. This is the name of the // DLL for the format you select. From table in PEExportTo topic. // Requires a null-terminated string. Does not need to include // drive, path or extension. For example, uxfsepv is an example of // a valid formatDLLName. DWORD formatType; // Some DLLs are used for more than one format. Enter the // appropriate value from the table under PEExportTo. void FAR *formatOptions; // Some formats offer additional options (see table in the // PEExportTo topic). You can set this element to 0. Then, If the // DLLs require more information, they will prompt the user // for it. To hard code this information, see the note immediately
95
// following this structure. char destinationDLLName [PE_DLL_NAME_LEN]; // Each export destination is defined in a DLL. This is the name of // the DLL for the destination you select. From table in PEExportTo // topic. Requires a null-terminated string. Does not need to // include drive, path or extension. For example, uxddisk is an // example of a valid destination DLLName. DWORD destinationType; // At the present time, each DLL implements only one destination. // You must specify a type here, nonetheless, because the DLL may // implement more than one destination someday. See the table under // PEExportTo for values to enter here. void FAR *destinationOptions; // Some destinations offer additional options (see table in the // PEExportTo topic). You can set this element to 0. Then, If the // DLLs require more information, they will prompt the user for // it. To hard code this information, see the note immediately // following this structure. WORD nFormatOptionsBytes; // Set by 'PEGetExportOptions', ignored by 'PEExportTo'. Both // functions use the same structure. PEGetExportOptions uses this // information in communicating with the application. The // application needs to know how many options bytes are being // returned because it may need to copy the options. PEExportTo // expects a filled in structure and does not need the byte // information because it is not going to copy the options. It uses // only a subset of the structure that does not include byte information. WORD nDestinationOptionsBytes; // Set by 'PEGetExportOptions', ignored by 'PEExportTo'. See // comments for nFormatOptionsBytes above. };
NOTE: You may choose to hard code the data for formatOptions and destinationOptions. You can set the formatOptions and destinationOptions elements to 0 as indicated. If the DLLs require more information than this, however, they will prompt the user to include more information. To hard code this information, you must define and fill in a structure of the appropriate kind. See the header file for the specified DLL for examples. Once the structure is defined, set the formatOptions or destinationOptions element to the address of the structure. Once PEExportTo returns or finishes, deallocate the formatOptions and destinationOptions structures. You should also deallocate the PEExportOptions structure once PEExportTo returns.
96
order to use PEGetExportOptions, Volume 2, Chapter 1 and PEExportOptions, Volume 2, Chapter 1, you must be using the version of the Crystal Report Engine (CRPE32.DLL) that came with the Professional Edition of Seagate Crystal Reports. If you have an earlier version of CRPE32.DLL installed on your machine and its earlier in the path, the program may find it first and not find the export functions. This can happen particularly if you are upgrading to the Professional Edition of Seagate Crystal Reports from the version of Seagate Crystal Reports that was shipped with Visual Basic Professional Edition. Visual Basic included an earlier version of CRPE32.DLL. Search your disk and delete or rename earlier versions of CRPE32.DLL, or make appropriate adjustments to your path statement. sure all format DLLs and destination DLLs are located in the same directory as CRPE32.DLL. Once Windows finds CRPE32.DLL, it will expect all of the DLL files to be in the same directory. Format DLLs are all UXF*.DLL files and Destination DLLs are all UXD*.DLL files. As a general rule, it is best to keep all of these files in the \CRW directory or the directory into which you installed Seagate Crystal Reports. Also, make certain that the PATH statement in your AUTOEXEC.BAT file includes \CRW. UXF*.H and UXD*.H header files are only necessary when compiling your application. These files should be copied to the same directory as your application's source files.
q Make
q The
97
// The comment TODO indicates where you need to add event // handling code specific to your application. #if defined (WIN32) BOOL CALLBACK EventCallback (short eventID, void *param, void *userData) #else BOOL CALLBACK __export EventCallback (short eventID, void *param, void *userData) #endif { switch(eventID) { case PE_CLOSE_PRINT_WINDOW_EVENT: case PE_PRINT_BUTTON_CLICKED_EVENT: case PE_EXPORT_BUTTON_CLICKED_EVENT: case PE_FIRST_PAGE_BUTTON_CLICKED_EVENT: case PE_PREVIOUS_PAGE_BUTTON_CLICKED_EVENT: case PE_NEXT_PAGE_BUTTON_CLICKED_EVENT: case PE_LAST_PAGE_BUTTON_CLICKED_EVENT: case PE_CANCEL_BUTTON_CLICKED_EVENT: case PE_ACTIVATE_PRINT_WINDOW_EVENT: case PE_DEACTIVATE_PRINT_WINDOW_EVENT: case PE_PRINT_SETUP_BUTTON_CLICKED_EVENT: case PE_REFRESH_BUTTON_CLICKED_EVENT: { PEGeneralPrintWindowEventInfo * eventInfo = (PEGeneralPrintWindowEventInfo *) param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_GENERAL_PRINT_WINDOW_EVENT_INFO); // TODO } break; case PE_ZOOM_LEVEL_CHANGING_EVENT: { PEZoomLevelChangingEventInfo * eventInfo = (PEZoomLevelChangingEventInfo *) param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_ZOOM_LEVEL_CHANGING_EVENT_INFO); // TODO } break;
98
case PE_GROUP_TREE_BUTTON_CLICKED_EVENT: { PEGroupTreeButtonClickedEventInfo * eventInfo = (PEGroupTreeButtonClickedEventInfo *)param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_GROUP_TREE_BUTTON_CLICKED_EVENT_INFO); // TODO } break; case PE_CLOSE_BUTTON_CLICKED_EVENT: { PECloseButtonClickedEventInfo *eventInfo = (PECloseButtonClickedEventInfo *)param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_CLOSE_BUTTON_CLICKED_EVENT_INFO); // TODO } break; case PE_SEARCH_BUTTON_CLICKED_EVENT: { PESearchButtonClickedEventInfo *eventInfo = (PESearchButtonClickedEventInfo *)param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_SEARCH_BUTTON_CLICKED_EVENT_INFO); // TODO } break; case PE_SHOW_GROUP_EVENT: { PEShowGroupEventInfo * eventInfo = (PEShowGroupEventInfo *)param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_SHOW_GROUP_EVENT_INFO); // TODO } break; case PE_DRILL_ON_GROUP_EVENT: { PEDrillOnGroupEventInfo * eventInfo =
99
(PEDrillOnGroupEventInfo *) param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_DRILL_ON_GROUP_EVENT_INFO); // TODO } break; case PE_DRILL_ON_DETAIL_EVENT: { PEDrillOnDetailEventInfo * eventInfo = (PEDrillOnDetailEventInfo *) param; ASSERT(eventInfo != 0 && eventInfo->StructSize == PE_SIZEOF_DRILL_ON_DETAIL_EVENT_INFO); // TODO } break; case PE_READING_RECORDS_EVENT: { PEReadingRecordsEventInfo * readingRecordsInfo = (PEReadingRecordsEventInfo *) param; ASSERT(readingRecordsInfo != 0 && readingRecordsInfo->StructSize == PE_SIZEOF_READING_RECORDS_EVENT_INFO); // TODO } break; case PE_START_EVENT: { PEStartEventInfo * startEventInfo = (PEStartEventInfo *) param; ASSERT(startEventInfo != 0 && startEventInfo->StructSize == PE_SIZEOF_START_EVENT_INFO); // TODO } break; case PE_STOP_EVENT: { PEStopEventInfo * stopEventInfo =
100
(PEStopEventInfo *) param; ASSERT(stopEventInfo != 0 && stopEventInfo->StructSize == PE_SIZEOF_STOP_EVENT_INFO); // TODO } break; default: break; } return TRUE; } // call this function after open a print job // before call PEStartPrintJob BOOL initializeEvent(short printJob) { // initialize window options // do not have to set window options to get events, // however, some of the events are fired only when // certain window options are on. PEWindowOptions windowOptions; windowOptions.StructSize = PE_SIZEOF_WINDOW_OPTIONS; PEGetWindowOptions(printJob, &windowOptions); windowOptions.hasGroupTree = TRUE; windowOptions.hasSearchButton = TRUE; windowOptions.canDrillDown = TRUE; if(!PESetWindowOptions(printJob, &windowOptions)) return FALSE; // enable event. // by default, events are disabled. PEEnableEventInfo eventInfo; eventInfo.StructSize = sizeof(PEEnableEventInfo); eventInfo.activatePrintWindowEvent = PE_UNCHANGED; eventInfo.closePrintWindowEvent = TRUE; eventInfo.startStopEvent = TRUE; eventInfo.printWindowButtonEvent = PE_UNCHANGED; eventInfo.drillEvent = TRUE; eventInfo.readingRecordEvent = TRUE;
101
if(!PEEnableEvent(printJob, &eventInfo)) return FALSE; // // // // set tracking cursor, gives the user feedback when the cursor is in the detail area (for a drill-down on detail event) use the default cursor behavior in group area.
PETrackCursorInfo cursorInfo; cursorInfo.StructSize = sizeof(PETrackCursorInfo); cursorInfo.groupAreaCursor = PE_UNCHANGED; cursorInfo.groupAreaFieldCursor = PE_UNCHANGED; cursorInfo.detailAreaCursor = PE_TC_CROSS_CURSOR; cursorInfo.detailAreaFieldCursor = PE_TC_IBEAM_CURSOR; cursorInfo.graphCursor = PE_UNCHANGED; if(!PESetTrackCursorInfo(printJob, &cursorInfo)) return FALSE; // set call back function if (!PESetEventCallback(printJob, lEventCallback, 0)) return FALSE; return TRUE; }
102
Volume 1
103
you open and close a form, the Crystal Report Engine opens every time you open the form and closes every time you close the form. If you print a report, close the form, and later decide to print a report again, the application has to reopen the Crystal Report Engine when you open the form, creating a time delay while running your application.
q When
you open and close the application, the Crystal Report Engine opens as you start the application, and stays open as long as the application is open. Once the Crystal Report Engine is open, you can print a report as often as you wish without the need to reopen the Crystal Report Engine every time you print.
104
Incorrect syntax
VBNameVariable$ = John Recselct$ = {file.LASTNAME} = + VBNameVariable$ This code results in the string: {file.LASTNAME} = John Since John is a literal string, the Formula Checker expects to see it enclosed in quotes. Without the quotes, the syntax is incorrect.
Correct syntax
VBNameVariable$ = John Recselct$ = {file.LASTNAME} = + (chr$(39) + VBNameVariable + chr$(39) This code results in the string: {file.LASTNAME} = 'John' This is the correct syntax for use in a Seagate Crystal Reports record selection formula. This is the syntax you would use if you were entering a selection formula directly into Seagate Crystal Reports. VBNameVariable$ = John Recselct$ = {file.Lastname} = (+ ' + VBNameVariable + ' This code also results in the string: {file.LASTNAME} = 'John' Again, the correct syntax.
Passing Dates/Date Ranges in Visual Basic using the Crystal Report Engine API Calls
You may want to pass date or date range information from your Visual Basic application to the Crystal Report Engine for use in formulas, selection formulas, etc. Here is an example showing a way to do it successfully:
1 2
Start by opening a print job and assigning the print job handle to a variable. JobHandle% = PEOpenPrintJob (C:\CRW\CUSTOMER.RPT) Create variables that hold the year, month, and day for both the start and end of the range. StartYear$ = 1992 StartMonth$ = 01 StartDay$ = 01 EndYear$ = 1993 EndMonth$ = 12 EndDay$ = 31
105
Now build a string to pass to the record selection formula. This is done in two steps:
q First,
build the starting and ending dates for the date range.
Assign the starting date string to the variable StrtSelect$. Assign the ending date string to the variable EndSelect$. StrtSelect$ = {filea.STARTDATE} < Date ( + StartYear$ + , + StartMonth$ + , + StartDay$ +) EndSelect$ = {filea.ENDDATE} < Date ( + EndYear$ + , + EndMonth$ + , + EndDay$ +)
q Second,
build the selection formula using the StrtSelect$ and EndSelect$ variables.
Once your formula is built, set the record selection formula for the report. RetCode% = PESetSelectionFormula (JobHandle%, RecSelect$)
Finally, print the report. RetCode% = PEStartPrintJob (JobHandle, 1) RetCode% = PEClosePrintJob (JobHandle, 1)
Identifying String Issues in Visual Basic Links to the Crystal Report Engine
When passing a string to the Crystal Report Engine as part of the Custom-Print Link, you may think that you are passing one thing when the program, in fact, is passing something entirely different. This can happen easily, for example, when you are passing a concatenated string that you have built using variables. A small syntax error (with embedded quotes, for example) can lead to an error message and a failed call. A simple debugging procedure follows.
106
Look at the string that is displayed and make certain that it is exactly what Seagate Crystal Reports expects for a string.
q If q If q If
the syntax is incorrect, look for errors in the concatenated string you have built. the syntax is correct, look for other problems that could have caused the call to fail.
you are not sure if the syntax is correct, write down the string from the message box, enter it in the Seagate Crystal Reports Formula Editor, and click the Check button. If there is an error in the string, the Formula Checker will identify it for you.
107
NOTE: The development tools may refer to an ActiveX Control by any of the following names: OLE Control, OCX Control, Custom Control, or ActiveX Control. As long as the term used refers to a control with an .OCX filename extension, it is synonymous with the term ActiveX Control used here. NOTE: Seagate Crystal Reports also includes a Visual Basic Custom Control (CRYSTAL.VBX). However, the ActiveX Control is based on more advanced technology and provides more features. You should use the ActiveX Control for development of any new Visual Basic projects. To upgrade an existing project to use the ActiveX Control, see Upgrading from the Crystal Custom Control, Page 110. If, for some reason, you choose to use the VBX in your project rather than the ActiveX Control, the VBX has been fully documented in Developers online Help.
1 2
Open Visual Basic. Open the project to which you want to add the ActiveX Control.
108
Choose COMPONENTS from the Project menu. The Components dialog box appears.
q If
Crystal Report Control appears in the Available Controls list, click the check box next to it, click OK, and skip to Step 6. q If Crystal Report Control does not appear in the Available Controls list, click Browse. The Add ActiveX Control dialog box appears.
NOTE: Crystal Report Control is the name of the Crystal ActiveX Control when it is added to a development project. The term ActiveX Control refers to a type of control, while Crystal Report Control is the name of the ActiveX Control provided by Seagate Crystal Reports. 4
Use the controls in the Add ActiveX Control dialog box to locate and select the CRYSTL32.OCX file. This file was installed in your \WINDOWS\SYSTEM directory when you installed Seagate Crystal Reports. Once you locate and select the file, click Open. Crystal Report Control will now appear in the Available Controls list box. Click the check box next to the name of the control, and click OK. Visual Basic adds the Crystal ActiveX Control to your toolbox. The tool looks like this:
To add the ActiveX Control to a form, double-click the tool in the toolbox and Visual Basic installs it on the active form.
NOTE: For instructions on how to add an ActiveX Control or OLE control to development applications other than Visual Basic, refer to the documentation that came with the development application you are using.
name of the report you want to print in response to an application event, destination for that report (window, file, or printer), number of copies you want to print (if your report is going to the printer), file information (if your report is going to a file), window sizing and positioning information (if your report is going to a window), formula information (if you want to limit the records in your report),
q print
information, and
related properties.
Crystal ActiveX Control properties can be changed either at design time or at runtime. Note, however, some properties are available only at runtime. These properties do not appear in the Properties list at design time.
NOTE: For a complete description of each property in the Crystal ActiveX Control, refer to the Crystal ActiveX Control Reference, Volume 3, Chapter 5.
109
NOTE: ActiveX Control properties also appear in the Visual Basic Properties list box. For instructions on using the Properties list box, refer to your Visual Basic documentation.
NOTE: The actual path indicated should correspond to the location of the Crystal ActiveX Control. The path on your system may or may not be the same as the path shown here. In addition, each entry should appear on a single line in your VB.INI file.
110
NOTE: The following procedures demonstrate the use of the Report Engine Automation Server in versions 5.0 and later of Visual Basic. For information on using automation servers in earlier versions of Visual Basic, or in other development environments, please refer to the documentation that came with your software.
111
To add the automation server to a project in Visual Basic versions 5.0 or 6.0, use the following procedure:
With your project open in Visual Basic, choose REFERENCES from the Project menu. The References dialog box appears.
NOTE: For complete information on adding ActiveX components to a project, refer to your Visual Basic documentation. 2
The Available References list box shows all available component object libraries currently registered on your system. Scroll through this list box until you find the Crystal Report Engine 7.0 Object Library. This is the Crystal Report Engine Automation Server.
NOTE: If the Crystal Report Engine Object Library does not appear in the Available References list box, use the Browse button to locate and select the Crystal Report Engine Automation Server (CPEAUT16.DLL or CPEAUT32.DLL) in your \WINDOWS\SYSTEM directory. 3 4
Toggle on the check box next to the Crystal Report Engine 7.0 Object Library reference. This makes the Crystal Report Engine Automation Server available to your project. Click OK in the References dialog box.
112
Alternately, you can use the following code: Dim app as New CRPEAuto.Application Crystal.CRPE.Application is the Application objects ProgID (programmatic identifier). Visual Basic uses this ID to create an instance of the Application object, which can then be used to obtain a Report object. For a complete description of the CreateObject function, refer to your Visual Basic documentation.
113
Releasing Objects
Visual Basic will clean up any objects that have not been released when your application terminates. However, since objects use memory and system resources that can not be accessed by other running applications, you should get into the habit of releasing any objects when you are finished with them. To release an object, simply set it equal to Nothing: Set report = Nothing Set app = Nothing
Handling Errors
Error trapping for the Crystal Report Engine Automation Server can be handled just like normal error trapping in Visual Basic. When an error occurs in the automation server, the error is sent to Visual Basic which sets the properties of the Err object appropriately. To avoid runtime problems, you should trap for errors inside your Visual Basic code. A typical error trapping routine might look something like this: On Error GoTo HandleError Several lines of Visual Basic code HandleError: If (Err.Number <> 0) Then MsgBox (Err.Description) End If The advantage of handling automation server errors like this is that they can be handled at the same time other Visual Basic errors are handled, making your code more efficient and easier for other developers to understand.
114
1 2 3
With your project open in Visual Basic, choose OBJECT BROWSER from the View menu. The Object Browser appears. From the Libraries/Projects drop-down box, select the Crystal Report Engine Object Library. Classes, methods, and properties exposed by the Object Library will appear in the Object Browser. Select a class in the Classes/Modules list box to view its methods and properties in the Methods/ Properties list box.
NOTE: While viewing the Crystal Report Engine Object Library in the Visual Basic Object Browser, you may notice several classes, methods, and properties that are not documented in the Seagate Crystal Reports Technical Reference. There are several features in the Crystal Report Engine Automation Server that are not available with Seagate Crystal Reports, and are protected by a security feature built into the Object Library. These features will become available in future Seagate Software products. Contact Seagate Softwares Sales department for further information.
Seagate Crystal Reports also provides the Crystal Report Engine Object Library Browser Application as a convenient utility for accessing online information about the Crystal Report Engine Object Library. Simply choose the Xtreme Mountain Bike option in the Sample Files when installing, or choose an automatic installation (the files will be installed by default) to install the utility, then browse through the Object Library using the tree control. Select a class, method, or property for more information on how to use it.
NOTE: Events are only available in Visual Basic 5.0 and later. If you are using a version of Visual Basic earlier than 5.0, you will not be able to make use of the Events exposed by the Report or Window object.
To handle Events for the Report or Window object, you must declare the instance of the object as Public and WithEvents. For example: Public WithEvents repEvents As CRPEAuto.Report Public WithEvents wndEvents As CRPEAuto.Window Once declared, the objects will appear in the Visual Basic Object window. If you select the object, its Events will be displayed, just as if you were working with any other Visual Basic object.
115
NOTE: The Window object events are only valid when a report is sent to a preview window using the Preview method.
The following code demonstrates how to set up and use events for both the Report object and the Window object. Actual event handling code is left for you to fill in. You are limited only by the restrictions of the Visual Basic language. Option Public Public Public Explicit WithEvents rpt1 As CRPEAuto.Report vw1 As CRPEAuto.View WithEvents wnd1 As CRPEAuto.Window
Private Sub Command1_Click() Set vw1 = rpt1.Preview Set wnd1 = vw1.Parent End Sub Private Sub Form_Load() Set app1 = CreateObject(Crystal.CRPE.Application) Set rpt1 = app1.OpenReport(c:\crw\rt01.rpt) rpt1.EventInfo.ActivatePrintWindowEventEnabled = True rpt1.EventInfo.ClosePrintWindowEventEnabled = True rpt1.EventInfo.GroupEventEnabled = True rpt1.EventInfo.PrintWindowButtonEventEnabled = True rpt1.EventInfo.ReadingRecordEventEnabled = True rpt1.EventInfo.StartStopEventEnabled = True End Sub Private Sub rpt1_Start(ByVal Destination As _ CRPEAuto.CRPrintingDestination, _ useDefault As Boolean) ' Put event handling code here. End Sub Private Sub rpt1_Stop (ByVal Destination As CRPEAuto.CRPrintingDestination, ByVal Status As CRPEAuto.CRPrintingProgress) ' Put event handling code here. End Sub Private Sub wnd1_ActivatePrintWindow() ' Put event handling code here. End Sub
116
Private Sub wnd1_ClosePrintWindow (useDefault As Boolean) ' Put event handling code here. End Sub Other events for the Report and Window objects can be seen by using the Visual Basic Object Browser with the Crystal Report Engine Object Library. (a lightning bolt icon appears next to Events in the Object Browser.) Once and instance of a Report object or Window object, is declared, you can add Event handlers to your code by selecting the object in the Visual Basic Object list and then selecting the desired event.
For complete descriptions of all available Crystal Report Engine Object Library Events, refer to the Report Object, Volume 3, Chapter 2, and the Window Object, Volume 3, Chapter 6.
NOTE: In the previous version of Seagate Crystal Reports a report or window object variable declared WithEvents could only be Set once. A VB error occurred if you tried to Set the variable to a different value(i.e. access a new report or display a new Preview window). This problem no longer exists. You can now reset the values of WithEvent object variables.
Sample Applications
Seagate Crystal Reports includes a complete sample application written in Visual Basic 5.0 using the Crystal Report Engine Automation Server. The Xtreme Mountain Bike Inventory Application is a complete real-world application that provides various reports to employees at a fictitious company. Report access is restricted based on user logon information. The application is located in \Program Files\Seagate Software\Crystal Reports\sample\Xtreme\Inventory and provides the option of viewing the source code for any Visual Basic form displayed.
117
In addition, a self-extracting executable located in the \Program Files\Seagate Software\Crystal Reports\sample\sam32aut (or sam16aut) directory contains three small sample applications that demonstrate various aspects of the Crystal Report Engine Automation Server. Simply run the SAM32AUT.EXE (32-bit) or SAM16AUT.EXE (16-bit) application to install the samples. The three samples are:
q AUBASIC
Demonstrates the basic code required to open a report and print, preview, or export it using the Crystal Report Engine Automation Server.
q AUBROWSE
Demonstrates how to browse through the areas of a report and access the objects in each area.
q AUFMLA
Demonstrates how to get and set record selection formulas, group selection formulas, and SQL queries stored with a report.
118
NOTE: You can add sample data to the data definition file so that values will appear for each field in the Preview Tab at design time, but the values will be identical for all records, and grouping will not be available.
At runtime, your application opens the report file, just as it would any other report file. Instead of simply formatting and printing the file at runtime, though, you change the data source pointed at by the Crystal Active Data Driver, which is the data definition file, to a Recordset or Rowset object for an ActiveX data source such as ADO, RDO, DAO, or the Crystal Data Sources (see Crystal Data Object, Page 128), and the Crystal Data Source Type Library (see Crystal Data Source Type Library, Page 131). Once the Crystal Active Data Driver obtains the Recordset from the runtime data source, the Crystal Report Engine can generate the actual report using existing data. The entire process saves you time designing reports and produces reports that are much more flexible and portable at runtime. For more information on data definition files, see Creating Data Definition Files, Page 123.
119
The following sections demonstrate this process using the Crystal Active Data Driver with the Crystal Automation Server in Visual Basic 4.0.
1 2 3
Click New Report in the Seagate Crystal Reports Welcome dialog box, or click the New button on the Seagate Crystal Reports toolbar. The Report Gallery appears. Click a Report Expert button in the Report Gallery. In this example, you can click Standard. The Create Report Expert appears. On the Data Tab, scroll down until you see the Active Data button. If this button does not appear on the Data Tab, you have not correctly installed the Active Data Driver. Run Seagate Crystal Reports Setup again. Click the Active Data button, and the Select Data Source dialog box appears. Click the Data Definition option in the Select Data Source dialog box, and click Browse to locate a data definition file. The Select Data Definition File dialog box appears. Locate the ORDERS.TTX file in the \Program Files\Seagate Software\Crystal Reports directory, and click Open. The specified file appears in the text box for the Data Definition option of the Select Data Source dialog box. Click Finish, and orders appears on the Data Tab of the Report Expert in Seagate Crystal Reports.
4 5 6
NOTE: For information on specifying an OLE DB provider or other ActiveX data source at design time instead of a data definition file, see Using ActiveX Data Sources at Design Time, Page 126.
1 2 3 4
Click the Fields Tab of the Report Expert. The data definition file orders appears as a database table in the Database Fields list box. Each of the fields defined in orders.ttx appears as a field in the orders table. Add fields to your report just as you would normally add fields to a report using the Report Expert. Continue designing the report using the Report Expert. When finished, click Design Report. Since the report is based on a data definition file, there is no point in previewing it at this time. Apply any formatting or other changes that you feel are necessary to fine-tune the look of your report. Save the report when finished.
NOTE: Before saving your report, be sure to turn off the Save Data with Report option under the File menu. The sample data stored with the data definition file is unnecessary at runtime, and will only increase the size of your report file.
120
NOTE: You must add the Data Access Objects component to your Visual Basic project before performing the following steps. For instructions on using DAO with Visual Basic, refer to your Visual Basic documentation.
1. Declare variables for the Database and Recordset objects in your Visual Basic application. This can be handled in the declarations section of a form or module. Use code similar to this: Dim db As New DAO.Database Dim rs As DAO.Recordset 2. Obtain a Database object from the Xtreme database. Set db = DBEngine.Workspaces(0).OpenDatabase( _ c:\Program Files\Seagate Software\Crystal Reports\xtreme.mdb) 3. Obtain a Recordset object from the Orders table of the Xtreme database. Set rs = db.OpenRecordset(Orders, dbOpenTable)
121
NOTE: You must add the Crystal Report Engine Automation Server component to your Visual Basic project before performing the following steps. For complete information on using the Automation Server, see Crystal Report Engine Automation Server, Page 111.
1. Declare variables for the Application and Report objects that you will obtain from the Crystal Report Engine Object Library in the automation server. This can be handled in the declarations section of a form or module. Dim app As CRPEAuto.Application Dim report As CRPEAuto.Report 2. Create an Application object with the Crystal Report Engine Automation Server. Set app = CreateObject(Crystal.CRPE.Application) 3. Obtain a Report object by opening the report file you created earlier. This example uses the file ORDERS.RPT. Set report = app.OpenReport(c:\reports\Orders.rpt)
122
The Active Data Driver supports the following data types in a data definition file:
Data Type
BLOB Boolean Byte Currency
Description
Fields that contain bitmap images. True/False Boolean value. 8-bit integer value. 64-bit floating-point value that can include a currency or percent sign.
123
Data Type
Date
Description
Any date/time value. Examples include: q Jan 5, 1999
q 07/11/97 q 07/11/97 q 23:30:01
5:06:07
32-bit integer value. Any string value over 254 characters long. You must indicate the maximum number of characters for the string. 64-bit floating-point value. 16-bit integer value. Any string value under 254 characters long, such as a name, description, or identification number that is not meant to be interpreted numerically. You must indicate the maximum number of characters for the string.
NOTE: The data type BLOB is supported when connecting to RDO, ADO, DAO and the data control at runtime but not when connecting to CDO.
Although data definition files can be created manually using a text editor such as Notepad, Seagate Crystal Reports provides tools for simplifying the process. Each tool has its advantages. Review the process for using each tool described below to determine which best suits your own environment and development process.
q Database q Active
1 2 3 4
Scroll down and click the Active Data button. The Select Data Source dialog box appears. Click the Data Definition option in the dialog box to create a report based on a data definition file. Click New to create a new data definition file. The Database Definition Tool appears. Use the Database Definition Tool to create fields for your data definition file. Use the controls to enter field names, field types, and sample data that will appear in the Seagate Crystal Reports Preview Tab. If you select String as the field type, you will also be asked to specify a maximum string length. Click Add to add each new field to your data definition file. Each field appears in the list box at the bottom of the Database Definition Tool. Continue adding as many fields as necessary for your data definition file by entering the information in the controls of the Database Definition Tool, and clicking Add each time. You can delete a field that you have created by selecting the field in the list box and clicking Delete.
5 6 7
124
Click the Close button in the upper right of the Database Definition Tool dialog box when you are finished designing your data definition file. A message appears asking if you want to save the data definition file. Click Yes, and a Save File As dialog box appears.
10 Save the data definition file where it can be accessed by your report file. When finished, the new data definition file will appear in the Data Definition text box in the Select Data Source dialog box. 11 Continue creating your report.
NOTE: To use the functions in the Active Data Driver DLL, you must declare the functions first. Refer to your Visual Basic documentation for information on declaring DLL functions. Search for Crystal Active Data Driver Reference in Developers online Help for information about declaring the Active Data Driver functions.
NOTE: For complete information on the functions provided by the Active Data Driver, search for Crystal Active Data Driver Reference in Developers online Help.
125
the drop-down list box to select an ODBC data source that is available on your system.
q Click
the New button to create a new ODBC data source. Refer to Microsoft ODBC documentation for information on creating ODBC data sources. the Advanced button to select ADO or RDO as the data objects technology used. This should match the technology used in your Visual Basic application.
q Click
2 3 4
After you select your data source and data objects technology, you can click Next in the Select Data Source dialog box. The Select Recordset dialog box appears. If the ODBC data source requires log on information, specify a user name and password to log on. Determine if you want to create a Recordset or Resultset using an object available from your data source, such as a database table, or if you prefer to specify a SQL statement. Select the appropriate option in the Recordset section of the Select Recordset dialog box.
NOTE: For simplicity, RDO Resultsets are also referred to as Recordsets in this dialog box. 5 6
If you want to connect to a database object, use the Object Type drop-down list box to select the type of database object, such as a Table, then select the object itself from the Object drop-down list box. If you want to obtain a Recordset using a SQL statement, write the SQL statement in the text box provided, or click Build to use the Microsoft Query application and Query Wizard to visually design your SQL statement.
126
7 8
Click Finish in the Select Recordset dialog box. Either ado or rdo will appear in the list box on the Data Tab of the Report Expert. Continue creating your report normally. While creating your report, the ado or rdo specification will act like a database table, providing all fields that have been obtained from your ADO Recordset or RDO Resultset.
7 8
10 Continue creating your report normally. While creating your report, the ado specification will act like a database table, providing all fields that have been obtained from your ADO Recordset.
DAO
1 2
Click the DAO option in the Select Data Source dialog box. This option allows you to connect to a database file through Data Access Objects (DAO). Select a database type from the Database drop-down list box. This list displays all DAO compatible database drivers installed on your system. Seagate Crystal Reports installs many DAO drivers for you. For this example, you can select Access as the database type. Use the Browse button to open the Select Database File dialog box. Use this dialog box to locate and select a database file. Seagate Crystal Reports includes several sample databases in the \Program Files\Seagate Software\Crystal Reports directory by default. You can select the XTREME.MDB Access file from this directory for this example.
127
4 5 6 7
Click Open in the Select Database File dialog box, and the path and file name of the database you selected appear in the DAO text box on the Select Data Source dialog box. Click Next, and the Select Recordset dialog box appears. If the database requires log on information, specify a user name and password to log on. Determine if you want to create a Recordset using an object available from your database, such as a database table, or if you prefer to specify a SQL statement. Select the appropriate option in the Recordset section of the Select Recordset dialog box. If you want to connect to a database object, use the Object Type drop-down list box to select the type of database object, such as a Table, then select the object itself from the Object drop-down list box. If you want to obtain a Recordset using a SQL statement, write the SQL statement in the text box provided and click Next.
8 9
10 Click Finish in the Select Recordset dialog box. You will see dao in the list box on the Data Tab of the Report Expert. 11 Continue creating your report normally. While creating your report, the dao specification will act like a database table, providing all fields that have been obtained from your DAO Recordset.
128
129
This code adds four fields to the Rowset with the specified field names, and field types. The field types are based on constant values for the Variant data type. The constant names used here are from Visual Basic. For information on valid constant values, see the AddField method in the Crystal Data Object Reference in Developers online Help.
NOTE: If your Rowset contains only a single field, you can use a one dimensional array instead of two dimensional. The single dimension indicates the number of rows or records in your Rowset.
Now that you have defined an array to hold data, you can begin adding values to the array. These array values will become the actual field values for the virtual database. Most likely, you will want to design a routine in your application that adds runtime data generated by your application into each cell of the array. The following code, however, demonstrates how you can explicitly add values to the array: Rows(0, Rows(0, Rows(0, Rows(0, 0) 1) 2) 3) = = = = 1002 The first Order ID Cyclist's Trail Co. The first Company Name #12/2/94# The first Order Date 5060.2725 The first Order Amount
From here, you could continue by adding a value to the first field of the second record, Rows (1, 0). You continue filling in data record by record and field by field. This technique, of course, requires a lot of code and is not very practical. Most real applications would contain a looping procedure that progressively filled in values for the array.
130
NOTE: The Crystal Data Source type library is designed for Visual Basic 5.0 or later.
If you simply need a quick means for packaging some data in a form that can easily be reported off of, you should consider using Crystal Data Objects. Crystal Data Source, on the other hand, is designed for developers who need more flexibility when working with custom data sources. Keep in mind, though, once you add the Crystal Data Source interface to your class, you must implement all methods and properties exposed by the interface.
131
132
1 2 3
With Visual Basic running, select New Project from the File menu. The New Project dialog box appears. Select ActiveX DLL from the New Project dialog box, and click OK. Your new ActiveX DLL project is created. Select Class1 in the Project window, and make sure the Properties window is displayed. To display the Properties window, press the F4 key or select Properties Window from the View menu.
NOTE: If you are not creating an ActiveX DLL, you may not have a class module in your project. See the next section, Adding a class module to a project. 4 5 6
Change the value of the (Name) property for Class1 to MyDataSource. Select Project1 in the Project window, and change the value of the (Name) property for Project1 to MyDataSourcePrj. Save the project. Use MyDataSource as the name of the class file and the project file.
133
1 2 3 4
From the Project menu, select the References command. The References dialog box appears. Scroll through the Available References list to locate the CRDataSource 1.0 Type Library. If you find the reference, skip to step 6. Otherwise, continue with the next step. In the References dialog box, click the Browse button to locate the type library file. The Add Reference dialog box appears. Locate the CRSOURCE.TLB type library file in the same directory that you installed Seagate Crystal Reports. If you accepted the default directory when you installed the product, this directory will be C:\Program Files\Seagate Software\Crystal Reports. Select CRSOURCE.TLB, and click Open. CRDataSource 1.0 Type Library will now appear in the Available References list in the References dialog box. Place a check mark in the check box next to CRDataSource 1.0 Type Library if one does not appear already. Click OK to add the reference to your project.
5 6 7
1 2
From the View menu, select the Object Browser command. The Object Browser appears. Switch the Object Browser to display just the CRDataSourceLib object library.
Notice that the Crystal Data Source interface contains a single object: CRDataSource. This object is similar to the Recordset object you would see if you added a reference to the Microsoft ActiveX Data Objects Recordset 2.0 Library to your project. This is also the object you would pass to the Active Data Driver (Page 306) when producing a report at runtime. Take a moment to review the properties and methods provided by the CRDataSource object. Close the Object Browser when finished.
134
With the code window for the MyDataSource class module open, add the following code to the General Declarations section of the class. Implements CRDataSourceLib.CRDataSource
2 3
Open the drop-down list of objects in the upper left of the code window. You will see a new object has been added to the list: CRDataSource. Select CRDataSource from the list of objects. A new Property Get procedure is added to the class module for the FieldCount property of the CRDataSource object. Remember that in COM interfaces, properties are actually implemented as Get and Let procedures. For more information, refer to your Visual Basic documentation. Open the drop-down list in the upper right of the class module code window. Notice that several procedures appear corresponding to the properties and methods of the Crystal Data Source interface. In fact, the properties and methods you saw in the Object Browser are the same properties and methods listed here in the code window.
Adding procedures
When you selected the CRDataSource object in the object list in the previous section, you automatically added a procedure to the class for the FieldCount property. This property procedure appears in bold in the list of CRDataSource methods and properties to indicate that it has already been added.
With the CRDataSource object selected in the code window, select Bookmark [Property Get] from the dropdown list in the upper right corner of the code window. A Property Get procedure appears in the class for the Bookmark property of CRDataSource. Repeat the process for the Property Let procedure of the Bookmark property. Keep in mind that Property Get procedures allow values to be retrieved from properties while Property Let procedures allow values to be assigned to properties.
135
3 4
Continue selecting each of the property and method procedures listed so that a procedure appears in your class for every property and every method defined by the Crystal Data Source interface. Notice that each of the procedures has been defined as Private. For our ActiveX DLL to expose these properties and methods to other applications, we need to change these to Public. Replace each Private statement with Public. Save your project to preserve all changes up to this point.
Implementing procedures
Exactly how you implement each of the properties and methods in the CRDDataSource interface depends upon the purpose and design of your application or component. To give you an idea of how to implement the procedures, though, the following code sample simply uses an ADO Recordset object connected to the Xtreme sample data DataSource. Obviously, this example has little value in a real application; an ADO Recordset can itself be reported on through the Active Data Driver. However, the example does illustrate how the properties and methods in the Crystal Data Source interface work. Implements CRDataSourceLib.CRDataSource Dim adoRs As ADOR.Recordset Private Sub Class_Initialize() Set adoRs = New ADOR.Recordset adoRs.Open "Customer", "Xtreme sample data", _ adOpenKeyset, adLockOptimistic, adCmdTable End Sub Private Sub Class_Terminate() adoRs.Close Set adoRs = Nothing End Sub Public Property Let CRDataSource_Bookmark(ByVal RHS As Variant) adoRs.Bookmark = RHS End Property Public Property Get CRDataSource_Bookmark() As Variant CRDataSource_Bookmark = adoRs.Bookmark End Property Public Property Get CRDataSource_EOF() As Boolean CRDataSource_EOF = adoRs.EOF End Property Public Property Get CRDataSource_FieldCount() As Integer CRDataSource_FieldCount = adoRs.Fields.Count End Property Public Property Get CRDataSource_FieldName _ (ByVal FieldIndex As Integer) As String CRDataSource_FieldName = adoRs.Fields(FieldIndex).Name End Property
136
Public Property Get CRDataSource_FieldType _ (ByVal FieldIndex As Integer) As Integer CRDataSource_FieldType = adoRs.Fields(FieldIndex).Type End Property Public Property Get CRDataSource_FieldValue _ (ByVal FieldIndex As Integer) As Variant CRDataSource_FieldValue = adoRs.Fields(FieldIndex).Value End Property Public Sub CRDataSource_MoveFirst() adoRs.MoveFirst End Sub Public Sub CRDataSource_MoveNext() adoRs.MoveNext End Sub Private Property Get CRDataSource_RecordCount() As Long CRDataSource_RecordCount = adoRs.RecordCount End Property
1 2
Make sure you save the entire project so that all source code is preserved. From the File menu, select Make MyDataSource.dll. Note that the name of the DLL that will be created is based on the name of your Visual Basic project file (.VBP), not on the project name as specified by the (Name) property. When the Make Project dialog box appears, select the location where the new DLL should reside. Click OK, and the new DLL is created and registered.
3 4
137
If you want to create a new report that can use the MyDataSource ActiveX DLL, create the report using three fields corresponding to the Customer ID, Customer Name, and City fields in the Customer table of the Xtreme sample data ODBC data source. To make things simple, you can use ADO to connect directly to those three fields. The purpose of this tutorial is simply to teach the techniques, not, necessarily, to produce a real application.
1 2 3 4
Open the code window for the form containing the CrystalSmart Viewer/ActiveX. In the General Declarations section for the form, add the following code: Dim myDs As New MyDataSourcePrj.MyDataSource In the Form_Load procedure, add the following line before the Report object is assigned to the ReportSource property of the CRViewer1 object: Report.Database.SetDataSource myDs
NOTE: This example is based on a Visual Basic application created using the Crystal Designer Component, not the Crystal Report Engine Automation Server, Page 111. If you are using the Report Engine Automation Server to assign the new data source to the Active Data Driver, refer to the instructions under Pass the Recordset to the Active Data Driver, Page 122 in the section on the Active Data Driver, Page 118.
138
The first line of code creates an instance of the MyDataSource object in your application, much like you might create an instance of an ADO Recordset object. The second line of code added uses the SetDataSource method inside the Crystal Designer Component library to dynamically change the source of data used by your report. If you designed your report using an ADO, DAO, or RDO data source, or by using a Data Definition file, then your report uses the Active Data Driver to access the report data at runtime. Since the Active Data Driver also supports data sources that expose the Crystal Data Source interface, you can easily assign the MyDataSource object to your report.
reports in Visual Basic programs is made even easier and does not require an existing .RPT
file.
qA
powerful feature of Visual Basic is ad-hoc queries that are run by executing SQL statements in the RecordSource property of the Data Control. By directly binding a Crystal Custom Control to a Data Control, users can now create reports of dynaset data which are the results of such ad-hoc queries.
139
Custom
This property allows you to create bound .RPT files at Visual Basic design time and is not available at runtime. After a bound .RPT file is created, programmers can then use Seagate Crystal Reports to customize the report layout or even link the bound data to other database tables.
BoundReportFooter (Boolean)
This property can be read/write both at design-time and runtime. This property is ignored if the ReportSource property is 0 (Report files). Default is False and the bound reports generated will not have page numbers printed. If set to True, page numbers will be printed at the bottom of a page.
140
141
the DataSource property to the Data Control (i.e., Data1). the ReportSource property to 3 - All Data Control Fields. the Custom property and select the Data-Bound Report Tab. the Save Report As button and enter a name for the report.
q Open q Click
Open the report template in Seagate Crystal Reports and apply any formatting that you want including spacing between columns, font size, colors, grouping, and totaling. Save the report template again when finished. In your Visual Basic application, set the following properties for the ActiveX control:
q Set q Set
the ReportSource to 0 - Report File. the ReportFileName to the .RPT file that you saved (include the complete path of the file).
On the command button, add the following code to the Click event: Private Sub Command1_Click() CrystalReport1.Action = 1 End Sub
Now, the application will create the report at runtime with the formatting you have applied.
1 2 3 4 5 6 7 8 9
Create your Visual Basic application as in the first example above. Set the ActiveX Control to print to a preview window, and run the application. Click the Export button in the preview window, and export the report to a disk file in .RPT format. Once the report has been exported, you can open it up in Seagate Crystal Reports. Perform all formatting changes that you want and save the report. Return to the Visual Basic application and stop it if it is still running. On the ActiveX Control: Set the ReportSource to 0 - Report File. Set the ReportFileName to the .RPT file that you created.
10 Run the Visual Basic application and you will be able to see your bound report with the formatting changes you've made.
142
NOTE: When creating formatted reports for use with the bound data control in Visual Basic, you will not be able to refresh the data from within Seagate Crystal Reports since the data does not exist outside of the Visual Basic application. NOTE: If you plan on using a formatted bound report, you will not be able to modify anything in the SELECT statement of the data control. The report needs all these fields and will fail if they are not all there. The formatted report can not report on any new fields.
When passing properties at runtime using bound reports (i.e., SortFields), the syntax is slightly different. For example, the following syntax would be used for the Formulas and SortFields properties in a normal report: CrystalReport1.Formulas(0) = COMMISSION= {TableName.FIELDNAME} CrystalReport1.SortFields(0) = +{TableName.FIELDNAME} However, for a bound report, the following syntax would be used: CrystalReport1.Formulas(0) = COMMISSION= {Bound Control.FIELDNAME} CrystalReport1.SortFields(0) = +{Bound Control.FIELDNAME}
Sample Application
Seagate Crystal Reports includes a complete sample application written in Visual Basic 5.0 using the Crystal Report Engine Automation Server and the Microsoft Data Bound Grid control. The Xtreme Mountain Bike Inventory Application is a complete real-world application that provides various reports to employees at a fictitious company. The Microsoft Data Bound Grid control is used for an order-entry page that dynamic reports are produced from. The application is installed, by default, in the \Program Files\Seagate Software \Crystal Reports\sample\Xtreme\Invntory directory.
143
Volume 1
145
ActiveX designers
ActiveX designers provide a design environment inside of the Visual Basic Integrated Development Environment (IDE) for visual development of an application feature. An example is the Microsoft UserConnection designer that comes with Visual Basic. The UserConnection designer allows you to visually design ODBC database connections accessible from within your Visual Basic application. For more information on the UserConnection designer, refer to your Visual Basic documentation. The Seagate Crystal Report Designer Component lets you visually add reporting functionality to your applications. The Report Designer window and the Create Report Expert provide the tools to visually design a report and implement it within your project at design time. The Report Designer object model provides a complete set of objects, properties, and methods to write code that manipulates your report and its data at runtime.
146
With the Report Designer Component, you build a report much like the way you build a form in Visual Basic:
q call q add q set
properties, events and methods, and on to the next part of your application, all without leaving Visual Basic.
q code
q move
section of the report is itself an object which has a Format event associated with it. When you double-click on any of the sections of the report, the Visual Basic code window opens displaying an event procedure for the Format event of that section. The Format event is invoked at runtime whenever the section is displayed and formatted. the Report Designer Component produces Visual Basic executable code, you can use Visual Basic for creating calculated fields and formulas in addition to using the built-in formula language. reports typically become an embedded part of the executable. This has implications for individuals who might want to later modify reports using standalone versions of Seagate Crystal Reports.
q Because
q Your
Despite these facts, you will find that you can quickly leverage your existing Seagate Crystal Reports knowledge to develop reports. While working with the Seagate Crystal Report Designer Component, though, keep in mind all of the following features.
147
Data Access
The Report Designer Component supports data access through Data Access Objects (DAO), Remote Data Objects (RDO), and ActiveX Data Objects (ADO). Through these three access methods, you can connect to most ISAM, ODBC, and SQL data sources available to Windows applications. In addition, you can create DAO Recordsets, RDO Resultsets, or ADO Recordsets in Visual Basic, then replace the data source used by a report at runtime by calling the SetDataSource method of the report Designer object models Report object. The Report Designer Component also provides the ability to design reports based on Data Definition files, text files that define the fields and field types of a database without actually serving as a source of data. Using Data Definition files, you can design a report without depending on the existence of a database at design time, then dynamically create the data at runtime and assign it to the Report object of the Report Designer Component. If you have installed the full Seagate Crystal Reports product, you also have the ability to use the Report Designer Component to connect to any data source that Seagate Crystal Reports can connect to. In such a case, the Report Designer Component implements the Seagate Crystal Reports user interface that you are already familiar with, so you can quickly connect to any existing data. Finally, the Report Designer Component also supports Data Environments in Visual Studio 6.0. If your project includes a data environment, the Report Designer Component will allow you to select the data environment as a data source at design time. Runtime reports make full use of the data exposed by a data environment by working with the standard connection, command, or recordset objects provided, much like working directly with an ADO object. For complete information on data access, refer to Working with data, Page 158.
Conditional Formatting
Conditional formatting is created using formulas. With the Report Designer Component, you can produce conditional formatting results using all of the power of the Visual Basic language. If you have used Seagate Crystal Reports before, you may already be familiar with conditional formatting and the Seagate Crystal Reports formula language. The formula language is still available within the Report Designer Component, but you also have the option of making full use of the entire Visual Basic programming language. For more information on using Visual Basic to produce conditional formatting, refer to Designing Reports in the Visual Basic Integrated Development Environment.
148
Preview Window
Unlike Seagate Crystal Reports, the Report Designer Component does not have a Preview window or tab. Although you can use the methods of the Report object in the Report Designer object model to print or export a report, you must use the Seagate Crystal Smart Viewer for ActiveX to display reports on screen. The Smart Viewer is a standard ActiveX control that can be placed inside any development environment that supports ActiveX controls. By passing in a Report object created using the Report Designer Component or its object model, you can easily display a report at runtime inside the Smart Viewer. The Smart Viewer window provides several controls and features that allow users to easily navigate and work with your reports. Additionally, the Smart Viewer, as an ActiveX control, can be programmed to create custom features and functionality specific to your application. For complete information on using the Seagate Crystal Smart Viewer ActiveX control in a Visual Basic application, see Smart Viewer Object Model Programming.
Pictures
Images can now be dynamically displayed in a report at runtime using OLE objects. You may need to display images of products, corporate logos, employee pictures, or any other type of image in your report, but you may want to control which images are displayed based on variables that exist in your application only at runtime. By adding OLE objects to your report, then changing the image at runtime using the FormattedImage property of the OLE object in the Report Designer object model, you can produce exciting, visually attractive reports for your users. For complete information working with OLE images, see Changing OLE object images.
Guidelines
Guidelines are not implemented in the Report Designer Components design window as they are in the Seagate Crystal Reports Design Tab. However, new alignment and sizing options have been added to eliminate much of the need for guidelines.
Subreports
Subreports are supported by the Report Designer Component, but they must be designed from within the main report. In Seagate Crystal Reports, you are able to create subreports from within the main report. You are also able to import existing report files as subreports. With the Report Designer Component, however, you are better off to create your subreports within the main report if you include Visual Basic code in your subreport.
q If
you create a report in the Report Designer Component and use Visual Basic code in the report, any report calculations or formatting that you performed using that code are dependent on that code being in place. If you save such a report to a Crystal Report file (.rpt), you will lose all the embedded Visual
149
Basic code; the .rpt file format does not support it. (For more information, see Report Distribution Considerations.) If you later insert that report as a subreport using the Report Designer Component, the subreport will not perform as expected.
q If
you create a subreport from within a main report in the Report Designer Component, all of the Visual Basic code used in the subreport will be stored as part of the executable. Thus, when you run the report, the subreport will perform as it should.
If you want to insert an existing report as a subreport in the Report Designer Component, make certain that you have used the Seagate Crystal Reports formula language for any calculations or conditional formatting in that report.
q no
While you will still be able to use the Seagate Crystal Reports formula language, you wont need to use it for your calculations and conversions. On a high level, the way you create calculated fields in the Report Designer using Visual Basic is to:
q create q enter
a text object,
the text object where you want the calculated value to appear, a variable to capture the result of the Visual Basic calculation, and
q create q code
the calculation.
Finally, you have the text object display the value in the variable via the SetText method. You can also use Visual Basic code when implementing the Format event procedure of a section in the report. You can open a Format event procedure for a section by double-clicking the section in the Report Designer window or selecting the section and clicking the View Code button in the Visual Basic Project window.
150
Application Distribution
Although the Seagate Crystal Report Designer Component is similar to Seagate Crystal Reports, it is made up of a separate group of files. If you will be distributing your application, you need to familiarize yourself with the new runtime distribution library. Before releasing your Visual Basic applications, review the list of files in the Runtime File Requirements in online Help.
System Requirements
The Seagate Crystal Report Designer Component has the following system requirements: Microsoft Windows 95, Windows 98, or Windows NT 4 (Server or Workstation) Visual Basic versions 5.0 and 6.0 (Professional or Enterprise Edition) Netscape Navigator or Microsoft Internet Explorer (Version 3.0 or higher) x86 processor or higher 32 MB RAM (minimum) 22 MB hard drive space (minimum for a full installation) CD-ROM drive
Installation
NOTE: The Seagate Crystal Report Designer Component is available with Microsoft Visual Basic 6.0 or as a download from the Seagate Software web site (www.seagatesoftware.com).
NOTE: The instructions given here can be used in either version 5 or 6 of Visual Basic, except where specifically noted.
151
Part One
Adding the Report Designer Component to a Project, Page 152 Selecting Data, Page 153 The Report Expert, Page 154 Adding the Smart Viewer, Page 155 Running the Application, Page 155
Part Two
CrystalReport1 - The Report Designer Component, Page 156 CRViewer1 - The Smart Viewer Control, Page 156 The Code, Page 157 Report Packages, Page 158
1 2 3 4 5 6 7
With Visual Basic running, select New Project from the File menu. The New Project dialog box appears. Select the Standard EXE icon and click OK. Visual Basic creates a new project for you with a single form. From the Project menu, select the Components command. The Components dialog box is displayed. Click the Designers Tab in the Components dialog box to see a list of all available ActiveX Designers. Select the Crystal Reports 7.0 ActiveX designer. The check box for this component should be toggled on. Click OK when finished. From the Project menu, select the Add ActiveX Designer submenu, then select the Crystal Reports 7.0 command that appears. A new Report Designer component is added to your project, and the Report Gallery appears inside the Visual Basic IDE.
NOTE: In Visual Basic 6.0, the command Add Crystal Reports 7.0 will appear directly on the Project menu.
152
Selecting Data
The first step to creating any report is selecting the source of the data that will be displayed. The Report Designer Component supports data sources exposed through Data Access Objects (DAO), Remote Data Objects (RDO), ActiveX Data Objects (ADO), Crystal Data Objects (CDO) through a Data Definition File, and Visual Basic Data Environments. If you have installed the full Seagate Crystal Reports product, you can also access any source of data supported by Seagate Crystal Reports, including SQL servers and ODBC data sources. In the following steps, you will connect to a data source using ADO.
In the Report Gallery, click the Standard button to design a standard report using the Report Designer Component. The Create Report Expert appears with the Data Tab active.
NOTE: If you close the Report Gallery dialog box without selecting a report type, the Report Designer Component will assume that you wish to use an Empty Report. You will be prompted to add the Smart Viewer control to your project. 2
In the Data Source section of the Data Tab, click the Project button to select a data source for your Visual Basic project. The Select Data Source dialog box appears.
NOTE: The VB Data Environment button on the Data Tab allows you to connect to an existing Visual Basic Data Environment. The Custom button allows you to connect to a data source other than RDO, ADO, DAO, or a Data Definition File. This option is only available if you have performed a complete install of Seagate Crystal Reports. For more information, refer to Working with data, Page 158. 3 4 5 6 7 8
Verify that the first option in the dialog box, ODBC, is selected. This option allows you to connect to an ODBC data source through ADO or RDO. In the drop-down list below the ODBC option, select Xtreme sample data. This is a sample database and ODBC data source created when you installed Seagate Crystal Reports. Click the Advanced button. The Advanced Options dialog box appears. Make sure the ADO option is selected in the Advanced Options dialog box. You will connect to the Xtreme sample data data source through ActiveX Data Objects. Click OK in the Advanced Options dialog box, and notice that ADO appears in parentheses next to the ODBC option. Click Next in the Select Data Source dialog box. The Select Recordset dialog box appears. Now that you have specified a data source and a connection type (ADO), you must specify the data within the data source that will be used for the report. From the Object drop-down list, select Customer. This is the Customer table in the Xtreme database. Note that if you are familiar with the SQL query language, you could also use the SQL option and write a SELECT statement. The Build button next to the SQL option opens Microsoft Query so that you can visually build a SQL statement.
10 Click Finish to return to the Create Report Expert. Notice that ado now appears in the Tables list of the Data Tab, indicating that you have selected an ActiveX Data Objects data source. You are now ready to design your report.
153
1 2
Select the Fields Tab in the Create Report Expert. The Database Fields list box lists the ADO connection that you made, and all available fields from the table you selected. Select Customer Name in the Database Fields list box, drag and drop the field into the Report Fields list box. ado.Customer Name will appear in the list box. You have just specified that data from the Customer Name field appear in your report. Continue using the drag and drop procedure, or use the Add button on the Fields Tab, to add the Last Years Sales, City, and Region fields to your report. Click the Sort Tab to sort the data in your report. Once again, use either the drag and drop method or the Add button to select the ado.Region field, then the ado.City field and add them to the list of Sort Fields. The records in the report will be sorted first by Region, then by City within each Region. Select each field in the Sort Fields list box, in turn, and verify that in ascending order is specified in the Order drop-down list. Select the Total Tab in the Create Report Expert. For each Region, your report will specify a subtotal of the Last Years Sales values. If ado.Last Years Sales does not appear in the Total Fields list box, select the field from the Report Fields list box and add it now. With ado.Last Years Sales selected in the Total Fields list box, verify that sum is selected in the drop-down list below.
3 4 5
6 7 8 9
10 Click the TopN Tab to obtain the Top N regions. Top N of Sum of ado.Last Years Sales should already be selected in the tab. 11 Change the 5 in the where N is text box to 10. Your report will display the top 10 regions. 12 Click the Graph Tab to create a graph for the report. The Graph Expert appears inside the Graph Tab. 13 Click the Pie button on the Type Tab, then proceed to the Data Tab. 14 Review the settings on the Data Tab. A single graph will appear in your report that contains a separate pie slice for each grouping of the Region field. The sizes of the pie slices will be determined by the subtotal obtained by adding together the values in the Last Years Sales field. 15 Click the Style Tab of the Create Report Expert. The Expert can automatically generate an overall style or look for your report. 16 Select Executive, Leading Break, and notice the image next to the list. This is the look that your report will have. 17 You have finished designing your first report in the Seagate Crystal Report Designer Component. Click Finish.
154
NOTE: If you close the Create Report Expert before clicking Finish, the Report Designer Component will assume that you wish to use an Empty Report. However, the data source you selected will be available. You will also be prompted to add the Smart Viewer control to your project.
The first option is whether or not you want a form containing the Crystal Reports Smart Viewer added to your project. The Smart Viewer is an ActiveX control that allows you to display reports directly in a form inside your application. Click Yes, if this option is not already selected. The second option is whether or not the form containing the Smart Viewer should be the first form displayed when your application runs, the startup form. Click Yes for this option as well. You could design your application so that another form is displayed initially, and the Smart Viewer form is displayed in response to some event. However, for the purposes of this demonstration, your application will simply display the report immediately upon running.
Click OK in the Crystal Report Expert dialog box. If you look in the Project window for your Visual Basic project, you will see that a new form and the Report Designer Component ActiveX designer have been added. In addition, the Report Designer Component design window appears in the Visual Basic IDE. Save your new project and the attached forms. For this tutorial, you can use the name CrystalReport1 for your project.
Click the Start button on the Visual Basic toolbar, or select the Start command from the Run menu. The Report Designer Component connects to your data source through ADO, and generates a report based on the design you created. The report is displayed inside the Crystal Smart Viewer, which sits on a Visual Basic form object. Use the arrow buttons at the top of the Smart Viewer to page through the report. If your system is connected to a printer, click the Print Report button to print a hard copy. Click CA in the tree control at the left side of the Smart Viewer. The group containing California data appears in the Smart Viewer. Click the plus sign next to CA to expand the CA group in the tree control. Four cities are listed for California.
2 3 4 5
155
6 7
Click San Diego in the CA group. Data for San Diego is highlighted in the Smart Viewer window. Select Vancouver from the drop-down list next to the Search Text button.
NOTE: If you are unsure of the name of a toolbar button, hold the mouse pointer over the button for a couple of seconds, and a tool tip will appear that indicates the buttons name. 8 9
Click the Search Text button. Data for Vancouver is highlighted in the Smart Viewer. When you are finished reviewing the report in the Smart Viewer window, close the window. Your application stops running as well.
Part Two
1 2 3 4
Select the CrystalReport1 designer in the Project window, and click the View Code button in the Project window's toolbar. A code page appears for the CrystalReport1 designer. In the drop-down list at the upper left of the Code page, notice that the entire report, along with each section within the report, is represented by a separate object. Select one of the Section objects in the code page. You will see that Section objects have Format events. Code written for a Format event will be executed when that particular section is formatted and displayed inside the Smart Viewer. Close the Code page for the CrystalReport1 designer.
Choose the COMPONENTS command from the Project menu. The Components dialog box appears.
156
2 3 4 5 6 7
Scroll through the list of available components on the Controls Tab of the dialog box. Notice that the Crystal Report Smart Viewer control is toggled on. Click OK, and the Components dialog box closes. If the Visual Basic Toolbox is not available, select the Toolbox command from the View menu. Notice that a new control appears at the bottom of the Toolbox. Move the mouse pointer over the new control in the Toolbox, and hold it still for a couple of seconds. A Tool Tip appears with the name of the new control: CRViewer. In the Project window, select the form containing the Smart Viewer control. If you followed the tutorial exactly, this will be Form2. Click the View Object button in the toolbar for the Project window. Form2 is displayed with the Smart Viewer control. Notice that, at design time, the Smart Viewer control contains several of the basic controls used when you viewed the report at runtime. The Smart Viewer is also resizable inside the form.
NOTE: When you view the form containing the Smart Viewer control, the control may appear to completely fill the form. However, the control is a separate object inside the form and can be resized within the form. 8
In the Properties window, select the CRViewer1 control from the list of objects. Properties appear that are specific to the Smart Viewer control.
The Code
Now you have seen the two principal objects added to your project, the Report Designer Component and the Smart Viewer control. The Report Designer Component provides an environment for designing powerful reports. The Smart Viewer control allows these reports to be displayed at runtime. There is only one element missing from the equation. You must have code that displays the Report Designer's report inside the Smart Viewer.
With the form containing the Smart Viewer control active, select the Code command from the View menu. A code page for the form appears. There are three sections to the code that appears in the form, a General Declarations section, a Load event for the Form, and a Resize event for the Form. Examine the code in the General Declarations section: Dim Report As New CrystalReport1 An instance of the CrystalReport1 object is declared. This object will be used in the Load event of the Form.
Now, examine the code for the Load event of the Form: CRViewer1.ReportSource = Report CRViewer1.ViewReport The first line assigns the declared CrystalReport1 object to the ReportSource property of the Smart Viewer control, CRViewer1. For the Smart Viewer to display a report, it must know where to find that report. In this case, it gets the report from the Report Designer Component, CrystalReport1. The second line of code simply tells the Smart Viewer to display the report. That is all of the code that is required.
157
Finally, examine the code for the Resize event of the form: CRViewer1.Top = 0 CRViewer1.Left = 0 CRViewer1.Height = ScaleHeight CRViewer1.Width = ScaleWidth These four lines make sure that the Smart Viewer takes up the entire area of the Form, and that the Smart Viewer is resized whenever the Form is resized, so it continues to fill the entire form. Note that this code is optional, but such techniques are often good practice to provide a complete user interface.
Report Packages
A report package is a convenient way to group reports from different sources for viewing or printing. Relevant information can be combined in one place, rather than having to output separate reports. Report packages can be created at design-time in Visual Basic. The package can contain reports created by the RDC, for example, CrystalReport1, and reports created outside the application using the designer in Seagate Crystal Reports or Seagate Info with an .rpt extension. The latter method uses CRAXDRT: Crystal Reports ActiveX Designer Run Time Library. The following code demonstrates how to create a report package at design time in VB: 'report created with RDC Dim Report As New CrystalReport1 'report created outside the VB application Dim MyApp As New CRAXDRT.Application 'Object to hold reports in a package for CRViewer Dim RptPk As New ReportSourceRouter 'Add reports to the package RptPk.AddReport Report RptPk.AddReport MyApp.OpenReport("MyDrive:\MyFolder\MyReport.rpt") 'View reports in the package CRViewer1.ReportSource = RptPk CRViewer1.ViewReport
158
actual data source until runtime. This option can be especially helpful if you need to manipulate the data at runtime in response to user actions or other conditions. If you have installed the full Seagate Crystal Reports product, all of the data source drivers provided by Seagate Crystal Reports are also available to the Report Designer Component. Instant and convenient report design based on SQL servers, NT event logs, ODBC data sources, and web server log files is provided right inside the Visual Basic environment. With so many options for connecting to data, selecting a single data access technology can become daunting. The following sections describe each data access option and suggest guidelines for choosing a specific technique. Keep in mind, though, the ultimate decision for data access should depend on your particular data.
159
ADO is the most flexible option for data access. It provides a means of connecting to all kinds of data, including mail messaging, event logs, and Web server site data. In addition, it has been designed, ultimately, to replace DAO and RDO. Developers creating new applications using Visual Basic should strongly consider ADO for data connections. In addition, Web site developers working with Visual InterDev will have an advantage using ADO with Active Server Pages.
Pick from a list option provides a list of object types and objects for each type. For this example, verify that Pick from a list is selected. SQL option allows you to write a SQL query statement. The Build button next to the SQL option opens the Microsoft Query Builder and allows you to visually design a SQL query.
q The
8 9
Select Table from the Object Type drop-down list. From the Object drop-down list, select Customer.
10 Click Finish in the Select Recordset dialog box. ado appears in the list of Tables on the Data Tab of the Create Report Expert.
160
The following string, however, connects to the pubs database in Microsoft SQL Server using the data source name Publishers: DATABASE=pubs;DSN=Publishers;UID=sa;Password=; For more information on connection strings, refer to the Microsoft documentation on ADO.
4 5 6
This example uses the first connection string shown above, a simple connection to the Xtreme sample data ODBC data source. Click Next after you enter the connection string. The Select Recordset dialog box appears. If the data source requires log on information, enter a user name and password in the Logon section of the dialog box. In the Recordset section of the dialog box, select either Pick from a list of Database Objects or SQL. q The SQL option allows you to write a SQL query statement. The Build button next to the SQL option opens the Microsoft Query Builder and allows you to visually design a SQL query.
q The
Pick from a list option provides a list of object types and objects for each type. For this example, verify that Pick from a list is selected.
7 8 9
Select Table from the Object Type drop-down list. Select Customer from the Object drop-down list. Click Finish in the Select Recordset dialog box. ado appears in the list of data source Tables on the Data Tab of the Create Report Expert.
RDO
Remote Data Objects (RDO) is designed specifically for working with remote data sources. This includes ODBC and most common SQL database systems. In fact, RDO acts as an object-oriented wrapper around the ODBC API. The flexibility of ODBC is available to Visual Basic programmers through the simplicity of a COM based object model. Already a common choice for developers of client/server systems, RDO allows the execution of stored procedures and the processing of asynchronous operations, meaning your users can continue to work while your application processes a data query in the background. The basic object used to manipulate data in RDO is a Resultset (specifically, the rdoResultset object). A new Resultset can be defined in your Visual Basic application and passed to the Report Designer Component at runtime using the SetDataSource method. The RDO data source used to initially create your report at design time, however, is not available for direct manipulation. Instead, information about the connection to the data source is stored inside the instance of the Report Designer Component that you add to your application. By creating a new Resultset at runtime, though, and passing the Resultset to the Report Designer Component, you can control the data in a report based on user requests and responses. For more information on using the SetDataSource method, see Setting a new data source for the report, Page 176. RDO provides a powerful connection to remote data sources through ODBC. If you are designing a client/ server application, or any application that needs to connect to a large database system such as Microsoft SQL Server, Oracle, or Sybase Adaptive Server, RDO can provide a strong solution. However, RDO limits your application to standard relational database systems. Other sources of data, such as e-mail and messaging servers, system logs, and Internet/intranet server logs are unavailable to RDO. Developers designing webbased applications using Visual InterDev would also be served better by ActiveX Data Objects (ADO).
161
1 2 3 4 5 6 7
On the Data Tab of the Create Report Expert, click Project. The Select Data Source dialog box appears. Verify the ODBC option is selected, and click Advanced. The Advanced Options dialog box appears. Select RDO as the technology to connect to your data source, and click OK. Select an ODBC data source from the ODBC option drop-down list. For this example, select Xtreme sample data. Click Next in the Select Data Source dialog box. The Select Recordset dialog box appears. If the data source requires logon information, enter a user name and password in the Logon section of the dialog box. In the Recordset section of the dialog box, select either Pick from a list of Database Objects or SQL.
q The
Pick from a list option provides a list of object types and objects for each type. For this example, verify that Pick from a list is selected. SQL option allows you to write a SQL query statement. The Build button next to the SQL option opens the Microsoft Query Builder and allows you to visually design a SQL query.
q The
8 9
Select Table from the Object Type drop-down list. Select Customer from the Object drop-down list.
10 Click Finish in the Select Recordset dialog box. rdo appears in the list of Tables on the Data Tab of the Create Report Expert.
DAO
Data Access Objects (DAO) is designed primarily for use with local and ISAM (Indexed Sequential Access Method) data sources created through applications such as Microsoft Access, Microsoft FoxPro, and Borland dBASE. Although DAO can be used to connect to ODBC data sources, RDO and ADO provide more powerful options for such data. However, DAO is the oldest of the three technologies, giving it the advantage of being familiar to many Visual Basic programmers. As a result, DAO is also frequently found in existing applications, and applications created with older versions of Visual Basic. If you are adding the Report Designer Component to a Visual Basic application that already uses DAO, or if you are connecting to a local data source such as an Access or dBASE file, you should consider using DAO to design your reports. Experienced Visual Basic programmers familiar with the DAO object model may also want to stick with a known technology. However, if you are working with ODBC or other remote data sources, RDO and ADO may be a better solution. Once you design your report in the Report Designer Component, information about the connection to your DAO data source is stored with the report, and can not be accessed directly. However, you can change the data displayed by a report by changing the data source at runtime using the SetDataSource method. A DAO Recordset object may be passed to the report through this method. Keep in mind, though, the Recordset must have fields identical to those in the original data source used at design time. For more information on using the SetDataSource method, see Setting a new data source for the report.
162
1 2 3 4 5 6 7
On the Data Tab of the Create Report Expert, click Project. The Select Data Source dialog box appears. Click the DAO option to connect to your data through DAO. The DAO controls are activated. From the Database drop-down list, select the database format you want to use for your report. For this example, select Access. In the DAO text box, enter the path and file name of the database you want to use, or use the Browse button to locate the database. For this example, select the Xtreme.mdb file. It is located in the Seagate Crystal Reports directory on your system (C:\Program Files\Seagate Software\Crystal Reports by default). When the path and file name of the database appear in the DAO text box, click Next in the Select Data Source dialog box. The Select Recordset dialog box appears. If the database requires logon information, enter a user name and password in the Logon section of the dialog box. In the Recordset section of the dialog box, select either Pick from a list of Database Objects or SQL.
q The
Pick from a list option provides a list of object types and objects for each type. For this example, verify that Pick from a list is selected. SQL option allows you to write an SQL query statement.
q The
8 9
From the Object Type drop-down list, select Table to see a list of database tables. From the Object drop-down list, select Customer.
10 Click Finish in the Select Recordset dialog box. dao appears in the list of Tables on the Data Tab of the Create Report Expert.
Data Environments
Data Environments (introduced with VB 6) allow for interactive creation of ADO Objects at design time, and easy access to data at run time. Through the Data Environment Designer you create Data Environment objects to connect with Data sources (Connection Objects), and access data from those sources (via Command Objects) at design time and run time. The following steps illustrate how to create and connect to Data Environment objects for Microsoft Access type data sources (.mdb files). This algorithm can be used as a general guide for any data source for which an OLE DB provider exists. Consult the Microsoft documentation for more detailed information on the Data Environment Designer.
Add the Seagate Crystal Report Designer Component and the Data Environment Designer to your project
1 2 3
Select Components from the project menu. In the Components dialog box, click on the Designers tab. Click on the Crystal Reports 7 checkbox and the Data Environment checkbox.
163
2 3 4 5 6 7 8 9
10 From the pull down list labeled Object Name select Customer. 11 Click Apply, then Click Okay
164
Data Access Objects (DAO), Remote Data Objects (RDO), or ActiveX Data Objects (ADO). A report designed with a Data Definition File contains information about the kind of data to place in the report instead of information about an actual data source. It looks for field types, rather than actual fields. These field types are specified in the Data Definition File. For example, the following is an example of the contents of a Data Definition file that could be replaced at runtime by the Orders table in the Xtreme database: Order ID Order Amount Customer ID Employee ID Order Date Required Date Ship Date Ship Via Shipped PO# Payment Received long currency long long date date date string 20 boolean string 50 boolean 1 1.00 1 1 Jan 5, 1994 Jan 5, 1994 Jan 5, 1994 string sample value TRUE string sample value TRUE
As you can see, the Data Definition File is a simple ASCII text file with fields listed on separate lines. Each field in the text file represents a field that must exist in the true ADO, RDO, or DAO data source that replaces the Data Definition file at runtime. At design time, you create your report based on the Data Definition file. The three columns of the file provide the name of the fields, the data type for the fields, and a sample value. String fields, as you can see, also require a value for the length of the string. The values in the sample value column are optional and will only be used if you neglect to replace the Data Definition file with a true data source. At runtime, you change the data source pointed at by the report using the SetDataSource method. The new data source can be a Recordset or Resultset object produced using DAO, RDO, ADO, or through the Visual Basic Data Control. Once the Report Designer Component obtains the Recordset or Resultset object from the runtime data source, it can produce and display the final report using actual data. The process saves you the time of creating a complete data source prior to designing the report and your application.
165
1 2 3 4
Click the Project button. The Select Data Source dialog box appears. Click the Data Definition option to create a report based on a Data Definition File. Click the New button next to the Data Definition text box. The Database Definition Tool appears. Use the Database Definition Tool to create fields for your Data Definition File. Use the controls to enter a field name, field type, and sample data. If you select String as the field type, you will also be asked to specify a maximum string length. Click Add to add each new field to your file. The new field will appear in the list at the bottom of the Database Definition Tool. Continue adding as many fields as necessary for your Data Definition File by entering the information in the controls of the Database Definition Tool, and clicking Add each time. You can delete a field that you have created by selecting the field in the list box and clicking Delete. Click the Close button in the right corner of the title bar when you are finished designing your Data Definition File. You will be prompted to save the new file. Click Yes, and the Save File As dialog box appears. Save the file in a convenient directory for your Visual Basic application. The resulting path and file name appear in the Data Definition text box of the Select Data Source dialog box.
5 6 7 8 9
10 Click Finish. The name of the Data Definition File appears in the Tables list of the Data Tab in the Create Report Expert. 11 Continue designing your report using the Create Report Expert and the Report Designer Component.
Declare an instance of the ADO Recordset object in your Visual Basic application. This can be handled in the declarations section of a form or module. Dim rs As New ADODB.Recordset
Obtain a set of records from an ODBC data source. rs.Open SELECT * FROM Customer, DSN=Xtreme sample data;, adOpenKeyset
166
Report Templates
If a Crystal Report file already exists that closely resembles the report you want to create, and it connects to the same or similar data and displays the data in a desirable fashion, you can use the existing report file as a report template. When you select the existing report, a copy of the report is created and set up as the basis of your new report in the Report Designer Component. The original report file is never changed. To use a report template:
1 2 3 4 5 6
Begin by adding the Report Designer Component to your Visual Basic project (see Adding the Report Designer Component to a Project). When the Report Gallery appears, click Import Report. The Open dialog box appears. Use the Open dialog box to locate and select an existing Crystal Report file. These files have .rpt extensions. Click Open. The Crystal Report Expert dialog box appears. Indicate whether or not you want a form containing the Crystal Smart Viewer added to your report, and, if so, whether or not this form should be the start-up form for your application. Click OK. An instance of the Report Designer Component appears in your project. The designer contains a new report design based on the report file you selected.
The data source accessed by the new report is identical to the data source used by the original report file. The following procedure describes how to change the location of the data source. Keep in mind, though, the structure of the new data source must match the original data source. For instance, relational databases must have identical tables and fields.
1 2 3 4
In the Field View of the Report Designer Component window, click the plus sign next to Database Fields. A list of all data connections will appear. If the report connects directly to a database, you will see a list of database tables. If the report uses a connection technology, such as ADO, you will see ado in the list. Right-click one of the data connections in the list and select SET LOCATION from the shortcut menu. The Set Location dialog box appears. In the Databases list, select the database table or other data connection that you want to change the location of, and click Set Location. A dialog box appropriate to the connection type appears. The remaining steps assume the data connection is an ADO connection. With the Choose SQL Table dialog box open (the dialog box that appears when setting the location of an ADO data source), click Log On Server. The Log On Server dialog box appears.
167
Highlight Active Data (ADO) in the Server Type drop-down list, and click OK. The Select Data Source dialog box appears. Use this dialog box to select a new ADO data source. For instructions on using this dialog box, see Selecting Data. Click Next, and the Select Recordset dialog box appears. Specify a new recordset for your report. Click Finish, and the new ADO connection appears in the SQL Databases list box of the Choose SQL Table dialog box. Highlight the new ADO connection, and click OK. The new data source is reflected in the Set Location dialog box. Click Done, and the report in the Report Designer Component window is updated.
6 7 8 9
1 2
On the Data Tab of the Create Report Expert, click Custom. The Log On Server dialog box appears. If your data exists in a standard PC or ISAM database such as Microsoft Access, Borland dBASE, Btrieve, or Microsoft FoxPro, see the section below titled PC Databases. If your data is in a SQL or ODBC data source, continue with the next step. Use the Server Type list box in the Log On Server dialog box to select the type of data source you will use in your report. For example, to connect to the Xtreme sample data ODBC data source, select ODBC - Xtreme sample data. Click OK. If the SQL server or ODBC data source requires log on information, a dialog box will prompt you for the correct information. Log on to the data source as you normally do to access the data. The Choose SQL Table dialog box appears. Use the SQL Tables list in the Choose SQL Table dialog box to select tables from the data source to use in your
168
report. If you connected to Xtreme sample data, select the Customer table and click Add.
6 7
Continue selecting tables and clicking Add. Click Done when finished. The selected tables appear in the Data Tab of the Create Report Expert. If you selected more than one table, the Linking Tab will appear. Proceed to design your report using the selected data.
PC Databases
This tutorial demonstrates how to connect to a Btrieve, xBase, Paradox, or Access database. Assuming you have clicked Custom on the Data Tab of the Create Report Expert:
1 2 3 4 5 6
From the Log On Server dialog box, click Database File. The Choose Database File dialog box appears. Use the Choose Database File dialog box to locate and select the database file you want to use in your report, then click Add. Continue selecting database files and clicking Add for every database you wish to use in your report. Click Done when finished selecting databases. You will return to the Create Report Expert, and the Linking Tab will be activated. Use the Linking Tab to specify links between database tables. Continue designing your report.
is the Report Designer Component? Designer Architecture Basic Environment (Design Time) Basic Environment (Runtime or Application EXE) Descriptions
q Component q Dual
- Interface
169
provides a rich design time environment where you can add controls and other objects to the Form object to create a more sophisticated object that has a similar look but different behavior at runtime. ActiveX designers created by Microsoft and other, third-party vendors work much like standard design objects but can be plugged in to Visual Basic or any other development environment that supports such designers. These components help expand what you can do with VB while behaving in a consistent fashion with the rest of the Visual Basic IDE. The Report Designer Component is an ActiveX designer that specializes in simplifying reporting tasks such as connecting to Visual Basic project data and formatting and modifying report fields. In addition to making reporting in Visual Basic easier, the designer also exposes the Report Designer Component object library. This gives the Report Designer Component a simple design time interface with very powerful runtime capabilities.
Design Time
At design time, the Report Designer Component provides a user interface that closely integrates with the Visual Basic IDE. Through the user interface, you design and manipulate reports and report data. This interface includes events that can be directly programmed from within Visual Basic. The Report Designer Component uses the Active Data Driver(see Active Data Driver, Page 118) for connecting to ISAM, ODBC, and SQL databases through Data Access Objects (DAO), Remote Data Objects (RDO), ActiveX Data Objects (ADO), and Data Environments (Visual Basic 6.0 only). You can design the data set from within Visual Basic, then apply it to the report contained by the Report Designer Component. When working in Visual Basic, you will often need to use the Seagate Crystal Report Smart Viewer for ActiveX as a user interface to display reports. The Smart Viewer is an ActiveX control that you can drop right on to a standard Visual Basic Form. The Smart Viewer is, ultimately, where your report is displayed at runtime.
170
This is a diagram illustrating design time relationship with Visual Basic. Red arrows (1) indicate methods, properties and events that VB developers can manipulate directly; Green arrows (2) indicate internal communications between Crystal components.
Runtime
The user interface provided by the Report Designer Component at design time does not appear in your application at runtime, or when it is compiled into an executable file. Instead, the Report Designer Component is accessed directly by your Visual Basic code. The Report Designer object model provides a complete object hierarchy for direct manipulation in Visual Basic. The Active Data Driver is also available at runtime, through the Report object of the Report Designer Component object model, and can be assigned a new set of data based on user interaction with your application. You design a Recordset or Resultset object in Visual Basic using the DAO, RDO, or ADO object model, and pass it to the report. Finally, the Smart Viewer takes center stage at runtime, connecting to the Report Designer Component and displaying the embedded report. With careful design and placement on the Form, the Smart Viewer appears simply as a window inside your application.
171
This is a diagram illustrating the runtime relationship with Visual Basic. Red arrows (1) indicate methods, properties and events that VB developers can manipulate directly; Green arrows (2) indicate internal communications between Crystal components.
Component Descriptions
Component
Crystal Report Designer UI Component Crystal Report Designer Design Time Component Crystal Report Designer Run Time Component Active Data Driver Crystal Reports Smart Viewer for ActiveX
Description
This is a COM (Component Object Model) component that provides the user interface at design time for the user to interact with and create or modify the report. This is an underlying COM component that provides services for the user interface component. This is the component that encapsulates all of the report objects and is responsible for doing all of the data processing and report layout. This is a data access driver that provides access to various types of object data sources including DAO, RDO, and ADO. This component is an Active X control which can be drawn on a form and manipulated at design time. It provides a rich object model which can be used to modify user interaction with the report at runtime. This component is required only if a developer wants to provide on-screen display of reports at runtime.
172
Component
Data Set
Description
One of the following: q Data Access Object (DAO) Recordset
q Remote q Active q VB
Data Environment Data Object (CDO) Data Source Type Library object
q Crystal
These objects do not need to be valid at design time, for example you could construct a report template at design time without the data being available. This is handled through a Data Definition Files, Page 164. However, the data set objects must be present and valid at runtime to generate a report. VB Form The Seagate Crystal Reports Smart Viewer Control must be embedded on a Visual Basic Form in order to display the report on screen. The Create Report Expert can automatically add a Form with the Smart Viewer embedded to the project when you finish designing a report with the Expert.
Dual - Interface
The object model for the Report Designer Component is exposed as a dual-interface. This means the component can be accessed and utilized easily in all kinds of development environments including Visual Basic, Visual InterDev, Visual C++, and Delphi. Although the component may not work as an ActiveX designer in all environments, the object model can be used as an automation server or ActiveX DLL in any development environment that supports ActiveX.
173
The tutorials in this section concentrate on the objects, properties, methods, and events of the object model exposed by the Report Designer Component. If you need to learn some general programming techniques that can be applied to all types of reports, review the topics listed below. The tutorials listed here do not assume that you are trying to create a specific type of report. Instead, they discuss the object model from a programming point of view, regardless of the report that you are trying to create.
174
175
176
Using ReadRecords
When using the SetDataSource method, be aware that the method will fail if your Recordset or Resultset object goes out of scope. For example, consider the following code: Dim Report As New CrystalReport1 Private Sub Form1_Load() Call SetData CRViewer1.ReportSource = rpt CRViewer1.ViewReport End Sub Private Sub SetData() Dim rs As New ADOR.Recordset rs.Open Select * From Customer, Xtreme sample data rpt.Database.SetDataSource rs End Sub In this example, although the rpt object is global (for the Form), the rs object exists only for the life of the SetData procedure. Even though it is assigned to the rpt object before SetData finishes, the object, and the data, that rs represents goes out of scope and is invalid for the Load event. Thus, the code will fail. This problem can be solved using the ReadRecords method. ReadRecords forces the report to read the records into the report so that they are internal to the Report object itself rather than remaining as a separate Recordset object referenced by the report. Normally, this process would not happen until the report is displayed in the viewer using the ViewReport method. Private Sub SetData() Dim rs As New ADOR.Recordset rs.Open Select * From Customer, Xtreme sample data rpt.Database.SetDataSource rs rpt.ReadRecords End Sub
177
Now, assume the Data Definition file was originally created with all of the following fields:
q Customer q Customer q Contact q Contact q Contact q Contact
ID Name
q Account q Last
Years Sales
Code
When you create a new recordset, if you only add the three fields that appear in your report, values for one or more fields may be missing. You must, instead, include the three fields in your report in the order that they appear in the Data Definition file, along with any fields that may appear between them. Thus, to correctly display Customer ID, Customer Name, and Last Years Sales in your report, you must design the new recordset using all of the following fields:
q Customer q Customer q Contact q Contact q Contact q Contact
ID Name
q Account q Last
Years Sales
In fact, you may want to get in the habit of designing your runtime recordsets so that they include all fields from the original Data Definition file. This can save time later if you make changes to the report.
178
1 2 3
In the Visual Basic Project window, select the CrystalReport1 designer from the Designers folder. Click the View Code button in the toolbar at the top of the Project window. A Code window will appear for the CrystalReport1 designer component. In the object drop-down list box at the top left of the Code window, select a Section object that you want to apply code to. Notice that Section objects are numbered in the order that they appear on your report, from the top of the Report Design window to the bottom. For instance, if you select the Section1 object, your code will apply to the Report Header section of your report. These Section objects are labeled for you at the top of each section in the Report Designer window.
Notice that when you select a Section object, the Format event is automatically selected for you in the event drop-down list box at the top right of the Code window. Format is the only event available to the Section object. When writing code for the Format event, keep in mind that not all properties and methods for all objects are available during the Format event. Many properties are available on a read-only basis. If you are not sure about a property or method, refer to the specific property or method name in the Report Designer Object Model reference section of this Help file. The Format event receives a single argument from the Report Designer Component. The pFormattingInfo argument is an object of type FormattingInfo. The FormattingInfo object has only three properties:
q IsEndOfGroup
q IsRepeatedGroupHeader
- This property is true if the section being formatted is a repeated Group Header. Repeated Group Headers appear when a group extends to two or more pages, and the group has been formatted to repeat information that appears in the Group Header on the second, third, etc. pages. This property is only true if the Group Header is the second, third, etc. instance of the Group Header. It is false for the original first instance of the Group Header. - This property is true if the section being formatted is a Group Header.
q IsStartOfGroup
179
When designing your application, be aware that when a section is being formatted, all objects in that section are also being formatted. Also, all other sections and objects outside of the current section are not being formatted. This information can affect how data is displayed in various sections of the report, depending on your code.
Calculating Results
If you are using the Format event to calculate values, do not perform any calculations which require the values to be carried across sections. For example, if you want to display a value in a Text object for the first record in the Details section, add a value to the first value, and display the results for the next record, the result may be incorrect. (This process is known as a running total.) It is possible for the Format event to be fired multiple times for a section, each time the report is displayed. Whether or not this happens depends on the contents of the section, groupings in the report, and various other common report features. For this reason, a calculation performed in the Format event, may be performed several times before final display, resulting in invalid results if the calculation is dependent on a value created in another record or section. In general, the Format event should be used primarily for formatting the report. Calculations can be performed, as long as they do not depend on assigning a value to an outside variable or receiving a value from an outside variable. For example, you could evaluate the value of a field in the section, then display a flag based on its value. If Sales values drop below a minimum quota, for instance, they could be displayed in red with a warning message next to them.
180
Notice that the SetText method is used to apply a new value. The Text property of the object models TextObject object is a read-only property, a convenient shortcut to get information about the existing value. However, SetText must be used to assign a new value. The example above simply assigns a string to the Text1 object in the report. A more complicated technique may be to access data in a database and calculate a new value in Visual Basic, then display that value through a Text object on the report. In such cases, you could design your report in the Report Designer Component design window to specifically supply a Text object for such a result. The following code demonstrates this technique: Private Sub Form_Load() Dim maxValue As Currency Dim maxValueString As String Dim Report As New CrystalReport1 Dim rs As New ADODB.Recordset rs.Open SELECT * FROM Customer, _ DSN=Xtreme sample data;, adOpenKeyset Report.Database.SetDataSource rs maxValue = 0 rs.MoveFirst Do While Not rs.EOF If rs.Fields(Last Years Sales) > maxValue Then maxValue = rs.Fields(Last Years Sales) End If rs.MoveNext Loop maxValueString = The maximum value is & _ Format(maxValue, Currency) Report.Text1.SetText maxValueString CRViewer1.ReportSource = Report CRViewer1.ViewReport End Sub In this example, we are finding the maximum value of the Last Years Sales field of the new data source, formatting that value as Currency, then displaying a message containing the value through a Text object on the report. As you can see, Text objects provide many options for controlling the output of data in your reports.
181
NOTE: That if the image changes, the picture must be reloaded. OLE image controls can be assigned bitmaps (bmp), Windows metafiles (wmf), JPEG files (jpg), GIF files (gif), Icons (ico), and enhanced metafiles (emf). NOTE: If you are familiar with COM interfaces, the FormattedPicture property can be assigned any image format that supports the IPictureDisp interface. Simply assign an instance of the interface to the property. Refer to the documentation that came with your image format tools to determine if the IPictureDisp interface is supported.
182
lastSectWithObject = Report.Sections.Count Set sect = Report.Sections.Item(lastSectWithObject) Do While sect.ReportObjects.Count <= 0 lastSectWithObject = lastSectWithObject - 1 Set sect = Report.Sections.Item(lastSectWithObject) Loop Set rptObject = sect.ReportObjects.Item(sect.ReportObjects.Count) Select Case rptObject.Kind Case crBlobFieldObject objKind = BLOB field object Case crBoxObject objKind = Box object Case crCrossTabObject objKind = CrossTab object Case crFieldObject objKind = Field object Case crGraphObject objKind = Graph object Case crLineObject objKind = Line object Case crOleObject
183
objKind = OLE object Case crSubreportObject objKind = Subreport object Case crTextObject objKind = Text object Case Else objKind = Unknown object End Select
Locate the first field in the report For Each sect In Report.Sections For Each rptObject In sect.ReportObjects Is it a field? If rptObject.Kind = crFieldObject Then Set fldObject = rptObject Is it a database field? If fldObject.Field.Kind = crDatabaseField Exit For End If End If
184
Next If fldObject.Field.Kind = crDatabaseField Then dbFieldDef = fldObject.Kind Exit For End If Next message = The first database field in the report is: & _ dbFieldDef.DatabaseFieldName MsgBox message
NOTE: You can not print, export, or display in the Smart Viewer a subreport outside of its primary report. The SubreportObject can be manipulated in any way that Report objects are, but they can only be printed, exported, or displayed as part of the primary report.
A SubreportObject is obtained through the ReportObjects collection. The following example shows how to iterate through the sections of a report and change the background color of each subreport to magenta. Dim Report As New CrystalReport1 Dim subReport As SubreportObject For Each sect In Report.Sections For Each rptObject In sect.ReportObjects If rptObject.Kind = crSubreportObject Then Set subReport = rptObject subReport.BackColor = RGB(255, 0, 255) Set subReport = Nothing End If Next Next
NOTE: Currently, the Seagate Crystal Report Designer Component does not support subreports inside of subreports. The report iterations can not go more than one subreport deep. However, you can have multiple subreports inside the main report.
For more information on working with the ReportObjects collection, see Working with the ReportObjects collection, Page 183.
185
186
Although crosstabs are much like subreports, because of their specialized handling of data, there are fewer properties available to the CrossTabObject object than to the SubreportObject object. Before trying to use a property with a crosstab in your report, verify that the property is available to the CrossTabObject object.
Exporting a report
Often, once a report is created, you may need to get the data into a different format. For instance, if you want to display the report on an Internet or intranet site, you need to export the report to HTML format. In such cases, exporting is an alternative to displaying the report in the Smart Viewer control. A common scenario might be to add a button control to a Form in your Visual Basic application, then have the Click event of that control send the report to the required format. The following code demonstrates this technique: Private Sub Command1_Click Dim Report As New CrystalReport1 Report.Export True End Sub The Export method is designed to automatically prompt the user with dialog boxes for information about the destination and format to use when exporting the report. The Seagate Crystal Report Designer Component allows users to export to any of the export formats and destinations provided by Seagate Crystal reports. For more information on export formats, refer to the Seagate Crystal Reports Users Guide.
187
When this code finishes, the rpt object is a valid Report object and can be used just like any Report object you would obtain through the Report Designer Component.
NOTE: The sample call to CreateObject above uses a version independent Prog Id for the Report Designer Component. The correct Prog Id for this version of the Report Designer Component is CrystalRuntime.Application.7, but the version independent Prog Id should use the most recent version of the component installed on your system.
Report events
Although the Format event for the Section object is the only event directly supported by the Report Designer Component, the Report object can produce the standard Visual Basic Initialize and Terminate events. The Initialize event is fired when your Report object is first referenced at runtime. For example, your application may contain a global variable that represents the Report object of the Report Designer that you added to your application at design time: Dim Report As New CrystalReport1 In this case, declaring and setting the Report variable fires the Initialize event. The Terminate event will be fired when this variable is set to Nothing: Set Report = Nothing As you can see, the Initialize event and the Terminate event are fired only once for each Report instance. With that in mind, many changes can be made to your report within the event procedure code for each of these events: Private Sub Report_Initialize() Add report initialization code here End Sub Private Sub Report_Terminate() Add report clean up code here End Sub Use the Initialize event to make broad changes that affect the entire report. For instance, you could assign a new data source using the SetDataSource method. The Terminate event is designed to allow convenient cleanup of any variables or objects that you created during the Initialize event. If, for instance, you created a new ADO Recordset object in the Initialize event, you can use the Terminate event to set this Recordset object equal to Nothing, freeing up system memory and resources.
188
Programmatic ID
The report Designer Component exposes two objects that can be created at runtime using the Visual Basic CreateObject function: Application and Report. The CreateObject function expects a single argument, the Prog Id (Programmatic Id) of the component object. The Application and Report objects expose the following Prog Ids: CrystalRuntime.Application.7 CrystalRuntime.Report.7 If you wish, you can use a version independent Prog Id when referring to the Report Designer Component. For example: CrystalRuntime.Application This Prog Id will use the most recent version of the Report Designer Component registered on your system. However, if you have more than one version of the Report Designer Component installed, and you want to be sure of using a specific version, include the version number in your CreateObject call.
189
Create your report using the standard tools and features of the Report Designer Component. See the tutorial Using the Seagate Crystal Report Designer Component Index for complete instructions on creating a report. With the Report Designer window active inside Visual Basic, click the Save to Crystal Reports File button in the Report Designers toolbar. This button appears to the far right of the toolbar, and you may need to expand the Report Designer window before you see it. When you click this button, a Save As dialog box appears. Use the dialog box to select a location and file name for the report. Click Save, and return to your Visual Basic project.
3 4
190
NOTE: If you create a report in the Report Designer Component and use Visual Basic code to create calculated fields and conditional formatting, you will lose that code (and thus the calculations and formatting) when you store the reports as an external file. The .RPT file format does not inherently support Visual Basic code. If you must retain calculated fields and conditional formatting, use only the Seagate Crystal Reports formula language to create your report formulas or do not save the report external to your application.
191
Volume 1
193
Installation
The following topics are covered in this section.
Delphi 2, Page 194 Delphi 3 & 4, Page 195 C++ Builder 3, Page 198
Delphi 2
Installing the Component
1 2 3 4 5 6
Select Component | Install from the Delphi Main Menu. Select Add from the Install Components Dialog Box. Browse Files of type unit (*.DCU). Select the UCRPE32.DCU file. Click OK (in the Add Module dialog to return to the Install Components dialog). The directory where UCRPE32.DCU is selected will automatically be installed in the Component Search Path. Select OK (in the Install Components dialog). When Delphi is finished rebuilding the Component Library, a Crystal Reports icon will appear on the Data Access page of the Component Palette.
194
Delphi 3 & 4
Installing the Component
The Package Collection file, CrystalVCL.dpc, contains all the files required for Delphi 3. If you are using Delphi 4, the Package Collection is called CrystalVCL4.dpc. To install this Package Collection, the following steps should be followed:
1 2 3 4 5
Go to the Component menu, choose Install Packages. Choose Add. Change the Files of Type extension to Package collection (*.dpc). Locate the CrystalVCL.dpc, select it and choose Open. Follow the steps in Delphi's Install Package Collection dialog. The install path can be changed, and the Sample App, Help, and Source files are optional and can be de-selected if desired.
When the install process is finished, The Crystal VCL should appear under the Data Access tab of the VCL Component palette.
NOTE: It is also necessary to add the Crystal VCL install path to Delphi's Library Path string (Tools | Environment Options | Library) in order for the Component files to be found by Delphi.
Problems
If another UCRPE32.DCU or CRYSTAL.DPL (CRYSTAL.BPL for Delphi 4) is found in the search path, the package might not install. Since the installation of the package comes after the files have been copied to the hard-drive, they should all be available in the directory chosen during install, and it is not necessary to run the install again. All that needs to be done in this case is to first remove any older copies of the component that Delphi found, and then add the package using one of the three ways described below. 1. The package included (DPL/BPL) can be directly installed. 2. The component (DCU) can be installed into a new package. 3. The component (DCU) can be installed into another package (Not recommended).
The Crystal VCL should appear under the Data Access tab of the VCL Component palette.
195
The Crystal VCL should appear under the Data Access tab of the VCL Component palette.
1 2 3 4
Go to the Component menu, choose Install Component. Choose the Into existing package tab. Browse the Unit file name to locate the UCRPE32.DCU. Choose OK, then Yes to the prompts that follow.
The Crystal VCL should appear under the Data Access tab of the VCL Component palette.
1 2 3 4 5
Copy the UCRPE32.HLP and UCRPE32.CNT to the Delphi 4 Help directory. Run Delphi 4 and go to the Help menu. Choose Customize (the OpenHelp installer can also be run outside the Delphi 4 environment by going to the Delphi 4 Bin directory and running OpenHelp.exe). With the Contents tab selected, right-click (or go to the Edit menu) and choose Add Files. Locate the UCRPE32.CNT file and add it to the list. With the Index tab selected, right-click (or go to the Edit menu) and choose Add Files. Locate the UCRPE32.HLP file and add it to the list. Choose File | Save Project.
196
3 4 5
Add the following line to the bottom of the Third-party Help section: :Link Ucrpe32.hlp Save the DELPHI3.CFG (or DELPHI4.CFG) file. Load the DELPHI3.CNT (or DELPHI4.CNT) file (located in the Delphi/Help directory) into an editor such as Notepad. At the top of the file you will see something like this: :Base delphi3.HLP>main :Title Delphi Help ; Index section ;============== :Index VCL Object and Component Reference=vcl3.hlp :Index Object Pascal Reference=obpascl3.hlp
At the bottom of the Index section add the following line: :Index Crystal Reports Component Help=ucrpe32.hlp
Go to the bottom of the DELPHI3.CNT (or DELPHI4.CNT) file and you should see an "Include section" something like this: ; Include section ;================ :include vcl3.cnt :include obpascl3.cnt :Include win32sdk.toc :Include winhlp32.cnt
At the bottom of the Include section add the following line: :Include ucrpe32.cnt
197
Context-sensitive Help should now be available from the Delphi IDE (choosing the F1 key while a property is selected should bring up the appropriate item in the UCRPE32.HLP file). Also, the Crystal Component Help will be available from the Delphi Help file Contents list, and Index list. As well, pressing F1 on an item in the Delphi code window should bring up the corresponding item in the Crystal Component Help file.
C++ Builder 3
Installing the Component
The Component can be installed in one of the three ways described below. 1. The package included (BPL) can be directly installed. 2. The component source (UCRPE32.PAS) can be installed into a new package. 3. The component source (UCRPE32.PAS) can be installed into another package.
NOTE: Whichever install method is chosen, the path to the BPL file should be added to the Tools | Environment Options | Library | Library Path and it may be necessary to add the same path to the Project | Directories/Conditionals Include and Library paths also.
The Crystal VCL should appear under the Data Access tab of the VCL Component palette.
The Crystal VCL should appear under the Data Access tab of the VCL Component palette.
198
4 Choose OK, then Yes to the prompts that follow. The Crystal VCL should appear under the Data Access tab of the VCL Component palette.
1 2 3 4 5
Copy the UCRPE32.HLP and UCRPE32.CNT to the BCB3 Help directory. Run BCB3 and go to the Help menu. Choose Customize (the OpenHelp installer can also be run outside the BCB3 environment by going to the BCB3 Bin directory and running OpenHelp.exe). With the Contents tab selected, right-click (or go to the Edit menu) and choose Add Files. Locate the UCRPE32.CNT file and add it to the list. With the Index tab selected, right-click (or go to the Edit menu) and choose Add Files. Locate the UCRPE32.HLP file and add it to the list. Choose File | Save Project.
Context-sensitive Help should now be available from the BCB IDE (choosing the F1 key while a property is selected should bring up the appropriate item in the UCRPE32.HLP file). Also, the Crystal Component Help will be available from the BCB Help file Contents list, and Index list. As well, pressing F1 on an item in the BCB code window should bring up the corresponding item in the Crystal Component Help file.
Programming Overview
The following topics are discussed in this section.
Introduction to the Object Inspector, Page 200 Changing Properties in the Object Inspector, Page 200 Changing Properties at Runtime, Page 200 Delphi Programmers introduction to the SCR Print Engine, Page 201 Dealing with SubClass Objects, Page 203 Consistent Code, Page 204 Using the Retrieve method, Page 205 Working with subreports, Page 206 Other Guidelines, Page 208
199
name of the report you want to print in response to an application event, destination for that report (window, file, or printer), number of copies you want to print (if your report is going to the printer), file information (if your report is going to a file), window sizing and positioning information (if your report is going to a window), formula information (if you want to limit the records in your report),
q print
information, and
related properties.
TCrpe component properties can be changed either at design time or at runtime. Note, however, some properties are available only at runtime. These properties will not appear on the Properties list in the Object Inspector. For a complete description of each property in the Crystal VCL Component, refer to Seagate Crystal Reports Technical Reference: Volume 4 - VCL Reference, which is available as a PDF file.
a text box appears next to the property name, type in a value for the property.
a drop down list box appears next to the property name, click the arrow to open the drop down list and select a value from that list. a text box with an ellipsis (...) button appears next to the property name, click the button to reveal a dialog box where you can define your setting for the property.
q If
200
201
Once you are familiar with these options, you will want to consider changing the other properties that affect how the report processes. Many of the options that are used to build a report can be changed via the runtime Print Engine. The following list gives the name of the option in the Crystal Reports Designer, and its equivalent in the Crystal Reports component:
Crystal Reports
Database Location Export Email Font Format Section
Grouping LogOn Information LogOnServer Page Setup / Page Margins Parameter Fields Passwords: MS Access Passwords: Paradox Print Date Printer Setup PrintOptions Report Comments Report Title Selection Formula: Group Selection Formula: Record Sort Records SQL Query Stored Procedure Parameters
GroupCondition Connect LogOnInfo LogOnServer Margins ParamFields SessionInfo Tables PrintDate Printer SummaryInfo ReportTitle GroupSelection Selection SortFields GroupSortFields SQL Params
202
Crystal Reports
Subreports Summary Info
Before attempting to use these properties, please read the following section:
203
Each object in the Crystal VCL that can contain more than one item, uses an internal Index to maintain which item it is currently looking at, similar to the ItemIndex property of a list box. This Index is updated whenever the Item property is used (LogOnInfo[2], for example), or whenever the key property (if applicable) is assigned a new lookup value. Key properties are things like Formulas.Name, or SortFields.Number; properties that contain a unique value for each item, and which serve as look up properties. They appear as drop-down lists in the Object Inspector. Number is the key property for the Tables object. Assigning a new value to the Number property will not overwrite the value stored there, but will rather cause the Tables object to try and find that new value, and point to the table that has the value. For example: Crpe1.Tables.Number := 2; This will cause the Tables object to look internally for a table with the number 2. If it finds it, the object will now point it's properties to that table and will remain pointing there until it is changed. That is one way of navigating through the tables. The ItemIndex property can also be used to navigate through the Tables object: Crpe1.Tables.ItemIndex := 2; Although in this case, ItemIndex represents the position of the table in the internal Tables list, not necessarily the table number (although if Retrieve is used, these should be the same). By far the easiest and most natural way of navigating through the Tables object is the default array property, Item. Since this is a default property, it does not need to be specified when making the call, so Tables[2] is the same as Tables.Item[2]. And since the Item property returns a reference to the Tables object, it is possible to add other properties to the end of the subscript: Crpe1.Tables[2].Path := 'c:\MyNewPath\'; Crpe1.Tables[3].Name := 'MyNewTable.dbf'; While initially this might seem like a lot more work, it actually is much more powerful, especially when dealing with items that have a dozen properties, such as the SectionFormat object. With SectionFormat, the old method involved passing a large string of about a dozen items separated by semicolons. Even if you only wanted to set one property, you still had to pass the whole string. With the new object format, you only need to set the property that you want to change.
Consistent Code
One of the reasons for making the properties into objects is that the coding syntax is more consistent. For example, there are a number of methods associated with the Tables object: Crpe1.Tables.Retrieve; Crpe1.Tables.Count; Crpe1.Tables.Clear;
204
They are much easier to code and to remember, and more consistent, than the old calls: Crpe1.RetrieveDatafiles; Crpe1.GetNDatafiles; Crpe1.Datafiles.Clear; And since each object in the new Component uses the same naming convention for the same methods, they are very easy to remember.
205
The second way of adding items to the Tables object would be to do it manually by using the Add method. The Retrieve method is not called. Instead it is up to the programmer to know how many tables are in the report, or to know which tables he wants to change. This method would be coded like as: (* Adds table 0 to Tables object *) Crpe1.Tables.Add(0); (* Set path of first table *) Crpe1.Tables.Path := 'c:\MyNewPath\'; (* Set name of first table *) Crpe1.Tables.Name := 'MyNewTable.dbf'; In the above example, it is not necessary to include the subscript [n] after the Tables object name. This is because the Tables object has an internal index that keeps track of which Table item it is currently looking at. To be compatible with future revisions of the Component, it would better to use a subscript as follows: (* Adds table 0 to Tables object *) Crpe1.Tables.Add(0); (* Set path of table just added *) Crpe1.Tables[Crpe1.Tables.Count - 1].Path := 'c:\MyNewPath\'; (* Set name of table just added *) Crpe1.Tables[Crpe1.Tables.Count - 1].Name := 'MyNewTable.dbf';
206
Here is a simple code example which illustrates how to fill the Seagate Crystal Component with report information, which can then be edited and sent back to the Print Engine: Crpe1.ReportName := 'c:\MyCrystalReport.rpt'; Crpe1.Subreports.Retrieve; Crpe1.Printer.Retrieve; Crpe1.PrintOptions.Retrieve; Crpe1.SummaryInfo.Retrieve; for cnt := 0 to (Crpe1.Subreports.Count - 1) do begin Crpe1.Subreports[cnt]; Crpe1.LogOnInfo.Retrieve; Crpe1.Connect.Retrieve; (* Do not do SQL Retrieve here because it slows down loading while trying to Logon to the Server. Use the SQL.Retrieve method after filling in the Password property of the Connect or LogOnInfo objects *) Crpe1.SQL.Params.Retrieve; Crpe1.Tables.Retrieve; Crpe1.Selection.Retrieve; Crpe1.GroupSelection.Retrieve; Crpe1.Formulas.Retrieve; Crpe1.ParamFields.Retrieve; Crpe1.GraphType.Retrieve; Crpe1.GraphText.Retrieve; Crpe1.GraphData.Retrieve; Crpe1.GraphOptions.Retrieve; Crpe1.SectionFormat.Retrieve; Crpe1.SectionFormatFormulas.Retrieve; Crpe1.AreaFormat.Retrieve; Crpe1.AreaFormatFormulas.Retrieve; Crpe1.SectionFont.Retrieve; Crpe1.SectionMinHeight.Retrieve;
207
Crpe1.SortFields.Retrieve; Crpe1.GroupSortFields.Retrieve; Crpe1.GroupOptions.Retrieve; Crpe1.PrintDate.Retrieve; Crpe1.Margins.Retrieve; Crpe1.RetrieveReportTitle; Crpe1.RetrieveDetailCopies; end; Please remember that the Retrieve method clears out the subclass object first before retrieving values from the report, so be sure to use it at the beginning of the code that deals with that particular object. This is the correct way: Crpe1.Tables.Retrieve; Crpe1.Tables[4].Name := 'MyNewTable.dbf'; And this is the wrong way: Crpe1.Tables[4].Name := 'MyNewTable.dbf'; Crpe1.Tables.Retrieve; (* or GroupCondition for Crystal 5.0 *)
Other Guidelines
Zero-based numbering is used throughout the Seagate Crystal Component, to make it compatible with the Seagate Crystal Reports Print Engine. So, the first table is Table[0], the first Formula is Formulas[0], etc. The only exception to the rule is the Group numbering, which starts with 1, just as it is in the Crystal Reports Designer. So the various Section objects use GH1 as the first group, not GH0. Likewise, the GroupCondition property takes 1 as the first Group for the Number property. For numeric properties, -1 has been used as a default value. Normally, empty strings in properties that are of string type will not be sent to the Print Engine. If you want to send an empty string, use the CrEmptyStr constant, which will tell the Crystal component that you want to intentionally pass an empty string to the report.
208
Programming Tips
The following topics are discussed in this section.
Always Set ReportName First, Page 209 Discard Saved Data, Page 210 Verify Database, Page 210 Connecting to SQL Servers, Page 210 Changing Tables & Formulas, Page 211 Changing Groups & Summary fields, Page 211 Using the Send methods, Page 211 Using the JobNumber property, Page 212
Therefore, if any of these properties have been set before ReportName, they will be cleared when the ReportName property is assigned a new value.
209
Verify Database
Under the Database menu in Seagate Crystal Report Designer, there are two menu items: Verify Database and Verify on Every Print. Since the database structure and index information are stored in a report file when it is saved, the report may have problems running if the database structure changes. One solution is to load the report into the Designer, and choose Verify Database, then resave the report. This works fine during development, but if the database structure will be changing during runtime operation, there is no equivalent for these Verify commands in the runtime engine. Therefore, Verify on Every Print should be turned on in these instances. With this option on, the report will reread the database structure every time the report runs. The amount of time taken to do this extra step is usually minimal. If the database structure will not change after deployment, there is no reason to turn this feature on.
210
2.
211
TCrpeString
The following topics are discussed in this section.
Introduction, Page 213 TCrpeString VCL Properties, Page 214 Using the TCrpeString, Page 214
212
Introduction
TCrpeString = class(TStringList) TCrpeString is the same as Delphi's TStringList, except the Put method defaults to Add if the subscript is one number larger than the number of strings in the StringList. With a normal StringList, the following code would cause an error: var slTemp : TStringList; begin slTemp := TStringList.Create; slTemp[0] := 'The first line'; end; The reason for the error is the code attempts to access the first string in the stringlist, but the first string does not exist yet. The proper way to do this would be: var slTemp : TStringList; begin slTemp := TStringList.Create; slTemp.Add('The first line'); end; However, with the TCrpeString type, the first example would work as well as the second one. Therefore, this is perfectly legal with the TCrpeString type: var slTemp : TCrpeString; begin slTemp := TCrpeString.Create; slTemp[0] := 'The first line'; end;
213
214
Introduction
Delphi variables can be used with Crystal Reports Formulas and the Crystal Component's Formulas object if they are declared as string or converted to string (regardless of the actual data type) before being passed to the Report. The value of the variable passed to the Report must be in the same format and look exactly as if entered directly into the Crystal Reports Formula Editor:
q String
data types must be surrounded by double quotes: "This is a String". Single quotes are also valid within Crystal Reports but because Delphi uses single quotes, all string data types passed to Crystal should use double quotes to avoid conflicts. do not need quotes: 1234
q Numbers q Dates
The VCL Formulas object can only be used to change formulas that already exist in Crystal Reports, not to create new formulas. The Formulas object can contain numerous Formula items, which can either be created by using the Retrieve method: Crpe1.Formulas.Retrieve; or the manual Add method: Crpe1.Formulas.Add('FormulaOne');
NOTE: Although Crystal Reports automatically prefixes the @ symbol to each Formula Name when a Formula is created, the @ must not be included when using the Name or Add methods of the Formulas object in Delphi.
Once the Formulas object has items in it, the next step is to navigate to the desired item. This can be done in 3 different ways: 1. Use the default Item array property (subscript): Crpe1.Formulas[0]; 2. Use the Name lookup property: Crpe1.Formulas.Name := 'FormulaOne'; 3. Use the ItemIndex property: Crpe1.Formulas.ItemIndex := 0;
215
Once the desired Formula has been located, the Formula property can be set. This is a stringlist that contains the actual Formula text. Since it is a stringlist, three different methods can be used to write to it: 1. The default Strings array (subscript): {Clear the Formula first} Crpe1.Formulas.Formula.Clear; Crpe1.Formulas.Formula[0] := '"Formula String"';
NOTE: It is also acceptable, and perhaps easier to read, if the subscript specifying the Formulas item is also used in the expression, although since the VCL objects have an internal Index, it is not strictly necessary:
{Clear the Formula first} Crpe1.Formulas[0].Formula.Clear; Crpe1.Formulas[0].Formula[0] := '"Formula String"'; If the subscript value is not known, it can be obtained right after setting the Formula Name: {Clear the Formula first} Crpe1.Formulas.Name := 'FormulaOne'; i := Crpe1.Formulas.ItemIndex; Crpe1.Formulas[i].Formula.Clear;Crpe1.Formulas[i].Formula[0] := '"Formula String"'; 2. The Text property: Crpe1.Formulas.Formula.Text := '23'; 3. The Assign method Crpe1.Formulas.Formula.Assign('Date(1998,01,01)');
Examples
The following examples are presented in this section.
Passing a variable from Delphi that results in a String data type in Crystal Reports, Page 216 Passing a variable from Delphi that results in a Numeric data type in Crystal Reports, Page 218 Passing a variable from Delphi that results in a Date data type in Crystal Reports, Page 219
Passing a variable from Delphi that results in a String data type in Crystal Reports
As both Delphi and Crystal Reports require string values to be surrounded by quotes, a variable that results in a string data type in Crystal Reports requires two sets of quotes: one set for Delphi and one set for Crystal Reports. The first two examples show how to pass the variable when the value of the variable is hard-coded. The third example shows how to pass the variable when the value of the variable is entered via an EditBox at runtime.
216
Example 1: The value is hard-coded and includes the extra quotes while assigning the variable a value: var sTmp: string; {Declare sTmp as a string variable} begin {Assign a value to the variable. Note the use of two sets of quotes} sTmp := '"This is a string"'; Crpe1.Formulas.Name := 'StringFormula'; {Set the variable to the VCL Formula property} Crpe1.Formulas.Formula.Text := sTmp; {Display the value that is passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: "This is a string"} {The Report will print: This is a string} Example 2: The value is hard-coded and includes the extra quotes in the Formula statement: var sTmp: string; {Declare sTmp as a string variable} begin {Assign a value to the variable. Note the use of one set of quotes} sTmp := 'This is a string'; Crpe1.Formulas.Name := 'StringFormula'; {Concatenate Formula with: opening quote, variable name, closing quote} Crpe1.Formulas.Formula.Text := '"' + sTmp + '"'; {Display the value that is passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: "This is a string"} {The Report will print: This is a string} Example 3: Shows how to pass a variable when the value is entered via an EditBox at runtime: var sTmp: string; {Declare sTmp as a string variable} begin {Assign the contents of an EditBox to the sTmp variable} sTmp := Edit1.Text; Crpe1.Formulas.Name := 'StringFormula'; {Concatenate Formula with: open quote, variable name, close quote} Crpe1.Formulas.Formula.Text := '"' + sTmp + '"'; {Display the value passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: EditBox value with surrounding double quotes} {The Report will print: EditBox value without surrounding double quotes}
217
Passing a variable from Delphi that results in a Numeric data type in Crystal Reports
Because the Formulas object passes only string data types, variables declared as type Integer must be converted to a string before being passed to Crystal Reports. The first example shows a number in a variable declared as type String. The second example shows a variable declared as type Integer converted to a string by using an additional string variable and the Str() function. Example 1: The value is hard-coded and the variable declared as type String: var sNum: string; {Declare sNum as a string variable} begin {Assign a value to the variable. Note the use of one set of quotes} sNum := '1234'; Crpe1.Formulas.Name := 'NumberFormula'; {Pass the variable value to the Formula text} Crpe1.Formulas.Formula.Text := sNum; {Display the value passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: 1234} {The Report will print: 1234} Example 2: The value is hard-coded and the variable declared as type Integer: var nTmp: integer; {Declare nTmp as an integer variable} sNum: string; {Declare sNum as string variable} begin {Assign a value to the integer variable.} nTmp := 1234; {Assign the value of nTmp to the sNum string variable} Str(sNum, nTmp; Crpe1.Formulas.Name := 'NumberFormula'; {Pass the variable value to the Formula text} Crpe1.Formulas.Formula.Text := sNum; {Display the value passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: 1234} {The Report will print: 1234}
218
Passing a variable from Delphi that results in a Date data type in Crystal Reports
Crystal Reports accepts dates only as a string data type in the Date(yyyy,mm,dd) format. The first example shows the date hard-coded and assigned to a single variable as a numeric string. The second example shows the date hard-coded and assigned to three variables as numeric strings. The third example shows how to pass the variable when the date is entered via three EditBoxes at runtime. Example 1: The date is hard-coded and assigned to a single variable as a string. Formatting is done in the Formula statement: var sDate: string; {Declare sDate as a string variable} begin {Assign a value to the variable. Note that the year is 4 digits, the month and day are 2 digits. The year, month and day are in the order Crystal Reports expects and are delimited by commas, and the entire string is surrounded by quotes.} sDate := '1995,01,31'; Crpe1.Formulas.Name := 'DateFormula'; {Concatenate Formula with: the word Date, opening parenthesis, the variable name, closing parenthesis} Crpe1.Formulas.Formula.Text := 'Date(' + sDate + ')'; {Display the value passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: Date(1995,01,31)} {The Report will print: 95/1/31} {The Date format will be Windows default unless formatted otherwise in the Report} Example 2: The date is hard-coded and assigned to three variables as numeric strings. Formatting is done in the Formula statement: var {Declare sYear, sMonth, sDay as string variables} sYear, sMonth, sDay: string; begin {Assign a value to sYear; Note that the year is 4 digits} sYear := '1995'; {Assign a value to sMonth; Note that the month is 2 digits} sMonth := '01'; {Assign a value to sDay; Note that the day is 2 digits} sDay := '31'; Crpe1.Formulas.Name := 'DateFormula'; {Concatenate the Formula with: the word Date, opening parenthesis, the sYear variable, a comma, the sMonth variable, a comma, the sDay variable, a comma, and a closing parenthesis}
219
Crpe1.Formulas.Formula.Text := 'Date(' + sYear + ',' + sMonth + ',' + sDay + ')'; {Display the value passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: Date(1995,01,31)} {The Report will print: 95/1/31} {The Date format will be Windows default unless formatted otherwise in the report} Example 3: The date is entered via three EditBoxes at runtime. The formatting is included while assigning the variable its value: var {Declare sYear, sMonth, sDay, and sWholeDate as string variables} sYear, sMonth, sDay, sWholeDate: string; begin {Assign the Year Entry EditBox value to sYear} sYear := Edit1.Text; {Assign the Month Entry EditBox value to sMonth} sMonth := Edit2.Text; {Assign the Day Entry EditBox value to sDay} sDay := Edit3.Text; {Concatenate Formula with: the word Date, an opening parenthesis, the sYear variable, a comma, the sMonth variable, a comma, the sDay variable, a comma, and a closing parenthesis, and assign the value to the sWholeDate variable} sWholeDate := 'Date(' + sYear + ',' + sMonth + ',' + sDay + ')'; Crpe1.Formulas.Name := 'DateFormula'; {Pass the variable value to the Formula text} Crpe1.Formulas.Formula.Text := sWholeDate; {Display the value passed to the Report} ShowMessage(Crpe1.Formulas.Formula.Text); {The Message Box will display: Date(YYYY,MM,DD) where YYYYMMDD represents whatever was entered in the Year Entry, Month Entry, and Day Entry Edit Boxes at runtime} {The Report will print: YYYY/MM/DD} {The Date format will be Windows default unless formatted otherwise in the Report}
220
Introduction
Section names in the Crystal Reports VCL are now the same as the shortened section names used in the Crystal Report Designer. The following prefixes are used for the different possible sections: RH PH GH D GF PF RF = Report Header = Page Header = Group Header = Details = Group Footer = Page Footer = Report Footer
Group Headers and Footers also have a number associated with the prefix, which specifies to which Group they belong, starting with the number 1 for the first Group: GH1 GF2 = Group Header for Group 1 = Group Footer for Group 2
If a Section has been divided into multiple Sub-Sections, these are specified by alphabetic letters going from a to z and then aa to zz, and so on. GH1a GF2b = Group Header 1, sub-section a = Group Footer 2, sub-section b
If the Retrieve method is used for the properties such as SectionFormat and AreaFormat, the Section property will automatically be calculated and filled by the VCL Component. If the manual Add/Delete methods are used, the Section will have to be assigned manually.
221
Methodology
The Crystal Reports Print Engine uses the following numbering division:
q 1000 q 25 q0
For example: 1000 is used for the report Header 2000 for the Page Header 3000 for the Group Header, etc. Groups can be from 0 to 24, so: Group Header 1 is 3000 Group Header 3 is 3002, etc. Sub-sections are divided by 25, so: Group Header 1a is 3000 Group Header 2b is 3026, etc. This means a possible 40 divisions of 25 for each Section, since 40 * 25 = 1000. Therefore the print engine cannot access more than 40 sub-sections at runtime. Since the VCL Component uses the runtime print engine, it also has this limitation. While this is not usually a problem with most reports, the limit is reached if a report contains more than 40 Detail sections, for example. In such cases, the VCL Component will only retrieve the first 40 sections. Using the information spelled out above, a simple example of the sections of a report, with their corresponding section code numbers is illustrated below: Area / Sections Report Header Report Header a Report Header b Page Header Page Header a Page Header b Area / Section Numbers 1000 1000 1025 2000 2000 2025
222
Group Header 1 Group Header 1a Group Header 1b Group Header 1c Group Header 2 Group Header 2a Group Header 2b Group Header 2c Details Details a Details b Group Footer 2 Group Footer 2a Group Footer 2b Group Footer 2c Group Footer 1 Group Footer 1a Group Footer 1b Group Footer 1c Page Footer Page Footer a Page Footer b Report Footer Report Footer a Report Footer b
3000 3000 3025 3050 3001 3001 3026 3051 4000 4000 4025 5001 5001 5026 5051 5000 5000 5025 5050 7000 7000 7025 8000 8000 8025
StrToSectionCode
The StrToSectionCode function is used internally by the Seagate Crystal Reports Component, but it is also a public method and can be used by programmers. It's purpose is to take a Section name from one of the component's Section properties and turn it back into a Print Engine Section code. This function is also used by those objects that have a SectionAsCode property.
223
C++ Builder 3
The following topics are discussed in this section.
Introduction, Page 224 Code Syntax, Page 224 Additional Code Examples, Page 225
Introduction
The Inprise (formerly Borland) C++ Builder 3 version of Seagate Crystal Reports 32-bit Delphi VCL Component has the same features as the Delphi version. In fact, it was recompiled from the Delphi source code. This component is released "as-is". It has slight modifications to the source (nothing that affects the properties or methods, just some compiler directives, etc.) made by a third party, to make it compile and run in the BCB3 environment. Currently, only limited support is offered for any problems arising from the use of this component. The Help file included is from the Delphi VCL Component, using Delphi code examples. Some notes regarding the BCB syntax are included below. Note that it is always possible to use direct Print Engine calls to the CRPE32.DLL using the CRPE.H and other header files included with Crystal Reports as an alternative. The installation of the C++ Builder Component was discussed earlier in this chapter in the installation section, C++ Builder 3, Page 198.
Code Syntax
The general guidelines for translating the Delphi code examples (in the Help file) to BCB are as follows: 1. Use the equals sign (=) instead of the colon-equals sign (:=) for assignment, and use the arrow pointer (->) instead of Delphi's dot (.) to specify class members. //Delphi Crpe1.DetailCopies := 3; //C++Builder Crpe1->DetailCopies = 3; 2. Use double quotes ("test") instead of single quotes ('test') for strings, and use double slashes for directories (\\) instead of single slashes (\). //Delphi Crpe1.ReportName := 'C:\Report1.rpt'; //C++Builder Crpe1->ReportName = "C:\\Report1.rpt";
224
3. Use the open brackets to specify a method or function that takes no parameters: //Delphi Crpe1.SectionFormat.Retrieve; //C++Builder Crpe1->SectionFormat->Retrieve(); 4. For default array properties, use the name of the array property instead of just the array brackets: //Delphi Crpe1.SectionFormat[1].BackgroundColor := clRed; //C++Builder Crpe1->SectionFormat->Item[1]->BackgroundColor = clRed;
225
Crpe1->SectionFormat->Retrieve(); Crpe1->SectionFormat->Section = "D"; Crpe1->SectionFormat->BackgroundColor = clRed; //The default array property Item can also be used Crpe1->SectionFormat->Item[1]->BackgroundColor = clGreen; //Run the Report Crpe1->Execute();
Known Problems
The following topics are discussed in this section.
Retrieving ParamFields from a Subreport, Page 226 DialogParent and Temporary Forms, Page 226
1 2
Set the DialogParent property of the VCL to a valid Form before running the Report a second time. Close the Print Job (Crpe1.CloseJob) and open it again to run it the second time.
226
Technical Support
Further help with Technical problems (including installation, implementation, and distribution of the VCL) can be obtained in the following ways: Phone: (604) 669-8379 Monday to Friday, 8:00am to 5:00pm, PST Email: support@webacd.seagatesoftware.com Web Email Form: http://webacd.seagatesoftware.com Fax: (604) 681-7163 The latest updates to the VCL can be obtained from: Web site: http://www.seagatesoftware.com/crystalreports/updates/ FTP site: ftp://ftp.img.seagatesoftware.com/pub/crystal/delphi/
227
I
A
D
code syntax with VCL Component ....................... 224 installation .......................... 198 using VCL Component ...... 224 changing selection formulas in web reports .................................. 30 codes section, see section codes ................................... 84 commands GF .......................................... 31 INIT ........................................ 30 Password# ............................. 32 Prompt# command ....... 35, 36 SF ........................................... 31 USER# ................................... 33 Controls ActiveX ................................ 108 Grid ...................................... 139 Create Report Expert database definition tool ..................................... 124 creating formatted bound reports ... 142 CrossTabObject ......................... 186 Crystal ActiveX Control ............ 108 Crystal Data Object using .................................... 129 Crystal Data Object (CDO) ..... 128 Crystal Data Object Model ..... 131 Crystal Data Source Type Library ................................... 131 Crystal Data Sources ................ 139 Crystal DataSouce object passing to Active Data Driver ................................. 137 Crystal Report Engine distributing applications ...................... 102 introduction .......................... 64 structures ............................... 92 using ...................................... 66 variable length strings ......... 89 when to open and close ................................... 104 Crystal Report Engine API .......... 68 using ...................................... 70 using in Visual Basic ......... 104 Crystal Report Engine Automation Server ............................. 44, 111 Crystal Report Engine Object Library viewing ................................ 115
Access, Microsoft see Microsoft Access Active Data Driver .......... 118, 125 using ..................................... 119 working with ....................... 118 Active Server Pages editing .................................... 47 session timeout ..................... 48 ActiveX Crystal Data Object CDO) .................................. 128 Crystal Smart Viewer ........... 57 ActiveX Control ......................... 108 adding to project ................ 108 changing properties ........... 110 changing properties at runtime .......................... 110 using ..................................... 109 ActiveX Data Sources ............... 118 using at design time ........... 126 ActiveX, Design-time Control ..................................... 44 administration Crystal Web Report erver ..................................... 16 ADO data sources ..................... 118 API Report Engine ....................... 68 Application Object and Report Designer Component ....................... 187 creating in VB ..................... 112 applications Report Engine ..................... 102 AuthentiCode, see Microsoft Authenticode Automation Server ............. 44, 111 adding to VB project ......... 111 distributing in VB applications ....................... 117 error handling in VB .......... 114 handling preview window events in VB ...................... 115 object name conflicts in VB .................................. 114 sample application in VB .................................. 117 session timeout ..................... 48 using in VB .......................... 112
Crystal Smart Viewer ActiveX .................................. 57 ActiveX parameters .............. 59 customizing ........................... 47 HTML ..................................... 53 Java ......................................... 55 Java parameters .................... 55 overview ................................ 50 printing from ......................... 51 Crystal Web Report Server administration ....................... 16 architecture ........................... 37 choosing version .................... 8 Command Expert .................. 29 commands ............................. 28 Image Server ................. 26, 39 implementing .......................... 8 installing .................................. 9 Job Manager .......................... 41 overview .................................. 2 Page Server .................... 26, 39 system requirements .............. 9 virtual directories ................. 14 customizing the Crystal Smart Viewer ..................................... 47 custom-print links coding .................................... 75 establishing ........................... 74 sample of ............................... 78 DAO data sources ..................... 118 Data Selecting with Report Designer Component ........................ 153 data and VCL Component ......... 210 drilling down on ................... 27 refreshing web report .......... 37 saved, and VCL Component ........................ 210 Data Definition Files ................. 119 and Report Designer Component ........................ 164 creating ................................ 123 database definition tool ..................... 124 Database object ......................... 186 databases changing group and summary fields with VCL Component ........................ 211 changing tables and formulas with VCL Component ...... 211
Index-1
connecting with the VCL Component ....................... 210 ODBC .................................... 31 secured .................................. 31 SQL ........................................ 31 DatabaseTable object ............... 186 Delphi installation, Delphi 2 VCL Component ....................... 194 installation, Delphi 3 VCL Component ....................... 195 installation, Delphi 4 VCL Component ....................... 195 Design-time ActiveX Control ..... 44 developers session timeout in Automation Server ................................... 48 what you should know ........ 65 development Report Engine API ................ 68 directories Crystal Web Report Server ................................... 14 distributing Report Engine applications .......................... 102 DLL VB Wrapper ........................ 107 drilling down on data ................. 27 Drivers Active Data ......................... 125 database (ADO, DAO, and RDO) .................................. 118 using Active Data ............... 119 editing Active Server Pages ............. 47 errors, preview window handling ................................ 97 establishing custom-print links ................ 74 print-only links ..................... 71 Events Format, and Report Designer Component ....................... 179 Preview window events in Automation Server ........... 115 Report, and Report Designer Component ....................... 188 existing reports selecting ................................ 45 Expert Crystal Web Server Command ............................ 29
Report, and Report Designer Component ....................... 154 export functions considerations for using .................................... 97 exporting reports ................................... 94 FieldObject object .................... 184 Files Data Definition .................. 119 Data Definition, and Report Designer Component ...... 164 Data Definition, creating .............................. 123 DLL, see DLL formatted bound reports creating ............................... 142 Formulas Delphi, examples with variables ............................ 216 Delphi, using variables ..... 215 GF command ............................... 31 Grid Controls ............................. 139 group selection formulas GF command ....................... 31 handling preview window errors ....................................... 97 Help Context-sensitive, Delphi 3 VCL Component .............. 197 Context-sensitive, Delphi 4 VCL Component .............. 197 HTML Crystal Smart Viewer ........... 53 HTML reports limitations of ......................... 53 Image Server Crystal Web Report Server ................................... 39 Images Report Designer Component and OLE object ................ 182 using with Report Designer Component ....................... 149 INIT command ............................ 30
installation C++ Builder 3 VCL Component ........................ 198 Crystal Web Report Server ..................................... 9 Delphi 2 VCL Component ........................ 194 Delphi 3 VCL Component ........................ 195 Delphi 4 VCL Component ........................ 195 Report Designer Component ........................ 151 VCL Component ................. 194
Java
Libraries Crystal Data Source Type .................................... 131 Crystal Report Engine Object ................................ 115 limitations of HTML reports ....... 53 links coding custom-print ............. 75 establishing custom-print .... 74 establishing print-only ......... 71 logging on Password# command .......... 32 USER# command ................. 33 methods Retrieve, and VCL Component ........................ 205 Send, and VCL Component ......................... 211 StrToSectionCode, and VCL Component ........................ 223 Microsoft Access, and Report Designer Component ........................ 189 AuthentiCode ........................ 58 Object Inspector VCL Component ................. 200 Objects Application and Report Designer Component ....... 187 Application, see Application Object ................................ 112
Index-2
CrossTabObject, and Report Designer Component ...... 186 Crystal Data ........................ 128 Crystal Data Object Model ................................. 131 Database, and Report Designer Component ....................... 186 DatabaseTables, and Report Designer Component ...... 186 FieldObject, and Report Designer Component ...... 184 Object Inspector, VCL Component ....................... 200 passing CRDataSource object to Active Data Driver ...... 137 releasing in VB ................... 114 Report, see Report Object ReportObjects collection, and Report Designer Component ....................... 183 Rowset, see Rowset Object SubClass, and VCL Component ....................... 203 SubreportObject, and Report Designer Component ...... 185 Text, and Report Designer Component ....................... 180 OCX adding to project ................ 108 changing properties ........... 110 using ..................................... 109 ODBC databases ......................... 31 OLE control adding to project ................ 108 changing properties ........... 110 changing properties at runtime .......................... 110 using ..................................... 109 opening Crystal Report Engine ........ 104 overview Crystal Smart Viewer ........... 50 Crystal Web Report Server ... 2 Page Server Crystal Web Report Server ................................... pages editing Active Server ........... parameter fields Prompt# command ...... 35, parameters Crystal Smart View for Java .................................
39 47 36 55
Crystal Smart Viewer for ActiveX ................................ 59 GF command ....................... 31 ranges .................................... 83 values .................................... 83 Password# command ................. 32 passwords Password# command .......... 32 Pictures see Images preview window errors handling ................................ 97 printing from the Crystal Smart Viewers ................................ 51 print-only link establishing ........................... 71 example code for ................. 73 problems Delphi VCL Component ....................... 226 Delphi, DialogParent and Temporary Forms ............. 226 Delphi, retrieving ParamFields from Subreport ................. 226 procedures SQL stored, see SQL Programmatic ID and Report Designer Component ....................... 189 programming Delphi, introduction to the Print Engine ...................... 201 Report Designer Component Object Model ................... 173 Report Engine API ................ 68 subreports and VCL Component ....................... 206 VCL Component and Crystal Reports Designer .............. 202 VCL Component and Sub-Class Objects .............................. 203 VCL Component tips ......... 209 VCL Component, and Retrieve method .............................. 205 VCL Component, changing properties at runtime ....... 200 VCL Component, changing properties with Object Inspector ............................ 200 VCL Component, Consistent Code .................................. 204 VCL Component, Delphi overview ............................ 199 VCL Component, guidelines .......................... 208
VCL Component, Object Inspector ............................ 200 Prompt# command .............. 35, 36 properties JobNumber, and VCL Component ........................ 212 ReportName, and VCL Component ........................ 209 RDO data sources ..................... 118 REAPI ............................................. 68 structures ............................... 92 variable length strings .......... 89 refreshing web report data .................... 37 Report Designer Component ... 145 adding RDC to a roject .................................. 152 adding Smart Viewer ......... 155 and ActiveX ......................... 146 and ADO ............................. 158 and Application object ...... 187 and CrossTabObject object ................................. 186 and CRViewer1 .................. 156 and CrystalReport1 ............ 156 and DAO ............................. 158 and Data Definition Files .................................... 158 and data sources ...... 158, 176 and Database object .......... 186 and DatabaseTable object ................................. 186 and FieldObject Object .... 184 and Microsoft Access sessions .............................. 189 and ODBC ........................... 158 and OLEDB ......................... 158 and PC data sources .......... 158 and Programmatic ID ........ 189 and RDO ............................. 158 and Report Events .............. 188 and Report Packages ......... 158 and Report Templates ........ 158 and ReportObjects collection ........................... 183 and Seagate Crystal Reports ............................... 147 and secure data sources .... 179 and Smart Viewer Control ............................... 156 and SQL data sources ........ 158 and SubreportObject object ................................. 185
Index-3
and Text Objects ................ 180 and the Format Event ......... 179 and VB Data Environment ...................... 158 and Visual Basic ................. 150 Architecture ........................ 170 Conditional Formatting ..... 148 Copy and Paste ................... 148 data access .......................... 148 Display code ....................... 157 distributing reports ............. 190 distribution of the Application ........................ 151 existing report as report template ............................. 167 exporting reports ................ 187 features ................................ 146 guidelines ............................ 149 Images .................................. 149 images, OLE object ............ 182 installation ........................... 151 introduction ........................ 146 Object Model programming .................... 173 passing fields ...................... 177 Pictures, see Images Preview Window ............... 149 Report Expert ...................... 154 running the application ..... 155 section codes ...................... 182 selecting data for a report .............................. 153 subreports ............................ 149 system requirements .......... 151 using the RDC .................... 151 Report Engine API .......................................... 68 before using in your application .......................... 65 distributing applications ... 102 introduction .......................... 64 using ....................................... 66 Report Engine API overview ................................ 68 structures ............................... 92 using in Visual Basic ......... 104 variable length strings ......... 89 Report Engine Automation Server ....................................... 44 Report Events and the Report Designer Component ....................... 188 Report Expert, Report Designer Component ........................... 154 Report Object obtaining in VB .................. 113
using in VB ......................... 113 Report Packages and Report Designer Component ....................... 158 ReportObjects collection ......... 183 reports creating formatted bound ................................ 142 distributing with Report Designer Component ...... 190 establishing custom-print link ....................................... 74 exporting ............................... 94 exporting in Report Designer Component ....................... 187 limitations of HTML ............ 53 selecting existing ................. 45 using existing as template in Report Designer Component ......................... 167 Rowset Object adding fields ....................... 130 sample web site ........................... 48 section codes and Report Designer Component ....................... 182 and VCL Component ........ 221 decoding ............................... 86 working with ........................ 84 Section Map ................................. 87 section names and VCL Component ........ 221 see also section codes VCL Component, StrToSectionCode method ................................ 223 secured databases ....................... 31 selecting existing reports to use ......... 45 selection formulas changing in web reports ..... 30 SF command ......................... 31 Server Image, see Crystal Web Report Server Page, see Crystal Web Report Server Server, Automation ..................... 44 Session Timeout .......................... 48 SF command ................................ 31 Smart Navigation ........................ 26 Smart Viewer ActiveX .................................. 57
customizing ........................... 47 HTML ..................................... 53 Java ......................................... 55 printing from ......................... 51 see also Crystal Smart Viewer SQL connection to databases with VCL Component ............... 210 databases, and Web Reports Server ................................... 31 stored procedures, and Web Reports Server ..................... 34 stored procedures, SQL see SQL structures Report Engine API ................ 92 SubClass Objects and VCL Component ........................ 203 SubreportObject, and Report Designer Component .......... 185 subreports and the VCL Component .. 206 using with Report Designer Component ........................ 149 working with ......................... 93 system requirements Crystal Web Report Server .... 9 Report Designer Component ......................... 151 TCrpeString and VCL Component ......... 212 Technical Support contacting ............................ 227 Text Objects and Report Designer Component ........................ 180 user IDs USER# command ................. 33 USER# command ......................... 33 using Crystal Report Engine API in Visual Basic ....................... 104 existing reports ..................... 45 the Crystal Report Engine .... 66 the Crystal Report Engine API ............................. 70
Index-4
VCL Component and C++ Builder 3 ............. 224 and saved data ................... 210 and section names ............. 221 and subreports .................... 206 changing database tables and formulas ............................. 211 changing group and summary fields ................................... 211 connecting to databases ........................... 210 Delphi programming overview ........................... 199 installation ........................... 194 JobNumber property .......... 212 know problems ................... 226 overview .............................. 194 programming guidlines ..... 208 programming tips ............... 209 properties, changing at runtime ............................ 200 properties, changing with Object Inspector ............... 200 ReportName property ........ 209 Retrieve method ................. 205 Send method ....................... 211 StrToSectionCode method ............................... 223 TCrpeString ......................... 212 using variables .................... 215 Visual Basic ActiveX Control, upgrading from Crystal Custom Control ............................... 110 ActiveX Controls ................ 108 adding ActiveX Control to project ................................ 108 adding Automation Server to project ........................... 111 changing properties for ActiveX Control ................ 110 changing properties for ActiveX Control at runtime ............ 110 dates and date ranges ........ 105 embedded quotes in VB calls ......................... 104 hard coded nulls in VB user defined types ..................... 107 releasing objects ................. 114 sample Automation Server application ........................ 117 section codes and ................ 88 solutions .............................. 103 string issues in VB links .............................. 106 using ActiveX Control ....... 109
using Automation Server .. 112 using the Crystal Report Engine API in ................................. 104 Wrapper DLL ...................... 107 Visual Basic applications when to open Crystal Report Engine ................................ 104 Visual InterDev Design-time ActiveX Control ..................... 44 web reports changing selection formulas in .......................... refreshing data ...................... web site sample of .............................. working with section codes ...............
30 37 48 84
Index-5