Saturday, 23 April 2016

Upload image and display in a gridview using asp.net

Description:


Here we define how we can upload a image using file upload and store in database. After that, How we can retrieve it from database and display it in a gridview. Here we follow 3 Tier or Layer Architecture to store a image in database and retrieve from database in a gridview.


SQL Table :

Here we define SQL Script to create a table. We create a Table name UploadPhoto

CREATE TABLE [dbo].[UploadPhoto](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [Customer_Name] [varchar](50) NULL,
 [Mobile_No] [varchar](50) NULL,
 [City] [varchar](50) NULL,
 [File_Name] [varchar](50) NULL,
 [File_Path] [varchar](max) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



SQL Procedure :

Here we use two procedures, one for insert data in to table and second for bind data with gridview.

--//---------------------------- FOR INSERT DATA-----------------------------//
Create procedure [dbo].[Insert_Photo]
(
@Mode int,
@ID int,
@Customer_Name varchar(50),
@Mobile_No varchar(50),
@City varchar(50),
@File_Name varchar(50),
@File_Path varchar(max)
)
as
if(@Mode=0)
begin
insert into UploadPhoto (Customer_Name,Mobile_No,City,File_Name,File_Path) values (@Customer_Name,@Mobile_No,@City,@File_Name,@File_Path)
end

if(@Mode=1)
begin 
delete from UploadPhoto where ID=@ID
end
 
 if (@Mode=2)
 begin
 update UploadPhoto set Mobile_No=@Mobile_No,City=@City where ID=@ID
 end

--//------------------------------- FOR GET DATA-------------------------//

Create procedure [dbo].[Get_Photo]
(
@Mode int,
@ID int
)
as
if(@Mode=0)
begin
select * from UploadPhoto
end

Aspx Page Code:





<%#Container.DataItemIndex + 1%>

Presentation Layer:


Here we use 3 layer architecture, Presentation Layer, Business Layer, Data Access Layer. First we define the code of Presentation Layer.
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.Data.SqlClient;
using Business_Layer;
using Data_Layer;
using System.IO;


namespace Upload_and_display_image_in_gridview
{
    public partial class Customer_Info : System.Web.UI.Page
    {
        DataTable dt = new DataTable();
        Business_Class BCobj = new Business_Class();
        int RowEffected;
        string File_Name;
        string File_Path;

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

        }
       
        
        public void Get_Data()
        {
            BCobj.Mode = 0;
            dt = BCobj.Customer_Info_Get_BL();
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            BCobj.Mode = 0;
        
            BCobj.Customer_Name = TextBox1.Text;
            BCobj.Mobile_No = TextBox2.Text;
            BCobj.City = TextBox3.Text;

            if (FileUpload1.PostedFile != null)
            {
                string Filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string filepath = "image/" + Filename;
                FileUpload1.PostedFile.SaveAs(Server.MapPath(filepath));
                BCobj.File_Name = Filename;
                BCobj.File_Path = filepath;
            }

           
            RowEffected = BCobj.Customer_Info_Insert_BL();

            if (RowEffected >= 1)
            {
                Label1.Text = "Data Insert Sucessfully";
                TextBox1.Text = "";
                TextBox2.Text = "";
                TextBox3.Text = "";
                Get_Data();
            }
            else
            {
                Label1.Text = "Data not Inserted";
                TextBox1.Text = "";
                TextBox2.Text = "";
                TextBox3.Text = "";
                Get_Data();
            }
        }
    }
}



Business Layer:


In 3 Layer Architecture, Second Layer is Business Logic Layer. Here we define business logic layer to define properties and business logic. Create a class with name Business_Class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Data_Layer;

namespace Business_Layer
{
    
    public class Business_Class
    {
        int RowEffected;

        #region properties
        private int _intID = 0;


        private int _Mode = 0;
        public int Mode
        {
            get { return _Mode; }
            set { _Mode = value; }
        }

        private int _ID = 0;
        public int ID
        {
            get { return _ID; }
            set { _ID = value; }
        }

        private string _Customer_Name = string.Empty;
        public string Customer_Name
        {
            get { return _Customer_Name; }
            set { _Customer_Name = value; }
        }


        private string _Mobile_No = string.Empty;
        public string Mobile_No
        {
            get { return _Mobile_No; }
            set { _Mobile_No = value; }
        }

        private string _City = string.Empty;
        public string City
        {
            get { return _City; }
            set { _City = value; }
        }

        private string _File_Name = string.Empty;
        public string File_Name
        {
            get { return _File_Name; }
            set { _File_Name = value; }
        }

        private string _File_Path = string.Empty;
        public string File_Path
        {
            get { return _File_Path; }
            set { _File_Path = value; }
        }
        #endregion

        #region Method


        // -------------------- INSERT DATA --------------------//

        public int Customer_Info_Insert_BL()
        {
            Data_Layer.Data_Class DCobj = new Data_Layer.Data_Class();
            if (_intID == 0)
            {
                RowEffected = DCobj.Customer_info_Insert_DL(this);
            }
            else
            {
                RowEffected = DCobj.Customer_info_Insert_DL(this);
            }
            return RowEffected;
        }



        //---------------------- GET DATA --------------------//
        public DataTable Customer_Info_Get_BL()
        {
            Data_Layer.Data_Class DCobj = new Data_Layer.Data_Class();
            return DCobj.Customer_info_Get_DL(this);
        }


        #endregion
    }
}

Data Access Layer:


In 3 layer architecture, 3rd Layer is Data Access Layer. We use Data Layer to access data from database. Here we define Data Access Layer with two Class. 1. Data Layer Class 2. ADO Layer Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Business_Layer;

namespace Data_Layer
{
    public class Data_Class
    {

        public DBManager DBManager = new DBManager();

        // ------------------- INSERT DATA -----------------------------------//
        public int Customer_info_Insert_DL(Business_Layer.Business_Class BCobj)
        {
            int RowEffected;
            SqlParameter[] param = new SqlParameter[7];

            param[0] = new SqlParameter("@Mode", BCobj.Mode);
            param[1] = new SqlParameter("@ID", BCobj.ID);
            param[2] = new SqlParameter("@Customer_Name", BCobj.Customer_Name);
            param[3] = new SqlParameter("@Mobile_No", BCobj.Mobile_No);
            param[4] = new SqlParameter("@City", BCobj.City);
            param[5] = new SqlParameter("@File_Name", BCobj.File_Name);
            param[6] = new SqlParameter("@File_Path", BCobj.File_Path);

            try
            {
                RowEffected = DBManager.update(param, "Insert_Photo");
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
            return RowEffected;
        }


        // --------------------------- GET DATA ----------------------------//
        public DataTable Customer_info_Get_DL(Business_Layer.Business_Class BCobj)
        {
            SqlParameter[] param = new SqlParameter[2];

            param[0] = new SqlParameter("@Mode", BCobj.Mode);
            param[1] = new SqlParameter("@ID", BCobj.ID);
            return DBManager.ExecuteProcedure(param, "Get_Photo");
        }

      
    }
}

ADO Layer:


ADO Layer Class use for SQL Connection and Command to access SQL database. Here we use a class with name DBManager
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace Data_Layer
{
    public class DBManager
    {
        string Connectionstring;
        SqlCommand cmd;
        SqlConnection conn;
        int EffectedRows = 0;

        public DBManager()
        {
            string Connectionstring = "Data Source='Test-PC'; Initial Catalog='Practise'; User Id='sa'; Password='sa@123'; ";
            conn = new SqlConnection(Connectionstring);
        }


//for open a connection

        public void OpenConnection()
        {
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
            }

        }
// Close a connection

        public void CloseConnection()
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }

        public void Dispose()
        {
            conn.Dispose();
            conn = null;
        }
// INSERT DATA

        public int update(SqlParameter[] param, String SpName)
        {

            OpenConnection();

            try
            {

                SqlCommand cmd = new SqlCommand();

                cmd.Connection = conn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = SpName;

                for (int i = 0; i < param.Length; i++)
                {
                    cmd.Parameters.Add(param.GetValue(i));
                }

                int EffectedRows = cmd.ExecuteNonQuery();
                CloseConnection();
                return EffectedRows;
            }
            catch
            {
                CloseConnection();
                Dispose();
                return 0;
            }
        }

//GET DATA
        public DataTable ExecuteProcedure(SqlParameter[] param, String SpName)
        {
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter();
            OpenConnection();
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = SpName;
                cmd.CommandType = CommandType.StoredProcedure;

                for (int i = 0; i < param.Length; i++)
                {
                    cmd.Parameters.Add(param.GetValue(i));
                }

                adp.SelectCommand = cmd;
                adp.Fill(dt);

                CloseConnection();
                return dt;
            }
            catch
            {

                CloseConnection();
                Dispose();
                return dt;
            }



        }


    }
}

No comments:

Post a Comment