Welcome

Welcome to CMS n Web. Learn & Study completely Free Articles\Training about Web Designing\Development and CMS.

Search This Web

Showing posts with label 3-Tier Architecture. Show all posts
Showing posts with label 3-Tier Architecture. Show all posts

Friday, January 10, 2014

Create and Implement 3-tier Architecture in ASP.NET (VS 2010)

Introduction
Here, I will explain about the uses of 3-tier architecture and how to create and implement 3-tier architecture for our project in ASP.NET.

What is a Layer?

A layer is a reusable portion of code that performs a specific function.
In the .NET environment, a layer is usually setup 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

DAL contains methods that help business layer to connect the data and perform required action, might be returning data or manipulating data (insertupdatedelete, etc.).

Business Layer

BAL contains business logic, validations or calculations related with 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

Presentation layer contains pages like .aspx or Windows form 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.

Advantages of Three Tier Architecture

The main characteristic of a Host Architecture is that the application and databases reside on the same host computer and the user interacts with the host using an unfriendly and dump terminal. This architecture does not support distributed computing (the host applications are not able to connect a database of a strategically allied partner). Some managers found that developing a host application take too long and it is expensive. Consequently led these disadvantages to Client-Server architecture.
Client-Server architecture is 2-tier architecture because the client does not distinguish between presentation layer and business layer. The increasing demands on GUI controls caused difficulty to manage the mixture of source code from GUI and Business Logic (spaghetti code). Further, Client Server Architecture does not support enough the Change Management. Let's suppose that the government increases the Entertainment tax rate from 4% to 8 %, then in the Client-Server case, we have to send an update to each client and they must update synchronously on a specific time otherwise we may store invalid or wrong information. The Client-Server Architecture is also a burden to network traffic and resources. Let us assume that about five hundred clients are working on a data server, then we will have five hundred ODBC connections and several ruffian record sets, which must be transported from the server to the clients (because the Business layer is stayed in the client side). The fact that Client-Server does not have any caching facilities like in ASP.NET, caused additional traffic in the network. Normally, a server has a better hardware than client therefore it is able to compute algorithms faster than a client, so this fact is also an additional pro argument for the 3-Tier Architecture. This categorization of the application makes the function more reusable easily and it becomes too easy to find the functions which have been written previously. If programmer wants to make further update in the application, then he easily can understand the previous written code and can update easily.
Let's start creating a 3 architecture application:
  1. Create a new project File -> New --> Project.
  2. In Visual C#, select Web 
    (Select ASP.NET Web application name it as: ThreeTierApp)
  3. How to Add Class Library to solution:
    After Clicking on new project, you would see this screen.

  • Select Class Library from this and name it as (BussinessObject):

  • Give the name of Class library as BussinessObject:

  • Add another Class Library to our Project (As the same way you add BussinessObject):
  • Name Class library as Bussinesslogic.
  • After adding, you will see like this view:

  • Adding Last Class library to our project known as Data Access Layer.
  • In the same way, you add BussinessObject.
  • Name the Class library to DataAccess:

After adding your solution would look like this:

Now we have completed Add all layers to our Project.
You can see three tiers in the image given below:

Basically 3-Tier architecture contains 3 layers:
  1. Application Layer or Presentation Layer (our web form and UI Part)
  2. Business Logic Layer (Bussinesslogic)
  3. Data Access Layer (DataAccess)
Here, I will explain each layer with a simple example that is User Registration Form.

Presentation Layer

Here I have Design User Interface for (Presentation Layer):

Here is the design of (Userregistration.aspx):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin: 0px auto; padding-left: 370px; padding-right: 30px; 
                                                            overflow: auto;">
        <div>
            <table width="50%">
                <tr>
                    <td colspan="2" style="background-color: Green; height: 30px; 
                                                     color: White;" align="center">
                        User Registration
                    </td>
                </tr>
                <tr>
                    <td> Name </td>
                    <td>
           <asp:TextBox ID="txtname" Width="150px" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        Address </td>
                    <td>
            <asp:TextBox ID="txAddress" Width="150px" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td> EmailID </td>
             <td>
            <asp:TextBox ID="txtEmailid" Width="150px" runat="server"></asp:TextBox>
             </td>
                </tr>
                <tr>
                    <td> Mobile Number   </td>
                    <td>
            <asp:TextBox ID="txtmobile" Width="150px" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td align="center" colspan="2">
         <asp:Button ID="BtnSave" runat="server" Width="100px" Text="Save"
                                                         OnClick="BtnSave_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
    </form>
</body>
</html>
Now let’s start to create Table for saving this data using (3 tier):
CREATE table Userinfo
(
userid bigint primary key not null identity(1,1),
Name Nvarchar(50),
Address Nvarchar(100),
EmailID Nvarchar(50), 
Mobilenumber varchar(10)
)
Let's start with Business object first.
Delete Class Class1.
Create New class Name (UserBO.cs):

Creating UserBO.cs

Then declare variables in UserBO.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BussinessObject
{
   Public class UserBO // Declare Class Public to Access any where 
    {
        //Declaring User Registration Variables
        private string _Name;
        private string _Address;
        private string _EmailID;
        private string _Mobilenumber;

        // Get and set values

        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
            }
        }

        public string address
        {
            get
            {
                return _Address;
            }

            set
            {
                _Address = value;
            }
        }

        public string EmailID
        {
            get
            {
                return _EmailID; 
            }

            set
            {
                _EmailID = value;
            }
        }

        public string Mobilenumber
        {

            get
            {
               return _Mobilenumber;
            }
            set
            {
                _Mobilenumber = value;
            }
        }
    }
}
Now in the same way as we created UserBO.cs, create New Class UserDA.cs in (DataAccess):

  • In DataAccess
  • We are going to use this layer for commutating with database.
  • All (InsertUpdateDelete, selecting records)
From database is done in this layer.
Now same way as we created UserDA.cs
 Create  New Class  UserBL.cs  in ( Bussinesslogic ) 

Main thing TO DO:
We add three layers:
  • UserBO.cs
  • UserBL.cs
  • UserDA.cs
But they are not interconnected to each other.
Let's connect them.

First Right Click on (DataAccess)

  • Click Add Reference tab
  • Select Project
  • Inside that, you will see all Layer Name.
  • Select (BussinessObject) from that and Click ok

Second Right Click on (Bussinesslogic)

  • Click Add Reference tab
  • Select Project
  • Inside that, you will see all Layer Name.
  • Select (DataAccess) from that and Click ok
Now, rebuild all layers.

Last step

  • Right click on Project add reference
  • Click Add Reference tab
  • Select Project
  • Inside that, you will see all Layer Name.
  • Select all add click ok
Now, build project.  

UserDA.cs (adding Records)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data; // Required for using Dataset , Datatable and Sql
using System.Data.SqlClient; // Required for Using Sql 
using System.Configuration; // for Using Connection From Web.config

using BussinessObject;  // for acessing bussiness object class

namespace DataAccess
{
    public class UserDA
    {
          SqlConnection con = new    
          SqlConnection(ConfigurationManager.ConnectionStrings["Myconstr"].ToString());

        public int AddUserDetails(UserBO ObjBO) // passing Bussiness object Here 
        {
            try
            {
                /* Because We will put all out values from our (UserRegistration.aspx) 
                 To in Bussiness object and then Pass it to Bussiness logic and then to 
                 DataAcess
                 this way the flow carry on*/

             SqlCommand cmd = new SqlCommand("sprocUserinfoInsertUpdateSingleItem", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Name", ObjBO.Name);
                cmd.Parameters.AddWithValue("@Address", ObjBO.address);
                cmd.Parameters.AddWithValue("@EmailID", ObjBO.EmailID);
                cmd.Parameters.AddWithValue("@Mobilenumber", ObjBO.Mobilenumber);

            con.Open();

            int Result = cmd.ExecuteNonQuery();

            return Result;

            con.close(); //closing connection
                
            
            }
            catch
            {
                throw;
            }

            finally
            {

            cmd.Dispose();  

            ObjBO.Dispose(); // disposing object

            }
        }
    }
}

UserBL.cs

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

using DataAccess; // for acessing DataAccess class
using BussinessObject; // for acessing bussiness object class

namespace Bussinesslogic
{
    public class UserBL
    {
      public int SaveUserregisrationBL(UserBO objUserBL) // passing Bussiness object Here 
        {
            try
            {
                UserDA objUserda = new UserDA(); // Creating object of Dataccess

              return objUserda.AddUserDetails(objUserBL); // calling Method of DataAccess 

            }
            catch
            {
                throw;
            }
        }
    }
}
The final output is as follows:

