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 LayerPresentation 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 okOpen 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; }
}
}
}
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
Hope this article helped you understanding 3-Tier architecture and designing it.
References
|
Welcome
Welcome to CMS n Web. Learn & Study completely Free Articles\Training about Web Designing\Development and CMS.
Search This Web
Tuesday, July 16, 2013
3-Tier Architecture in ASP.Net(C#)
Labels:
3-Tier Architecture,
Asp.net,
C#