The AJAX Solution
The HTML side of the AJAX page is shown in Listing 6
calls, which adds the different fields that are returned in the XML the server. The startup
page starts the first request to the server. The getData starts a request by calling createHTTPRequest
. This function has cross-platform code to build the HTTP request object.
The HTTP request is asynchronous. When it completes, the handleResponse function is called. That function parses up the XML and creates some new HTML for the data table. That HTML is placed into the 'grid' <div> tag.
The code behind for this page is shown in Listing 7. The page_load of this code starts the job and then sets the hidden input field with the URL of the data request page.
The get_data.aspx page takes a request ID and returns an XML representation of the current data set. The page code is shown below:
<%@ Page language="c#" Codebehind="get_data.aspx.cs"
AutoEventWireup="false" Inherits="background.get_data" %>
Obviously the code behind is more important in this case. That code is shown in Listing 8
, which starts with setting the content type of the response to 'text/xml.' Without that the AJAX code in the browser won't create an XML document from the response. After that the code gets the request and asks the DataSet to create the XML. It then alters the XML response slightly to add the 'done' field, which tells the client whether the request has completed.
When the page first launches it looks like Figure 6.
Figure 6. Still Polling: The screen shot shows the AJAX page while it is still polling.
Figure 7. Complete: The screen shot shows the completed AJAX page.
When the request has completed the browser will look like Figure 7
When working with AJAX solutions keep in mind that you are setting a minimum browser requirement when you write the code. Not all browsers can create an HTTP request. In fact, just the most recent browsers can do it. Ideally your solution should support both a polling version for older browsers and an AJAX version for newer browsers.
Threading can be problematic at the best of times. And in this case the threading can be harder to monitor than usual because it's running on the server in the background. It's possible that the request will keep running even if there is no web client monitoring it. If that is an issue then you should have the web monitoring code set a time stamp with the threaded process. If the threaded process sees that it hasn't been viewed for a while then it can cancel itself.
There are a number of ways to do background processing in .NET. This threading approach is just one way. You can also work with ASP.NET cache, or even go so far as to create a real background process.
With these different techniques you can make turn long processing wait times into a user experience that gives rich feedback about how the processing is going.