How to use LINQ to SQL for binding data in CrystalReports 2008

clock September 10, 2008 01:54 by author Mohammad Mahdi Ramezanpour

Today I just decided to create some reports for one of our customers in Visual Studio 2008 and .NET Framework 3.5. Because I'm developing this application using LINQ, I wanted to use LINQ to SQL in CrystalReports. In this post I want to show you how you can use LINQ in order to bind data in CrystalReports.

Add CrystalReportViewer

At first, all sections are regular. You need to create a new application (I used Windows Application) and then add a Crystal Report Viewer to you specified form. When you add this control, you will see that Visual Studio added five new references to your application. These references are:

  • CrystalDecisions.CrystalReports.Engine
  • CrystalDecisions.Enterprise.Framework
  • CrystalDecisions.Enterprise.InfoStore
  • CrystalDecisions.ReportSource

You will need these libraries in order to let your application work with CrystalReports.

You made a place to show your reports in. Now you have to get started and create some reports. I want to add a new report by right clicking on my project, point to Add and then New Item. In the list of new items you need to point to Reporting section on the left side of "Add New Item" form and select Reporting. You items on templates side will be filtering to just 3 items:

  • Crystal Report
  • Report
  • Report Wizard

We want to work with CrystalReport here but for now I want to tell you other 2 items will work with Microsoft SQL Server Reporting Service that enables you to create flexible reports like CrystalReports but because CrystalReports is more common, most of developers prefer to use CrystalReports.

We just select Crystal Report and then select Add.

Because we want to work with LINQ classes, I need to create a LINQ to SQL class in order to add my tables to it and then use it in my CrystalReport file (For information about how you can create a LINQ to SQL class, Just check out my previous post: How to use SQL "IN" keyword in LINQ). Here is my tables structure:

LINQtoSQLClass

All I want is to show records from my Articles table. So I should implement this in my report. As you know when you're working with LINQ to SQL, tables become classes and fields become properties of those classes. When you want to add a new data source to your CrystalReport file (Data Fields section), there are some possibilities. You can use ADO.NET Datasets that enables you to use datasets you implemented in your application; and also you can use .NET Objects. It means that you can use classes in your application to be a data source for your report file. Because LINQ is based on classes, You must use .NET Objects in order to use LINQ to SQL as your Report's data source.

When you expand .NET Objects, you can see all classes in your application and also you can see the classes that made by LINQ class designer. Because I want to use my articles table I have to select Article class in the list as shown below:

Selecting Article Class

If you select this class as your data source you can see all fields available in the Articles table in database field section of our crystal report file. It means you can add each field you want to your report. So I just want to add Title field to my report (Details section):

Add Title To My Report

OK. That's all we need in our report file. Just one section left and that's let your report file know what data to show. You need to assign a database query to your file.

Let's go back to our report viewer file and go to code-behind section. In order to set your report file's properties, you have to create a new instance of your report file as following:

CrystalReport1 rpt = new CrystalReport1();

Now it's time to specify a query to your report file. A CrystalReport report file has a method named SetDataSource() that takes a datasource as the following types:

  • DataSet
  • DataTable
  • IDataReader
  • IEnumerable

LINQ to SQL, enables you to convert your data to a List<entityType>, Array and more. As you know List inherits IEnumerable, so All you need is to create a LINQ object and add a ToList() method to it and finally set the "SetDataSource()" method to our LINQ object as you can see in the code below:

ReportSampleDBDataContext db = 
    new ReportSampleDBDataContext();
var data = (from records in db.Articles 
            select records).ToList();
rpt.SetDataSource(data);


There is a property in our CrystalReportViewer control name ReportSource that enable you to specify which report file you want show in your CrystalReportViewer control. So you must set it up:

crystalReportViewer1.ReportSource = rpt;


It's working fine, isn't?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


How to create multi-language websites using ASP.NET

clock September 2, 2008 00:49 by author Mohammad Mahdi Ramezanpour

Using Resources can help you create flexible multi-language websites in ASP.NET. In this post I want to show you how you can do it.

As you know, ASP.NET has some specific folders like: App_Data, App_Code, ... . One of these folders is App_GlobalResources that holds resources. you can add this folder by right click on your website in Solution Explorer and from Add New ASP.NET Folder, select App_GlobalResources as following:

