views:

1242

answers:

2

I am trying to return a binary from the DB using linq for display in the browser. The method below using ado.net works but I am trying to ypgrade to linq but the linq version returned the error.

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) 
    Dim imageId As String = context.Request.QueryString("id")
    Dim ret As DataTable = Nothing
    ret = DPGetImageData.GetImageById(Convert.ToInt64(imageId))

        For Each dt As DataRow In ret.Rows
            For Each c As DataColumn In ret.Columns
                If Not (dt(c) Is Nothing) Then
                    context.Response.Clear()
                    context.Response.BufferOutput = False
                    context.Response.OutputStream.Write(CType(dt.Table.Rows(0).Item("imageData"), Byte()), 0, CInt(dt.Table.Rows(0).Item("imageSize")))
                    context.Response.End()
                End If

            Next
        Next


End Sub

Working Linq Version:

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    If Not String.IsNullOrEmpty(Current.Request.QueryString("Id")) Then
        Dim imageId = HttpContext.Current.Request.QueryString("Id")
        Dim result = repository.FindById(Convert.ToInt64(imageId)).imageData.ToArray
        HttpContext.Current.Response.BinaryWrite(result)
        context.Response.End()

    End If
End Sub
A: 

You should not need the cast as Binary.ToArray, returns a byte array already.

An alternative is to use a byte array directly. You can modify it in the designer.

UPDATE:

I am not fully sure, but it could be that your DataContext has been disposed already. I think the Binary type uses deferred loading.

If you add a stacktrace, we could see if that is the case.

leppie
I was getting a nullReference all the time because the data was not in the model. I just don't know how preferment it will be with large files. I hope someone will speak to that. I also found this article http://tinyurl.com/ck39un/ It fills in more of the blanks for me.
ruffone
+1  A: 

You should be able to just call Response.BinaryWrite(result.ToArray()). Notice the parantheses, ToArray is a method call.

Simon Svensson
Good catch, I dont know VB though :)
leppie