3-Tier Architecture Tutorial for Beginner

C#.NET window based Application or ASP.NET website have one coding structure which is popular as a 3-Tier Architecture which is also known as 3-Layered Architecture.

So, let’s start discuss with :

What is a Layer?

3 tier architecture
3-Tier Architecture

A layer is a reusable portion of code that performs a specific function. In the .NET environment, a layer is usually set up as a project that represents this specific function. This specific layer is in charge of working with other layers to perform some specific goal. Let’s briefly look at the latter situation first.

  • Data Layer
    A DAL contains methods that helps the Business Layer to connect the data and perform required actions, whether to return data or to manipulate data (insert, update, delete and so on).
  • Business Layer
    A BAL contains business logic, validations or calculations related to the data.
    Though a web site could talk to the data access layer directly, it usually goes through another layer called the Business Layer. The Business Layer is vital in that it validates the input conditions before calling a method from the data layer. This ensures the data input is correct before proceeding, and can often ensure that the outputs are correct as well. This validation of input is called business rules, meaning the rules that the Business Layer uses to make “judgments” about the data.
  • Presentation Layer
    The Presentation Layer contains pages like .aspx or Windows Forms forms where data is presented to the user or input is taken from the user. The ASP.NET web site or Windows Forms application (the UI for the project) is called the Presentation Layer. The Presentation Layer is the most important layer simply because it’s the one that everyone sees and uses. Even with a well structured business and data layer, if the Presentation Layer is designed poorly, this gives the users a poor view of the system.

Let’s consider one example for Desktop Application :

For example, if we can store City from website or window desktop application to SQL Server DB..

Create DB & Table :

  • Create database with name 3-TierDemoDB and create table with name MST_City
SQL Server Database
SQL Server Database
  • Column in MST_City is like : Here, CityID is Primary Key which is directly show left side of CityID Column Name with yellow color.
City Table
City Table
  • Create Stored Procedure for Insert data into Table like :
CREATE PROCEDURE [dbo].[PR_MST_City_Insert]

@CityID		int OUTPUT,
@CityName	varchar(50),
@PinCode	varchar(20),
@StateID	int

AS
BEGIN

SELECT @CityID= ISNULL(MAX([CityID]),0) + 1 FROM [dbo].[MST_City]

INSERT INTO [dbo].[MST_City]
(
	[dbo].[MST_City].[CityID],
	[dbo].[MST_City].[CityName],
	[dbo].[MST_City].[PinCode]
)
VALUES
(
	@CityID,
	@CityName,
	@PinCode
)

END

Code for ENT (Entity) :

Here, In Visual Studio Create .cs file with name ENT_MST_City and write code for getter & setter properties of each field of MST_City table.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3_TierDemo.ENT
{
    class ENT_MST_City
    {

        #region Variables
        private Int32 _CityID;
        private String _CityName;
        private String _PinCode;
        private Int32 _StateID;
        #endregion

        #region Properties
        public Int32 CityID
        {
            get
            {
                return _CityID;
            }
            set
            {
                _CityID = value;
            }
        }

        public String CityName
        {
            get
            {
                return _CityName;
            }
            set
            {
                _CityName = value;
            }
        }

        public String PinCode
        {
            get
            {
                return _PinCode;
            }
            set
            {
                _PinCode = value;
            }
        }
        #endregion

    }
}

Code for BAL (Business) :

Here, for city insert there is no any Business logic so, We can only create BAL_MST_City and leave it blank . . .

Code for DAL (Data Access) :

Here, we can communicate with Database with DataBaseHelper.cs Class :

So, 1st Create DataBaseHelper.cs class & write code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;

namespace _3_TierDemo.Class
{
    class DataBaseHelper
    {

        #region Constructor
        public DataBaseHelper()
        {
            ConStr = @"Here Your ConnectionString";
        }
        #endregion

        #region Variables
        private string ConStr;
        #endregion

        #region ExecuteNonQuery with cmd
        public Boolean ExecuteNonQuery(SqlCommand cmd)
        {
            using (SqlConnection con = new SqlConnection(ConStr))
            {
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                try
                {
                    cmd.ExecuteNonQuery();
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("" + ex.Message.ToString());
                    return false;
                }
                finally
                {
                    con.Close();
                    con.Dispose();
                    cmd.Dispose();
                }
            }
        }
        #endregion

        #region SelectData
        public DataTable SelectData(SqlCommand cmd)
        {
            using (SqlConnection con = new SqlConnection(ConStr))
            {
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                try
                {
                    da.Fill(dt);
                    return dt;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("" + ex.Message.ToString());
                    return null;
                }
                finally
                {
                    con.Close();
                    con.Dispose();
                    da.Dispose();
                    cmd.Dispose();
                }
            }
        }
        #endregion

    }
}

Here, ExecutreNonQuery() function used for Insert, Update, Delete functionality & SelectData() function used for retrieved data from database or select data by specific column name from database.

Now, Code for DAL_MST_City.cs class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using _3_TierDemo.ENT;
using _3_TierDemo.Class;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;

namespace _3_TierDemo.DAL
{
    class DAL_MST_City
    {

        #region InsertData
        public Boolean InsertData(MST_CityENT _ENT)
        {
            DataBaseHelper _DBH = new DataBaseHelper();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "PR_MST_City_Insert";
            cmd.Parameters.AddWithValue("@CityID", _ENT.CityID);
            cmd.Parameters.AddWithValue("@CityName", _ENT.CityName);
            cmd.Parameters.AddWithValue("@PinCode", _ENT.PinCode);
            return _DBH.ExecuteNonQuery(cmd);
        }
        #endregion

        #region UpdateByPK
        public Boolean UpdateByPK(MST_CityENT _ENT)
        {
            DataBaseHelper _DBH = new DataBaseHelper();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "PR_MST_City_UpdateByPK";
            cmd.Parameters.AddWithValue("@CityID", _ENT.CityID);
            cmd.Parameters.AddWithValue("@CityName", _ENT.CityName);
            cmd.Parameters.AddWithValue("@PinCode", _ENT.PinCode);
            return _DBH.ExecuteNonQuery(cmd);
        }
        #endregion

        #region DeleteByPK
        public Boolean DeleteByPK(SqlInt32 Id)
        {
            DataBaseHelper _DBH = new DataBaseHelper();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "PR_MST_City_DeleteByPK";
            cmd.Parameters.AddWithValue("@CityID", Id);
            return _DBH.ExecuteNonQuery(cmd);
        }
        #endregion

        #region SelectByPK
        public DataTable SelectByPK(SqlInt32 Id)
        {
            DataBaseHelper _DBH = new DataBaseHelper();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "PR_MST_City_SelectByPK";
            cmd.Parameters.AddWithValue("@CityID", Id);
            return _DBH.SelectData(cmd);
        }
        #endregion

        #region SelectAll
        public DataTable SelectAll()
        {
            DataBaseHelper _DBH = new DataBaseHelper();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "PR_MST_City_SelectAll";
            return _DBH.SelectData(cmd);
        }
        #endregion

    }
}

Conclusion :

So, Using this structure, we can separate each & every functionality in .NET project. also, we can easily find any changes or any error with this separated layers. Also, This structure is efficient compare to simple coding or other structure.

 

i Hart
i Hart


This post has been seen 5132 times.

Team Maffat

News Maffat Com is a Free Guest Blogging Website. Must Try once.

Comments are closed.