AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1991&pId=-1
Using the New WPF Viewer with SAP Crystal Reports for Visual Studio 2010
page
by Vince Varallo
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 46588/ 27

Introduction

One of the new features of SAP Crystal Reports for Visual Studio 2010 is the WPF Viewer. This control makes is easy to integrate your reports into your WPF applications. You still get all the features of the viewer just as if it were a WinForms or ASP.NET application. This article will create a WPF application that uses the Entity Framework to populate a DataGrid control and then also display the data in a Crystal Report.

Before you begin you will need to have installed Visual Studio 2010. Crystal Reports is no longer distributed with Visual Studio and is available as a separate download. You can download Crystal Reports here. You also will need to download the AdventureWorks sample database from here.  Once you've installed the database you will need to create a SQL Login that the WPF application can use to connect to the database. My sample code expects a SQL Login to be called "aspalliance" with the password "aspalliance". The sample code for this application can be downloaded here.

Using the Viewer

Step 1: Create a New Solution

1.    Launch Visual Studio 2010.

2.    Select File -> New Project… from the menu.

3.    Select the WPF Application template from the list of C# templates.

4.    Name the project AdventureWorks and click the OK button. The MainWindow.xaml should appear in you designer. This is the form we'll use to display the data in a grid and we'll drop a button on the form to display the report.

Step 2: Displaying the data in a DataGrid control using the Entity Framework

1.    Drag a DataGrid control from the toolbox to the main window. Resize the grid so it is the width of the window and is at the top of the window.

2.    Now you need to add the Entity Framework data model. Right click on the project file and select Add -> New Item…

3.    Click on the Data templates and select ADO.NET Entity Data Model.  Name the file AdventureWorksModel.edmx and click the Add button. The Entity Data Model Wizard should appear.

4.    Select the "Generate from database" option and click the Next button.

5.    The next screen asks you to choose your data connection. Click the New Connection button.

6.    Enter the server name where you installed the AdventureWorks database. Select "Use SQL Authentication" and enter the aspalliance user name and password. You needed to create this user when you installed the AdventureWorks database and give the user read access to the database.

7.    Select the AdventureWorks database from the drop down list and then click the OK button.

8.    You should now be back to the Entity Data Model Wizard. Select the option to include the sensitive information in the connection string and check the box to save the connection string in the App.Config file. Click the Next button.

9.    Expand the Tables node and check the box next to the Contact table name. This will tell the wizard to create a class that represents the Contact table that you will be able to query using LINQ.

10. Now click the Finish button.

11. The AdventureWorksModel.edmx model will appear in the Visual Studio designer. You can close this file since we won't be changing it.

12. Double click on the MainWindow to open the code pane. This will create the Window_Loaded event handler.

13. Add the following code to the event handler.

using (AdventureWorksEntities db = new AdventureWorksEntities())
{
    dataGrid1.DataContext = from c in db.Contacts
                          select new { c.FirstName, c.LastName, 
                                       c.EmailAddress, c.Phone };
 
}

This code will select all the records from the Contact table and bind them to the DataGrid when the window is loaded. 

14. Click back to the design view. In the XAML window add the following attributes to the DataGrid's tags.

AutoGenerateColumns="True" DataContext="{Binding}"  ItemsSource="{Binding}"  

This will make the DataGrid automatically create a column for each column returned from the LINQ query.

15. Run the project. The DataGrid should appear with all the records.

Step 3: Create the Crystal Report

The next step is to create the Crystal Report that will display the same data as the DataGrid.  We'll create a report that can be bound to the data by using the same LINQ query as the grid.  To do this you need to create and XSD file that contains the fields that are returned by the LINQ query.  This file is used by the Crystal Reports designer to allow you to design the report.

1.    Right click on the project file and select AddàNew Item.

2.    Click the Data node from the list of templates and then select the DataSet template.

3.    Change the name of the file to ContactSchema.xsd and click the Add button.

4.    Right click on the design surface and select AddàData Table.

5.    Right click on the data table and select AddàColumn.  Set the name of the column to FirstName.

6.    Repeat the same steps to create the LastName, EmailAddress, and Phone columns.

7.    Save this file.

8.    Now you can add the report and link it to this schema file.

9.    Right click on the project and select Add -> New Item...

10. Click on the Reporting templates and click the Crystal Reports template.

11. Change the name of the report to ContactReport.rpt and click the Add button.

12. The Crystal Reports Gallery will appear.  Select the" As A Blank Report" option and click the OK button.

13. The report should appear in design mode.  Right click on the Database Fields node in the Field Explorer and select Database Expert.  The Database Expert should appear.

14. Click the plus sign next to the Create New Connection node.

15. Click the plus sign next to the ADO.NET (XML) node.  This will display a dialog box that allows you to select the ContactSchema.xsd file that you just created.

16. Click the File Path button to browse to the xsd file.

17. Click the Finish button.

18. The DataTable1 node will appear.  Click the > button to move this node to the Selected Tables list.

19. Click the OK button.

20. The DataTable1 node will appear under the Database Fields node in the Field Explorer window.  Click the plus sign next to the table name to view the fields.

21. Drag each field to the details section in the Crystal Report file.

22. Save the report.

23. When the program is compiled the executable will be copied to the bin folder.  You need to make sure that the report file is copied there as well.  To do this right click on the ContactReport.rpt file and click on Properties.  Change the "Copy To Output Directory" to "Copy Always".

Step 4: Displaying the data in a Crystal Report

The next step will create a new window with the Crystal Reports Viewer control and then we'll add a button to the MainWindow to display the report.

1.    Right click on the project file and select AddàWindow.

2.    Change the name of the file to PrintPreview.xaml and click the Add button.

3.    Drag the CrystalReportsViewer control from the toolbox to the form.  If the control is not listed in the toolbox you can right click on a blank space in the toolbox and select Choose Items…  Check the box next to the CrystalReportsViewer control on the WPF Components tab and click the OK button.

4.    Stretch the window and the control so the user can see at least the width of the report.

5.    Double click on the window so the Window_Loaded event handler is created and the code pane is displayed.  Add the following using statements.

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

6.    Now add the following code to the Window_Loaded event handler.

ReportDocument report = new ReportDocument();
report.Load("ContactReport.rpt");
 
using (AdventureWorksEntities db = new AdventureWorksEntities())
{
   report.SetDataSource(from c in db.Contacts
                      select new { c.FirstName, c.LastName, 
                                   c.EmailAddress, c.Phone });
}
                        
crystalReportsViewer1.ViewerCore.ReportSource = report;

 

7.    The next step is to add a button to the MainWindow and add the code to the button click event to show this form.  Open the MainWindow in the designer and drag a Button control under the DataGrid control on the form.

8.    Change the content of the button to Print Preview.

9.    Double click on the button to create the click event handler.

10. Add the following code to the event handler.

PrintPreview pp = new PrintPreview();
pp.ShowDialog();

11. Now run the application. You should get a compile error.

Error 6     The tag 'CrystalReportsViewer' does not exist in XML namespace 
'clr-
namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer'. 
Line 6 Position 10

To resolve this error you need to go to the properties of the project and set the Target Framework to .NET Framework 4 not the .NET Framework 4 Client Profile. I'm not sure if this is a bug in the Beta version so hopefully you won't have to do this when the production copy is released.

12. Run the project again. You should see the grid populated with the data from the Contacts table. Now click the Print Preview button. You're going to get another error.

13. You have to change a setting in your app.config file to fix this problem.

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

Now run the application again and click the print preview button. You should see the report this time.

Summary

This article demonstrated how to use the new WPF Crystal Report Viewer control in a WPF application using the Entity Framework 4.0. There are a couple of tricky issues that you need to work around but at the end of the day if you can integrate your reports into a WPF application I think it's worth the trouble. Good luck on your project and happy coding. 



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 9:36:27 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search