I will explain how to develop a simple application in ASP.NET using a three-tier architecture.

  • The presentation tier
  • The business tier
  • The data tier

3-thierLayersConcepts:

The presentation tier contains the UI (User Interface) elements of the site, and includes all the logic that manages the interaction between the visitor and the client’s business. (ASP.NET Web Forms,Web User Controls,ASP.NET Master Pages)

The business tier receives requests from the presentation tier and returns a result to the presentation tier depending on the business logic it contains. (C# Classes)

The data tier  is responsible for storing the application’s data and sending it to the business tier when requested. (SQL Server Stored Procedures)

 

 

 

 

The first Step is to create a new Web Site - C# Language.

 3-ThierLayers_01

We need to add a Master Page to define our web site style.

3-ThierLayers_02

3-ThierLayers_03

Here is the design of our application.

3-thierLayersDiagram

 


Creating the Database

Script:

Create Database SampleDb
Use SampleDb
Create Table Client
(
    clientID int not null,
    name varchar(50) not null,
    description varchar(1000)
)
Alter Table Client Add Constraint PK_Client Primary Key(clientID)

Insert into Client Values(001,'Edison Daniel García Chiñas','Mexico - CodeApp.NET Company')
Insert into Client Values(002,'Esperanza Ubaldo Mota','Mexico - COPESA Company');

Creating the Store Procedure

Create Procedure GetClients
As
Select clientID,name,description From Client

Adding Logic to the Site

We need 3 classes

  • Configuration
  • GenericData
  • Client

 

Creating the Configuration Class

First Add an ASP.NET Folder called App_Code and then inside of it a class called Configuration.cs

Configuration Class Code:

1.- Add the System.Configuration namespace.

using System.Configuration;

namespace SConfiguration
{
    
    public static class Configuration
    {

        private static string dbConnectionString;
        private static string dbProviderName;


        static Configuration()
        {
            dbConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            dbProviderName = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;
        }

        public static string DbConnectionString
        {
            get { return dbConnectionString; }
        }

        public static string DbProviderName
        {
            get { return dbProviderName; }
        }

    }

}

2.- Go to web.config file to add the two values that we are going to take from the configuration class.

<connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=.\MSPLAP;Initial Catalog=SampleDb;Persist Security Info=True;User ID=sa;Password=***********" providerName="System.Data.SqlClient"/>
    </connectionStrings>

Creating the GenericData Class

First add these namespaces to the class.

using System.Data;
using System.Data.Common;
using SConfiguration;

We need to create three methods for managing data.

  1. ExecuteReader()  is for SELECT Statement . The reason is we just need all the data returned from the select query.
  2. ExecuteNoneQuery() is for SQL Statements like INSERT, UPDATE, DELETE. The reason is simple, we don’t need to get data returned only the affected rows.
  3. ExecuteScalar()  is for SELECT Statement when we just need the first data returned from a select query. (“The top”).

 

So, here is the first method:

public static DataTable ExecuteReader(DbCommand command)
        {
            DataTable table;
            try
            {
                command.Connection.Open();
                DbDataReader reader = command.ExecuteReader();
                table = new DataTable();
                table.Load(reader);
            }
            catch (Exception ex)
            {throw ex;}
            finally
            {command.Connection.Close();}
            return table;
        }

This ExecuteReader method has a DbCommand parameter, this command will get a DataTable result of the select query, the DbDataReader will read all the data from the Table(s). Finally the command is going to return the table.

  public static int ExecuteNoneQuery(DbCommand command)
        {

            int AfectedRows = -1;
            try
            {   command.Connection.Open();
                AfectedRows = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            { throw ex;}
            finally
            { command.Connection.Close();}
            return AfectedRows;
        }

This method will return the number of AfectedRows result of INSERT,DELETE,UPDATE statements.

 public static string ExecuteScalar(DbCommand command)
        {
            string value = "";
            try
            {
                command.Connection.Open();
                value = command.ExecuteScalar().ToString();
            }
            catch (Exception ex)
            {throw ex;}
            finally
            {command.Connection.Close();}
            return value;
        }

Finally we just need a CreateCommand Method:

 //Create a command
        public static DbCommand CreateCommand()
        {

            string dbProviderName = Configuration.DbProviderName;
            string dbConnectionString = Configuration.DbConnectionString;
            DbProviderFactory factory = DbProviderFactories.GetFactory(dbProviderName);
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = dbConnectionString;
            DbCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            return command;

        }

In this method we define what command type we are going to use, in this sample website is going to be StoredProcedure type.

GenericClass Complete Code:

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.Common;
using SConfiguration;

namespace DataAcess
{

    public static class GenericData
    {
        static GenericData()
        {
           
        }

        public static DataTable ExecuteReader(DbCommand command)
        {
            DataTable table;
            try
            {
                command.Connection.Open();
                DbDataReader reader = command.ExecuteReader();
                table = new DataTable();
                table.Load(reader);
            }
            catch (Exception ex)
            {throw ex;}
            finally
            {command.Connection.Close();}
            return table;
        }

        //Create a command
        public static DbCommand CreateCommand()
        {

            string dbProviderName = Configuration.DbProviderName;
            string dbConnectionString = Configuration.DbConnectionString;
            DbProviderFactory factory = DbProviderFactories.GetFactory(dbProviderName);
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = dbConnectionString;
            DbCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            return command;

        }

        public static int ExecuteNoneQuery(DbCommand command)
        {

            int AfectedRows = -1;
            try
            {   command.Connection.Open();
                AfectedRows = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            { throw ex;}
            finally
            { command.Connection.Close();}
            return AfectedRows;
        }


        public static string ExecuteScalar(DbCommand command)
        {
            string value = "";
            try
            {
                command.Connection.Open();
                value = command.ExecuteScalar().ToString();
            }
            catch (Exception ex)
            {throw ex;}
            finally
            {command.Connection.Close();}
            return value;
        }

    }
}

Creating the Client Class

using System.Data;
using System.Data.Common;
using DataAcess;


namespace SClient
{
    public class Client
    {
        public static DataTable GetClients()
        {
            DbCommand command = GenericData.CreateCommand();
            command.CommandText = "GetClients";
            return GenericData.ExecuteReader(command);
        }
    }

}

Adding the presentation Layer

3-ThierLayers_04

Add a Web User Control called ClientsList.ascx.

 3-ThierLayers_05

Then add a gridview into the design tab.

After that double click to ClientsList.ascx.cs to add the fowolling code:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SClient;

public partial class Controls_ClientsList : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = Client.GetClients();
        GridView1.DataBind();
    }
}

Create a Content Page (New WebForm) from the MasterPage and drag and drop the ClientsList server control to the contentplaceHolder. Press F5.

3-ThierLayers_06

See you in the other post of this sample…

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# re: A simple 3-tier layers application in ASP.NET

Excellent tutorial and very good site 4/5/2009 10:28 AM | Andres

# re: A simple 3-tier layers application in ASP.NET

Very Nice,
Thanx budy,u explain this in very simple and nice way.
Thanx a lot

Abhishek 7/28/2009 4:49 AM | Abhishek Tayade

# re: A simple 3-tier layers application in ASP.NET

Hi Abhishek,
I copied this sample in and made the table in SQL Server express and I get an error thrown in the Execute Reader Catch exception code which says that a network-related instance-specific error occurred while establishing a connection to SQL Server.

Do you have any ideas?

Don

8/7/2009 2:39 PM | Don Gee

# re: A simple 3-tier layers application in ASP.NET

MIND BLOWING TUTORIAL. I have created it within few minutes. Thanks a lot. 8/8/2009 1:44 PM | Ritesh

# re: A simple 3-tier layers application in ASP.NET

Thank u v much 4 this article. It has helped me a lot. Keep up the gud work. 8/18/2009 11:17 AM | ALTAF

# re: A simple 3-tier layers application in ASP.NET

Hi

This is a really cool example, but does anybosy have it in vb.net? 9/14/2009 5:06 AM | Nivash

# re: A simple 3-tier layers application in ASP.NET

Excellent example. So simple to understand. Great help. Thanks a ton. 10/18/2009 10:54 PM | Pooja

# re: A simple 3-tier layers application in ASP.NET

Clear, Concise, perfect. A true gentleman are your sir. Boils down bits and pieces of 10 books into one GREAT example. I printed it out and taped it to the wall. 10/22/2009 9:52 PM | pat garvey

# re: A simple 3-tier layers application in ASP.NET

thanks lot dear.
that'n simple and nice. 11/6/2009 11:51 PM | Hassan

# re: A simple 3-tier layers application in ASP.NET

Nice article. I agree with what you said. Thanks 11/10/2009 10:09 PM | Nia

# re: A simple 3-tier layers application in ASP.NET

hi, reallly very nice tutorial, please post as many like this in more advance topics, particularly i need in gridview controls all and web services and post very useful topics in c#.. really thank u very much 12/15/2009 11:47 PM | ram

# re: A simple 3-tier layers application in ASP.NET

very good ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss 12/31/2009 10:44 PM | sdfs

# re: A simple 3-tier layers application in ASP.NET

hi, really very nice..........
7/2/2010 1:00 AM | prakash

# re: A simple 3-tier layers application in ASP.NET

Well explained buddy. Thanks mate..... 7/8/2010 2:27 AM | Jerry

# re: A simple 3-tier layers application in ASP.NET

Great tutorial... the catch is configuring the connection string with sql server... Outstanding tutorial... works perfectly...... 8/22/2010 1:37 PM | Marcelo Salvador

# re: A simple 3-tier layers application in ASP.NET

very good 12/21/2010 12:46 AM | srini

# re: A simple 3-tier layers application in ASP.NET

not understandable 12/21/2010 1:07 AM | srinivas

# re: A simple 3-tier layers application in ASP.NET

merci svp 1/16/2011 12:13 PM | LAID

# re: A simple 3-tier layers application in ASP.NET

i applied to mine site and its working u can see the code also...
http://www.cprogramming.uniquetricks.com 1/21/2011 3:55 AM | dev

# re: A simple 3-tier layers application in ASP.NET with basic coding

hi sir explain the three tier architecture in asp.net with basic coding 2/14/2011 11:09 PM | veera

# re: A simple 3-tier layers application in ASP.NET

nicely presented keep going the good work ...... 5/9/2011 2:24 AM | vinod gulagannavar

# re: A simple 3-tier layers application in ASP.NET

i love it 5/30/2011 5:47 PM | khoa

# re: A simple 3-tier layers application in ASP.NET

Amigo por favor me podria ayudar informando un poco + sobre esta parte?, gracias

Creating the GenericData Class
First add these namespaces to the class.
using System.Data;
using System.Data.Common;
using SConfiguration;
We need to create three methods for managing data.

No se donde creo eso, hago una clase para cada uno. 6/9/2011 3:30 PM | Oscar

# re: A simple 3-tier layers application in ASP.NET

I NEED MORE SAMPLES FOR BEGINNERS LIKE ME. 6/16/2011 4:48 AM | Louvi

# re: A simple 3-tier layers application in ASP.NET

Buen ejemplo para iniciar con esto, gracias. 6/29/2011 1:11 PM | Adolfo

# re: A simple 3-tier layers application in ASP.NET

thanks for such great effort for us,
BUT if possible then we want more example on the n-tier and layered application.
THANK YOU! 7/7/2011 9:32 AM | dharmesh

# re: A simple 3-tier layers application in ASP.NET

Great, clean and simple. 9/7/2011 10:59 PM | Kelee

# re: A simple 3-tier layers application in ASP.NET

this article is good for start
thanks 9/20/2011 11:53 AM | hossein

# re: A simple 3-tier layers application in ASP.NET

the Code??? post???? 9/22/2011 12:28 PM | Juanjo

# re: A simple 3-tier layers application in ASP.NET

Such a nice .... 9/29/2011 7:16 AM | Umesh

# re: A simple 3-tier layers application in ASP.NET

FUCK YOU!

ASP.NET SUCKS! 11/4/2011 10:37 AM | alawar's vault

# re: A simple 3-tier layers application in ASP.NET

im trying to implemt this exercise but it have an error in the CreateCommand Method,

string dbProviderName = Configuration.DbProviderName;

when i run the application, a error page appear:

"Object reference not set to an instance of an object"


do you know why??

11/7/2011 3:16 PM | Fernando

# re: A simple 3-tier layers application in ASP.NET

It is such good web site which is helping me to learn the 3 tier application easily. 1/2/2012 4:23 AM | Samatha

# re: A simple 3-tier layers application in ASP.NET

Nice article 1/3/2012 5:04 AM | gowths

# re: A simple 3-tier layers application in ASP.NET

How do you add parameters when instantiating the DbCommand object in your Business Layer? 1/4/2012 2:48 PM | Fred B

Post a comment





 

 

News

Example?xcxc

Archives

Post Categories

Syndication: