4-Tier Architecture in ASP.NET with C#

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]

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.

– Hide Code

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

    #region Propertiers 
    public int PersonID 
    { 
        get { return m_PersonID; } 
        set { m_PersonID = value; } 
    } 

    public string FirstName 
    { 
        get { return m_FirstName; } 
        set { m_FirstName = value; } 
    } 

    public string LastName 
    { 
        get { return m_LastName; } 
        set { m_LastName = value; } 
    } 

    public int Age 
    { 
        get { return m_Age; } 
        set { m_Age = value; } 
    } 
    #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 it and name it as PersonDAL.cs

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

– Hide Code

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Data.SqlClient; 

/// <summary> 
/// Summary description for PersonDAL 
/// </summary> 
public class PersonDAL : IDisposable         
{ 
    string connStr = ConfigurationManager.ConnectionStrings["TutTestConn"].ToString(); 
    SqlConnection conn = null; 

	public PersonDAL() 
	{ 
        conn = new SqlConnection(connStr); 
        conn.Open(); 
	} 

    /// <summary> 
    /// Used to insert records into database 
    /// </summary> 
    /// <param name="p"></param> 
    /// <returns></returns> 
    public int Insert(Person person) 
    { 

        // If any duplicate recods found, then return 0 that will indicate in the UI that no records inserted as  

firstname already exists 
        if (CheckForDuplicateRecord(person.FirstName) > 0) 
            return 0; 

        // go ahead with inserting records into database 
        string strSql = "INSERT INTO Person (firstname, lastname, age) VALUES ('" + 
            person.FirstName + "', '" + person.LastName + "', " + person.Age + ")"; 

        SqlCommand dCmd = new SqlCommand(strSql, conn); 
        try 
        { 
            return dCmd.ExecuteNonQuery(); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            dCmd.Dispose(); 
        } 
    } 

    /// <summary> 
    /// Update record into database 
    /// </summary> 
    /// <param name="p"></param> 
    /// <returns></returns> 
    public int Update(Person person) 
    { 
        string connStr = ConfigurationManager.ConnectionStrings["TutTestConn"].ToString(); 
        string strSql = "UPDATE Person SET firstname = '" + person.FirstName + "', lastname = '" +  

person.LastName + "', " + 
            "age = " + person.Age + " WHERE PersonID = " + person.PersonID; 

        SqlConnection conn = new SqlConnection(connStr); 
        conn.Open(); 
        SqlCommand dCmd = new SqlCommand(strSql, conn); 
        try 
        { 
            return dCmd.ExecuteNonQuery(); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            dCmd.Dispose(); 
        } 
    } 

    /// <summary> 
    /// Load all records from database 
    /// </summary> 
    /// <returns></returns> 
    public DataTable Load() 
    { 
        string strSql = "SELECT * FROM Person ORDER BY FirstName"; 
        SqlConnection conn = new SqlConnection(connStr); 
        conn.Open(); 
        SqlDataAdapter dAd = new SqlDataAdapter(strSql, conn); 
        DataSet dSet = new DataSet(); 
        try 
        { 
            dAd.Fill(dSet, "PersonTable"); 
            return dSet.Tables["PersonTable"]; 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            dSet.Dispose(); 
            dAd.Dispose(); 
        } 
    } 

    /// <summary> 
    /// Search records from database using its Local connection  
    /// </summary> 
    /// <param name="person"></param> 
    /// <returns></returns> 
    public DataTable SearchFirstName(Person person) 
    { 
        string strSql = "SELECT * FROM Person WHERE firstname LIKE '%" + person.FirstName + "%'  

ORDER BY firstname";  
        SqlConnection localConn = new SqlConnection(connStr); 
        conn.Open(); 

        SqlDataAdapter dAd = new SqlDataAdapter(strSql, localConn); 
        DataSet dSet = new DataSet(); 
        try 
        { 
            dAd.Fill(dSet, "SearchResult"); 
            return dSet.Tables["SearchResult"]; 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            dSet.Dispose(); 
            dAd.Dispose(); 
            localConn.Close(); 
            localConn.Dispose(); 

            // As we are not using public connection here, so lets close it explicitely here 
            this.Dispose(); 
        } 

    } 

    /// <summary> 
    /// delete record from database 
    /// </summary> 
    /// <param name="person"></param> 
    /// <returns></returns> 
    public int delete(Person person) 
    { 
        string strSql = "delete Person WHERE PersonID = " + person.PersonID; 
        SqlCommand dCmd = new SqlCommand(strSql, conn); 
        try 
        { 
            return dCmd.ExecuteNonQuery(); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            dCmd.Dispose(); 
        } 
    } 

    /// <summary> 
    /// Check for duplicate records based on first name 
    /// </summary> 
    /// <param name="firstName"></param> 
    /// <returns></returns> 
    public int CheckForDuplicateRecord(string firstName) 
    { 
        string strSql = "select PersonID from Person WHERE FirstName = '" + firstName + "'"; 
        // check for the duplicate records 
        SqlCommand dCmd = new SqlCommand(strSql, conn); 
        try 
        { 
            object obj = dCmd.ExecuteScalar(); 
            if (obj != null) 
                return 1; 
            else 
                return 0; 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            dCmd.Dispose(); 
        } 
    } 

