Auto-Update as a Simple Custom Control


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.

AutoRefresh1.gif

Figure 1:  Solution Explorer

The control library only contains a single class entitled, "AutoRefresh.cs". 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 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).

AutoRefresh2.gif

Figure 2:  The Test Website in Operation

The Code:  AutoRefresh.cs

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:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls; 

 

[DefaultProperty("Update Interval"), ToolboxData("<{0}:AutoRefresh runat=server></{0}:AutoRefresh>")]

public class AutoRefresh : 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.
   

private int mTimeInterval;

private void AutoRefresh_Init(object sender, System.EventArgs e)

{

    this.Height = 20;

    this.Width = 20;

}

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).

[Category("Update Interval") ]

[Browsable(true) ]

[Description("Set the interval at which the page will refresh (in seconds)")]

public int TimeInterval

{

    get

    {

        return mTimeInterval;

    }

    set

    {

        mTimeInterval = value;

    }

}

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 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:

protected override void RenderContents(HtmlTextWriter writer)

{ 

    try

    { 

        StringBuilder sb = new StringBuilder();

        sb.Append("<meta http-equiv=\'Refresh\' content=" + TimeInterval + "> "); 

        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        writer.Write(sb.ToString());

        writer.RenderEndTag(); 

    }

    catch (Exception)

    { 

        // if there is an error, the control will just display 'Auto Refresh'

        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        writer.Write("Auto Refresh");

        writer.RenderEndTag(); 

    }

}

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 work around 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 display 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:

AutoRefresh3.gif

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

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

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        lblTime.Text = DateTime.Now.ToShortTimeString();

    }

}

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 need 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.

NOTE: THIS ARTICLE IS CONVERTED FROM VB.NET TO C# USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON VB.NET Heaven (http://www.vbdotnetheaven.com/). 


Similar Articles