Wednesday, September 28

ImageBinding In GridView Where ImageUrl taking From SqlServer DataBase

I have taken One Asp.net image control, one file upload control And two label,One gridView And Three buttons.


Here is the Source Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="imageUpload.aspx.cs" Inherits="imageUpload" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Image ID="Image1" runat="server" Width="273px" />
    <p>
        <asp:Button ID="upload" runat="server" onclick="Button1_Click" Text="upload" />
        <asp:Button ID="Add" runat="server" onclick="Add_Click" Text="Add" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
        Text="GridImageBinding" />
    </p>
    <asp:Label ID="lblError" runat="server" Text="Label" Visible="False"></asp:Label>
    <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
    <asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
        <asp:ImageButton ID="ImageButton1" ImageUrl='<%#Eval("image1") %>' runat="server" />
    </ItemTemplate>
   
    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </form>
</body>
</html>

Here is Your Page Behind Code:


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

public partial class imageUpload : System.Web.UI.Page
{
    SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);


    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileName = FileUpload1.FileName.ToString();
            string uploadFolderPath = "~/Image/";
            string filePath = HttpContext.Current.Server.MapPath(uploadFolderPath);
            FileUpload1.SaveAs(filePath + "\\" + fileName);
            Image1.ImageUrl = "~/Image/" + "/" + FileUpload1.FileName.ToString();
        }
    }
    protected void Add_Click(object sender, EventArgs e)
    {
        conn1.Open();
        SqlCommand cmd3 = new SqlCommand("insert into MyImage(image1) values('" + Image1.ImageUrl + "')", conn1);
        cmd3.ExecuteNonQuery();
        conn1.Close();
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        conn1.Open();
       
        SqlDataAdapter da = new SqlDataAdapter("select image1 from MyImage", conn1);
        DataSet ds = new DataSet();
       da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}


I used this connectionstrins in Web.config file:

<connectionStrings>
        <add name="cs" connectionString="Data Source=DEV4;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=netserver" providerName="System.Data.SqlClient"/>
    </connectionStrings>



Following is my Database Details:




I have taken DataBase As Test,
One Table Name as MyImage
Having Columns 
1.equipment_id As int, NotNull (i,e Auto incremented columns true)
2.image1 As Varchar(50),Null 

Thanks
   Shibashish mohanty Software developer 




Saturday, September 24

Databinding in a Gridview within a Gridview






Page Source View:-

i have taken one Panel and and two gridView .Here is the source code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView Within GridView.aspx.cs" Inherits="GridView_Within_GridView" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <span>
<asp:Panel ID="Panel7" runat="server" Height="250px"
                       Width="920px" ScrollBars="Vertical" Visible="false">
    <asp:GridView ID="GdviewParent" runat="server" AutoGenerateColumns="False"
        BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
        CellPadding="4" Width="900px" >
        <PagerSettings FirstPageText="First" LastPageText="Last" NextPageText="Next"
            PreviousPageText="Prev" />
        <FooterStyle BackColor="#009933" ForeColor="#003399" />
        <RowStyle BackColor="White" ForeColor="#003399" />
       
        <Columns>
            <asp:TemplateField HeaderText="Asp:GridView" HeaderStyle-ForeColor="White">
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server" Text="Date:"></asp:Label>
                    &nbsp;<%#Eval("Date")%>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Label ID="Label3" runat="server" Text="Guest Name:"></asp:Label>
                    &nbsp;<asp:Label ID="Label8" runat="server" Text='<%#Eval("GstName")%>'></asp:Label>
                    <br />
                    <asp:Label ID="Label9" runat="server" Text="Bill No:"></asp:Label>
                    &nbsp;<asp:Label ID="Label10" runat="server" Text='<%#Eval("BillNO")%>'></asp:Label>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Label ID="Label1" runat="server" Text="RoomNo:"></asp:Label>
                    &nbsp;<%#Eval("RoomNo")%><br />
                    <asp:Label ID="Label2" runat="server" Text="ChalanN0 No:"></asp:Label>
                    &nbsp;<asp:Label ID="Label11" runat="server" Text='<%#Eval("ChalanN0")%>'></asp:Label>
                    <br />
