This post goes over how to display images stored in a database using the SlideShowExtender control. The examples use VB.Net (what I have to use at the office) and assumes that you are storing your images in a database, have a way to retrieve the images from the database (e.g. stored procedure) and have AJAX (example is based on the AJAX controls in VS2008) setup in your ASP.Net project already. Also the example was based on retrieving images that are photos hence the names of some of the various functions, controls, etc.
The first piece is the SlideShowExtender, image control and the button controls on your aspx page. The example below does not use the Loop or PlayButtonID properties since I used it more as a picture gallery rather than cycling through images. Just add the Loop=’true’ property and another control for the play/stop button if you wanted to do that (an example here).
<asp:Image ID="imgPhoto" runat="server" Height="175px" />
<br />
<center>
<asp:Button ID="btnPrevPhoto" runat="server" Text="Prev" />
<asp:Button ID="btnNextPhoto" runat="server" Text="Next" />
</center>
<cc1:SlideShowExtender ID="ssePhotos" runat="server" TargetControlID="imgPhoto" AutoPlay="false"
PreviousButtonID="btnPrevPhoto" NextButtonID="btnNextPhoto" SlideShowServicePath="Photos.asmx"
SlideShowServiceMethod="GetPhotos" ContextKey="123">
</cc1:SlideShowExtender>
So now you have an image control to show the image, a button to cycle to the next image, a button to go back to the previous image and the SlideShowExtender itself. All that is pretty straightforward, the real guts of how it works lies in the web service (asmx file) and the web handler (ashx file). One very important property to note is the ContextKey. This is the value that you can pass to your function to retrieve your photos. In this example it is an ID for a group of photos and that ID is stored in the database. This would depend on how your table storing the images are setup but probably you have some sort of ID that goes along with a group of images (a site, an item, etc.). In reality that value would NOT be hard coded in but set in the code behind file.
The SlideShowServicePath property is set to Photos.asmx. This is a small web service that will add the images to a AjaxControlToolkit.Slide array. The SlideShowServiceMethod property contains the function in the web service that handles retrieving the images (with the help of the web handler). One key item, DO uncomment the <System.Web.Script.Services.ScriptService()> line. Otherwise a script (like the AJAX control) will not work. Here is the code for the web service:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class SitePhotos
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetPhotos(ByVal contextKey As String) As AjaxControlToolkit.Slide()
Dim photoReader As SqlDataReader
Dim conn As SqlConnection = New SqlConnection
Dim cmd As SqlCommand = New SqlCommand
conn.ConnectionString = ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
cmd.CommandText = "spGetThumbnailIDs"
cmd.Parameters.Add("@ID", SqlDbType.Int)
cmd.Parameters("@ID").Value = contextKey
conn.Open()
photoReader = cmd.ExecuteReader()
Dim slides(24) As AjaxControlToolkit.Slide
Dim i As Integer = 0
While photoReader.Read
slides(i) = New AjaxControlToolkit.Slide("Photo.ashx?TypeID=1&PhotoID=" & photoReader("ThumbnailID"), "test", "test")
i += 1
End While
photoReader.Close()
conn.Close()
i -= 1
ReDim Preserve slides(i)
Return slides
End Function
End Class
The first half of the GetPhotos function deals with making the database connection and executing the stored procedure (MSSQL). The variable slides is setup with 25 possible items so if you needed to display 50 items declare slides(49). The SqlDataReader reads in each image’s ThumbnailID and using the help of the ashx file (more on that later) adds the actual image data to slides. After the reading is complete the counter variable is set to one less than it is and slides is ReDimmed to eliminate any empty items that may exist. If this is not done then the SlideShowExtender will try and cycle through the empty items.
Before showing the web handler let me explain the various ids used in the GetPhotos function. The ID of the group of images needed is passed as the contextKey to the function. The spGetThumbnailIDs stored procedure then returns the ThumbnailIDs that are associated with ID into photoReader. The photoReader does not actually deal with the stored image file, the web handler retrieves that data and puts in the slides variable based on the ThumbnailID read from photoReader.
Now for the web handler file.
<%@ WebHandler Language="VB" Class="Photo" %>
Imports System
Imports System.Web
Imports System.Data
Public Class Photo : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim sdsPhoto As SqlDataSource = New SqlDataSource
sdsPhoto.ConnectionString = ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
sdsPhoto.SelectCommand = "spGetPhotos"
sdsPhoto.SelectCommandType = SqlDataSourceCommandType.StoredProcedure
sdsPhoto.SelectParameters.Add("ID", context.Request.QueryString("PhotoID"))
Dim dv As DataView = sdsPhoto.Select(DataSourceSelectArguments.Empty)
Dim dr As DataRow
Try
dr = dv.Table.Rows(0)
Catch
context.Response.Write("No Image Found")
Exit Sub
End Try
Dim arrImage() As Byte = CType(dr("Image"), Byte())
context.Response.BinaryWrite(arrImage)
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
This file takes the ThumbnailID and uses it in the spGetPhotos stored procedure to retrieve the actual image data. Again the first half of the sub is setting up the database connection. The image is then stored in the arrImage byte.
One final note the web handler can also be used to display images without the SlideShowExtender. You can use the ashx file in controls like the ImageButton and use the path in the ImageUrl.
Technorati Tags:
ASP.Net,
AJAX,
VB.Net