Add App_GlobalResources Folder

When you created this folder, then right click on App_GlobalResources folder and then select Add New item:

Add A Resource File to Global Resource Folder

As you can see, you can add a limited types of items to this folder. From the list, select Resource File and then select a name for your new file as always. I selected WebRes.resx as my file name. Resource files are XML based files that hold data in your application and will compile with your application. In order to create multi-language websites, you need to create a file for each language you want to implement in your website. So because I want to have Persian language too, I should create another resource file. The important section of creating another resource file is in it's name. You must follow some rules in your naming in order to let ASP.NET know which languages you have in your application. The rules are listed below:

  • You must start your resource file name with the name you specified to your first resource (In this post WebRes).
  • The only difference between your first file name and new language file name is in the last section of your file name. For example if you have a first resource file named WebRes.resx, and you want to add Persian language to your application, you must name your Persian language resource file WebRes.fa.resx (fa is short for Farsi and it's global); After that .NET Framework automatically understands that you have a Persian language resource file.

Now how to use resources in my application?

In order to use resources, you must make a use of embedded tags (<% %>) in your application. For example imagine that I have a label in my application and I want to use one of my resource keys in as the text property of my label. In order to do this, you must do something like this:

<asp:Label runat="server" ID="Label1" Text='<%$ Resources: WebRes, ResLabel %>'></asp:Label>

How it works?

The first part is Resources that tells ASP.NET that it's going to be a Global Resource.
WebRes is the name of our Resource file (Without any suffix). Note that you don't need to write any suffix in this section.
ResLabel is the name of our key we want to use in. I just added a key named ResLabel as shown below:

Added Resources

After you specified where want to show your resource , now you must let your application know which of those languages (In this sample, English (Unites States) and Persian) you want to use.

Your have two general options:

  1. Let your Web Browser decide.
  2. You enforce your application to use your specific language.

Let your Web Browser decide:

In order to set your application to get default language from your web browser, all you need is to set Culture and UICulture attributes to auto as shown below:

<%@ Page 
Culture="auto" 
UICulture="auto" 
Language="C#" 
AutoEventWireup="true"  
CodeFile="Default.aspx.cs"
Inherits="_Default" %>

Your Web Browser automatically fill your culture information from user's Operating System.

Enforce your application to use your specific language:

Now it's time to write some code. in order to enforce your application to use a specific language, you need to dynamically change the default Culture and UICulture of your application. ASP.NET holding culture information in the application main thread. So you have to change that as following:

    protected void ChangeLanguage()
    {
        string langName;
        //Language short name for English (United States).
        langName = "en-US";
        System.Threading.Thread.CurrentThread.CurrentCulture =
            System.Globalization.CultureInfo.GetCultureInfo(langName);
        System.Threading.Thread.CurrentThread.CurrentUICulture = 
            System.Globalization.CultureInfo.GetCultureInfo(langName);
        //Now the language is English (United States).
 
        //Language short name for Persian.
        langName = "fa-IR";
        System.Threading.Thread.CurrentThread.CurrentCulture =
            System.Globalization.CultureInfo.GetCultureInfo(langName);
        System.Threading.Thread.CurrentThread.CurrentUICulture =
            System.Globalization.CultureInfo.GetCultureInfo(langName);
        //Now the language is Persian.
    }

As you saw, .NET Framework will automatically understands which culture you want to use and then tells your application which resource file it must use.

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Cross-Page post backs using ASP.NET 3.5

clock August 30, 2008 02:06 by author Mohammad Mahdi Ramezanpour

Some developers are still want to use cross page post backs that we used it in the classic version of ASP. For example: you may want to create a page that contains a form and add them to your database in another page like ASP classic.

In this post I want to show how to do such a thing in ASP.NET and how you can make it easier in ASP.NET 3.5.

Imagine that I have a Default.aspx file that shows a form and users can enter their name and company name; and also I have another page named DataTransfer.aspx that shows user's information in some labels.

Here is my Default.aspx page:

<%@ Page Language="C#" 
AutoEventWireup="true" 
CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center;">
        Name:<br />
        <asp:TextBox runat="server" ID="nameTextBox"></asp:TextBox><br />
        Company name:<br />
        <asp:TextBox runat="server" ID="companyTextBox"></asp:TextBox><br />
        <asp:Button runat="server" ID="submitButton"
         Text="Save" 
         PostBackUrl="DataTransfer.aspx" />
    </div>
    </form>
</body>
</html>

As you can see, I have two textboxes named "nameTextBox", "companyTextBox" and also a button named "submitButton" that are normal and there is nothing unusual in it. The interesting part in the PostBackUrl of my button that links this page to our second page.

There is nothing to do more in the first page, so lets take a look at our second page "DataTransfer.aspx":

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataTransfer.aspx.cs" Inherits="DataTransfer" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>User's information</h3>
    <div>
        Name : 
        <asp:Label runat="server" ID="nameLabel"></asp:Label><br />
        Company : 
        <asp:Label runat="server" ID="companyLabel"></asp:Label>
    </div>
    </form>
</body>
</html>

Very simple, just two labels in order to show the user's information. I have to write some code in the code-behind section in order to bind information to labels. Here is my code-behind of my DataTransfer.aspx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class DataTransfer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create an instance of our previous page's controls that we want to get.
        TextBox name = null;
        TextBox company = null;
        
        // Fill variables with the values in the previous page using FindControl method of Previous Page property.
        name = (TextBox)this.PreviousPage.FindControl("nameTextBox");
        company = (TextBox)this.PreviousPage.FindControl("companyTextBox");
 
        // Bind lables using values in textboxes.
        nameLabel.Text = name.Text;
        companyLabel.Text = company.Text;
    }
}

In the code above I used PreviousePage property available in every ASP.NET page and FindControl method of that property. With FindControl you can get the object you want by it's ID from your previous page. But because the information returns from FindControl are objects and no specific types, you must cast it as I did.

If you launch your application now, you will see you can gather the information from first page and show them in the second page.

Now let's change it a little bit by add a new directive to our second page. This directive name PreviousPageType and it's new with ASP.NET 3.5 and let you specify your previous page path. So you can have all public or internal (Friend in VB) classes, methods, properties or any other objects in your second page. This is my second page after a little changes:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataTransfer.aspx.cs" Inherits="DataTransfer" %>
<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
...

You know, because I'm always trying to be organized :D, I want to create two properties in my first page that holds values in textboxes:

    public string Name
    {
        get { return nameTextBox.Text; }
    }
 
    public string CompanyName
    {
        get { return companyTextBox.Text; }
    }

Now you can get values of textboxes in Default.aspx page much easier. It means that Visual Studio can identify our first page objects and you can use code hints in order to access your objects in the second page as shown in the picture below:

ASPNET35 Previous Page Inteligency

And our second page's code-behind will change to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class DataTransfer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill variables with the values in the previous page using properties.
        nameLabel.Text = PreviousPage.Name;
        companyLabel.Text = PreviousPage.CompanyName;
    }
}

Now you know that with the PreviousPageType new directive in ASP.NET 3.5, it's much easier to access you object in a page from another page.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Four hours free ASP.NET 3.5 training

clock August 28, 2008 01:00 by author Mohammad Mahdi Ramezanpour

ASP_net_logo

This is a special news to some of you who want to start developing ASP.NET. APPDEV, released 4 hours of free ASP.NET training and it's now available for download.

The best part is that these courses are available in both VB.NET and C#. So it doesn't matter which programming language you're using.

Download training courses by click the following link:

http://www.appdev.com/promo.asp?page=SN00040

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Validation of ViewState MAC failed error has been solved

clock August 14, 2008 21:29 by author Mohammad Mahdi Ramezanpour

VS2008

You may got this exception before: Validation of ViewState MAC failed

You will get this exception when you click on a LinkButton or such a thing on a page when your page load has not completed yet.

In ASP.NET 1.1, 2, 3 and 3.5, you can solve this issue by set some attributes in your web.Config file:

<pages enableeventvalidation="false" viewstateencryptionmode="Never">

It' will work fine and will not get Validation of ViewState MAC failed exception, but it has some security issues; So what should we do?

Microsoft solved this problem in .NET Framework 3.5 SP1, so that you'll never need to add something like attributes above.

Now I think it's better to get started and use SP1 of Microsoft .NET Framework and Visual Studio.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Welcome


Mohammad Mahdi Ramezanpour
Welcome to my website. Hope you can get something useful here. For more information about me and ways you can contact, please use site menu.

Main Menu

Sign in