ASP.NET is extremely fast when you're creating and delivering Web pages.
However, no matter how fast and efficient your Web server and the software it
runs (including your Web applications) are, the delay between the user clicking
a button and seeing the results can vary tremendously. On a good ADSL or direct
Internet connection, it might be a "wow, that was quick" few seconds.
On a dial-up connection, especially when the server is on the other side of
the world, it's more likely to be the seemingly interminable "did
I remember to pay the phone bill?" response.

One feature that most executable applications offer but that is hard to provide
in a Web application is accurate status information and feedback on a long-running
process. However, this can be achieved in at least two different ways, depending
on the process your application is carrying out and the kind of status or feedback
information you want to provide.

One technique is a "smoke and mirrors" approach, in that it makes
the user feel comfortable that something is happeningwhile in fact the
information the user sees bears no real relationship to the progress of the
server-based operation. The other approach, covered toward the end of the chapter,
provides accurate status and feedback details but imposes limitations on client
device type and the kinds of operation for which it is suitable.

In this chapter you will see what is possible regarding loading progress and
status displays. You'll learn how to use and adapt a variety of techniques
to suit your own applications and requirements. This chapter starts with a look
at the theory of the process and examines the simplest way it can be achieved.

Displaying a "Please Wait" Page

Many ASP.NET developers find that despite their best efforts in producing
efficient code that minimizes response times, the vagaries of database response
times, the transit time over the Internet, and user input criteria that are not
specific enough can result in a lengthy delay before a page appears in the
browser. The result is that users often click the submit button several times to
try to elicit a response from your server, sometimes causing all kinds of
unfortunate side effects.

Chapter 6, "Client-Side Script Integration," looks at some specific
solutions for creating a one-click button. However, an alternative approach
is to provide a page that loads quickly and that displays a "please wait"
message or some suitable graphic feature, while the real target page is being
processed and delivered. In ASP 3.0 and other dynamic Web programming environments,
it's common to handle this process with separate pages that implement the
three execution stages shown in Figure 3.1.

ASP.NET engenders the single-page postback architecture approach. However,
you can build similar features into ASP.NET applications by implementing the
three pages as separate sections of a single page. The server control approach
to populating elements and attributes on the page also makes it easier to work
with elements such as the <meta> element that you use as part
of the process. Figure 3.2 shows the
ASP.NET approach, as it is adopted in the example described in the following
sections.

Passing Values Between Requests

Of course, what's missing from Figures
3.1 and 3.2 is how any values submitted
by the user are passed from the "please wait" page to the code that
creates the results. In ASP 3.0 and other dynamic Web page technologies, the
usual technique is to include a placeholder within the content attribute
of the <meta> element that gets replaced by a query string
containing the values sent from the <form> section. You can
then extract these from the query string in the page or section of code that
generates the results. You'll see this discussed in more detail in the
section "Displaying the "Please Wait" Message,"
later in this chapter.

A Simple "Please Wait" Example

Figure 3.3 shows the initial display
of a simple sample page that displays a "please wait" message while
the main processing of the user's request is taking place. The page queries
the Customers table in the sample Northwind database that is provided
with SQL Server. In the text box on the page, the user enters all or part of
the ID of the customer he or she is looking for.

When the user clicks the Go button, the value in the text box is submitted
to the server, and the page shown in Figure
3.4 is displayed. No complex processing is required to display this page,
and the total size of the content transmitted across the wire is small, so it
should appear very quickly. The user knows that his or her request is being
handled, and there is no submit button for the user to play with in the meantime.

Figure
3.4 The "please wait" message that is displayed while processing
the main page.

After a short delay (about 3 or 4 seconds, in this example), the main page,
which contains the results, is returned to the user and replaces the "please
wait" message. You can see in Figure
3.5 that the main page contains a list of customers matching the partial
ID value that was provided. At the bottom of the page is a New Customer link
that takes the user back to the first page.

Figure
3.5 The main page, displaying the results of a search for matching customers.

The HTML and Control Declarations

Listing 3.1 shows the relevant parts of the sample page shown in the
preceding section. Notice that although you include a <meta>
element in the <head> section of the page, you don't specify
any attributes for it. Instead, you give it an ID and specify that it is a
server control by including the runat="server" attribute.
However, this <meta> element will have no effect on the page or
the behavior of the browser until you specify the attributes for it in the
server-side code.

Listing 3.1 The HTML and Control Declarations for the Simple "Please
Wait" Sample Page

The remainder of the page is made up of the three sections that implement the
three pages shown in Figures 3.3 through
3.5. All three pages include a Visible="False"
attribute in their container elementeither the <form> element
itself for the first one or the containing <div> element for
the other two pages. So all three sections will be hidden when the page is loaded,
and you can display the appropriate one by simply changing its Visible
property to True.

Meta Refresh and Postback Issues

As you can see from the figures and code so far in this chapter, this example
uses a <meta> element in the "please wait" page to
force the browser to load the main page. This much-used technique is a handy way
to redirect the browser to a different page, and it is supported in almost every
browser currently in use today.

When you use the server-side Response.Redirect method in an ASP.NET
(or ASP 3.0) page, the server sends two HTTP headers to the client to indicate
that the browser should load a different page from the one that was requested.
The 302 Object Moved header indicates that the requested resource is
now at a different location, and the Location new-url header specifies
that the resource is located at the URL denoted by new-url.

The <meta> element supports the http-equiv attribute,
which is used to simulate the effects of sending specific HTTP headers to the
browser. To redirect the browser to a different URL, using a
<meta> element, you can use this:

<meta http-equiv="refresh" content="[delay];url=[new-url] />

In this syntax, [delay] is the number of seconds to wait
before loading the page specified in [new-url]. All browsers
will maintain the current page they are displaying until they receive the first
HTTP header sent by the server for the new page. So if the processing required
for creating the new page takes a while and the server does not send any
response until the processing is complete, the user will continue to see the
page containing the <meta> element (the "please wait"
message). By default, ASP.NET enables response buffering, so it does not
generate any output until the new page is complete and ready to send to the
browser.

Replacing the Existing Page in the Browser

Web browsers continue to display the existing page when you click a link in
that page or enter a new URL in the address bar, while they locate and start to
load the new page. However, as soon as the first items of the page that will be
rendered are received (as opposed to the HTTP headers), the existing page is
removed from the display, to be replaced by the progressive rendering of the new
page.

One important point to note, however, is that if you disable output buffering
by setting Response.Buffer = False, or if you force intermediate output
to be sent to the response by using Response.Flush, the page currently
displayed in the browser will be discarded as soon as the partial output of the
new page is received.

However, the issue here is that unlike when you submit an ASP.NET
<form> element, the redirection caused by the
<meta> element doesn't perform a postback. This means that
viewstate for the page will not be maintained, and the values of any controls on
the whole page (including the nonvisible sections) will be lost. So any values
that you want to pass to the page the next time it loads (that is, when you
display the results of processing the main section of the page) must be passed
in the query string of the URL specified in the <meta>
element.

Of course, this is what you would have to do in the pre-ASP.NET example shown
in Figure 3.1 as well. Code in the page
must collect the values from all the controls in the <form> section
of the page when it is posted to the server, and it must build up a query string
containing these within the <meta> element. You'll see how
to do this in the following section.

The Page_Load Event Handler

The Page_Load event handler for the sample page first has to
determine the current stage of the three-step process:

Stage 1The user has just posted the <form>
element containing his or her input to the server.

Stage 2The "please wait" message is displayed, and
the <meta> element has caused the browser to request the page
containing the results.

Stage 3The user has clicked the New Customer link to go back
to Stage 1.

The following sections describe the code and page content that is used in the
example to implement these three stages.

Displaying the "Please Wait" Message

Listing 3.2 shows the first section of the Page_Load event handler
for the sample page. The only time a postback will have occurred is at Stage 1
because the other two stages are initiated by a <meta> element or
a hyperlink. (Code in a section of the Page_Load event handler makes
the <form> element visible when the page first loads, as
you'll see shortly.)

The Page.IsPostback property will be True only at Stage 1.
At that point, you can extract the value of the text box (and any other control
values that you might have in more complex examples) and build up the URL and
query string for the <meta> element. You obviously want to reload
the same page, so you get the URL from the Url property of the current
Request instance. In this example, the only value you need to maintain
as the page is reloaded is the value of the text box, and you use the name
custID for this as you create the query string.

Then, as shown in Listing 3.2, you add the attributes you need to the
<meta> element already declared in the page. You declare the
<meta> element as a server control by using the following:

<meta id="mtaRefresh" runat="server" />

ASP.NET will implement this element as an instance of the
HtmlGenericControl class because there is no specific control type
within the .NET Framework class library for the <meta> element.
However, the HtmlGenericControl type has an Attributes
collection that you can use to add the attributes you need to it. You add the
http-equiv="refresh" attribute and the content
attribute, with a value that will cause the browser to immediately reload the
page. If you view the source of the page in the browser (by selecting View,
Source), you'll see the complete <meta> element:

The next line of code hides the <form> section of the page.
Because this stage is a postback, the viewstate of the controls on the page is
maintained, so the form will remain visible if you don't hide it. The final
code line makes the section containing the "please wait" message
visible.

The HtmlGenericControl Class

The HtmlGenericControl class is described in more detail in Chapter
1, "Web Forms Tips and Tricks," where it is used for another control
type that is not part of the .NET Framework class library.

Displaying the Results

Listing 3.3 shows the second section of the Page_Load event handler.
This section is executed only if the Page.IsPostback property is
False; however, you have to detect whether the page is being loaded by
the <meta> element in the "please wait" page (Stage 2)
or the hyperlink in the results page (Stage 3).

Listing 3.3 The Second Part of the Page_Load Event Handler

...
Else
' get customer ID from query string
Dim sCustID As String = Request.QueryString("custID")
If sCustID > "" Then
' page is loading from META REFRESH element and
' so currently shows the "please wait" message
' a customer ID was provided so display results
divResult.Visible = True
' set URL for "Next Customer" hyperlink
lnkNext.NavigateUrl = Request.FilePath
' get data and bind to DataGrid in the page
FillDataGrid(sCustID)
Else
' either this is the first time the page has been
' loaded, or no customer ID was provided
' display controls to select customer
frmMain.Visible = True
End If
End If
End Sub

You've just seen how the code that runs in Stage 1, when the user
submits the form, adds the customer ID to the query string as
custID=value. (When the user loads the page by clicking the hyperlink
in the results page, there will be no query string.) So you test for the
presence of a customer ID value and, if there is one, you can make the section
of the page that displays the results visible, set the URL of the hyperlink in
that section of the page so that it will reload the current page, and then call
a separate routine, named FillDataGrid, that calculates the results and
fills the ASP.NET DataGrid control in this section of the page.

At the end of Listing 3.3 you can see the code that runs for Stage 3 of the
process. In this case, you know that it's not a postback, and there is no
customer ID in the query string. So either this is the first time the page has
been accessed or the user did not enter a customer ID value in the text box. In
either case, you just have to make the <form> section visible,
and the user ends up back at Stage 1 of the process.

Viewstate and the Visible Property

Notice that because the page does not maintain viewstate for Stages 2 and 3,
you don't need to hide the other sections of the page content. All three
carry the Visible="False" attribute, so they will not be
displayed unless you specifically change the Visible property to
True when the page loads each time.

Populating the DataGrid Control

The only other code in the sample page is responsible for fetching the
required data from the database and populating the DataGrid control on
the page. The full or partial customer ID, extracted from the query string at
Stage 2 of the process, is passed to the FillDataGrid routine, which is
shown in full in Listing 3.4.

The code here is fairly conventional. It creates a parameterized SQL
statement and then executes it with a Command instance to return a
DataReader instance that points to the result set generated by the
database. You use the customer ID passed to the routine as the value of the
single Parameter instance you create, and the resulting
DataReader instance is bound to the DataGrid control. See the
section "Using Parameters with SQL Statements and Stored Procedures"
in Chapter 10, "Relational Data-Handling Techniques," for more details
on using parameterized SQL statements.

Simulating a Complex or Lengthy Process

The code used to populate the DataGrid control in this example is
unlikely to qualify as a complex or lengthy operation. Unless someone pulls the
network cable out, it won't take long enough for the user to see the
"please wait" message in the demonstration page. So to simulate a long
process, you can insert a call to the Sleep method of the static
Thread object, specifying that the current thread should wait 3 seconds
before continuing:

Thread.Sleep(3000)

The only point to watch for here is that you have to import the
System.Threading namespace into the page to be able to access the
Thread object: