Wednesday, December 28, 2011

Generate a Report using Crystal Reports in Visual Studio 2010

Since a long time, Visual Basic and Visual Studio have Crystal report with it. People are saying that since 1993. But in VS2010, they excluded Crystal reports. Yes, what you just heard is right, Crystal Report has been dropped from Visual Studio 2010. But don't worry, it is available as a separate download from the SAP web site. These are the things that I found from the internet.
'It turns out that Crystal Reports for Visual Studio 2010 will be released separately, instead of included with the product and Most importantly, Crystal Reports for Visual Studio 2010 will continue to be free, with no registration required.'
Download Crystal report from this link, or just directly paste the link below to your address bar and it will ask to save an EXE file.

Introduction

I was searching the internet for Crystal reports in 2010 and I found in 2005, but was not able to find any particular tutorials for 2010. So I thought, let me take a chance to write it for some beginners like me who have not worked on Crystal Reports earlier.
In this article, I will show you simple report creation process with screenshots. A picture is worth more than a thousand words, so I always believe in an article with screenshots.
Let's start by creating a new website in VS2010. See the following screen:
rsz_1figure_1.jpg
Figure 1
As per figure 1, create a new website in VS2010 and name it as per your choice. Now let me show you the database table structure.
Figure_2.JPG
Figure 2
The above figure shows the db table structure. And the below figure (Figure 3) will show you some sample data in the table:
Figure_3.JPG
Figure 3
If you want to run this sample project directly, then you can download the database script from the link at the top.
Now we have to create an xsd file as a blank data source as we are going to use strong data type. Here I will divide this tutorial in 5 sub sections as mentioned below:
  • Simple report using Crystal Reporting Tool
  • Group report
  • Chart report
  • Sub report
  • Cross tab report

Simple Report using Crystal Report

The below figure shows you the process to create an XSD file.
For adding an XSD file, click on Solution Explorer -> Right Click on Project -> click on Add new Item and then it will show you the below screen.
Figure_4.JPG
Figure 4
Click on the ok button, so it will ask for confirmation to put that file in App_Code folder. Just click ok and that file will open in the screen as a blank screen.
Now we will add one blank datatable to that XSDfile. Just right click on the file and select Add -> Datatable. It will add one DataTable1 to the screen. Figure 5 shows how to add datatable to XSD file.
Figure_5.JPG
Figure 5
Now datatable1 is added to XSD file. Now we will add data column to the datatable1 as per figure 6. Remember whatever fields (columns) we add here, it will be available to show on the report. So add column which you want to display in your reports one by one here.
Figure_6.JPG
Figure 6
Remember to give the exact same name for data column as in database and also select data type which is the same as database, otherwise you will get an error for field and data type mismatch.
Once we add all the required columns in datatable, then set property for the datacolumn as it has in database. The below figure will show you how to set property for data columns. Default datatype for all the columns is string here so if datatype is other than string then only change it manually.
Just right click on the datacolumn in datatable and select property and from property window, select appropriate datatype from DataType Dropdown for that datacolumn.
Figure_7.JPG
Figure 7
That's it. XSD file creation has been done. Now we will move to create Crystal report design.
Just click on the Solution Explorer -> Right click on the project name and select crystal reports. Name it as per your choice and hit the add button.
Figure 8 will show you the creation process of Crystal reports.
Figure_8.JPG
Figure 8
Click on the add button and one .rpt file will be added to the solution. And also, it will ask for the report creation type of how you want to create the report. Figure 9 will show you a screenshot.
Figure_9.JPG
Figure 9
Just click ok button to proceed. It will lead you to figure 10:
Figure_10.JPG
Figure 10
Under project data, expand ADO.NET Datasets and select DataTable1 and add to the selected table portion located at the right side of the windows using > button.
Now click on the Finish button and it will show the next screen (Figure 11):
rsz_figure_11.jpg
Figure 11
Once report file is added, you can see Field Explorer on the left side near server explorer.
Expand Database Fields, under that you will be able to find Datatable that we have created earlier. Just expand it and drag one by one filed from Field Explorer to the rpt file under detail section.
Now the report design part is over. Now we have to fetch the data from database and bind it to dataset and then bind that dataset to the report viewer.
Let's go step by step.
First Drag a CrystalReportViewer control on aspx page from tool box as per below screen:
Figure_12.JPG
Figure 12
Now we will fetch the data, pass data to the dataset and then add that dataset to the Crystal Report. Below is the C# code which will do the job:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Below is the final code for reports:
protected void Page_Load(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
dsSample ds = new dsSample(); // .xsd file name
DataTable dt = new DataTable();
// Just set the name of data table
dt.TableName = "Crystal Report Example";
dt = getAllOrders(); //This function is located below this function
ds.Tables[0].Merge(dt);
// Your .rpt file path will be below
rptDoc.Load(Server.MapPath("../Reports/SimpleReports.rpt")); 
//set dataset to the report viewer.
rptDoc.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rptDoc;
}
public DataTable getAllOrders()
{
//Connection string replace 'databaseservername' with your db server name
string sqlCon = "User ID=sa;PWD=sa; server=databaseservername;
 INITIAL CATALOG=SampleDB;PERSISTSECURITY INFO=FALSE;Connect Timeout=0";
SqlConnection Con = new SqlConnection(sqlCon);
SqlCommand cmd = new SqlCommand();
DataSet ds = null;
SqlDataAdapter adapter;
try
{
Con.Open();
//Stored procedure calling. It is already in sample db.
cmd.CommandText = "getAllOrders";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = Con;
ds = new DataSet();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds, "Users");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
cmd.Dispose();
if (Con.State != ConnectionState.Closed)
Con.Close();
}
return ds.Tables[0];
}hrow new Exception(ex.Message);
}
finally
{
cmd.Dispose();
if (Con.State != ConnectionState.Closed)
Con.Close();
}
return ds.Tables[0];
} 
Now just save everything and run report. It will look like the below figure:
Figure_13.JPG
Figure 13

Grouping in Crystal Report

Here we will see only report design and rest of the things, you can refer from Section 1. Here we will groupCustomerProductOrder and Quantity. For details, just go through Figure 14.
Just add a report (.rpt) file to the solution. Select the appropriate dataset from popup window. Once it's done, then select grouping option like figure 14.
Figure_14.jpg
Figure 14
Now, right click on the report, select Report -> Group Experts and the resulting window will look like figure 15:
Figure_15.jpg
Figure 15
Now we want to group like Customer Name and Product name so first add Customer to the right Panel. Then move product name to the right panel like figure 16:
Figure_16.jpg
Figure 16
This time Crystal report design will be different than the previous time. See figure 17.
GroupHeaderSection1 and GroupHeaderSection2 are added to the report designer. Here Group #1 Name refers to Customer Name and Group #2 Name refers to Product Name.
And also GroupFooterSection1 and GroupFooterSection2 are added below if you want to add something to group footer.
Figure_17.jpg
Figure 17
Now under every group, we want to show the number of orders per customer and productwise, so for that, we have to add summary to the GroupFooterSection2. Refer to Figure 18.
Figure_18.jpg
Figure 18
Right Click on the GroupFooterSection select Insert -> Summary. It will show you the next screen (Figure 19). And I have also added Order_ID and Product_Qty field to the detail (section 3) part.
Figure_19.jpg
Figure 19
In summary window, select the column which you want to summarize in the first dropdown.
Select Sum (First option) from the calculate drop down.
Summary Location is already set to the report footer. So just click ok to place that summary field to the report.
By default, Summary field is added to the Report Footer section so move it to the groupFooterSection2 if you want to group product wise, move it to the GroupFooterSection1 if you want to group Customer wise or keep it at original place if you want to sum all ordered products. I have moved to the FooterSection1 so it will show Customer Wise Total Quantity. Refer to Figure 20.
Figure_20.jpg
Figure 20
Now save the report and run it finally. It looks like figure 21.
Figure_21.jpg
Figure 21

Chart in Crystal Report