    #region IDisposable Members 

    public void Dispose() 
    { 
        conn.Close(); 
        conn.Dispose(); 
    } 

    #endregion 
}

In this class file, we have Insert, Update, delete, Load and few other supporting methods. In this class file, first I am getting the connectionstring from the web.config file in a class level variable named connStr and defining a class level SqlConnection variable. In the constructor of this class, I am instantiating the connection object with the connectionstring and opening the connection.

Instead of using above approach you can open and close connection in respective methods. Just for demonstration purpose, I have created SearchFirstName method that use its internal connection object and close when work is done.

For simplicity reason, I have not used Store Procedure to Insert, Update, delete or Load records. You can use stored procedure here in the way it is used normally. 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.

– Hide Code

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 

/// <summary> 
/// Summary description for PersonBAL 
/// </summary> 
public class PersonBAL 
{ 
	public PersonBAL() 
	{ 

	} 

    /// <summary> 
    /// insert records into database 
    /// </summary> 
    /// <param name="person"></param> 
    /// <returns></returns> 
    public int Insert(Person person) 
    { 
        PersonDAL pDAL = new PersonDAL(); 
        try 
        { 
            return pDAL.Insert(person); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            pDAL.Dispose(); 
        } 
    } 

    /// <summary> 
    /// Update records into database 
    /// </summary> 
    /// <param name="person"></param> 
    /// <returns></returns> 
    public int Update(Person person) 
    { 
        PersonDAL pDAL = new PersonDAL(); 
        try 
        { 
            return pDAL.Update(person); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            pDAL.Dispose(); 
        } 
    } 

    /// <summary> 
    /// Load records from database 
    /// </summary> 
    /// <returns></returns> 
    public DataTable Load() 
    { 
        PersonDAL pDAL = new PersonDAL(); 
        try 
        { 
            return pDAL.Load(); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            pDAL.Dispose(); 
        } 
    } 

    /// <summary> 
    /// Search  
    /// </summary> 
    /// <param name="person"></param> 
    /// <returns></returns> 
    public DataTable SearchFirstName(Person person) 
    { 
        PersonDAL pDAL = new PersonDAL(); 
        try 
        { 
            return pDAL.SearchFirstName(person); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            pDAL = null; 
        } 
    } 

    /// <summary> 
    /// delete record from database 
    /// </summary> 
    /// <param name="person"></param> 
    /// <returns></returns> 
    public int delete(Person person) 
    { 
        PersonDAL pDAL = new PersonDAL(); 
        try 
        { 
            return pDAL.delete(person); 
        } 
        catch 
        { 
            throw; 
        } 
        finally 
        { 
            pDAL.Dispose(); 
        } 
    } 

}

Here, we are creating separate methods each for respective PersonDAL.cs methods here. As in our case we don’t have any business logic, so we are just instantiating the Data Access Layer objects, using its methods and and returning to UI (fourth layer, described later on).

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;"> 
            <tr style="background-color:#ECF3AB;"> 
                <th colspan="3">Add Records</th> 
            </tr> 
            <tr> 
                <td> 
                    First Name: 
                </td> 
                <td> 
                    <asp:TextBox ID="txtFirstName" runat="Server"></asp:TextBox> 
                </td> 
                <td> 
                    <asp:RequiredFieldValidator ID="req1" runat="Server" Text="*"  

ControlToValidate="txtFirstName" Display="dynamic"></asp:RequiredFieldValidator> 
                </td> 
            </tr> 
            <tr> 
                <td> 
                    Last Name: 
                </td> 
                <td> 
                    <asp:TextBox ID="txtLastName" runat="Server"></asp:TextBox> 
                </td> 
                <td> 
                    <asp:RequiredFieldValidator ID="req2" runat="Server" Text="*"  

ControlToValidate="txtLastName" Display="dynamic"></asp:RequiredFieldValidator> 
                </td> 
            </tr> 
            <tr> 
                <td> 
                    Age: 
                </td> 
                <td> 
                    <asp:TextBox ID="txtAge" runat="Server" Columns="4"></asp:TextBox> 
                </td> 
                <td> 
                    <asp:RequiredFieldValidator ID="req3" runat="Server" Text="*" ControlToValidate="txtAge"  

Display="dynamic"></asp:RequiredFieldValidator> 
                    <asp:CompareValidator ID="Comp1" runat="Server" Text="Only integer"  

ControlToValidate="txtAge" Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator> 
                </td> 
            </tr> 
            <tr> 
                <td> </td> 
                <td> 
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="AddRecords" /> 
                </td> 
            </tr> 
        </table> 
    </div> 
    </form>

Picture – 2 (Default.aspx)

AddRecords method

– Hide Code

protected void AddRecords(object sender, EventArgs e) 
    { 
        //Lets validate the page first 
        if (!Page.IsValid) 
            return; 

        int intResult = 0; 
        // 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 
        person.FirstName = txtFirstName.Text; 
        person.LastName = txtLastName.Text; 
        person.Age = Int32.Parse(txtAge.Text); 

        try 
        { 
            intResult = pBAL.Insert(person); 
            if (intResult > 0) 
                lblMessage.Text = "New record inserted successfully."; 
            else 
                lblMessage.Text = "FirstName [<b>"+ txtFirstName.Text +"</b>] alredy exists, try another  

name"; 

        } 
        catch (Exception ee) 
        { 
            lblMessage.Text = ee.Message.ToString(); 
        } 
        finally 
        { 
            person = null; 
            pBAL = null; 
        }         
    }

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 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" 
         DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False" 
          OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord"  

OnRowCancelingEdit="CancelRecord" 
           OnRowDeleting="deleteRecord"> 
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> 
            <RowStyle BackColor="#EFF3FB" /> 
            <EditRowStyle BackColor="#2461BF" /> 
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> 
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> 
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> 
            <AlternatingRowStyle BackColor="White" /> 
            <Columns> 
                <asp:BoundField DataField="PersonID" HeaderText="Person ID" /> 
                <asp:TemplateField HeaderText="First Name"> 
                    <ItemTemplate> 
                        <%# Eval("FirstName") %> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="txtFName" runat="Server" Text='<%# Eval("FirstName")  

%>'></asp:TextBox> 
                    </EditItemTemplate> 
                </asp:TemplateField> 
                <asp:TemplateField HeaderText="Last Name"> 
                    <ItemTemplate> 
                        <%# Eval("LastName") %> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName")  

%>'></asp:TextBox> 
                    </EditItemTemplate> 
                </asp:TemplateField> 
                <asp:TemplateField HeaderText="Age"> 
                    <ItemTemplate> 
                        <%# Eval("Age") %> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("Age") %>'></asp:TextBox> 
                    </EditItemTemplate> 
                </asp:TemplateField> 
                <asp:TemplateField HeaderText="delete?"> 
                    <ItemTemplate> 
                        <span onclick="return confirm('Are you sure to delete?')"> 
                            <asp:LinkButton ID="lnBD" runat="server" Text="delete"  

CommandName="delete"></asp:LinkButton> 
                        </span> 
                    </ItemTemplate> 
                </asp:TemplateField> 

            </Columns> 
        </asp:GridView> 
    </div> 
    </form>

Picture – 3 (List.aspx)

On the OnRowEditing, OnRowUpdating, OnRowCancelEdit and OnRowDeleting events we are calling respective methods to do data manipulation. Following are codes to bind the GridView and methods that will fire on GridView events.

– Hide Code

protected void Page_Load(object sender, EventArgs e) 
    { 
        if (!IsPostBack) 
            BindGrid(); 
    } 

    private void BindGrid() 
    { 
        PersonBAL p = new PersonBAL(); 
        try 
        { 
            GridView1.DataSource = p.Load(); 
            GridView1.DataBind(); 
        } 
        catch (Exception ee) 
        { 
            lblMessage.Text = ee.Message.ToString(); 
        } 
        finally 
        { 
            p = null; 
        } 
    } 

    /// <summary> 
    /// Fired when Cancel button is clicked 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void CancelRecord(object sender, GridViewCancelEditEventArgs e) 
    { 
        GridView1.EditIndex = -1; 
        BindGrid(); 
    } 

    /// <summary> 
    /// Fires when Edit button is clicked 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void EditRecord(object sender, GridViewEditEventArgs e) 
    { 
        GridView1.EditIndex = e.NewEditIndex; 
        BindGrid(); 
    } 

    /// <summary> 
    /// Fires when Update button is clicked 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void UpdateRecord(object sender, GridViewUpdateEventArgs e) 
    { 
        int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString()); 
        int intResult = 0; 
        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(); 
        try 
        { 
            person.PersonID = personID; 
            person.FirstName = tFN.Text; 
            person.LastName = tLN.Text; 
            person.Age = Int32.Parse(tAge.Text); 
            intResult = pBAL.Update(person); 
            if (intResult > 0) 
                lblMessage.Text = "Record Updated Successfully."; 
            else 
                lblMessage.Text = "Record couldn't updated"; 
        } 
        catch (Exception ee) 
        { 
            lblMessage.Text = ee.Message.ToString(); 
        } 
        finally 
        { 
            person = null; 
            pBAL = null; 
        } 

        GridView1.EditIndex = -1; 
        // Refresh the list 
        BindGrid(); 
    } 

    /// <summary> 
    /// fires when delete button is clicked 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void deleteRecord(object sender, GridViewdeleteEventArgs e) 
    { 
        int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());  

        // instantiate BAL 
        PersonBAL pBAL = new PersonBAL(); 
        Person person = new Person(); 
        try 
        { 
            person.PersonID = personID; 
            pBAL.delete(person); 

            lblMessage.Text = "Record deleted Successfully."; 
        } 
        catch (Exception ee) 
        { 
            lblMessage.Text = ee.Message.ToString(); 
        } 
        finally 
        { 
            person = null; 
            pBAL = null; 
        } 

        GridView1.EditIndex = -1; 
        // Refresh the list 
        BindGrid(); 
    }

http://www.dotnetfunda.com/articles/article18.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: