使用ASP.NET Atlas编写显示真实进度的ProgressBar(进度条)控件

 英文版见: http://dflying.dflying.net/1/archive/100_building_a_real_time_progressbar_using_aspnet_atlas.html

当后台在进行某些长时间的操作时,如果能在页面上提供一个显示真实进度的进度条,而不是让用户不知情的等待或是从前的那些简单的估计,将是一个非常难得的出彩之处。现在使用ASP.NET Atlas完全有可能做到这些。这篇文章将讨论如何完成这一功能并介绍一些有关Atlas客户端控件开发的基本概念。您同时可以在这里下载示例程序以及源文件

实现网页上的进度条想法其实很简单:编写一个客户端的Atlas控件,每隔一段时间请求一次服务器,并使用返回的当前进度数据更新进度条的显示。在这个示例中,将有四个部分的代码组成:

  1. 一个需要较长时间才能完成的Web Service
  2. 一个用来查询上述Web Service进度的Web Service
  3. 客户端Atlas进度条(ProgressBar)控件,负责维护客户端逻辑并输出可视化UI。这也是本示例中最重要的一个组件,在将来可被重用于其他页面或程序的开发
  4. 包含上述Web Service以及控件的ASP.NET测试页面

下面我们一步一步地来实现以上四个步骤:

 需要较长时间完成的Web Service

在实际的程序中,一个需要较长时间完成的Web Service可能有如下声明:

1 None.gif [WebMethod]
2 None.gif public   void  TimeConsumingTask()
3 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
4InBlock.gif    ConnectToDataBase();
5InBlock.gif    GetSomeValueFromDataBase();
6InBlock.gif    CopySomeFilesFromDisk();
7InBlock.gif    GetARemoteFile();
8ExpandedBlockEnd.gif}

这样我们就可以插入一些辅助方法来确定当前进度完成情况,setProgress(int)用来设定当前的进度完成百分比:

 1 None.gif [WebMethod]
 2 None.gif public   void  TimeConsumingTask()
 3 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 4InBlock.gif    setProgress(0);
 5InBlock.gif    ConnectToDataBase();
 6InBlock.gif    setProgress(10);
 7InBlock.gif    GetSomeValueFromDataBase();
 8InBlock.gif    setProgress(40);
 9InBlock.gif    CopySomeFilesFromDisk();
10InBlock.gif    setProgress(50);
11InBlock.gif    GetARemoteFile();
12InBlock.gif    setProgress(100);
13ExpandedBlockEnd.gif}

在本示例中,我们仅仅使用Cache来储存进度完成信息并利用Thread.Sleep()方法模拟操作的延迟:

 1 None.gif [WebMethod]
 2 None.gif public   int  StartTimeConsumingTask()
 3 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 4InBlock.gif    string processKey = this.Context.Request.UserHostAddress;
 5InBlock.gif    string threadLockKey = "thread" + this.Context.Request.UserHostAddress;
 6InBlock.gif    object threadLock = this.Context.Cache[threadLockKey];
 7InBlock.gif    if (threadLock == null)
 8ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 9InBlock.gif        threadLock = new object();
10InBlock.gif        this.Context.Cache[threadLockKey] = threadLock;
11ExpandedSubBlockEnd.gif    }

12InBlock.gif
13InBlock.gif    // Only allow 1 running task per user.
14InBlock.gif    if (!Monitor.TryEnter(threadLock, 0))
15InBlock.gif        return -1;
16InBlock.gif
17InBlock.gif    DateTime startTime = DateTime.Now;
18InBlock.gif
19InBlock.gif    // Simulate a time-consuming task.
20InBlock.gif    for (int i = 1; i <= 100; i++)
21ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
22InBlock.gif        // Update the progress for this task.
23InBlock.gif        this.Context.Cache[processKey] = i;
24InBlock.gif        Thread.Sleep(70);
25ExpandedSubBlockEnd.gif    }

26InBlock.gif
27InBlock.gif    Monitor.Exit(threadLock);
28InBlock.gif
29InBlock.gif    return (DateTime.Now - startTime).Seconds;
30ExpandedBlockEnd.gif}

31 None.gif

 

查询进度的Web Service

很容易实现,只需从Cache中取得进度信息:

 1 None.gif [WebMethod]
 2 None.gif public   int  GetProgress()
 3 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 4InBlock.gif    string processKey = this.Context.Request.UserHostAddress;
 5InBlock.gif    object progress = this.Context.Cache[processKey];
 6InBlock.gif    if (progress != null)
 7ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 8InBlock.gif        return (int)progress;
 9ExpandedSubBlockEnd.gif    }

