Sunday, February 26, 2012

Getting image from DB error?

Unsure why I am getting such an error when the image is there and thesearch feature for the site is not working so that doesn't help so I'mhoping some out there can offer why I maybe getting this and help mewith getting the image from the DB.

I use the code from the starter app for retrieving an image from the DB and I get the error message:
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'

Here is the code and I am getting the error on the red line (Return New MemoryStream(CType(result, Byte()))):

Public Overloads Function GetPhoto(ByVal UserName As String) As Stream
command.CommandText = "sp_Themes_GetUserThemeImage"
command.Parameters.Add("@.UserName", SqlDbType.VarChar, 50)
command.Parameters(0).Value = UserName

Dim result As Object = command.ExecuteScalar
Try
If result Is Nothing Then
Dim path As String =HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings("siteImageDirectory"))
path = (path + "noimageav.gif")

Return New FileStream(path, FileMode.Open, FileAccess.Read,FileShare.Read)
Else
Return New MemoryStream(CType(result, Byte()))
End If
Catch e As ArgumentNullException
Return Nothing
End Try
End Function

--this is the code from the imagehandler.ashx page--
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

Dim userName As String
Dim stream As IO.Stream = Nothing
If ((Not (context.Request.QueryString("UserName")) Is Nothing) _
AndAlso (context.Request.QueryString("UserName") <> "")) Then
userName = [Convert].ToString(context.Request.QueryString("UserName"))
stream = (New PhotoManager).GetPhoto(userName)

'Get the photo from the database, if nothing is returned, get thedefault "placeholder" photo
'If (stream Is Nothing) Then
' stream = (New PhotoManager).GetDefaultPhoto()
'End If
' Write image stream to the response stream
Dim buffersize As Integer = (1024 * 16)
Dim buffer() As Byte = New Byte((buffersize) - 1) {}
Dim count As Integer = stream.Read(buffer, 0, buffersize)

Do While (count > 0)
context.Response.OutputStream.Write(buffer, 0, count)
count = stream.Read(buffer, 0, buffersize)
Loop
End If
End Sub

--this is how I call it from the image.aspx page--

<img src='imageHandler.ashx?username=<%# Eval("UserName") %>'style="border:2px solid white;height:40px;" alt='Thumbnail.' /
Thanks for all your help.

Big Smile [:D]

The image data is a null, I think. Try doing:

IF result=system.DBNULL.value then
Return nothing
ELSE
Return New MemoryStream(CType(result, Byte()))
ENDIF

|||Well, I changed things which works but still the image will not show up.

I was using the photoManager.vb file which was part of one of the starter apps but I eliminated a step and came up with this:

If ((Not (context.Request.QueryString("UserName")) Is Nothing) _
AndAlso (context.Request.QueryString("UserName") <> "")) Then
userName = [Convert].ToString(context.Request.QueryString("UserName"))
Dim connection As SqlConnection
Dim command As SqlCommand
Dim reader As SqlDataReader

connection = NewSqlConnection(ConfigurationManager.ConnectionStrings("owcConnectionString").ConnectionString)
command = New SqlCommand
command.Connection = connection
command.CommandType = CommandType.StoredProcedure
connection.Open()

'get image from db
command.CommandText = "sp_Themes_GetUserThemeImage"
command.Parameters.Add("@.UserName", SqlDbType.VarChar, 50)
command.Parameters(0).Value = userName

Try
reader = command.ExecuteReader(CommandBehavior.CloseConnection)
Do While (reader.Read)
If IsDBNull(reader.GetValue(0)) Then
Dim path As String =HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings("siteImageDirectory"))
path += "noimageav.gif"
stream = New FileStream(path, FileMode.Open, FileAccess.Read,FileShare.Read)
Dim buffersize As Integer = (1024 * 16)
Dim buffer() As Byte = New Byte((buffersize) - 1) {}
Dim count As Integer = stream.Read(buffer, 0, buffersize)
context.Response.OutputStream.Write(buffer, 0, count)
Exit Do
Else
context.Response.ContentType = reader.Item(1).ToString
context.Response.BinaryWrite(reader.Item(0))
End If
Loop
Catch e As Exception
context.Response.Write(e)
Finally
command.Dispose()
connection.Dispose()
End Try
End If

Which works just fine except that I am still not getting the image fromthe DB to show up. I don't get any error messages or anything andwhen I debug and walk through, it walks through just fine but no imagefrom the DB.

Can anyone offer some help on this?

thanks|||

You don't need to/shouldn't be looping (Do While reader.read), since you can't output multiple images that way -- Change it to "If reader.read then ...". You aren't supplying a contenttype if your image is null. If your noimageav.gif is larger than 16k, you'll truncate it. I would also issue a response.clear before you set the contenttype, and response.end after you finish writing.

Personally, I would probably just issue a response.redirect instead of opening the file, reading it and dumping it in the case that you don't have an image, but that's me.

|||Point well taken but I'm only outputting a single image and onlyretrieving a single image so no concerns about multiple images. Also, if the image in the DB is null, it then retrieves thenoimageav.gif which never changes in size and it also isn't in the DBso it is not the problem. The problem is the is the image that isstored in the DB is not showing up.

When it hits these 2 lines of code, I would expect it to return the image but it doesn't. Just shows blank.

context.Response.ContentType = reader.Item(1).ToString
context.Response.BinaryWrite(reader.Item(0))

Even though there is data. Verified this when debugged.

Any other ideas?

thanks
|||

Grab fiddler (www.fiddler.com), and with that you can see exactly what the server is sending back to you.

Like I said, i would reponse.clear before, and response.end around those 2 lines of code just to make sure the headers are getting cleared out, and not getting clobbered after.

Make sure that you close the browser you are trying to pull the image with regularly because IE seems to cache the contenttype of a page, and it's rather hard to get it to change to the new type sometimes.

|||That link doesn't have anything on it related to what you mentioned.

I did do a response.clear and response.end in my latest code but still the same thing.

So far, I've tried about 3 different ways for displaying an image froma DB. 1st from a book, second from the starter app and 3rd froman online source and none of them worked. At 1st I was thinkingthat the data but that doesn't seem to be the case.

Right now, I've come to a complete and total stand still in trying to solve this.

Any ideas out there about what it may be?

thanks

No comments:

Post a Comment