原来的文章地址:
[原来的小说源码下载]
[翻译改后源码下载]

Introduction

[翻译]使用ASP.NET AJAX达成幻灯片效果

Most web-based slide show applications depend on a database for some or
all of the storage. This application allows you to show pictures from a
directory structure without any underlying database. The application
uses an ASP.NET 2.0 TreeView control for file system navigation and the
AJAX 1.0 SlideShow Extender (control) to display the images found in the
directory.

最早的作品发表日期:二零零五.05.27
作者:Bipin Joshi
翻译:webabcd

Required Software

介绍
一些合作社平日会有在web上机械地展现它们付加物的图纸(即幻灯片卡塔 尔(英语:State of Qatar)的急需。
当然你能够运用JavaScript来支付这几个顺序,不过意气风发旦应用ASP.NET
AJAX的话会让你的行事变得非常轻巧。 本文中,笔者将由此ASP.NET AJAX的page
methods和顾客端脚本扩充的扶助,来支付三个回顾的幻灯片程序。
这么些幻灯片能够由客商调整它的启幕和行车制动器踏板,暗中认可景况下它会循环呈现全体图片。
当然,顾客也得以对幻灯片实行手动操作。

  • Post a
    comment
  • Email
    Article
  • Print
    Article
  • 图片 1
    Share
    Articles图片 2

新建叁个SlideShow类
付出那一个幻灯片程序在此之前,大家先来新建二个启用了AJAX效能的web site。
然后增添三个名称叫JScript.js的JavaScript,在该文件内成立三个名为SildeShow的类,它的办事就是决定幻灯片的起来、截至和导航。
大家赖以了ASP.NET AJAX的客商端脚本扩充的扶助来支付那么些类,其代码如下:

In order to create this application, you need to install Microsoft
Visual Studio. I used Visual Studio 2005 Professional. You also need to
download the ASP.NET AJAX Extensions and the AJAX Control ToolKit found
at http://www.asp.net. These are two different
installs so make sure to get both. The version of AJAX you download must
be compatible with your version of Visual Studio and .NET Framework.
Since I’m using Microsoft Visual Studio 2005 and ASP.NET 2.0, I chose
ASP.NET 2.0 AJAX Extensions 1.0. There is only one download for the
Control Toolkit. If you are developing from an IIS website, as opposed
to a Visual Studio project, make sure the web site is in the correct
ASP.NET version. For my application, I choose 2.0.

图片 3Type.registerNamespace(“Demo”);
图片 4
图片 5Demo.SlideShow=function()
图片 6图片 7图片 8{
图片 9    this._slides=new Array();
图片 10    this._delay=2000;
图片 11    this._currentIndex=0;
图片 12    this._pause=false;
图片 13}
图片 14
图片 15Demo.SlideShow.prototype=
图片 16图片 17图片 18{
图片 19    get_Slides:function()
图片 20图片 21    图片 22{
图片 23        return this._slides;
图片 24    },
图片 25    
图片 26    set_Slides:function(value)
图片 27图片 28    图片 29{
图片 30        this._slides=value;
图片 31    },
图片 32    
图片 33    get_Delay:function()
图片 34图片 35    图片 36{
图片 37        return this._delay;
图片 38    },
图片 39    
图片 40    set_Delay:function(value)
图片 41图片 42    图片 43{
图片 44        this._delay=value;
图片 45    },
图片 46    
图片 47    get_CurrentIndex:function()
图片 48图片 49    图片 50{
图片 51        return this._currentIndex;
图片 52    },
图片 53    
图片 54    set_CurrentIndex:function(value)
图片 55图片 56    图片 57{
图片 58        if(value<0)
图片 59图片 60        图片 61{
图片 62            this._currentIndex=this._slides.length-1;
图片 63            return;
图片 64        }
图片 65        if(value>=this._slides.length)
图片 66图片 67        图片 68{
图片 69            this._currentIndex=0;
图片 70        }
图片 71        else
图片 72图片 73        图片 74{
图片 75            this._currentIndex=value;
图片 76        }
图片 77    },
图片 78    
图片 79    get_IsPaused:function()
图片 80图片 81    图片 82{
图片 83        return this._pause;
图片 84    },
图片 85    
图片 86    set_IsPaused:function(value)
图片 87图片 88    图片 89{
图片 90        this.pause=value;
图片 91    },
图片 92    
图片 93    Pause:function()
图片 94图片 95    图片 96{
图片 97        this._pause=true;
图片 98    },
图片 99    
图片 100    Play:function()
图片 101图片 102    图片 103{
图片 104        this._pause=false;
图片 105        window.setTimeout(“slideshow.ShowImage()”,
图片 106    this.get_Delay());
图片 107    },
图片 108    
图片 109    ShowFirst:function()
图片 110图片 111    图片 112{
图片 113        this._currentIndex=0;
图片 114        this.ShowImage();
图片 115    },
图片 116    
图片 117    ShowLast:function()
图片 118图片 119    图片 120{
图片 121        this._currentIndex=this._slides.length-1;
图片 122        this.ShowImage();
图片 123    },
图片 124    
图片 125    ShowNext:function()
图片 126图片 127    图片 128{
图片 129        var newIndex=this._currentIndex +1;
图片 130        this.set_CurrentIndex(newIndex);
图片 131        this.ShowImage();
图片 132    },
图片 133    
图片 134    ShowPrevious:function()
图片 135图片 136    图片 137{
图片 138        var newIndex=this._currentIndex -1;
图片 139        this.set_CurrentIndex(newIndex);
图片 140        this.ShowImage();
图片 141    },
图片 142    
图片 143    ShowImage:function()
图片 144图片 145    图片 146{
图片 147        var img=$get(“Image1”);
图片 148    if(img.style.visibility==”hidden”) 
图片 149图片 150    图片 151
图片 152    img.style.visibility=”visible”; 
图片 153    } 
图片 154        var slides=this.get_Slides();
图片 155        var curIndex=this.get_CurrentIndex();
图片 156        img.src=slides[curIndex];
图片 157        if(this.get_IsPaused()==false)
图片 158图片 159        图片 160{
图片 161            this.set_CurrentIndex(curIndex+1);
图片 162            this.Play();
图片 163        }
图片 164    }
图片 165}
图片 166
图片 167
图片 168Demo.SlideShow.registerClass(“Demo.SlideShow”);
图片 169
图片 170var slideshow=new Demo.SlideShow();

You may need to build the AJAX extensions or the AJAX Control ToolKit.
You will need to remember the location of the build Control Toolkit’s
binary: AjaxControlToolkit.dll. You will add this library as a reference
to your web project.

这段代码的开始部分注册了八个名称叫德姆o的命名空间。
然后创制了多少个名称为SildeShow的类。
在SildeShow类的构造函数内表明了4个成员变量。
_slides变量是一个数组,其内的成分就是图形的ULacrosseL。
_delay变量指明了图片转换的间距时间,单位是阿秒。
_currentIndex变量保存的是时下图片在_slides数组中的索引。
最终,_pause变量用来证明是不是暂停幻灯片的展示,暂停正是true,运维就是false。

A Quick Look at the Application

在SlideShow类的prototype中定义了4个属性,分别是Slides、Delay、CurrentIndex和IsPause,它们都有getter和setter。
看名就能够知道意思,笔者就不对这一个属性做过多的演说了,不过set_CurrentIndex()小编要好好表达一下。
这一个性子首先会检讨传来的值。
倘使值超过了Slides数组的界定,那会它会基于条件实行判别,设置该值为“0”或数组内成分总量减1。
其本质上正是让幻灯片能够循环播放。

The purpose of the application is, given a directory location, load and
display any pictures in that directory via the SlideShow. The
application is a single visual web page divided into two sections. The
left side of the page is the navigation provided by the ASP.NET 2.0
TreeView control tied to the file system. The right side of the page is
the Ajax SlideShow found in the Ajax Control Toolkit with some
description labels and control buttons below the image.

Pause()方法用于安装_pause变量为true。
调用那些办法会使幻灯片暂停止播放放。

图片 171

