File - ALL IN ONE @ EVERYTHING UNDER ONE ROOF

advertisement
Programming Implementation in level based [1-Tire/2-Tire/3Tire…n-Tire]
In general when we work or develop with any application that is related to
database will contain the 3 types of code.
 UI Design & validation code
 Business Logic code
 Data Access Code
1.) UI Design & validation code: This code is related to user interface controls
like TextBoxs, Buttons, RadioButtons, ListBoxes,etc..
In general this code will change based on the type of Application like Console
Application, Windows Application, or Web Application or Mobile Applications.
2.) Business Logic code: This code is related to the type of business that been
Computerise.
Based on logic of this business ,the complete logic code will be changing.
Ex:-This code is like searching the data based on EmpId.
3.) Data Access Code: This code is purely related with interacting with Database
that is getting the data from database and updating the data from database.
This code will be change based on the database & providers that is used to
connect with the database.
 I-Tire Architecture: In general in any front end application if all these three
types of code are present in single application. Then, it’s known as I-Tire
Architecture.
 Take the Design as bellow.
.aspx Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TwoTire.aspx.cs"
Inherits="TwoTire" %>
<!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 runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 100%;
}
.style4
{
width: 151px;
}
.style3
{
width: 139px;
}
</style>
</head>
<body>
<form id="form2" runat="server">
<div>
<table class="style1">
<tr>
<td align="right" class="style4">
Enter EId:</td>
<td class="style3">
<asp:TextBox ID="txtEno" runat="server"></asp:TextBox>
</td>
<td rowspan="6">
<asp:GridView ID="GridView1" runat="server" Height="128px" Width="468px">
</asp:GridView>
<br />
<asp:Label ID="lbldisplay" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right" class="style4">
Enter EmpName:</td>
<td class="style3">
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="style4">
Salary:</td>
<td class="style3">
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="style4">
DeptNo:</td>
<td class="style3">
<asp:TextBox ID="txtDeptno" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="style4">
<asp:Button ID="btnInsert" runat="server" onclick="btnInsert_Click"
Text="Insert" />
</td>
<td class="style3">
<asp:Button ID="btnFind" runat="server" onclick="btnFind_Click"
Text="Find" />
</td>
</tr>
<tr>
<td align="right" class="style4">
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
</td>
<td class="style3">
<asp:Button ID="btnDelete" runat="server" onclick="btnDelete_Click"
Text="Delete" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
.aspx.cs Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class OneTire : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("server=.;user id=sa;password=abc;database=test");
SqlCommand cmd;
SqlDataAdapter da;
SqlDataReader dr;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
get();
}
public DataSet get()
{
string query = "select * from Employee";
cmd = new SqlCommand(query, con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
return ds;
}
protected void btnInsert_Click(object sender, EventArgs e)
{
string s = "insert into Employee values(@Eno,@Ename,@Salary,@DeptNo)";
cmd = new SqlCommand(s, con);
con.Open();
cmd.Parameters.AddWithValue("@Eno", txtEno.Text);
cmd.Parameters.AddWithValue("@Ename", txtEmpName.Text);
cmd.Parameters.AddWithValue("@Salary", txtSalary.Text);
cmd.Parameters.AddWithValue("@DeptNo", txtDeptno.Text);
int i=cmd.ExecuteNonQuery();
if (i > 0)
{
lbldisplay.Text = "Record Inserted";
}
else
lbldisplay.Text = "Record not inserted";
con.Close();
get();
}
protected void btnFind_Click(object sender, EventArgs e)
{
string s = "select EName,Salary,DeptNo from Employee where Eno=@Eno";
cmd = new SqlCommand(s, con);
con.Open();
cmd.Parameters.AddWithValue("@Eno", txtEno.Text);
dr = cmd.ExecuteReader();
if (dr.Read())
{
txtEmpName.Text = dr[0].ToString();
txtSalary.Text = dr[1].ToString();
txtDeptno.Text = dr[2].ToString();
}
else
lbldisplay.Text = "Record not Found";
con.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string s = "update Employee set EName=@Ename,Salary=@Salary,DeptNo=@DeptNo
where Eno=@Eno";
cmd = new SqlCommand(s, con);
con.Open();
cmd.Parameters.AddWithValue("@Eno", txtEno.Text);
cmd.Parameters.AddWithValue("@Ename", txtEmpName.Text);
cmd.Parameters.AddWithValue("@Salary", txtSalary.Text);
cmd.Parameters.AddWithValue("@DeptNo", txtDeptno.Text);
int i=cmd.ExecuteNonQuery();
if (i > 0)
{
lbldisplay.Text = "Record Updated";
}
else lbldisplay.Text = "Record is not Updated";
con.Close();
get();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string s = "delete from Employee where Eno=@Eno";
con.Open();
cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("@Eno", txtEno.Text);
int i=cmd.ExecuteNonQuery();
if (i > 0)
{
lbldisplay.Text = "Record deleted";
}
else
lbldisplay.Text = "record not found";
get();
}
}
OutPut:
 II-Tire Architecture:
 If all the three types of code that is UI Design & Validations code, Business
Logic code and Data Access Code in front code is divided into two parts or
two layers. Then it’s known as II-Tire Architecture.
First layer developed using Console Application / Windows Form
Applications / Web / Mobile Applications.
Second layer is developed using .Net components / Web Services / WCF
services.





 Take the Design as bellow.
