1. Trang chủ
  2. » Công Nghệ Thông Tin

4-Tier Architecture in ASP.NET with C#

26 450 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề 4-Tier Architecture in ASP.NET with C#
Thể loại Article
Định dạng
Số trang 26
Dung lượng 115,5 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

After reading this article, I can see the benefits to add a Business Access Layer in some complex scenarios.From the author: Almost all of us must have heard about 3-Tier architecture bu

Trang 1

4-Tier Architecture in ASP.NET with C#

I am using 3-Tier architecture in my different projects, but adding a 4th tier is a novelty for me

After reading this article, I can see the benefits to add a Business Access Layer in some complex scenarios.From the author:

Almost all of us must have heard about 3-Tier architecture but what is this 4-Tier architecture? What are the benefits and how it is different from other architectures?

Well, the architecture I am going to demonstrate here is just enhancement of 3-Tier archicture In this

architecture; you no need of writing long function parameters throughout the layers (as in traditionally 3-Tier archicture has to) and the actual objects of the application will be in a separate tier so that in future you can separately use these objects for enhancements Change in the object definition can be done without touching the entire Business Access Layers

Let me explain you step-wise process of creatioin of 4-Tier architecture application

In this application, I am going to take example of a Person that will have 3 properties: FirstName, LastName, Age We will create a separate pages to insert these records (default.aspx) into database and list,update,delete records (list.aspx) from database

In this application we will have following 4-Tiers

1 Business Object [BO]

2 Business Access Layer [BAL]

3 Data Access Layer [DAL]

4 UI (4-Tier) folder [UI]

Well, the architecture I am going to demonstrate here is just enhancement of 3-Tier archicture In this

architecture; you no need of writing long function parameters throughout the layers (as in traditionally 3-Tier archicture has to) and the actual objects of the application will be in a separate tier so that in future you can separately use these objects for enhancements Change in the object definition can be done without touching the entire Business Access Layers

Let me explain you step-wise process of creatioin of 4-Tier architecture application

In this application, I am going to take example of a Person that will have 3 properties: FirstName, LastName, Age

We will create a separate pages to insert these records (default.aspx) into database and list,update,delete records(list.aspx) from database

In this application we will have following 4-Tiers

1 Business Object [BO]

2 Business Access Layer [BAL]

3 Data Access Layer [DAL]

4 UI (4-Tier) folder [UI]

Picture - 1 (Solution Explorer)

For simplicity reason, I have created separate folders for first 3-tiers into App_Code folder You can create a separate projects for these tiers and add into forth tier (UI) solution

Lets create above tiers one by one

Business Object [BO - Person.cs]

Create a separate folder by right-clicking App_Code folder and name it as BO Right click this folder and create a new cs (Class) file named Person.cs Write following code inside it

Trang 2

- Hide Code

int m_PersonID = 0;

string m_FirstName = string.Empty; string m_LastName = string.Empty; int m_Age = 0;

public int Age

{

get { return m_Age; }

set { m_Age = value; }

Trang 3

}

#endregion Properties

Here, we are first declaring 4 variables for corresponding properites and defining properties for them.This is your Business Object with all its properties/attributes to work with Next step is to create Data Access Layer

Data Access Layer [DAL - PersonDAL.cs]

The way you created BO folder inside App_Code folder, create another folder named DAL Create a cs file inside itand name it as PersonDAL.cs

Write following code inside it (You can copy-paste)

Trang 5

dCmd.Parameters.AddWithValue("@personID", person.PersonID); return dCmd.ExecuteNonQuery();

}

catch

{

throw;

Trang 6

SqlConnection conn = new SqlConnection(connStr);

SqlDataAdapter dAd = new SqlDataAdapter("LoadAll", conn);

dAd.SelectCommand.CommandType = CommandType.StoredProcedure; DataSet dSet = new DataSet();

Trang 8

In this class file, we have Insert, Update, Delete, Load methods In this class file, first I am getting the connection

string from the web.config file in a class level variable called connStr and using the same string in all my methods

to open the connection

For simplicity reason, I have not shown the code for Stored Procedure, however you can get the complete database and code by downloading the Source Code files This was your Data Access Layer Till

now you have your Business Object and Data Access Layer ready Now lets go to the third layer and create Business Access Layer

Business Access Layer [BAL - PersonBAL.cs]

Again, right click App_Code folder and add a new folder named BAL Create a new class file inside it and name it

as PersonBAL.cs Write following code inside it

Trang 9

/// Summary description for PersonBAL/// </summary>

public class PersonBAL

public int Insert(Person person)

Trang 10

public int Update(Person person)

Trang 11

public int Delete(Person person)

catch

Trang 12

You must have noticed here that in the try catch block, I am just writing throw; statement This is because when any error will occur it will be send to the calling layers (in our case UI) and there we will handle it

Till now, we have BO, BAL and DAL ready Now we are left with our application face, I mean UI Lets first create default.aspx file that will contain one form and textboxs that will be used to enter records

User Interface - [UI]-Default.aspx

Create a separate folder in your UI solution named 4-Tier and add one aspx page called Default.aspx (Picture - 2) In this page, we will write ASP.NET code to render textboxes and buttons OnClick event of the button we will

calll AddRecords method that will ultimately insert the records into database Below is the code to render the

asp.net form

- Hide Code

<form id="form1" runat="server">

<div>

<p><a href="List.aspx">List Records</a></p>

<asp:Label ID="lblMessage" runat="Server" ForeColor="red"

EnableViewState="False"></asp:Label>

<table style="border:2px solid #cccccc;">

Trang 13

</tr>

Trang 14

<asp:CompareValidator ID="Comp1" runat="Server" Text="Only integer"

ControlToValidate="txtAge" Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>

Trang 15

// Page is valid, lets go ahead and insert records

// Instantiate BAL object

PersonBAL pBAL = new PersonBAL();

// Instantiate the object we have to deal with

Person person = new Person();

// set the properties of the object

Trang 16

In the above method, I am doing following things mainly:

1 Instantiating BAL object

2 Instantiating BO object

3 Settinng properties of BO object by the textbox values

4 Calling Insert method of the BAL object and passing BO object as parameter [pBAL.Insert(person)] in try block

5 Checking for number of records affected, If the number is more than zero, I am writing Success message otherwise Duplicate records found

6 If any layer will throw any error, I am catching it and displaying to the user in throw block

7 Whatever objects I had instantiated, I am specifying their values to null to let the GC know that I am no more going to use them

User Interface - [UI]-List.aspx

In this page, I am going to use a GridView to List, Modify, Sort and Delete records from the database Create

an aspx page in the same 4-Tier folder named List.aspx (Picture - 3) Following is the code for the GridView that will do data manipulation for us

- Hide Code

<form id="form1" runat="server">

<div>

<p><a href="Default.aspx">Add Record</a></p>

<asp:Label ID="lblMessage" runat="Server" ForeColor="red" EnableViewState="False"></asp:Label> <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"

Trang 17

DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False"

OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord" OnRowDeleting="DeleteRecord" AllowPaging="True" AllowSorting="true" PageSize="5"

OnPageIndexChanging="ChangePage" OnSorting="SortRecords">

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<RowStyle BackColor="#EFF3FB" />

<EditRowStyle BackColor="#2ff1BF" />

<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

Trang 18

<span onclick="return confirm('Are you sure to Delete?')">

<asp:LinkButton ID="lnBD" runat="server" Text="Delete"

Trang 20

GridViewRow row = GridView1.Rows[e.RowIndex];

TextBox tFN = (TextBox) row.FindControl("txtFName");

TextBox tLN = (TextBox)row.FindControl("txtLName");

TextBox tAge = (TextBox)row.FindControl("txtAge");

// instantiate BAL

PersonBAL pBAL = new PersonBAL();

Person person = new Person();

Trang 22

PersonBAL pBAL = new PersonBAL();

Person person = new Person();

Trang 23

protected void ChangePage(object sender, GridViewPageEventArgs e) {

Trang 24

PersonBAL p = new PersonBAL();

DataTable dTable = new DataTable(); try

finally

{

p = null;

}

Trang 25

string sortDirection = string.Empty;

// if clicked on the same column twice then let it toggle the sort order, else reset to ascending

Trang 26

Browse it as http://localhost/4-Tier (Provided you have created "4-Tier" virtual directory in your IIS or you can choose your own virtual directory name), you should see your screens as shown above (default.aspx and list.aspx pages)

Try manipulating data and see how effectively its happening This was a simple application, based on this

architecture, you can create larger application by adding separate objects and their corresponding tiers

In order to use namespace in different tiers, you should define your namespace in respective tiers objects and usethose namespace by using statement whereever you need

Ngày đăng: 17/10/2013, 14:15

TỪ KHÓA LIÊN QUAN

w