The Report Engine Object Model
The Report Engine Object Model is the .NET programmatic entry point to the Crystal Reports engine. It provides a collection of objects, methods, and properties that enable you to process, save, export, and print reports. While doing that, you are able to manipulate the report by modifying parameter values, database credentials, sorting, and grouping. The Report Engine Object Model (hereafter referred to as the object model) consists of a standard .NET assembly called CrystalDecisions.CrystalReports.Engine.dll. As the name of the dll implies, the namespace for all the objects contained in this dll is CrystalDecisions. CrystalReports.Engine. Because this is a standard .NET assembly, the object model contained within it can be used from any .NET programming language or tool. All sample code within this chapter uses the Visual Basic .NET language, but any .NET-compliant language could, of course, be used. Keep in mind that although the object model is pure "managed" code, the underlying report engine is not. This means you can perform a pure "xcopy" deployment that Microsoft likes to advertise that all .NET applications can do.
There are many objects and thus capabilities in the object model. This chapter does not explain all of them but rather covers the most common scenarios. For a complete reference of all objects, properties, and methods, consult the Crystal Reports 10 documentation that is installed to the MSDN Help Collection. Some of you may be skeptical about the product documentation because in the past it was very sparse. However, there is much more information in the documentation in version 10 than ever before; have a look through it and you will be impressed.
Opening Reports
The main object you use when working with the object model is the ReportDocument object. It is the root object in the object model hierarchy and forms the entry point to opening reports. The first step in opening reports is to create a new instance of the ReportDocument class. Then to open a report file, call the Load method. This method takes a single parameter, which is a string that points to the RPT file. An example of this is as follows:
Dim Report As New ReportDocument Report.Load("C:My ReportsSales.rpt")
NOTE
One common way to handle file paths is to use Application.StartupPath to determine the current location of the Windows Forms executable and reference report files relative to there.
The other way to load a report is to use a strongly typed report object. A strongly typed report object is an object automatically generated when a report is added to the Visual Studio .NET project. This object (sometimes called code-behind) is specific to the report file both in its class name and properties. For example, a report added to the project called InvoiceReport.rpt would in turn have a class called InvoiceReport. Instead of calling the Load method, a developer only needs to create an instance of the InvoiceReport class. This class knows how to locate the report. In the case of strongly typed reports, instead of having an external RPT file, the report file is compiled into the application executable. The report is loaded out of the applications resources from there. Whether you use a ReportDocument (untyped report) or a strongly typed report, the rest of the object model is the same.
Exporting Reports
One of the most common uses of the object model is to run a report and export it to another file format. In past versions, exporting required a good sized chunk of code. Fortunately exporting in version 10 is very easy with the updated object model. First, a ReportDocument object needs to be created and a report loaded into it. After that is done, several exporting methods are available to you:
- ExportToDisk: This is the simplest way to export a report; it accepts an argument to indicate the export format type to use and a filename to export to. This method is useful when you just need to export a file to the disk.
- ExportToStream: This method only accepts a single argumentthe export format type. The return value of this method is a System.IO.Stream object. This is actually a MemoryStream object so you can cast it to a MemoryStream if need be. This method is useful when you intend to send the exported report elsewhere as a stream without having to write to an intermediate disk file. Its best to call the steams Close method when finished with the stream to release memory.
- ExportToHttpResponse: This method is similar to the ExportToStream method in that it is intended to be used when the resulting report is streamed back to the user. However, this method accepts as an argument the ASP.NET HttpResponse object and automatically streams the exported report back to the Web browser handling the mime type and response stream for you.
- Export: This method is the master Export method. It accepts an object called ExportOptions as an argument that describes the export format type and destination type. You can think of this as the "long-hand" way of exporting but it does allow for a few additional options such as e-mail and Exchange destinations and page range options.
A common argument to all these exporting methods is the export format type. This is specified using the ExportFormatType enumeration found in the CrystalDecisions.Shared namespace. Its generally a good idea to add a reference to CrystalDecisions.Shared.dll because you will find many common objects used in the object model located in this assembly. The following list describes the members of the ExportFormatType enumeration:
- Excel: Microsoft Excel format
- ExcelRecord: A variation of the Microsoft Excel format that just exports the data, not the formatting
- HTML32: HTML for Netscape Navigator or other non-common browsers
- HTML40: HTML for Microsoft Internet Explorer
- PortableDocFormat: Adobe PDF format
- RichText: Microsofts Rich Text Format (RTF)
- WordForWindows: Microsoft Word format
- Text: Plain text format
- CrystalReport: Standard Crystal Reports (RPT) format
TIP
When exporting to Crystal Reports format, a standard RPT file is created; however, the report has saved data. This is quite useful because you can run a report once and export to Crystal Reports format and then have many people view that report using the saved data. In this scenario, only one hit is made to the database even though many people are viewing the report. This is similar to creating a report instance in the Crystal Enterprise environment. This feature can be used to affect a greater scalability by introducing a "report instance" delivery model.
A common scenario for exporting would be processing many reports in a batch job. This is a great use of the object model. To help you do this effectively, Ill share a few tips here. First, you need to clean up to make sure memory is released, and second, use multiple threads to maximize the time available for processing reports. The report engine object model is thread safe. Listing 29.1 illustrates a multithreaded report processing class. Listing 29.2 shows how this class could be called.
Listing 29.1. Multithreaded Batch Processing Class
Imports System.Threading Imports CrystalDecisions.Shared Imports CrystalDecisions.CrystalReports.Engine Public Class BatchProcessor Private ReportList As New ArrayList Private OutputFolder As String Private BatchCounter As Integer Call this method to add a report to the list of reports to be processed by the batch processor Public Sub AddReportJob(ByVal ReportPath As String) ReportList.Add(ReportPath) End Sub This runs an individual report job Private Sub ProcessNextReportJob(ByVal Index As Object) Dim report As New ReportDocument Dim outputFileName As String Load the report based on index report.Load(ReportList(Index)) Construct an output filename outputFileName = "Report" & Index & ".pdf" Call the ExportToDisk method report.ExportToDisk(ExportFormatType.PortableDocFormat, _ OutputFolder & "" & outputFileName) Make sure to clean up the report object report.Close() Decrement a counter of remaining jobs BatchCounter = BatchCounter - 1 End Sub Public Sub ExecuteBatch(ByVal OutputFolder As String) Me.OutputFolder = OutputFolder BatchCounter = ReportList.Count Grab the current time Dim startTime As DateTime = DateTime.Now Start the batch job Dim i As Integer For i = 1 To ReportList.Count Use the .NET ThreadPool class to handle the multiple requests Dim wc As New WaitCallback(AddressOf ProcessNextReportJob) ThreadPool.QueueUserWorkItem(wc, i - 1) Next While BatchCounter > 0 Thread.Sleep(250) End While Dim elapsedTime As TimeSpan = DateTime.Now.Subtract(startTime) MessageBox.Show("Batch completed in " + _ elapsedTime.Seconds.ToString() & " seconds") End Sub End Class
Listing 29.2. Calling the Batch Processor
Dim bp As New BatchProcessor bp.AddReportJob("C:TempReportsReport1.rpt") bp.AddReportJob("C:TempReportsReport2.rpt") bp.AddReportJob("C:TempReportsReport3.rpt") bp.AddReportJob("C:TempReportsReport4.rpt") bp.AddReportJob("C:TempReportsReport5.rpt") bp.AddReportJob("C:TempReportsReport6.rpt") bp.AddReportJob("C:TempReportsReport7.rpt") bp.AddReportJob("C:TempReportsReport8.rpt") bp.AddReportJob("C:TempReportsReport9.rpt") bp.AddReportJob("C:TempReportsReport10.rpt") bp.ExecuteBatch("C:TempOutput")
Printing Reports
Although the fantasy of a paperless office floats around our heads, the reality today is that no matter how much technology for viewing reports is produced, people will always want to print them. Along these lines, the object model supports printing reports to printers. This is accomplished by calling the ReportDocuments PrintToPrinter method. It takes the following arguments, which determine basic print settings:
- nCopies: An integer representing the number of copies to print
- collated: A Boolean value indicating whether the printed pages should be collated
- startPageN: An integer representing the page number on which to start printing
- endPageN: An integer representing the page number on which to end printing
In addition to these printing options, there is another set of more advanced options. These options are in the form of properties and are contained in the ReportDocuments PrintOptions object:
- PaperSize: An enumeration of standard paper sizes, such as Letter or A4
- PaperOrientation: An enumeration to indicate the orientation of the paper, such as Portrait or Landscape
- PageMargins: A PageMargins object containing integer-based margin widths
- PageContentHeight/PageContentWidth: Integer-based width and height for the main page area
- PaperSource: An enumeration containing standard paper tray sources such as upper and lower
- PrinterDuplex: An enumeration containing duplexing options for the printer
- PrinterName: A string representing the name of the printer device or print queue
NOTE
Keep in mind that whatever account the report engine object model is running under needs access to the printer when the PrintToPrinter method is invoked. Sometimes when the object model is used in ASP.NET, it is running under a Guest-level account, which does not have access to the machines printers. If this is the case, you need to install and grant access to the printers for that account.
Категории