Wednesday, 13 March 2013

Example of 3 tier architecture in asp.net with C#



Description:-

Here in this example we explain that how to create 3-tier Architecture and implement 3 tier architecture in our project.


What are the Layers?
in N-Tier architecture. user create as much layer as possible to classify code in three different categories and put them in three different layers.

Basically there are 3 layers in 3-Tier Architectur
Application Layer or Presentation Layer
Buisness Access Layer or Buisness Logic Layer
Data Access Layer



 Uses of 3-tier Architecture:-

·         To make an application easily understandable to the user.
·         Better security than simple application.
·         Easy to maintain and understand and monitoring.
·        Separate the code

What is Presentation Layer:-

Presentation Tier is the tier in which the users interact with an application. Presentation Tier contents Shared UI code, Code Behind and Designers used to represent information to user.
Presentation Layer is the only layer which is directly connected with the user.  it’s a really important layer for marketing purposes. Presentation Layer is mainly used for getting user data and then passing it to Business Logic Layer for further procedure, and when data is received in Value Object then it’s responsible to represent value object in the appropriate form which user can understand.

What is Buisness Logic Layer (BLL):-

            In this Layer all part of the Coding or Logic is Defined with a Structure of a Class. All Function,Logic Code of the Insert Update Delete are Mentioned in this Layer. BLL is also known as Buisness Logic Layer.

What is Data Access  Layer (DAL):-

            In this Layer All part of the of the DataBase are Mentioned or Define in this Layer.it can Contain table,Procedure,Trigger,Function etc..


For Devloping three tier we have to create a two file one is student_BAL.cs And other is Student_DAL.cs 

The BAL (buisness access layer) is a file that can work as a midiator between two tier.
The DAL(data access layer) is a file that can define the all logic means all function or coding of the Form.

So through three tier you can secure your website and define in a proper way.


Implement Remember Me functionality using CheckBox ASP.Net 

set WaterMark Text in PDF using itextsharp in C#

How to set Default Button in MVC Web Form Application 

How to Bind XML File data to Treeview in asp.net

JQuery datepicker calender with Dropdown month and year in asp.net.


Default.aspx:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false" %>

<!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 id="Head1" runat="server">
<script type="text/javascript">

    function fun() {

        var s = document.getElementById("Div1");
        if (s.style.display == 'none')
            s.style.display = 'block';
    }