Chart is the most important and visible part of the reporting tool. Crystal has very powerful feature to add chart in report. Let's see how to add chart in CR. Here also, we will see only designing of the chart for other thing. Please refer to Section 1.
Here we will show customer wise product ordered quantity in chart. X portion will display Customer name and Y portion will display customers total ordered quantity.
First add charts to the report design.
Right click on the .rpt file and select Insert->Chart. Refer to figure 22.
Figure_22.jpg
Figure 22
Once you add chart to the report, it will not show chart on the report file but with mouse pointer you can see one blank rectangle is moving. So just click on the Report header. It will open popup for chart style and other options. Refer to figure 23.
Figure_23.jpg
Figure 23
Now from type tab, select type of the charts like bar chart, line chart, pie chart, etc. form the left side. Select sub type from the right pane like side by side chartpercentage bar chart, etc. I am not going into the detail of it. I am leaving it for you to practice work.
And also select vertical or horizontal radio button from the below section if you want to change the chart style vertically or horizontally. Check Use depth effect check box if you need shadow effect on the graph. Refer to figure 23.
Figure_24.jpg
Figure 24
As per figure 24, move to the next tab data. There are three boxes, available fields, on change of and show values. So move Customer Name from available fields to on changes of box, and move Product Quantity filed to the show value box and click ok.
Now you can see chart is added to the report header section as per figure 25.
Figure_25.jpg
Figure 25
Now, just save the report and run it. You can see a Report as a chart on the screen.

Report Inside Report (Sub Report)

Crystal reports provide reports inside report feature which are normally known as a subreport feature.
Let me explain it in detail. Here also, we will design only sub report design. For rest of the things, refer to Section 1.
Add new report to the solution. Then add Report->Group and select only Customer name because we want to design report for each customer and sub report product wise. So there will be only one group header inside theCustomergroup header as per figure 26.
Figure_26.jpg
Figure 26
Now right click on Detail section and select Insert->Subreport. Refer to figure 27.
Figure_27.jpg
Figure 27
Once we add subreport, it will show screen like figure 28.
Figure_28.jpg
Figure 28
As per figure 28, by default, choose a Crystal Report in project is selected if you want to add report from the project, then otherwise select create a subreport with the report wizard. Once we select create a subreport with Report Wizard (3rd radio button), we have to click on the Report Wizard button to select report type and data source just do as Part - 1 first. Then click on ok button so like chart report it will show a moving rectangle around mouse, click on the detail section where you want to show subreport.
Now to edit the sub report, refer to figure 29.
Figure_29.jpg
Figure 29
Click on the edit subreport option and format the report as per your need. Here I will suggest add product name and product quantity or you can add chart also for sub report. When you click on the subreport button, it will open subreport designer, actually CR will create a separate .rpt file but it will remain hidden inside the main .rpt file so we can't see it..
Now run the report and you can see the result, report inside report like figure 30.
Figure_30.jpg
Figure 30
Here number 1 is the main report and number 2 is the subreport it's showing title as Product wise.

Cross Tab Report in Crystal Report

First, let me make it clear as to what is a Cross tab report. Normally, we generate report row wise like first we show customer name, then product wise, etc. But suppose we want to see report as column wise like product name should be displayed as column in report, then cross tab report comes into the picture. See result of Cross Tab report in figure 31.
Figure_31.jpg
Figure 31
Here also, I will show how to design cross tab report only, for rest of the things, refer to Section 1.
First add .rpt file to the solution. Then add cross report to the Report Header section as per the below figure (Refer to figure 32).
Remember we can add cross tab report only in Report header or report footer section.
Figure_32.jpg
Figure 32
Once we click on cross tab report options, it will show moving rectangle around mouse pointer just place it to the report header section.
As we click on header section, it will lead to the figure 33.
Figure_33.jpg
Figure 33
As per the figure, move Customer name field to the Rows section, Product name we want to show as a Column so move it to the Columns fields, and we want to show product total so move it to the summarized fields. That's it. Just run the report and you can see the output as shown in figure 31.
It's as simple as that. If you have any queries regarding any type of the above mentioned reports, please let me know by way of comments. I will try my level best to fulfill your request.
Let's enjoy reporting!
Article Source: DotNet Stuff  

Thursday, December 22, 2011

barcode 128c ใน formula field Crystal Report

Aeromium Barcode Fonts comes bundled with formulas to help you create barcodes in Crystal Reports easily. This tutorial is specially designed to get you started in generating barcodes in your reports.

Prerequisites


1. Ensure the appropriate Aeromium Barcode Fonts and Crystal Reports are installed.

Note - The trial version of Aeromium can also be used in this tutorial.

2. Launch Crystal Reports from the Windows Start Menu. Create a new report or use your existing report for the following steps.

Tutorial


1. In the Field Explorer, create a new formula by right clicking Formula Fields and select the New item in the context menu.



Note - If you cannot see the Field Explorer, click on the menu View->Field Explorer in Crystal Report.

2. Name your formula aerocode39

3. You will now see the Formula Workshop - Formula Editor. Change the syntax from "Crystal Syntax" to "Basic Syntax".


4. Copy and paste the formula for the barcode that you intend to use from the file AeromiumBarcodeFormulasForCrystalReport.txt to the Crystal Report's Formula Editor. The text file can be found in the CrystalReports subdirectory of Aeromium Barcode Fonts.

The table below shows the barcode and their corresponding formulas in the AeromiumBarcodeFormulasForCrystalReport.txt text file.

Barcode SymbologyFormulas
Code 128 A AeroCode128 A
Code 128 B AeroCode128 B
Code 128 C AeroCode128 C
Code 128 Auto AeroCode128 Auto
Code 39 AeroCode39
Code39 Extended AeroCode39 Extended
EAN13 AeroEAN13
EAN8 AeroEAN8
EXT2 AeroEXT2
EXT5 AeroEXT5
I2of5 AeroI2of5
Industrial 2of5 AeroIndustrial2of5
ITF14 AeroITF14
Modified Plessy AeroModifiedPlessy
POSTNET AeroPOSTNET
UCCEAN (GS1 128) AeroUCCEAN
UPCA AeroUPCA
UPCE AeroUPCE


5. Modify the 'data = "12345678' statement to encode the specific data or alternatively set it to a data source field.

6. Save the formula and drag it to your report to create a formula field.

7. Set the font of the formula field to the appropriate barcode font. For example, for Code 39, the font can be FontCode39H3.

Note - The font preview in the drop down list of Crystal Reports may appear as barcodes.


Back to Barcode Software and Fonts main page. 

ref: http://www.barcodefonts.net/crystal_reports_barcode_fonts.html

Export Crystal Reports to PDF file

Reports are used by business for various management purposes. Crystal reports is very versatile and easy to use reporting tool that is bundled with the Microsoft Visual Studio .Net. There have been many enhancements in the latest version of crystal reports which make it simpler for developers to export reports directly to the HTTP response object.

The export option is very useful when business users want to have reports exported different formats such as PDF, Excel, Word and HTML. They want this facility in order to download the report and store it for future use or to modify the report further (possible in case of Word and Excel). In many cases the export option is used for scheduled reports to be send via email, In this case, the exporting is done on the server side and the exported file is attached to an email and send to the user's email id.
In this tutorial, I will be showing you how to export a report to PDF format, but it can be easily modified to export the report in other formats.

Create a Crystal Report and display to the user

Create a New ASP.NET Web Site Project

I will be using an XML file as the data source for this tutorial. In normal scenarios a business layer class would return a dataset or datatable containing data to be displayed in the report. So I created an XML file with customer data and will be reading the contents into a Dataset.

Add XML file to the Project

Right-Click on App_Data folder and select Add Existing Item
Browse to the XML file and select it:

Add a crystal report to the project

Right-Click on the website root and select Add New Item.
Select "Crystal Report".
Enter the name of the report, I used the default name given by the IDE.
When the Crystal report wizard comes up select "Standard" and click OK.
Select a data source for the report.
Expand the Create New Connection node and then expand the ADO.net option.
Browse to the XML file and select the file.
The Customers table will appear in the list of data sources, add the table to selected table list by clicking on the right arrow.
Select all the columns that you need to display in the reports. I selected all of them for simplicity.
Setup grouping as needed to display the report.
Setup fields available for filtering.
Select the layout of report that you want.
The report is now created, you can now change the layout, add logos, etc.

Display the report on a web page

In the design view drag and drop the crystal reports viewer from Toolbox onto the web page.
Add a button which will handle the displaying of the report.
The HTML for body of the webpage should like as follows:
<body>
<formid="form2"runat="server">
<div>
<asp:ButtonID="btnShow"runat="server"OnClick="btnShow_Click"Text="Show Report in Viewer" /><br/>
<br/>
<CR:CrystalReportViewerID="CrystalReportViewer1"runat="server"AutoDataBind="true"/>
</div>
</form>
</body>
Remember to add following namespaces at the top of code behind page for referencing Crystal Report objects.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
The event handler should looks as follows:
protectedvoid btnShow_Click(object sender, EventArgs e)
{
// Get the report document and bind it with the crystal report viewer
CrystalReportViewer1.ReportSource = getReportDocument();
CrystalReportViewer1.DataBind();
}

// Returns a ReportDocument object with the report and data loaded
private ReportDocument getReportDocument()
{
// File Path for Crystal Report
string repFilePath = Server.MapPath("CrystalReport.rpt")
// Declare a new Crystal Report Document object
// and the report file into the report document
ReportDocument repDoc = new ReportDocument();
repDoc.Load(repFilePath);
// Set the datasource by getting the dataset from business
// layer and
// In our case business layer is getCustomerData function
repDoc.SetDataSource(getCustomerData());
}

// Business layer class to get the data from database
private DataSet getCustomerData()
{
string customerFilePath = Server.MapPath("App_Data\\Customers.xml");
DataSet ds =new DataSet();
ds.ReadXml(customerFilePath);
}
Run the Project to see if if works.

Export the Crystal Report in PDF format

Add a button to the web page so that user can click and get the PDF.

The HTML for web page should looks as follows:
<body>
<formid="form2"runat="server">
<div>
<asp:ButtonID="btnShow"runat="server"OnClick="btnShow_Click"Text="Show Report in Viewer" /><br/>
<br/>
<asp:ButtonID="btnExport"runat="server"OnClick="btnExport_Click"Text="Export To PDF"/>
<br/>
<br/>
<CR:CrystalReportViewerID="CrystalReportViewer1"runat="server"AutoDataBind="true"/>
</div>
</form>
</body>
The Code behind for export is as follows:
protectedvoid btnExport_Click(object sender, EventArgs e)
{
// Get the report document
ReportDocument repDoc = getReportDocument();
// Stop buffering the response
Response.Buffer =false;
// Clear the response content and headers
Response.ClearContent();
Response.ClearHeaders();
try
{
// Export the Report to Response stream in PDF format and file name Customers
repDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat,Response,true,"Customers");
// There are other format options available such as Word, Excel, CVS, and HTML in the ExportFormatType Enum given by crystal reports
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
ex =null;
}
}

Export to other formats

The report can be exported in different formats as follow:
PDFExportFormatType.PortableDocFormat
Complete Report to ExcelExportFormatType.Excel
Only Report Data to ExcelExportFormatType.ExcelRecord
HTMLExportFormatType.HTML40
RTFExportFormatType.RichText
WordExportFormatType.WordForWindows
Run the project to see does it working.
Once you click on the Export the PDF button the dialog box to download the pdf file will appear.
Now open the file and see if it is displayed properly.
By the end if this tutorial you should be able to

1) Create simple crystal reports
2) Display it to a web page using a crystal reports viewer
3) Allow users to download the reports in various formats such as PDF, Excel, Word and HTML.
You can download Sample Export Crystal Report To PDF Visual Studio Project, used in this tutorial.
Many people found that Crystal Reports are complicate to learn. Personally, I like Stimulsoft Reports for ASP.NET application. If you use SQL Server, nice solution is ApexSQL Report.
This tutorial is written by Chirag Nirmal - CANSoft.