Image Gallery Using Three Tier Architecture in ASP.NET

Firstly open SQL Server and create a table name Image_Upload. Include the following columns,
  1. Id int not null primary key,  
  2. Name nvarchar(50),  
  3. Path nvarchar(300),  
  4. IsActive bit  
Then create a Stored Procedure name Image_Upload_Gallery. The following is the Stored Procedure: 
  1. CREATE PROCEDURE [dbo].[Image_Upload_Gallery] (@Para VARCHAR(30)='', @Id INT=0, @Path NVARCHAR(300)='', @Name nvarchar(50)=''AS BEGIN IF @Para='Add' BEGIN  
  2. INSERT INTO Image_Upload (Path,Name,IsActive)  
  3. VALUES (@Path,  
  4.         @Name,  
  5.         1) END ELSE IF @Para='Update' BEGIN  
  6. UPDATE Image_Upload  
  7. SET Path=@Path,  
  8.     Name = @Name  
  9. WHERE Id=@Id END ELSE IF @Para='Delete' BEGIN  
  10.   UPDATE Image_Upload  
  11.   SET IsActive=0 WHERE Id=@Id END ELSE IF @Para='Get' BEGIN  
  12.   SELECT Id,  
  13.          Name,  
  14.          Path  
  15.   FROM Image_Upload WHERE IsActive=1 END ELSE IF @Para='Get_By_Id' BEGIN  
  16.   SELECT Name,  
  17.          Path  
  18.   FROM Image_Upload WHERE IsActive=1  
  19.   AND Id=@Id END ELSE IF @Para='Get_Images' BEGIN  
  20.   SELECT Name,  
  21.          Path  
  22.   FROM Image_Upload WHERE IsActive=1 
  23. END END  
Go to Microsoft Visual Studio, then go to file-new project and select ASP.NET WebApplication. Right click on solution in Solution Explorer and click add new project in the windows tab. Select class library and name it SCHEMA and insert the following code in it:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace SCHEMA {  
  6.     public class Class1 {  
  7.         private string _Path;  
  8.         private string _Name;  
  9.         public string Path {  
  10.             get {  
  11.                 return _Path;  
  12.             }  
  13.             set {  
  14.                 _Path = value;  
  15.             }  
  16.         }  
  17.         public string Name {  
  18.             get {  
  19.                 return _Name;  
  20.             }  
  21.             set {  
  22.                 _Name = value;  
  23.             }  
  24.         }  
  25.     }  
  26. }  
In the same way create one more class library and name it to DAL and write the following code to it. Add Reference of SCHEMA to DAL. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data.SqlClient;  
  6. using System.Data;  
  7. using System.Configuration;  
  8. using SCHEMA;  
  9. namespace DAL {  
  10.     public class Class1 {  
  11.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());  
  12.         SqlCommand cmd;  
  13.         DataTable dt;  
  14.         public int InsertData(SCHEMA.Class1 objSchema) {  
  15.             try {  
  16.                 using(cmd = new SqlCommand("Image_Upload_Gallery", con)) {  
  17.                     cmd.CommandType = CommandType.StoredProcedure;  
  18.                     cmd.Parameters.AddWithValue("@Para""Add");  
  19.                     cmd.Parameters.AddWithValue("@Name", objSchema.Name);  
  20.                     cmd.Parameters.AddWithValue("@Path", objSchema.Path);  
  21.                     if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  22.                     int result = cmd.ExecuteNonQuery();  
  23.                     con.Close();  
  24.                     return result;  
  25.                 }  
  26.             } catch (Exception ex) {  
  27.                 throw ex;  
  28.             } finally {  
  29.                 con.Close();  
  30.             }  
  31.         }  
  32.         public DataTable BindGrid() {  
  33.             using(cmd = new SqlCommand("Image_Upload_Gallery", con)) {  
  34.                 try {  
  35.                     cmd.CommandType = CommandType.StoredProcedure;  
  36.                     cmd.Parameters.AddWithValue("@Para""Get");  
  37.                     if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  38.                     SqlDataAdapter da = new SqlDataAdapter(cmd);  
  39.                     dt = new DataTable();  
  40.                     da.Fill(dt);  
  41.                     con.Close();  
  42.                     return dt;  
  43.                 } catch (Exception ex) {  
  44.                     throw ex;  
  45.                 }  
  46.             }  
  47.         }  
  48.         public DataTable GetById(int Id) {  
  49.             using(cmd = new SqlCommand("Image_Upload_Gallery", con)) {  
  50.                 try {  
  51.                     cmd.CommandType = CommandType.StoredProcedure;  
  52.                     cmd.Parameters.AddWithValue("@Para""Get_By_Id");  
  53.                     cmd.Parameters.AddWithValue("@Id", Id);  
  54.                     if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  55.                     SqlDataAdapter da = new SqlDataAdapter(cmd);  
  56.                     dt = new DataTable();  
  57.                     da.Fill(dt);  
  58.                     con.Close();  
  59.                     return dt;  
  60.                 } catch (Exception ex) {  
  61.                     throw ex;  
  62.                 }  
  63.             }  
  64.         }  
  65.         public int UpdateData(SCHEMA.Class1 objSchema, int Id) {  
  66.             try {  
  67.                 using(cmd = new SqlCommand("Image_Upload_Gallery", con)) {  
  68.                     cmd.CommandType = CommandType.StoredProcedure;  
  69.                     cmd.Parameters.AddWithValue("@Para""Update");  
  70.                     cmd.Parameters.AddWithValue("@Id", Id);  
  71.                     cmd.Parameters.AddWithValue("@Name", objSchema.Name);  
  72.                     cmd.Parameters.AddWithValue("@Path", objSchema.Path);  
  73.                     if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  74.                     int result = cmd.ExecuteNonQuery();  
  75.                     con.Close();  
  76.                     return result;  
  77.                 }  
  78.             } catch (Exception ex) {  
  79.                 throw ex;  
  80.             } finally {  
  81.                 con.Close();  
  82.             }  
  83.         }  
  84.         public int DeleteData(int Id) {  
  85.             try {  
  86.                 using(cmd = new SqlCommand("Image_Upload_Gallery", con)) {  
  87.                     cmd.CommandType = CommandType.StoredProcedure;  
  88.                     cmd.Parameters.AddWithValue("@Para""Delete");  
  89.                     cmd.Parameters.AddWithValue("@Id", Id);  
  90.                     if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  91.                     int result = cmd.ExecuteNonQuery();  
  92.                     con.Close();  
  93.                     return result;  
  94.                 }  
  95.             } catch (Exception ex) {  
  96.                 throw ex;  
  97.             } finally {  
  98.                 con.Close();  
  99.             }  
  100.         }  
  101.         public DataTable BindImages() {  
  102.             using(cmd = new SqlCommand("Image_Upload_Gallery", con)) {  
  103.                 try {  
  104.                     cmd.CommandType = CommandType.StoredProcedure;  
  105.                     cmd.Parameters.AddWithValue("@Para""Get_Images");  
  106.                     if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  107.                     SqlDataAdapter da = new SqlDataAdapter(cmd);  
  108.                     dt = new DataTable();  
  109.                     da.Fill(dt);  
  110.                     con.Close();  
  111.                     return dt;  
  112.                 } catch (Exception ex) {  
  113.                     throw ex;  
  114.                 }  
  115.             }  
  116.         }  
  117.     }  
  118. }  
In the same way add another class library and name it to BAL and add reference of DAL to BAL and write following code in it, 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using SCHEMA;  
  6. using DAL;  
  7. using System.Data;  
  8. namespace BAL {  
  9.     public class Class1 {  
  10.         public int Insert(SCHEMA.Class1 objSchema) {  
  11.             try {  
  12.                 DAL.Class1 objDAL = new DAL.Class1();  
  13.                 return objDAL.InsertData(objSchema);  
  14.             } catch (Exception ex) {  
  15.                 throw ex;  
  16.             }  
  17.         }  
  18.         public DataTable BindGrid() {  
  19.             try {  
  20.                 DAL.Class1 objDAL = new DAL.Class1();  
  21.                 return objDAL.BindGrid();  
  22.             } catch (Exception ex) {  
  23.                 throw ex;  
  24.             }  
  25.         }  
  26.         public DataTable GetById(int Id) {  
  27.             try {  
  28.                 DAL.Class1 objDAL = new DAL.Class1();  
  29.                 return objDAL.GetById(Id);  
  30.             } catch (Exception ex) {  
  31.                 throw ex;  
  32.             }  
  33.         }  
  34.         public int Update(SCHEMA.Class1 objSchema, int Id) {  
  35.             try {  
  36.                 DAL.Class1 objDAL = new DAL.Class1();  
  37.                 return objDAL.UpdateData(objSchema, Id);  
  38.             } catch (Exception ex) {  
  39.                 throw ex;  
  40.             }  
  41.         }  
  42.         public int Delete(int Id) {  
  43.             try {  
  44.                 DAL.Class1 objDAL = new DAL.Class1();  
  45.                 return objDAL.DeleteData(Id);  
  46.             } catch (Exception ex) {  
  47.                 throw ex;  
  48.             }  
  49.         }  
  50.         public DataTable BindImages() {  
  51.             try {  
  52.                 DAL.Class1 objDAL = new DAL.Class1();  
  53.                 return objDAL.BindImages();  
  54.             } catch (Exception ex) {  
  55.                 throw ex;  
  56.             }  
  57.         }  
  58.     }  
  59. }  
