Tuesday, 19 April 2016

How to Create dynamic photo gallery in asp.net

Create dynamic photo gallery in asp.net using C#

Create Database in sql like this. There are two table 
1. Album Table
2. Image Table (which are related with album table)

Sql Script

CREATE TABLE [dbo].[GroupImage](
[Id] [int] IDENTITY(1,1) NOT NULL,
[GroupName] [varchar](80) NOT NULL,
[Image] [varchar](200) NULL,
 CONSTRAINT [PK__GroupIma__6EFCD4350F975522] PRIMARY KEY CLUSTERED 
(
[GroupName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [dbo].[Image](
[Id] [int] IDENTITY(1,1) NOT NULL,
[GroupName] [varchar](80) NULL,
[Name] [varchar](50) NULL,
[Date] [varchar](30) NULL,
[Image] [varchar](200) NULL
) ON [PRIMARY]


Now add a folder with name of "GroupImage" in project folder.

Now add aspx page with name of GroupImage.aspx and add following script between head tag

  <script type="text/javascript">
        function fnConfirm() {
            if (confirm("The item will be deleted. Are you sure want to continue?") == true)
                return true;
            else
                return false;
        }
</script>
    <script type="text/javascript">
        function previewFile() {
            var preview = document.querySelector('#<%=Image1.ClientID %>');
            var file = document.querySelector('#<%=fulImage_Group.ClientID %>').files[0];
            var reader = new FileReader();

            reader.onloadend = function () {
                preview.src = reader.result;
            }

            if (file) {
                reader.readAsDataURL(file);
            } else {
                preview.src = "";
            }
        }
   </script>
  
Now add following code under body tag


 <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
  <section id="main" class="column">
  <article class="module width_full">
<header><h3>  Add Album</h3></header>
           <div class="row">
                <div class="col-lg-12">
<div class="module_content">

   <table class="xx">
        <tr>
            <td rowspan="2" 
                
                style="vertical-align: top;">
                <asp:GridView ID="GridView1" class="table table-striped table-bordered table-hover" runat="server" AutoGenerateColumns="False" 
                    OnSelectedIndexChanged="OnSelectedIndexChanged" 
                    onrowdeleting="GridView1_RowDeleting" Width="400px" Height="100%">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="Name" runat="server" text='<%#Eval("GroupName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Image">
                            <ItemTemplate>
                                <asp:Image ID="Image" runat="server" Height="50" ImageUrl='<%# "~/" +Eval("Image")%>'
                                    Width="50" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Action">
                            <ItemTemplate>
                                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select" ForeColor="Red">Select</asp:LinkButton>
                                <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" ForeColor="Red">Delete</asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
            <td style=" font-size: 20px;">
              </td>
        </tr>
        <tr>
            <td style="vertical-align: top; width: 400px;">
                <table style=" width: 400px; line-height:40px; margin-left:40px">
                    <tr>
                        <td>
                            Folder Name</td>
                        <td>
                            <asp:TextBox ID="txtName_Group" runat="server"  Width="200px"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Image</td>
                        <td>
                         <input ID="fulImage_Group" type="file" onchange="previewFile()"  
                    runat="server"  />
                           
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                                ControlToValidate="fulImage_Group" ErrorMessage="RequiredFieldValidator" 
                                ForeColor="Red" ValidationGroup="a">*</asp:RequiredFieldValidator>
                           
                        &nbsp;</td>
                    </tr>
                    <tr>
                        <td>
                            &nbsp;</td>
                        <td>
                            <asp:Button ID="btnSave_Group" runat="server" 
                                Text="Save" onclick="Upload" ValidationGroup="a" />
                            &nbsp;<asp:Button ID="btnEdit_Group" runat="server" onclick="btnEdit_Group_Click" 
                                Text="Edit" Visible="False" ValidationGroup="a" />
                            &nbsp;<asp:Button ID="btnCancel_Group" runat="server" 
                                onclick="btnCancel_Group_Click" Text="Cancel" Visible="False" />
                        </td>
                    </tr>
                </table>
                <br />
                <asp:Image ID="Image1" runat="server" Height="100px" Width="100px" />
            </td>
        </tr>
        <tr>
            <td class="style2">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
         </div>
        </div>
        </div>
        </article>
    </section>


Code behind (C#) code for cs file of this page
 add following namespace

using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;


after this use this code

    SqlCommand cmd;
    SqlDataAdapter da;
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {

        gridViewBind();

    }
    private int CreateDirectory(string NewDirectory)
    {
        int c = 0;
        try
        {
            string savelocation = Server.MapPath("~/" + "GroupImage/");
            int directoryCount = System.IO.Directory.GetDirectories(savelocation).Length;
            savelocation = savelocation + NewDirectory;
            for (int i = 0; i < directoryCount; i++)
            {
                if (Directory.Exists(savelocation))
                {
                    c = 1;
                    break;
                }
            }
        }
        catch (IOException _err)
        {
            Response.Write(_err.Message);
        }
        return c;
    }
    void gridViewBind()
    {
        try
        {
            if (Connection.con.State != ConnectionState.Open)
                Connection.con.Open();
            da = new SqlDataAdapter("select * from GroupImage", Connection.con);
            ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Connection.con.Close();
        }
    }
    protected void Upload(object sender, EventArgs e)
    {
        int dir = CreateDirectory(txtName_Group.Text);
        if (dir == 1)
        {
            Page.ClientScript.RegisterStartupScript(typeof(Page), "Error", "alert('This Name Folder Allready Exits')", true);
        }
        else
        {
            try
            {
                string imgPath = null, fileName = null;
                Directory.CreateDirectory(Server.MapPath("~/" + "GroupImage/" + txtName_Group.Text));
                if (fulImage_Group.PostedFile != null && fulImage_Group.PostedFile.FileName != "")
                {
                    fileName = fulImage_Group.PostedFile.FileName;
                    imgPath = "GroupImage/" + txtName_Group.Text + "/" + fileName;
                    string targetPath = Server.MapPath("~/" + imgPath);
                    Stream strm = fulImage_Group.PostedFile.InputStream;
                    var targetFile = targetPath;
                    GenerateThumbnails(strm, targetFile);
                }
                if (Connection.con.State != ConnectionState.Open)
                    Connection.con.Open();
                int x = 0;
                SqlCommand cmd = new SqlCommand("insert into GroupImage values('" + txtName_Group.Text + "','" + imgPath + "')", Connection.con);
                x = cmd.ExecuteNonQuery();
                if (x == 1)
                {
                    txtName_Group.Text = "";
                    gridViewBind();

                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(typeof(Page), "Error", "alert('Try Again !!!')", true);
                }
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterStartupScript(typeof(Page), "Error", "alert('" + ex.Message + "')", true);
            }
            finally
            {
                Connection.con.Close();
            }
        }
    }
    protected void btnEdit_Group_Click(object sender, EventArgs e)
    {
        try
        {
            int x = 0;
            string imgPath = null, fileName = null;
            if (fulImage_Group.PostedFile != null && fulImage_Group.PostedFile.FileName != "")
            {
                fileName = fulImage_Group.PostedFile.FileName;
                imgPath = "GroupImage/" + txtName_Group.Text + "/" + fileName;
                string targetPath = Server.MapPath("~/" + imgPath);
                Stream strm = fulImage_Group.PostedFile.InputStream;
                var targetFile = targetPath;
                GenerateThumbnails(strm, targetFile);
            }
            if (Connection.con.State != ConnectionState.Open)
                Connection.con.Open();
            SqlCommand cmd = new SqlCommand("update GroupImage set Image='" + imgPath + "' where GroupName='" + txtName_Group.Text + "'", Connection.con);
            x = cmd.ExecuteNonQuery();
            if (x == 1)
            {
                txtName_Group.Text = "";
                txtName_Group.Enabled = true;
                Image1.ImageUrl = "";
                btnSave_Group.Visible = true;
                btnEdit_Group.Visible = false;
                btnCancel_Group.Visible = false;
                gridViewBind();

            }

        }
        catch (Exception ex)
        {
        }
        finally
        {
            Connection.con.Close();
        }
    }
    protected void btnCancel_Group_Click(object sender, EventArgs e)
    {
        txtName_Group.Text = "";
        txtName_Group.Enabled = true;
        btnCancel_Group.Visible = false;
        btnEdit_Group.Visible = false;
        btnSave_Group.Visible = true;
        Image1.ImageUrl = "";
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            Label Name = GridView1.Rows[e.RowIndex].FindControl("Name") as Label;
            Connection.con.Open();
            string qry = "delete from GroupImage where GroupName='" + Name.Text + "'";
            cmd = new SqlCommand(qry, Connection.con);
            cmd.ExecuteNonQuery();
            string path = Server.MapPath("~/" + "GroupImage/" + Name.Text);
            Directory.Delete(path, true);
            gridViewBind();

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Connection.con.Close();
        }
    }
    private void GenerateThumbnails(Stream sourcePath, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            //var newWidth = (int)(image.Width * scaleFactor);
            //var newHeight = (int)(image.Height * scaleFactor);
            var newWidth = (int)(200);
            var newHeight = (int)(200);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }
    protected void OnSelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GridView1.SelectedRow;
        txtName_Group.Text = (row.FindControl("Name") as Label).Text;
        Image1.ImageUrl = (row.FindControl("Image") as System.Web.UI.WebControls.Image).ImageUrl;
        txtName_Group.Enabled = false;
        btnSave_Group.Visible = false;
        btnEdit_Group.Visible = true;
        btnCancel_Group.Visible = true;

    }


Now Add New aspx file with name of Image.aspx

Add this html code in
 <script type="text/javascript">
        function previewFile() {
            var preview = document.querySelector('#<%=Image1.ClientID %>');
            var file = document.querySelector('#<%=FileUpload1.ClientID %>').files[0];
            var reader = new FileReader();

            reader.onloadend = function () {
                preview.src = reader.result;
            }

            if (file) {
                reader.readAsDataURL(file);
            } else {
                preview.src = "";
            }
        }
   </script>

<asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
  <section id="main" class="column">
  <article class="module width_full">
<header><h3>  Add Album</h3></header>
           <div class="row">
                <div class="col-lg-12">
<div class="module_content">
    <table class="style1">
        <tr>
            <td>
               
              
               
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td style="width: 500px;  vertical-align: top;">
                <asp:GridView ID="GridView1" class="table table-striped table-bordered table-hover" runat="server" AutoGenerateColumns="False" 
                    OnSelectedIndexChanged="OnSelectedIndexChanged" 
                    onrowdeleting="GridView1_RowDeleting">
                 <Columns>
                  <asp:templatefield headertext="Group Name">
                    <itemtemplate>
                        <asp:label id="GroupName" runat="server" text='<%#Eval("GroupName")%>'></asp:label>
                    </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Image Name">
                    <itemtemplate>
                        <asp:label id="Name" runat="server" text='<%#Eval("Name")%>'></asp:label>
                    </itemtemplate>
                    </asp:templatefield>
                      <asp:templatefield headertext="Date">
                    <itemtemplate>
                        <asp:label id="Date" runat="server" text='<%#Eval("Date")%>'></asp:label>
                    </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Image">
                    <itemtemplate>
                        <asp:Image ID="Image" runat="server" ImageUrl='<%#"~/" +Eval("Image")%>' Width="50" Height="50"/>
                     </itemtemplate>
                    </asp:templatefield>
                      <asp:TemplateField HeaderText="Action">
                            <ItemTemplate>
                                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select" ForeColor="Blue">Select</asp:LinkButton>
                                <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" ForeColor="Blue">Del</asp:LinkButton>
                                 <asp:label id="Id" runat="server" text='<%#Eval("Id")%>' Visible="false"></asp:label>
                                </ItemTemplate>
                        </asp:TemplateField>
                   </Columns>
                </asp:GridView>
            </td>
            <td style="width: 400px; vertical-align: top;">
                <table style="margin-left:30px">
                    <tr>
                        <td>
                            Group Name</td>
                        <td>
                            <asp:DropDownList ID="DropDownList1" runat="server" 
                                DataSourceID="SqlDataSource1" DataTextField="GroupName" 
                                DataValueField="GroupName" AutoPostBack="True" 
                                onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="200px" 
                                Height="25px">
                            </asp:DropDownList>
                            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                                ConnectionString="<%$ ConnectionStrings:CS %>" 
                                SelectCommand="SELECT [GroupName] FROM [GroupImage] ORDER BY [GroupName]">
                            </asp:SqlDataSource>
                            <asp:HiddenField ID="hdfId" runat="server" />
                            <asp:HiddenField ID="hdfGroupName" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Name</td>
                        <td>
                            <asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Date</td>
                        <td>
                            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                            <asp:CalendarExtender ID="TextBox2_CalendarExtender" runat="server" Format="dd/MM/yyyy" 
                                Enabled="True" TargetControlID="TextBox2">
                            </asp:CalendarExtender>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Image</td>
                        <td>
                            <asp:FileUpload ID="FileUpload1" runat="server" onchange="previewFile()" />
                           
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                                ControlToValidate="FileUpload1" ErrorMessage="RequiredFieldValidator" 
                                ForeColor="Red" ValidationGroup="a">*</asp:RequiredFieldValidator>
                           
                        </td>
                    </tr>
                    <tr>
                        <td>
                            &nbsp;</td>
                        <td>
                            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" 
                                ValidationGroup="a" />
                            <asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="Edit" 
                                Visible="False" ValidationGroup="a" />
                        &nbsp;<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Cancel" 
                                Visible="False" />
                        </td>
                    </tr>
                </table>
                <br />
                <asp:Image ID="Image1" runat="server" Height="100px" Width="100px" 
                    ImageAlign="Top" />
                    <br />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
    </div>
        </div>
        </div>
        </article>
    </section>


Now add this code in Image.aspx.cs file

using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Drawing.Drawing2D;
using System.IO

SqlCommand cmd;
    SqlDataAdapter da;
    DataSet ds;
    string st;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            binddata("select * from Image where GroupName='" + DropDownList1.SelectedItem + "' Order by [Id] Desc");

    }
    string check()
    {
        string imgPath = null, imgName = null, savelocation;
        imgName = FileUpload1.FileName;
        imgPath = "GroupImage/" + DropDownList1.SelectedItem + "/" + imgName;
        if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
        {
            savelocation = Server.MapPath("~/" + imgPath);
            int i = 1;
            while (i > 0)
            {
                if (File.Exists(savelocation))
                {
                    imgPath = "GroupImage/" + DropDownList1.SelectedItem + "/" + i + "-" + imgName;
                    savelocation = Server.MapPath("~/" + imgPath);
                    i++;
                    continue;
                }
                else
                {
                    i = 0;
                    break;
                }
            }
        }
        return imgPath;

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string imgPath = check();
            string targetPath = Server.MapPath("~/" + imgPath);
            Stream strm = FileUpload1.PostedFile.InputStream;
            var targetFile = targetPath;
            Connection.con.Open();
            SqlCommand cmd = new SqlCommand("insert into Image values('" + DropDownList1.SelectedItem + "','" + TextBox1.Text + "','" + TextBox2.Text + "','" + imgPath + "')", Connection.con);
            SqlDataReader dr = cmd.ExecuteReader();
            GenerateThumbnails(strm, targetFile);
            dr.Close();
            binddata("select * from Image where GroupName='" + DropDownList1.SelectedItem + "'");
        }
        catch (Exception ex)
        {
        }
        finally
        {
            Connection.con.Close();
        }
    }
    private void GenerateThumbnails(Stream sourcePath, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            //var newWidth = (int)(image.Width * scaleFactor);
            //var newHeight = (int)(image.Height * scaleFactor);
            var newWidth = (int)(640);
            var newHeight = (int)(480);
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }
    void binddata(string st)
    {
        try
        {
            if (Connection.con.State != ConnectionState.Open)
                Connection.con.Open();
            da = new SqlDataAdapter(st, Connection.con);
            ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Connection.con.Close();
        }
    }
    protected void OnSelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GridView1.SelectedRow;
        hdfGroupName.Value = (row.FindControl("GroupName") as Label).Text;
        hdfId.Value = (row.FindControl("Id") as Label).Text;
        TextBox1.Text = (row.FindControl("Name") as Label).Text;
        TextBox2.Text = (row.FindControl("Date") as Label).Text;
        Image1.ImageUrl = (row.FindControl("Image") as System.Web.UI.WebControls.Image).ImageUrl;
        Button1.Visible = false;
        Button2.Visible = true;
        Button3.Visible = true;
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            Label Id = GridView1.Rows[e.RowIndex].FindControl("Id") as Label;
            Label GroupName = GridView1.Rows[e.RowIndex].FindControl("GroupName") as Label;
            System.Web.UI.WebControls.Image ImgId = GridView1.Rows[e.RowIndex].FindControl("Image") as System.Web.UI.WebControls.Image;
            Connection.con.Open();
            string qry = "delete from Image where Id='" + Id.Text + "' and GroupName='" + GroupName.Text + "'";
            string path = Server.MapPath(ImgId.ImageUrl);
            System.IO.File.Delete(path);
            cmd = new SqlCommand(qry, Connection.con);
            cmd.ExecuteNonQuery();
            //GridView1.DataBind();
            binddata("select * from Image where GroupName='" + GroupName.Text + "'");

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Connection.con.Close();
        }
    }


    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string st = "select * from Image where GroupName='" + DropDownList1.SelectedItem + "'";
        binddata(st);
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            int x = 0;
            string imgPath = check();
            string targetPath = Server.MapPath("~/" + imgPath);
            Stream strm = FileUpload1.PostedFile.InputStream;
            var targetFile = targetPath;
            Connection.con.Open();
            SqlCommand cmd = new SqlCommand("update Image set Image='" + imgPath + "',Name='" + TextBox1.Text + "',Date='" + TextBox2.Text + "' where GroupName='" + hdfGroupName.Value + "' and Id='" + hdfId.Value + "'", Connection.con);
            x = cmd.ExecuteNonQuery();
            GenerateThumbnails(strm, targetFile);
            if (x == 1)
            {
                TextBox1.Text = "";
                TextBox2.Text = "";
                Image1.ImageUrl = "";
                Button1.Visible = true;
                Button2.Visible = false;
                Button3.Visible = false;
            }
            binddata("select * from Image where GroupName='" + hdfGroupName.Value + "'");
        }
        catch (Exception ex)
        {
        }
        finally
        {
            Connection.con.Close();
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        TextBox1.Text = "";
        TextBox2.Text = "";
        Button2.Visible = false;
        Button3.Visible = false;
        Button1.Visible = true;
        Image1.ImageUrl = "";
    }


This is only for save gallery in database 
Now how to display this gallery in website like this

Next Page


No comments:

Post a Comment