Home > Articles > Programming > ASP .NET

Loading Progress and Status Displays in ASP.NET 1.1

This chapter shows you two ways to present users with status information while a complex or lengthy process is taking place: displaying a simple "please wait" message or animated GIF image, and implementing the server-side process as a series of staged individual operations.
This chapter is from the book

This chapter is from the book

In This Chapter

  • Displaying a "Please Wait" Page

  • Replacing the Existing Page in the Browser

  • Displaying a Progress Bar Graphic

  • Implementing a Staged Page Load Process

  • Summary

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.

Figure 3.1Figure 3.1 The traditional separate-pages approach to providing a "please wait" message.

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.

Figure 3.2Figure 3.2 The ASP.NET single-page approach to providing a "please wait" message.

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.

Figure 3.3Figure 3.3 The initial page of the simple "please wait" example.

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.

Obtaining the Sample Files

You can download this example and the other examples for this book from the Sams Web site at http://www.samspublishing.com, or from http://www.daveandal.net/books/6744/. You can also run many of this book's examples online at http://www.daveandal.net/books/6744/.

Figure 3.4Figure 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.5Figure 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

<html>
<head>
<!----- dynamically filled META REFRESH element ----->
<meta id="mtaRefresh" runat="server" />
</head>
<body>

<!----- form for selecting customer ----->
<form id="frmMain" Visible="False" runat="server">
 Enter Customer ID:
 <asp:Textbox id="txtCustomer" runat="server" />
 <asp:Button id="btnSubmit" Text="Go" runat="server" />
</form>

<!----- "please wait" display ----->
<div id="divWait" Visible="False" runat="server">
 <center>
 <p>&nbsp;</p>
 <p>&nbsp;</p>
 <b>Searching, please wait...</b><p />
 <p>&nbsp;</p>
 <span id="spnError"></span>
 <p>&nbsp;</p>
 </center>
</div>

<!----- section for displaying results ----->
<div id="divResult" Visible="False" runat="server">
 <b><asp:Label id="lblResult" runat="server" /></b><p />
 <asp:DataGrid id="dgrResult" runat="server" /><p />
 <asp:Hyperlink id="lnkNext" Text="New Customer" runat="server" />
</div>

</body>
</html>

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.

You can delay the removal of the existing page in some browsers—for example, Internet Explorer supports page translations, which take advantage of the built-in Visual Filters and Transitions feature (see http://msdn.microsoft.com/workshop/author/filter/filters.asp#Interpage_Transition).

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

Listing 3.2 The First Part of the Page_Load Event Handler

Sub Page_Load()

 If Page.IsPostback Then

  ' user submitted page with customer ID
  ' create URL with query string for customer ID
  ' next page will not be a postback, so viewstate will be lost
  Dim sRefreshURL As String = Request.Url.ToString() _
   & "?custID=" & txtCustomer.Text

  ' use META REFRESH to start loading next page
  mtaRefresh.Attributes.Add("http-equiv", "refresh")
  mtaRefresh.Attributes.Add("content", "0;url=" & sRefreshURL)

  ' hide <form> section and show "wait" section
  frmMain.Visible = False
  divWait.Visible = True

 Else
 ...

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:

<meta id="mtaRefresh" http-equiv="refresh" content="0;url=
/daveandal/books/6744/loadwait/simplewait.aspx?custID=a"></meta>

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.

Listing 3.4 The Final Part of the Page_Load Event Handler

Sub FillDataGrid(sCustID As String)

 Dim sSelect As String _
  = "SELECT CustomerID, CompanyName, City, Country, Phone " _
  & "FROM Customers WHERE CustomerID LIKE @CustomerID"
 Dim sConnect As String _
  = ConfigurationSettings.AppSettings("NorthwindSqlClientConnectString")
 Dim oConnect As New SqlConnection(sConnect)

 Try

  ' get DataReader for rows from Northwind Customers table
  Dim oCommand As New SqlCommand(sSelect, oConnect)
  oCommand.Parameters.Add("@CustomerID", sCustID & "%")
  oConnect.Open()
  dgrResult.DataSource = oCommand.ExecuteReader()
  dgrResult.DataBind()
  oConnect.Close()
  lblResult.Text = "Results of your query for Customer ID '" _
          & sCustID & "'"

  ' force current thread to sleep for 3 seconds
  ' to simulate complex code execution
  Thread.Sleep(3000)

 Catch oErr As Exception

  oConnect.Close()
  lblResult.Text = oErr.Message

 End Try

End Sub

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:

<%@Import Namespace="System.Threading" %>

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020