3-Tier Architecture in asp.net using C# with Crude Operations

Category: ASP.NETC#.NetTHREE TIER ARCHITECTURE Comments: 7 comments

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

3-Tier architecture in asp.net

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.

Example Below:

3

Table Script

CREATE TABLE [dbo].[EmpData](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](50) NULL,
[gender] [nvarchar](50) NULL,
[address] [nvarchar](50) NULL,
[email] [nvarchar](50) NULL,
[country] [nvarchar](50) NULL,
[phone] [int] NULL,
[image] [nvarchar](50) NULL,
CONSTRAINT [PK_EmpData] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE PROCEDURE [dbo].[showFullData]
@id int
AS
BEGIN
select * from EmpData where id=@id
END

CREATE PROCEDURE [dbo].[DeleteUser]
@id int
AS
BEGIN
delete from EmpData where id=@id
END

CREATE PROCEDURE [dbo].[employeedata]
@name nvarchar(50),
@gender nvarchar(50),
@address nvarchar(50),
@email nvarchar(50),
@country nvarchar(50),
@phone int,
@image nvarchar(50)
AS
BEGIN
insert into EmpData values(@name,@gender,@address,@email,@country,@phone,@image)
END

CREATE PROCEDURE [dbo].[updateEmpData]
@id int,
@name nvarchar(50),
@gender nvarchar(50),
@address nvarchar(50),
@email nvarchar(50),
@country nvarchar(50),
@phone int,
@image nvarchar(50)
AS
BEGIN
update EmpData set name=@name,gender=@gender,address=@address,email=@email,country=@country,phone=@phone,image=@image
where id=@id
END

CREATE PROCEDURE [dbo].[showDetail]
AS
BEGIN
select * from EmpData
END

Now Come To Bussiness Layer

BAL:

bal

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Classes in Bussiness Layer:

allclass

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Now Come To Data Access Layer

DAL:

using System.Configuration;
using BussinessLayer;

namespace DataLink
{

public class DAL
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["precticedata"].ConnectionString);
#region Adduserdetail
public int insertdetail(UserInfo1 obdef)
{
int res = 0;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(“employeedata”, con);
cmd.Parameters.Add(“@name”, obdef.name);
cmd.Parameters.Add(“@gender”, obdef.gender);
cmd.Parameters.Add(“@address”, obdef.address);
cmd.Parameters.Add(“@email”, obdef.email);
cmd.Parameters.Add(“@country”, obdef.country);
cmd.Parameters.Add(“@phone”, obdef.phone);
cmd.Parameters.Add(“@image”, obdef.image);
cmd.CommandType = CommandType.StoredProcedure;
res = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
return res;

}
#endregion
#region showDetail
public DataSet showfulldetail()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand(“showDetail”, con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

 

con.Close();
return ds;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region updateDetail

public int UpdateDetail(userUpdateInfo1 obup)
{
int res = 0;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(“updateEmpData”, con);
cmd.Parameters.Add(“@id”,obup.id);
cmd.Parameters.Add(“@name”, obup.name);
cmd.Parameters.Add(“@gender”, obup.gender);
cmd.Parameters.Add(“@address”, obup.address);
cmd.Parameters.Add(“@email”, obup.email);
cmd.Parameters.Add(“@country”, obup.country);
cmd.Parameters.Add(“@phone”, obup.phone);
cmd.Parameters.Add(“@image”, obup.image);
cmd.CommandType = CommandType.StoredProcedure;
res= cmd.ExecuteNonQuery();

con.Close();

}
catch (Exception ex)
{
throw ex;
}
return res;
}

#endregion

#region showData
public DataSet showUserdetail(int id)
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand(“showFullData”, con);
cmd.Parameters.Add(“@id”, id);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

 

con.Close();
return ds;
}
catch (Exception ex)
{
throw ex;
}
}

#endregion
#region deletedata
public int deletedata(int id)
{
int res = 0;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(“DeleteUser”, con);
cmd.Parameters.Add(“@id”,id);
cmd.CommandType = CommandType.StoredProcedure;
res = cmd.ExecuteNonQuery();

con.Close();

}
catch (Exception ex)
{
throw ex;
}
return res;
}

#endregion
}
}

 

Web Config Setting

<configuration>
<system.web>
<compilation debug=”true” targetFramework=”4.0″ />
</system.web>
<connectionStrings>
<add name=”precticedata” connectionString=”data source=.\SQLExpress; Database=Practise; integrated security=true” />
</connectionStrings>
</configuration>

 

Calling Bussiness Layer in Pages

Insert Page

Design Page:

add

 

 

 

 

 

 

 

 

 

 

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<table style=” margin:0 auto; background-color:Gray; width:217px; text-align:center; text-decoration:blink;”>
<tr>
<td><h3>Registration Page</h3></td></tr>

</table>
<table style=” margin:0 auto; background-color:Gray;”>
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Gender:
</td>
<td>
<asp:RadioButton ID=”RadioBttnMale” runat=”server” GroupName=”a” Text=”Male” />
<asp:RadioButton ID=”RadioBttnFemale” runat=”server” GroupName=”a” Text=”Female”/>
</td>
</tr>
<tr>
<td>
Address:
</td>
<td>
<asp:TextBox ID=”txtAddress” runat=”server” TextMode=”MultiLine”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<asp:TextBox ID=”txtEmail” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Country:
</td>
<td>
<asp:DropDownList ID=”DDLCountry” runat=”server”>
<asp:ListItem>–Select–</asp:ListItem>
<asp:ListItem>india</asp:ListItem>
<asp:ListItem>australia</asp:ListItem>
<asp:ListItem>england</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Phone No:
</td>
<td>
<asp:TextBox ID=”txtPhone” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Image:
</td>
<td>
<asp:FileUpload ID=”FileUploadImg” runat=”server” />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID=”Imgshow” runat=”server” Height=”45px” Width=”45px” Visible=”false” />
<asp:Button ID=”BttnSave” runat=”server” Text=”Save” onclick=”BttnSave_Click” />
<asp:Button ID=”BttnUpload” runat=”server” Text=”Upload”
onclick=”BttnUpload_Click” />
</td>
<td>
<asp:Button ID=”BttnReset” runat=”server” Text=”Reset”
onclick=”BttnReset_Click” />
</td>
</tr>
</table>
</form>
</body>
</html>

 

Code Page:

using BussinessLayer;
namespace PresentationLayer
{
public partial class AddUser : System.Web.UI.Page
{
BAL obbal = new BAL();
protected void Page_Load(object sender, EventArgs e)
{

}

protected void BttnSave_Click(object sender, EventArgs e)
{
UserInfo1 ob1 = new UserInfo1();
ob1.name = txtName.Text.Trim().ToString();
ob1.gender = RadioBttnMale.Text.Trim().ToString();
ob1.address = txtAddress.Text.Trim().ToString();
if (RadioBttnMale.Checked)
ob1.gender = “Male”;
else
ob1.gender = “Female”;
ob1.email = txtEmail.Text.Trim().ToString();
ob1.country = DDLCountry.SelectedItem.Text.ToString();
ob1.phone = Convert.ToInt32(txtPhone.Text.Trim().ToString());
if (ViewState["saveimage"] != null)
{
ob1.image = ViewState["saveimage"].ToString();
int res = obbal.insertdetaildata(ob1);
if (res > 0)
{
Response.Write(“<script>alert(‘save data’)</script>”);

Response.Redirect(“Show Details.aspx”);
}
else
{
Response.Write(“<script>alert(‘not save data’)</script>”);
}
}
else
{
Response.Write(“<script>alert(‘plese upload must’)</script>”);
}
}

protected void BttnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUploadImg.PostedFile.FileName).ToString();
FileUploadImg.SaveAs(Server.MapPath(@”/image/”) + filename);
string s1 = FileUploadImg.FileName;
ViewState["saveimage"] = s1;
Imgshow.ImageUrl = (@”/image/” + filename);
Imgshow.Visible = true;

}

protected void BttnReset_Click(object sender, EventArgs e)
{
txtName.Text = “”;
RadioBttnMale.Checked = false;
RadioBttnFemale.Checked = false;
txtAddress.Text = “”;
txtEmail.Text = “”;
DDLCountry.SelectedIndex = 0;
txtPhone.Text = “”;
Imgshow.ImageUrl = “”;
}
}
}

Edit Page

Design Page:

edit

 

 

 

 

 

 

 

 

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<table style=”margin: 0 auto; background-color: Gray; text-align: center;”>
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Gender:
</td>
<td>
<asp:TextBox ID=”txtGender” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Address:
</td>
<td>
<asp:TextBox ID=”txtAddress” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
EmailId:
</td>
<td>
<asp:TextBox ID=”txtEmail” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Country:
</td>
<td>
<asp:TextBox ID=”txtCountry” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
PhoneNo:
</td>
<td>
<asp:TextBox ID=”txtPhone” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Image:
</td>
<td>
<asp:ImageButton ID=”ImagePreview” runat=”server” Height=”35px” Width=”35px” />
<asp:FileUpload ID=”FileUploadUpdate” runat=”server” />
<asp:Button ID=”BttnPreview” runat=”server” Text=”Upload”
onclick=”BttnPreview_Click1″ />
</td>
</tr>
<tr>
<td>
<asp:Button ID=”bttnUpdate” runat=”server” Text=”Update” onclick=”bttnUpdate_Click” />
</td>
</tr>
</table>
</form>
</body>
</html>

 

 

Code Page:

using BussinessLayer;
using System.Data;

namespace PresentationLayer
{
public partial class UpdateForm : System.Web.UI.Page
{
BAL info = new BAL();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadpage();
}
}
public void loadpage()
{

int id = Convert.ToInt32(Request.QueryString["id"]);
if (id > 0)
{

DataSet ds = new DataSet();
ds = info.showprofile(id);
DataTable td = ds.Tables[0];
for (int i = 0; i < td.Rows.Count; i++)
{
txtName.Text = td.Rows[i]["name"].ToString();
txtGender.Text = td.Rows[i]["gender"].ToString();
txtAddress.Text = td.Rows[i]["Address"].ToString();
txtEmail.Text = td.Rows[i]["email"].ToString();
txtCountry.Text = td.Rows[i]["country"].ToString();
txtPhone.Text = td.Rows[i]["phone"].ToString();
ImagePreview.ImageUrl = @”/image/” + td.Rows[i]["image"].ToString();
ViewState["MImg"] = td.Rows[i]["image"].ToString();

 

}
}
}

protected void bttnUpdate_Click(object sender, EventArgs e)
{
string autoid = Request.QueryString["id"];
userUpdateInfo1 obuser = new userUpdateInfo1();
obuser.id = Convert.ToInt16(autoid);
obuser.name = txtName.Text.Trim();
obuser.gender = txtGender.Text.Trim();
obuser.address = txtAddress.Text.Trim();
obuser.email = txtEmail.Text.Trim();
obuser.country = txtCountry.Text.Trim();
obuser.phone =Convert.ToInt32(txtPhone.Text.Trim());
if (ViewState["MImg"] != null)
{
obuser.image = Convert.ToString(ViewState["MImg"]);
}
obuser.image = Convert.ToString(ViewState["MImg"]);
int i = info.updatenewdata(obuser);
if (i > 0)
{

Response.Redirect(“Show Details.aspx”);

}
else
{

}
}

 

protected void BttnPreview_Click1(object sender, EventArgs e)
{
string imgName = FileUploadUpdate.FileName;
FileUploadUpdate.SaveAs(Server.MapPath(@”/image/”) + imgName);
ViewState["MImg"] = imgName;

ImagePreview.ImageUrl = @”/image/” + imgName;

}
}
}

Show and Delete

Design Page:

