Write a ProgressBar (progress bar) control that shows real progress using ASP.net atlas

Source: Internet
Author: User
Tags contains datetime query sleep thread
Asp.net| Control | display

See the English version: http://dflying.dflying.net/1/archive/100_building_a_real_time_progressbar_using_aspnet_atlas.html
When the background is doing some long time operation, if can provide a real progress on the page to show the progress bar, instead of letting the user uninformed waiting or the previous simple estimates, will be a very rare place. Now it is entirely possible to use ASP.net atlas to do this. This article will discuss how to do this and introduce some basic concepts about the development of the Atlas client control. You can also download sample programs and source files here.

The idea of implementing a progress bar on a Web page is really simple: write a client-side Atlas control, request the server at intervals, and update the progress bar display with the current progress data returned. In this example, there will be four parts of code:

A web Service that takes a long time to complete
A Web service to query the progress of the Web service described above
Client Atlas progress bar (ProgressBar) control, which is responsible for maintaining client logic and outputting the visual UI. This is also one of the most important components in this example that can be reused in the future for other pages or program development
asp.net test page that contains the above Web service and controls
Here's a step-by-step approach to achieving these four steps:

Web Service that takes a long time to complete

In a real-world program, a Web service that takes a long time to complete may have the following declaration:

1[webmethod]
2public void Timeconsumingtask ()
3{
4 Connecttodatabase ();
5 getsomevaluefromdatabase ();
6 Copysomefilesfromdisk ();
7 Getaremotefile ();
8}
This allows us to insert some helper methods to determine the current progress completion, setprogress (int) To set the current percentage of progress complete:

1[webmethod]
2public void Timeconsumingtask ()
3{
4 setprogress (0);
5 connecttodatabase ();
6 setprogress (10);
7 getsomevaluefromdatabase ();
8 Setprogress (40);
9 Copysomefilesfromdisk ();
Setprogress (50);
One getaremotefile ();
Setprogress (100);
13}
In this example, we use the cache only to store progress completion information and to use the Thread.Sleep () method to simulate the delay of the operation:

1[webmethod]
2public int Starttimeconsumingtask ()
3{
4 string processkey = this. Context.Request.UserHostAddress;
5 string threadlockkey = "Thread" + this. Context.Request.UserHostAddress;
6 Object Threadlock = this. Context.cache[threadlockkey];
7 if (Threadlock = null)
8 {
9 Threadlock = new Object ();
this. Context.cache[threadlockkey] = Threadlock;
11}
12
Allow 1 running task per user.
if (! Monitor.TryEnter (threadlock, 0))
return-1;
16
DateTime starttime = DateTime.Now;
18
//Simulate a time-consuming task.
for (int i = 1; I <= i++)
21 {
//Update The progress for this task.
this. Context.cache[processkey] = i;
Thread.Sleep (70);
25}
26
Monitor.Exit (Threadlock);
28
Return (Datetime.now-starttime). Seconds;
30}
31

Web Service for Query progress

Easy to implement, just get the progress information from the cache:

1[webmethod]
2public int getprogress ()
3{
4 string processkey = this. Context.Request.UserHostAddress;
5 Object progress = this. Context.cache[processkey];
6 if (Progress!= null)
7 {
8 return (int) progress;
9}
10
return 0;
12}

Client progress bar (ProgressBar) control

First step: Inherit from Sys.UI.Control

The ProgressBar control should inherit from the control base class Sys.UI.Control of Atlas and be declared as a sealed class (sealed class, which can no longer be inherited). The Sys.UI.Control base class contains operations and methods that are common to all controls. For example, associating yourself with an HTML element (that is, the so-called binding). Also register to have Atlas understand this new type for future declarations and use, for example, to allow Atlas to obtain this type of description.

1sys.ui.progressbar = function (associatedelement) {
2 Sys.UI.ProgressBar.initializeBase (this, [associatedelement]);
3
4}
5type.registersealedclass (' Sys.UI.ProgressBar ', Sys.UI.Control);
6sys.typedescriptor.addtype (' script ', ' ProgressBar ', Sys.UI.ProgressBar);
7

Step Two: Add private members and write the corresponding setter/getter

Below you need to add some attributes to set our controls. In this example, we need three attributes:

Interval. Each time you requery the progress and updates the progress bar interval. Unit: MS
Service Url. The path to the Web service file.
Service method. The name of the method that gets the progress information.
These attributes should strictly adhere to the naming conventions of Atlas: The getter should start with ' get_ ', and the setter should start with ' set_ ' and pass in a parameter. You also need to add a description of these properties in the description method (descriptor) of the control. The description Method (descriptor) is described in step fourth. For example, for the service method attribute, we have the following declaration:

1var _servicemethod;
2
3this.get_servicemethod = function () {
4 return _servicemethod;
5}
6
7this.set_servicemethod = function (value) {
8 _servicemethod = value;
9}

Step three: Use the Timer control to query the Web Service every once in a while

Sys.timer is used to invoke a method every once in a while (issue an event), we can define a delegate to point to this method and query the Web Service for each time period. To avoid browser memory leaks, you should remember to do some necessary cleanup in the control destructor (Dispose).

Also, note that a second request should not be sent when the current request does not return.

1var _timer = new Sys.timer ();
2var _responsepending;
3var _tickhandler;
4var _obj = this;
5
6this.initialize = function () {
7 Sys.UI.ProgressBar.callBaseMethod (this, ' Initialize ');
8 _tickhandler = Function.createdelegate (this, this._ontimertick);
9 _timer.tick.add (_tickhandler);
This.set_progress (0);
11}
12
13this.dispose = function () {
if (_timer) {
_timer.tick.remove (_tickhandler);
_tickhandler = null;
_timer.dispose ();
18}
_timer = null;
Associatedelement = null;
_obj = null;
22
Sys.UI.ProgressBar.callBaseMethod (This, ' Dispose ');
24}
25
26this._ontimertick = function (sender, EventArgs) {
if (!_responsepending) {
_responsepending = true;
29
//Asynchronously Call the service method.
Sys.Net.ServiceMethod.invoke (_serviceurl, _servicemethod, NULL, NULL, _onmethodcomplete);
32}
33}
34
35function _onmethodcomplete (Result) {
//Update the progress bar.
Panax Notoginseng _obj.set_progress (result);
_responsepending = false;
39}

Step Fourth: Add control methods

We should be able to control the start/stop of the progress bar. Also, the associated description method (descriptor) is necessary for an Atlas control. Atlas uses it to describe this type of information.

1this.getdescriptor = function () {
2 var td = Sys.UI.ProgressBar.callBaseMethod (this, ' getdescriptor ');
3 Td.addproperty (' interval ', number);
4 Td.addproperty (' Progress ', number);
5 td.addproperty (' serviceurl ', String);
6 Td.addproperty (' Servicemethod ', String);
7 Td.addmethod (' Start ');
8 Td.addmethod (' Stop ');
9 return TD;
10}
11
12this.start = function () {
_timer.set_enabled (TRUE);
14}
15
16this.stop = function () {
_timer.set_enabled (FALSE);
18}

OK, so far the client's control is complete. We save it as a progressbar.js.

asp.net testing Page ASP. NET test page

The first thing we need to do with any Atlas page is to add a ScriptManager server control. In this example we will refer to the ProgressBar control, which is a long time to complete the Web service and the Progress Query Web service. (These two Web service are located in the same file: Taskservice.asmx)

1<atlas:scriptmanager id= "ScriptManager1" runat= "Server" >
2 <Scripts>
3 <atlas:scriptreference path= "scriptlibrary/progressbar.js" scriptname= "Custom"/>
4 </Scripts>
5 <Services>
6 <atlas:servicereference path= "Taskservice.asmx"/>
7 </Services>
8</atlas:scriptmanager>
Next is the layout and style of the page:

 1<style type= "Text/css"
 2* {} {
 3    Font-family:tahoma;
 4}
 5.progressbarcontainer {} {
 6    border:1px solid #000;
 7    width:500px;
 8    height:15px;
 9}
10.progressBar {} {
11    background-color:green;
12    height:15px;
13    width:0px;
14    Font-weight:bold;
15}
16</style>

18<div>task progress</div>
19<div class= "Progressbarcontainer"
20    <div id= "PB" class= "ProgressBar" ></DIV>
21</div>
22<input Type= "button" id= "Start" value= "start the time consuming task!"/>
23<div id= "Output" ></DIV>
Finally, a piece of JavaScript starts that long time to complete the Web service and lets the ProgressBar control begin to work:


Screenshots and Downloads

Now all the things are done, can run!

Page initialization:


In operation:

Run Complete:

Sample programs and source files can be downloaded here.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.