Geeks With Blogs
Microsoft Technologies Edison García - Microsoft Student Partner

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…

Posted on Sunday, April 5, 2009 10:14 AM | Back to top


Comments on this post: A simple 3-tier layers application in ASP.NET

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Excellent tutorial and very good site
Left by Andres on Apr 05, 2009 10:28 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Very Nice,
Thanx budy,u explain this in very simple and nice way.
Thanx a lot

Abhishek
Left by Abhishek Tayade on Jul 28, 2009 4:49 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
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

Left by Don Gee on Aug 07, 2009 2:39 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
MIND BLOWING TUTORIAL. I have created it within few minutes. Thanks a lot.
Left by Ritesh on Aug 08, 2009 1:44 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Thank u v much 4 this article. It has helped me a lot. Keep up the gud work.
Left by ALTAF on Aug 18, 2009 11:17 AM

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

This is a really cool example, but does anybosy have it in vb.net?
Left by Nivash on Sep 14, 2009 5:06 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Excellent example. So simple to understand. Great help. Thanks a ton.
Left by Pooja on Oct 18, 2009 10:54 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
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.
Left by pat garvey on Oct 22, 2009 9:52 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
thanks lot dear.
that'n simple and nice.
Left by Hassan on Nov 06, 2009 11:51 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Nice article. I agree with what you said. Thanks
Left by Nia on Nov 10, 2009 10:09 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
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
Left by ram on Dec 15, 2009 11:47 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
very good ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
Left by sdfs on Dec 31, 2009 10:44 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
hi, really very nice..........
Left by prakash on Jul 02, 2010 1:00 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Well explained buddy. Thanks mate.....
Left by Jerry on Jul 08, 2010 2:27 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Great tutorial... the catch is configuring the connection string with sql server... Outstanding tutorial... works perfectly......
Left by Marcelo Salvador on Aug 22, 2010 1:37 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
very good
Left by srini on Dec 21, 2010 12:46 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
not understandable
Left by srinivas on Dec 21, 2010 1:07 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
merci svp
Left by LAID on Jan 16, 2011 12:13 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
i applied to mine site and its working u can see the code also...
http://www.cprogramming.uniquetricks.com
Left by dev on Jan 21, 2011 3:55 AM

# re: A simple 3-tier layers application in ASP.NET with basic coding
Requesting Gravatar...
hi sir explain the three tier architecture in asp.net with basic coding
Left by veera on Feb 14, 2011 11:09 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
nicely presented keep going the good work ......
Left by vinod gulagannavar on May 09, 2011 2:24 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
i love it
Left by khoa on May 30, 2011 5:47 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
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.
Left by Oscar on Jun 09, 2011 3:30 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
I NEED MORE SAMPLES FOR BEGINNERS LIKE ME.
Left by Louvi on Jun 16, 2011 4:48 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Buen ejemplo para iniciar con esto, gracias.
Left by Adolfo on Jun 29, 2011 1:11 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
thanks for such great effort for us,
BUT if possible then we want more example on the n-tier and layered application.
THANK YOU!
Left by dharmesh on Jul 07, 2011 9:32 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Great, clean and simple.
Left by Kelee on Sep 07, 2011 10:59 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
this article is good for start
thanks
Left by hossein on Sep 20, 2011 11:53 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
the Code??? post????
Left by Juanjo on Sep 22, 2011 12:28 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Such a nice ....
Left by Umesh on Sep 29, 2011 7:16 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
FUCK YOU!

ASP.NET SUCKS!
Left by alawar's vault on Nov 04, 2011 10:37 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
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??

Left by Fernando on Nov 07, 2011 3:16 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
It is such good web site which is helping me to learn the 3 tier application easily.
Left by Samatha on Jan 02, 2012 4:23 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Nice article
Left by gowths on Jan 03, 2012 5:04 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
How do you add parameters when instantiating the DbCommand object in your Business Layer?
Left by Fred B on Jan 04, 2012 2:48 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
exelente tutorial
Left by ANDRES on Apr 12, 2012 1:54 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
It is giving error in connecting sql server. Please check your sql server connection.

Regards,
Rohit
xpode.com
Left by Rohit on May 10, 2012 10:53 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
i want to insert all the text entry in sql server.data shoud pass through datalayer and bussiness layer and finally query shoul execute in sql server as stored procedur..please get me answer
Left by Anurag on May 19, 2012 3:12 PM

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

very good example
but can u put hole example like insert,update,delete
in three tire in linq ????
Left by Trilok pathak on May 30, 2012 10:51 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
This is helpful....
Left by anand rajput on Jun 05, 2012 7:53 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
EXELENTE TUTURIAL PARA PRINCIPIANTES
Left by Rafael on Jun 08, 2012 9:33 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
i want to do select query for a sign in page.my pagew havew username & password.pls sent me answer
Left by ammu on Jun 13, 2012 9:34 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
i want to do select query for a sign in page.my pagew have username & password.pls sent me answer
Left by ammu on Jun 13, 2012 9:35 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
It's nice...and..you r explain it in very easy way...it is easy to understand...!!!


Give me more example WITH INSERT,UPDATE,and DELETE with paging IN GridView...!!!
Left by Mayank on Jun 14, 2012 5:09 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Great example! Got it to work with DB2 in no time.

How would I deploy the business and data tier in a separate server? Would I use IIS? Does the code have to change in any way?
Left by JPC on Jun 29, 2012 5:54 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
great work..
Left by humayun ikram on Aug 25, 2012 11:13 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
gut aber niecht fantastics
Left by ravi on Sep 22, 2012 4:33 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Nice one good understand the this architecture
Left by Lingraj on Sep 24, 2012 2:12 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
: A simple 3-tier layers application in ASP.NET
Nice one good understand the this architecture.
Left by kaleem Paracha on Oct 01, 2012 4:33 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Basically you have described a 3 layer architecture here in this article.
3 tier is different than 3 layered architecture.
Left by Moin on Oct 02, 2012 1:14 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Ahhh, it's data access layer, not data-layer. Cross talk should not change the meaning of the layers. Providing procedures to deliver data is a bad idea too as it typically allows poeple to create some of the business of the data in the db, not the business layer.
Left by Ahhhh on Oct 04, 2012 4:31 PM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Nice coding
Left by Mangesh on Oct 09, 2012 1:50 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
very helpful easily understand.....
Left by Rupesh Pakhale on Jan 04, 2013 6:26 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
nice example and easy way to learn quickly. thanks
Left by sureshrana on Feb 27, 2013 12:38 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
thanks nice to learn.......
Left by kesu on Feb 28, 2013 12:10 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
i am beginner in mvc 3...i don't know which is best....help me....i am first graduate in my family.....
Left by kesu on Feb 28, 2013 12:32 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Nice articles..
gr8 work..
Left by Raju on Feb 28, 2013 2:36 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
nice example and easy to understand...
Left by venkat on Mar 08, 2013 3:42 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
Hi,I have problem with this program when I run it an error occured that says "DbProviderFactory factory = DbProviderFactories.GetFactory(dbProviderName)" returns null,would anyone pleas help me?
what should I do?
Left by bahareh on Mar 09, 2013 12:42 AM

# re: A simple 3-tier layers application in ASP.NET
Requesting Gravatar...
It is good code ,helps in developing big application
Left by Raju on Apr 18, 2013 1:48 AM

Your comment:
 (will show your gravatar)
 


Copyright © mredison | Powered by: GeeksWithBlogs.net | Join free