Now right click on project in solution explorer and add a webform and name it to webform1.aspx. This WebForm is for Inserting, Updating and Deleting Images. 

On design side write the following code:
 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ThreeTier.WebForm1" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10.             <div>  
  11.                 <table>  
  12.                     <tr>  
  13.                         <td>  
  14.                             <asp:Label ID = "lblName" runat="server" Text="Enter Image Name"></asp:Label>  
  15.                         </td>  
  16.                         <td>  
  17.                             <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  
  18.                         </td>  
  19.                     </tr>  
  20.                     <tr>  
  21.                         <td>  
  22.                             <asp:Label ID = "lblImage" runat="server" Text="UploadImage"></asp:Label>  
  23.                         </td>  
  24.                         <td>  
  25.                             <asp:FileUpload ID="imgUpload" runat="server" />  
  26.                             <asp:HiddenField ID="hdnImage" runat="server" />  
  27.                         </td>  
  28.                     </tr>  
  29.                     <tr>  
  30.                         <td>  
  31.                             <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />  
  32.                         </td>  
  33.                     </tr>  
  34.                     <tr>  
  35.                         <td>  
  36.                             <asp:GridView ID="gdImages" runat="server" AutoGenerateColumns="False"  
  37.                               AllowPaging="true" PageSize = 5  
  38.                               CssClass="Gridview t_view" HeaderStyle-BackColor="#61A6F8" ShowFooter="True"  
  39.                               HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"  
  40.                               onpageindexchanging="gdImages_PageIndexChanging"  
  41.                               onrowdeleting="gdImages_RowDeleting"  
  42.                               onselectedindexchanging="gdImages_SelectedIndexChanging"  
  43.                               onrowcommand="gdImages_RowCommand">  
  44.                                 <Columns>  
  45.                                     <asp:BoundField DataField="Id" HeaderText="Id"/>  
  46.                                     <asp:BoundField DataField="Name" HeaderText="Name"/>  
  47.                                     <asp:TemplateField HeaderText="Images">  
  48.                                         <ItemTemplate>  
  49.                                             <a target="_blank" id="lnk" runat="server" href='<%# string.Format("~/Site/Upload/Images/{0}", Eval("Path"))%>'><%#Eval("Path")%>  
  50.                                             </a>  
  51.                                         </ItemTemplate>  
  52.                                     </asp:TemplateField>  
  53.                                     <asp:CommandField ButtonType="Button" SelectText="Edit" ShowSelectButton="True" />  
  54.                                     <asp:TemplateField>  
  55.                                         <ItemTemplate>  
  56.                                             <asp:Button runat="server" ID="btnDelete" OnClientClick="return confirm('Are you sure,you want to delete this record ?');" Text="Delete" CommandArgument='  
  57.   
  58.                                                 <%# Eval("Id") %>' CommandName="Delete" />  
  59.                                             </ItemTemplate>  
  60.                                         </asp:TemplateField>  
  61.                                     </Columns>  
  62.                                     <HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>  
  63.                                 </asp:GridView>  
  64.                             </td>  
  65.                         </tr>  
  66.                     </table>  
  67.                 </div>  
  68.             </form>  
  69.         </body>  
  70.     </html>  
In cs side write the following code,add reference of  DAL, Schema and BAL in the project.  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.IO;  
  8. using SCHEMA;  
  9. using BAL;  
  10. using System.Data;  
  11. namespace ThreeTier {  
  12.     public partial class WebForm1: System.Web.UI.Page {  
  13.         DataTable dt;  
  14.         protected void Page_Load(object sender, EventArgs e) {  
  15.             if (!IsPostBack) BindGrid();  
  16.         }  
  17.         private void BindGrid() {  
  18.             try {  
  19.                 BAL.Class1 objBal = new BAL.Class1();  
  20.                 gdImages.Columns[0].Visible = true;  
  21.                 gdImages.DataSource = objBal.BindGrid();  
  22.                 gdImages.DataBind();  
  23.                 gdImages.Columns[0].Visible = false;  
  24.                 gdImages.Visible = true;  
  25.             } catch (Exception ex) {  
  26.                 return;  
  27.             }  
  28.         }  
  29.         protected void btnSubmit_Click(object sender, EventArgs e) {  
  30.             try {  
  31.                 if (btnSubmit.Text == "Submit") {  
  32.                     if (checkBlank()) {  
  33.                         InsertData();  
  34.                     }  
  35.                 } else if (btnSubmit.Text == "Update") {  
  36.                     int Id = int.Parse(gdImages.Rows[gdImages.SelectedIndex].Cells[0].Text);  
  37.                     UpdateData(Id);  
  38.                 }  
  39.             } catch (Exception ex) {  
  40.                 throw ex;  
  41.             }  
  42.         }  
  43.         private void InsertData() {  
  44.             string FileName = UploadImages();  
  45.             SCHEMA.Class1 objSchema = new SCHEMA.Class1();  
  46.             objSchema.Name = txtName.Text;  
  47.             if (imgUpload.HasFile) {  
  48.                 objSchema.Path = FileName;  
  49.             } else {  
  50.                 objSchema.Path = hdnImage.Value;  
  51.             }  
  52.             BAL.Class1 objBAL = new BAL.Class1();  
  53.             int result = objBAL.Insert(objSchema);  
  54.             if (result > 0) {  
  55.                 Showmsg("Image Uploaded Successfully");  
  56.             }  
  57.             BindGrid();  
  58.             Clear();  
  59.         }  
  60.         public void UpdateData(int Id) {  
  61.             string FileName = UploadImages();  
  62.             SCHEMA.Class1 objSchema = new SCHEMA.Class1();  
  63.             objSchema.Name = txtName.Text;  
  64.             if (imgUpload.HasFile) {  
  65.                 objSchema.Path = FileName;  
  66.             } else {  
  67.                 objSchema.Path = hdnImage.Value;  
  68.             }  
  69.             BAL.Class1 objBAL = new BAL.Class1();  
  70.             int result = objBAL.Update(objSchema, Id);  
  71.             if (result > 0) {  
  72.                 Showmsg("Image Updated Successfully");  
  73.             }  
  74.             btnSubmit.Text = "Submit";  
  75.             BindGrid();  
  76.             Clear();  
  77.         }  
  78.         private void Clear() {  
  79.             txtName.Text = "";  
  80.         }  
  81.         private bool checkBlank() {  
  82.             bool flag = true;  
  83.             string msg = string.Empty;  
  84.             if (!imgUpload.HasFile) {  
  85.                 Showmsg("Please Upload Image");  
  86.                 flag = false;  
  87.             } else {  
  88.                 if (!(Path.GetExtension(imgUpload.PostedFile.FileName).Equals(".jpg") || Path.GetExtension(imgUpload.PostedFile.FileName).Equals(".img") || Path.GetExtension(imgUpload.PostedFile.FileName).Equals(".png"))) {  
  89.                     Showmsg("Please Upload Valid File");  
  90.                     flag = false;  
  91.                 }  
  92.             }  
  93.             return flag;  
  94.         }  
  95.         private void Showmsg(string Message) {  
  96.             ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "Alert""alert('" + Message + "');"true);  
  97.         }  
  98.         public string UploadImages() {  
  99.             string result = string.Empty;  
  100.             if (imgUpload.HasFile) {  
  101.                 string extension = System.IO.Path.GetExtension(imgUpload.PostedFile.FileName);  
  102.                 if (extension == ".jpg" || extension == ".png" || extension == ".img") {  
  103.                     result = imgUpload.PostedFile.FileName;  
  104.                     imgUpload.PostedFile.SaveAs(MapPath("~") + "/Site/Upload/Images/" + result);  
  105.                 }  
  106.             }  
  107.             return result;  
  108.         }  
  109.         protected void gdImages_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) {  
  110.             try {  
  111.                 BAL.Class1 objBAL = new BAL.Class1();  
  112.                 int Id = int.Parse(gdImages.Rows[e.NewSelectedIndex].Cells[0].Text);  
  113.                 dt = new DataTable();  
  114.                 dt = objBAL.GetById(Id);  
  115.                 if (dt.Rows.Count > 0) {  
  116.                     txtName.Text = dt.Rows[0]["Name"].ToString();  
  117.                     hdnImage.Value = dt.Rows[0]["Path"].ToString();  
  118.                     btnSubmit.Text = "Update";  
  119.                 }  
  120.             } catch (Exception ex) {  
  121.                 throw ex;  
  122.             }  
  123.         }  
  124.         protected void gdImages_RowDeleting(object sender, GridViewDeleteEventArgs e) {}  
  125.         protected void gdImages_PageIndexChanging(object sender, GridViewPageEventArgs e) {  
  126.             gdImages.PageIndex = e.NewPageIndex;  
  127.             BindGrid();  
  128.         }  
  129.         protected void gdImages_RowCommand(object sender, GridViewCommandEventArgs e) {  
  130.             if (e.CommandName.Equals("Delete")) {  
  131.                 int Id = int.Parse(e.CommandArgument.ToString());  
  132.                 DeleteRecord(Id);  
  133.             }  
  134.         }  
  135.         private void DeleteRecord(int Id) {  
  136.             try {  
  137.                 BAL.Class1 objBAL = new BAL.Class1();  
  138.                 int Result = objBAL.Delete(Id);  
  139.                 if (Result > 0) {  
  140.                     Showmsg("Image Deleted Sucessfully");  
  141.                 }  
  142.                 BindGrid();  
  143.                 Clear();  
  144.             } catch (Exception ex) {  
  145.                 throw ex;  
  146.             }  
  147.         }  
  148.     }  
  149. }  
Now right click on project in solution explorer and add a webform and name it to webform2.aspx. This WebForm is for displaying images.
 
Write the following code on design i.e. aspx page: 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="ThreeTier.WebForm2" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10.             <div>  
  11.                 <asp:DataList ID = "dtImages" runat="server" RepeatColumns = "3" RepeatDirection = "Horizontal" Width="50%" BorderColor="#336699" BorderStyle="Solid" BorderWidth="2px">  
  12.                     <ItemTemplate>  
  13.                         <asp:Label ID = "lblImages" runat = "server" Text = '<%#Eval("Name")%>'>  
  14.                         </asp:Label>  
  15.                         <br />  
  16.                         <asp:Image ID="imgGallery" runat="server" ImageUrl='  
  17.                             <%# Bind("Path""~/Site/Upload/Images/{0}") %>' />  
  18.                         </ItemTemplate>  
  19.                     </asp:DataList>  
  20.                 </div>  
  21.             </form>  
  22.         </body>  
  23.     </html>  
And on the cs side write the following code: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. namespace ThreeTier {  
  8.     public partial class WebForm2: System.Web.UI.Page {  
  9.         protected void Page_Load(object sender, EventArgs e) {  
  10.             if (!IsPostBack) {  
  11.                 BindImages();  
  12.             }  
  13.         }  
  14.         private void BindImages() {  
  15.             try {  
  16.                 BAL.Class1 objBal = new BAL.Class1();  
  17.                 dtImages.DataSource = objBal.BindImages();  
  18.                 dtImages.DataBind();  
  19.                 dtImages.Visible = true;  
  20.             } catch (Exception ex) {  
  21.                 throw ex;  
  22.             }  
  23.         }  
  24.     }  
  25. }   
I have attached the project for reference, if there are some issues mention it in the comment section.