Crude Operations

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<table>
<tr>
<td>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” OnRowCommand=”GridView1_RowCommand”
onrowdeleting=”GridView1_RowDeleting”>
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
<Columns>
<asp:TemplateField HeaderText=”ID”>
<ItemTemplate>
<asp:Label ID=”lblID” Text=’<%#Eval(“id”) %>’ runat=”server”></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<asp:Label ID=”lblName” Text=’<%#Eval(“name”) %>’ runat=”server”></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Gender”>
<ItemTemplate>
<asp:Label ID=”lblGender” runat=”server” Text=’<%#Eval(“gender”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Address”>
<ItemTemplate>
<asp:Label ID=”lblAddress” runat=”server” Text=’<%#Eval(“address”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”EmailId”>
<ItemTemplate>
<asp:Label ID=”lblEmail” runat=”server” Text=’<%#Eval(“email”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Country”>
<ItemTemplate>
<asp:Label ID=”lblCountry” runat=”server” Text=’<%#Eval(“country”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”PhoneNo.”>
<ItemTemplate>
<asp:Label ID=”lblPhone” runat=”server” Text=’<%#Eval(“phone”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Image”>
<ItemTemplate>
<asp:Image ID=”ImgBind” ImageUrl=’<%#getimage(Eval(“image”)) %>’ runat=”server” Height=”35px”
Width=”35px” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>

<asp:Button ID=”BttnEdit” runat=”server” Text=”Edit” CommandArgument=’<%#Eval(“id”) %>’ CommandName=”Edit” />
<asp:Button ID=”BttnDelete” runat=”server” Text=”Delete” CommandArgument=’<%#Eval(“id”) %>’
CommandName=”Delete” />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor=”#999999″ />
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<SortedAscendingCellStyle BackColor=”#E9E7E2″ />
<SortedAscendingHeaderStyle BackColor=”#506C8C” />
<SortedDescendingCellStyle BackColor=”#FFFDF8″ />
<SortedDescendingHeaderStyle BackColor=”#6F8DAE” />
</asp:GridView>
</td>
</tr>
</table>
</form>
</body>
</html>

 

Code Page:

using BussinessLayer;

namespace PresentationLayer
{
public partial class Show_Details : System.Web.UI.Page
{

BAL b1 = new BAL();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
load();
}
}
public string getimage(object ob)
{
string img = @”/image/” + ob.ToString();
return img;
}
public void load()
{
DataSet ds = new DataSet();
ds = b1.showdata();
GridView1.DataSource = ds;
GridView1.DataBind();
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == “Edit”)
{
int autoid = Convert.ToInt16(e.CommandArgument.ToString());
Response.Redirect(“UpdateForm.aspx?id=” + autoid);

}

if (e.CommandName == “Delete”)
{
//Page.RegisterStartupScript(“Success”, “<script>alert(‘Successfully Added’);</script>”);
int id = Convert.ToInt16(e.CommandArgument.ToString());

b1.deleteuserdata(id);

load();
}

}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

}
}
}

Example:  Download Code  SQL Script

7 comments on “3-Tier Architecture in asp.net using C# with Crude Operations

  1. Hi all,

    I am new to 3 tier architecture so please help me i try implementing the same but m getting an error.Object reference not set to an instance of an object.
    please anyone help me

    • raheel on said:

      i can help u contact me coz when i m begineer somebody helped me like this blog if u want any help then contact me

    • Abdul Khursheed on said:

      Hi Asha,

      Sorry for late reply,Can you tell me exactly where you getting the error in application.Provide the full details or mail me (abdulkhursheed@gmail.com) and then i’ll solve your problem.

      Thanks,
      Admin

  2. M Sravan Kumar on said:

    Hai…
    Am beginer in 3 tire Architecture it’s very nice example.I will follow you.

    Thank you&regards,
    M.sravan Kumar

  3. Kovendan on said:

    Nice man:)

  4. bhavani on said:

    nice

Leave a Reply

Your email address will not be published. Required fields are marked *

*

HTML tags are not allowed.