 SELECT * FROM Userinfo


Tuesday, July 16, 2013

3-Tier Architecture in ASP.Net(C#)


Introduction
 Here I will explain about uses of 3-Tier architecture and how to create or implement 3-tier architecture for a project in asp.net
Description
§  What is the use of 3-tier architecture and why we go for that architecture?
§  First we need to know what 3-Tier architecture is.
§  How to create 3-Tier architecture for our project?
 Uses of 3-Tier Architecture
§  To make application more understandable.
§  Easy to maintain, easy to modify application and we can maintain good look of architecture.
§  If we use this 3-Tier application we can maintain our application in consistency manner.  
 Basically 3-Tier architecture contains 3 layers
§  Application Layer or Presentation Layer
§  Business Access Layer (BAL) or Business Logic Layer (BLL)
§  Data Access Layer (DAL)
Designing 3-Tier Architecture 
 Here I will explain each layer with simple example that is User Registration

Fig:1 3-layer architecture
Fig:2 3-layer architecture designed
Application Layer or Presentation Layer
Presentation layer contains UI part of our application i.e., our aspx pages or input is taken from the user. This layer mainly used for design purpose and get or set the data back and forth. Here I have designed my registration .aspx page like this
Fig:3 Presentation layer 

This is Presentation Layer for our project Design your page like this and double click on button save now in code behind we need to write statements to insert data into database this entire process related to Business Logic Layer and Data Access Layer.
 Business Access Layer (BAL) or Business Logic Layer (BLL)
This layer contains our business logic, calculations related with the data like insert data, retrieve data and validating the data. This acts as an interface between Application layer and Data Access Layer.
 Implementation of 3-Tier Architecture 
 We have already finished form design (Application Layer) now I need to insert user details into database if user click on button save. Here user entering details regarding
                                         Login id                           Password                        Confirm Password
                                        First Name                      Last Name                       Email Address             
                                        Birthday                          Gender                                                      
 I need to insert all these 9 parameters to database. Here we are placing all of our database actions into data access layer (DAL) in this case we need to pass all these 9 parameters to data access layers.
 We should place all these parameter into one place. For that reason, right now we will create an entity layer or property layer (DTO-Data Transfer Object). This layer will pass values from application layer to data access layer where we require. And this layer comes under sub group of our Business Logic Layer (BLL).
Right click on your project web application---> select add new item ----> select class file in wizard ---> give name as UserDTO.CS because here I am using this name click ok
 Open the UserDTO.CS class file declare the parameters like this in entity layer.
 Here, I have declared whatever the parameters I need to pass to data access layer I have declared those parameters only.
 UserDTO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 namespace Backend.DTO
{
    public class UserDTO
    {
        private int _id;
        private string _loginId;
        private string _password;
        private string _firstName;
        private string _lastName;
        private DateTime _dateOfBirth;
        private string _gender;
        private string _email;
        private string _userType;
        private DateTime _registeredDate;
        private bool _isActive;
        private string _resetPasswordKey;

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public string LoginId
        {
            get { return _loginId; }
            set { _loginId = value; }
        }
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }
        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
        public DateTime DateOfBirth
        {
            get { return _dateOfBirth; }
            set { _dateOfBirth = value; }
        }

        public string Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }
        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }
        public string UserType
        {
            get { return _userType; }
            set { _userType = value; }
        }
      public DateTime RegisteredDate
        {
            get { return _registeredDate; }
            set { _registeredDate = value; }
        } 
        public bool IsActive
        {
            get { return _isActive; }
            set { _isActive = value; }
        }      
 public string ResetPasswordKey
        {
            get { return _resetPasswordKey; }
            set { _resetPasswordKey = value; }
        }
    }
}

UserBLL.cs
Our parameters declaration is finished now I need to create Business logic layer(BLL) how I have create it follow same process for add one class file now give name called UserBLL.CS.
Here one point don’t forget this layer will act as only mediator between application layer and data access layer based on this assume what this layer contains. Now I am writing the following UserBLL.CS (Business Logic layer)
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Backend.DAL;
using Backend.DTO;

namespace Backend.BLL
{
    public class UserBLL
    {
        private UserDAL userDAL = new UserDAL();

        public string AddUser(UserDTO aUser)
        {
            /* validate business logic */
            if (userDAL.IsLoginIdExist(aUser.LoginId))
            {
return "Login Id already taken by another user. Please try a different one.”
            }

            if (userDAL.IsEmailExist(aUser.Email))
            {
                return "Email Address already exists";
            }

            try
            {
                return userDAL.AddUser(aUser);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool UpdateUser(string field, string value, int id)
        {
            try
            {
                return userDAL.UpdateUser(field, value, id);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void DeleteUser(int deleteId)
        {
            try
            {
                userDAL.DeleteUser(deleteId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
              
    }
}

So, to sum up, a DTO is just a collection of properties (or data members).  It has no validation, no business logic, and no logic of any kind.  It’s just a simple, lightweight data container used for moving data between layers.
 And now we will discuss how this method comes
 return userDAL.AddUser(aUser);
return userDAL.UpdateUser(field, value, id);
Here UserDTO aUser means we already created one class file called UserBEL.CS with some parameters have you got it now I am passing all these parameters to Data access Layer by simply create one object for our UserDTO class file
 What is about these statements I will explain about it in data access layer

UserDAL userDAL = new UserDAL();
DAL objUserDAL = new DAL();
return userDAL.AddUser(aUser);

This DAL related our Data access layer. Check below information to know about that function and Data access layer
Data Access Layer (DAL)

Data Access Layer contains methods to connect with database and to perform insert, update, delete, get data from database based on our input data
 I think it’s too much data now directly I will enter into DAL
 Create one more class file like same as above process and give name as UserDAL.CS
 Write the following code in DAL class file
 UserDAL.CS
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using Backend.DTO;
using System.Data;
namespace Backend.DAL
{
    class UserDAL
    {
        private SqlConnection sqlConnection;

        public UserDAL()
        {
            DbConn aConn = new DbConn();
            sqlConnection = aConn.GetUssdSqlConnection;
        } 
        public string AddUser(UserDTO aUser)
        {
            int insertId = 0;
             try
            {
                sqlConnection.Open();
string sql = "INSERT INTO Users(LoginId, Password, FirstName, LastName, DateOfBirth, Gender, Email, UserType, RegisteredDate, IsActive) " +"VALUES(@loginId, @password, @firstName, @lastName, @dateOfBirth, @gender, @email, @userType, @registeredDate, @isActive)";          
SqlCommand command = new SqlCommand(sql, sqlConnection);
command.Parameters.AddWithValue("loginId", aUser.LoginId);
command.Parameters.AddWithValue("password", aUser.Password);
command.Parameters.AddWithValue("firstName", aUser.FirstName);
command.Parameters.AddWithValue("lastName", aUser.LastName
command.Parameters.AddWithValue("dateOfBirth", aUser.DateOfBirth); 
command.Parameters.AddWithValue("gender", aUser.Gender);               
command.Parameters.AddWithValue("email", aUser.Email);
command.Parameters.AddWithValue("userType", aUser.UserType);
command.Parameters.AddWithValue("registeredDate", aUser.RegisteredDate);
command.Parameters.AddWithValue("isActive", aUser.IsActive);
                 insertId = command.ExecuteNonQuery();
                if (insertId > 0)
                {
                    return "success";
                }
                else
                {
                    return "Unknown error occourd.";
                }
            }
            catch (SqlException sqlException)
            {
                throw sqlException;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
      if (sqlConnection.State != ConnectionState.Closed)
                {
                    sqlConnection.Close();
                }
            }
        }
public bool UpdateUser(string field, string value, int id)
        {           
           try
            {
                sqlConnection.Open();

SqlCommand command = new SqlCommand("UPDATE Users SET " + field + " = @resetPasswordKey WHERE Id=@userId", sqlConnection);

command.Parameters.AddWithValue("resetPasswordKey", value);
         
command.Parameters.AddWithValue("userId", id);
          
command.ExecuteNonQuery();
                 return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sqlConnection.State !=
                    ConnectionState.Closed)
                {
                    sqlConnection.Close();
                }
            }
        }    
 public void DeleteUser(int deleteId)
        {
            try
            {
                sqlConnection.Open();

SqlCommand command = new SqlCommand("DELETE FROM Users WHERE Id = @id", sqlConnection);
        command.Parameters.AddWithValue("id", deleteId);
        command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
if (sqlConnection.State != ConnectionState.Closed)
                {
                    sqlConnection.Close();
                }
            }
        }     
        }
    }

Here if you observe above functionality I am getting all the parameters by simply creating DTO UserDTO aUser.
If we create one entity file we can access all parameters throughout our project by simply creation of one object for that entity class based on this we can reduce redundancy of code and increase re usability.
Observe above code have u seen this function before?
In UserBLL.CS I said I will explain it later got it in UserDAL.CS I have created one function
public string AddUser(UserDTO aUser)
and using this one in UserBLL.CS by simply creating one object of DAL in UserBLL.CS.
Here you will get one doubt that is why BLL.CS we can use this DAL.CS directly into our code behind  we already discuss Business logic layer provide interface between DAL and Application layer by using this we can maintain consistency to our application.
Now our Business Logic Layer is ready and our Data access layer is ready now how we can use this in our application layer write following code in your save button click like this.
protected void RegisterUserButton_Click(object sender, EventArgs e)
        {
            string loginId = txtLoginId.Text();
            string password = txtPassword.Text();
            string confirmPassword =
txtConfirmPassword.Text();
            string firstName = txtFirstName.Text();
            string lastName = txtLastName.Text();
            DateTime dateOfBirth;
            string email = txtEmail.Text();
            int month =
Convert.ToInt32(ddlMonth.SelectedItem.Value);
            int day =
Convert.ToInt32(ddlDay.SelectedItem.Value);
            int year =
Convert.ToInt32(ddlYear.SelectedItem.Value);
            string gender = string.Empty;
            bool isActive = false;
            string userType = "User";

            if (rdoGenderMale.Checked)
{
gender = rdoGenderMale.Text;
}
            else if (rdoGenderFemale.Checked)
{
gender = rdoGenderFemale.Text;
}

            if (rdoIsActiveYes.Checked)
{ isActive = true; }
            else if (rdoIsActiveNo.Checked)
{ isActive = false; }

if (loginId == string.Empty || password ==
string.Empty || confirmPassword ==
string.Empty || firstName == string.Empty
|| lastName == string.Empty || email ==
string.Empty)
            {
                AlertError.InnerText = "Required field
cannot be empty";
                AlertError.Visible = true;
                return;
            }

            if (password != confirmPassword)
            {
AlertError.InnerText = "Confirm Password does not match with Password";
                AlertError.Visible = true;
                 return;
            }

            try
            {
               dateOfBirth  = Convert.ToDateTime(year + "-
" + month + "-" + day);
            }
           


catch (Exception ex)
            {
                AlertError.InnerText = ex.Message;
                AlertError.Visible = true;
                return;
            }

            UserDTO newUser = new UserDTO();
            newUser.LoginId = loginId;
            newUser.Password = password;
            newUser.FirstName = firstName;
            newUser.LastName = lastName;
            newUser.DateOfBirth = dateOfBirth;
            newUser.Gender = gender;
            newUser.Email = email;
            newUser.UserType = userType;
            newUser.RegisteredDate = DateTime.Now;
            newUser.IsActive = isActive;

            try
            {
                UserBLL aUserBll = new UserBLL();
                string userAddResult =
aUserBll.AddUser(newUser);

                if (userAddResult != "success")
                {
                    AlertError.InnerText = userAddResult;
                    AlertError.Visible = true;
                    return;
                }
                else
                {
                    AlertSuccess.InnerText = "User
registered successfully.";
                    AlertSuccess.Visible = true;
                    ClearRegisterUserForm();
                    return;
                }
            }
catch (Exception ex)
            {
                AlertError.InnerText = ex.Message;
                AlertError.Visible = true;
                return;
            }
        }
Here if you observe I am passing all parameters using this DTO (Entity Layer) and we are calling the method AddUser(UserDTO aUser) by using this BLL(Business Logic Layer)
Conclusion
By using 3-Tier architecture in your project you can achieve
  • Separation - the functionality is separated from the data access and presentation so that it is more maintainable
  •  Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
  •   Re usability - As the layers are separated, it can exist as a module that can be reused by other application by referencing it.
 Hope this article helped you understanding 3-Tier architecture and designing it.
References