Monday, July 7, 2008

Using Crystal Reports with C# and ASP.NET

I've been using Crystal Reports for more than 3 to 4 years now, but I've never bothered to use it for Web-based applications. I've always just used it for standalone Windows executable applications. Recently, I've been thinking on how I can generate PDF reports for directly downloading over the web just like the ones available at Citibank Online. Writing web-based reports using traditional HTML is pretty cumbersome. And with more and more NetSecure clients asking for report customizations, I've been dreading having to touch the NetSecureWeb code for new reports.

Since I seem to recall reading somewhere that the Crystal Reports that comes with Visual Studio can be used for making web reports, I decided to do some R&D today. First stop, of course, is Google. Doing a search on "crystal reports for .net", the first three links returned gave me all the answers I needed.

Armed with the first article at the top of the search, I started off with my POS Solution. I created a new test web application, and added a Crystal Reports item onto it. Doing some quick copy-and-pasting from the main POS source code, I got a report running in record time (well, it took me several minutes because I got stumped with something that turned out to be an error on my part).

Next, I wanted to implement an export-to-PDF or view-as-PDF-on-the-web feature. The 3rd article from the search shows just how simple it is. Its basically the same as the code to do the one above, except you just add something like:

MemoryStream oStream = (MemoryStream)userReport.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
Response.Buffer= true;
Response.ContentType = "application/pdf";

And voila! The Acrobat plug-in opens the PDF on your IE and the report is displayed as PDF. And, of course, it follows that the user can print the PDF report by using the Acrobat plug-in's (or the browser's) capability to send its output to the printer.

There is also this interesting article about publishing the Crystal Report as a web service. Then when you drag-and-drop a Crystal Report control onto your form, you just point its report source to the URL of the web service. Very interesting concept. One can make the reports appear as a web service, and it can be extracted on runtime by standalone exe's or web-based applications. No need to embed the .rpt file directly onto the applications. Makes it easier to update also without having to recompile the code of your apps.

No comments: