Monday, 6 February 2012

Multiple fileuploder with sql server in asp.net


Introduction
The multiple fileuploader is important in the web site. When you are create a new website you have to implement in the in the picture galary inside the album as well. So in this article I will explain how to we can upload multiple file with a single click.
Implementation
As usual create a simple asp.net web project and then add following html code to design page accept the user input such as button to add file uploder according to your need and upload button for save image inside the folder and the database. and create a folder named in the root of your application where the images will be stored.

 
Figure:multiple fileuploders
HTML Code
<head runat="server">
    <title>Multiple FileUpload Example</title>
    <%--i am using this javascript function to add the fileuploader --%>
    <script type = "text/javascript">
        var counter = 0;
        function AddFileUpload()
        {
             var div = document.createElement('DIV');
             div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
             document.getElementById("FileUploadContainer").appendChild(div);
             counter++;
        }
        function RemoveFileUpload(div)
        {
             document.getElementById("FileUploadContainer").removeChild(div.parentNode);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data" method = "post">
        <span style ="font-family:Arial">Click to add files</span>&nbsp;&nbsp;
         <!--FileUpload Controls will be added here after clicking below button -->
         <!--m calling AddFileUpload() function on the click of this button  -->
        <input id="Button1" type="button" value="add" onclick = "AddFileUpload()" />
       
        <br /><br />
        <div id = "FileUploadContainer">
            <!--FileUpload Controls will be added here -->
        </div>
        <br />
      <!--this button is used to upload the files and save inside the database -->
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </form>
</body>
</html>
 We have designed galary page, to upload the multiple picture like as facebook and orkut.
now write code for multiple fileuploader.
C# code
using System;
using System.Data;
using System.Configuration;
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;
 // this  nemaespace for file upload.
using System.IO;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    // here m declared some variables that will be used to store the file name
    string fn, aguid;
    protected void Page_Load(object sender, EventArgs e)
    {
        // here i am creating connection with the database
        //or
        //  here i am declaring  connectionstring
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
        con.Open();
       

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        // here m using for loop
        // Request.Files.Count(with this line  i am count how many files user want to upload)
        // and this loop will work(i depend on the Request.Files.Count )
      
        for (int i = 0; i < Request.Files.Count; i++)
        {
            HttpPostedFile PostedFile = Request.Files[i];
            // here m checking that, fileuploader have file or not
            // if yes then it will go inside the if condition
            if (PostedFile.ContentLength > 0)
            {
                // here m opening the connection if the connection will close
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
               // in the fn variable m storing file
                fn = System.IO.Path.GetFileName(PostedFile.FileName);
                // here m using Guid.NewGuid()  method to create file new name
                aguid = Guid.NewGuid() + fn.Substring(fn.LastIndexOf(".")).ToString();
                // here m storing the file inside the folder
                PostedFile.SaveAs(Server.MapPath("image_thumbnail\\") + aguid);
                // here m using simple  insertion code
                 SqlCommand cmd = new SqlCommand();
                // insert query
                cmd.CommandText = @"INSERT INTO  tb_image_upload
                VALUES(@image_upload)";
                cmd.Connection = con;
                // here m a passing parameter
                cmd.Parameters.AddWithValue("@image_upload", aguid);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
               
             
            }
           
        }
    }
}

In above code, just create multiple file uploader in asp.net using c#.

Sql server script:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_image_upload]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tb_image_upload](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [image_upload] [nvarchar](500) NULL,
 CONSTRAINT [PK_tb_image_upload] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END


Conclusion
Through this article, you have learned how to ‘upload multiple files with a single click’ operation in web site using asp.net. ok guys(developers) enjoy the code.

Friday, 3 February 2012

How to split the string


Introduction: Hello friends, in this article i will explain that how we can split the string from a particular word. Here i’ll split the string from the <br/>tag.

Implementation: Create a new website add a page named split.aspx. Drag and drop a label named lbl_display and a button named btn_split from the toolbox at .aspx page.

Code for split.aspx page:

<form id="form1" runat="server">
    <div>
        <asp:Button ID="btn_split" runat="server" Text="Show Data"
            onclick="btn_split_Click" /><br />
        <asp:Label ID="lbl_display" runat="server" Text=""></asp:Label>
    </div>
    </form>

Code for gridview.aspx.cs page:

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.Text;

public partial class split : System.Web.UI.Page
{
    // here m declaring StringBuilder
    StringBuilder str_split = new StringBuilder();
    // These variable are for print solution in  next line
    string[] parts1;
    string[] parts2;
    string output;
    string input;
    Int32 k;
    Int32 j;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            // here i am addding the data inside in stringbuilder
            str_split.Append(@"Lorem Ipsum is simply dummy text of the printing and typesetting industry.<br/>
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, <br/>
            when an unknown printer took a galley of type and scrambled it to make a type specimen book.<br/>
            It has survived not only five centuries, but also the leap into electronic typesetting,
            remaining essentially unchanged.<br/>
            It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, <br/>
            and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.");
            // here here m adding  the stringbulder's data inside the input sting
            input = str_split.ToString();
            // here i am splitting the data after every <br/>
            parts1 = input.Split(new string[] { "<br/>" }, StringSplitOptions.None);
            // here i am using for loop to insert the data inside the  ViewState["parts"]
            //from the array  parts1 and add <br/> after every line
            for (k = 0; k < 6; k++)
            {
                ViewState["parts"] += (parts1[k] + "<br/>");
            }
            // here m using a viewstate to displaying the the data after clicking the button
            ViewState["value"] = 0;
        }
    }
    protected void btn_split_Click(object sender, EventArgs e)
    {

       // here m emptying the label after every click
        lbl_display.Text = string.Empty;
        //  // here here m adding  the ViewState's data inside the output sting
        output = ViewState["parts"].ToString();
        // here i am splitting the data after every <br/>
        parts2 = output.Split(new string[] { "<br/>" }, StringSplitOptions.None);
        Int32 j;
        // here m using the for loop to display the data step by step inside teh label
        for (j = 0; j <= Convert.ToInt32(ViewState["value"]); j++)
        {
            lbl_display.Text += (parts2[j] + "<br/>");
        }
        // when all line will be printed then the below condition will be satisfaies.
        // and the code will enter inside this condition
        if (Convert.ToInt32(ViewState["value"]) == 6)
        {
            // here m disabling the button after printing all the line
            btn_split.Enabled = false;
          
            //ViewState["value"]= "";
            return;
        }
        // here m incrementing in the viewstate with 1 everytime
        ViewState["value"] = Convert.ToInt32(ViewState["value"]) + 1;

      
    }
}


Below i am displaying the outout of this program in the image after first click:



Below i am displaying the outout of this program in the image after second click:



Below i am displaying the outout of this program in the image after third click:


Below i am displaying the outout of this program in the image after fourth click:



Below i am displaying the outout of this program in the image after fifth click:


Below i am displaying the outout of this program in the image after sixth click:


After sixth click the button will be disable because after sixth click all the complete six lives will be displayed in the label

Conclusion: Dear friends, through this article you have learned that how we can split the string.