</script>

    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="foo" runat="server">
    <asp:Label ID="lblMessage" runat="Server" ForeColor="red" EnableViewState="False"></asp:Label>

        <table style="border:2px solid #cccccc;" id="tb" runat="server">

            <tr style="background-color:#507CD1;color:White;">

                <th colspan="3">Add Records</th>

            </tr>

            <tr>

                <td>

                    First Name:

                </td>

                <td>

                    <asp:TextBox ID="txtFirstName" runat="Server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="enter name" ControlToValidate="txtFirstName" Display="Dynamic"></asp:RequiredFieldValidator>

                </td>

                <td>

                  

                </td>

            </tr>

            <tr>

                <td>

                    Last Name:

                </td>

                <td>

                    <asp:TextBox ID="txtLastName" runat="Server"></asp:TextBox>
                       <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="enter name" ControlToValidate="txtLastName" Display="Dynamic"></asp:RequiredFieldValidator>
                </td>

                <td>


                </td>

            </tr>

            <tr>

                <td>

                    Age:

                </td>

                <td>

                    <asp:TextBox ID="txtAge" runat="Server" Columns="4"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="enter age" ControlToValidate="txtAge" Display="Dynamic"></asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator2" runat="server" ErrorMessage="only number is allowed" Operator="DataTypeCheck" Type="Integer" ControlToValidate="txtAge"></asp:CompareValidator>
                </td>

                <td>

                  
                </td>

            </tr>
        <tr>

                <td>

                    photo:

                </td>

                <td>

                    <asp:FileUpload ID="FileUpload1" runat="server" />
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="browse photo" ControlToValidate="FileUpload1" Display="Dynamic"></asp:RequiredFieldValidator>
                </td>

                <td>

                  
                </td>

            </tr>
            <tr>

                <td>

                    BirthDate:

                </td>

                <td>

                    <asp:TextBox ID="TextBox2" runat="Server" Columns="4"></asp:TextBox><img src="cal.png" alt="ss" width="30" height="30" onclick="fun()" />
                    <div id="Div1" style="display:none";>
        <asp:Calendar ID="Calendar1"
            runat="server"  SelectionMode="DayWeekMonth"
                onselectionchanged="Calendar1_SelectionChanged" BackColor="#0066FF"
                onvisiblemonthchanged="Calendar1_VisibleMonthChanged">
            <DayStyle BackColor="#FF0066" />
            </asp:Calendar></div>
        <asp:CompareValidator ID="CompareValidator1" runat="server"
            ControlToValidate="TextBox2" ErrorMessage="only date is allowed."
            Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>
                </td>

                <td>

                </td>

            </tr>
            <tr>

                <td>&nbsp;</td>

                <td>

                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="AddRecords" />

                </td>

            </tr>

        </table>
                <asp:GridView ID="GridView1" runat="server"
        ForeColor="#333333" GridLines="None"

         DataKeyNames="id"  AutoGenerateColumns="False"
         
          OnRowDeleting="DeleteRecord"
        onrowcancelingedit="GridView1_RowCancelingEdit"
        onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
            CellPadding="4" >

            <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="id" HeaderText="ID" ReadOnly="True"  SortExpression="id" />

                <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">

                    <ItemTemplate>

                        <%# Eval("FirstName") %>

                    </ItemTemplate>

                    <EditItemTemplate>

                        <asp:TextBox ID="txtFName" runat="Server" Text='<%# Eval("FirstName") %>'></asp:TextBox>

                    </EditItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="LastName" SortExpression="LastName">

                    <ItemTemplate>

                        <%# Eval("LastName") %>

                    </ItemTemplate>

                    <EditItemTemplate>

                        <asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName") %>'></asp:TextBox>

                    </EditItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Age" SortExpression="age">

                    <ItemTemplate>

                        <%# Eval("age") %>

                    </ItemTemplate>

                    <EditItemTemplate>

                        <asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("age") %>'></asp:TextBox>

                    </EditItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="photo" SortExpression="photo">

                    <ItemTemplate>

                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("photo") %>' AlternateText="image" Width="80" Height="80" />
                    </ItemTemplate>

                    <EditItemTemplate>

                        <asp:FileUpload ID="FileUpload2" runat="server" />

                    </EditItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="BirthDate" SortExpression="birthdate">

                    <ItemTemplate>

                        <%# ((DateTime)Eval("birthdate")).ToString("dd/MM/yyyy")%>

                    </ItemTemplate>

                    <EditItemTemplate>

                        <asp:TextBox ID="txtbd" runat="Server" Text='<%# ((DateTime)Eval("birthdate")).ToString("dd/MM/yyyy") %>'></asp:TextBox>
                      
                    </EditItemTemplate>

                </asp:TemplateField>
                <asp:CommandField ButtonType="Button" ShowEditButton="true"  ShowCancelButton="true" CausesValidation="false" />
                <asp:CommandField ButtonType="Button" ShowDeleteButton="true" />
              
            </Columns>    </asp:GridView>

    <br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

  
    </div>

    </form>
</body>
</html>



Default.aspx.cs

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.Configuration;

using System.Web.Security;

using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Text;
using System.Xml;



public partial class _Default : System.Web.UI.Page
{
    private void BindGrid()
    {

        PersonBAL3 p = new PersonBAL3();
        DataTable result;

        result = p.Load();

        GridView1.DataSource = result;

        GridView1.DataBind();

    }
    protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
    {

        int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());


        PersonBAL3 pBAL = new PersonBAL3();

        pBAL.Delete(id);
        lblMessage.Text = "Record Deleted Successfully.";

        GridView1.EditIndex = -1;

