How to Implement 3 Tier Architecture Concepts in asp.net with Real Life Example

By
Hi Friends ! Today , I am going to Explain 3 Tier Architecture in asp.net with real life example. I have Explained this in more simplest way,so that a weak student can easily learn the concepts of 3 Tier Architecture.I have given a real life example also so that student can relate 3 tier Architecture concepts easily. You can easily enhance this application features from This page .
There are three layers in 3 Tier Architecture as given below:-
  1. Presentation Layer (UI Layer)
  2. Business Access Layer (BAL)
  3. Data Access Layer (DAL)
     1.) Presentation Layer(UI) :-
Presentation Layer is nothing but it is a user interface which every user see on your computer ,mobile and window screen. You can say,designing part of any application is known as Presentation Layer. The User can post input and get output on your presentation Layer only.In asp.net .axpx file is known as a presentation layer.
   2.) Business Access Layer(BAL) :-
Business Access Layer is act as mediator Layer between Presentation layer and Data Access layer.This layer is used to transfer the data between Presentation Layer and Data Access Layer. This layer is mainly used for Validations and calculations purpose. Every validations and calculations of data are held on that layer only. I have also implemented Property layer or Entity Layer concepts in Business Access Layer. It is optional layer if you are working on a small projects.But if you are working on large projects then you have to include this layer in your 3 Tier Architecture Applications.It is used to enhance the security and prevent to brokering the application. 

  3.) Data Access Layer (DAL) :-
This Layer only communicate with Business Access Layer. Data Access Layer contains the methods that helps Business Access Layer.Business layer class's methods call the Data Access Layer Class methods to perform some required action with database such as insertion,deletion,updation etc. All database related connection codes are written in this layer  only such as sql query ,stored procedure etc.

You can easily understand the exact concepts of 3 Tier Applications as show below:-

image

Real Life Example :-
Suppose if you want to book tatkal ticket then what will you do ? You will hire a third party man that is called mediator or Broker man.You can easily talk with this Broker man but you can't talk with Ticket counter officers. The Broker man can easily talk with Ticket counter officers as well as users. Same Funda and activity followed in 3 Tier Architecture Applications.You can relate it as follows:-
User (You)   ---> Presentation Layer
Broker man  ---> Business Access Layer
Ticket Counter Officer ---> Data Access Layer


real life


  • In 3 tier application Presentation layer can't talk with Data Access Layer Directly for Security Purpose. Same for users (you) also, you can't talk with Ticket counter officer directly. 
  • Business Access Layer can talk with both layers.Here Broker man talk with both man(you,officers). 
Now you can easily relate other activity of user,Broker man and Ticket Officer also with Presentation layer ,Business layer and Data Access Layer respectively That is completely similar with 3 tier architecture.

What are the working process of 3 Layers:-

When any user post data from your presentation layer(user Interface layer)-->Then this data first goes to Business Access Layer -->After that validation and calculation are held on this layer -->After that this data pass data to Data Access Layer -->After that data Access Layer fetch required  data or insert the data in database.-->After that Data Access Layer pass the required data to the business Access Layer.-->After that Business Access Layer send the required data to the Presentation Layer,-->After that Presentation Layer  is  responsible to display the required data to the user's computers or mobiles or Windows. 

Why does we use 3 Tier Architecture:-
There are following reasons to use 3 Tier Architecture in our asp.net application as given below:-
  • To increase the security in Application.
  • To easily maintain the application.
  • To easily modify or change in application.
  • To Reduce the server over load.
  • To reduce the loading time of  application.
Example :- 
  • All companies, which are working in software environment they always used 3 tier architecture concepts in your application whether they are working on small projects or large projects.  if you are using 3 tier concepts then it will be more complex but more understandable to the users.
  • Suppose you are working on a project in team 1000 members.There are many member shifted day by day due to some problems.When any new member assigned  for this project,then he can easily understand the concepts of 3 Tier Architecture and involve in this project.If companies are working on 1 Tier Architecture then shifting of employee from one project to another projects are not possible.
  • In 3 Tier, you can easily update any Tiers of codes easily.But in 1 Tier, it is not possible.
Advantages of 3 Tier Architecture:-
  • Each layer always use your separate codes,so it is easy to modify the codes.
  • It is helpful to easily maintain and understand the large projects.
  • You can easily change your graphical Environment.
  • It is more secure because any users can't access the database directly. 
  • You can easily change any layer codes without affecting other two layers.
  • It is a more consistence application.
Disadvantage of 3 Tier Architecture :- 
  • Its takes more time to build.
  • Many peoples face problems because they haven't good knowledge in oops concepts and  other c# programming such as class,object,property etc.
  • 3 Tier Architecture is more complex to build.
There are some steps to implement the 3 Tier Architecture concepts in asp.net applications.In this application ,I will explain "How to build 3 tier registration and Login page in asp.net " as given below:- 

Step 1:- First open your visual studio --> File -->New--> website -->Select ASP.NET Empty website -->OK -->Open Solution Explorer-->Add a New Web Form (Home.aspx)-->Drag and drop Label ,Text Box ,Button ,Hyper Link ,RequiredFieldValidator,Comarevalidator and SqlDataSource On the page from Toolbox as shown below:-


web form
  
Note:- This is called presentation layer.
Step 2:- Now open Solution Explorer -->Add a New web Form (login.aspx) -->Drag and drop Label,Text Box and Button controls on the page from toolbox as shown below:- 


login page

Note:- This is also called presentation layer.
Step 3:- Now open Solution Explorer --> Add Database.mdf file on your project folder -->Create student table with a specified column as shown below:-


sql_database

Note:-If you are facing problem to add .mdf file on your project then read below links:-

Step 4:- Now go Home.aspx page -->and Configure Sql Data Source.. with student table by following the Wizard steps (i have create a reg_connection string in this wizard) as shown below:-
CONFIGURATIONS

Note:-
  • It is very easy process to connect a database.
  • When you will follow whole configuration steps then you will see that connection string codes will be automatically inserted in web.config file.If you don't use Sql Data Source then you will have to add connection string(sql connection,stored procedure etc.) codes in web.config file manually.

?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
 <connectionStrings>
  <add name="reg_connection" connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>
 <system.web>
  <compilation debug="true" targetFramework="4.0">
   <assemblies>
    <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
 </system.web>
</configuration>

Descriptions:- 
  • Here you can see all connection strings codes are inserted within <connectionStrings> ...</connectionStrings>
  • If You want to insert other connection string codes such stored procedure , sql server connections then you can put under the configuration section of your web.config file as shown in above codes. 
Step 5:- Now Open your Solution Explorer -->Create a App_Code folder inside Your project folder --> After that Right Click on App_Code -->Add New Items -->Select Class (Name -Business_Object.cs) -->  Click Add Button as shown below:-


class

 Step 6:- Similarly follow step 5 and Add two other classes als0 such as 
  • Business _Layer.cs
  • Data Access Layer.cs 
as shown below:-
class layer

 Step 7:-Now Open Business_Object.cs file -->and write the c# property codes for get and set the data  as given below:- 

using System;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Business_Object
/// </summary>
public class Business_Object
{
 //Declared Registration Variables
    private string user_name;
    private string password;
    private string qualification;
    private string age;
    private string mobile;
//use propertis concepts in c#,to get and set the value in variables
    public string Username_value
    {
        get
        {
            return user_name;
        }
        set
        {
            user_name = value;
        }
    }
   
    public string pass_value
    {
        get
        {
            return password;
        }
        set
        {
            password = value;
        }
    }
    public string Qualification_value
    {
        get
        {
            return qualification;
        }
        set
        {
            qualification = value;
        }
    }
    public string Age_value
    {
        get
        {
            return age;
        }
        set
        {
            age= value;
        }
    }
    public string mobile_value
    {
        get
        {
            return mobile;
        }
        set
        {
           mobile = value;
        }
    }
}

Note:-
  • Read more about property in c# here.
  • This Layer is the sub group of Business Access Layer that is called property layer or entity layer.
Descriptions:-
  • Here i have declared all registrations variables Privately .
  • Create different methods for each variables to get and set the respective values.Here you can see, each method is returning string values. 
  • After set and get this method send the respective values to other method from where its called.When you will read each steps carefully then you will see that each layer class methods will call property layer class 's methods. 
Step 8:- Now open Data_Access_Layer.cs--> Write the following c# codes as given below:-

using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Data_access_layer
/// </summary>
public class Data_access_layer
{   
    //Insert your registration values in student table
    public string registration_details(Business_Object user_details)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["reg_connection"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into student values(@a,@b,@c,@d,@e)", con);
        try
        {
            cmd.Parameters.AddWithValue("@a", user_details.Username_value);
            cmd.Parameters.AddWithValue("@b", user_details.pass_value);
            cmd.Parameters.AddWithValue("@c", user_details.Qualification_value);
            cmd.Parameters.AddWithValue("@d", user_details.Age_value);
            cmd.Parameters.AddWithValue("@e", user_details.mobile_value);
            return cmd.ExecuteNonQuery().ToString();
        }
        catch (Exception show_error)
        {
            throw show_error;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }

        public string login_details(Business_Object user_login_details)
        {
            SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["reg_connection"].ConnectionString);
            con1.Open();
            try
            {
                SqlCommand cmd1 = new SqlCommand("select COUNT(*)from student where name='" + user_login_details.Username_value + "' and password='" + user_login_details.pass_value + "'", con1);
                string str=cmd1.ExecuteScalar().ToString();
                return str;
            }
            catch (Exception info)
            {
                throw info;
            }
            finally
            {
                con1.Close();
                con1.Dispose();
            }
        }   

    }
Note:- This is the 3 Layer of this application.
Descriptions:- In above Data Access Layer class ,i have created methods as given below:-
public string registration_details(Business_Object user_details)
{
connection stings codes....................
}


public string login_details(Business_Object user_login_details)
{
connection stings codes....................
}

In above two method, i have pass Business _Object class  or property layer class object. Here i passed the Business_Object class values as a parameter whatever this layer retrieve from our top layer (presentation layer) .
 Step 9:-Now open Business_Layer.cs file -->write the following c# codes as shown below:-

using System;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Business_Layer
/// </summary>
public class Business_Layer
{
    public string record_insert(Business_Object abc)
    {
        Data_access_layer dal = new Data_access_layer();
        try
        {
            return dal.registration_details(abc);
        }
        catch (Exception info)
        {
            throw info;
        }
        finally
        {
            dal = null;
        }
    }

    public string db_login(Business_Object my_login)
    {
        Data_access_layer dal1 = new Data_access_layer();
        try
        {
            return dal1.login_details(my_login);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            dal1 = null;
        }
    }

}


Note:- This is called 2 Layer of this application.
Descriptions:- In Business Access Layer ,i have created two methods that takes Business_Class object as a parameter as given below:-
 public string record_insert(Business_Object abc)

  {
       Data_access_layer dal = new Data_access_layer();
        return dal.registration_details(abc);
}

  • Here I have created the object of Data Access Layer class,so that all members of this class  loaded in memory.
  • After that call the registration_details method from data access layer with the help of object of that class and pass the value to Data Access Layer or Presentation Layer ,it depends who is calling this class's methods. You already know that this layer easily talk with both layers.
 public string db_login(Business_Object my_login)

    {
       Data_access_layer dal1 = new Data_access_layer();
       return dal1.login_details(my_login);

     }
  • Here i have also created the object of Data Access Layer class as above.
  • Here I have  called login_details ( ) method of Data Access layer Class.
Step 10:- Now open Home.aspx.cs file --> Write the following c# codes as given below:-

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Home : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Load or call Business object class in memory and get and set the value in variables
            Business_Object bo = new Business_Object();
            bo.Username_value = TextBox1.Text;
            bo.pass_value = TextBox2.Text;
            bo.Qualification_value = TextBox4.Text;
            bo.Age_value = TextBox5.Text;
            bo.mobile_value = TextBox6.Text;
           //call business layer class by creating object of business layer class
            Business_Layer bl = new Business_Layer();
            
        try{
            string result = bl.record_insert(bo);
            if (result != null)
            {
                Label1.Text = "Data successfully inserted in database";
            }
            else
            {
                Label1.Text = "Try again...";
            }
        }
        catch (Exception info)
        {
            throw info;
        }
        finally
        {
            bo = null;
            bl = null;
        }

    }
}


Note:- This is called 1 Layer of this application.

Descriptions:-
Here i have created object(ob) of Business_Object Class.So that we can call Business_Object class methods for assigning the respective Text Box values to the variables.
Ex.
Business_Object bo = new Business_Object();
      bo.Username_value = TextBox1.Text;

Here i have called the Username_value method from Business_Object class by the object(bo) of this class and set the TextBox1 values to its variables.
Ex.
 Business_Layer bl = new Business_Layer();
string result = bl.record_insert(bo);


  • Here i have created object(bl)of the Business_Layer Class.
  • After that call the record_insert () method and pass the object of the Business-Object class
Step 11:-Now open  login.aspx.cs file-->Write the following c# codes as given below:-

using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Business_Object business = new Business_Object();
        business.Username_value = txtuser.Text;
        business.pass_value = txtpass.Text;
        Business_Layer b_layer = new Business_Layer();
        try
        {
            string login = b_layer.db_login(business);
            int i = int.Parse(login);
            if (i>0)
            {
                Response.Redirect("Success.aspx");
            }
            else
            {
                Label1.Text = "Invalid Login.try again....";
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            b_layer = null;
        }
         
    }
}


Note:- This is also called 1 Layer of this application.

Descriptions:-
Business_Object business = new Business_Object();
Business_Layer b_layer = new Business_Layer();
  • Here i have  loaded  Business_Object class an Business_Layer Class by creating the object of each classes.
string login = b_layer.db_login(business);
  • Here i have called the db_login() method by the object(db_layer) of that class and pass  object(Business) of  the Business_Object class as a parameter.After that store it in login variable.
Step 12:- Now ,You have completed the 3 Tier Application -->Run the application (press F5) --> Enter the Registration Fields Details -->Press Register Now Button -->You will see following output as shown below:-
3 tier

Step 13:-  If you have completed the registration Field details --> Press Click here Button as given below -->login.aspx page will be opened --> Now enter login details -->and press Login Button -->You will see following output as shown below:-
login_output



Step 14:- Now open Your student table from Database.mdf file --> You will see that data is inserted successfully as shown below:-


output

Attention:-
  • Here Business_Object class is optional for small project,you can use it or not.But if you are working Large project then you have to use it in your project.
  • In Above application ,i have used SqlDataSource connection string.You can also use stored procedure for your database connections if required.
  • You can add all class file(.cs) from out side of  App_Code folder but you have to set the References to each classes.
I hope this helpful for you.
You can easily run below application on your system.if any problem ask me.
For More...

  1. How to use secure login page in asp.net with example
  2. How to Add and verify Captcha image in 3 tier architecture in asp.net
  3. How to use virtual keyboard in asp.net for security purpose
  4. How to implement hashing concepts in asp.net
  5. Learn complete .Net Interview Questions and answers for job seekers

Download whole Attached file
      Download

13 comments:

  1. You have mixed 3 tier with 3 layered architecture. both are different.

    ReplyDelete
    Replies
    1. please explain difference between 3 tier and 3 layered with example.

      Delete
  2. How to add refrences to each cs file plz tell

    ReplyDelete
  3. Click on the project and go to add reference.There you will find all other class libraries.Select the class library that you want to add as a reference.Done.

    ReplyDelete
  4. Thala superb.... i am week students but now getting clearly

    ReplyDelete
  5. you have any vedio related this topic...

    ReplyDelete

Powered by Blogger.