Monday, December 28, 2015

How to create photo album in asp.net - Part I

Introduction: In this article I am going to explain how to create photo album in asp.net

Description:
This article will cover the concept of creating photo album/albums in asp.net project. User’s will be able to create their own album/albums and can upload/add photos.
To fulfill this requirement I have created two tables Tb_Album and Tb_Photo.


Implementation:
Create store procedure to insert data into database:
Create PROCEDURE Sp_InsertAlbum
(
@name varchar(100),
@albumcover varchar(max),
@id int output
)
AS
BEGIN
            SET NOCOUNT ON;

  Insert into Tb_Album(AlbumName,AlbumCover) values (@name,@albumcover)
  set @id = SCOPE_IDENTITY() 
return @id 
END

Store procedure to fetch the record of album table
Create PROCEDURE Sp_GetAlbum
AS
BEGIN
           
            SET NOCOUNT ON;
select * from Tb_Album
END

HTML Markup of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <style>
   table tr td
   {
           text-align: center;
   }
   a
   {
           text-decoration: none;
    font-weight: bold;
    font-size: 18px;
    color: #000;
}
   </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin-left:40px;">
     <table>
        <tr><td></td><td></td></tr>
           <tr><td></td><td></td></tr>
    <tr><td>Create Album :</td><td> <asp:TextBox ID="txtalbumname" runat="server"></asp:TextBox></td></tr>
     <tr><td></td><td></td></tr>
    <tr><td>Upload Cover :</td><td> <asp:FileUpload ID="albumcover" runat="server" /></td></tr>
     <tr><td></td><td></td></tr>
    <tr><td></td><td> <asp:Button ID="btncreate" runat="server" Text="Create Album"
             /></td></tr>
    <tr><td></td><td></td></tr>
    <tr><td></td><td></td></tr>
    </table>
    <asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal" DataKeyField="AlbumId" RepeatColumns="4"
            onitemcommand="DataList1_ItemCommand">         
            <AlternatingItemStyle Font-Bold="False" Font-Italic="False"
                Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
            <ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False"
                Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Right" />         
        <ItemTemplate> 
        <table>
        <tr><td><asp:Image ID="imgEmp" runat="server" Width="300px" Height="300px" ImageUrl='<%# Bind("AlbumCover") %>' style="padding:10px"/></td></tr>
          <tr><td> <asp:LinkButton ID="linkItemDetails" runat="server" Text='<%# Bind("AlbumName") %>'></asp:LinkButton>
             </td></tr>
        </table>
           </ItemTemplate>
        </asp:DataList>
    </div>
    </form>
</body>
</html>

Add the namespace:
C# Code:

using System.Configuration;
using System.Data.SqlClient;
using System.Data;

VB.net Code:
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data

Create sqlconnection:
C# Code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());

VB.net Code:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

Insert the data
On button click write the below given code
C# Code:
protected void btncreate_Click(object sender, EventArgs e)
    {
        try
        {
                string filepath = Server.MapPath("~/img/") + Guid.NewGuid() + albumcover.PostedFile.FileName;
                albumcover.SaveAs( filepath);
                string fl = filepath.Substring(filepath.LastIndexOf("\\"));
                string[] split = fl.Split('\\');
                string newpath = split[1];
                string imagepath = "~/img/" + newpath;
                SqlCommand cmd = new SqlCommand("Sp_InsertAlbum", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                cmd.Parameters.AddWithValue("@name", txtalbumname.Text);
                cmd.Parameters.AddWithValue("@albumcover", imagepath);
                cmd.Parameters.Add("@id", SqlDbType.Int);
                cmd.Parameters["@id"].Direction = ParameterDirection.Output;
                cmd.ExecuteNonQuery();
                Session["albumid"] = cmd.Parameters["@id"].Value;
                Response.Redirect("frmphotogallery.aspx", false);
                con.Close();      
        }
        catch (Exception ex)
        {
        }
    }

VB.net Code:
Protected Sub btncreate_Click(sender As Object, e As System.EventArgs) Handles btncreate.Click
        Try
            Dim filepath As String = Server.MapPath("~/img/") + Guid.NewGuid().ToString() + albumcover.PostedFile.FileName
            albumcover.SaveAs(filepath)
            Dim fl As String = filepath.Substring(filepath.LastIndexOf("\"))
            Dim split As String() = fl.Split("\"c)
            Dim newpath As String = split(1)
            Dim imagepath As String = Convert.ToString("~/img/") & newpath
            Dim cmd As New SqlCommand("Sp_InsertAlbum", con)
            cmd.CommandType = CommandType.StoredProcedure
            con.Open()
            cmd.Parameters.AddWithValue("@name", txtalbumname.Text)
            cmd.Parameters.AddWithValue("@albumcover", imagepath)
            cmd.Parameters.Add("@id", SqlDbType.Int)
            cmd.Parameters("@id").Direction = ParameterDirection.Output
            cmd.ExecuteNonQuery()
            Session("albumid") = cmd.Parameters("@id").Value
            Response.Redirect("frmphotogallery.aspx", False)
            con.Close()
        Catch ex As Exception
        End Try
    End Sub

Fetch created albums from database
Create a method to get the albums information from database and call it on page load.
C# Code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Binddatalist();
        }
    }
public void Binddatalist()
    {
        SqlDataAdapter adp = new SqlDataAdapter("Sp_GetAlbum", con);
        adp.SelectCommand.CommandType = CommandType.StoredProcedure;
        DataTable dt = new DataTable();
        adp.Fill(dt);
        DataList1.DataSource = dt;
        DataList1.DataBind();
    }

VB.net Code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Binddatalist()
        End If
    End Sub

Public Sub Binddatalist()
        Dim adp As New SqlDataAdapter("Sp_GetAlbum", con)
        adp.SelectCommand.CommandType = CommandType.StoredProcedure
        Dim dt As New DataTable()
        adp.Fill(dt)
        DataList1.DataSource = dt
        DataList1.DataBind()
    End Sub

Write the below given code on Itemcommend event of datalist.
C# Code:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    {
        int id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex].ToString());
        Session["albumid"] = id;
        Response.Redirect("gallery.aspx");
    }

VB.net Code:
Protected Sub DataList1_ItemCommand(source As Object, e As DataListCommandEventArgs)
        Dim id As Integer = Convert.ToInt32(DataList1.DataKeys(e.Item.ItemIndex).ToString())
        Session("albumid") = id
        Response.Redirect("gallery.aspx")
    End Sub

Build and run the application. 


Part II : howto upload or add photo to album in asp.net


DEMO:

How to create photo album in asp.net

No comments:

Post a Comment