        BindGrid();

    }
    public void clear()
    {
        txtFirstName.Text = "";
        txtLastName.Text = "";
        txtAge.Text = "";
        TextBox2.Text = "";

    }
    protected void AddRecords(object sender, EventArgs e)
    {
        int intResult = 0;



        PersonBAL3 pBAL = new PersonBAL3();

        string firstName = txtFirstName.Text;

        string lastName = txtLastName.Text;

        int age = Int32.Parse(txtAge.Text);
        string photo = "~/image/" + FileUpload1.FileName;
        string birthdate = TextBox2.Text;
        string fileExtension = Path.GetExtension(FileUpload1.FileName.ToString());
        fileExtension.ToLower();
        if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".png")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only jpeg,jpg,png,gif photo is allowed');</script>");
            return;
        }
        string serverPath = Server.MapPath(@"~/image/" + FileUpload1.FileName);
        FileUpload1.SaveAs(serverPath);

        intResult = pBAL.Insert(firstName, lastName, age, photo, birthdate);

        if (intResult > 0)
        {
            lblMessage.Text = "New record inserted successfully.";
            BindGrid();
            clear();
        }
        else
        {

            lblMessage.Text = "FirstName [<b>" + txtFirstName.Text + "</b>] alredy exists, try another name";
        }


    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGrid();
        }
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int id = 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");
        FileUpload ph = (FileUpload)row.FindControl("FileUpload2");
        TextBox bd = (TextBox)row.FindControl("txtbd");
        PersonBAL3 pBAL = new PersonBAL3();
        string photo = "~/image/" + ph.FileName;


        string fileExtension = Path.GetExtension(ph.FileName.ToString());
        fileExtension.ToLower();
        if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".png")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only jpeg,jpg,png,gif photo is allowed');</script>");
            return;
        }
        string serverPath = Server.MapPath(@"~/image/" + ph.FileName);
        ph.SaveAs(serverPath);

        intResult = pBAL.Update(id, tFN.Text, tLN.Text, int.Parse(tAge.Text), photo, bd.Text);

        if (intResult > 0)

            lblMessage.Text = "Record Updated Successfully.";

        else

            lblMessage.Text = "Record couldn't updated";
        GridView1.EditIndex = -1;

        BindGrid();



    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {


        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        e.Cancel = true;
        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        TextBox2.Text = Calendar1.SelectedDate.ToString("d");


    }
    protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
    {
        DateTime nextMonth = DateTime.Now.AddMonths(1);
        Calendar1.TodaysDate = nextMonth;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;

        GridView1.AllowPaging = false;
        GridView1.DataBind();
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        System.Text.StringBuilder SB = new System.Text.StringBuilder();
        System.IO.StringWriter SW = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlTW = new System.Web.UI.HtmlTextWriter(SW);
        foo.RenderControl(htmlTW);
        string strBody = "<html>" +
            "<body>" + "<div><b>" + htmlTW.InnerWriter.ToString() + "</b></div>" +
            "</body>" +
            "</html>";
        //string strBody = "<html>" + "<body>" + strResponsePageContent.ToString() + htmlTW.InnerWriter.ToString() + "</body>" +
        //   "</html>";    
        string fileName = "MsWordSample.doc";
        // You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
        Response.AppendHeader("Content-Type", "application/msword");
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.ContentEncoding = System.Text.Encoding.UTF7;

        string fileName1 = "Z://kiit/books" + DateTime.Now.Millisecond.ToString();
        BinaryWriter writer = new BinaryWriter(File.Open(fileName1, FileMode.Create));
        writer.Write(strBody);
        writer.Close();
        FileStream fs = new FileStream(fileName1, FileMode.Open, FileAccess.Read);
        byte[] renderedBytes;
        // Create a byte array of file stream length
        renderedBytes = new byte[fs.Length];
        //Read block of bytes from stream into the byte array
        fs.Read(renderedBytes, 0, System.Convert.ToInt32(fs.Length));
        //Close the File Stream
        fs.Close();
        FileInfo TheFile = new FileInfo(fileName1);
        if (TheFile.Exists)
        {
            File.Delete(fileName1);
        }
        Response.BinaryWrite(renderedBytes);
        Response.Flush();
        Response.End();
    }



    public override void VerifyRenderingInServerForm(Control control)
    {

        /* Verifies that the control is rendered */

    }

}






PersonBAL3.cs

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;


public class PersonBAL3
{

    public int Insert(string FirstName, string LastName, int age, string photo, string birthdate)
    {

        PersonDAL3 pDAL = new PersonDAL3();

        try
        {

            return pDAL.Insert(FirstName, LastName, age, photo, birthdate);

        }

        catch
        {

            throw;

        }

        finally
        {

            pDAL = null;

        }

    }

    public int Update(int id, string FirstName, string LastName, int age, string photo, string birthdate)
    {

        PersonDAL3 pDAL = new PersonDAL3();

        try
        {

            return pDAL.Update(id, FirstName, LastName, age, photo, birthdate);

        }

        catch
        {

            throw;

        }

        finally
        {

            pDAL = null;

        }

    }

    public DataTable Load()
    {

        PersonDAL3 pDAL = new PersonDAL3();

        try
        {

            return pDAL.Load();

        }

        catch
        {

            throw;

        }

        finally
        {

            pDAL = null;

        }

    }

    public int Delete(int id)
    {

        PersonDAL3 pDAL = new PersonDAL3();

        try
        {

            return pDAL.Delete(id);

        }

        catch
        {

            throw;

        }

        finally
        {

            pDAL = null;

        }

    }



}





PersonDAL3.cs

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;

public class PersonDAL3
{

    string connStr = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demod;Password=Demo1@";

    public int Insert(string FirstName, string LastName, int age, string photo, string birthdate)
    {

        SqlConnection conn = new SqlConnection(connStr);

        conn.Open();

        SqlCommand dCmd = new SqlCommand("dbo.insdata", conn);

        dCmd.CommandType = CommandType.StoredProcedure;

        try
        {

            dCmd.Parameters.AddWithValue("@FirstName", FirstName);

            dCmd.Parameters.AddWithValue("@LastName", LastName);

            dCmd.Parameters.AddWithValue("@age", age);
            dCmd.Parameters.AddWithValue("@photo", photo);
            dCmd.Parameters.AddWithValue("@birthdate", birthdate);
            return dCmd.ExecuteNonQuery();

        }

        catch
        {

            throw;

        }

        finally
        {

            dCmd.Dispose();

            conn.Close();

            conn.Dispose();

        }

    }

    public int Update(int id, string FirstName, string LastName, int age, string photo, string birthdate)
    {

        SqlConnection conn = new SqlConnection(connStr);

        conn.Open();

        SqlCommand dCmd = new SqlCommand("dbo.updata", conn);

        dCmd.CommandType = CommandType.StoredProcedure;

        try
        {
            dCmd.Parameters.AddWithValue("@id", id);
            dCmd.Parameters.AddWithValue("@FirstName", FirstName);

            dCmd.Parameters.AddWithValue("@LastName", LastName);

            dCmd.Parameters.AddWithValue("@age", age);
            dCmd.Parameters.AddWithValue("@photo", photo);
            dCmd.Parameters.AddWithValue("@birthdate", birthdate);


            return dCmd.ExecuteNonQuery();

        }

        catch
        {

            throw;

        }

        finally
        {

            dCmd.Dispose();

            conn.Close();

            conn.Dispose();

        }

    }


    public DataTable Load()
    {

        SqlConnection conn = new SqlConnection(connStr);

        SqlDataAdapter dAd = new SqlDataAdapter("dbo.seldata1", conn);

        dAd.SelectCommand.CommandType = CommandType.StoredProcedure;

        DataSet dSet = new DataSet();

        try
        {

            dAd.Fill(dSet, "tier");
            //da.Fill(dtset, "tb_sproctest");
            return dSet.Tables["tier"];
        }

        catch
        {

            throw;

        }

        finally
        {

            dSet.Dispose();

            dAd.Dispose();

            conn.Close();

            conn.Dispose();

        }


    }

    public int Delete(int id)
    {

        SqlConnection conn = new SqlConnection(connStr);

        conn.Open();

        SqlCommand dCmd = new SqlCommand("dbo.deldata", conn);

        dCmd.CommandType = CommandType.StoredProcedure;

        try
        {

            dCmd.Parameters.AddWithValue("@id", id);

            return dCmd.ExecuteNonQuery();

        }

        catch
        {

            throw;

        }

        finally
        {

            dCmd.Dispose();

            conn.Close();

            conn.Dispose();

        }

    }




}

0 comments:

Post a Comment