Avatar of dzumwalt
dzumwalt

asked on 

How To Display BLOB Images in a gridview using asp.net VB code

Hi All.

I have seen in EE how to show BLOB images that are stored in the database. The solution showed a c# approach, however I am using asp.net with VB code behind. I tried to convert the c# to vb with no success.

Can anybody give me an example of how to do this?
ASP.NETVisual Basic.NET

Avatar of undefined
Last Comment
dzumwalt
Avatar of prairiedog
prairiedog
Flag of United States of America image

Do you have the C# version? I might be able to help you convert it to VB.
Avatar of dzumwalt
dzumwalt

ASKER

Sorry for the delay in responding.....

I am having trouble finding the example code that I originally worked from. Here is the code as it stands now.

First ... there one file called Try2_ImageShow.aspx. It is as follows:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Try2_ImageShow.aspx.vb" Inherits="Try2_ImageShow" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       
        <img alt="My Picture" src="Try2_ImageSupplier.aspx"/>&nbsp;
       
    </div>
    </form>
</body>
</html>


Then there is a second file called Try2_ImageSupplier.aspx. It is as follows:

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Data.SqlClient
Imports ODBCTool


Partial Class Try2_ImageSupplier
    Inherits System.Web.UI.Page

    Dim m_dsPhotos As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim Conn As Odbc.OdbcConnection
        Dim da As Odbc.OdbcDataAdapter
        Dim drows As DataRow()
        Dim bytes() As Byte


        Conn = New Odbc.OdbcConnection("DSN=AuctionRPM")
        da = New Odbc.OdbcDataAdapter()
        da.SelectCommand = New Odbc.OdbcCommand("SELECT * FROM InventoryPictures;")
        da.SelectCommand.Connection = Conn
        da.Fill(m_dsPhotos)

        drows = m_dsPhotos.Tables(0).Select("InventoryItemUniqueID=3")
        bytes = drows(0).Item("Picture")

        Response.Expires = 0
        Response.Buffer = True
        Response.Clear()
        Response.ContentType = "image/jpg"
        Response.BinaryWrite(bytes)
        Response.End()

    End Sub

End Class


I have tried both         Response.BinaryWrite(bytes) as well as Response.OutputStream.Write(bytes, 0, bytes.Length) with no luck.

What am I doing wrong?
Avatar of prairiedog
prairiedog
Flag of United States of America image

Does your database store the contenttype or mime type of the image?
Avatar of dzumwalt
dzumwalt

ASKER

At this point I am assuming that it is a JPG and so that is why I am saying

Response.ContentType = "image/jpg"

in the code. Is the content type property more than just a string property that contains the above?
Avatar of prairiedog
prairiedog
Flag of United States of America image

1. Do you see a "red cross" or nothing at all when you run the application?
2. Do you use any authentication?
Avatar of dzumwalt
dzumwalt

ASKER

No red cross. Blank screen. (Actually ... if I use the "alt", I see the text of the "alt").  I'm not sure what you mean by authentication.

Sorry for being such a novice!
Avatar of prairiedog
prairiedog
Flag of United States of America image

Are you using Forms Authentication or Windows Authentication for your application?  In your web.config, there is something like this: <authentication mode="Windows" />.
What happens if you use Image server control, instead of the HTML image tag:
<asp:image id="imgMyPicture" runat="server" ImageUrl="Try2_ImageSupplier.aspx"></asp:image>

Open in new window

Avatar of dzumwalt
dzumwalt

ASKER

Authentication mode is set to Windows.

I tried the new code that you sent. Same result.
Avatar of prairiedog
prairiedog
Flag of United States of America image

Let's try this:
1.Comment out these lines:
Response.Expires = 0
Response.Buffer = True
Response.Clear()

2. Use Image Server control as I mentioned earlier, and make sure the ImageUrl is correct.
3. Set Response.ContentType = "image/jpeg"
4. Use Response.OutputStream.Write

Please report the result. If possible, attach a screen shot.
Avatar of dzumwalt
dzumwalt

ASKER

No change.

I can verify that the bytes.length is over 300k and so I know it is loading the picture into the byte array.

One question I have is you say to use the "image server" control. If by that you mean:

<asp:image AlternateText="Picture" id="imgMyPicture" runat="server" ImageUrl="Try2_ImageSupplier.aspx"></asp:image>

Then good. If not, then I cannot find any control that is called "image server". This one is simply called "image" in the toolbox.

Here is the Image_supplier code as it stands now.