<%--Here i Have Bind the child GridView:- --%>
                    <asp:GridView ID="GridViewChild" runat="server" AutoGenerateColumns="false"
                        DataSource='<%#blcommon.getData(Eval("ChalanN0")) %>' Width="880px">
                        <Columns>
                            <asp:TemplateField HeaderText="Sl.No" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                    <asp:Label ID="lblSlno" runat="server" Text="<%#Container.DataItemIndex+1 %>" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Item Name" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
        <%#Eval("Item")%>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Quatity" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
        <%#Eval("Quantity")%>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Rate" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
        <%#Eval("Rate")%>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Tax" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
        <%#Eval("Tax")%>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Amount" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
        <%#Eval("Amount")%>
                                </ItemTemplate>
  
    </asp:TemplateField>
                        </Columns>
       
     
       
                    </asp:GridView>
                    <br />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <PagerStyle BackColor="#009900" ForeColor="Black" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#009933" Font-Bold="True" ForeColor="#CCFF99" />
        <HeaderStyle BackColor="#009933" ForeColor="Black"/>
       
    </asp:GridView>
</asp:Panel>
   </span>
    <div>
   
    </div>
    </form>
</body>
</html>

Take one button id as button1 and here is button1 click events:-

protected void button1_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

public void BindGrid()
    {//i have bind data from date to toDate and i have used some 3 tire architecture to bind that Parent gridview you can bind this Parent Gridview as in Your comfortable way of coding 
        if (TxtFrmDate.Text != "" || TxtToDate.Text != "")
        {
            HouseBO hBO = new HouseBO();

            DataSet DS = null;
            hBO.Operation = "SelectLndryChlBil";
            hBO.Date4 = TxtFrmLundryReport.Text;
            hBO.Date5 = TxtTolndryRprt.Text;
            DS = hBO.SelectLndryChlBil(hBO);
            if (DS.Tables.Count > 0)
            {

                GdViewLndryRprt.DataSource = DS.Tables[0];
                GdViewLndryRprt.DataBind();
                if (DS.Tables[0].Rows.Count > 7)
                {
                    Panel7.Visible = true;
                    Panel7.ScrollBars = ScrollBars.Vertical;
                    Panel7.Height = 250;
                }
                else
                {
                    Panel7.Visible = true;
                    Panel7.ScrollBars = ScrollBars.Auto;
                    Panel7.Height = GdviewParent.Height;
                }


            }
        }
        else
        {
            HouseBO hBO = new HouseBO();

            DataSet DS = null;
            hBO.Operation = "SelectLndryChlBil1";

            DS = hBO.SelectLndryChlBil1(hBO);
            if (DS.Tables.Count > 0)
            {

                GdviewParent.DataSource = DS.Tables[0];
                GdviewParent.DataBind();
                if (DS.Tables[0].Rows.Count > 7)
                {
                    Panel7.Visible = true;
                    Panel7.ScrollBars = ScrollBars.Vertical;
                    Panel7.Height = 250;
                }
                else
                {
                    Panel7.Visible = true;
                    Panel7.ScrollBars = ScrollBars.Auto;
                    Panel7.Height = GdviewParent.Height;
                }


            }
        }
    }

This is my Utility Class  Which is derived in a specific folder like App Code
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

/// <summary>
/// Summary description for utility
/// </summary>
public class utility
{
   static string  ConnString = ConfigurationManager.ConnectionStrings["cs"].ToString();

    public utility()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public static DataSet GetData(string sqlstat)
    {

        SqlConnection cn = new SqlConnection(ConnString);
        SqlDataAdapter da = new SqlDataAdapter(sqlstat, cn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
  
}    }

This is my blcommon Class  Which is derived in a specific folder like App Code
using System;
using System.Data;
using System.Configuration;

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


/// <summary>
/// Summary description for blcommon
/// </summary>
public class blcommon
{

    public blcommon()
    {
        //
        // TODO: Add constructor logic here
        //
    }
 
  
    public static DataSet getData(object s)
    {
        string ChalanN0 = s.ToString();

        return utility.GetData("select * from LaunderyChalana L where L.ChalanN0=" + ChalanN0);
    }
   }

  

  



GridView DataBinding in Asp.net

 This is one of the best article for a learner who is trying to bind data in a GridView Control.


Page Source:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="BasicGridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

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

File: Default.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Web.Configuration;
using System.Data.SqlClient;

public partial class BasicGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["ShibaConn"].ConnectionString;
string selectSQL = "SELECT ID, Name, Price FROM Students ";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();

adapter.Fill(ds, "Products");

GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}


File: Web.config

<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ShibaConn" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>

Simplest Way to upload an image in a Database

Page View:-
 By click on Upload button it will bind image to Asp:image Control and by click on Add button it will store the path of that image into database;
Page Source View:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="imageUpload.aspx.cs" Inherits="imageUpload" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Image ID="Image1" runat="server" Width="273px" />
    <p>
        <asp:Button ID="upload" runat="server" onclick="Button1_Click" Text="upload" />
        <asp:Button ID="Add" runat="server" onclick="Add_Click" Text="Add" />
    </p>
    <asp:Label ID="lblError" runat="server" Text="Label" Visible="False"></asp:Label>
    <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

Code View:-


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

public partial class imageUpload : System.Web.UI.Page
{
    SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);


    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileName = FileUpload1.FileName.ToString();
            string uploadFolderPath = "~/Image/";
            string filePath = HttpContext.Current.Server.MapPath(uploadFolderPath);
            FileUpload1.SaveAs(filePath + "\\" + fileName);
            Image1.ImageUrl = "~/Image/" + "/" + FileUpload1.FileName.ToString();
        }
    }
    protected void Add_Click(object sender, EventArgs e)
    {
        conn1.Open();
        SqlCommand cmd3 = new SqlCommand("insert into MyImage(image1) values('" + Image1.ImageUrl + "')", conn1);
        cmd3.ExecuteNonQuery();
        conn1.Close();
    }
}

My test database With table name as MyImage:-

Database Script:- 
USE [Test]
GO
/****** Object:  Table [dbo].[MyImage]    Script Date: 09/24/2011 15:27:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MyImage](
    [equipment_id] [int] IDENTITY(1,1) NOT NULL,
    [image1] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

How to upload an image using ASP.NET

Introduction

This article is for freshers who want to learn how to upload images.

Step 1

First add the following HTML tag :-
<input id="Upload" style="Z-INDEX: 102; LEFT: 104px; WIDTH: 288px; 
  POSITION: absolute; TOP: 64px; HEIGHT: 22px" type="file" 
  size="28" name="Upload" runat="server"> 
This control will upload your image.

Step 2

Create a Button called "Upload" and another called "LoadImage".  Add the DataGrid and do required bindings.

Step 3

Lets see some sample code now.
private void Button1_Click(object sender, System.EventArgs e)
    {
        //It verifies if the archive exists 

        if (Upload.PostedFile != null)
        {
            //To create a PostedFile

            HttpPostedFile File = Upload.PostedFile;

            //Create byte Array with file len

            byte[] Data = new Byte[File.ContentLength];
            //force the control to load data in array

            File.InputStream.Read(Data,0,File.ContentLength);
                
            int i = 0;

            //Dysplay array data in textbox

            for (i=0;i<Data.Length;i++)
            {
                TextBox1.Text += Data[i].ToString();  
            }

            //Create procedure parameter

            object[] obj = new object[1]; 

            obj[0] = Data;

            //Execute the procedure with Microsoft.ApplicationBlocks.Data

            //Simple procedure

            /*CREATE PROCEDURE sp_img(@img image)  AS

            insert into tb_img values(@img)*/

            //record data

            SqlHelper.ExecuteNonQuery(connectionString,"sp_img",obj);       

        }
    }

    private void Button2_Click(object sender, System.EventArgs e)
    {
        //Bind data to your grid

        //more details consulting

        //Working DataGrid TemplateColumns and Bind this Columns 

        DataSet ds = SqlHelper.ExecuteDataset(connectionString,
            "sp_load_img",null);
        grid.DataSource  = ds.Tables[0].DefaultView;
        grid.ObjectName = "Image1";
        grid.FieldName = "img";
        grid.Editable = false;
        grid.DataBind();
        grid.DataBindObjects(grid,ds,0,grid.PageSize);  

        int i =0;

        for (i=0;i<ds.Tables[0].Rows.Count;i++)
        {
                        //test your bitmap is valid 

                        //Demonstration

            byte[] bits = (byte[]) ds.Tables[0].Rows[i]
                ["img"];  
            MemoryStream memorybits = new MemoryStream(bits);
            Bitmap bitmap = new Bitmap(memorybits);
        }

 
    }

    private void grid_PageIndexChanged(object source, 
           System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
        //Page your grid

        //Bind data to your grid

        //more details consulting

        //Working DataGrid TemplateColumns and Bind this Columns 

        grid.CurrentPageIndex =e.NewPageIndex; 
        DataSet ds = SqlHelper.ExecuteDataset(connectionString,
            "sp_load_img",null);
        grid.DataSource  = ds.Tables[0].DefaultView;
        grid.ObjectName = "Image1";
        grid.FieldName = "img";
        grid.Editable = false;
        grid.DataBind();
        grid.DataBindObjects(grid,ds,e.NewPageIndex,grid.PageSize);  
        
    }
}

Friday, September 23

3-tier architecture in C#

Introduction

This article discusses and implements 3-tier architecture using C# and a dummy customer using MS Access database. In this article I am trying to implement a small reusable component that maintains customers in 3-tier architecture. It shows how to add, update and find customer details.

Background

To begin with I would like to discuss a little about the theoretical aspects of 3-tier architecture. I'll briefly go through what 3-tier architecture is and what are its advantages.

What is a 3-tier architecture?

Three-tier (layer) is a client-server architecture in which the user interface, business process (business rules) and data storage and data access are developed and maintained as independent modules or most often on separate platforms. Basically, there are 3 layers, tier 1 (presentation tier, GUI tier), tier 2 (business objects, business logic tier) and tier 3 (data access tier). These tiers can be developed and tested separately.
What is the need for dividing the code in 3-tiers? Separation of the user interface from business logic and database access has many advantages. Some of the advantages are as follows:
  • Reusability of the business logic component results in quick development. Let's say we have a module that handles adding, updating, deleting and finding customers in the system. As this component is developed and tested, we can use it in any other project that might involve maintaining customers.
  • Transformation of the system is easy. Since the business logic is separate from the data access layer, changing the data access layer won�t affect the business logic module much. Let's say if we are moving from SQL Server data storage to Oracle there shouldn�t be any changes required in the business layer component and in the GUI component.
  • Change management of the system is easy. Let's say if there is a minor change in the business logic, we don�t have to install the entire system in individual user�s PCs. E.g. if GST (TAX) is changed from 10% to 15% we only need to update the business logic component without affecting the users and without any downtime.
  • Having separate functionality servers allows for parallel development of individual tiers by application specialists.
  • Provides more flexible resource allocation. Can reduce the network traffic by having the functionality servers strip data to the precise structure needed before sending it to the clients.

Using the code

This component has 3 tiers. Tier 1 or GUI tier with a form will be called FrmGUI, tier 2 or business logic will be called BOCustomer short for Bussniess Object Customer and finally the tier 3 or the data tier will be called DACustomer short for Data Access Customer. I have compiled all the 3 tiers in the same project for ease of work. I am including all the source code along with the MS Access database that is used to test this project in the included zip file.

User Interface tier

This is a chunk of code from the user interface. I am only including the functions that are used to call the middle tier or the business logic layer.
I am keeping a reference to business logic layer as BOCustomer.
//This function get the details from the user via GUI 

//tier and calls the Add method of business logic layer.

private void cmdAdd_Click(object sender, System.EventArgs e)
{
      try
      {
            cus = new BOCustomer();
            cus.cusID=txtID.Text.ToString();
            cus.LName = txtLName.Text.ToString();
            cus.FName = txtFName.Text.ToString();
            cus.Tel= txtTel.Text.ToString();
            cus.Address = txtAddress.Text.ToString();
            cus.Add();
      }
      catch(Exception err)
      {
            MessageBox.Show(err.Message.ToString());
      }
}

//This function gets the ID from the user and finds the 

//customer details and return the details in the form of

//a dataset via busniss object layer. Then it loops through 

//the content of the dataset and fills the controls.

 
private void cmdFind_Click(object sender, System.EventArgs e)
{
      try
      {
            String cusID = txtID.Text.ToString();
                  
            BOCustomer thisCus = new BOCustomer();
                  
            DataSet ds = thisCus.Find(cusID);
 
            DataRow row;
            row = ds.Tables[0].Rows[0];
 
            //via looping

            foreach(DataRow rows in ds.Tables[0].Rows )
            {
               txtFName.Text = rows["CUS_F_NAME"].ToString();
               txtLName.Text = rows["CUS_L_NAME"].ToString();
               txtAddress.Text = rows["CUS_ADDRESS"].ToString();
               txtTel.Text = rows["CUS_TEL"].ToString();
            }
      }
      catch (Exception err)
      {
            MessageBox.Show(err.Message.ToString());
      }
 
}

//this function used to update the customer details. 

private void cmdUpdate_Click(object sender, 
                                 System.EventArgs e)
{
      try
      {
            cus = new BOCustomer();
            cus.cusID=txtID.Text.ToString();
            cus.LName = txtLName.Text.ToString();
            cus.FName = txtFName.Text.ToString();
            cus.Tel= txtTel.Text.ToString();
            cus.Address = txtAddress.Text.ToString();
 
            cus.Update();
      }
      catch(Exception err)
      {
            MessageBox.Show(err.Message.ToString());
      }
}

Business Logic layer

Here, I am including all the code for this tier. Basically it has properties that are needed to define the customer object. But as I mentioned it is just a dummy customer and many other properties can be added if required. It also has all the methods including Add, update, find that are required to maintain customer details.
This is the middle tier and acts between the GUI and the Data access layer. It keeps a reference to the data access tier as cusData = new DACustomer(). It also has a reference to System.Data namespace as sometimes it returns details in the form of DataSet to the GUI tier.
using System;
using System.Data;

namespace _3tierarchitecture
{
      /// <SUMMARY>

      /// Summary description for BOCustomer.

      /// </SUMMARY>

      
      public class BOCustomer
      {
            //Customer properties

            private String fName;
            private String lName;
            private String cusId;
            private String address;
            private String tel;
 
            private DACustomer cusData;
 
       public BOCustomer()
       {
            //An instance of the Data access layer!

             cusData = new DACustomer();
         }   
 
 
 
            /// <SUMMARY>

            /// Property FirstName (String)

            /// </SUMMARY>

            public String FName 
            {
      
                  get
                  {
                        return this.fName;
                  }
                  set
                  {
                        try
                        {
                              this.fName = value;
 
                              if (this.fName == "")
                              {
                                    throw new Exception(
                                      "Please provide first name ...");
                              }
                        }
                        catch(Exception e)
                        {
                              throw new Exception(e.Message.ToString());
                        }
                  }
            }
 
            /// <SUMMARY>

            /// Property LastName (String)

            /// </SUMMARY>

            public String LName
            {
                  get
                  {
                        return this.lName;
                  }
                  set
                  {
                        //could be more checkings here eg revmove ' chars

                        //change to proper case

                        //blah blah

                        this.lName = value;
                        if (this.LName == "")
                        {
                              throw new Exception("Please provide name ...");
                        }
 
                  }
            }
             
            /// <SUMMARY>

            /// Property Customer ID (String)

            /// </SUMMARY>

            public String cusID
            {
                  get
                  {
                        return this.cusId;
                  }
                  set
                  {
                        this.cusId = value;
                        if (this.cusID == "")
                        {
                              throw new Exception("Please provide ID ...");
                        }
 
                  }
            }
 
            /// <SUMMARY>

            /// Property Address (String)

            /// </SUMMARY>

            public String Address
            {
                  get
                  {
                        return this.address;
                  }
                  set
                  {
                        this.address = value;
 
                        if (this.Address == "")
                        {
                              throw new Exception("Please provide address ...");
                        }
                  }
            }
 
            /// <SUMMARY>

            /// Property Telephone (String)

            /// </SUMMARY>

            public String Tel
            {
                  get
                  {
                        return this.tel;
                  }
                  set
                  {
                        this.tel = value;
                        if (this.Tel == "")
                        {
                              throw new Exception("Please provide Tel ...");
                        }
 
                  }
            }
 
            /// <SUMMARY>

            /// Function Add new customer. Calls 

            /// the function in Data layer.

            /// </SUMMARY>

            public void Add()
            {
                  cusData.Add(this);
            }
 
 
            /// <SUMMARY>

            /// Function Update customer details. 

            /// Calls the function in Data layer.

            /// </SUMMARY>

            public void Update() 
            {
                  cusData.Update(this);
            }
 
            /// <SUMMARY>

            /// Function Find customer. Calls the 

            /// function in Data layer.

            /// It returns the details of the customer using 

            /// customer ID via a Dataset to GUI tier.

            /// </SUMMARY>

            public DataSet Find(String str) 
            {
                  if (str == "")
                      throw new Exception("Please provide ID to search");
                      
                  DataSet data = null;
 
                  data = cusData.Find(str);
 
                  return data;
            }
      }
}

Data Access Layer

The data tier has details to manipulate an MS Access database. However, all these details are transparent and do not affect the business logic layer. This module has a reference to the business logic layer as BOCustomer cus. To make the usage easier and be supported by any other database I have created some constants including the database name and field name that need to be changed as per the customer table details. This is an usable module for any database after making these changes.
using System;
using System.Data.OleDb;
using System.Data;

namespace _3tierarchitecture

{

    /// <SUMMARY>

    /// Summary description for DACustomer.

    /// </SUMMARY>

    public class DACustomer
    {
        private OleDbConnection cnn;
        //change connection string as per the 

        //folder you unzip the files

        private const string CnnStr = 
          "Provider=Microsoft.Jet.OLEDB.4.0;Data " +
          "Source= D:\\Rahman_Backup\\Programming\\" + 
             "Csharp\\3tierarchitecture\\customer.mdb;";

        //local variables
        private String strTable="";
        private String strFields="";
        private String strValues="";
        private String insertStr="";
        
        //this needs to be changed based on customer 
        //table fields' Name of the database!
        private const String thisTable = "tblCustomer";
        private const String cus_ID = "CUS_ID";
        private const String cus_LName = "CUS_L_NAME";
        private const String cus_FName = "CUS_F_NAME";
        private const String cus_Tel = "CUS_TEL";
        private const String cus_Address = "CUS_ADDRESS";
 

        public DACustomer()
        {
        }
        
        public DACustomer(BOCustomer cus)
        {
            // A reference of the business object class
        }
        
        //standard dataset function that adds a new customer

        public void Add(BOCustomer cus)
        {

            String str = BuildAddString(cus);
            
            OpenCnn();

            //Open command option - cnn parameter is imporant
            OleDbCommand cmd = new OleDbCommand(str,cnn);


            //execute connection
            cmd.ExecuteNonQuery();
            
            // close connection
            CloseCnn();
            
        }
        
        //standard dataset function that updates 
        //details of a customer based on ID
        public void Update(BOCustomer cus)
        {
            OpenCnn();
            
            String selectStr = "UPDATE " + thisTable + 
                " set " + cus_LName + " = '" + cus.LName + "'" +
                ", " + cus_FName + " = '" + cus.FName + "'" +
                ", " + cus_Address + " = '" + cus.Address + "'" +
                ", " + cus_Tel + " = '" + cus.Tel + "'" +
                " where cus_ID = '" + cus.cusID + "'";

            OleDbCommand cmd = new OleDbCommand(selectStr,cnn);

            cmd.ExecuteNonQuery();
            
            CloseCnn();
        }
        
        //standard dataset function that finds and 
        //return the detail of a customer in a dataset
        public DataSet Find(String argStr)
        {
            DataSet ds=null;

            try
            {
                OpenCnn();
            
                String selectStr = "select * from " + thisTable + 
                              " where cus_ID = '" + argStr + "'";
                OleDbDataAdapter da = 
                       new OleDbDataAdapter(selectStr,cnn);
                ds = new DataSet();
                da.Fill(ds,thisTable);
            
                CloseCnn();

                
            }
            catch(Exception e)
            {
                String Str = e.Message;
            }

            return ds;
        }

        private void OpenCnn()
        {
            // initialise connection
            String cnnStr = CnnStr;
            cnn = new OleDbConnection(cnnStr);
            // open connection
            cnn.Open();
        }

        private void CloseCnn()
        {
            // 5- step five
            cnn.Close();
        }
        
        // just a supporting function that builds 
        // and return the insert string for dataset.
        private String BuildAddString(BOCustomer cus)
        {
            // these are the constants as 
            // set in the top of this module.
            strTable="Insert into " + thisTable;
            strFields=" (" + cus_ID + 
            "," + cus_LName + 
            "," + cus_FName + 
            "," + cus_Address + 
            "," + cus_Tel + ")";
            
            //these are the attributes of the 
            //customer business object.
            strValues= " Values ( '" + cus.cusID + 
            "' , '" + cus.LName + 
            "' , '" + cus.FName + 
            "' , '" + cus.Address + 
            "' , '" + cus.Tel + "' )";

            insertStr = strTable + strFields + strValues;
            
            return insertStr;
            
        }
    }
}

Possible enhancements

This code is very simple and shows the basic usage of 3-tier architecture. A lot of enhancements including complete details of a client, error handling and many more are possible.

About Author:

i am shibashish mohanty working as a software developer.You can send me your query in shibashish.mohanty@treztech.com

DataBase BackUp in Specific Folder Using Asp.Net


Here is some code for Coping your database in a specific folder:-

 Page Source View:-

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Database.aspx.cs" Inherits="Database" %>

<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
        <asp:Button ID="Button1" runat="server" Font-Bold="True" Font-Size="Large"
            ForeColor="#990000" Height="169px" onclick="Button1_Click" Text="BackUpButton"
            Width="402px" />
  
    </div>
    </form>
</body>
</html>

Code View:-

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class Database : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
           
            File.Copy("D:/Demo3tyre/App_Data/shiba.mdf", "E:/Backup/db/shiba.mdf");
            File.Copy("D:/Demo3tyre/App_Data/shiba_log.ldf", "E:/Backup/db/shiba_log.ldf");
            Response.Write("<script>alert('Back Successfully')</script>");

        }
        catch (Exception)
        {

            throw;
        }
    }
}

By click on that button You can store our database in a specific folder which is provided by you.
Before that go to server explorer or your management studio and right click on database i,e. shiba(which is my database name) and click on Detach.


Simple code to Send a mail by using Smtp.Host as gmail.com


Coding Part:-
use namespace:
using System.Net.Mail;

protected void btnSendmail_Click(object sender, EventArgs e)
    {
try
{

MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
mail.From = new MailAddress(txtEmail.Text);
// mail.To.Add(new MailAddress(txtTo.Text));
mail.To.Add(new MailAddress("shibashishXYZ@gmail.com"));

mail.Subject = txtSubject.Text;
mail.Body =txtName.Text + txtMessage.Text;
mail.IsBodyHtml = true;
smtp.Host = "smtp.gmail.com";


//smtp.Host = "localhost";

smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "txtEmail.Text";
NetworkCred.Password = "1234";
//NetworkCred.UserName = "xyz@shibashish.com";
// NetworkCred.Password = "Password123!";
smtp.UseDefaultCredentials = true;
//smtp.Credentials = NetworkCred;
smtp.Credentials = new System.Net.NetworkCredential("txtEmail.Text", "1234");

smtp.Port = 587;//this is Gmail port for e-mail
//smtp.Port = 25;// this is default port no
smtp.Send(mail);//send an e-mail

lblStatus.Text="Message Sended";
}
catch(Exception ex)
{
throw ex;
}
}


Design View:-

<div class="col_w420 float_l">
          
             <h3>Contact Form</h3>
              
              <div id="cp_contact_form">
              <body>
              <form runat="server" id="frmSend">
              
                    <div>
        <h2 style="background-color:Brown; color:Wheat; font-family:Verdana; font-size:14px" align=center>Please enter the following requested 
information below to send us your Message.</h2>
<table align=center>
<tr>
<td class="style1">
                        <label for="author">
                       
Name:</label></td>
<td><asp:textbox id="txtName" Width="241" Runat="server"></asp:textbox></td>
</tr>
<tr>
<td class="style1">
                        <label for="email">
                        Email:</label></td>
<td><asp:textbox id="txtEmail" Width="241" Runat="server"></asp:textbox></td>
</tr>
<tr>
<td class="style1">
                        <label for="subject">
                        Subject:</label></td>
<td><asp:textbox id="txtSubject" Width="241" Runat="server"></asp:textbox></td>
</tr>
<tr>
<td colSpan="2" >
                        <label for="text">
                        Message:</label></td>
</tr>
<tr>
<td align="center" colSpan="2" width=100%><asp:textbox id="txtMessage" Width="99%" 
                            Runat="server" Height="99px" TextMode="MultiLine" MaxLength="400"></asp:textbox></td>
</tr>
<tr>
<td colSpan="2">&nbsp;</td>
</tr>
<tr>
<td align=center class="style1"><asp:button id="btnSendmail" Runat="server" Text="Send " 
                            OnClick="btnSendmail_Click"></asp:button></td>
<td align=center><asp:button id="btnReset" Runat="server" Text="Reset" OnClick="btnReset_Click"></asp:button></td>
</tr>
<tr>
<td colSpan="2"><asp:label id="lblStatus" Runat="server" EnableViewState="False"></asp:label></td>
</tr>
</table>
    </div>
    </form>
    </body>
            </div>
               
      </div>

.

ShibashishMnty
shibashish mohanty