10InBlock.gif
11InBlock.gif    return 0;
12ExpandedBlockEnd.gif}

 

客户端进度条(ProgressBar)控件

第一步:从Sys.UI.Control继承

ProgressBar控件应该继承自Atlas的控件基类Sys.UI.Control,并且声明为密封类(sealed class,不能再被继承)。Sys.UI.Control基类包含了一些所有的控件共有的操作与方法。比如,将自己与某个HTML元素关联起来(也就是所谓的binding)等。同时也要注册以让Atlas了解这个新的类型以便今后的声明及使用,例如,让Atlas可以取得这个类型的描述等。

1 ExpandedBlockStart.gif ContractedBlock.gif Sys.UI.ProgressBar  =   function (associatedElement)  dot.gif {
2InBlock.gif    Sys.UI.ProgressBar.initializeBase(this, [associatedElement]);
3InBlock.gif
4ExpandedBlockEnd.gif}

5 None.gifType.registerSealedClass('Sys.UI.ProgressBar', Sys.UI.Control);
6 None.gifSys.TypeDescriptor.addType('script','progressBar', Sys.UI.ProgressBar);
7 None.gif

 

第二步:添加私有成员并书写相应的Setter/Getter

下面需要添加一些属性用来设定我们的控件。在这个例子中,我们需要三个属性:

  1. Interval. 每次重新查询进度并更新进度条的间隔时间。单位:毫秒
  2. Service Url. Web Service文件的路径。
  3. Service Method. 取得进度信息的方法名。

这些属性应该严格遵守Atlas的命名规范:Getter应该以'get_'开头,Setter应该以'set_'开头并传入一个参数。还需要在控件的描述方法(descriptor)中添加对于这些属性的说明。有关描述方法(descriptor)将在第四步中说明。例如,针对Service Method属性,我们有如下声明:

1 None.gif var  _serviceMethod;
2 None.gif
3 ExpandedBlockStart.gifContractedBlock.gif this .get_serviceMethod  =   function ()  dot.gif {
4InBlock.gif    return _serviceMethod;
5ExpandedBlockEnd.gif}

6 None.gif
7 ExpandedBlockStart.gifContractedBlock.gif this .set_serviceMethod  =   function (value)  dot.gif {
8InBlock.gif    _serviceMethod = value;
9ExpandedBlockEnd.gif}

 

第三步:使用Timer控件每隔一段时间查询一次Web Service

Sys.Timer用于每过一段时间调用一个方法(发出一个事件),我们可以定义一个委托来指向这个方法,并在并在每一个时间段内查询这个Web Service。为了避免浏览器内存泄露,在控件析构(dispose)的时候应该记得做一些必要的清理。

还有,注意当前一个请求并没有返回时,不应该发送第二个请求。

 1 None.gif var  _timer  =   new  Sys.Timer();
 2 None.gif var  _responsePending;
 3 None.gif var  _tickHandler;
 4 None.gif var  _obj  =   this ;
 5 None.gif
 6 ExpandedBlockStart.gifContractedBlock.gif this .initialize  =   function ()  dot.gif {
 7InBlock.gif    Sys.UI.ProgressBar.callBaseMethod(this, 'initialize');
 8InBlock.gif    _tickHandler = Function.createDelegate(thisthis._onTimerTick);
 9InBlock.gif    _timer.tick.add(_tickHandler);
10InBlock.gif    this.set_progress(0);
11ExpandedBlockEnd.gif}

12 None.gif
13 ExpandedBlockStart.gifContractedBlock.gif this .dispose  =   function ()  dot.gif {
14ExpandedSubBlockStart.gifContractedSubBlock.gif    if (_timer) dot.gif{
15InBlock.gif        _timer.tick.remove(_tickHandler);
16InBlock.gif        _tickHandler = null;
17InBlock.gif        _timer.dispose();
18ExpandedSubBlockEnd.gif    }

19InBlock.gif    _timer = null;
20InBlock.gif    associatedElement = null;
21InBlock.gif    _obj = null;
22InBlock.gif
23InBlock.gif    Sys.UI.ProgressBar.callBaseMethod(this, 'dispose');
24ExpandedBlockEnd.gif}

25 None.gif
26 ExpandedBlockStart.gifContractedBlock.gif this ._onTimerTick  =   function (sender, eventArgs)  dot.gif {
27ExpandedSubBlockStart.gifContractedSubBlock.gif    if (!_responsePending) dot.gif{
28InBlock.gif        _responsePending = true;
29InBlock.gif        
30InBlock.gif        // Asynchronously call the service method.
31InBlock.gif        Sys.Net.ServiceMethod.invoke(_serviceURL, _serviceMethod, nullnull, _onMethodComplete);
32ExpandedSubBlockEnd.gif    }

33ExpandedBlockEnd.gif}

34 None.gif
35 ExpandedBlockStart.gifContractedBlock.gif function  _onMethodComplete(result)  dot.gif {
36InBlock.gif    // Update the progress bar.
37InBlock.gif    _obj.set_progress(result);
38InBlock.gif    _responsePending = false;
39ExpandedBlockEnd.gif}

 

第四步:添加控制方法

我们应该可以控制进度条的开始/停止。并且,对于一个Atlas控件,相关的描述方法(descriptor)也是必须的。Atlas会利用它来描述这个类型的信息。

 1 ExpandedBlockStart.gif ContractedBlock.gif this .getDescriptor  =   function ()  dot.gif {
 2InBlock.gif    var td = Sys.UI.ProgressBar.callBaseMethod(this, 'getDescriptor');
 3InBlock.gif    td.addProperty('interval', Number);
 4InBlock.gif    td.addProperty('progress', Number);
 5InBlock.gif    td.addProperty('serviceURL', String);
 6InBlock.gif    td.addProperty('serviceMethod', String);
 7InBlock.gif    td.addMethod('start');
 8InBlock.gif    td.addMethod('stop');
 9InBlock.gif    return td;
10ExpandedBlockEnd.gif}

11 None.gif
12 ExpandedBlockStart.gifContractedBlock.gif this .start  =   function ()  dot.gif {
13InBlock.gif    _timer.set_enabled(true);
14ExpandedBlockEnd.gif}

15 None.gif
16 ExpandedBlockStart.gifContractedBlock.gif this .stop  =   function ()  dot.gif {
17InBlock.gif    _timer.set_enabled(false);
18ExpandedBlockEnd.gif}

 

OK,目前为止客户端的控件就完成了。我们把它存为ProgressBar.js。

ASP.NET Testing Page ASP.NET测试页面

对于任何的Atlas页面,我们第一件需要做的事情就是添加一个ScriptManager服务器控件。在这个示例中我们将引用ProgressBar控件,较长时间才能完成的Web Service以及进度查询Web Service。(这两个Web Service位于同一个文件中:TaskService.asmx)

1 None.gif < atlas:ScriptManager  ID ="ScriptManager1"  runat ="server"   >
2 None.gif     < Scripts >
3 None.gif         < atlas:ScriptReference  Path ="ScriptLibrary/ProgressBar.js"  ScriptName ="Custom"   />
4 None.gif     </ Scripts >
5 None.gif     < Services >
6 None.gif         < atlas:ServiceReference  Path ="TaskService.asmx"   />
7 None.gif     </ Services >
8 None.gif </ atlas:ScriptManager >

接下来是页面的布局与样式:

 1 ExpandedBlockStart.gif ContractedBlock.gif < style  type ="text/css" > dot.gif
 2ExpandedSubBlockStart.gifContractedSubBlock.gif{dot.gif}{
 3InBlock.gif    font-family: tahoma;
 4ExpandedSubBlockEnd.gif}

 5ExpandedSubBlockStart.gifContractedSubBlock.gif.progressBarContainer {dot.gif}{
 6InBlock.gif    border: 1px solid #000;
 7InBlock.gif    width: 500px;
 8InBlock.gif    height: 15px;
 9ExpandedSubBlockEnd.gif}

10ExpandedSubBlockStart.gifContractedSubBlock.gif.progressBar {dot.gif}{
11InBlock.gif    background-color: green;
12InBlock.gif    height: 15px;
13InBlock.gif    width: 0px;
14InBlock.gif    font-weight: bold;
15ExpandedBlockEnd.gif}

16None.gif
</ style >
17 None.gif
18 None.gif < div > Task Progress </ div >
19 None.gif < div  class ="progressBarContainer" >
20 None.gif     < div  id ="pb"  class ="progressBar" ></ div >
21 None.gif </ div >
22 None.gif < input  type ="button"  id ="start"  onclick ="startTask();return false;"  value ="Start the Time Consuming Task!"   />
23 None.gif < div  id ="output"   ></ div >

最后是一段JavaScript启动那个较长时间才能完成的Web Service并让ProgressBar控件开始工作:


截图和下载

现在所有的事情都搞定了,可以运行了!

页面初始化:
progressbar_1.JPG

运行中:
progressbar_2.JPG

运行完成:
progressbar_3.JPG

 

示例程序以及源文件可以在这里下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值