views:

416

answers:

3

I have done this previously but in a different way. I am trying to get the code below to work. If I do not cast 'OriginalPhoto' or 'Thumbnail' an error occurs. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. I don't understand why it asking to cast. However if I do cast it, the images add to the database just fine in a binary data format. When trying to view the images, i get the error 'Unable to display the given data'. I have inserted both byte[] into a table using a SqlDataAdapter and that works. I want to use this method though, what am I doing wrong?

PROFILEGALLERY TABLE CONTAINS:

UserId nvarchar(50)
Title nvarchar(10)
OriginalImage varbinary(max)
ThumbImage varbinary(max)

protected void AddPhotoToDatabase()
{
    byte[] OriginalPhoto = GetImage();
    byte[] Thumbnail = GenerateThumbnail();
    string Title = FileUpload1.FileName.ToString();
    string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))";
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
    SqlConnection conn = new SqlConnection(strCon);
    SqlCommand comm = new SqlCommand(sql, conn);
    conn.Open();
    comm.ExecuteNonQuery();
    conn.Close();
}

protected byte[] GetImage()
{
    byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
    FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length);
    return photo;
}

protected byte[] GenerateThumbnail()
{
    System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
    double thumbwidth = 0;
    double thumbheight = 0;
    double imgsz = 150.0;
    if (imgsz / image.Width < imgsz / image.Height)
    {
        thumbwidth = image.Width * (imgsz / image.Width);
        thumbheight = image.Height * (imgsz / image.Width);
    }
    else
    {
        thumbwidth = image.Width * (imgsz / image.Height);
        thumbheight = image.Height * (imgsz / image.Height);
    }
    System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0);
    MemoryStream ms = new MemoryStream();
    thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    return ms.ToArray();
}
+3  A: 

You should use sql parameters:

using( SqlConnection cnn = GetConnection() ) {
    using( SqlCommand cmd = cnn.CreateCommand() ) {
        cmd.CommandText = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES (@UserId, @Title, @OriginalPhoto, @Thumbnail)";
        cmd.Parameters.AddWithValue( "@UserId", User.Identity.Name );
        cmd.Parameters.AddWithValue( "@Title", Title );
        cmd.Parameters.AddWithValue( "@OriginalPhoto", OriginalPhoto );
        cmd.Parameters.AddWithValue( "@Thumbnail", Thumbnail );

        cnn.Open();
        cmd.ExecuteNonQuery();
        cnn.Close();
    }
}
TcKs
THANK YOU! YOU ARE AWESOME...wow that was a headache. I don't even care why my way didn't work. Now I know why everyone does it this way. THANK YOU!
+1  A: 

Don't try to build the data into the insert query. Try this:

string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage],
              [ThumbImage]) VALUES (@userId, @title, @originalImage, @thumbImage)";


string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;

SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);

comm.Parameters.Add(new SqlParameter("@userId", User.Identity.Name));
comm.Parameters.Add(new SqlParameter("@title", Title));
comm.Parameters.Add(new SqlParameter("@originalImage", OriginalPhoto));
comm.Parameters.Add(new SqlParameter("@thumbImage", Thumbnail));
Justin Niessner
+1  A: 

Just looking at your code, I'm a little concerned that you are wide open for a SQL Injection attack. To help mitigate this should also fix your problem. You need to use a parametized query. Something like

cmd.CommandText="Insert into [ProfileGallery]" +
                "(UserId,OriginalPhoto) values (@UserId,@OriginalPhoto)";
cmd.Parameters.AddWithValue("UserId",User.Identity.Name);
cmd.Parameters.AddWithValue("OriginalPhoto",OriginalPhoto);

The reason your code is failing can be seen with this sample application:

static void Main(string[] args)
{
    byte[] byteArray = new byte[] { 1, 2, 0 };
    Console.WriteLine("This is my byte array: " + byteArray);
    Console.ReadLine();
}

This outputs This is my byte array: System.Byte[]

I'm a little shocked that you can add a byte array to a string, especially sicne it just gives us the name of the type.

JoshBerke
lol, very true. Thank you!