Solved

can't show image from a DB in a repeater vb.net

Posted on 2011-09-03
19
513 Views
Last Modified: 2012-06-27
Hi
 
I have a problem showing images from a DB, the images are saved like this from another site.
 
cmd.Parameters.Add("@img_type", OleDbType.VarChar).Value = imageType
cmd.Parameters.Add("img_stream", OleDbType.Binary).Value = imageContent
 
So the images is saved to the access db as Binary data. (that work)
 Now i will show the images in a repeater like
 <img src="face.gif" alt="" /> when looking on the serverside code.
 
but if i make the connection and the repeater and make this
 <img src="<%# Container.DataItem("img_stream")%>" alt="" />
 
the code dont show the image, i have some text from the db and it ok, tha code show the text, but not the image.
 Can someone help me, im new to this..
0
Comment
Question by:tjgrindsted
  • 10
  • 9
19 Comments
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36478342
Hi! Src attribure of img is for Url not file content. So to display from database, first you need to implement a httphandler:
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27233449.html
0
 

Author Comment

by:tjgrindsted
ID: 36478369
Hi Ivan Vagunin
Thx for the feedback, ok sounds right, my problem is that im not info C-sharp, and i can only finde C-sharp handlers, and when trying to convert em to vb.net its not working, can U or somebody link me to a vb.net handler or maybe show me an ex. on a vb.net image handler !?
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36478498
Look following exmaple: http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.processrequest.aspx.

The code should be like following:

Namespace HandlerExample

    Public Class MyHttpHandler
        Implements IHttpHandler

        ' Override the ProcessRequest method.
        Public Sub ProcessRequest(context As HttpContext) _
        Implements IHttpHandler.ProcessRequest
           
            context.Response.Clear
            context.Response.ContentType = "image/jpeg";
            Dim buffer() As Byte = getImageDataFromDB(context.Request.Url)
            context.Response.OutputStream.Write(buffer, 0, buffer.Length)
            context.Response.End        End Sub

        ' Override the IsReusable property.        
        Public ReadOnly Property IsReusable() As Boolean _
        Implements IHttpHandler.IsReusable

            Get
                Return True
            End Get
        End Property
    End Class

Good cs to vb translaor is http://www.carlosag.net/tools/codetranslator/
0
 

Author Comment

by:tjgrindsted
ID: 36480951
have looked at it and im stuck, sry, the ex. is with SQL connection not Access.
If I give u these info, can u then help me !?
I cant get this to work...
<%@ WebHandler Language="VB" Class="ShowImage" %>

Imports System
Imports System.Web
Imports System.Data
Imports System.Data.OleDb
Imports System.IO

Public Class ShowImage 
    Inherits System.Web.UI.Page : Implements IHttpHandler
    
    Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("App_Data/db1.mdb")

    ' Object created for Oledb Connection
    Dim myAccessConnection As New OleDbConnection(connStr)

    Public Sub openAccessConnection()
        ' If condition that can be used to check the access database connection
        ' whether it is already open or not.
        If myAccessConnection.State = ConnectionState.Closed Then
            myAccessConnection.Open()
        End If
    End Sub

    Public Sub closeAccessConnection()
        ' If condition to check the access database connection state
        ' If it is open then close it.
        If myAccessConnection.State = ConnectionState.Open Then
            myAccessConnection.Close()
        End If
    End Sub
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        If context.Request.QueryString("autoId") Is Nothing Then
            Return
        End If
        Dim connStr As String = ConfigurationManager.ConnectionStrings("ConnStr").ToString()
        Dim autoId As String = context.Request.QueryString("autoId")
        myAccessConnection.Open()
        Using cmd As New OleDbCommand("select * from tblImg where img_id=@autoId", myAccessConnection)
            cmd.Parameters.Add(New OleDbParameter("@autoId", autoId))
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                reader.Read()
                context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                reader.Close()
            End Using
        End Using
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Open in new window

0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481060
Hi! So what's the problem with the code? Do you get any error? What is the type img_id? If it is numeric try following:
Using cmd As New OleDbCommand("select * from tblImg where img_id=" + autoId, myAccessConnection)
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                reader.Read()
                context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                reader.Close()
            End Using
        End Using
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481062
I meant What is the type of img_id column in DB?
0
 

Author Comment

by:tjgrindsted
ID: 36481165
Its Autonum and Key

when i run the code then i get this error, se the screencasting.
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481169
Sorry, I don't see any screens
0
 

Author Comment

by:tjgrindsted
ID: 36481170
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481203
I guess you sql request does not return any row, because autoId is considered to be of String type (not numeric). So try this:

Using cmd As New OleDbCommand("select * from tblImg where img_id=@autoId", myAccessConnection)
            Dim paramId As New OleDbParameter("@autoId", OleDbType.Numeric)
            paramId.Value = int.Parse(autoId)
            cmd.Parameters.Add(paramId)
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                If reader.HasRows Then
                    reader.Read()
                    context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                    reader.Close()
                End If
            End Using
        End Using
0
 

Author Comment

by:tjgrindsted
ID: 36481271
If i use that the VS program is saying that there was build error.
The errors are these http://imageshack.us/photo/my-images/847/error2d.jpg/
If i make a simple site SLET.ASPX
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="SLET.aspx.vb" Inherits="SLET" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Image ID="Image1" runat="server" ImageUrl="showImage.ashx?autoId=1"/> 
    </div>
    </form>
</body>
</html>

Open in new window


i then get a red image cross error on server site and "show code" i get this:
<!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><title>

</title></head>
<body>
    <form method="post" action="SLET.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE1MTU2MzE5MDhkZIV95aciKHYdJK92JmReSVo+l5lrlifyfkPQg30t5TLX" />
</div>

    <div>
    <img id="Image1" src="showImage.ashx?autoId=1" /> 
    </div>
    </form>
</body>
</html>

Open in new window

0
 
LVL 18

Accepted Solution

by:
ivan_vagunin earned 250 total points
ID: 36482495
I'm sorry, there was a misprint:
Using cmd As New OleDbCommand("select * from tblImg where img_id=@autoId", myAccessConnection)
            Dim paramId As New OleDbParameter("@autoId", OleDbType.Numeric)
            paramId.Value = Int32.Parse(autoId)
            cmd.Parameters.Add(paramId)
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                If reader.HasRows Then
                    reader.Read()
                    context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                    reader.Close()
                End If
            End Using
        End Using
0
 

Author Comment

by:tjgrindsted
ID: 36491297
hi Ivan

Dont say Sry. im happy that u will help.
I have looked at the code, but i still get a error, its about the fileContent !?
http://imageshack.us/photo/my-images/819/errorjie.jpg/
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36493630
Hi!
The error means that the row is returned, but there is no "FieldContent" column in it. Please check the spelling.
Try to debug: check the number of field returned (reader.FieldCount) and schema (reader.GetSchemaTable) - can you see FileContent field inside schema table?


0
 

Author Comment

by:tjgrindsted
ID: 36498089
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36498394
Hi! Then you should change
context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
to
context.Response.BinaryWrite(DirectCast(reader("img_stream"), [Byte]()))
0
 

Author Comment

by:tjgrindsted
ID: 36505829
Hi u to thx alot, i have learned alot of this thread...thx.
0
 

Author Comment

by:tjgrindsted
ID: 36505840
i mean U ;)
0
 

Author Closing Comment

by:tjgrindsted
ID: 36505845
great help....
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now