January 26, 2011

Get the Line number in Visual Studio:

Most of the developer's face the trouble to reach the exact line after getting the error details with line number while debug, Here the simple tips to achieve this,

If you want the line numbers throughout the project fallow the below steps...

Just Go to

TOOLS---->Options------>Text Editor------>Select the language in which you write the code----->Display------>Select Line Number. 

If you get the line number just at the time of debug just press " CONTROL + G " where you find the textbox to enter the line number and fix the error....






December 20, 2010

Upload the image to database and View in Gridview

Hi,

Most of them using the images to be displayed in their websites, I have most of the beginners when trying this they are able to upload the images to database but suffer a lot to view the same image in the web, Since i have posted the coding in C# to upload the image in database and view the list of all images in grid view.

Here the coding starts,

First create the table as fallows,
create table filees(
id IDENTITY(1,1),
name varchar(50),
images image)


Let create the .aspx file the code as fallows, I used file upload control to upload the image,

    <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button runat="server" ID="btnSave" OnClick="SaveToTheDatabase" Text="Save to the database" />
<p><asp:Label ID="lblMessage" runat="server" EnableViewState="false" />&nbsp;</p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField HeaderText="ID" DataField="id" />
    <asp:BoundField HeaderText="Picture Name" DataField="names" />
    <asp:TemplateField HeaderText="Picture">
    <ItemTemplate>
    <img src="Handler1.ashx?id=<%# Eval("id").ToString() %>" width="150" height="100" />
    </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>
</form>

When the select the image and cliks the button the image is saved in binary format.
The code behind coding is

protected void Page_Load(object sender, EventArgs e)
        {
            string connStr = ConfigurationManager.ConnectionStrings["setting"].ConnectionString;
            DataTable table = new DataTable();
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "SELECT id, names FROM files ORDER BY names";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    {
                        conn.Open();
                        ad.Fill(table);
                        conn.Close();
                    }
                }
            }
            GridView1.DataSource = table;
            GridView1.DataBind();
        }
        protected void SaveToTheDatabase(object sender, EventArgs e)
        {
            string fileName = FileUpload1.PostedFile.FileName;
            int fileLength = FileUpload1.PostedFile.ContentLength;
            byte[] imageBytes = new byte[fileLength];
            FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, fileLength);
            string connStr = ConfigurationManager.ConnectionStrings["setting"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "INSERT INTO files (names, doc) VALUES (@names, @doc)";
                SqlParameter[] prms = new SqlParameter[2];
                prms[0] = new SqlParameter("@names", SqlDbType.VarChar, 50);
                prms[0].Value = fileName;
                prms[1] = new SqlParameter("@doc", SqlDbType.Image);
                prms[1].Value = imageBytes;
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(prms);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
                lblMessage.Text = "Picture uploaded successsfully !";
            }
        }

And i am using the generic handler to view the images in the grip view, which is called by the item template in the grip view:

public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["id"] == null) return;
            string connStr = ConfigurationManager.ConnectionStrings["setting"].ConnectionString;
            string pictureId = context.Request.QueryString["id"];
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT doc FROm files WHERE id = @id", conn))
                {
                    cmd.Parameters.Add(new SqlParameter("@id", pictureId));
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                       reader.Read();
                        context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("doc")]);
                        reader.Close();
                    }
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

Usually the IsReusable method is set to false, i changed so that the same handler can be used in future.



The output would be show as:

December 16, 2010

File Upload & Download with asp.net, C# & sql server

Files of ms-word, ms-excel, pdf and images are stored (Uploaded)  into sql server 2005 and retrieving back to client side(downloaded to client system).
Iam saving the files in database in binary format & list of files is listed in dropdown fetched from sql server.
. 1. Create a Table in database in which we are going store our uploaded files, 
CREATE TABLE [dbo].[Files](
    [FileID] [int] NOT NULL,
    [FileName] [varchar](50) NOT NULL,
    [Files] [varbinary](max) NOT NULL
) ON [PRIMARY]

2.Create the  Fileupload.aspx which contains
  • ·         FileUpload control
  • ·         Dropdownlist
  • ·         Buttons(2)-Upload, Open

  Fileupload.aspx
Select the File to upload
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
Download or Open the File<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Open" />

3.The code for code behind of Fileupload.aspx.cs as fallows

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Filldrop(); 
            }
        }
        private void Filldrop()
    {
        SqlDataAdapter ad = new SqlDataAdapter("Select FileID, FileName from files", "Data Source=servername;Initial Catalog=databasename");
            DataSet ds=new DataSet() ;
            ad.Fill(ds, "docs");
            DropDownList1.DataSource = ds.Tables[0];
            DropDownList1.DataTextField = " FileName ";
            DropDownList1.DataValueField = " FileName ";
            DropDownList1.DataBind();
    }
protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (FileUpload1.HasFile)
                {
                    int filsize = FileUpload1.PostedFile.ContentLength;
                    byte[] filebyt = new byte[filsize];
                    FileUpload1.PostedFile.InputStream.Read(filebyt, 0, filsize);
                    SqlConnection con = new SqlConnection("Data Source=servername;Initial Catalog=databasename");
                    SqlCommand cmd = new SqlCommand("insert into files(FileName, Files)"+
                        "values (@FileName,@ Files)", con);
                    cmd.Parameters.AddWithValue("@FileName ", Path.GetFileName(FileUpload1.PostedFile.FileName));
                    cmd.Parameters.AddWithValue("@Files ", filebyt);
                    con.Open();
                    int result = cmd.ExecuteNonQuery();
                    con.Close(); cmd.Dispose(); con.Dispose(); filebyt = null;
                    Response.Write("File uploaded");
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                string strname = string.Empty;
                string namee = DropDownList1.SelectedItem.Value;
                SqlConnection con = new SqlConnection("Data Source=servername;Initial Catalog=databasename");
                SqlCommand cmd = new SqlCommand("select FileName, Files from files where names='"+namee+"'", con);
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    strname = dr["FileName "].ToString();
                    Byte[] filbyt = (Byte[])dr["Files "];
                    FileStream filstr = new FileStream(
                        Server.MapPath("Documents")
                        + @"\" + strname, FileMode.OpenOrCreate);
                    filstr.Write(filbyt, 0, filbyt.Length);
                    filstr.Close(); filstr.Dispose();
                    filbyt = null;
                }
con.Close(); cmd.Dispose(); con.Dispose();
                if (strname != string.Empty)
                {
Response.Redirect(@"Documents/" + strname);
                }
            }
            catch (Exception ex)
            {
               Response.Write(ex.Message);
            }
}

4. Now the Project executes perfectly….

Fallow me to play interesting codes with c#, asp.net coding