Play()方法用于运转幻灯片。
首先设置_pause变量为false,然后调用window的setTimeout()方法。
setTimeout()方法供给五个参数,分别是在钦命的延迟时间后要求实施的代码和延迟时间(单位:阿秒卡塔 尔(阿拉伯语:قطر‎。
在我们的那些例子中,延迟时间正是get_Delay()属性的值。
须求调用的代码正是ShowImage()方法。

The application is based on four main files: Default.aspx,
Default.aspx.cs, SlideService.asmx, and Web.Config. Default.aspx
contains the graphical elements and their default values.
Default.aspx.cs is the bulk of the work to control the navigation
via the TreeControl, the ClickThrough, the ViewState and QueryString.
SlideShow.asmx is the web service that the SlideShow Control relies
on. Web.Config holds all locations and names for the application.

ShowImage()方法是用来显示图片的。 它使用了CurrentIndex属性和Slides属性。
它从Slides数组中读取三个图纸路线,并设置给img标签的src属性。
注意,“Image1”是大家稍后将会追加的img标签的ID。
其余,注意一下我们使用的$get()方法,它相当于document.getElementById()方法。
Play()方法每被调用三次,CurrentIndex属性就能够自加1。
用这种措施,幻灯片就能反复地周而复始呈现。

Explanation of TreeView Structure Versus Web and File System

ShowFirst(),ShowLast(),ShowNext()和ShowPrevious()方法用于调节_currentIndex变量,进而调用ShowImage()方法彰显相关的图样。

The TreeView control displays and provides navigation for a hierarchical
structure of data. This can be any hierarchy. Since the TreeView control
is remarkable similar to the TreeView show in the file system
application of the operating system, it is an obvious choice for
navigation of any file system.

写完那么些类后,大家再用ASP.NET AJAX的registerClass()方法来注册那几个类。
最终,声美素佳儿(Friso卡塔尔个SlideShow类的全局变量。

The TreeView control in this article’s application has several
properties in each node to identify the node. The three most useful are
the Text, ValuePath, and the Value. The Text is what displays in the
tree, the directory name. For example, “Product Images”. The Value is
the web location of the location, for example, “/Images/Product/”. The
ValuePath is the location of the node as required by the TreeView
control, for example “/Images/|/Images/Product/”. The pipe character “|”
is the PathSeparator. It is important to set the PathSeparator instead
of taking the default which is “/”. You can see where the ValuePath of
“/Images///Images/Product/” would be easily confusing. When you use the
ValuePath to find the node again, the TreeView control will not find the
node using the default PathSeparator. In order to find the directory and
it’s child directories contained in the directory, the application uses
Server.MapPath to change from the web location of “/Images/Product/” to
“c:\project\Images\Product”. This may seem simple but you need to be
able to distinguish between these different address types while
debugging.

开发Web Form
在Visual Studio中新建一个web form。 确认保障页中有ScriptManager控件。
增加叁个两行一列的HTML表格。
在率先行中增多四个<img>标签,在第二行中增多6个HTML开关。
实现后的web form如下图所示:
图片 172

The SlideShow control, for this application, shows images in the
location contained in the ContextKey and is the same value as the
TreeView’s Value property. If the location of the SlideShow images did
not change, it would not be necessary to use the ContextKey.

像上海图书馆所示那样设置6个开关的value属性。

Control Location Example
TreeView.SelectedNode.Text Product
TreeView.SelectedNode.Value /Image/Product/
TreeView.SelectedNode.ValuePath /Image/|/Image/Product/
SlideShow.ContextKey /Image/Product/

接下去,选用ScriptManager控件,并设置它的EnablePageMethods属性为true。
然后,像如下那样增添JScript.js文件的引用。
图片 173

Introduction to SlideShow Web Service

创设一个用来回到图片URubiconL的web method
SlideShow类允许你利用Slides属性来钦点图片数组。
大家得以设置Slides属性为一个原则性的图纸链接数组。
可是,更妥当的不二等秘书诀是动态地从服务端得到图片链接数组。
那样您就足以回去三个遵照有个别条件转移的图纸链接数组,或然应付有些数据库驱动的逻辑。
为了落实那样的职能,大家来创建三个赶回图片链接数组的web method。 这几个web
method将被客商端的JavaScript调用。

The SlideShow extender on the Default.aspx page relies on
SlideService.asmx which returns an array of slides. This array contains
the location, title, and description of the images to show in the slide
show. The following XML is a returned Slide array:

转到web form的后置代码中,扩大如下所示的web method。

<?xml version="1.0" encoding="utf-8"?> <ArrayOfSlide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://MYDOMAINHERE.com/">     <Slide>         <ImagePath>images_15seconds.jpg</ImagePath>         <Name> images_15seconds</Name>         <Description />     </Slide>     <Slide>         <ImagePath> images_Blue hills.jpg</ImagePath>         <Name> images_Blue hills</Name>         <Description />     </Slide>     <Slide>         <ImagePath> images_Sunset.jpg</ImagePath>         <Name> images_Sunset</Name>         <Description />     </Slide>     <Slide>         <ImagePath> images_Water lilies.jpg</ImagePath>         <Name> images_Water lilies</Name>         <Description />     </Slide>     <Slide>         <ImagePath> images_Winter.jpg</ImagePath>         <Name> images_Winter</Name>         <Description />     </Slide> </ArrayOfSlide>

图片 174[WebMethod]
图片 175public static string[] GetSlides()
图片 176图片 177图片 178{
图片 179    string[] slides = new string[4];
图片 180
图片 181    slides[0] = “images/slide1.jpg”;
图片 182    slides[1] = “images/slide2.jpg”;
图片 183    slides[2] = “images/slide3.jpg”;
图片 184    slides[3] = “images/slide4.jpg”;
图片 185
图片 186    return slides;
图片 187}

The <ImagePath> must be a valid value or the SlideShow will not
display. The other tags of Name and Description can be empty.

GetSlides()是三个静态方法,并被标识了[WebMethod]本性。
它将赶回二个图片链接数组。
为了有支持,大家在示范程序中是通过硬编码得到数组的,你能够将它改为从数据库中取值。

You will notice that all images supplied with the sample application
have the directory name prefixed to the file name such as “images_Bull
Hills.jpg” above. This is done on purpose for easy debugging. The images
displayed should be prefixed by the TreeView.Value found in the selected
node.

用JavaScript调用GetSlides()方法
后天,大家供给用顾客端的JavaScript来调用上边的web
method,即GetSlides()方法。 转变来HTML源视图,并在web
form的<head>节点内加多四个<script>块,如下所示:

Complexities of the Slide Service

图片 188<script type=”text/javascript”>
图片 189function pageLoad()
图片 190图片 191图片 192{
图片 193    var img=$get(“Image1”); 
图片 194    img.style.visibility=”hidden”; 
图片 195    PageMethods.GetSlides(OnSuccess,OnError,OnTimeOut);
图片 196}
图片 197        
图片 198function OnSuccess(result)
图片 199图片 200图片 201{
图片 202    slideshow.set_Slides(result);
图片 203    slideshow.set_Delay(2000);
图片 204    slideshow.Play();
图片 205}
图片 206        
图片 207function OnError(result)
图片 208图片 209图片 210{
图片 211    alert(result.get_message());
图片 212}
图片 213
图片 214function OnTimeOut(result)
图片 215图片 216图片 217{
图片 218    alert(result);
图片 219}
图片 220</script>

The only job your service needs to perform is, given a valid web
directory, return a valid Slide array or NULL. In order to have a robust
service, the service needs to:

这段脚本内富含二个pageLoad()方法,只要web
from在客商端被加载,AJAX框架就能够自行地调用它。
它特别像ASP.NET里的Page_Load事件。在pageLoad()方法中,首先掩盖了图片。
然后经过内置的PageMethods类的相助,调用了GetSlides()方法。 在ASP.NET
AJAX中,全数的实行都以异步的,所以GetSlides()方法是有回调函数的,何况其回调函数分别会在试行成功、出错或超时的时候被调用。

  1. check that the web directory exists with Directory.Exists
  2. check that the image extensions are valid for this application by
    comparing the extension again a list in web.config
  3. return a valid image listed in web.config if no images are found in
    the directory

OnSuccess()函数接受二个经过GetSlides()方法重临的字符串数组为参数,然后设置SlideShow类的Slides属性。
再往下是设置幻灯片的延迟时间为二零零三皮秒。
最终,它调用SlideShow类的Play()方法来从前运维幻灯片。

Create Web Application

OnError()和OnTimeOut()分别用于突显错误新闻。

In Visual Studio, create a new AJAX enabled web application.

接下去,像上边那样改正button标识:

图片 221

图片 222<input id=”Button1″ 图片 223 onclick=”slideshow.ShowFirst()” />
图片 224<input id=”Button2″ 图片 225 onclick=”slideshow.ShowPrevious()” />
图片 226<input id=”Button5″ 图片 227 onclick=”slideshow.Pause()”/>
图片 228<input id=”Button6″ 图片 229 onclick=”slideshow.Play()”/>
图片 230<input id=”Button3″ 图片 231 onclick=”slideshow.ShowNext()” />
图片 232<input id=”Button4″ 图片 233 onclick=”slideshow.ShowLast()”/>

Add the AjaxControlToolkit.dll to the project as a reference.

你能够观察,button的onclick事件分别调用对应的SlideShow类的方式。

Create SlideService.asmx

便是那么些东西,非常粗略吗。 运转那一个web
form,你就能够在浏览器中观望我们的幻灯片。

Add a web service file named SlideService.asmx. Change the supplied
“Hello World” function to the following:

作者:Bipin Joshi
Email:
简要介绍:Bipin
乔希i是DotNetBips.com的管理员。他是的提议者,这一个公司提供.NET
framwork的培养练习和咨询服务。他在India芝加哥为开垦者提供培养练习。他也是微软的MVP(ASP.Net)和ASPInsiders的会员。

[WebMethod]     public AjaxControlToolkit.Slide[] GetSlides(String contextKey)     {         return null;     }

The function name is GetSlides. The parameter is contextKey of type
String. You can use contextKey in anyway you want, it is meant to pass
information from the calling AJAX control to the web service. In this
application, the parameter will be used to supply the directory for the
slide show to be fed from. The return parameter is an array of Slides.
The AJAX SlideShow control looks for this signature and the signature is
case sensitive and exact. Don’t try to change any of this syntax or your
service not be called.

Add the following keys to Web.Config:

<add key="SlideServiceNoImagesFoundLocation" value="NoImagesFound.jpg"/>     <add key="SlideServiceValidImageExtensions" value="jpg,gif,bmp,ico"/>

The first key provides a web location for an image to display in the
slide show when no images are found in the directory specified in the
contextKey parameter. In this case, the location is the root of the web
site. The second parameter is a list of valid extensions in the
directory to return in the slide array.

In the above example, I have provided an image titled
“NoImagesFound.jpg” which you will find in this articles’ download
package. The image is displayed as used in the application below:

图片 234

The function for NoImagesFound is below and is called from GetSlides():

private AjaxControlToolkit.Slide[] GetNoImagesFoundDirectory()     {         AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[1];         // get image from web.config and verify it exists on file system         _noImagesFoundWebLocation = System.Configuration.ConfigurationSettings.AppSettings.Get("SlideServiceNoImagesFoundLocation");         if (!File.Exists(Server.MapPath(_noImagesFoundWebLocation)))             throw new Exception("SlideService.asmx::GetNoImagesFoundDirectory - NoImagesFoundLocation found in web.config does not exist after server.mappath - " + Server.MapPath(_noImagesFoundWebLocation));         // create slide from image         slides[0] = new AjaxControlToolkit.Slide(_noImagesFoundWebLocation, "No Images Found: Please click on another directory", "");         // return slide         return (slides);     }

This GetNoImagesFoundDirectory function creates a Slide array of one
element. It grabs the image file location from Web.Config then verifies
that the file does exist. It then adds the image into the Slide array
with the title to indicate that the user should click on another
directory.

Two functions that are called from GetSlides() that are not provided in
this article but are provided in the articles’ download are IsImage()
and GetImageExtensionsFromWebConfig().

The function for GetSlides() is below:

[WebMethod]     public AjaxControlToolkit.Slide[] GetSlides(String contextKey)     {         // get valid extensions         GetImageExtensionsFromWebConfig();         // contextKey not empty         if (String.IsNullOrEmpty(contextKey))             return null;         // contextKey in scope         if ((contextKey.IndexOf("..")>=0))             return null;         // verify contextKey directory exists         String mapPath = Server.MapPath(contextKey);         if (!Directory.Exists(mapPath))             throw new Exception("SlideService.asmx::GetSlides - mapPath does not exist - " + Server.MapPath(mapPath));         // get files in contextKey directory         string[] fileNames = System.IO.Directory.GetFiles(mapPath);         if (fileNames.Length == 0)             return GetNoImagesFoundDirectory();         // create generic empty list of slides         List<AjaxControlToolkit.Slide> list = new List<AjaxControlToolkit.Slide>();         String justFileName;         String displayedFileTitleOnSlider;         String displayedFileDescriptionOnSlider;         for (int i = 0; i < fileNames.Length; i++)         {             if(IsImage(Path.GetExtension(fileNames[i])))             {                 // get complete filename                 justFileName = Path.GetFileName(fileNames[i]);                 // get title                 displayedFileTitleOnSlider = Path.GetFileNameWithoutExtension(fileNames[i]);                 // set description to empty                 displayedFileDescriptionOnSlider = String.Empty;                 // add file to list of slides                 list.Add(new AjaxControlToolkit.Slide(contextKey + justFileName, displayedFileTitleOnSlider, displayedFileDescriptionOnSlider));             }         }         return (list.ToArray());     }

This GetSlides() function gets the valid file extensions from Web.Config
and validates that contextKey is not empty and is not trying to go
outside of the scope of this application for security. Then the
application changes the contextKey from its web location to the physical
location on disk via Server.MapPath and ensures its existence. Next the
function grabs all files in the directory into a string array. If there
are no filenames in the string array, the function returns the
NoImagesFound image via the GetNoImagesFoundDirectory() function. Then
the function creates an empty list of slides via generics. Then the
files names are looped, looking for valid extensions. Each file name
with a valid extension is added to the slide array. The file name minus
the extension is the slide show image title. The slide show image
description is empty.

Add the following class variables:

String _noImagesFoundWebLocation; //path and file of the image containing "No Images Found" text     String _arrayOfImageExtensions; //string of valid image file extensions without "." in the value ex "jpg,gif"     String[] _extensionList; //string array of valid image file extensions without "." and with comma removed

Add the following references:

using System.Web.UI.WebControls;     using System.Diagnostics;     using System.IO;     using System.Configuration;     using System.Collections.Generic;

Add this to the declarations above the GetSlides function:

[System.Web.Script.Services.ScriptService()]

When you are done, test the service in the browser by calling the web
service page directly: SlideService.asmx.

图片 235
(Full Size
Image)

Ensure that the results are in the following format:

<Slide>         <ImagePath>Blue hills.jpg</ImagePath>         <Name>Blue hills</Name>         <Description />     </Slide>

A Word of Caution

Do not move on to the web page until you are sure the slide service is
returning the right data in the right format. When you build and test
your web page, it will be nice to know that the slide service is not
part of any bugs that pop up. The AJAX Slide Service control will not
inform you when you are using it wrong or passing it malformed data from
the slide service. It just won’t work.

Introduction to TreeView

The TreeView control is a standard navigation control provided in
System.Web.UI.WebControls namespace. The default start location of the
TreeView control is stored in the TreeViewDefaultStartLocation key
in the Web.Config. This location is the root of the control. All other
nodes are added by crawling through the child directories in code.

We need to add code to:

  1. given a selected node, pass the node’s ValuePath as the contextKey
    to the web service
  2. given a location off the node passed in by query string, find the
    selected node and pass it’s ValuePath as the contextKey to the web
    service

The TreeView control has a concept of a selected node. Each node with
children will have a selection icon such as a + sign. This indicates the
node has children. Clicking on the plus sign is not “selecting” the node
but just navigation through the nodes. Once you click on the name of the
directory, you have selected it. The SlideShow will only change images
on node selection, not on tree navigation.

Introduction to the AJAX Slide Show

The AJAX Slide Show control is a member of the AJAX control toolkit
found in AJAXControlToolkit.dll. It displays images from a location
found via a web path. The Slide Show control must know where to find the
slide web service. This parameter is stored in the Web.Config in the
SlideShowWebServiceLocation key and is a web path and file name. One
of the parameters for the control is the location of the slide web
service that the slide show uses. This is stored in the Web.Config file
in the SlideShowDefaultLocation. Another parameter is the first file
to load. This allows the slide show to display an image while the web
service is building the array of slides. This value is stored in the
Web.Config in the SlideShowDefaultLocationFirstPicture key.

If you are using a single directory of images, you can set all the
necessary values for the Slide Show in the control’s parameters. You do
not need to add any script/code. Since this application does change
directories, some of the Slide Show parameters will be set in the code
behind file.

Modify Web Page

In the default.aspx, add an AJAX Script Manager:

<asp:ScriptManager ID="ScriptManager1" runat="server" />

The script manager is provided from the AJAX Extensions library.

Then add a TreeControl from the navigation tab of the toolbox. Change
the default control from:

<asp:TreeView ID="TreeView1" runat="server">     </asp:TreeView>

to:

<asp:TreeView ID="TreeView1" runat="server"         ExpandDepth=1         ShowExpandCollapse=true         OnSelectedNodeChanged="TreeView1_OnSelectedNodeChanged"         PathSeparator="|"         EnableViewState=true         SelectedNodeStyle-Font-Bold=true         SelectedNodeStyle-ForeColor=red     />

The two most important parameters are the OnSelectedNodeChanged and the
PathSeparator. The OnSelectedNodeChanged will call the slide service for
a new array of slides to display. The PathSeparator has already been
discussed.

Add an Image control which is where the Slide Show will display the
images:

<asp:Image ID="imgPhotos" runat="server" Height="300" Style="width:auto; border:solid 1px #000000;" />

Add the SlideShow Extender (control) from the AJAX control toolkit.
Change the default control from:

<cc1:SlideShowExtender ID="SlideShowExtender1" runat="server">     </cc1:SlideShowExtender>

to:

<cc1:SlideShowExtender ID="SlideShowExtender1" runat="server"         TargetControlID="imgPhotos"         SlideShowServiceMethod="GetSlides"         SlideShowServicePath="/SlideService.asmx"         ContextKey="images/"         UseContextKey=true         AutoPlay="true"         NextButtonID="btnNext"         PlayButtonText="Play"         StopButtonText="Stop"         PreviousButtonID="btnPrev"         PlayButtonID="btnPlay"         Loop="true"         ImageTitleLabelID=lblTitle         ImageDescriptionLabelID=lblDescription     />

The TargetControlId is where the slide show images will appear. You will
also need buttons for Prev, Stop, and Next functionality as well as the
Title and Description of the images. In this application, the title is
used as the title of the file but the description is used to display the
path of the file for debugging purposes. The LabelClickthroughURL is
used to be able to test TreeView control navigation from a querystring.
An example of this is to send a link to a non-root node via email.

Add the following label controls below the Slide Show:

<center><asp:Label ID="lblTitle" runat=server></asp:Label></center><br />     <asp:Label ID="LabelTreeSelectedNode" runat=server></asp:Label><br />     <asp:Label ID="LabelClickthroughURL" runat=server></asp:Label><br />     <asp:Label ID="lblDescription" runat=server></asp:Label><br />     <center>     <asp:Button ID="btnPrev" Text="Prev" runat="server" />     <asp:Button ID="btnPlay" Text="Play" runat="server" />     <asp:Button ID="btnNext" Text="Next" runat="server" />     </center>

Default.aspx.cs

The main work of the code behind file is to fill the TreeView control,
find the correct node, and handle selection of the node.

Add the following library to the default.aspx to handle file and
directory management:

using System.IO;

The Page_Load function and the TreeView1_OnSelectedNodeChanged
function are the two main functions in the default.aspx.cs. The rest of
the functions will be lightly discussed here but are supplied in full in
this article’s download.

The Page_Load function is below:

protected void Page_Load(object sender, EventArgs e)     {         GetWebConfigSettings();         VerifyDirectoriesAndFiles();         // SET first image         imgPhotos.ImageUrl = _slideShowDefaultLocation + _slideShowDefaultLocationFirstPicture;         imgPhotos.AlternateText = _slideShowDefaultLocation + _slideShowDefaultLocationFirstPicture;         // set web service path         SlideShowExtender1.SlideShowServicePath = _slideShowWebServiceLocation;         SlideShowExtender1.ContextKey = _slideShowDefaultLocation;         // don't add copy of tree to tree on postback         if (TreeView1.Nodes.Count == 0)             PopulateTree();         // Set From QueryString or ViewState         if ((!String.IsNullOrEmpty(_currentTreePathQueryStringName)) && ((Request[_currentTreePathQueryStringName] != null) || (ViewState[_currentTreePathQueryStringName] != null)))             SelectNodeBasedOnQueryStringOrViewState();         // else assume first time to page         else         {             // first time to page             if (!String.IsNullOrEmpty(_slideShowDefaultLocation))             {                 ExpandTreePathByDirPath();             }         }         // set labels so that selected info is visible on page         //LabelTreeSelectedNode.Text = "<b>SlideShowExtender1.ContextKey:</b>" + SlideShowExtender1.ContextKey;         if (String.IsNullOrEmpty(LabelClickthroughURL.Text))         {             LabelClickthroughURL.Text = "<a href='mailto:?subject=Picture SlideShow from the Berrys&amp;Body=" + HttpContext.Current.Request.Url + "?" + _currentTreePathQueryStringName + "=" + Server.UrlEncode(_slideShowDefaultLocation) + "'>Send link to this page by email</a><br>";         }     }

The first two lines get directories and image information from the
Web.Config, then verify their existence. The next two lines get the
first image for the Slide Show. This is the image that is displayed
while the Slide Show service is called and processed. It could be
anything from a “please wait…” image to no image at all. The next line
tells the Slide Show where to find the service it is to use to get the
list of slides. The next couple of lines populate the TreeView control
as long was the TreeView control isn’t already populated. This is
important for postback. The next section of lines determines which node
in the TreeView control should be set as selected (and therefore
highlighted in red) based on ViewState or QueryString. This is useful
when you want to send the URL to someone and you want the TreeView to
load from an interior node when they click on the link. The last line
displays the current context key into a Label on the page for debugging
purposes.

The TreeView1_OnSelectedNodeChanged function is below:

protected void TreeView1_OnSelectedNodeChanged(object sender, EventArgs e)     {         // DFB: Get Location of Node Selected used by TreeView to find a node         _currentTreePath = TreeView1.SelectedNode.ValuePath;         //lblDescription.Text = "<b>Selected ValuePath :</b>" + _currentTreePath ;         // DFB: Get Location of web Directory         SlideShowExtender1.ContextKey = TreeView1.SelectedNode.Value;         //LabelTreeSelectedNode.Text = "<b>SlideShowExtender1.ContextKey:</b> " + SlideShowExtender1.ContextKey +         // "<br><b>Server.MapPath(ContextKey)</b>:" + Server.MapPath(SlideShowExtender1.ContextKey);         // DFB: If Path is not empty, add it to state so we have it on postback         if (!String.IsNullOrEmpty(_currentTreePath))         {             ViewState.Add(_currentTreePath, _currentTreePath);             LabelClickthroughURL.Text = "<a href='mailto:?subject=Picture SlideShow from the Berrys&Body=" + HttpContext.Current.Request.Url + "?" + _currentTreePathQueryStringName + "=" + Server.UrlEncode(_currentTreePath) + "'>Send link to this page by email</a><br>";         }     }

This function is called when the name of a directory is clicked on, not
when the expand/contract sign to the left of the name of the directory
is clicked on. This selection of the directory name indicates that all
valid images (as defined in Web.config) should be found (via the web
service) and loaded into the Slide Show control or the “No Image Found”
image should be loaded.

The first two lines of the function grab the ValuePath and place it
in a label on the page. The next couple of lines get the Value of
the directory. This value is the new contextKey for the Slide Service
and is placed in a label on the page. The next section of text adds the
selected ValuePath to the ViewState and uses it to build a link that you
could send someone to get back to this current node’s display in the
Slide Show.

Once you have the default.aspx and default.aspx.cs written, make sure
you have a working web service and valid values in the Web.Config.

Summary

Build your Slide service first and make sure it returns valid
information. The function signature is exact, don’t change the
characters or case. Next build the default.aspx and the code behind page
by adding a TreeView for navigation and the AJAX Slide Show for viewing.

相关文章