Thursday, 5 December 2013

3 tier architecture example in dotnet



In this article I will explain about uses of 3-Tier architecture and how to create and implement 3-tier architecture for our project in asp.net. 

 Uses of 3-Tier Architecture
  
1.    To make application more understandable (Flow of the code). 
2.    Easy to maintain, easy to modify application and we can maintain good look of architecture.
3.    If we use this 3-Tier application we can maintain our application in consistency manner.   

Basically 3-Tier architecture contains 3 layers

1.    Application Layer
2.    Business Logic Layer (BLL) 
3.    Data Access Layer (DAL)



Here I will explain each layer with simple example that is User Registration

Application Layer

Application layer contains UI part of our application i.e., our aspx pages or input is taken from the user. This layer mainly used for design purpose and get or set the data back and forth. Here I have designed my registration aspx page like this




This is Application layer for our project Design your page like this and double click on button save now in code behind we need to write statements to insert data into database this entire process related to Business Logic Layer and Data Access Layer.

Buntton click code for data saving

protected void btnSubmit_Click(object sender, EventArgs e)
        {
StudentRegistration objStudentRegistration = new StudentRegistration();
objStudentRegistration.FirstName = txtFirstName.Text;
objStudentRegistration.LastName = txtLastName.Text;
objStudentRegistration.Gender = ddlGender.SelectedItem.Text;

ds = objStudentManger.RegisterStudent(objStudentRegistration);
}

Now we will discuss about Business Logic Layer 

Business Logic Layer (BLL)

This layer contains our business logic, calculations related with the data like insert data, retrieve data and validating the data. This acts as interface between Application layer and Data Access Layer

Now I will explain this business logic layer with my sample

I have already finished form design (Application Layer) now I need to insert user details into database if user click on button save. Here user entering details regarding Firstname, Lastname, and Gender. I need to insert all these 3 parameters to database. Here we are placing all of our database actions into data access layer (DAL) in this case we need to pass all these 3 parameters to data access layers.
In this situation we will write one function and we will pass these 3 parameters to function like this
String Username= InserDetails (string Firstname, string Lastname, string Gender)

Don't get confuse just follow my instructions enough
How we have to create entity layer it is very simple 

Right click on your project web application---> select add new item ----> select class file in wizard ---> give name as BEL.CS because here I am using this name click ok

 Open the BEL.CS class file declare the parameters like this in entity layer 

Don’t worry about code it’s very simple for looking it’s very big nothing is there just parameters declaration that’s all check I have declared whatever the parameters I need to pass to data access layer I have declared those parameters only 

BEL.CS

#region Private Variables
/// <summary>
/// User Registration Variables
/// </summary>
private string _FirstName;
private string _LastName;
private string _Gender;
#endregion

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

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

public string Gender
{
get
{
return _ Gender;
}
set
{
_ Gender = value;
}
}

Our parameters declaration is finished now I need to create Business logic layer how I have create it follow same process for add one class file now give name called BLL.CS. Here one point don’t forget this layer will act as only mediator between application layer and data access layer based on this assume what this layer contains. Now I am writing the following BLL.CS(Business Logic layer)

public DataSet RegisterStudent(StudentRegistration objsr)
        {
            DataTable dt = CreateregisterDataTable();
            DataRow dr = dt.NewRow();
            dr["FirstName"] = objsr.FirstName;
            dr["LastName"] = objsr.LastName;
            dr["Gender"] = objsr.Gender;
     dt.Rows.Add(dr);
            DataSet ds = new DataSet("StudentRegistration");
            ds.Tables.Add(dt);
            string @xmlParam = ds.GetXml();

            DataSet DSTesting = new DataSet();
            DataBase objDB = new DataBase();
            DSTesting = objDB.SaveDataReturn(StoredProcedures.SPNames.savestudentregistrationdata, @xmlParam, 1);

            return DSTesting;

        }

private DataTable CreateregisterDataTable()
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn();
            dc.ColumnName = "FirstName";
            dc.DataType = Type.GetType("System.String");
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "LastName";
            dc.DataType = Type.GetType("System.String");
            dt.Columns.Add(dc);

            dc = new DataColumn();
            dc.ColumnName = "Gender";
            dc.DataType = Type.GetType("System.String");
            dt.Columns.Add(dc);
}


this DAL related our Data access layer. Check below information to know about that function and Data access layer

Data Access Layer(DAL)

Data Access Layer contains methods to connect with database and to perform insert,update,delete,get data from database based on our input data

I think it’s to much data now directly I will enter into DAL

Create one more class file like same as above process and give name as DAL.CS

Write the following code in DAL class file

public DataSet SaveDataReturn(StoredProcedures.SPNames SPName, string xmlParam, int flag)
        {
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());


            try
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
                con.Open();

                SqlCommand cmd = new SqlCommand(SPName.ToString(), con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter param1 = new SqlParameter();
                param1.Direction = ParameterDirection.Input;
                param1.DbType = DbType.String;
                param1.Value = xmlParam;
                param1.ParameterName = "@xmlParam";
                cmd.Parameters.Add(param1);

                SqlParameter param2 = new SqlParameter();
                param2.Direction = ParameterDirection.Input;
                param2.DbType = DbType.Int16;
                param2.Value = flag;
                param2.ParameterName = "@flag";
                cmd.Parameters.Add(param2);

                //SqlParameter outparam = new SqlParameter();
                //outparam.Direction = ParameterDirection.Output;
                //outparam.DbType = DbType.Int16;
                //outparam.Value = DBNull.Value;
                //outparam.ParameterName = "@outParam";
                //cmd.Parameters.Add(outparam);
                // cmd.ExecuteNonQuery();

                //cmd.Parameters.Add(param);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);

                return ds;

                //return (int)outparam.Value;
            }
            catch (Exception ex)
            {
                return ds;
            }
            finally
            {
                GC.Collect();
                con.Close();
            }
        }       
    }

Here if you observe above functionality I am getting all the parameters by simply creating BEL objBELUserDetails. If we create one entity file we can access all parameters through out our project by simply creation of one object for that entity class based on this we can reduce redundancy of code and increase re usability

Observe above code have u seen this function before? in BLL.CS i said i will explain it later got it in DAL.CS I have created one function InsertUserInformation and using this one in BLL.CS by simply creating one object of DAL in BLL.CS.

Here you will get one doubt that is why BLL.CS we can use this DAL.CS directly into our code behind  we already discuss Business logic layer provide interface between DAL and Application layer by using this we can maintain consistency to our application.



No comments:

Post a Comment