• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 684
  • Last Modified:

Two different FileUpload controls on one page

I am trying to upload two files to a student database. One for course syllabus and the other is for course description with one class submit button. But for some reason same file is getting uploaded to the databse for both of the fields. I double-checked quite a few times to see if it was a naming issue or a wrong reference issue, but I couldnt find anything. When I try to add them seperately it works just fine so I might be doing something wrong with the if statements.

Then I am displaying class information on a gridview where these files (stored in database) can be opened through hyperlinks.

Any suggestions?. This is urgent and thank you.
protected void btnClassAdd_Click(object sender, EventArgs e)
    {
        SqlConnection scon = new SqlConnection(******);
        scon.Open();
        SqlCommand scom = new SqlCommand();
        scom.Connection = scon;
        scom.CommandText = "Insert into ClassDef (ClassDefName,ClassDefGroup,ClassDefSylName,ClassDefSylType,ClassDefSylBytes,ClassDefDescName,ClassDefDescType,ClassDefDescBytes) values ('" + txtClassName.Text + "','" + ddlClassGroup.SelectedItem.Text + "',@FileName,@FileType,@FileBytes,@DescFileName,@DescFileType,@DescFileBytes);Select Scope_identity();";
 
        if (SyllabusUpload.PostedFile == null || string.IsNullOrEmpty(SyllabusUpload.PostedFile.FileName) || SyllabusUpload.PostedFile.InputStream == null)
        //DescriptionUpload.PostedFile == null || string.IsNullOrEmpty(DescriptionUpload.PostedFile.FileName) || DescriptionUpload.PostedFile.InputStream ==null 
        {
            scom.Parameters.Add("@FileName", SqlDbType.NVarChar).Value = DBNull.Value;
            scom.Parameters.Add("@FileType", SqlDbType.VarChar).Value = DBNull.Value;
            scom.Parameters.Add("@FileBytes", SqlDbType.VarBinary).Value = DBNull.Value;
        }
        else
        {
            string extension = Path.GetExtension(SyllabusUpload.PostedFile.FileName).ToLower();
            string FileType = null;
            switch (extension)
            {
                case ".doc":
                    FileType = "document/doc";
                    break;
                case ".pdf":
                    FileType = "document/pdf";
                    break;
                default:
                    Label8.Visible = true;
                    Label8.Text = "Invalid file type uploaded for 'Course Syllabus'";
                    return;
            }
            scom.Parameters.AddWithValue("@FileName", txtSyllabusName.Text.Trim());
            scom.Parameters.AddWithValue("@FileType", FileType);
 
            byte[] imageBytes = new byte[SyllabusUpload.PostedFile.InputStream.Length + 1];
            SyllabusUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
            scom.Parameters.AddWithValue("@FileBytes", imageBytes);
        }
 
        if (DescriptionUpload.PostedFile == null || string.IsNullOrEmpty(DescriptionUpload.PostedFile.FileName) || DescriptionUpload.PostedFile.InputStream == null)
        {
            scom.Parameters.Add("@DescFileName", SqlDbType.NVarChar).Value = DBNull.Value;
            scom.Parameters.Add("@DescFileType", SqlDbType.VarChar).Value = DBNull.Value;
            scom.Parameters.Add("@DescFileBytes", SqlDbType.VarBinary).Value = DBNull.Value;
        }
        else
        {
            string DescExtension = Path.GetExtension(DescriptionUpload.PostedFile.FileName).ToLower();
            string DescFileType = null;
            switch (DescExtension)
            {
                case ".doc":
                    DescFileType = "document/doc";
                    break;
                case ".pdf":
                    DescFileType = "document/pdf";
                    break;
 
                default:
                    Label8.Visible = true;
                    Label8.Text = "Invalid file type uploaded for 'Course Description'";
                    return;
            }
 
            scom.Parameters.AddWithValue("@DescFileName", txtDescriptionName.Text.Trim());
            scom.Parameters.AddWithValue("@DescFileType", DescFileType);
            byte[] DescImageBytes = new byte[DescriptionUpload.PostedFile.InputStream.Length + 1];
            DescriptionUpload.PostedFile.InputStream.Read(DescImageBytes, 0, DescImageBytes.Length);
            scom.Parameters.AddWithValue("@DescFileBytes", DescImageBytes);
        }
        int ClassDefId = Convert.ToInt32(scom.ExecuteScalar());

Open in new window

0
askasp
Asked:
askasp
  • 12
  • 12
1 Solution
 
wht1986Commented:
at first glance it looks like you are missing the
        int ClassDefId = Convert.ToInt32(scom.ExecuteScalar());
after setting the parameters for the SyllabusUpload control

I only see your command executing once at the bottom. It which case only the DescriptionUpload file will get saved.
0
 
askaspAuthor Commented:
But actually Syllabus is getting inserted but not the Description properly. Description always gets the same file I upload with Syllabus.

And using
int ClassDefId = Convert.ToInt32(scom.ExecuteScalar());
twice wouldn't throw an error anyways?
0
 
askaspAuthor Commented:
So my logic was basicly
- Connection,sql statement and defining parameters
- Passing values to each parameter with two if statements
- and then executing the sql and getting the scope identity

I am really not sure what am I doing wrong
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
wht1986Commented:
Oh my bad, I see now it is different parameters for each file on the same sql command. Let me relook at the code and try a quick example on my end
0
 
wht1986Commented:
Well I just tried a simple experiment with 2 file upload controls and the simple code below and both inserted correctly into the table. I have the length of the varbinary fields set as MAX.

if you do a
select LEN(FileBytes), LEN(DescFileBytes) from ClassDef
do the sizes always equal?

If no, I am guessing it is saving correctly but perhaps the gridview has a bound column set incorrectly making it seem like it saved inccorectly.
    protected void Button1_Click(object sender, EventArgs e)
    {
        byte[] imageBytes = new byte[FileUpload1.PostedFile.InputStream.Length + 1];
        FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
 
        byte[] DescImageBytes = new byte[FileUpload2.PostedFile.InputStream.Length + 1];
        FileUpload2.PostedFile.InputStream.Read(DescImageBytes, 0, DescImageBytes.Length);
 
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Expert ExchangeConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("INSERT INTO [ClassDef] ([FileName], [FileType], [FileBytes], [DescFileName], [DescFileType], [DescFileBytes]) VALUES (@FileName, @FileType, @FileBytes, @DescFileName, @DescFileType, @DescFileBytes); SELECT SCOPE_IDENTITY();", conn);
 
        cmd.Parameters.AddWithValue("@FileName", FileUpload1.PostedFile.FileName);
        cmd.Parameters.AddWithValue("@FileType","");
        cmd.Parameters.AddWithValue("@FileBytes", imageBytes);
        cmd.Parameters.AddWithValue("@DescFileName", FileUpload2.PostedFile.FileName);
        cmd.Parameters.AddWithValue("@DescFileType","");
        cmd.Parameters.AddWithValue("@DescFileBytes", DescImageBytes);
 
        conn.Open();
        int id = Convert.ToInt32(cmd.ExecuteScalar());
        conn.Close();
 
    }

Open in new window

0
 
askaspAuthor Commented:
I will give a try. Thank you.

Would putting those if statements be a problem there before executing the sql? Cause I am still not sure if I am checking correctly for the fileupload controls if each is null or not?
0
 
wht1986Commented:
i usually check for the filename != "" and content.length > 0
0
 
askaspAuthor Commented:
I tried
select LEN(FileBytes), LEN(DescFileBytes) from ClassDef and here is what I found.
I think there are couple issues going on here, one is If they are both word documents (different) then
query result = same length
But If one is .pdf and the other one is .doc
query result = different length
which make me think I have another issue there with either my filehandler or gridview because I am opening the same word document instead of the pdf. But .pdf is in place in the database.

Not sure where to start from though. I will be waiting for your feedback and will try your code seperately and start building up on top of that.

I appreciate your time on this.
0
 
askaspAuthor Commented:
Just wanted to update. Ok so this query worked, I tried to do with your order and structure and now it is inserting the files to the database correctly with different lengths. Now I am going to display the display part of it.

By the way I think I also got confused with the length of the files because if they are both word document with a little text inside. I guess their length is still same even though text is different inside them.
    protected void btn_Add_Click(object sender, EventArgs e)
    {             
        SqlConnection conn = new SqlConnection(*****);
        SqlCommand cmd = new SqlCommand("INSERT INTO [Test] ([DescName], [DescBytes], [DescType], [SylName], [SylBytes], [SylType]) VALUES (@DescName, @DescBytes, @DescType, @SylName, @SylBytes, @SylType); SELECT SCOPE_IDENTITY();", conn);
 
        if (DescFileUpload.PostedFile == null || string.IsNullOrEmpty(DescFileUpload.PostedFile.FileName) || DescFileUpload.PostedFile.InputStream == null)
        {
            cmd.Parameters.Add("@DescName", SqlDbType.NVarChar).Value = DBNull.Value;
            cmd.Parameters.Add("@DescBytes", SqlDbType.VarBinary).Value = DBNull.Value;
            cmd.Parameters.Add("@DescType", SqlDbType.VarChar).Value = DBNull.Value;
        }
        else
        {
            string DescExtension = Path.GetExtension(DescFileUpload.PostedFile.FileName).ToLower();
            string DescFileType = null;
 
            switch (DescExtension)
            {
                case ".doc":
                    DescFileType = "document/doc";
                    break;
                case ".pdf":
                    DescFileType = "document/pdf";
                    break;
 
                default:
                    return;
            }
 
            cmd.Parameters.AddWithValue("@DescName", txtDescName.Text.Trim());
            cmd.Parameters.AddWithValue("@DescType", DescFileType);
 
            byte[] DescImageBytes = new byte[DescFileUpload.PostedFile.InputStream.Length + 1];
            DescFileUpload.PostedFile.InputStream.Read(DescImageBytes, 0, DescImageBytes.Length);
 
            cmd.Parameters.AddWithValue("@DescBytes", DescImageBytes);
        }
 
 
        if (SylFileUpload.PostedFile == null || string.IsNullOrEmpty(SylFileUpload.PostedFile.FileName) || SylFileUpload.PostedFile.InputStream == null)
        {
            cmd.Parameters.Add("@SylName", SqlDbType.NVarChar).Value = DBNull.Value;
            cmd.Parameters.Add("@SylType", SqlDbType.VarChar).Value = DBNull.Value;
            cmd.Parameters.Add("@SylBytes", SqlDbType.VarBinary).Value = DBNull.Value;
        }
        else
        {
            string extension = Path.GetExtension(SylFileUpload.PostedFile.FileName).ToLower();
            string FileType = null;
 
            switch (extension)
            {
                case ".doc":
                    FileType = "document/doc";
                    break;
                case ".pdf":
                    FileType = "document/pdf";
                    break;
 
                default:
                    return;
            }
 
            cmd.Parameters.AddWithValue("@SylName", txtSylName.Text.Trim());
            cmd.Parameters.AddWithValue("@SylType", FileType);
 
            byte[] imageBytes = new byte[SylFileUpload.PostedFile.InputStream.Length + 1];
            SylFileUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
 
            cmd.Parameters.AddWithValue("@SylBytes", imageBytes);
 
        }
        
        conn.Open();
        int TestID = Convert.ToInt32(cmd.ExecuteScalar());
        conn.Close();
 
        TextBox1.Text = TestID.ToString();
    }

Open in new window

0
 
wht1986Commented:
i think the problem is in the gridview and the fact that the filesizes are identical are because someone either selected the same size file or perhaps its old data from when things werent working right.  The following code follows your logic, and the data inserts correctly.  if you want, post the markup of your gridview.
CREATE TABLE [dbo].[ClassDef](
	[ClassDefId] [int] IDENTITY(1,1) NOT NULL,
	[FileName] [nvarchar](200) NULL,
	[FileType] [varchar](50) NULL,
	[FileBytes] [varbinary](max) NULL,
	[DescFileName] [nvarchar](200) NULL,
	[DescFileType] [varchar](50) NULL,
	[DescFileBytes] [varbinary](max) NULL,
 CONSTRAINT [PK_ClassDef] PRIMARY KEY CLUSTERED 
(
	[ClassDefId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
 
 
==================================
 
protected void Button1_Click(object sender, EventArgs e)
{
 
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ExpertExchangeConnectionString"].ConnectionString))
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO [ClassDef] ([FileName], [FileType], [FileBytes], [DescFileName], [DescFileType], [DescFileBytes]) VALUES (@FileName, @FileType, @FileBytes, @DescFileName, @DescFileType, @DescFileBytes); SELECT SCOPE_IDENTITY();", conn);
        cmd.Parameters.Add("@FileName", SqlDbType.NVarChar, 200);
        cmd.Parameters.Add("@FileType", SqlDbType.VarChar, 50);
        cmd.Parameters.Add("@FileBytes", SqlDbType.VarBinary, -1);
        cmd.Parameters.Add("@DescFileName", SqlDbType.NVarChar, 200);
        cmd.Parameters.Add("@DescFileType", SqlDbType.VarChar, 50);
        cmd.Parameters.Add("@DescFileBytes",SqlDbType.VarBinary, -1);
 
        if ((this.FileUpload1.PostedFile.ContentLength == 0) || string.IsNullOrEmpty(this.FileUpload1.FileName))
        {
            cmd.Parameters["@FileName"].Value = DBNull.Value;
            cmd.Parameters["@FileType"].Value = DBNull.Value;
            cmd.Parameters["@FileBytes"].Value = DBNull.Value;
        }
        else
        {
            byte[] imageBytes = new byte[FileUpload1.PostedFile.InputStream.Length + 1];
            FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
 
            cmd.Parameters["@FileName"].Value = this.FileUpload1.FileName;
            cmd.Parameters["@FileType"].Value = "";
            cmd.Parameters["@FileBytes"].Value = imageBytes;
        }
 
        if ((this.FileUpload2.PostedFile.ContentLength == 0) || string.IsNullOrEmpty(this.FileUpload2.FileName))
        {
            cmd.Parameters["@DescFileName"].Value = DBNull.Value;
            cmd.Parameters["@DescFileType"].Value = DBNull.Value;
            cmd.Parameters["@DescFileBytes"].Value = DBNull.Value;
        }
        else
        {
            byte[] DescImageBytes = new byte[FileUpload2.PostedFile.InputStream.Length + 1];
            FileUpload2.PostedFile.InputStream.Read(DescImageBytes, 0, DescImageBytes.Length);
            cmd.Parameters["@DescFileName"].Value = this.FileUpload2.FileName;
            cmd.Parameters["@DescFileType"].Value = "";
            cmd.Parameters["@DescFileBytes"].Value = DescImageBytes;
        }
 
 
        conn.Open();
        int id = Convert.ToInt32(cmd.ExecuteScalar());
        conn.Close();
    }
}

Open in new window

0
 
wht1986Commented:
Heh posting at same time :)  Ok post the gridview markup if you need help debugging that part of it.
0
 
askaspAuthor Commented:
I am glad to see you here :)
So I think now I am sure that it is not the gridview either but it is my Filehandler, which I wasn't really sure about it's structure at all. I will post the code for both gridview and the way I am handling the files.

Filehandler might look ugly, so bare with me  - never did before hehe:) Wasn't sure how to check two different document types for two different fields in the same table.

So, basic gridview with DescBytes and SylBytes as template fields with a hyperlink inside them which is "text bound to DescName" and "SylName" respectively.  The navigate url takes it to my Handler.ashx
---Gridview---
 
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="TestID" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="TestID" HeaderText="TestID" InsertVisible="False" 
                ReadOnly="True" SortExpression="TestID" />
            <asp:BoundField DataField="DescName" HeaderText="DescName" 
                SortExpression="DescName" />
            <asp:TemplateField HeaderText="DescBytes" SortExpression="DescBytes">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("DescBytes") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" 
                        NavigateUrl='<%# Eval("TestID", "~/Handler.ashx?id={0}") %>' 
                        Text='<%# Bind("DescName") %>'></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="DescLength" HeaderText="DescLength" ReadOnly="True" 
                SortExpression="DescLength" />
            <asp:BoundField DataField="DescType" HeaderText="DescType" 
                SortExpression="DescType" />
            <asp:BoundField DataField="SylName" HeaderText="SylName" 
                SortExpression="SylName" />
            <asp:TemplateField HeaderText="SylBytes" SortExpression="SylBytes">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("SylBytes") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink2" runat="server" 
                        NavigateUrl='<%# Eval("TestID", "~/Handler.ashx?id={0}") %>' 
                        Text='<%# Bind("SylName") %>'></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="SylLength" HeaderText="SylLength" ReadOnly="True" 
                SortExpression="SylLength" />
            <asp:BoundField DataField="SylType" HeaderText="SylType" 
                SortExpression="SylType" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:facultydevConnectionString %>" 
        SelectCommand="SELECT TestID, DescName, DescBytes, LEN(DescBytes) AS DescLength, DescType, SylName, SylBytes, LEN(SylBytes) AS SylLength, SylType FROM Test">
    </asp:SqlDataSource>
 
 
-----File Handler ----
 
<%@ WebHandler Language="C#" Class="FileHandler" %>
 
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
 
public class FileHandler : IHttpHandler {
 
    const string conString = "****";
    
    public void ProcessRequest (HttpContext context) 
    {
        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand("SELECT DescName,DescBytes,DescType,SylName,SylBytes,SylType FROM Test WHERE TestID=@TestID", con);
        cmd.Parameters.AddWithValue("@TestID", context.Request["Id"]);
        using (con)
        {
            con.Open();
            SqlDataReader rdr = null;
            rdr = cmd.ExecuteReader();
            while (rdr.Read())  
            {
                try
                {
                    if (rdr["DescType"].ToString() == "document/pdf")
                    {
                        context.Response.ContentType = rdr["DescType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["DescName"].ToString() + ".pdf"));
                        byte[] file = (byte[])rdr["DescBytes"];
                        context.Response.BinaryWrite(file);
                    }
 
                    if (rdr["DescType"].ToString() == "document/doc")
                    {
                        context.Response.ContentType = rdr["DescType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["DescName"].ToString() + ".doc"));
                        byte[] file = (byte[])rdr["DescBytes"];
                        context.Response.BinaryWrite(file);
                    }
                    if (rdr["SylType"].ToString() == "document/pdf")
                    {
                        context.Response.ContentType = rdr["SylType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["SylName"].ToString() + ".pdf"));
                        byte[] file = (byte[])rdr["SylBytes"];
                        context.Response.BinaryWrite(file);
                    }
 
                    if (rdr["SylType"].ToString() == "document/doc")
                    {
                        context.Response.ContentType = rdr["SylType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["SylName"].ToString()+".doc"));
                        byte[] file = (byte[])rdr["SylBytes"];
                        context.Response.BinaryWrite(file);
                    }
                }
                catch(Exception)
                {
                   context.Response.Write("File can not be found");
                }                   
            }
        }
    } 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Open in new window

0
 
wht1986Commented:
Well at first glance i see the hyperlink for the DescBytes column is
    <%# Eval("TestID", "~/Handler.ashx?id={0}") %>
and the hyperlink for the SylBytes column is
    <%# Eval("TestID", "~/Handler.ashx?id={0}") %>

They are the same so your handler has to figure out which file to return based on the DescType of SylType fields.  Problem I see is based on your previous code, it is possible to upload 2 files at same time, but the way your if statements work (not using if else statmenets) as long as the SylType is filled in you will be returning that.  Might I suggest changing your hyperlinks to:

    <%# Eval("TestID", "~/Handler.ashx?id={0}&type=1") %>
and
    <%# Eval("TestID", "~/Handler.ashx?id={0}&type=2") %>

then in your Filehandler, look at the query string and return the DescBytes if type=1 or the SylBytes if type=2
0
 
askaspAuthor Commented:
Yeah that makes perfect sense. But I am not sure how I will define that type=1 versus type=2 in the query in my Handler?

And the reason I didnt do any if - if else's is because I tried to get every scenerio evaluated to get null values to the DB if that's the case.
0
 
wht1986Commented:
in the handler you can use

int filetype = int.Parse(QueryString["type"]);

if (filetype == 1)
{
  // use DescBytes
}
else
{
  // use SylBytes
}
0
 
askaspAuthor Commented:
Hmm..still not sure where to plug that into? So will that "querystring" is my sql command or do i need to somehow pass that type to my  @TestID parameter and keep the sql command same for both cases?

Or is that something to do with "context.Request["Id"] " this part?

>>Confused :P


<%@ WebHandler Language="C#" Class="FileHandler" %>
 
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
 
public class FileHandler : IHttpHandler {
 
    const string conString = "****";
    
    public void ProcessRequest (HttpContext context) 
    {
        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand("SELECT DescName,DescBytes,DescType,SylName,SylBytes,SylType FROM Test WHERE TestID=@TestID", con);
        cmd.Parameters.AddWithValue("@TestID", context.Request["Id"]);
        using (con)
        {
            con.Open();
            SqlDataReader rdr = null;
            rdr = cmd.ExecuteReader();
            while (rdr.Read())  
            {
                try
                {
                    if (rdr["DescType"].ToString() == "document/pdf")
                    {
                        context.Response.ContentType = rdr["DescType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["DescName"].ToString() + ".pdf"));
                        byte[] file = (byte[])rdr["DescBytes"];
                        context.Response.BinaryWrite(file);
                    }
 
                    if (rdr["DescType"].ToString() == "document/doc")
                    {
                        context.Response.ContentType = rdr["DescType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["DescName"].ToString() + ".doc"));
                        byte[] file = (byte[])rdr["DescBytes"];
                        context.Response.BinaryWrite(file);
                    }
                    if (rdr["SylType"].ToString() == "document/pdf")
                    {
                        context.Response.ContentType = rdr["SylType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["SylName"].ToString() + ".pdf"));
                        byte[] file = (byte[])rdr["SylBytes"];
                        context.Response.BinaryWrite(file);
                    }
 
                    if (rdr["SylType"].ToString() == "document/doc")
                    {
                        context.Response.ContentType = rdr["SylType"].ToString();
                        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["SylName"].ToString()+".doc"));
                        byte[] file = (byte[])rdr["SylBytes"];
                        context.Response.BinaryWrite(file);
                    }
                }
                catch(Exception)
                {
                   context.Response.Write("File can not be found");
                }                   
            }
        }
    } 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Open in new window

0
 
wht1986Commented:
<%# Eval("TestID", "~/Handler.ashx?id={0}&type=1") %>
 will pass (2) items in the query string, after the bind it would look something like
<a href="~/Handler.ashx?id=7&type=1>My File Name</a>

in your handler code you are already getting the id from the querystring via
    context.Request["Id"]);
do the same thing with the type
    context.Request["type"]);

simpliest thing i can think of the is alter the sql statement to return what you want like below

(Might be some syntax errors, i cant check atm, but the logic should basically be correct)

string CommandText = "";
 
if (context.Request["type"] == "1")
  CommandText = SELECT DescName as FileName, DescBytes as FileBytes, DescType as FileType FROM Test WHERE TestID=@TestID
else
  CommandText = SELECT SylName  as FileName, SylBytes  as FileBytes, SylType  as FileType FROM Test WHERE TestID=@TestID
  
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(CommandText, con);
cmd.Parameters.AddWithValue("@TestID", context.Request["Id"]);
 
using (con)
{
  con.Open();
  SqlDataReader rdr = cmd.ExecuteReader();
  while (rdr.Read())  
  {
    string fileType = rdr["FileType"].ToString();
    context.Response.ContentType = fileType;       
    
    // im assuming only pdf and doc files, you can add extra validation checks here
    if (fileType.Equals("document/pdf")
        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["FileName"].ToString() + ".pdf"));
    else
        context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["FileName"].ToString() + ".doc"));
    
    byte[] file = (byte[])rdr["DescBytes"];
    context.Response.BinaryWrite(file);
    break;
  }
  rdr.Close();
  con.Close();
}

Open in new window

0
 
wht1986Commented:
sorry change the
byte[] file = (byte[])rdr["DescBytes"];
to
byte[] file = (byte[])rdr["FileBytes"];
0
 
askaspAuthor Commented:
Yeah that worked smootly thank you very much. Back to my original code, so below is my final code  and there is one more thing i want to ask. So with somefiles their byte values are NULL in the database but still showing a link in the gridview. So I tried adding (as u can refer to the code below)
if (fileType.Equals("document/pdf"))
...
else if (fileType.Equals("document/doc"))
....
else
context.Response.Write("File can not be found");

so that when user clicks they can get "File can not be found" message, however below is what I am getting for that null values

The XML page cannot be displayed
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
--------------------------------------------------------------------------------
Invalid at the top level of the document. Error processing resource 'http://localhost:.....
File can not be found
^

-- instead of just simple "File not found" text.....Any suggestions?
 

<%@ WebHandler Language="C#" Class="FileHandler" %>
 
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
 
public class FileHandler : IHttpHandler {
 
    const string conString = "****"
    
    public void ProcessRequest (HttpContext context) 
    {
        string CommandText = "";
 
        if (context.Request["type"] == "1")
        {
            CommandText = "SELECT ClassDefDescName as FileName, ClassDefDescBytes as FileBytes, ClassDefDescType as FileType FROM ClassDef WHERE ClassDefId=@ClassDefId";
        }
        else 
        {
            CommandText = "SELECT ClassDefSylName  as FileName, ClassDefSylBytes  as FileBytes, ClassDefSylType  as FileType FROM ClassDef WHERE ClassDefId=@ClassDefId";
        }
        
        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand(CommandText, con);
        cmd.Parameters.AddWithValue("@ClassDefId", context.Request["Id"]);
        
        
        using (con)
        {
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())              
            {
                string fileType = rdr["FileType"].ToString();
                context.Response.ContentType = fileType;
 
                // im assuming only pdf and doc files, you can add extra validation checks here
                if (fileType.Equals("document/pdf"))
                {
                   context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["FileName"].ToString() + ".pdf"));
                   byte[] file = (byte[])rdr["FileBytes"];
                   context.Response.BinaryWrite(file);
                   break;
                }
                else if (fileType.Equals("document/doc"))
                {
                   context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0};", rdr["FileName"].ToString() + ".doc"));
                   byte[] file = (byte[])rdr["FileBytes"];
                   context.Response.BinaryWrite(file);
                   break;                    
                }
                else
                {
                    context.Response.Write("File can not be found");
                }
            }
            rdr.Close();
            con.Close();
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Open in new window

0
 
wht1986Commented:
I would change the select for the grid view to

SELECT TestID,
DescName, isnull(DescBytes) as DescExists, DescType,
SylName, isnull(SylBytes) as SylBytesExists, SylType FROM Test

Then add to the visibility of the hyperlink the exist column return

<asp:HyperLink ID="HyperLink2" runat="server"
                        NavigateUrl='<%# Eval("TestID", "~/Handler.ashx?id={0}") %>'
                        Text='<%# Bind("SylName") %>'
                        Visibil='<%# Eval("SylBytesExists") %>'
></asp:HyperLink>
               
0
 
askaspAuthor Commented:
Then i get the error
--The isnull function requires 2 argument(s).
0
 
wht1986Commented:
sorry i was posting from my iphone while in a meeting and couldnt think as well as i should of. Basically i was trying to show 2 things. (1) no sense in returning the data for the grid bind as its just extra overhead and (2) you can hide the links for anything that doesnt have data.  I think the below code should work for you.
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="TestID" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="TestID" HeaderText="TestID" InsertVisible="False" ReadOnly="True" SortExpression="TestID" />
            <asp:TemplateField HeaderText="DescBytes" SortExpression="DescBytes">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("TestID", "~/Handler.ashx?id={0}&type=1") %>'
                        Text='<%# Eval("DescName") %>' Visible='<%# Eval("DescExists") %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="SylBytes" SortExpression="SylBytes">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# Eval("TestID", "~/Handler.ashx?id={0}&type=2") %>'
                        Text='<%# Eval("SylName") %>' Visible='<%# Eval("SylExists") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Expert ExchangeConnectionString %>"
        SelectCommand="Select TestID,  DescName, convert(bit, case when DescBytes is null then 0 else 1 end) AS DescExists, 
                       LEN(DescBytes) as DescLength, DescType, SylName,  convert(bit, case when SylBytes is null then 0 else 1 end) AS SylExists, 
                       LEN(SylBytes) AS SylLength, SylType 
                       FROM Test" />

Open in new window

0
 
askaspAuthor Commented:
Well in my structure my gridview field is linked not to Byte field but to Name field in my database. And once it is clicked it passes to my Filehandler then the filehandler pulls the information from my Byte field.
So there was a problem with my insert/update fuction sometimes apparently it was inserting for example the "Description Name" but not the "Description Byte" which was causing the link to show up but with NULL value in my Byte field.
I decided to change that update/insert function so that it also inserts NULL values for the Name fields when filestream is null. And now gridview won't show the links cause the Name fields are also Null which solved the problem. (if all these made sense:) , I am new and trying to learn with practice)

And thank you very much you have been very very helpful.

0
 
askaspAuthor Commented:
Been very accurate and helpful. Thank you.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 12
  • 12
Tackle projects and never again get stuck behind a technical roadblock.
Join Now