Step 1:open asp.net webapplication and rename it as
Two TierExample
Step2:-Design webform1.aspx like below
Step3:-add class library project BALDAL
Step4:-rename class1.cs as TwoTier.cs
Step5:-write the below code TwoTier.cs
using System.Data;
using System.Data.SqlClient;
namespace BALDAL
{
public class TwoLayer
{
public TwoLayer()
{
//
// TODO: Add constructor logic here
//
}
SqlConnection con = new SqlConnection("server=.;user
id=sa;password=abc;database=test");
SqlCommand cmd;
SqlDataAdapter da;
SqlDataReader dr;
DataSet ds;
public DataSet get()
{
string query = "select * from Employee";
cmd = new SqlCommand(query, con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
return ds;
}
int eno, deptno;
string ename, salary;
public int peno { set { eno = value; } get { return eno; } }
public int pdeptno { set { deptno = value; } get { return eno; } }
public string pename { set { ename = value; } get { return ename; } }
public string psalary { set { salary = value; } get { return salary; } }
public int insertrec()
{
string s = "insert into Employee values(@Eno,@Ename,@Salary,@DeptNo)";
cmd = new SqlCommand(s, con);
con.Open();
cmd.Parameters.AddWithValue("@Eno", eno);
cmd.Parameters.AddWithValue("@Ename", ename);
cmd.Parameters.AddWithValue("@Salary", salary);
cmd.Parameters.AddWithValue("@DeptNo", deptno);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public SqlDataReader findrec()
{
string s = "select EName,Salary,DeptNo from Employee where Eno=@Eno";
cmd = new SqlCommand(s, con);
con.Open();
cmd.Parameters.AddWithValue("@Eno", eno);
dr = cmd.ExecuteReader();
return dr;
}
public int deleterec()
{
string s = "delete from Employee where Eno=@Eno";
con.Open();
cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("@Eno", eno);
int i = cmd.ExecuteNonQuery();
return i;
}
public int updaterec()
{
string s = "update Employee set
EName=@Ename,Salary=@Salary,DeptNo=@DeptNo where Eno=@Eno";
cmd = new SqlCommand(s, con);
con.Open();
cmd.Parameters.AddWithValue("@Eno", eno);
cmd.Parameters.AddWithValue("@Ename", ename);
cmd.Parameters.AddWithValue("@Salary", salary);
cmd.Parameters.AddWithValue("@DeptNo", deptno);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
}
}
Step7:adding reference of BALDAL
Step8: .aspx.cs
using System.Data.SqlClient;
using System.Data;
namespace TwoTierApplication
{
public partial class WebForm1 : System.Web.UI.Page
{
BALDAL.TwoLayer obj=new BALDAL.TwoLayer();
protected void Page_Load(object sender, EventArgs e)
{
GDget();
}
public void GDget()
{
DataSet ds = obj.get();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
obj.pename = txtEmpName.Text;
obj.psalary = txtSalary.Text;
obj.pdeptno = Convert.ToInt32(txtDeptno.Text);
int s=obj.insertrec();
if (s > 0)
{
lbldisplay.Text = "Record Inserted";
}
else
{
lbldisplay.Text = "Record not Inserted";
}
GDget();
}
protected void btnFind_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
SqlDataReader dr=obj.findrec();
if (dr.Read())
{
txtEmpName.Text = dr[0].ToString();
txtSalary.Text = dr[1].ToString();
txtDeptno.Text = dr[2].ToString();
}
else
{
lbldisplay.Text = "Record not found";
}
dr.Close();
GDget();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
obj.pename = txtEmpName.Text;
obj.psalary = txtSalary.Text;
obj.pdeptno = Convert.ToInt32(txtDeptno.Text);
int s = obj.updaterec();
if (s > 0)
{
lbldisplay.Text = "Record updated";
}
else
{
lbldisplay.Text = "Record not updated";
}
GDget();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
int s = obj.deleterec();
if (s > 0)
{
lbldisplay.Text = "Record deleted";
}
else
{
lbldisplay.Text = "Record not deleted";
}
GDget();
}
}
}
 III-Tire Architecture: In this method total front end will be divided into 3
parts .
 First layer will contain the UI Design & validations code is known as
Presentation layer.
 Second layer will contain the Business Logic code and is known as
Business Logic Layer.
 Third Layer will contain the Data Access Code and is known as Data
Access Layer.
In general in III-Tire Architecture Presentation layer is always interact with
Business Logic layer only, Business Logic layer is interact with Data Access
Layer. The Data Access Layer is always interact with Database.
Step1:open asp.net webapplication rename it as ThreeTierApplication
Step2:-Design webform1.aspx
Step3:-add class library project rename it as DAL
Step4:-rename class1.cs as DALClass.cs
Note:-Stored procedure which we are using :
Stored procedure for InsertRec
Create proc InsertRec (
@Eno int,@Ename varchar(50),@Salary varchar(50),@Deptno int)
as
begin
insert into Employee values(@Eno,@Ename,@Salary,@Deptno)
end
Stored procedure for FindRec
create proc FindRec(
@Eno int)
as
begin
select
end
EName,Salary,DeptNo from Employee where Eno=@Eno
Stored procedure for UpdateRec
create proc UpdateRec (
@Eno int,@Ename varchar(50),@Salary varchar(50),@Deptno int)
as
begin
update Employee set EName=@Ename,Salary=@Salary,DeptNo=@Deptno where Eno=@Eno
end
Stored procedure for DeleteRec
create proc DeleteRec (
@Eno int)
as
begin
delete from Employee where Eno=@Eno
end
Step5:- DALClass.cs code
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
public class DALClass
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
SqlDataAdapter da;
SqlDataReader dr;
DataSet ds;
SqlCommand cmd;
public DataSet get()
{
string query = "select * from Employee";
cmd = new SqlCommand(query, con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
return ds;
}
public int insertrec(int eno,string ename,string salary,int deptno)
{
cmd = new SqlCommand("InsertRec", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Eno", eno);
cmd.Parameters.AddWithValue("@Ename", ename);
cmd.Parameters.AddWithValue("@Salary", salary);
cmd.Parameters.AddWithValue("@DeptNo", deptno);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public SqlDataReader findrec(int eno)
{
cmd = new SqlCommand("FindRec", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("@Eno", eno);
dr = cmd.ExecuteReader();
return dr;
}
public int deleterec(int eno)
{
con.Open();
cmd = new SqlCommand("DeleteRec", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Eno", eno);
int i = cmd.ExecuteNonQuery();
return i;
}
public int updaterec(int eno, string ename, string salary, int deptno)
{
cmd = new SqlCommand("UpdateRec", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("@Eno", eno);
cmd.Parameters.AddWithValue("@Ename", ename);
cmd.Parameters.AddWithValue("@Salary", salary);
cmd.Parameters.AddWithValue("@DeptNo", deptno);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
}
}
Step3:-add class library project rename it as BLL
Step4:-rename class1.cs as BLLClass.cs
Step5:-add DAL reference to BLL
Step6:- BLLClass.cs code
using System.Data;
using System.Data.SqlClient;
namespace BLL
{
public class BLLClass
{
DAL.DALClass obj = new DAL.DALClass();
int eno, deptno;
string ename, salary;
public int peno { set { eno = value; } get { return eno; } }
public int pdeptno { set { deptno = value; } get { return eno; } }
public string pename { set { ename = value; } get { return ename; } }
public string psalary { set { salary = value; } get { return salary; } }
public DataSet gett()
{
DataSet ds = obj.get();
return ds;
}
public int insert()
{
int i;
i = obj.insertrec(eno, ename, salary, deptno);
return i;
}
public SqlDataReader find()
{
SqlDataReader dr;
dr = obj.findrec(eno);
return dr;
}
public int delete()
{
int i;
i = obj.deleterec(eno);
return i;
}
public int update()
{
int i = obj.updaterec(eno, ename, salary, deptno);
return i;
}
}
}
Step 7:-adding BLL reference to ThreeTierApplication
Step8:-.aspx.cs code
using System.Data;
using System.Data.SqlClient;
namespace ThreeTierAppliction
{
public partial class WebForm1 : System.Web.UI.Page
{
BLL.BLLClass obj = new BLL.BLLClass();
protected void Page_Load(object sender, EventArgs e)
{
GDget();
}
public void GDget()
{
DataSet ds = obj.gett();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
obj.pename = txtEmpName.Text;
obj.psalary = txtSalary.Text;
obj.pdeptno = Convert.ToInt32(txtDeptno.Text);
int i = obj.insert();
if (i > 0)
{
lbldisplay.Text = "Record Inserted";
}
else
{
lbldisplay.Text = "Record not Inserted";
}
GDget();
}
protected void btnFind_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
SqlDataReader dr = obj.find();
if (dr.Read())
{
txtEmpName.Text = dr[0].ToString();
txtSalary.Text = dr[1].ToString();
txtDeptno.Text = dr[2].ToString();
}
else
{
lbldisplay.Text = "Record not found";
}
dr.Close();
GDget();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
obj.pename = txtEmpName.Text;
obj.psalary = txtSalary.Text;
obj.pdeptno = Convert.ToInt32(txtDeptno.Text);
int s = obj.update();
if (s > 0)
{
lbldisplay.Text = "Record updated";
}
else
{
lbldisplay.Text = "Record not updated";
}
GDget();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
obj.peno = Convert.ToInt32(txtEno.Text);
int s = obj.delete();
if (s > 0)
{
lbldisplay.Text = "Record deleted";
}
else
{
lbldisplay.Text = "Record not deleted";
}
GDget();
}
}
}
This article explains how to create and implement a 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 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.
Advantages of a 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 dumb terminal. This architecture
does not support distributed computing (the host applications are unable to connect to a database of a
strategically allied partner). Some managers find that developing a host application takes too long and it
is expensive. These disadvantages consequently led to a Client-Server architecture.
A Client-Server architecture is a 2-Tier architecture because the client does not distinguish between
Presentation Layer and Business Layer. The increasing demands on GUI controls caused difficulty in
managing the mixture of source code from a GUI and the Business Logic (Spaghetti Code). Further, the
Client Server Architecture does not support enough the Change Management. Let us suppose that the
government increases the Entertainment tax rate from 4% to 8 %, then in the Client-Server case, we need
to send an update to each client and they must update synchronously on a specific time otherwise we
may store invalid or incorrect 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, that must be transported from
the server to the clients (because the Business Layer remains in the client side). The fact that Client-Server
does not have any caching facilities like in ASP.NET causes additional traffic in the network. Normally, a
server has better hardware than the client, therefore it is able to compute algorithms faster than a client,
so this fact is also an additional argument in favor of the 3-Tier Architecture. This categorization of the
application makes the function more reusable easily and it becomes too easy to find the functions that
have been written previously. If a programmer wants to make further updates in the application then he
can easily understand the previous written code and can update it easily.
Let's start creating a 3-Tier Architecture Application.
1. Create a new project using "File" -> "New" -> "Project...".
2. In Visual C# select "Web".
(Select "ASP.NET Web application" and name it’s as: ThreeTierApp)
3. How to add class library to solution:
After clicking on a new project you would see the following screen.

Select "Class Library" from this and name it "BussinessObject".

Provide the name of the Class library as "BussinessObject".

Add another Class Library to our project.
(In the same way as you added a BussinessObject.)


Name the Class library "Bussinesslogic".
After adding you will see as in this view.



Add the last Class Library to our project called "Data Access Layer".
In the same way as you added BussinessObject.
Name the Class Library "DataAccess".
After adding, your solution would look like this:
Now we are done. Add all layers to our project.
You can see the three tiers in the image given below.
Basically a 3-Tier architecture contains the following 3 layers:
1.
2.
3.
Application Layer or Presentation Layer (our web form and UI Part)
Business Logic Layer (Bussinesslogic)
Data Access Layer (DataAccess)
Here I will explain each layer with a simple example that is a User Registration Form.
Presentation Layer
Here, I have designed a user interface for the Presentation Layer.
Here is the design of "Userregistration.aspx":
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" 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 a table for saving this data using our 3-Tier Architecture.
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 a bussiness object first, as in the following:
Delete Class Class1
Create a new class name, "UserBO".
Creating UserBO.cs
Then declare variables in UserBO as in the following:
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, create a new class, UserDA, in DataAccess.



In Dataaccess
We will use this layer for communicating with the database
All operations (insert , update, delete and selecting records) for the database is done in this layer.
Now in the same way as we created UserDA:
Create New Class UserBL.cs in ( Bussinesslogic )
The main thing TO DO
The main thing to do nest is to add the three layers:



UserBO.cs
UserBL.cs
UserDA.cs
But they are not inter connected to each other.
Let's connect them.
DataAccess connections
First right-click on DataAccess then:




Click the "Add Reference" tab
Select "Project"
Inside that you will see all Layer Name
Select BussinessObject from that and click "Ok"
Bussinesslogic connections
Then right-click on Bussinesslogic then:


Click the "Add Reference" tab
Select "Project"


Inside that you will see all Layer Name.
Select DataAccess from that and click "Ok"
New rebuild all layers.
Last step





Right-click on the project and select "Add references"
Click the "Add Reference" tab
Select "Project"
Inside that you will see all Layer Name.
Select all add thn click "Ok"
Now build the 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();
cmd.Dispose();
return Result;
}
catch
{
throw;
}
}
}
}
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;
}
}
}
}
Final Output
SELECT * FROM Userinfo
1st round Hr- duration 10-12 mins
1. Brief out your profile ?
2. Why did u leave your previous company and Work experience related questions ?
2nd round by Tech Lead - 50-55 mins
Tech Lead : Before i start tell me how much do you rate yourself in the key skills which you've
mentioned in your resume
Faizanc# = 3.5/5
asp.net =3/5
sql server = 3.5/5
Wcf = 2.5/5
Html/css = 3/5
Tech Lead :
1.describe the architecture of ur latest project?
2.default time out for connection string ?
3.How will u handle exceptions in stored procedure?
4.WAP to sort an array ?
5. how will you use stored procedures.. write an example ?
7.Difference between interfaces and abstract classes ?
8.authorization and authentication? and its types ? what is forms authentication.. can you write
the code for the forms authentication now?
9.OOPS features...while explaining features i came to the encapsulation and when i said we can
achieve 100% encapsulation using the keyword called class then he asked me "cant we achieve
100% encapsulation using structs" ?
10. different types of cursors ?
11. Show one example using querry string ? have you used in your project ?
12.how will you register public assembly under gac? can you register private assemble under gac
?
13. difference between webform and webgarden ?
14. do u have any idea about rowid in oracle and sql server ?
15.what is application pooling and its types ?
16. What are third party controls and have you used that in your project ?
17. indexes ? different types of indexes ? where do we create indexes ?
18. how will you deploy a website ?
19. Page life cycle events ?
20. What are end points ? types of hosting ?
21. Difference between webservice and Wcf ? Which is better to use Web service or Wcf ?
Where have you used Webserice and Wcf in your project?
22. Difference between Primary key and unique key ?
23. Steps to consume Wcf service ?
Tech lead:Well we were good Do you have any questions to ask now
I was asked to wait outside for 20 mins and then they called me for the final round of Project
Manager
3rd round By Project Manager : duration 30-35 mins
1. Why did you leave Wipro ? Its such a good company ?
2. What are the pages which you've developed in your last two projects just write it down the
names of the pages
3. He asked me to draw the 6 screens on the paper which he selected ?
4. What are OOPS features ?
5.do you have any DEPLOYMENT EXPERIENCE ?
6. Page life cycle ?
7. what are the options available on visual studio sdk ?
8.Difference between interface and abstract class ? in which scenario we go for interface and
abstract classes ? give me examples ?
9. How will you review the code ?
10. Have you created Unit tests ?
11. Difference between the page with ajax and page without ajax ?
12.How will you remove unused namespaces from the project ?
What Is Multi-Tier Architecture, And Why Do We Care?
Multi-tier (or n-tier) architecture refers to the practice of separating an application into layers.
Doing so makes it easier for you and other developers to re-use your code. Typically, a multitier application will be broken into three layers:



Data Access Layer (DAL): This layer contains all the code that interacts with the data
store used by the application. For example, if your data store is a typical RDBMS like
Sql Server or Oracle, the data access layer will contain the code that calls the stored
procedures in your database to perform reads and writes (or if you don't use stored
procedures, the data access layer may contain your SQL code).
Business Logic Layer (BLL): This layer contains all the code that implements your
application's business rules. It makes calls to the DAL, usually on behalf of the
Presentation Layer (see below). The BLL typically contains code that operates on the
data received from the DAL prior to passing it back to the Presentation Layer for display
to the user. For example, the BLL may perform calculations based on data retrieved from
the DAL to be displayed along with the actual data.
Presentation Layer: This layer typically reads and writes to the BLL. The Presentation
Layer is responsible for taking the data it receives from the BLL, formatting it, and
displaying it to the user. It is also responsible for collecting user-entered data and
conveying it to the BLL for further processing. In the .NET world, the Presentation
Layer is typically created with either ASP.NET Web Forms, Windows Forms, or more
recently WPF (Windows Presentation Foundation).
Dividing an application's code in this manner allows us to take advantage of distributed
deployment. For example, you could deploy your Data Access Layer to a data server, your
Business Logic Layer to an application server, and your Presentation Layer to a web server
(assuming it was a web-based GUI). Later, should you decide to create a Windows GUI client
that consumes the same Business Logic Layer component, you could deploy that client to your
users' desktops and reference the Business component on the application server. In addition, a
distributed, multi-tiered application is much more likely to scale for future growth.
How We'll Go About It
We will be creating three Visual Studio projects, all within the same solution for simplicity's
sake. The application we create will read and write to database tables which contain information
on car manufacturer's, makes, and models. Figure 1 shows the structure and relationships of the
three tables involved. You should create these tables for yourself, and when doing so, don't
forget to specify Primary Keys for each table as indicated in the diagram:
Figure 1
I've pre-populated each table as shown in Figure 2, Figure 3, and Figure 4:
Figure 2: Manufacturer table
Figure 3: Make table
Figure 4: Model table
You will need to set these tables up in your database in order to play along with us during the
creation of the application. The data doesn't have to match exactly, but the structures of each
table does. Also, when entering data, keep in mind the relationships between the tables as shown
in Figure 1 above.
As mentioned earlier, our goal is to create a multi-tier application consisting of a Data Access
Layer, a Business Logic Layer, and a Presentation Layer. There will be absolutely no direct
communication between the Presentation Layer and the Data Access Layer. Furthermore, the
Data Access Layer will be totally unaware of the Business Logic Layer, and the Business Logic
Layer will be totally unaware of the Presentation Layer. In this way (as it should always be in
multi-tier architecture), each of the layers should be able to support any .NET client. For
example, although our Presentation Layer will be web-based, once this application is finished,
you will be able to create a new Presentation Layer in Windows Forms (or WPF, for that matter)
that can consume the Business Logic Layer we will be building (which in turn will consume the
Data Access Layer).
When we are finished building our application, it will allow us to perform maintenance on the
three tables above. It will also contain a reporting function which will enable a user to display a
list of all models in the system, including the Manufacturer Name, Make Name, Model Name,
and Model Year.
Let's Do It
OK, so start off by creating a new solution in Visual Studio, and call it "Cars". (As I mentioned
at the top of the article, I'm assuming you know your way around Visual Studio, so I'm not going
to take you through creating solutions and projects within Visual Studio. If you don't know how
to do that already, please take advantage of the documentation and videos on Microsoft's web
site to familiarize yourself with these procedures.)
Developing the Data Access Layer
Within the Cars solution, create a new Class Library project and call it "CarsDAL". This project
is where we will develop our Data Access Layer. Once the project is created, delete the
Class1.cs file that gets created by default as we won't be needing it. (I told you there wasn't
going to be much coding at the beginning, see?) Then, create a new folder named App_Code in
the project.
Right click on the App_Code folder, add a new DataSet, and name it "CarsDataSet". Once the
DataSet is added, a Table Adapter Design Window will open. Right click anywhere within the
TableAdapter Design Window, the click on Add, then TableAdapter from the popup menu. This
will launch the TableAdapter Configuration Wizard. We will now create our first TableAdapter,
the Manufacturer TableAdapter, by taking the following steps:




On the first page of the TableAdapter Configuration Wizard, choose your data
connection, which should point to the "Cars" database schema you created in preparation
earlier, then click Next.
The next page asks you to choose a Command Type. For the purposes of this article we
will choose the option that says, "Create New Stored Procedures". Then click Next.
On the next screen, click the Query Builder button, which will load the Query Builder
window. The Add Table dialog box is displayed. Select Manufacturer, then click the
Add button, and then close the Add Table dialog box. In the Manufacturer table now
displayed in the top frame of the Query Builder window, check each of the fields. Leave
the "*(All Columns)" checkbox unchecked. Then click OK in the Query Builder
window, and click Next to advance the TableAdapter Configuration Wizard.
In the next screen you are asked to name the four stored procedures that will be created
for you for the Manufacturer TableAdapter. (That's right, you don't need to create them
yourself, Visual Studio does it for you.) Change the default names so that the four stored






procedures are named Manufacturer_s, Manufacturer_i, Manufacturer_u, and
Manufacturer_d, for Select, Insert, Update, and Delete respectively. Click Next.
The next screen is the Choose Methods screen. We're going to uncheck the "Fill A
DataTable" checkbox, and leave "Return A DataTable" and "GenerateDBDirectMethods"
checkboxes checked. Also, in the text field under the "Return A DataTable" checkbox,
change the method name to GetManufacturerData. Click Next.
The Wizard Results screen will list all of the procedures and methods that were generated
for you. Look these over, then click Finish.
When the TableAdapter Configuration Wizard closes, you should see the Manufacturer
TableAdapter represented in the TableAdapter Design Window. It should contain two
sections; the Manufacturer section which lists the fields, and the
ManufacturerTableAdapter section which lists the queries available in the TableAdapter.
If you recall, we only created one query for this TableAdapter, called
GetManufacturerData(), which returns all of the rows in the Manufacturer table. It's a
good idea to create one more query which we will call GetManufacturerDataById(), so
that we can load a particular Manufacturer record if necessary. This query is going to
accept the MfrId as a parameter. We'll create it as follows:
Right click on the bottom half of the Manufacturer TableAdapter, anywhere in the
ManufacturerTableAdapter section. Choose Add Query from the popup menu, and you
will be presented with the TableAdapter Query ConfigurationWizard. Choose "Create
New Stored Procedure", then click Next.
On the Query Type screen choose the first option, "SELECT which returns rows", then
click Next.
In the Generate Stored Procedure screen, you can use the Query Builder, or you can
manually type in your query. It should end up looking like this:
SELECT MfrId, MfrName, Created_Date FROM Manufacturer WHERE (MfrId =
@MfrId)




Then click Next. On the Create Stored Procedure screen, name the stored procedure
"Manufacturer_By_Id_s", then click Next.
On the Choose Methods screen, uncheck the "Fill A DataTable" checkbox and leave the
"Return A DataTable" checkbox checked. Change the name of the method to
"GetManufacturerDataById", then click Next.
The Wizard Results screen will list all of the procedures and methods that were generated
for you. Look these over, then click Finish.
You should now see the Manufacturer TableAdapter represented in the TableAdapter
Design Window with the new method included.
Now, repeat each of those steps for the Make table, and then again for the Model table. Be sure
to create "ById" queries and methods for each table, passing the appropriate field (MakeId and
ModelId) and naming each query correctly depending on the table you're dealing with. When
you're done, there is just one more step and we'll be done with the Data Access Layer.
OK, now we need to create just one more TableAdapter in the DAL. As before, right click on
any empty area within the TableAdapter Design Window, and click Add, and then TableAdapter
in the popup menu. This will load the TableAdapter Configuration Wizard one more time:



Choose your Cars connection string, then click Next.
Choose Create New Stored Procedures, then click Next.
In the Query Builder window, either click the Query Builder button or manually type
your SQL query. Either way, it should look pretty much like this when you're done:
SELECT Manufacturer.MfrName, Make.MakeName, Model.ModelName,
Model.ModelYear FROM Model INNER JOIN Make ON Model.MakeId =
Make.MakeId INNER JOIN Manufacturer ON Make.MfrId = Manufacturer.MfrId



Then click Next. In the Create Stored Procedures screen, change the name of the Select
query to "ModelReport_s". The rest of the queries won't matter since you can't insert,
update, or delete when joining tables as we did with this query. Visual Studio is smart
enough to recognize this and doesn't actually create these queries regardless of what you
name them. (Why it wasn't smart enough to just disable them is beyond me.) Anyway,
click Next when that's done.
Again you will see the Choose Methods screen. As before, uncheck the "Fill A
DataTable" checkbox and leave the "Return A DataTable" checkbox checked. Change
the method name to "GetModelReportData". Click Next.
The Wizard Results screen will list all of the procedures and methods that were generated
for you. Look these over, then click Finish.
The Data Access Layer is now complete. Next, we'll take a look at the Business Logic Layer.
Business Logic Layer
Create a new Class Library project in the Cars solution, and call it CarsBLL. Next, add a
reference to the CarsDLL project. Then rename the Class1.cs file created by default to
CarsBLL.cs, add the [System.ComponentModel.DataObject] attribute to the CarsBLL class, and
add four fields, one for each adapter created in the DAL. The CarsBLL should look like this at
this point:
using CarsDAL.App_Code.CarsDataSetTableAdapters;
using CarsDAL.App_Code;
namespace CarsBLL
{
[System.ComponentModel.DataObject]
public class CarsBLL
{
private ManufacturerTableAdapter _manufacturerAdapter = null;
private MakeTableAdapter _makeAdapter = null;
private ModelTableAdapter _modelAdapter = null;
private ModelReport_sTableAdapter _carsReportAdapter = null;
}
}
The [System.ComponentModel.DataObject] attribute, along with the others we will be adding to
the methods we create next in this class, will make the BLL and its methods visible to the
controls we will be using later in the Presentation Layer.
Next, we'll add a property for each adapter, methods to Add, Update, Delete, and Get data for the
Manufacturer, Make, and Model tables, and a Get method for the Report adapter. Note that each
of these methods will make calls into the DAL, which as we saw earlier, makes calls to the
database. Once these properties and methods are created, your CarsBLL class should look
something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Note the attributes added to each method:
[System.ComponentModel.DataObjectMethodAttribute
(System.ComponentModel.DataObjectMethodType.Select, true)]. Again, this ensures that they
are visible to the ObjectDataSource control which will be used in the Presentation Layer.
Now, you may have noticed that the BLL Delete methods all accept one parameter, which
represents the primary key for the corresponding table. We're going to have to go back to the
DAL and adjust the Delete methods there and in the Delete stored procedures that were
generated by Visual Studio. For some reason, Visual Studio's TableAdapter Configuration
Wizard generates these methods and procedures so that it's necessary to pass a variable for every
field into them. That's just ridiculous. Visual Studio should be able to recognize when a table
has a primary key, and it should generate the Delete methods and procedures accordingly. Well,
it doesn't, so we're going to do that. (We could leave it the way it is and adjust our BLL to deal
with this stupidity, but I have a low tolerance for stupidity. Besides, it's almost as easy to do it
correctly, and certainly worth the extra effort.)
So, let's go back to our CarsDAL project and take a look at the CarsDataSet.Designer.cs file that
was generated by the TableAdapter Configuration Wizard. Within that file there should be three
different methods called InitAdapter(), one for each table in our schema. Within each of these
methods you can see how each command object is created. You want to look for where the
parameters are being added to the command object. Look for code that looks something like
this:
this._adapter.DeleteCommand.Parameters.Add(new
global::System.Data.SqlClient.SqlParameter("@RETURN_VALUE",
global::System.Data.SqlDbType.Variant, 0,
global::System.Data.ParameterDirection.ReturnValue, 0, 0, null,
global::System.Data.DataRow Version.Current, false, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new
global::System.Data.SqlClient.SqlParameter("@Original_MfrId",
global::System.Data.SqlDbType.Int, 0,
global::System.Data.ParameterDirection.Input, 0, 0, "MfrId",
global::System.Data.DataRow Version.Original, false, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new
global::System.Data.SqlClient.SqlParameter("@Original_MfrName",
global::System.Data.SqlDbType.NVarChar, 0,
global::System.Data.ParameterDirection.Input, 0, 0, "MfrName",
global::System.Data.DataRow Version.Original, false, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new
global::System.Data.SqlClient.SqlParameter("@Original_Created_Date",
global::System.Data.SqlDbType.DateTime, 0,
global::System.Data.ParameterDirection.Input, 0, 0, "Created_Date",
global::System.Data.DataRow Version.Original, false, null, "", "", ""));
The above code adds four parameters to the DeleteCommand object of the Manufacturer
TableAdapter. We only need the first two; the first parameter represents the return value of the
stored procedure, and the second one represents the primary key value of the record to be
deleted. That's all we really need, so delete the third and fourth parameters. Once you've done
that, repeat the process for both the Make TableAdapter and the Model TableAdapter.
Now we need to adjust the three stored procedures that perform the Deletes in the respective
tables. You will need to adjust the parameter list within each stored proc so that it only expects
the first "input" parameter as mentioned above. In addition, you will need to adjust the WHERE
clause in each of these stored procs as well, so that they only include the primary key field.
Here's what the Manufacturer_d stored procedure should look like when you're done:
CREATE PROCEDURE dbo.Manufacturer_d
(
@Original_MfrId int
) AS SET NOCOUNT OFF;
DELETE FROM [Manufacturer]
WHERE (([MfrId] = @Original_MfrId))
You will need to do this for both the Make_d and Model_d stored procedures as well.
We have now completed both the Data Access Layer and the Business Logic Layer.
Presentation Layer
The Presentation Layer is the final piece to our puzzle. Keep in mind that although I'll be using
ASP.NET in order to create a web GUI for the purposes of this article, you could just as easily
create a Windows Forms or a WPF-based presentation layer for your app, and utilize the exact
same Business Logic Layer and Data Access Layer components we created previously. After all,
that is the point of multi-tier architecture.
Within our Cars solution, create a new ASP.NET Web Application project, and name it
CarsWeb. VS will create a Default.aspx page within the project which we will look at soon.
You can leave it alone for now.
Before we start coding, we want to add a reference to the CarsBLL project. Just right-click on
the CarsWeb project, choose Add Reference from the menu, then choose the CarsBLL project
from the Project tab. After that's done, rebuild the solution. This will ensure that CarsBLL is
visible from within CarsWeb.
Our presentation layer is going to consist of a menu of options which will be contained in
Default.aspx. It will also contain a Maintenance page for each of our tables where a user can
view, edit, or delete records. In addition, there will be a Reports page which will list each model,
along with the names of its Manufacturer and Make. VS already created our Default.aspx page,
so just add four new pages, naming them mfrmaint.aspx, makemaint.aspx, modelmaint.aspx, and
report.aspx. You should have five aspx files in total, including Default.aspx. (Our GUI is not
going to be pretty or fancy, but it will be functional. You can add pretty and fancy at your
leisure.)
We'll start by adding an ObjectDataSource to the Manufacturer maintenance page:







Open up the mfrmaint.aspx page in design mode.
Add an ObjectDataSource control to the page by dragging it in from the Data section of
the VS toolbox. It will be named ObjectDataSource1 by default.
Right-click on the ObjectDataSource control and choose Configure Data Source from the
context menu.
In the configuration window, choose CarsBLL.CarsBLL from the business objects list,
then click Next.
The next screen contains four tabs; SELECT, UPDATE, INSERT, and DELETE. In each
of these tabs, ensure that the appropriate method is selected. The chosen methods should
be GetManufacturerData(), UpdateManufacturer(), AddManufacturer(), and
DeleteManufacturer() respectively.
Click Finish
Switch to Source view, and change the OldValuesParameterFormatString attribute from
"original_{0}" to just "{0}" (due to a bug in the ObjectDataSource control)
And now, a GridView control:

Open up the mfrmaint.aspx page in design mode again





Add a GridView control to the page by dragging it in from the Data section of the
Toolbox
In the Properties window of the GridView control, assign ObjectDataSource1 to the
DataSourceID property
In the GridView Tasks sheet, check the following options: Enable Paging, Enable
Sorting, Enable Editing, and Enable Deleting
Set the ReadOnly property to True for the MfrId and Created_Date fields
Set the DataKeyNames attribute of the GridView control to "MfrId", so that the control
knows which is the Primary Key field
Now, repeat the above steps in both makemaint.aspx and modelmaint.aspx for Make
Maintenance and Model Maintenance. When that's all done, meet me at the next paragraph.
Ok, now that the table maintenance pages are done, we'll do the Report page. The report will
consist simply of a call to the GetAllModels() method of our BLL. It's just like the table
maintenance pages we just completed, only easier. Open up report.aspx in Design mode and add
an ObjectDataSource just like we did on the table maintenance pages. Right-click on it and
choose Configure Data Source from the menu. In the configuration window, choose
CarsBLL.CarsBLL from the business objects list, then click Next. On the next screen we'll only
be concerned with the SELECT tab this time. In the SELECT tab, choose the GetAllModels()
method and click Finish. Next, add a GridView control, and assign ObjectDataSource1 as its
DataSourceID property. Then go to the GridView control's GridView Tasks sheet, check Enable
Paging and Enable Sorting.
Lastly, open up Default.aspx and create a simple menu with links to each of the other four
pages. Something like this:
<a href="report.aspx">Run Report</a><br /><br />
<a href="mfrmaint.aspx">Manufacturer Maintenance</a><br />
<a href="makemaint.aspx">Make Maintenance</a><br />
<a href="modelmaint.aspx">Model Maintenance</a><br />
And that's it! Build your solution, and you should have pages that look as follows:
Default.aspx
mfrmaint.aspx
makemaint.aspx
modelmaint.aspx
report.aspx
3 tier :
3-Tier Architecture in asp.net using c#
In this asp.net tutorial you will learn how to implement 3-tier architecture in
asp.net using c#. 3-Tier architecture is also called layered architecture.
Some people called it n-tier architecture. Layer architectures are essentially
objects and work in object oriented environment just like asp.net. 3-tier
architecture is a very well known architecture in the world of software
development, it doesn't matter whether you are developing web based
application or desktop based, it is the best architecture to use.
3-Tier Architecture in asp.net using c#
3-Tier architecture consists of
1) UI or Presentation Layer
2) Business Access Layer or Business Logic Layer
3) Data Access Layer
Presentation Layer
Presentation layer consists of pages like .aspx or desktop based form where
data is presented to users or getting input from users.
Business Logic layer or Business Access Layer
Business logic layer contains all of the business logic. Its responsibility is to
validate the business rules of the component and communicating with the
Data Access Layer. Business Logic Layer is the class in which we write
functions that get data from Presentation Layer and send that data to
database through Data Access Layer.
Data Access Layer
Data Access Layer is also the class that contains methods to enable business
logic layer to connect the data and perform desired actions. These desired
actions can be selecting, inserting, updating and deleting the data. DAL
accepts the data from BAL and sends it to the database or DAL gets the data
from the database and sends it to the business layer. In short, its
responsibility is to communicate with the backend structure.
Illustration of 3-Tier Architecture with Diagram
The figure clearly describe about the purpose of BAL and DAL. The main
advantage of 3-tier architecture is to separate the presentation layer from
data access layer. You will not write any function to communicate with
database in presentation layer, all the required functions for communication
with database will be available in DataAcessLayer. Its mean at presentation
layer you will just focus at information that you will present in front of user.
I am going to create BAL, DAL in App_Code folder. You can also create
separate projects for BAL, DAL and UI (Your website) and referenced your
DAL into BAL and BAL into UI. In that scenario you have to rebuild the DAL
and BAL every time, in order to view the change that you have made in your
BAL and DAL. So to get rid of rebuilding layers every time after change, I am
going to create BAL and DAL folder in App_Code. Now feel free to make
changes in BAL and DAL and just refresh the webpage to view the change
that you made, in short no rebuilding of DAL and BAL is required. The
following figure shows the 3-tier architecture of our website that we are
going to made.
Design and implement 3-tier architecture
.
1) Open visual studio or visual web developer.
2) Go to File-> New Web Site
3) Select ASP.NET Web Site and then browse the Folder in which you want
to save your web pages.
4) Go to Solution Explorer and then right click on your website folder. Go to
Add ASP.NET Folder-> App_Code.
5) Now right click on App_Code Folder and select New Folder.
6) Create Two Folders and give BusinessLayer and DataAccessLayer names
to them.
7) Now right click on DataAccessLayer -> Add New Item.
8) Select Class as template and give DbAccess name to that class.
9) Now right click on BusinessLayer folder-> Add New Item
10) Select Class as template and give BusComments.cs name to that class.
Now open your DbAccess.cs file placed in DataAccessLayer folder. Clear it by
deleting all its built-in code and then copy/paste the following code in your
DbAccess.cs file and then save it
DbAccess.cs
view plainprint?
1.
2.
3.
4.
using
using
using
using
System;
System.Data;
System.Collections;
System.Collections.Generic;
5. using System.Configuration;
6. using System.Data.SqlClient;
7. using System.Web;
8.
9.
10.
namespace DataAccessLayer
11.
{
12.
/// <summary>
13.
/// Constains overloaded method to access database and run qu
eries
14.
/// </summary>
15.
public class DbAccess
16.
{
17.
private SqlConnection DbConn = new SqlConnection();
18.
private SqlDataAdapter DbAdapter = new SqlDataAdapter();
19.
private SqlCommand DbCommand = new SqlCommand();
20.
private SqlTransaction DbTran;
21.
private string strConnString = ConfigurationManager.Connection
Strings["WebsiteConnectionString"].ToString();
22.
23.
24.
public void setConnString(string strConn)
25.
{
26.
try
27.
{
28.
strConnString = strConn;
29.
}
30.
catch (Exception exp)
31.
{
32.
throw exp;
33.
}
34.
}
35.
36.
37.
public string getConnString()
38.
{
39.
try
40.
{
41.
return strConnString;
42.
}
43.
catch (Exception exp)
44.
{
45.
throw exp;
46.
}
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
}
private void createConn()
{
try
{
DbConn.ConnectionString = strConnString;
DbConn.Open();
}
catch (Exception exp)
{
throw exp;
}
}
public void closeConnection()
{
try
{
if (DbConn.State != 0)
DbConn.Close();
}
catch (Exception exp)
{
throw exp;
}
}
public void beginTrans()
{
try
{
if (DbTran == null)
{
if (DbConn.State == 0)
{
createConn();
}
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
DbTran = DbConn.BeginTransaction();
DbCommand.Transaction = DbTran;
DbAdapter.SelectCommand.Transaction = DbTran;
DbAdapter.InsertCommand.Transaction = DbTran;
DbAdapter.UpdateCommand.Transaction = DbTran;
DbAdapter.DeleteCommand.Transaction = DbTran;
}
}
catch (Exception exp)
{
throw exp;
}
}
public void commitTrans()
{
try
{
if (DbTran != null)
{
DbTran.Commit();
DbTran = null;
}
}
catch (Exception exp)
{
throw exp;
}
}
public void rollbackTrans()
{
try
{
if (DbTran != null)
{
DbTran.Rollback();
DbTran = null;
}
135.
136.
137.
}
138.
catch (Exception exp)
139.
{
140.
throw exp;
141.
}
142.
}
143.
144.
145.
/// <summary>
146.
/// Fills the Dataset dset and its Table tblname via stored proced
ure provided as spName arguement.Takes Parameters as param
147.
/// </summary>
148.
/// <param name="dSet"></param>
149.
/// <param name="spName"></param>
150.
/// <param name="param"></param>
151.
/// <param name="tblName"></param>
152.
public void selectStoredProcedure(DataSet dSet, string spName,
Hashtable param, string tblName)
153.
{
154.
try
155.
{
156.
if (DbConn.State == 0)
157.
{
158.
createConn();
159.
}
160.
DbCommand.Connection = DbConn;
161.
DbCommand.CommandText = spName;
162.
DbCommand.CommandType = CommandType.StoredProcedure;
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
foreach (string para in param.Keys)
{
DbCommand.Parameters.AddWithValue(para, param[para]);
}
DbAdapter.SelectCommand = (DbCommand);
DbAdapter.Fill(dSet, tblName);
}
catch (Exception exp)
{
176.
177.
178.
throw exp;
179.
}
180.
}
181.
182.
183.
public void selectStoredProcedure(DataSet dSet, string spName,
string tblName)
184.
{
185.
try
186.
{
187.
if (DbConn.State == 0)
188.
{
189.
createConn();
190.
}
191.
DbCommand.Connection = DbConn;
192.
DbCommand.CommandText = spName;
193.
DbCommand.CommandType = CommandType.StoredProcedure;
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
me)
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
DbAdapter.SelectCommand = DbCommand;
DbAdapter.Fill(dSet, tblName);
}
catch (Exception exp)
{
throw exp;
}
}
public void selectQuery(DataSet dSet, string query, string tblNa
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.CommandTimeout = 600;
DbCommand.Connection = DbConn;
DbCommand.CommandText = query;
DbCommand.CommandType = CommandType.Text;
DbAdapter = new SqlDataAdapter(DbCommand);
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
am)
259.
DbAdapter.Fill(dSet, tblName);
}
catch (Exception exp)
{
DbAdapter.Dispose();
DbConn.Close();
throw exp;
}
finally
{
DbAdapter.Dispose();
DbConn.Close();
}
}
public int executeQuery(string query)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = query;
DbCommand.CommandType = CommandType.Text;
return DbCommand.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
}
finally
{
DbAdapter.Dispose();
DbConn.Close();
}
}
public int executeStoredProcedure(string spName, Hashtable par
{
260.
261.
262.
263.
264.
265.
266.
267.
268.
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = spName;
DbCommand.CommandType = CommandType.StoredProcedure;
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
foreach (string para in param.Keys)
{
DbCommand.Parameters.AddWithValue(para, param[para]);
}
return DbCommand.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
}
}
public int returnint32(string strSql)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
else
{
DbConn.Close();
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = strSql;
DbCommand.CommandType = CommandType.Text;
return (int)DbCommand.ExecuteScalar();
}
catch (Exception exp)
{
return 0;
303.
}
304.
}
305.
public Int64 returnint64(string strSql)
306.
{
307.
try
308.
{
309.
if (DbConn.State == 0)
310.
{
311.
createConn();
312.
}
313.
DbCommand.Connection = DbConn;
314.
DbCommand.CommandText = strSql;
315.
DbCommand.CommandType = CommandType.Text;
316.
return (Int64)DbCommand.ExecuteScalar();
317.
}
318.
catch (Exception exp)
319.
{
320.
throw exp;
321.
}
322.
}
323.
public int executeDataSet(DataSet dSet, string tblName, string s
trSql)
324.
{
325.
try
326.
{
327.
if (DbConn.State == 0)
328.
{
329.
createConn();
330.
}
331.
332.
333.
DbAdapter.SelectCommand.CommandText = strSql;
334.
DbAdapter.SelectCommand.CommandType = CommandType.Tex
t;
335.
SqlCommandBuilder DbCommandBuilder = new SqlCommandBui
lder(DbAdapter);
336.
337.
338.
return DbAdapter.Update(dSet, tblName);
339.
}
340.
catch (Exception exp)
341.
{
342.
throw exp;
343.
}
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
}
public bool checkDbConnection()
{
int _flag = 0;
try
{
if (DbConn.State == ConnectionState.Open)
{
DbConn.Close();
}
DbConn.ConnectionString = getConnString();
DbConn.Open();
_flag = 1;
}
catch (Exception ex)
{
_flag = 0;
}
if (_flag == 1)
{
DbConn.Close();
_flag = 0;
return true;
}
else
{
return false;
}
}
public string GetColumnValue(string Query)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.CommandTimeout = 120;
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
DbCommand.Connection = DbConn;
DbCommand.CommandType = CommandType.Text;
DbCommand.CommandText = Query;
object objResult = DbCommand.ExecuteScalar();
if (objResult == null)
{
return "";
}
if (objResult == System.DBNull.Value)
{
return "";
}
else
{
return Convert.ToString(objResult);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
DbAdapter.Dispose();
DbConn.Close();
}
}
}
}
I will not go into any detail of the code written in DbAccess.cs file but I will
tell you three main things about my DbAccess.cs file
1) I have created a namespace DataAccessLayer and place the DbAccess
class inside the namespace. Namespaces are a way to define the classes and
other types of data into one hierarchical structure. System is the basic
namespace used by every .NET page. A namespace can be created via the
Namespace keyword just like I did.
2) private string strConnString =
ConfigurationManager.ConnectionStrings["WebsiteConnectionString"].ToStri
ng() contains the name of the connection string(WebsiteConnectionString)
that I declared in web.config file.
3) DbAccess class contains all the methods to communicate with database
via query and store procedures. It contains all the methods for you to
perform the select, insert, update and delete the data.
Now open your BusComments.cs file and clear it by deleting all the built-in
code and then copy/paste the below mention code in it.
BusComments.cs
view plainprint?
1. using
2. using
3. using
4. using
5. using
6. using
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Data;
DataAccessLayer;
namespace BusinessLayer
{
public class BusComments
{
DbAccess _dbAccess = new DbAccess();
private DataSet _CommentsDS = new DataSet();
public DataSet CommentsDS
{
get
{
return _CommentsDS;
}
set
{
_CommentsDS = value;
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
;
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
}
}
public void getComments()
{
try
{
string strSQL = "SELECT * from comments";
//Creating Datatable, if datatable not exist already.
//The data return by query will be stored in DataTable.
if (_CommentsDS.Tables.Contains("GetComments"))
{
_CommentsDS.Tables.Remove("GetComments");
}
_dbAccess.selectQuery(_CommentsDS, strSQL, "GetComments")
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Same as DbAccess.cs, I have created a namespace BusinessLayer
and put BusComments class in it. I have declared a private dataset
_CommentsDS and define a public dataset _CommentsDS in BusComments
class. After interacting with database, Private Dataset will return all the data
to the public dataset so that data can be accessible to the Presentation
Layer. You may notice that I have used the DataAccessLayer namespace
with other namespaces. I have also created the object of DbAccess class to
get the appropriate methods written inside it to communicate with database;
it’s all possible due to the inclusion of DataAccessLayer namespace. So
don’t forget to include DataAccessLayer namespace in your every
business layer class.
Now open the Default.aspx file and again clear all the pre written code in it
and then copy/paste the following code in it.
Default.aspx
view plainprint?
1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Defau
lt.aspx.cs" Inherits="Default" %>
2.
3.
4. <!DOCTYPE html PUBLIC "//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xht
ml1/DTD/xhtml1-transitional.dtd">
5. <html xmlns="http://www.w3.org/1999/xhtml">
6. <head runat="server">
7. <title>Designing and implementing the 3tier architecture in asp.net</title>
8. <style type="text/css">
9. .textDIV
10.
{
11.
font-family: Verdana;
12.
font-size: 12px;
13.
}
14.
</style>
15.
</head>
16.
<body>
17.
<form id="form1" runat="server">
18.
<div class="textDIV">
19.
<table width="100%" border="0" cellpadding="0" cellspacing="
0" align="center">
20.
<tr>
21.
<td style="width: 45%">
22.
23.
24.
</td>
25.
<td>
26.
27.
28.
</td>
29.
<td>
30.
31.
32.
</td>
33.
</tr>
34.
<tr>
35.
<td width="20%" colspan="3" align="center">
36.
<span style="display: inline;"><strong>Comments</strong></
span>
37.
</td>
38.
</tr>
39.
<tr>
40.
<td width="20%" colspan="3">
41.
42.
43.
</td>
44.
</tr>
45.
<tr>
46.
<td colspan="3" align="center">
47.
<hr style="width: 50%;" />
48.
</td>
49.
</tr>
50.
<tr>
51.
<td>
52.
53.
54.
</td>
55.
</tr>
56.
<tr>
57.
<td align="center" width="100%">
58.
<asp:GridView ID="GridView1" runat="server" EnableTheming=
"false" AutoGenerateColumns="false"
59.
GridLines="None" OnRowDataBound="GridView1_RowDataBoun
d" Width="660px" HorizontalAlign="Center">
60.
<Columns>
61.
<asp:TemplateField HeaderText="Sr No" HeaderStyleWidth="15%" HeaderStyle-HorizontalAlign="Center">
62.
<ItemTemplate>
63.
<%# Container.DataItemIndex + 1 %>
64.
</ItemTemplate>
65.
<ItemStyle HorizontalAlign="Center" />
66.
</asp:TemplateField>
67.
<asp:TemplateField HeaderText="First Name" HeaderStyleWidth="15%" HeaderStyle-HorizontalAlign="Left">
68.
<ItemTemplate>
69.
<asp:Label ID="lblFirstName" runat="server" EnableTheming="f
alse" Text='<%# Bind("first_name")%>'></asp:Label>
70.
</ItemTemplate>
71.
<ItemStyle HorizontalAlign="Left" />
72.
</asp:TemplateField>
73.
<asp:TemplateField HeaderText="Last Name" HeaderStyleWidth="15%" HeaderStyle-HorizontalAlign="Left">
74.
<ItemTemplate>
75.
<asp:Label ID="lblLastName" runat="server" EnableTheming="f
alse" Text='<%# Bind("last_name")%>'></asp:Label>
76.
</ItemTemplate>
77.
<ItemStyle HorizontalAlign="Left" />
78.
</asp:TemplateField>
79.
<asp:TemplateField HeaderText="Comments" HeaderStyleWidth="50%" HeaderStyle-HorizontalAlign="Left">
80.
<ItemTemplate>
81.
<asp:Label ID="lblComments" runat="server" EnableTheming="
false" Text='<%# Bind("comments")%>'></asp:Label>
82.
</ItemTemplate>
83.
<ItemStyle HorizontalAlign="Left" />
84.
</asp:TemplateField>
85.
</Columns>
86.
</asp:GridView>
87.
</td>
88.
</tr>
89.
<tr>
90.
<td>
91.
92.
93.
</td>
94.
</tr>
95.
<tr>
96.
<td align="center">
97.
<input type="button" value="Back" onclick="history.back(1);" />
98.
</td>
99.
</tr>
100.
</table>
101.
</div>
102.
</form>
103.
</body>
104.
</html>
As you have seen that in .aspx file I just placed the asp:GridView control.
Now let's have a look over the Default.aspx.cs file
Default.aspx.cs
view plainprint?
1. using System;
2. using System.Collections;
3. using System.Configuration;
4. using System.Data;
5. using System.Linq;
6. using System.Web;
7. using System.Web.Security;
8. using System.Web.UI;
9. using System.Web.UI.HtmlControls;
10.
using System.Web.UI.WebControls;
11.
using System.Web.UI.WebControls.WebParts;
12.
using System.Xml.Linq;
13.
using BusinessLayer;
14.
15.
16.
public partial class Default : System.Web.UI.Page
17.
{
18.
BusComments _objComments = new BusComments();
19.
protected void Page_Load(object sender, EventArgs e)
20.
{
21.
if (!Page.IsPostBack)
22.
{
23.
BindGrid();
24.
}
25.
}
26.
27.
28.
public void BindGrid()
29.
{
30.
_objComments.getComments();
31.
//Tables[“GetComments”] is the DataTable that we have created
in BusComments class
32.
GridView1.DataSource = _objComments.CommentsDS.Tables["G
etComments"];
33.
GridView1.DataBind();
34.
}
35.
36.
37.
protected void GridView1_RowDataBound(object sender, GridVie
wRowEventArgs e)
38.
{
39.
if (e.Row.RowType == DataControlRowType.DataRow)
40.
{
41.
((Label)e.Row.FindControl("lblComments")).Text = ((Label)e.Ro
w.FindControl("lblComments")).Text.ToString().ToUpper();
42.
}
43.
44.
45.
}
46.
}
I have included the BusinessLayer namespace on the top so that I can get
access to the BusComments class. Then I initialized the object of
BusComments class and then by using the object I have called my required
function placed in BusComments class to get data and populate the
GridView. Now you have seen I called the function written in BusComments
class to get the data from database and that function actually called its
required function written in DbAccess class to get the data from database.
DbAccess gets the data from database and return to BusComments
Class, BusComments class gets the data from DbAccess class and
return to Presentation Layer which is default.aspx
Update Note at May-01-2011
I have seen through tracking software that this post is very much popular
among my respected users. So i have decided to write further posts on this
topic, such as how to insert, delete, update records in database using 3-tier
architecture. So keep in touch with nice-tutorials:)
Update Note at May-05-2011
Just now i have written post on Insertion of records in database using 3-tier
architecture in asp.net with c#. More to come soon on this topic. Keep in
touch.
Update Note at June-01-2011
Just now i have written post on Delete records in database using 3-tier
architecture in asp.net with c#. More to come soon on this topic. Stay tune
:)
Update Note at August-09-2011
Sorry for the delay. Just now i have written post on Update records in
database using 3-tier architecture in asp.net with c#. Stay tuned. This topic
is not over yet. Soon i will write posts for jquery and 3-tier architecture in
asp.net with c#. Jquery will boost the performance of your website, boost up
the speed of your website and also make your website light. :)
So this is the way to design and implement the 3-tier architecture/layered
architecture/n-tier architecture in asp.net using c#.
http://www.tutorialized.com/view/tutorial/3-Tier-Architecture-in-asp.net-using-c/67931
http://www.webcodeexpert.com/2014/01/how-to-create-3-tier-application-in.html#.U2eIP6KtZng
How to create 3 tier application in Asp.Net
C# to Insert,edit,update,bind and delete data
Click on image to enlarge
Introduction: In this article you will learn how to create 3 tier project with example to
Save, Bind, Edit, Update and Delete Book Details using asp.net and Sql server as a back end
database as shown in image.
Note: Before reading this article you must read the article How to setup 3 tier architecture
project in asp.net C# to set up the 3 tier architecture for this application because this article
is the continued part of the previous article where you learned how to set up 3 tier project.
I am assuming that you have setup the 3-tier project after reading the above mentioned
article.
So now our next step is to create the database.

So create a Sql server database e.g. "BookDb" and in that create a table using the
script below:
CREATE TABLE [dbo].[BookDetails]
(
[BookId] [int] IDENTITY(1,1) NOT NULL,
[BookName] [varchar](100),
[Author] [varchar](100),
[Publisher] [varchar](200),
[Price] [decimal](18, 2) NOT NULL
)

Now create the stored procedure to insert the book details in the table.
CREATE PROCEDURE [dbo].[InsertBookDetails_SP]
@BookName
VARCHAR(100),
@Author
VARCHAR(100),
@Publisher
VARCHAR(200),
@Price
DECIMAL(18,2)
AS
BEGIN
INSERT INTO BookDetails
(
BookName,Author,Publisher,Price
)
VALUES
(
@BookName,@Author,@Publisher,@Price
)
END

Create a stored procedure to update the book detail
CREATE PROCEDURE [dbo].[UpdateBookRecord_SP]
@BookId
INT,
AS
BEGIN
@BookName
@Author
@Publisher
@Price
VARCHAR(100),
VARCHAR(100),
VARCHAR(200),
DECIMAL(18,2)
UPDATE BookDetails SET
BookName=@BookName,
Author=@Author,
Publisher=@Publisher,
Price=@Price
WHERE BookId=@BookId
END

Create a stored procedure to delete book record
CREATE PROCEDURE [dbo].[DeleteBookRecords_Sp]
@BookId
INT
AS
BEGIN
DELETE FROM BookDetails WHERE BookId=@BookId
END

Create a stored procedure to delete book record
CREATE PROCEDURE [dbo].[FetchBookRecords_Sp]
AS
BEGIN
SELECT * FROM BookDetails
END

Now we need to connect our asp.net application with the sql server database. So in
the web.config file create the connection string under the <configuration> tag as:
<connectionStrings>
<add name="conStr" connectionString="Data Source=localhost;Initial
Catalog=BooksDb;Integrated Security=True"/>
</connectionStrings>
Now database part is done. Now it's time to write the code for each layer.
Create Class In BEL


So let's create an entity/ property class in BEL.
Right click on the "BEL_BookApp" in the solution explorer -> Add -> New Item ->
Select "Class" and name it "BooksDetails_BEL.cs" as shown in image below.
Click on image to enlarge

Create the property for each column in the table "BookDetails". So write the code
in BooksDetails_BEL.cs as:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BEL_BookApp
{
public class BooksDetails_BEL
{
public int BookId { get; set; }
public string BookName { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public decimal Price { get; set; }
}
}
Create Class in DAL


Now we need to create a class in DAL to perform database operations.
So right click on the "DAL_BookApp" in the solution explorer -> Add -> New Item ->
Select "Class" and name it "BooksDetails_DAL.cs" as shown in image below.
Click on image to enlarge
Write the following code in BooksDetails_DAL.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using BEL_BookApp;
namespace DAL_BookApp
{
public class BooksDetails_DAL
{
SqlConnection con
= new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString
);
public Int32 SaveBookDetails(BooksDetails_BEL objBEL)
{
int result;
try
{
SqlCommand cmd = new SqlCommand("InsertBookDetails_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@BookName", objBEL.BookName);
cmd.Parameters.AddWithValue("@Author", objBEL.Author);
cmd.Parameters.AddWithValue("@Publisher", objBEL.Publisher);
cmd.Parameters.AddWithValue("@Price", objBEL.Price);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
cmd.Dispose();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close();
}
}
}
public DataSet GetBookRecords()
{
DataSet ds = new DataSet();
try
{
SqlCommand cmd = new SqlCommand("FetchBookRecords_Sp", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.Dispose();
}
catch (Exception ex)
{
throw;
}
finally
{
ds.Dispose();
}
return ds;
}
public Int32 DeleteBookRecord(BooksDetails_BEL objBEL)
{
int result;
try
{
SqlCommand cmd = new SqlCommand("DeleteBookRecords_Sp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@BookId", objBEL.BookId);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
cmd.Dispose();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close();
}
}
}
public Int32 UpdateBookRecord(BooksDetails_BEL objBEL)
{
int result;
try
{
SqlCommand cmd = new SqlCommand("UpdateBookRecord_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@BookId", objBEL.BookId);
cmd.Parameters.AddWithValue("@BookName", objBEL.BookName);
cmd.Parameters.AddWithValue("@Author", objBEL.Author);
cmd.Parameters.AddWithValue("@Publisher", objBEL.Publisher);
cmd.Parameters.AddWithValue("@Price", objBEL.Price);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
cmd.Dispose();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close();
}
}
}
Create Class in BLL


Now we need to create a class that act as a bridge between Presentation tier and
Data access layer whose work is to pass the data from the presentation layer to data
access layer for processing and after that getting sending the results back to the
presentation layer.
So right click on the "BLL_BookApp" in the solution explorer -> Add -> New Item ->
Select "Class" and name it "BooksDetails_BLL.cs" as shown in image below.
Click on image to enlarge
Write the following code in BooksDetails_BLL.cs as:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using BEL_BookApp;
using DAL_BookApp;
namespace BLL_BookApp
{
public class BookDetails_BLL
{
public Int32 SaveBookDetails(BooksDetails_BEL objBel)
{
BooksDetails_DAL objDal = new BooksDetails_DAL();
try
{
return objDal.SaveBookDetails(objBel);
}
catch (Exception ex)
{
throw;
}
finally
{
objDal = null;
}
}
public DataSet GetBookRecords()
{
BooksDetails_DAL objDal = new BooksDetails_DAL();
try
{
return objDal.GetBookRecords();
}
catch (Exception ex)
{
throw;
}
finally
{
objDal = null;
}
}
public Int32 DeleteBookRecord(BooksDetails_BEL objBel)
{
BooksDetails_DAL objDal = new BooksDetails_DAL();
try
{
return objDal.DeleteBookRecord(objBel);
}
catch (Exception ex)
{
throw;
}
finally
{
objDal = null;
}
}
public Int32 UpdateBookRecord(BooksDetails_BEL objBel)
{
BooksDetails_DAL objDal = new BooksDetails_DAL();
try
{
return objDal.UpdateBookRecord(objBel);
}
catch (Exception ex)
{
throw;
}
http://www.dotnetfunda.com/articles/show/2708/3-tier-architecture-in-aspnet-a-complete-article
http://aspdotnet-sekhar.blogspot.in/2013/04/working-or-consuming-three-tierlayered.html
http://www.programmingposts.com/2014/02/registration-form-in-aspnet-cnet-uisng.html
http://geekswithblogs.net/edison/archive/2009/04/05/a-simple-3-tier-layers-application-inasp.net.aspx
http://www.aspdotnet-suresh.com/2010/05/introduction-to-3-tier-architecture-in_17.html
Download