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


LINQ to SQL: How to execute command in a transaction

clock August 23, 2008 22:28 by author Mohammad Mahdi Ramezanpour

It may happen to everyone; sometimes you may want to execute your LINQ to SQL commands in one transaction like you do it in SQL Server as following:

 

BEGIN TRANSACTION
 
IF ([something happend])
begin
    -- Your code is here
end
ELSE
begin
    -- Restore to original
    ROLLBACK TRANSACTON
end
 
COMMIT TRANSACTION

In this post I want to show how you can do it using LINQ to SQL:

Create your LINQ to SQL project and write some code in order to do something ex.: Add a new record to a database. You should pass the following steps in order to manage transactions in LINQ to SQL:

First, You must add a new reference named System.Transactions to your project:

SelectingSytem_Transactions_Reference

Then, you must create a new variable from System.Transactions.TransactionScope like this:

 

using (TransactionScope ts = new TransactionScope())
{
     // Your code comes here.
}

After that you must add your insert code between using tags:

using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    Post p = new Post();
                    p.title = title;
                    p.keywords = keywords;
                    p.shortDesc = shortDesc;
                    p.content = content;
                    p.startRate = Convert.ToByte(startRate);
                    p.enableComments = enableComments;
                    p.usersCanRate = usersCanRate;
                    p.createDate = DateTime.Now;
                    p.lastModifyDate = DateTime.Now;
                    c.Posts.InsertOnSubmit(p);
                    c.SubmitChanges();
                    
                    Guid postId = p.postId;
 
                    foreach (var author in authors)
                    {
                        Posts_AddAuthorRelation(postId, author.AuthorID);
                    }
 
                    foreach (var category in categories)
                    {
                        Posts_AddCategoryRelation(postId, category.CategoryID);
                    }
 
                    foreach (var source in sources)
                    {
                        Posts_AddSourceRelation(postId, source.SourceID);
                    }
 
                    foreach (var media in medias)
                    {
                        Posts_AddMediaRelation(postId, media.MediaID);
                    }
                }
                catch
                {
                    Transaction.Current.Rollback();
                }
            }

As you can see I put a try...catch statements to my code. In try section I just wrote my insert code. If there is any error with my database or something. It will goes to my catch block.
Because I insert to more than one table, I should delete all inserted tables if there is any exception(s).

So you must use System.Transactions.Transaction.Rollback() method in order roll it back like SQL Server's ROLLBACK TRANSACTION command that we talked about it above.

With System.Transactions, you can manage your LINQ to SQL commands in transactions.

Be the first to rate this post

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


The power of XLINQ in Visual Basic 2008

clock August 14, 2008 01:19 by author Mohammad Mahdi Ramezanpour

Using LINQ to XML (XLINQ) will help you to access your XML data very easier, like never before. But I don't know why, using XLINQ in Visual Basic is more interesting than C# for me.

In this post I want to show you how easy can be for VB to generate an XML file than C#.

Assume that we want to generate an XML file like following:

<?xml version="1.0" encoding="utf-8" ?>
<configs>
    <config name="Mohammad Mahdi Ramezanpour"></config>
</configs>

 

In order to generate such a thing in C#, you will need to write something like this:

XDocument xdoc = new XDocument();
XElement xroot = new XElement("configs");
XElement xitem = new XElement("config", 
                 new XAttribute("Name", "Mohammad Mahdi Ramezanpour"));
xroot.Add(xitem);
xdoc.Add(xroot);
xdoc.Save("C:\\sample.xml");

As you can see, I just created a new XDocument and then add some XElements to it. All things are very routine and then I saved the data into an XML file "C:\sample.xml".

Now, lets check such the code above in Visual Basic:

Dim xdoc As New XDocument
Dim xroot As XElement = <configs></configs>
Dim xitem As XElement = <config name="Mohammad Mahdi Ramezanpour"></config>
xroot.Add(xitem)
xdoc.Add(xroot)
xdoc.Save("C:\sample.xml")

in the code above I created an XML file exactly like our previous exmple and the result will be equal.

Lets take a look at this code snippet; In Visual Basic when you declare a variable as XElement, you can write your XML content exactly like the syntax you're using in an XML file. It means that you can use XML tags (<configs></configs>) straight in your code.

As I said in my previous posts, I like VB more than C# and I thing VB is much powerful than C# at least in this part :).

Be the first to rate this post

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


Microsoft SQL Server 2008 Is now available for download

clock August 12, 2008 18:37 by author Mohammad Mahdi Ramezanpour

I was waiting a lot for this realase of SQL Server and finally it has been released today. Lets take a look at product overview published from Microsoft official website:

Your Data, Any Place, Any Time

SQL Server 2008 delivers on Microsoft’s Data Platform vision by helping your organization manage any data, any place, any time. It enables you to store data from structured, semi-structured, and unstructured documents, such as images and music, directly within the database. SQL Server 2008 delivers a rich set of integrated services that enable you to do more with your data such as query, search, synchronize, report, and analyze. Your data can be stored and accessed in your largest servers within the data center all the way down to desktops and mobile devices, enabling you to have control over your data no matter where it is stored.

SQL Server 2008 enables you to consume your data within custom applications developed using Microsoft .NET and Visual Studio and within your service-oriented architecture (SOA) and business process through Microsoft BizTalk Server while information workers can access data directly in the tools they use every day, such as the 2007 Microsoft Office system. SQL Server 2008 delivers a trusted, productive, and intelligent data platform for all your data needs.

SQL Server 2008 New Features

TRUSTED

SQL Server provides the highest levels of security, reliability, and scalability for your business-critical applications.

  • Transparent Data Encryption

    Enable encryption of an entire database, data files, or log files, without the need for application changes. Benefits of this include: Search encrypted data using both range and fuzzy searches, search secure data from unauthorized users, and data encryption without any required changes in existing applications.

  • Extensible Key Management

    SQL Server 2005 provides a comprehensive solution for encryption and key management. SQL Server 2008 delivers an excellent solution to this growing need by supporting third-party key management and HSM products.

  • Auditing

    Create and manage auditing via DDL, while simplifying compliance by providing more comprehensive data auditing. This enables organizations to answer common questions, such as, "What data was retrieved?"

  • Enhanced Database Mirroring

    SQL Server 2008 builds on SQL Server 2005 by providing a more reliable platform that has enhanced database mirroring, including automatic page repair, improved performance, and enhanced supportability.

  • Automatic Recovery of Data Pages

    SQL Server 2008 enables the principal and mirror machines to transparently recover from 823/824 types of data page errors by requesting a fresh copy of the suspect page from the mirroring partner transparently to end users and applications.

  • Log Stream Compression

    Database mirroring requires data transmissions between the participants of the mirroring implementations. With SQL Server 2008, compression of the outgoing log stream between the participants delivers optimal performance and minimizes the network bandwidth used by database mirroring.

  • Resource Governor

    Provide a consistent and predictable response to end users with the introduction of Resource Governor, allowing organizations to define resource limits and priorities for different workloads, which enable concurrent workloads to provide consistent performance to their end users.

  • Predictable Query Performance

    Enable greater query performance stability and predictability by providing functionality to lock down query plans, enabling organizations to promote stable query plans across hardware server replacements, server upgrades, and production deployments.

  • Data Compression

    Enable data to be stored more effectively, and reduce the storage requirements for your data. Data compression also provides significant performance improvements for large I/O bound workloads, like data warehousing.

  • Hot Add CPU

    Dynamically scale a database on demand by allowing CPU resources to be added to SQL Server 2008 on supported hardware platforms without forcing any downtime on applications. Note that SQL Server already supports the ability to add memory resources online.

    PRODUCTIVE

    To take advantage of new opportunities in today's fast-moving business world, companies need the ability to create and deploy data-driven solutions quickly. SQL Server 2008 reduces time and cost of management and development of applications.

  • Policy-Based Management

    Policy-Based Management is a policy-based system for managing one or more instances of SQL Server 2008. Use this with SQL Server Management Studio to create policies that manage entities on the server, such as the instance of SQL Server, databases, and other SQL Server objects.

  • Streamlined Installation

    SQL Server 2008 introduces significant improvements to the service life cycle for SQL Server through the re-engineering of the installation, setup, and configuration architecture. These improvements separate the installation of the physical bits on the hardware from the configuration of the SQL Server software, enabling organizations and software partners to provide recommended installation configurations.

  • Performance Data Collection

    Performance tuning and troubleshooting are time-consuming tasks for the administrator. To provide actionable performance insights to administrators, SQL Server 2008 includes more extensive performance data collection, a new centralized data repository for storing performance data, and new tools for reporting and monitoring.

  • DATE/TIME

    SQL Server 2008 introduces new date and time data types:

    • DATE—A date-only type

    • TIME—A time-only type

    • DATETIMEOFFSET—A time-zone-aware datetime type

    • DATETIME2—A datetime type with larger fractional seconds and year range than the existing DATETIME type

    The new data types enable applications to have separate data and time types while providing large data ranges or user defined precision for time values.

  • HIERARCHY ID

    Enable database applications to model tree structures in a more efficient way than currently possible. New system type HierarchyId can store values that represent nodes in a hierarchy tree. This new type will be implemented as a CLR UDT, and will expose several efficient and useful built-in methods for creating and operating on hierarchy nodes with a flexible programming model.

  • FILESTREAM Data

    Allow large binary data to be stored directly in an NTFS file system, while preserving an integral part of the database and maintaining transactional consistency. Enable the scale-out of large binary data traditionally managed by the database to be stored outside the database on more cost-effective storage without compromise.

  • Integrated Full Text Search

    Integrated Full Text Search makes the transition between Text Search and relational data seamless, while enabling users to use the Text Indexes to perform high-speed text searches on large text columns.

  • Sparse Columns

    NULL data consumes no physical space, providing a highly efficient way of managing empty data in a database. For example, Sparse Columns allows object models that typically have numerous null values to be stored in a SQL Server 2005 database without experiencing large space costs.

  • Large User-Defined Types

    SQL Server 2008 eliminates the 8-KB limit for User-Defined Types (UDTs), allowing users to dramatically expand the size of their UDTs.

  • Spatial Data Types

    Build spatial capabilities into your applications by using the support for spatial data.

    • Implement Round Earth solutions with the geography data type. Use latitude and longitude coordinates to define areas on the Earth's surface.

    • Implement Flat Earth solutions with the geometry data type. Store polygons, points, and lines that are associated with projected planar surfaces and naturally planar data, such as interior spaces.

  • INTELLIGENT

    SQL Server 2008 provides a comprehensive platform, delivering intelligence where your users want it.

  • Backup Compression

    Keeping disk-based backups online is expensive and time-consuming. With SQL Server 2008 backup compression, less storage is required to keep backups online, and backups run significantly faster since less disk I/O is required.

  • Partitioned Table Parallelism

    Partitions enable organizations to manage large growing tables more effectively by transparently breaking them into manageable blocks of data. SQL Server 2008 builds on the advances of partitioning in SQL Server 2005 by improving the performance on large partitioned tables.

  • Star Join Query Optimizations

    SQL Server 2008 provides improved query performance for common data warehouse scenarios. Star Join Query optimizations reduce query response time by recognizing data warehouse join patterns.

  • Grouping Sets

    Grouping Sets is an extension to the GROUP BY clause that lets users define multiple groupings in the same query. Grouping Sets produces a single result set that is equivalent to a UNION ALL of differently grouped rows, making aggregation querying and reporting easier and faster.

  • Change Data Capture

    With Change Data Capture, changes are captured and placed in change tables. It captures complete content of changes, maintains cross-table consistency, and even works across schema changes. This enables organizations to integrate the latest information into the data warehouse.

  • MERGE SQL Statement

    With the introduction of the MERGE SQL Statement, developers can more effectively handle common data warehousing scenarios, like checking whether a row exists, and then executing an insert or update.

  • SQL Server Integration Services (SSIS) Pipeline Improvements

    Data Integration packages can now scale more effectively, making use of available resources and managing the largest enterprise-scale workloads. The new design improves the scalability of runtime into multiple processors.

  • SQL Server Integration Services (SSIS) Persistent Lookups

    The need to perform lookups is one of the most common ETL operations. This is especially prevalent in data warehousing, where fact records need to use lookups to transform business keys to their corresponding surrogates. SSIS increases the performance of lookups to support the largest tables.

  • Analysis Scale and Performance

    SQL Server 2008 drives broader analysis with enhanced analytical capabilities and with more complex computations and aggregations. New cube design tools help users streamline the development of the analysis infrastructure enabling them to build solutions for optimized performance.

  • Block Computations

    Block Computations provides a significant improvement in processing performance enabling users to increase the depth of their hierarchies and complexity of the computations.

  • Writeback

    New MOLAP enabled writeback capabilities in SQL Server 2008 Analysis Services removes the need to query ROLAP partitions. This provides users with enhanced writeback scenarios from within analytical applications without sacrificing the traditional OLAP performance.

  • Enterprise Reporting Engine

    Reports can easily be delivered throughout the organization, both internally and externally, with simplified deployment and configuration. This enables users to easily create and share reports of any size and complexity.

  • Internet Report Deployment

    Customers and suppliers can effortlessly be reached by deploying reports over the Internet.

  • Manage Reporting Infrastructure

    Increase supportability and the ability to control server behavior with memory management, infrastructure consolidation, and easier configuration through a centralized store and API for all configuration settings.

  • Report Builder Enhancements

    Easily build ad-hoc and author reports with any structure through Report Designer.

  • Built-In Forms Authentication

    Built-in forms authentication enables users to easily switch between Windows and Forms.

  • Report Server Application Embedding

    Report Server application embedding enables the URLs in reports and subscriptions to point back to front-end applications.

  • Microsoft Office Integration

    SQL Server 2008 provides new Word rendering that enables users to consume reports directly from within Microsoft Office Word. In addition, the existing Excel renderer has been greatly enhanced to accommodate the support of features, like nested data regions, sub-reports, as well as merged cell improvements. This lets users maintain layout fidelity and improves the overall consumption of reports from Microsoft Office applications.

  • Predictive Analysis

    SQL Server Analysis Services continues to deliver advanced data mining technologies. Better Time Series support extends forecasting capabilities. Enhanced Mining Structures deliver more flexibility to perform focused analysis through filtering as well as to deliver complete information in reports beyond the scope of the mining model. New cross-validation enables confirmation of both accuracy and stability for results that you can trust. Furthermore, the new features delivered with SQL Server 2008 Data Mining Add-ins for Office 2007 empower every user in the organization with even more actionable insight at the desktop.

  •  For more information about this release and download it, you can check out Microsoft SQL Server 2008 Home Page

     By the way I have to thanks a lot from Microsoft for releasing this version of SQL Server.

    Be the first to rate this post

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


    LINQ to SQL : How to work with Take keyword

    clock August 5, 2008 00:53 by author Mohammad Mahdi Ramezanpour

    As you know, we have a keyword in SQL name TOP that we can use in order to take a limit count of rows in a select statement. Now if you want to use such a thing in LINQ to SQL, you have to use the Take keyword.

    Here is an example of using Take keyword:

        var first4Customers = (
                    from c in customers

                    select new {c.CustomerID, c.CustomerName} )
                    .Take(4);

    In this example the result will return first 4 records of our Customer table. The equivalent of this code is SQL is something like this:

    SELECT TOP(4) CustomerID, CustomerName FROM Customers

    When you're using Take keyword the type of result we be equal to a simple select statement. This will return an object from IQueryable(Of T), So that you can use the result like a simple select statement. For example, if you want to return you result set as a List(Of T), you can use the following code:

        var first4Customers = (
                    from c in customers

                    select new {c.CustomerID, c.CustomerName} )
                    .Take(4).ToList();

    Note that is doesn't have any difference between this and a simple select statement.

    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