CLR Stored Procedure in Linq based n-tier architecture

September 8th, 2009 by virat.kothari § 1

Table of contents

  1. Introduction
  2. Define Tiers for the Application
  3. Role of Tiers
  4. Implementing CLR Stored Procedure in LINQ based n-tier Architecture Step by Step
  5. Steps to Create Architecture
  6. Using the code
  7. Conclusion
  8. Points of Interest
  9. History

Introduction

This article is a sequence of my previous article about “CLR Stored Procedure & creating it step by step”. In my previous article I have explained CLR Stored Procedure, benefits & drawbacks of it and also how to implement it. CLR Stored Procedure is very powerful and gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management, etc. Development of any project in n-tier architecture is different taste and having its own benefits and drawbacks. Microsoft has launched LINQ i.e. Language Integrated Query with .net framework 3.0. LINQ can be implemented in variety of ways for e.g. LINQ with SQL, LINQ with objects, LINQ with dataset and LINQ with xml etc. I have implemented simple n-tier architecture few years back in my company. It is suitable for both web as well as desktop applications. It is a centralized n-tier architecture i.e. all the objects are resides at the same place in the target system. I don’t claim this as best but I have implemented this architecture as I want at least following benefits out of it.

  1. It must be secure, easy to implement and easy to deploy
  2. It must be tiered based and at least 3 tiered so that if we change code of any tier, we need to deploy dll of that tier only.
  3. Single architecture for web and desktop application with standard application performance
  4. Parallel development should be possible i.e. one developer can work with database, another can work with business logic and one more can work with user interface and so on
  5. No in-line SQL queries
  6. It must not be complex so that new developer can easily set on development without undergoing long training and existing developers can be easily migrated to and from any of the projects as basic development architecture of all the projects will remain same

Define Tiers for the Application

Now, let me explain various tiers of the architecture. Any good architecture will consist at least 3 important tiers viz. 1) User Interface or Presentation Layer 2) Business Logic Layer 3) Data Layer. The architecture which I am going to explain have 5 tiers. Any architecture having more than 3 tiers is called n-tier architecture. Following image will clarify it.

Architecture

Following is the image showing architecture in our application. It contains following 4 tiers (see image) and 1 database so total 5 tiers.

SolutionExplorer

Role of Tiers

Let me explain each of above tier in brief.

  1. Tier – 1: Presentation Layer: This layer will be responsible for various activities between Users and application. All the user interface related logic will reside at this layer. That means web forms or Win forms will reside here. This layer does not have direct access to the database or Data Access Layer. So, all the data goes in or comes out to Presentation Layer will be through the Business Logic Layer only. A reference of Business Logic Layer will be added to this layer. A separate project will be there for this layer.
  2. Tier – 2: Business Logic Layer: Business Logic Layer will perform all the Business Logics of the application. Business logic consists of two things viz., Core business logic and Data access logic. Data access logic is been segregated to different layer to provide more security and data encapsulation to the application. There will be a separate class for each table of the database to provide better management, in this layer. This class will have various methods. Business logic will be applied to data coming from or going to Presentation Layer and Data Access Layer. A reference of Data Access Layer will be added to this layer. A separate project will be there for this layer.
  3. Tier – 3: Data Access Layer: This layer is a part of Business logic but is separated from core business logic. All the data related operations between application and database will be performed over here. This layer will be created using “LINQ”. One LINQ to SQL class will be created over here and all the needed database tables or Stored Procedures will be dragged and dropped over here. This layer will have minimum manual coding. A separate project will be there for this layer.
  4. Tier – 4: CLR Stored Procedure Layer: This layer will be responsible for defining various CLR Stored Procedures. There will be a separate class for each table of the database to provide better management, in this layer. This layer is not directly associated with Presentation Layer, Business Logic Layer or Data Access Layer. CLR Stored Procedure will be deployed to SQL server. A separate project will be there for this layer. To know, what is CLR Stored Procedure and how to create it refer my article “CLR Stored Procedure and Creating It Step by Step”.
  5. Tier – 5: Database: This is core data and other objects to maintain and access it. For e.g. SQL server database. Core data is data in various tables and objects to maintain & access such data are various tables, Stored Procedures, CLR Stored Procedures, Views and Functions etc.

Physically there are 5 layers but logically they are 4 layers as assembly of CLR Stored Procedure will be the part of Database at the time of deployment.

To add reference of one project to another project is very simple. Just right click on the project >> Click on Add Reference. A dialog box will be displayed. Select “Projects” tab and select appropriate project in the list of projects. Click “OK” button. We can not add circular reference within project for e.g. In our case, Presentation Layer refers to Bussiness Layer and Business Layer refers to Data Access Layer. Now, we can not add reference of Presentation Layer to Data Access Layer as it will create circular reference.

Implementing CLR Stored Procedure in LINQ based n-tier Architecture Step by Step

Let us implement CLR Stored Procedure in LINQ based n-tier architecture. I have listed all SQL statements used for creating database, creating table, inserting dummy records in the table, etc. in the script attached with this article.

Application Development Specification

  • IDE: Visual Studio 2008
  • Framework: 3.5 with SP 1
  • Language: C# 3.0
  • Database: Microsoft SQL Server 2005 Express edition
  • Operating system: Windows XP with SP 2

Steps to Create Architecture

1. Open Microsoft Visual Studio 2008 >> Create New Project. A dialog box will be opened. Select, Visual C# >> Windows on left side “Project Types” panel. Select, “Windows Forms Application” on right side “Templates” panel. Give proper name to project, solution and select location to save this solution. This project will be our presentation layer. Following image will make it clear.

1

A default form with the name “Form1” will be created with the project. Rename it to “Demo”. Design it as shown in following image. There is a Label control for heading, one Data Grid View control, a Group Box control to hold various buttons viz., Get Data, Insert Random Record, Delete Selected Record, Clear Grid and Exit. Following image will make it clear.

BlankDemoForm

2.    Right click on Solution, click on Add >> New Project. A dialog box will be opened. Select, Database Projects >> Microsoft SQL Server >> SQL CLR on left side “Project Types” panel. Select, “SQL Server Project” on right side “Templates” panel. Give proper name to project and select location to save this solution. This project will be our CLR Stored Procedure Layer. Follow the steps I have explained in my article “CLR Stored Procedure and Creating It Step by Step” to add CLR Stored Procedure in this project. Following image will make it clear.

SQLServerProject

Right click on the project >> Select Add >> Add New Items. A dialog box will be displayed as shown in following image. Select Visual C# Items from left “Categories” panel. Select Stored Procedure from right side “Templates” panel. Give proper name to it.

AddClrSP

3.    Right click on Solution, click on Add >> New Project. A dialog box will be opened. Select, Visual C# >> Windows on left side “Project Types” panel. Select, “Class Library” on right side “Templates” panel. Give proper name to project and select location to save this solution. This project will be our Business Logic Layer. I have added two classes to this project i.e. 1) “ConvertToDataTable” and 2) “CustomerSalesInformation”. “ConvertToDataTable” class has various methods to convert array of objects to DataTable or DataSet. CustomerSalesInformation class consist various methods to Insert a record, Delete a record and Get records from database. Following image will make it clear.

BusinessLayer

4.    Once again, Right click on Solution, click on Add >> New Project. A dialog box will be opened. Select, Visual C# >> Windows on left side “Project Types” panel. Select, “Class Library” on right side “Templates” panel (same as step 3). Give proper name to project and select location to save this solution. This project will be our Data Access Layer.

5.    Right click on “DataAccessLayer” project, Select Add >> New Item option from the menu. A dialog box shown in following image will be displayed. Select on Visual C# Items in left side “Categories” panel and “Linq to SQL Classes” in right panel “Templates”.

LinqToSqlDal

6.    Open Server explorer and click on “Connect to database” button given at
top-middle of the server explorer window. It will start a new wizard to
connect to the database. Now drag and drop Stored Procedures
“CustomerSalesInformationDelete” and
“CustomerSalesInformationInsertRandomRecord”. Do NOT drag and drop
“CustomerSalesInformationGet” right now as we need to change it. I have
added “AccessData” class to add various useful methods and variables to
be used on Business Logic Layer. Write now I have declared one private
object of “LinqToSqlDataContext” and exposed it using property “Call”.
Following images will make it clear. Change the connection string I
have statically wrote while declaring object of “LinqToSqlDataContext”.

Dbml

7.    I have suggested not to drag and drop “CustomerSalesInformationGet” because it is a Stored Procedure which does not contain any SELECT query. That is why if you drag and drop it in .dbml file, the return type of the method of the said Stored Procedure will be “int” instead of ISingleResult and so it will not produce any result which we are expecting from this Stored Procedure. You can see this in .cs file of dbml. The work around I am going to explain is not the standard way but it works fine. Let me know if you find any better option. Following are the steps of the work around.

Step 1: Go to query analyzer and drop the Stored Procedure “CustomerSalesInformationGet” which was automatically created at the time of deploying CLR stored procedure, using following SQL statement.

DROP PROCEDURE [dbo].[CustomerSalesInformationGet]

Step 2: Create new stored procedure with the same name as stored procedure created at the time of deploying CLR stored procedure, using following SQL statements.

CREATE PROCEDURE [dbo].[CustomerSalesInformationGet]
AS
BEGIN
	SELECT * from CustomerSalesInformation
END

Step 3: Now come to the Visual Studio and refresh the “Stored Procedure” element of the tree view. You can simply right click on the element and click on “Refresh” option of the menu or cliking on refresh icon at the top-left of Server Explorer. Now drag and drop “CustomerSalesInformationGet” stored procedure to the .dbml file. This will create a method for the said stored procedure with the return type “ISingleResult”. You can verify this in .cs file of dbml. So this will return the result per our expectation.

Step 4: Once again go to query analyzer and drop the manually created stored procedure “CustomerSalesInformationGet” using following SQL statement.

DROP PROCEDURE [dbo].[CustomerSalesInformationGet]

Step 5: Now come to the Visual Studio and Right click on “ClrStoredProcedureLayer” project and click on “Deploy” option of the menu. This will deploy CLR stored procedure to the database once again. Now do NOT drag and drop this stored procedure to the dbml file otherwise we have to repeat this whole work around.

8.    You have to change connection at two places while using my sample source code.

1.    In the “AccessData.cs” file where we have declared an object of “LinqToSqlDataContext”. Following will clarify this.

private static LinqToSqlDALDataContext objLinqToSqlDALDataContext = _
new LinqToSqlDALDataContext("Data Source=OM\\SQLEXPRESS;Initial Catalog=DbForClrDemo;User ID=sa;Password=airborne");

2.    In the “CLRStoredProcedureLayer” project. Right click on the said project in solution explorer and click on “Properties”. A screen like following image will be displayed. Select “Database” tab and change the connection string at “Connection String” option where a textbox and Browse button is given.

ChangeConnectionInClrProject

9.    Save the whole solution. Right click on the solution in solution explorer and click on “Build” option. Now, you can run the application by hitting F5. A dialog box will be opened as shown in following image. Click on “Get Data” button, it will retrieves records from the database and loads in to the grid. “Insert Random Record” will insert random record in the table and once again retrieves records from the database and loads in to the grid. “Delete Selected Record” deletes the selected record. “Clear Grid” button clears the records from the grid. “Exit” button will close and exit the application. Following is the demo of the same.

DemoFormWithData

Using the Code

  1. Download the zip files for source code and sql script  and extract them
  2. Create Database and tables using “Script to create Database and Table.sql”. Also, insert records in the table using same file
  3. Change connections at 2 places in application as explained in Step 8
  4. Run the demo.
  5. When you hit “Get Data” button for the first time, it will take little time to fetch data from database. Now, hit “Clear Grid” button and hit “Get Data” button once again, you will realize the speed. Also, try to hit “Insert Random Record” button continuously for many time. It inserts record to the database and fills the grid at every hit, but still see the speed of it.
  6. This will give little slow performance in web application than windows application.

Conclusion

Clr Stored Procedures can be efficiently implemented in n-tier architecture

Suggestion

Refer my another article “CLR Stored Procedure and Creating It Step by Step

Points of Interest

  1. Exploring IMultipleResult in LINQ.

History

  1. 08th September, 2009: Initial release

using System;
using System.Windows.Forms;
using BusinessLayer;

namespace ClrInNTierPresentationLayer
{
/// <summary>
/// Represents demo form for the application
/// </summary>
public partial class frmDemo : Form
{
#region Constructor

/// <summary>
/// Constructor of the application
/// </summary>
public frmDemo()
{
InitializeComponent();
}

#endregion

#region Event Handler

#region Buttons

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnGetData_Click(object sender, EventArgs e)
{
try
{
FillDataGridView();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnInsertRandomRecord_Click(object sender, EventArgs e)
{
try
{
CustomerSalesInformation.CustomerSalesInformationInsertRandomRecord();
FillDataGridView();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Deletes selected record from the database
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnDeleteSelectedRecord_Click(object sender, EventArgs e)
{
try
{
if (dgvData.Rows.Count > 0)
{
if (MessageBox.Show(“Are you sure to delete selected record?”, “Confirmation”, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
CustomerSalesInformation.CustomerSalesInformationDelete(Convert.ToDouble(dgvData.CurrentRow.Cells["ID"].Value.ToString()));
FillDataGridView();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnClearGrid_Click(object sender, EventArgs e)
{
try
{
dgvData.DataSource = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// Handles Click event of the button
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnExit_Click(object sender, EventArgs e)
{
try
{
Application.Exit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

#endregion

#endregion

#region Private Methods

/// <summary>
/// Fills the data in the DataGridView
/// </summary>
private void FillDataGridView()
{
try
{
//Filling the grid with data
dgvData.DataSource = CustomerSalesInformation.CustomerSalesInformationGet();

//Formating the columns of the grid
dgvData.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dgvData.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dgvData.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

dgvData.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

#endregion
}
}

CLR Stored Procedures and creating it step by step

June 15th, 2009 by virat.kothari § 6

Download code & SQL statements: BlueDownArrow

Introduction:

We usually face problem in Stored Procedures and other database object when we need to implement some complicated logic within it. We found inefficient performance when we try to implement complex logic & business rules in database objects. In many cases we found C# or VB classes more powerful to implement such things. Microsoft has launched a new concept to resolve such issues with SQL server 2005 called “CLR Stored Procedure”.

What is CLR Stored Procedure?

Now, let us understand CLR stored procedure. CLR as most of .Net programmer knows is Common Language Runtime and Stored Procedures are routine stored procedures of database. Thus, CLR Stored Procedures are combination of both. As we all know, Common Language Runtime is core .Net component. The Common Language Runtime is runtime execution environment which supplies managed code with various services like cross language integration, code access security, lifetime management of object, resources management, threading, debugging & type safety etc. So now, CLR Stored Procedures are .Net objects which run in the memory of database.

The very first usage of CLR Stored Procedures can be said accessing system resources. Accessing system resources could also be done using Extended Stored Procedures which are again database object like Stored Procedures, Functions etc. Extended Stored Procedures can do most of the things which a standard executable program can do. Then, why are CLR Stored Procedures? The very first advantage of CLR Stored Procedures is it is a managed object unlike Extended Stored Procedures, which are unmanaged objects. The common thing between them is both runs under database memory. In this way CLR Stored Procedures gives all the benefits of managed objects. Following screen explains memory allocation while execution of CLR Stored Procedure.

0

When should I use CLR Stored Procedure?

Extended stored procedures run in the same process space as the database engine, memory leaks, bugs etc., can affects the performance of database engine. CLR stored procedures resolves these issues as they are managed object and runs per specifications of Common Language Runtime. CLR Stored Procedures can replace a standard stored procedure that contains complex logic and business rules. CLR Stored Procedures takes benefit of .Net classes and thus makes easy to implement complex logic, calculation, intense string operations, complex iterations, data encryptions etc., that are difficult to obtain in standard stored procedures. Standard stored procedures are still best for data oriented tasks. CLR Stored Procedures not only includes stored procedures but also includes Functions, Triggers etc. CLR Stored Procedures are compiled one so gives better performance.

Benefits of CLR Stored Procedures:

  1. Gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management etc.
  2. CLR Stored Procedures are managed codes so ensures type safety, memory management etc.
  3. Better code management and provides object oriented programming capability thus enables encapsulation, polymorphism & inheritance.
  4. Convenient for programmer as CLR Stored Procedures can be written in C#, VB or any other language that .Net Framework supports.
  5. CLR Stored Procedures can also be used with Oracle 10g Release 2 or later versions.
  6. Not convenient in all contexts for e.g. it should not be used to execute simple queries. In that case standard stored procedures give better results.
  7. Deployment may be difficult in some scenarios.

Drawbacks of CLR Stored Procedures:

  1. Not convenient in all contexts for e.g. it should not be used to execute simple queries. In that case standard stored procedures give better results.
  2. Deployment may be difficult in some scenarios.

Standard Stored Procedures vs. CLR Stored Procedures:

You are the best judge when to use regular Stored Procedures and when to use CLR Stored Procedures. CLR Stored Procedures can be used in following scenarios.

  1. When the program requires complex logic or business rules.
  2. When the flow is CPU intensive. CLR Stored Procedures gives better results as they are in complied form and managed one.
  3. The tasks which are not possible in TSQL, accessing system resources, cryptography, accessing web services etc.
  4. In option of Extended Stored Procedures. One should always consider CLR Stored Procedures before going for Extended Stored Procedures.
  5. An operation requires higher data safety.

Creating CLR Stored Procedure step by step:

Let us create one simple CLR Stored Procedure which fetches all the rows from one table of the database. I have attached whole list of SQL statement used for creating database, creating table, inserting dummy records in the table etc., under “SQL statements used in the demo” section.

Application development specification:

  • IDE: Visual Studio 2008
  • Framework: 3.5 with SP 1
  • Language: C# 3.0
  • Database MS SQL Server 2005 Express edition

Steps to create CLR Stored Procedure:

1) Open Microsoft Visual Studio >> Click on New Project >> Select Database Projects >> SQL Server Project.

1

2) You can choose reference of existing database connection or click on Add New Reference.

2

3) If you selects from existing references skit step 3 else add new database reference as shown in following image and click on Test Connection to test the connection.

3

4) On clicking on OK button, Visual Studio will ask you to enable SQL/CLR debugging on the selected connection. You can select “Yes” to enable debugging or “No” to disable the same.

4

5) Once the database reference and debugging option is selected, the project will be displayed in Solution Explorer. Select the project and right click on Solution Explorer >> Click on Add >> Stored Procedure.

5

6) Add new procedure from the installed templates as shown in following screen. Give proper name to it.

6

7) Once you select the template, it will create .cs file with the content shown in following image.

7

8 ) Add following code in the method already created. Pass “context connection=true” as connection string in the constructor while creating new SqlConnection. This CLR stored procedure is going to be the part of the database, so it will be the internal part of database so no need to connect database externally. So, no need to provide connection string that we usually provide in applications. Then Click on Build menu >> Click on Build Solution. Also click on Build menu >> Deploy solution. This will deploy the assembly to the database for which we have made connection initially.

8

9) Now, select the database >> Programmability. Right click on Stored Procedures >> Click on Refresh. The list of Stored Procedures should show one newly added stored procedure. Also right click on Assemblies >> click on Refresh. This should show newly added Assembly. Also, enable CLR Stored Procedure by following query.

sp_configure ‘clr enabled’, 1

Run following query to take effect or above query.

RECONFIGURE

Now, execute the stored procedure. It should give similar results shown in following screen.

9

SQL statements used in the demo:

Following is the queries to create database, create table, insert records in the table etc.

–Create a new databse for demo

CREATE DATABASE DbForClrDemo

–Use database

USE DbForClrDemo

–Create table for CustomerSalesInformation

CREATE TABLE [dbo].[CustomerSalesInformation](

[Id] [int] IDENTITY(1,1) NOT NULL,

[Name] [varchar](50) NOT NULL,

[Sales] [decimal](18, 2) NOT NULL DEFAULT ((0)),

CONSTRAINT [PK_CustomerSalesInformation] PRIMARY KEY CLUSTERED

(

[Id] ASC

)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

–Insert dummy data to CustomerSalesInformation table

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Virat Kothari’, 50000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Dhruval Shah’, 5000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Urvish Sheth’, 15000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Rakesh Bajania’, 25000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (‘Dhaval Shah’, 150000)

–Enable CLR Stored Procedure in database

sp_configure ‘clr enabled’, 1

–Run following statuement to take effect of above statement

RECONFIGURE

–Now execute our CLR Stored Procedure. Remember “ClrDemo” is name of our Stored Procedure

EXEC [dbo].ClrDemo

Conclusion:

CLR Stored procedures are very simple and can be used in most complex scenarios.

Bibliography:

  1. MSDN (http://msdn.microsoft.com/en-us/library/ms131094.aspx)
  2. Code project
  3. http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1251402,00.html

Reference : Virat Kothari (www.viratkothari.wordpress.com)

Where Am I?

You are currently browsing entries tagged with virat kothari at Digicorp.