Wednesday, 10 September 2014

Three Tier Architecture in Asp.Net

Three Tier Architecture


Three-tier (layer) is a client-server architecture in which the user interface, business process (business rules) and data storage and data access are developed and maintained as independent modules or most often on separate platforms. 

Basically, there are 3 layers,
1. User Interface layer (UI) or Presentation Layer. 
2. Business Access Layer (BAL) or Business Logic Layer (BLL).
3. Data Access Layer (DAL).

User Interface Layer is responsibility for Look and Feel.

Business Layer is responsible for Business Logic.

Data Access Layer is responsible for to maintain the code you utilize to drag data from your Data Base.

What is the need for dividing the code in 3-tiers? Separation of the user interface from business logic and database access has many advantages. Some of the advantages are as follows:

•Reusability of the business logic component results in quick development. Let's say we have a module that handles adding, updating, deleting and finding customers in the system. As this component is developed and tested, we can use it in any other project that might involve maintaining customers. 
•Transformation of the system is easy. Since the business logic is separate from the data access layer, changing the data access layer won’t affect the business logic module much. Let's say if we are moving from SQL Server data storage to Oracle there shouldn’t be any changes required in the business layer component and in the GUI component. 
•Change management of the system is easy. Let's say if there is a minor change in the business logic, we don’t have to install the entire system in individual user’s PCs. E.g. if GST (TAX) is changed from 10% to 15% we only need to update the business logic component without affecting the users and without any downtime. 
•Having separate functionality servers allows for parallel development of individual tiers by application specialists. 
•Provides more flexible resource allocation.

Benefits of Three Tier Architecture


1. Easy to Use and Modify your Applications.
2. Fast Communications between Layers.
3. We Can Change the User Interface without affecting the other Two Layers (Data Access Layer and Business Layer).
4. Scalability, Performance, Secure and Availability.

Example:

SQL Server Database

Here I am using for back end SQL Server for Storing and Retrieve Employee Details in Database. Let’s Create New Table in SQL Server named Called "Employee" having following Fields.

1. EmpID - Employee ID. It should be auto increment.
2. EmpName - Employee Name. 
3. DOB - Employee Birth date.
4. ContactNo - Employee Contact Number 


Create “Employee”Table below:

CREATE TABLE [dbo].[Employee1](
      [EmpID] [int] IDENTITY(1000,1) NOT NULL,
      [EMPName] [nvarchar](50) NOT NULL,
      [DOB] [datetime] NOT NULL,
      [ContactNo] [nvarchar](12) NULL)
GO

 

Stored procedure:


I am Using Stored procedure for Inserting, Updating and Deleting Record.
1. sp_InsertEmployeeDetails for inserting Records into Employee Table.
2. sp_UpdateEmployeeDetails for updating records from Employee Table.
3. sp_DeleteEmployeeDetails for Deleting records from Employee Table.


Insert:

Create PROCEDURE [dbo].[sp_InsertEmployeeDetails]
      -- Add the parameters for the stored procedure here
      @EMPName AS NVARCHAR(50),
      @DOB AS DATETIME,
      @ContactNo AS NVARCHAR(12)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
      INSERT INTO Employee(EMPName,DOB,ContactNo)
      VALUES(@EMPName,@DOB,@ContactNo)
END


Update:

Create PROCEDURE [dbo].[sp_UpdateEmployeeDetails]
      -- Add the parameters for the stored procedure here
      @EmpID as Int,
      @EMPName AS NVARCHAR(50),
      @DOB AS DATETIME,
      @ContactNo AS NVARCHAR(12)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
      UPDATE Employee SET EMPName =@EMPName,
      DOB = @DOB,
      ContactNo= @ContactNo
      WHERE EMPID=@EmpID
 
END


Delete:

Create PROCEDURE [dbo].[sp_DeleteEmployeeDetails]
      -- Add the parameters for the stored procedure here
      @EmpID as Int
     
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
      Delete from Employee
      WHERE EMPID=@EmpID
 
END
 

Here you’ll explain how to create simple Web application using Three Tier Architecture in ASP.Net.

So before you start the lab, you need check whether Visual Studio 2010 is installed or not. I hope Installed. 

Here I am Using Visual Studio 2010. So the first thing let go to Microsoft Visual Studio 2010 lets open Visual Studio 2010.So let’s click File --> New project --> and so let select Web.

And web you can see that there is a couple of ASP.Net Web Application Templates. ASP.Net Web Applications and ASP.Net Empty Web Applications.

Here we Select the ASP.Net Empty Web Applications and give the nice name here "3tierSimpleWebApplication" and let’s click OK button. Once click ok you can see that the template has created certain project structure for us. 



Create a Business Layer, Right click on the solution of the Web Applications "3tierSimpleWebApplication" and add the new project and Select the Class Library named "BLLTestProjects".


You have to create Data Access Layer like similar to create a Business Layer, Right click on the solution of the Web Applications "3tierSimpleWebApplication" and add the new project and Select the Class Library named "DALTestProjects".

Add Business Layer and Data Access Layer to Projects. Right click on the solution of the Web Applications "3tierSimpleWebApplication" and Click Add Reference

1. BLLTestProjects
2. DALTestProjects


You will get the below Screenshot After add both Business Layer and Data Access Layer.


Here I am creating Data Access Layer for Web Applications, Right Click on the Solution of Class Library named "DALTestProject", Add New Class named "DALEmpDetails" and Below Code.

Write Below code in DALEmpDetails

-----------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
namespace DALTestProject
{
    public class DALEmpDetails
    {

        private string ConnectionString = "Data Source=MY-PC;Initial Catalog=MyDB;Integrated Security=True";
        public DataSet getEmpDetails()
        {
            DataSet dsEmpDetails = new DataSet();
            dsEmpDetails = SqlHelper.ExecuteDataset(ConnectionString, "sp_getAllEmployeeDetails");
            return dsEmpDetails;
        }
        public int createNewEmpDetails(string EmpName, DateTime DOB, string ContactNo)
        {
            SqlParameter[] objParams = new SqlParameter[3];
            objParams[0] = new SqlParameter("@EMPName", SqlDbType.VarChar, 50);
            objParams[0].Value = EmpName;
            objParams[1] = new SqlParameter("@DOB", SqlDbType.DateTime);
            objParams[1].Value = DOB;
            objParams[2] = new SqlParameter("@ContactNo", SqlDbType.VarChar, 50);
            objParams[2].Value = ContactNo;

            return SqlHelper.ExecuteNonQuery(ConnectionString, "sp_InsertEmployeeDetails", objParams);

        }
        public int UpdateEmpDetails(int EmpID, string EmpName, DateTime DOB, string ContactNo)
        {
            SqlParameter[] objParams = new SqlParameter[4];
            objParams[0] = new SqlParameter("@EMPID", SqlDbType.Int);
            objParams[0].Value = EmpID;

            objParams[1] = new SqlParameter("@EMPName", SqlDbType.VarChar, 50);
            objParams[1].Value = EmpName;
            objParams[2] = new SqlParameter("@DOB", SqlDbType.DateTime);
            objParams[2].Value = DOB;
            objParams[3] = new SqlParameter("@ContactNo", SqlDbType.VarChar, 50);
            objParams[3].Value = ContactNo;

            return SqlHelper.ExecuteNonQuery(ConnectionString, "sp_InsertEmployeeDetails", objParams);


        }
        public DataSet getEmpDetails(int EmpID)
        {
            DataSet dsEmpDetails = new DataSet();
            SqlParameter[] objParams = new SqlParameter[1];
            objParams[0] = new SqlParameter("@EmpID", SqlDbType.Int);
            objParams[0].Value = EmpID;
            dsEmpDetails = SqlHelper.ExecuteDataset(ConnectionString, "sp_getAllEmployeeDetailsByEmpNo", objParams);
            return dsEmpDetails;
        }

    }
}

-----------------------------------------------------------------------------------------------------------

Here I am creating Business Access Layer for Web Applications, Right Click on the Soluiton of Class Library named "BLLTestProjects",Add New Class named "BLLEmpDetails" and Write Below code in BLLEmpDetails Class.

-----------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DALTestProject;
namespace BLLTestProjects
{
    Public class BLLEmpDetails
    {
        DALEmpDetails objEmp = new DALEmpDetails();


        public DataSet getEmpDetails()
        {
            return objEmp.getEmpDetails();
        }

        public int createNewEmpDetails(string EmpName, DateTime DOB, string ContactNo)
        {
            return objEmp.createNewEmpDetails(EmpName, DOB, ContactNo);
        }
        public DataSet getEmpDetails(int EmpNo)
        {
            return objEmp.getEmpDetails(EmpNo);
        }
    }
}

EmpDetails.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmpDetails.aspx.cs" Inherits="3tierSimpleWebApplication.EmpDetails" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div> <table style="width:100%;">
    <tr><td class="style1">EmpName:</td><td>
    <asp:textbox ID="txtEmpName" runat="server"></asp:textbox>
    </td></tr> <tr>
    <td class="style1">DOB: </td>  <td> <asp:TextBox 
     ID="txtDate" runat="server"></asp:TextBox> </td>
            </tr>  <tr> <td class="style1">
    Contact #:   <br />  </td>      <td>
                    <asp:textbox ID="txtContact" runat="server"></asp:textbox><asp:Label ID="Label1" runat="server" Text="Successfully Inserted"  Visible="False"></asp:Label> </td></tr>
        </table> <asp:Button ID="btnSubmit" runat="server" Text="Save" onclick="btnSubmit_Click" />
        <asp:Button ID="btnUpdate" runat="server" Text="Update"
            onclick="btnUpdate_Click" /><br />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />   
    </div>
    </form>
</body>
</html>

-----------------------------------------------------------------------------------------------------------

Write Below code in EmpDetails.aspx.cs 

-----------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLLTestProjects;
using DALTestProject;
namespace 3tierSimpleWebApplication
{

     BLLEmpDetails objEmp = new BLLEmpDetails();
    public partial class EmpDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
        {
            GridView1.DataSource = objEmp.getEmpDetails();
            GridView1.DataBind();
        }

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
                    int status = 0;
        DateTime objDate;
        objDate = DateTime.Parse(txtDate.Text);
        status= objEmp.createNewEmpDetails(txtEmpName.Text, objDate, txtContact.Text);
        if (status != 0)
            Label1.Visible = true;
        else
            Label1.Visible = false;
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
        }
    }
}

-----------------------------------------------------------------------------------------------------------

Write Below code in EmpDetailsUpdate.aspx

-----------------------------------------------------------------------------------------------------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmpDetailsUpdate.aspx.cs" Inherits="EmpDetailsUpdate" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 129px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <table style="width:100%;">
            <tr>
                <td class="style1">
    EmpName:</td>
                <td>
                    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                        onselectedindexchanged="DropDownList1_SelectedIndexChanged">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td class="style1">

    DOB:
                </td>
                <td>
                    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style1">

    Contact #:
    <br />
                </td>
                <td>
                    <asp:textbox ID="txtContact" runat="server"></asp:textbox>
                    <asp:Label ID="Label1" runat="server" Text="Successfully Inserted"
                        Visible="False"></asp:Label>
                </td>
            </tr>
        </table>
    <asp:Button ID="btnSubmit0" runat="server" Text="Update"
             />
   
    </div>
    </form>
</body>
</html>

-----------------------------------------------------------------------------------------------------------

Write Below code in EmpDetailsUpdate.aspx.cs

-----------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLLTestProjects;
using System.Data;
public partial class EmpDetailsUpdate : System.Web.UI.Page
{
    BLLEmpDetails objEmp = new BLLEmpDetails();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = objEmp.getEmpDetails();
            DropDownList1.DataTextField = "EmpName";
            DropDownList1.DataValueField = "EmpID";
            DropDownList1.DataBind();
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int Empno = Convert.ToInt32(DropDownList1.SelectedItem.Value);
        DataSet dsEmpdetails = objEmp.getEmpDetails(Empno);
        if (dsEmpdetails != null)
        {
            if (dsEmpdetails.Tables[0] != null)
                txtContact.Text = dsEmpdetails.Tables[0].Rows[0]["ContactNo"].ToString();
            txtDate.Text = dsEmpdetails.Tables[0].Rows[0]["DOB"].ToString();
        }
    }
}


Have a look at Screenshot for Add Employee details page in Simple 3 Tier Architecture in ASP.Net Web application.




1 comments:

Post a Comment