Partial Class Try2_ImageSupplier
    Inherits System.Web.UI.Page

    Dim m_dsPhotos As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim Conn As Odbc.OdbcConnection
        Dim da As Odbc.OdbcDataAdapter
        Dim drows As DataRow()
        Dim bytes() As Byte


        Conn = New Odbc.OdbcConnection("DSN=AuctionRPM")
        da = New Odbc.OdbcDataAdapter()
        da.SelectCommand = New Odbc.OdbcCommand("SELECT * FROM InventoryPictures;")
        da.SelectCommand.Connection = Conn
        da.Fill(m_dsPhotos)

        drows = m_dsPhotos.Tables(0).Select("InventoryItemUniqueID=3")
        bytes = drows(0).Item("Picture")

        'Response.Expires = 0
        'Response.Buffer = True
        'Response.Clear()
        Response.ContentType = "image/jpeg"
        Response.OutputStream.Write(bytes, 0, bytes.Length)
        Response.End()

    End Sub

End Class

The web.config contains the following (among other things):

<authentication mode="Windows"/>



I REALLY appreciate you help!
Avatar of dzumwalt
dzumwalt

ASKER

I don't know if this makes any difference, but my default browser is firefox.
Avatar of prairiedog
prairiedog
Flag of United States of America image

Yes, I meant Image server control, and sorry about the capitalized "Server" caused confusion.
Can you attach a screen shot of your current page after running the application?
Avatar of dzumwalt
dzumwalt

ASKER

Here are three images. One is the browser, and the other two are the code pages.

Again ... thanks!
Snap2.jpg
Snap3.jpg
Snap4.jpg
Avatar of prairiedog
prairiedog
Flag of United States of America image

The code runs ok on my machine. Here is my code and a screen shot (I am using AdventureWorks2000 database). Make sure there is data in your dataset and the selected datarow.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="imgPicture" runat="server" AlternateText="Picture" ImageUrl="~/Draw.aspx" /></div>
    </form>
</body>
</html>
 
'Draw.aspx
Partial Class Draw
    Inherits System.Web.UI.Page
    Dim ds As New DataSet
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
        Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("AdventureWorks2000ConnectionString").ToString())
        Dim sda As New SqlDataAdapter()
        sda.SelectCommand = New SqlCommand("SELECT ThumbNailPhoto, LargePhoto FROM ProductPhoto WHERE (ProductPhotoID = 1)", conn)
 
        sda.Fill(ds)
        Dim dr As DataRow = ds.Tables(0).Rows(0)
        Dim data() As Byte
        data = dr("ThumbNailPhoto")
        Response.ContentType = "image/jpeg"
        Response.OutputStream.Write(data, 0, data.Length)
        Response.End()
 
    End Sub
End Class

Open in new window

2008-07-25-154549.jpg
Avatar of prairiedog
prairiedog
Flag of United States of America image

If you still cannot get the image, then it is likely there is a permission issue on your Sql server. Change your code to the attached code snippet and let me know if you have any exception error.
Try
	da.Fill(m_dsPhotos)
 
	drows = m_dsPhotos.Tables(0).Select("InventoryItemUniqueID=3")
	bytes = drows(0).Item("Picture")
 
	Response.ContentType = "image/jpeg"
	Response.BinaryWrite(bytes)
	Response.End()
Catch ex As Exception
 
End Try

Open in new window

Avatar of dzumwalt
dzumwalt

ASKER

OK. I see a disconnect between us. The data is being stored and read from an Access MDB not SQLServer. I have had to covert the code you sent to me as follows:

        Dim objDBS As New ADODB.Connection
        Dim rst As New ADODB.Recordset

        ' Create a connection to the access database.
        objDBS.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Src_Code\VS2005_Code\WebSites\RPM_Interactive\App_Data\AuctionRPM.mdb;User Id=admin;Password=;")
        rst.Open("SELECT Picture FROM InventoryPictures WHERE (InventoryItemUniqueID = 3)", objDBS)

        Dim data() As Byte
        data = rst("Picture").Value

        Response.ContentType = "image/jpeg"
        Response.OutputStream.Write(data, 0, data.Length)
        Response.End()

Still no luck - by the way. I'm trying to see if this is a forefox vs. IE issue and so I have uninstalled firefox completely. NOW THE IDE KEEPS SAYING THAT IT CAN'T FIND FIREFOX AND I CAN'T SEE WHERE TO CHANGE IT TO IE!! I swear - this must be a Monday.
Avatar of dzumwalt
dzumwalt

ASKER

OK. Figured out how to set the defautl browser for the file. (right click on the file and choose "browse with").

Now that I am using IE, I am now getting an red X.
Avatar of dzumwalt
dzumwalt

ASKER

One final note before I start my weekend,

I have tested this even on the categories table in the Northwind MDB that comes with MSAccess. No joy.
Avatar of prairiedog
prairiedog
Flag of United States of America image

Please refer to my comment  ID: 22092338. Put your code in a Try/Catch block and report here any exception you encountered.

Also, make sure there is data in your returned dataset/datatable.
Avatar of dzumwalt
dzumwalt

ASKER

Finally, we might be getting somewhere.

I placed the try catch in there and there was apparently a problem with the Response.End(). When it branched to the catch (but hadn't yet executed the code in the catch), at that moment the following showed up in the immediate window:

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll

When I attempted to interrogate the EX object, I got the following:

Expression cannot be evaluated at this time.

I placed the following code in the catch section:

Response.Write(ex.Message)

When execiting that line I got the following in the immediate window:

An exception of type 'System.Threading.ThreadAbortException' occurred in App_Web_rrq7y_sz.dll but was not handled in user code

Do you think my mscorlib.dll has been hosed somehow?
Avatar of prairiedog
prairiedog
Flag of United States of America image

First, I am confused. Why did you have to convert your code? Did the code you provided in your question not work?

Secondly, don't worry about "'System.Threading.ThreadAbortException" error. Response.End and Response.Redirect will cause this exception error and this error will not cause any problem to you application.

Thirdly,  can you confirm there is data (in right format) in the row that you just selected.

Avatar of dzumwalt
dzumwalt

ASKER

OK. I think we are real close now.

The image was originally placed in the database by a VB6 application. In that application I am using ADO to read/write the picture data to/from the database.

I notice that rst.Fields("Picture").ActualSize in the vb6 application reports the size of the jpg as 301426 however in that application I am writing the database field to a string variable. When I do, the resultant length of that string is exactly half (150713). Performing a binary write of that string to a disk file creates a good jpg file.

In an effort to prove the third item in your last post, in the asp.net code I took the contents of the database picture field and wrote it to a file. That file turned out to be 301426 bytes in size.  Doing a byte by byte comparison of the original file and this one that I wrote out, I notice that there is a ton of nulls (seems like every other character) in the 301426 sized file.

I guess if I can find a way to convert the data (different bit encoding perhaps?) then that might be the key.
Avatar of prairiedog
prairiedog
Flag of United States of America image

If you store the actual size of the image file when saving it to the database, then try change this line:
Response.OutputStream.Write(data, 0, actualSize) '<===Get the actual size from database
Does it make any difference?
Avatar of dzumwalt
dzumwalt

ASKER

No difference.

Take a look at the screenshot. It is an old dos binary comparison program. The upper half of the screen shows the original file, the lower half shows the file that this program is putting out. The bottom line of the upper half of the screen shows (for instance) that there are the characters "Exif", however there are intervening nulls between those characters in the file on the bottom half of the screen. Isn't there some translation method so that I can get the same result in vb.net as vb6?
Snap5.jpg
ASKER CERTIFIED SOLUTION
Avatar of prairiedog
prairiedog
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of dzumwalt
dzumwalt

ASKER

I will do exactly that. For future readers of this thread, the new question ID is 23601647

prairiedog ... I appreciate you hanging in there with me on this. Even though the issue isn't fully resolved, you have definitely helped me with narrowing down where the problem. I will award the points for this thread to you.

Thanks!
Avatar of prairiedog
prairiedog
Flag of United States of America image

Hi dzumwalt,
You're very welcome. I learned a lot during the whole process.

I hope once you get the answer for your new question (https://www.experts-exchange.com/questions/23601647/How-vb-net-can-read-binary-BLOB-data-from-MSAccess-originally-saved-by-vb6-AppendChunk.html), you can come back to this question to test the code to see if it will work then.
Avatar of prairiedog
prairiedog
Flag of United States of America image

Congrats!
Now, are you able to display the image with the code I provided here?
Avatar of dzumwalt
dzumwalt

ASKER

Yes. The final code is as follows.

Imports System.Data.OleDb
Imports System.IO
Imports System.Xml.Serialization
Imports System.Drawing.Imaging
Imports System.Text


Partial Class Draw

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim dbsMain As New ADODB.Connection
        Dim rst As New ADODB.Recordset
        Dim MyData() As Byte


        ' Create a connection to the database.
        dbsMain.Open("DSN=AuctionRPM")

        ' Fill the recordset with a the sought after data.
        rst.Open("SELECT * FROM InventoryPictures WHERE InventoryItemUniqueID=3;", dbsMain)

        ' Assign the data to a byte var.
        MyData = rst("Picture").Value

        ' Perform tests.
        Response.ContentType = "image/jpeg"
        Response.OutputStream.Write(Encoding.Convert(Encoding.Unicode, Encoding.Default, MyData), 0, Encoding.Convert(Encoding.Unicode, Encoding.Default, MyData).Length)

        ' Close out objects.
        rst.Close()
        dbsMain.Close()

    End Sub

End Class
ASP.NET
ASP.NET

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications

128K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo