ImageRotator Control
Life With Nate
Nate's Poetry Page
Resume (PDF)
Nate's Code
ASP.NET 2.0/3.5
ButtonExtensions
CheckBoxValidator
ConditionalRequiredTextValidator
CSSImageMap
CustomStyle
DateTimePicker
DateTimePickerTemplated
LengthValidator
RestrictInputTextBox
RestrictInputValidator
Rollovers
RotatedTextHandler
RotatedTextImage
Rotators
AdRotator
ImageRotator
TemplateRotator
RotatorAd
RotatorImage
RotatorTemplate
Sample Rotator XML File
Rotators DTD
SelectedCountValidator
SlideIntoView
StatesDropDownList
UniqueValueValidatorBase
VB.NET 2.0/3.5
Just For Fun
Windows Phone 7
Description
The ImageRotator control creates an image that periodically changes. The control allows you to specify the frequency of the change and whether it is to another random image or whether it enumerates through the images in the order they are listed. All code used to rotate through the images is written in JavaScript. The ImageRotator also generates JavaScript that preloads the images to avoid delay when displaying them. Images can be specified as part of the control using
RotatorImage
s as child controls or by specifying an XML file or images directory.
Example
Data From
XML File:
Data From RotatorImage
Child Controls:
Random
Order
Sequential
Order
<NJS:ImageRotator runat="server" RandomOrder="True" XMLFileName="~/RotatorsExample.xml" Width="200" Height="200" TargetBlank="True"/> <NJS:ImageRotator runat="server" RandomOrder="True" Width="200" Height="200" TargetBlank="True"> <NJS:RotatorImage runat="server" ImageUrl="~/images/Black.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Blue.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Green.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Red.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Yellow.gif"/> </NJS:ImageRotator> <NJS:ImageRotator runat="server" RandomOrder="False" XMLFileName="~/RotatorsExample.xml" Width="200" Height="200" TargetBlank="True" XMLRotatorID="imr"/> <NJS:ImageRotator runat="server" RandomOrder="False" Width="200" Height="200" TargetBlank="True"> <NJS:RotatorImage runat="server" ImageUrl="~/images/Black.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Blue.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Green.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Red.gif"/> <NJS:RotatorImage runat="server" ImageUrl="~/images/Yellow.gif"/> </NJS:ImageRotator>
Properties & Methods
ImageRotator
The ImageRotator is a simple control that generates an image that periodically changes
Height
- (Inherited from WebControls.Image) The height, in pixels, of the image
Images
- The List of RotatorImages obtained from either the XML file or child controls
Interval
- The amount of time, in milliseconds, between image changes (default="1750")
RandomOrder
- A Boolean value specifying whether the images should be displayed sequentially or in random order (default="False")
Width
- (Inherited from WebControls.Image) The width, in pixels, of the image
XMLFileName
- The XML file that contains the images. If not specified, the ImageRotator will use any images in the directory specified in ImageDirectory. If no ImageDirectory valu is specified, the ImageRotator will look for child controls of type
RotatorImage
XMLRotatorID
- A String value specifying which of the ImageRotator elements in the specified XML file to use. If not specified, the first one will be used
ImageDirectory
- The directory that contains the images. If both the XMLFileName and ImageDirectory properties are unspecified, the ImageRotator will look for child controls of type
RotatorImage
Source Code
Rotators.vb:
Namespace NathanSokalski <ParseChildren(True, "Ads")> Public Class AdRotator : Inherits System.Web.UI.HtmlControls.HtmlAnchor Private img As New HtmlImage Private _randomorder As Boolean = False Private _ads As New Collections.Generic.List(Of RotatorAd) Private _interval As Long = 1750 Private _xmlfilename As String Private _xmlrotatorid As String <UrlProperty(), _ Description("The XML file that contains the images and URLs")> _ Public WriteOnly Property XMLFileName() As String Set(ByVal value As String) Me._xmlfilename = value End Set End Property <Description("A String value specifying which of the AdRotator elements in the specified XML file to use")> _ Public WriteOnly Property XMLRotatorID() As String Set(ByVal value As String) Me._xmlrotatorid = value End Set End Property <Description("The width, in pixels, of the image")> Public WriteOnly Property Width() As Integer Set(ByVal value As Integer) Me.img.Style.Add(HtmlTextWriterStyle.Width, String.Concat(value, "px")) End Set End Property <Description("The height, in pixels, of the image")> Public WriteOnly Property Height() As Integer Set(ByVal value As Integer) Me.img.Style.Add(HtmlTextWriterStyle.Height, String.Concat(value, "px")) End Set End Property <DefaultValue(False), _ Description("A Boolean value specifying whether the images and URLs should be displayed sequentially or in random order")> _ Public Property RandomOrder() As Boolean Get Return Me._randomorder End Get Set(ByVal value As Boolean) Me._randomorder = value End Set End Property <Browsable(False), _ Description("The List of RotatorAds obtained from either the XML file or child controls")> _ Public ReadOnly Property Ads() As Collections.Generic.List(Of RotatorAd) Get Return Me._ads End Get End Property <DefaultValue(1750), _ Description("The amount of time, in milliseconds, between image and URL changes")> _ Public Property Interval() As Long Get Return Me._interval End Get Set(ByVal value As Long) Me._interval = value End Set End Property <DefaultValue(True), _ Description("A Boolean value that specifies whether or not clicking the image will open in a new browser window")> _ Public Property TargetBlank() As Boolean Get Return Me.Target.ToLower() = "_blank" End Get Set(ByVal value As Boolean) If value Then Me.Target = "_blank" Else Me.Target = String.Empty End Set End Property Public Sub New() MyBase.New() Me.Target = "_blank" End Sub Private Sub Ctrl_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Me.EnableViewState = False Me.img.EnableViewState = False Me.img.Style.Add(HtmlTextWriterStyle.BorderWidth, "0px") Me.Controls.Add(Me.img) If Not String.IsNullOrEmpty(Me._xmlfilename) Then Dim xmldoc As New System.Xml.XmlDocument() Dim xmlads As System.Xml.XmlNodeList xmldoc.Load(HttpContext.Current.Server.MapPath(Me._xmlfilename)) If xmldoc.GetElementsByTagName("AdRotator").Count > 0 Then If String.IsNullOrEmpty(Me._xmlrotatorid) Then xmlads = xmldoc.GetElementsByTagName("AdRotator")(0).ChildNodes Else Dim temp As System.Collections.IEnumerator = xmldoc.GetElementsByTagName("AdRotator").GetEnumerator() While temp.MoveNext() If Not IsNothing(CType(temp.Current, System.Xml.XmlNode).Attributes.ItemOf("Id")) AndAlso CType(temp.Current, System.Xml.XmlNode).Attributes.ItemOf("Id").Value = Me._xmlrotatorid Then xmlads = CType(temp.Current, System.Xml.XmlNode).ChildNodes Exit While End If End While End If If Not IsNothing(xmlads) Then For Each ad As XmlNode In xmlads Me._ads.Add(New RotatorAd(ad.Attributes.ItemOf("ImageUrl").Value, ad.Attributes.ItemOf("LinkUrl").Value)) Next End If End If End If End Sub Private Sub Ctrl_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender If Not Me.Page.ClientScript.IsClientScriptBlockRegistered("AdRotator") Then Me.Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "AdRotator", "function AdRotator(ctrlid){ctrlid.currindex=(ctrlid.randomorder?Math.floor(Math.random()*ctrlid.adsdata.length):++ctrlid.currindex%ctrlid.adsdata.length);document.getElementById(ctrlid.anchorid).href=ctrlid.adsdata[ctrlid.currindex][0];document.getElementById(ctrlid.anchorid).firstChild.src=ctrlid.adsdata[ctrlid.currindex][1];}", True) Dim adscript As New System.Text.StringBuilder() adscript.AppendLine() For Each currentad As RotatorAd In Me._ads adscript.AppendFormat("(new Image()).src=""{0}"";", Me.ResolveClientUrl(currentad.ImageUrl)) Next adscript.AppendLine() adscript.AppendFormat("var {0}_data={{anchorid:""{0}"",currindex:0,randomorder:{1},adsdata:[", Me.ClientID(), Me._randomorder.ToString().ToLower()) For Each currentad As RotatorAd In Me._ads adscript.AppendFormat("[""{0}"",""{1}""],", Me.ResolveClientUrl(currentad.LinkUrl), Me.ResolveClientUrl(currentad.ImageUrl)) Next adscript.AppendLine("]};").Replace("],]", "]]") adscript.AppendFormat("window.setInterval(""AdRotator({0}_data)"",{1});", Me.ClientID(), Me._interval.ToString().TrimStart("-"c)).AppendLine() Me.Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), Me.ClientID(), adscript.ToString(), True) End Sub End Class <ParseChildren(True, "Images")> Public Class ImageRotator : Inherits System.Web.UI.WebControls.Image Private _randomorder As Boolean = False Private _images As New Collections.Generic.List(Of RotatorImage) Private _interval As Long = 1750 Private _xmlfilename As String Private _xmlrotatorid As String Private _imagedirectory As String <UrlProperty(), _ Description("The XML file that contains the images")> _ Public WriteOnly Property XMLFileName() As String Set(ByVal value As String) Me._xmlfilename = value End Set End Property <Description("A String value specifying which of the ImageRotator elements in the specified XML file to use")> _ Public WriteOnly Property XMLRotatorID() As String Set(ByVal value As String) Me._xmlrotatorid = value End Set End Property <DefaultValue(False), _ Description("A Boolean value specifying whether the images should be displayed sequentially or in random order")> _ Public Property RandomOrder() As Boolean Get Return Me._randomorder End Get Set(ByVal value As Boolean) Me._randomorder = value End Set End Property <Browsable(False), _ Description("The List of RotatorImages obtained from either the XML file or child controls")> _ Public ReadOnly Property Images() As Collections.Generic.List(Of RotatorImage) Get Return Me._images End Get End Property <DefaultValue(1750), _ Description("The amount of time, in milliseconds, between image changes")> _ Public Property Interval() As Long Get Return Me._interval End Get Set(ByVal value As Long) Me._interval = value End Set End Property <UrlProperty(), _ Description("The directory that contains the images")> _ Public WriteOnly Property ImageDirectory() As String Set(ByVal value As String) Me._imagedirectory = value If Not Me._imagedirectory.EndsWith("/") Then Me._imagedirectory &= "/" End Set End Property Private Sub Ctrl_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Me.EnableViewState = False Me.BorderWidth = New Unit(0, UnitType.Pixel) If Not String.IsNullOrEmpty(Me._xmlfilename) Then Dim xmldoc As New System.Xml.XmlDocument() Dim xmlimgs As System.Xml.XmlNodeList xmldoc.Load(HttpContext.Current.Server.MapPath(Me._xmlfilename)) If xmldoc.GetElementsByTagName("ImageRotator").Count > 0 Then If String.IsNullOrEmpty(Me._xmlrotatorid) Then xmlimgs = xmldoc.GetElementsByTagName("ImageRotator")(0).ChildNodes Else Dim temp As System.Collections.IEnumerator = xmldoc.GetElementsByTagName("ImageRotator").GetEnumerator() While temp.MoveNext() If Not IsNothing(CType(temp.Current, System.Xml.XmlNode).Attributes.ItemOf("Id")) AndAlso CType(temp.Current, System.Xml.XmlNode).Attributes.ItemOf("Id").Value = Me._xmlrotatorid Then xmlimgs = CType(temp.Current, System.Xml.XmlNode).ChildNodes Exit While End If End While End If If Not IsNothing(xmlimgs) Then For Each img As XmlNode In xmlimgs Me._images.Add(New RotatorImage(img.Attributes.ItemOf("ImageUrl").Value)) Next End If End If ElseIf Me._imagedirectory <> String.Empty Then Dim imagepaths() As String = System.IO.Directory.GetFiles(HttpContext.Current.Server.MapPath(Me._imagedirectory)) For Each imagepath As String In imagepaths Me._images.Add(New RotatorImage(Me.ResolveClientUrl(String.Concat(Me._imagedirectory, imagepath.Substring(imagepath.LastIndexOf("\")))))) Next End If End Sub Private Sub Ctrl_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender If Not Me.Page.ClientScript.IsClientScriptBlockRegistered("ImgRotator") Then Me.Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "ImgRotator", "function ImgRotator(ctrlid){ctrlid.currindex=(ctrlid.randomorder?Math.floor(Math.random()*ctrlid.imglist.length):++ctrlid.currindex%ctrlid.imglist.length);document.getElementById(ctrlid.imageid).src=ctrlid.imglist[ctrlid.currindex];}", True) Dim imgscript As New System.Text.StringBuilder() imgscript.AppendLine() For Each currentad As RotatorImage In Me._images imgscript.AppendFormat("(new Image()).src=""{0}"";", Me.ResolveClientUrl(currentad.ImageUrl)) Next imgscript.AppendLine() imgscript.AppendFormat("var {0}_data={{imageid:""{0}"",currindex:0,randomorder:{1},imglist:[", Me.ClientID(), Me._randomorder.ToString().ToLower()) For Each currentimg As RotatorImage In Me._images imgscript.AppendFormat("""{0}"",", Me.ResolveClientUrl(currentimg.ImageUrl)) Next imgscript.AppendLine("]};").Replace(",]", "]") imgscript.AppendFormat("window.setInterval(""ImgRotator({0}_data)"",{1});", Me.ClientID(), Me._interval.ToString().TrimStart("-"c)).AppendLine() Me.Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), Me.ClientID(), imgscript.ToString(), True) End Sub End Class Public Class RotatorAd : Inherits System.Web.UI.Control Private _linkurl As String = String.Empty Private _imageurl As String = String.Empty <UrlProperty(), _ Description("The URL that the user will be taken to when they click on the image")> _ Public Property LinkUrl() As String Get Return Me._linkurl End Get Set(ByVal value As String) Me._linkurl = value End Set End Property <UrlProperty(), Description("The URL of the image")> Public Property ImageUrl() As String Get Return Me._imageurl End Get Set(ByVal value As String) Me._imageurl = value End Set End Property Public Sub New() MyBase.New() End Sub Public Sub New(ByVal imgurl As String, ByVal lnkurl As String) Me._imageurl = imgurl Me._linkurl = lnkurl End Sub End Class Public Class RotatorImage : Inherits System.Web.UI.Control Private _imageurl As String = String.Empty <UrlProperty(), Description("The URL of the image")> Public Property ImageUrl() As String Get Return Me._imageurl End Get Set(ByVal value As String) Me._imageurl = value End Set End Property Public Sub New() MyBase.New() End Sub Public Sub New(ByVal imgurl As String) Me._imageurl = imgurl End Sub End Class End Namespace
Remarks
This control is designed for scenarios in which all images are the same size (this is why the Width/Height properties are in the ImageRotator control instead of with the specific images). I strongly recommend specifying values for the Width/Height properties, especially when using the ImageDirectory property.