Click here to Skip to main content
15,885,914 members
Articles / Web Development / HTML
Article

Auto-Update as a Simple Custom Control

Rate me:
Please Sign up or sign in to vote.
3.00/5 (3 votes)
2 Nov 20066 min read 43.7K   470   23  
This article describes an easy way to implement automated page refreshes through the use of a custom control.

Image 1

Introduction

This article describes an easy way to implement automated page refreshes through the use of a custom control. Whilst it is simple enough to key in the text to do this on every page where an auto refresh is required, it is just as simple to create a custom control to handle the task on any number of pages. With a custom control in place, the developer can add the auto-refresh feature by merely dropping the control onto a form and setting the update interval property in the IDE’s property editor.

Performing auto-refreshes on a page is typically a questionable practice, but in some instances, it is necessary. For example, if you are working on a web based GIS solution that tracks GPS enabled long haul trucks, you may want to use a browser window to study the adventures of one of the truck drivers over a period of time. In order to continue to get updates on the position of the truck, it may be less of a burden on the user if the page auto-refreshed periodically to update the position of the trucks (as opposed to requiring the user to continuously hit the browser’s Refresh button). Aside from this example, the control could be useful when the purpose of the page is to display any continuously updated value such as a stock price or to monitor something such as the final moments of bidding in an online auction.

When using the control, the update interval should be set to a reasonable value. For example, you’d typically not want the control to update the page once a second, but you might want to capture updates at the rate of once a minute. Further, if the page contains other controls, the state of the controls will have to be rigorously maintained in order to prevent the loss of user entries between user initiated post backs.

In light of the recent interest in AJAX, doing timer based partial page updates will likely be a more reasonable approach to address most requirements. However, there are still instances where performing a periodic whole page update is not such a bad thing and this control was intended for those types of situations.

Getting Started

In order to begin, unzip the downloaded files and open the project provided. Within the solution, you will find two projects, one is the control library called “AutoUpdate”, and the other is a test web site.

Image 2

Figure 1: Solution Explorer

The control library only contains a single class entitled, “AutoRefresh.vb”. This simple class defines the custom control and its properties and methods.

The test website contains a single web page (default.aspx). This page contains an instance of the Auto Refresh control and, for the sake of demonstration, a single Label control that is updated with the current time whenever the page load event is fired.

The website’s bin folder contains a reference to the Auto-Update dynamic link library (DLL).

Image 3

Figure 2: The Test Website in Operation

The Code: AutoRefresh.vb

The auto refresh control class is pretty simple; the class contains only the default library imports, and the class itself inherits from the WebControl class. The first section of the code is as follows:

VB
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls


<DefaultProperty("Update Interval"), _
   ToolboxData("<{0}:AutoRefresh " & _ 
   "runat=server></{0}:AutoRefresh>")>_
Public Class AutoRefresh
    Inherits WebControl…

The next section of code in this class is equally simple. Following the class declaration, a private member variable used to contain the update time interval value is declared. Following that variable declaration, the next bit of code handles the control’s initialization event, and within that event handler, the control is given a default size of 20 x 20 pixels. This serves no useful purpose other than to make the control visible at design time so that the developer using the control can select it and load its properties into the property grid. If you’d prefer, you can color the control and write some text into (such as the control name) but I did not do anything special with regards to the appearance of the control at design time.

VB
Private mTimeInterval As Integer

Private Sub AutoRefresh_Init(ByVal sender As Object, _
                             ByVal e As System.EventArgs)
Handles Me.Init
    Me.Height = 20
    Me.Width = 20
End Sub

After the initialization event handler, a single property is declared, and that property is used to set or get the current time interval allowed between updates through the local time interval member variable (mTimeInterval).

VB
<Category("Update Interval")>_
<Browsable(True)>_
<Description("Set the interval at which the" & _
                " page will refresh (in seconds)")>_
Property TimeInterval() As Integer
    Get
        Return mTimeInterval
    End Get
    Set(ByVal value As Integer)
        mTimeInterval = value
    End Set
End Property

In examining the property code, note that the attributes for Category, Browsable, and Description are included with the property declaration. These attributes are providing design time support for the control within the Visual Studio IDE. The populated attributes set the property grid’s text and description for the time interval variable when it is displayed in the IDE’s property editor.

The last thing to do is to render the control. In this case, the control really does not have any sort of visualization associated with it, so it is just added to the page. This is accomplished by overriding the default RenderContents subroutine:

VB
    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)

        Try

            Dim sb As New StringBuilder
            sb.Append("<meta http-equiv='Refresh' content=" & TimeInterval & "> ")

            writer.RenderBeginTag(HtmlTextWriterTag.Div)
            writer.Write(sb.ToString())
            writer.RenderEndTag()

        Catch ex As Exception

            ' if there is an error, the control will just display 'Auto Refresh'
            writer.RenderBeginTag(HtmlTextWriterTag.Div)
            writer.Write("Auto Refresh")
            writer.RenderEndTag()

        End Try
    End Sub

End Class

In examining this code, note that the rendering option is wrapped in a Try Catch block, the purpose of this being to catch any errors in rendering the control, and to allow the control to render something safe if the operation fails for any reason. If this potential error is not trapped and an error occurs, then the IDE will display the error in an unfriendly way.

Also note that the HTMLTextWriter is placing the refresh tag into a div on the page. It is possible to write this into the head, but Microsoft did not provide a convenient method for doing this, and the workaround approaches for doing this are often not worth the effort (as is true in this case). The good news is that the control works just fine even if dumped into a div. You may also override the HTMLTextWriter begin tag (for example, you could change it to use a head tag instead of a div) and it will work, but it will still place the tag at the insertion point of the control and not in the actual head.

The Code: Default.aspx

The test web site has only a single webpage and that page is default.aspx. The page is simple and does not do anything more than show the current time; the current time is displayed upon the initial page load, and is updated after each post back. The time itself is displayed in an ASP.NET Label control. In addition to the Label, the page has a single copy of the auto update control added to it, and its interval is set to 10 seconds through the design time property editor support:

Image 4

Figure 3: Design Time Support for the Auto-Refresh Control

The only real code in the project is the page load event handler:

VB
Partial Class _Default
    Inherits System.Web.UI.Page

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

        lblTime.Text = DateTime.Now.ToShortTimeString()

    End Sub

End Class

As you can see, the only thing going on here is that, each time the page loads, the ASP.NET Label control is updated to display the current time. The auto-refresh control will force the page to update at the interval specified in the “TimeInterval” property, and in response to each update, the page load event will fire and the time will be updated.

That pretty much wraps up all of the coding needed to both build the custom control and to use it in the context of a web application.

Summary

While the demonstration control and project represent a very simple example of building a custom control, it still has some value both as a control (if used sparingly) and as an example of the procedures used to build an ASP.NET custom control. One could apply the same basic procedures used in this demonstration to build any number of unique custom controls.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --