Converting Sql.LINQ.Binary to Byte()

Just a real short entry today.  I had some trouble with this one - took me a little bit to figure out so I figured I would post a quick note about it.  Mostly to remind myself how I did it next time I need to. 

I'm working in a starterkit that I'm designing.  It's not ready for general public publicity yet - but I can tell you that I have a database storing images, and typically in .net 2.0 I'd create an imagehandler.ashx for this and just use the querystring to parse out and grab the binary using a Datareader.

 

It'd typically look like this: (hijacked from http://www.123aspx.com/redir.aspx?res=36098)

public class ImageHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        string imageid = context.Request.QueryString["ImID"];
        SqlConnection connection = new SqlConnection
        (ConfigurationManager.ConnectionStrings
        ["connectionString"].ConnectionString);
        connection.Open();
        SqlCommand command = new 
        SqlCommand("select Image from Image where ImageID="+imageid, connection);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        connection.Close();
        context.Response.End();              
        
    }

I however am in a LINQ .net 3.5 project, and I didn't want to use SQL commands and data readers, I wanted to do it the new fan dangled way. 

It turns out that it's not straightforward to grab an SQL.Linq.Binary field and convert it to a byte array.  It's not hard mind you, but there really isn't any clue on how to make it work.  So I fiddled around with it and here's what I came up with.

Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        If Not String.IsNullOrEmpty(HttpContext.Current.Request.QueryString("imageID")) Then
            Dim imageID = HttpContext.Current.Request.QueryString("imageID")
            Dim db As New AuctionsDataContext
            Dim result = From img In db.Images _
                         Where img.imageID = imageID _
                         Select img.image


            HttpContext.Current.Response.BinaryWrite(CType(result.First.ToArray, Byte()))
            context.Response.End()
        End If
    End Sub

 

The key line being the BinaryWrite portion towards the bottom.  result.first.toArray didnt make a lot of sense to me, but it seems to work, and pretty quickly. :) 

Good luck!

No Comments