Rank: Advanced Member
Joined: 4/01/2009(UTC) Posts: 37 Location: Taipei, Taiwan
|
Finally, I made the slideshow to work. The design didn't follow you suggestion, sorry. It took me several days to try to figure out the relationship among Gallery.cs , GalleryPage.cs , MediaObject.ascx ...... it's too difficult for my current programming capability, but I did learn a lot. I used part of the suggested archietecture and codes, used javascript to do most work. A slideshow.asmx to feed image urls. This is based on the assumption that to-be-displayed images are external images. and also a modified database table and mediaobject properties ... After loading image urls from slideshow.asmx , the browser makes no request to the server while the user doing operations on the page (pre, next, pause, play, increase/decrease sec ... etc). This is my first javascript practice. The user experience is not as good as Flickr's flash slideshow. For example, Flickr's flash slideshow can be embeded in any web site, can be in real fullscreen ... etc. Javascript is limited and hated by browsers somehow; and sometimes it needs different codes for different browsers; and also it can be blocked by browsers by default. slideshow.aspx.cs Code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using GalleryServerPro.Business; using GalleryServerPro.Business.Interfaces; using GalleryServerPro.Configuration; using GalleryServerPro.ErrorHandler.CustomExceptions; using GalleryServerPro.Web.Entity; using GalleryServerPro.Web; using marty1101.GSP; using marty1101.WebControls;
namespace GalleryServerPro.Web.Controls { public partial class slideshow : System.Web.UI.UserControl { #region Private Fields
private IAlbum _album; private Message _message = Message.None; private IGalleryServerRoleCollection _roles; private string _pageTitle = String.Empty; private bool? _isAnonymousUser; private int[] _moids = { }; private string _ReferringUrl = string.Empty; private static GspUrl.RootAspxPageId _thisAspxPage = GspUrl.RootAspxPageId.SlideShowAspxPage; private string _galleryAspxPagePathFile = GspUrl.GetRootAspxPagePathFile(_thisAspxPage, GspUrl.RootAspxPageId.GalleryAspxPage); private bool _includingSubFolders = false; private string _GspPath = "/album"; // variables for JavaScript use private bool _autoplay = true; // auto-play at page load private bool _repeat = true; // repeat slideshow cycle private int _interval = 4000; private int _timeout_sec = 30; // if a image is not loaded within, go to the next image. private int _preload_batch = 3; // At each slide change, we preload 'preload_batch' images more into the browser cache. private string _progressGifUrl = Util.GalleryRoot + "/images/progressbar.gif"; private string _loadingGifUrl = Util.GalleryRoot + "/images/loading.gif"; private int _topbarMinHeight = 35; // for calculating the image container size private string _pauseButtonTextPause = Resources.GalleryServerPro.SlideShow_PauseButton_Text_Pause; private string _pauseButtonTextPlay = Resources.GalleryServerPro.SlideShow_PauseButton_Text_Play;
private string ReferringUrl { get { if (_ReferringUrl == string.Empty) return GetReferringUrl(); else return _ReferringUrl; } set { _ReferringUrl = value; } }
#endregion
#region Private Properties
private bool IsAnonymousUser { get { if (!this._isAnonymousUser.HasValue) { this._isAnonymousUser = !HttpContext.Current.User.Identity.IsAuthenticated; } return this._isAnonymousUser.Value; } }
private Message Message { get { if (this._message == Message.None) { int msgId = Util.GetQueryStringParameterInt32("msg"); if (msgId > int.MinValue) { this._message = (Message)Enum.Parse(typeof(Message), msgId.ToString(CultureInfo.InvariantCulture)); } } return this._message; } set { this._message = value; } }
#endregion
#region Public Properties
public virtual string PageTitle { get { if (_album == null) return Resources.GalleryServerPro.SlideShow_PageTitle; else return Util.RemoveHtmlTags(_album.Title); } set { this._pageTitle = value; } }
#endregion
#region Protected Events
protected void Page_PreRender(object sender, EventArgs e) { HtmlHead header = this.Page.Header; if (header == null) throw new WebException(Resources.GalleryServerPro.Error_Head_Tag_Missing_Server_Attribute_Ex_Msg); SetupHeadControl(header); }
protected override void Render(System.Web.UI.HtmlTextWriter writer) { writer.AddAttribute("class", "gsp_ns"); // gsp_ns stands for Gallery Server Pro namespace writer.RenderBeginTag(HtmlTextWriterTag.Div); base.Render(writer); writer.RenderEndTag(); }
protected string GetReferringUrl() { return ParseReferringUrl(Util.GetQueryStringParameterString("ReturnUrl")); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ShowWarningPanel(false); ReferringLB.PostBackUrl = ReferringUrl; ReferringLB.ToolTip = Resources.GalleryServerPro.SlideShow_ReferringUrl_Tooltip; LogoIB.PostBackUrl = _galleryAspxPagePathFile; LoadingImageDiv.Style.Add(HtmlTextWriterStyle.BackgroundImage, _loadingGifUrl); MinusButton.ToolTip = Resources.GalleryServerPro.SlideShow_MinusButton_Tooltip; PlusButton.ToolTip = Resources.GalleryServerPro.SlideShow_PlusButton_Tooltip; PreviousButton.ToolTip = Resources.GalleryServerPro.SlideShow_PreviousButton_Tooltip; PauseButton.ToolTip = Resources.GalleryServerPro.SlideShow_PauseButton_Tooltip; NextButton.ToolTip = Resources.GalleryServerPro.SlideShow_NextButton_Tooltip;
string mode = Util.GetQueryStringParameterString("mode"); switch (mode) { default: { _album = GetAlbum(); AlbumMode_Validate();
if (_album != null) { AlbumLB.Text = _album.Title; AlbumLB.PostBackUrl = _galleryAspxPagePathFile + "?g=album&aid=" + _album.Id.ToString(); if (Util.GetQueryStringParameterBoolean("sub") == true) _includingSubFolders = true; else _includingSubFolders = false;
Gsp.SlideShow s = new Gsp.SlideShow(); int[] moids = s.GetMOIDs(_album.Id, _includingSubFolders); if (moids != null) { if (moids.Length > 0) { if (Util.GetQueryStringParameterBoolean("autoplay") == false) { _autoplay = false; } else { _autoplay = true; } RegisterJavaScript(_album.Id); } else { ShowErrorMessage(Message.MediaObjectDoesNotExist); } } } break; } }
} } #endregion
#region Protected Methods
[DataObjectMethod(DataObjectMethodType.Select)] protected IGalleryServerRoleCollection GetGalleryServerRolesForUser() { if (this._roles == null) { this._roles = Util.GetRolesForUser(); }
return this._roles; }
[DataObjectMethod(DataObjectMethodType.Select)] protected static IGalleryServerRoleCollection GetGalleryServerRoles() { return Factory.LoadGalleryServerRoles(); }
protected string ParseReferringUrl(string ReferringUrl) { ReferringUrl = Server.UrlDecode(ReferringUrl); try { Uri ReturnUri = new Uri(ReferringUrl); } catch (Exception ex) { ReferringUrl = _galleryAspxPagePathFile + "?g=album"; }
return ReferringUrl; }
protected string ParseReturnUrl(string ReturnUrl) { try { Uri ReturnUri = new Uri(ReturnUrl); } catch (Exception ex) { ReturnUrl = _galleryAspxPagePathFile + "?g=album"; }
return Server.UrlEncode(ReturnUrl); }
protected void RedirectToLoginPage() { string ReturnUrl = (HttpContext.Current.Request.Url).AbsoluteUri; ReturnUrl = ParseReturnUrl(ReturnUrl); // This is GSP's login page //string url = string.Format("{0}?g={1}&ReturnUrl={2}", _galleryAspxPagePathFile, PageId.login, ReturnUrl);
// This is CS2008.5's login page string LoginUrl = HttpContext.Current.Request.FilePath; // http://localhost:16800/GSP_Source/album/slideshow.aspx LoginUrl = LoginUrl.Replace(GspUrl.GetRootAspxFilename(_thisAspxPage), ""); // http://localhost:16800/GSP_Source/album/ LoginUrl = LoginUrl.Replace(_GspPath, ""); // http://localhost:16800/GSP_Source/ LoginUrl = LoginUrl + "login.aspx?ReturnUrl=" + ReturnUrl; // http://localhost:16800/GSP_Source/login.aspx?ReturnUrl= +ReturnUrl
System.Web.HttpContext.Current.Response.Redirect(LoginUrl, true); }
protected void AlbumMode_Validate() //If no error, no redirect happens, and we get a viewable _album { if (!Util.GetGalleryServerProConfigSection().Core.AllowAnonymousBrowsing && this.IsAnonymousUser) { // when AllowAnonymousBrowsing=false AND user is not logged in, redirect to login page RedirectToLoginPage(); } else { // no matter if the user is logged in or not, permission has to be checked to see if this album is viewable by this user. if (_album == null) { ShowErrorMessage(Message.AlbumDoesNotExist); } else { if (!Util.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, GetGalleryServerRolesForUser(), _album.Id, _album.IsPrivate)) { if (IsAnonymousUser) // If this album can not be view by anonymous, direct to login page. { RedirectToLoginPage(); } else // This use is logged in, but has no permission to view this album. { ShowErrorMessage(Message.InsufficientPermissionCannotViewAlbum); } } } } }
protected void ShowWarningPanel(bool show) { if (show) { Panel1.Visible = false; TopbarRightPanel.Visible = false; WarningPanel.Visible = true; } else { Panel1.Visible = true; TopbarRightPanel.Visible = true; WarningPanel.Visible = false; } }
protected void ShowErrorMessage(Message err) { ShowWarningPanel(true); switch (err) { case Message.AlbumDoesNotExist: { WarningLabel.Text = Resources.GalleryServerPro.SlideShow_ErrorMessage_AlbumDoesNotExist; break; } case Message.InsufficientPermissionCannotViewAlbum: { WarningLabel.Text = Resources.GalleryServerPro.SlideShow_ErrorMessage_InsufficientPermissionCannotViewAlbum; break; } case Message.MediaObjectDoesNotExist: { WarningLabel.Text = Resources.GalleryServerPro.SlideShow_ErrorMessage_MediaObjectDoesNotExist; break; } default: { WarningLabel.Text = Resources.GalleryServerPro.SlideShow_ErrorMessage_UnhandledError; break; } } }
private void SetupHeadControl(HtmlHead head) { if (String.IsNullOrEmpty(head.Title)) head.Title = PageTitle; head.Controls.Add(MakeStyleSheetControl(Util.GetUrl("/styles/slideshow.css"))); }
protected void RegisterJavaScript(int aid) {
string scriptUrl1 = Util.GetUrl("/script/jquery-1.3.2.js"); string scriptUrl2 = Util.GetUrl("/script/marty1101.js"); ScriptManager sm = ScriptManager.GetCurrent(this.Page); if (sm != null) { sm.Scripts.Add(new ScriptReference(scriptUrl1)); sm.Scripts.Add(new ScriptReference(scriptUrl2)); } else throw new WebException("Slideshow requires a ScriptManager on the page.");
string script = string.Empty;
/// ================ /// Initial set-up /// ================ script = string.Format(CultureInfo.InvariantCulture, @" var PhotoClientID = '{0}'; var LoadingImageDivClientID = '{1}'; var topbar_minHeight = {2}; var image_control = document.getElementById(PhotoClientID); var windowInnerSize = GetWindowInnerSize();
function ShowProgressBar(show) {{ var progressDiv = document.getElementById('progressDiv'); if (show) progressDiv.style.display = ''; else progressDiv.style.display = 'none'; }}
function ShowPhoto(show) {{ if (show) image_control.style.display = ''; else image_control.style.display = 'none'; }}
ShowProgressBar(true); ShowPhoto(false);
if (windowInnerSize.width < screen.availWidth*0.93 || windowInnerSize.height < screen.availHeight*0.8) MaximizeWindow(); " , Photo.ClientID // 0 , LoadingImageDiv.ClientID // 1 , _topbarMinHeight // 2 );
/// ================================ /// call Gsp.SlideShow Web Service /// ================================ script += string.Format(CultureInfo.InvariantCulture, @" var aid = {0}; var includingSubFolders = {1}; var _moids; var _moObjects; var errMediaObjectDoesNotExist = '{2}'; var errConnection = '{3}';
Gsp.SlideShow.GetMOIDs(aid, includingSubFolders, GetMOIDsCompleted, GetMOIDsFailure);
function GetMOIDsCompleted(results, context, methodName) {{ _moids = results; if (_moids == null) {{ alert(errMediaObjectDoesNotExist); }} else {{ Gsp.SlideShow.GetImages(_moids, GetImagesCompleted, GetImagesFailure); }} }}
function GetMOIDsFailure(error, context, methodName) {{ // alert(""GetMOIDs() "" + error.get_exceptionType() + "": "" + error.get_message()); alert(errConnection); }}
function GetImagesCompleted(results, context, methodName) {{ _moObjects = results; slideshow_init(); }}
function GetImagesFailure(error, context, methodName) {{ // alert(""GetImages() "" + error.get_exceptionType() + "": "" + error.get_message()); alert(errConnection); }} " , _album.Id // 0 , _includingSubFolders.ToString().ToLower() // 1 , Resources.GalleryServerPro.SlideShow_ErrorMessage_AlbumDoesNotExist // 2 , Resources.GalleryServerPro.SlideShow_ErrorMessage_NetworkError // 3 ); ScriptManager.RegisterStartupScript(this, this.GetType(), "call_Gsp.SlideShow_webservice" + Guid.NewGuid().ToString(), script, true);
/// =============================== /// jQuery_preloadImages function /// =============================== script = string.Format(CultureInfo.InvariantCulture, @" jQuery.preloadImages = function() {{ for(var i = 0; i<arguments.length; i++) {{ jQuery('<img>').attr('src', arguments[i]); }} }} "); ScriptManager.RegisterStartupScript(this, this.GetType(), "jQuery_preloadImges" + Guid.NewGuid().ToString(), script, true);
/// ========================== /// SlideShow Initialization /// ========================== script = string.Format(CultureInfo.InvariantCulture, @" // Set global variables var GalleryAspxFilePath = '{0}'; var play = {1}; var interval = {2}; var loadingGifUrl = '{3}'; var repeat = {4}; var timeout_sec = {5}; var referringUrl = '{6}'; var PauseButtonTextPause = '{7}'; var PauseButtonTextPlay = '{8}'; var MinusButtonClientID = '{9}'; var PlusButtonClientID = '{10}'; var PreviousButtonClientID = '{11}'; var PauseButtonClientID = '{12}'; var NextButtonClientID = '{13}'; var slide_index = 0; var still_loading = false; var NumberOfCheckingLoadingFailed = 0; var NumberOf_moObjects = 0; var intervalID; var preloaded = new Array(); var preload_index = 1; var preload_batch = {14};
function slideshow_init() {{ document.onkeydown = KeyDownHandler;
if (_moObjects == null) // If there is no image, stop @here {{ alert(errMediaObjectDoesNotExist); }} else {{ image_control.onload = function() {{ still_loading = false; }} // This tells if a image is completed loaded. ShowIntervalSecond(interval);
still_loading = false; NumberOf_moObjects = _moObjects.length; SetPauseButtonText(play);
for (i = 0; i < NumberOf_moObjects; i++) {{ preloaded[i] = false; }}
//CalculateContainerSize(); // Get sizes of the current window. ShowFirstImage(); // Starts cycle }} }}
function ShowIntervalSecond(i) {{ document.getElementById('Interval_text').innerHTML = roundNumber(i / 1000, 0); }}
function PreLoadImages(_moObjects, start_index, end_index) {{ if (end_index >= NumberOf_moObjects) {{ end_index = NumberOf_moObjects-1; }} if (start_index <= end_index) {{ for (i = start_index; i <= end_index; i++) {{ if (!preloaded[i]) {{ // if (_moObjects[i].ThumbnailUrl != null) {{ $.preloadImages(_moObjects[i].ThumbnailUrl); }} // else {{ alert('_moObjects[i].ThumbnailUrl is null in function PreLoadImages() !'); }} if (_moObjects[i].ImageUrl != null) {{ $.preloadImages(_moObjects[i].ImageUrl); }} // else {{ alert('$.preloadImages(_moObjects[i].ImageUrl is null in function PreLoadImages() !'); }} preloaded[i] = true; }} }} }} }}
function SetPauseButtonText(play) {{ var obj = document.getElementById(PauseButtonClientID); if (play) {{ obj.value = PauseButtonTextPause; obj.style.backgroundColor = '#FA3250'; }} else {{ obj.value = PauseButtonTextPlay; obj.style.backgroundColor = '#99FF99'; }} }}
function CalculateContainerSize() {{ var windowInnerSize = GetWindowInnerSize(); container_width = floorNumber(windowInnerSize.width * 0.9 , 0); container_height = floorNumber((windowInnerSize.height - topbar_minHeight)* 0.9 , 0); //height of the top banner }}
function StopTimer() {{ if (intervalID != undefined) {{ clearInterval(intervalID); }} }}
function RestartTimer() {{ StopTimer(); if (play) {{ intervalID = setInterval('SlideshowCycle()', interval); }} }}
function StopSlideshowCycle() {{ StopTimer(); play = false; SetPauseButtonText(play); }}
function ShowCounter(i) {{ document.getElementById('slideshow_topbar_counter').innerHTML = i + '/' + NumberOf_moObjects; }}
function RenderImage(_moObject) {{ if (_moObject == null && !AdvanceSlideIndex(repeat)) {{ StopSlideshowCycle(); }} else {{ ShowCounter(slide_index+1); // CalculateContainerSize(); // display_width = _moObject.ImageWidth; // display_height = _moObject.ImageHeight;
// if (display_width > container_width) // {{ // display_height = floorNumber( display_height * (container_width / display_width) , 0); // display_width = container_width; // }} // // if (display_height > container_height) // {{ // display_width = floorNumber( display_width * (container_height / display_height) , 0); // display_height = container_height; // }}
still_loading = true; image_control.alt = _moObject.Title; image_control.src = _moObject.ImageUrl; // image_control.width = display_width; // image_control.height = display_height;
document.getElementById('Title').innerHTML = _moObject.Title; document.getElementById('moidUrl').href = GalleryAspxFilePath + ""?g=mediaobject&moid="" + _moObject.moid;
if (slide_index > preload_index) {{ var start_index = slide_index - preload_batch; if (start_index <= 0) {{ start_index = 0; }} var end_index = slide_index + preload_batch; if (end_index > NumberOf_moObjects-1) {{ end_index = NumberOf_moObjects-1}} PreLoadImages(_moObjects, start_index, end_index); }}
if (preload_index < NumberOf_moObjects) {{ preload_index += preload_batch; PreLoadImages(_moObjects, preload_index-preload_batch+1, preload_index); }} }} }}
function ShowFirstImage() {{ ShowProgressBar(false); ShowPhoto(true);
slide_index = 0; RenderImage(_moObjects[slide_index]); if (NumberOf_moObjects <=1) SetPauseButtonText(false); else if (play && NumberOf_moObjects > 2) {{ NumberOfCheckingLoadingFailed = 0; RestartTimer(); }} }}
function SlideshowCycle() {{ if (NumberOfCheckingLoadingFailed * interval/1000 >= timeout_sec) {{ still_loading = false; }}
if (still_loading) {{ NumberOfCheckingLoadingFailed++; }} else {{ NumberOfCheckingLoadingFailed = 0;
if (AdvanceSlideIndex(repeat) && _moObjects[slide_index] != null) {{ RenderImage(_moObjects[slide_index]); }} else {{ StopSlideshowCycle(); }} }} }}
function AdvanceSlideIndex(repeat) {{ if (slide_index < NumberOf_moObjects - 1) {{ slide_index++; return true; }} else {{ if (repeat) {{ slide_index = 0; return true; }} else {{ return false; }} }} }}
function toggle_pause() {{ play = !play; SetPauseButtonText(play); if (play) {{ RestartTimer(); }} else {{ StopTimer(); }} }}
function previous_image() {{ if (NumberOf_moObjects > 0) {{ StopTimer(); slide_index--; if (slide_index < 0) {{ slide_index = NumberOf_moObjects - 1; }} //if first image is displayed
RenderImage(_moObjects[slide_index]); RestartTimer(); }} }}
function next_image() {{ if (NumberOf_moObjects > 0) {{ StopTimer(); slide_index++; //if last image is reached,display the first image if (slide_index >= NumberOf_moObjects) slide_index = 0;
RenderImage(_moObjects[slide_index]); RestartTimer(); }} }}
function plus() {{ if (interval<1000) {{ interval = 1000; }} else {{ interval += 1000;}} ShowIntervalSecond(interval); RestartTimer(); }}
function minus() {{ if (interval >1000) {{ interval -= 1000; }} else {{ interval = 400; }} ShowIntervalSecond(interval); RestartTimer(); }}
function KeyDownHandler(e) {{ var ESC = String.fromCharCode(27); var home = String.fromCharCode(36); var left = String.fromCharCode(37); var right = String.fromCharCode(39); var up = String.fromCharCode(38); var down = String.fromCharCode(40); var keychar = GetKBPressedChar(e); switch(keychar) {{ case 'M': case home: OpenNewWindow(referringUrl); return false; // To disable the default behavior of keydown break; case 'X': case left: previous_image(); break; case ' ' : toggle_pause(); return false; // To disable the default behavior of keydown break; case 'C': case right: next_image(); break; case 'E': case up: plus(); return false; // To disable the default behavior of keydown break; case 'D': case down: minus(); return false; // To disable the default behavior of keydown break; case 'B': GoBackReferringUrl(); break; case ESC: still_loading = false; break; default: break; }} }}
function GoBackReferringUrl() {{ StopTimer(); window.location = referringUrl; }}
function OpenNewWindow(url) {{ newwin = window.open(url, '', 'directories=no, location=yes, resizable=yes, menubar=no, toolbar=no, scrollbars=yes, status=yes'); if (window.focus) {{ newwin.focus(); }} return false; }}
function GetKBPressedChar(e) {{ var keynum; var keychar; e = window.event || e; if(window.event) // IE {{ keynum = e.keyCode; }} else if(e.which) // Netscape/Firefox/Opera {{ keynum = e.which; }} keychar = String.fromCharCode(keynum); return keychar; }} " , _galleryAspxPagePathFile // 0 , _autoplay.ToString().ToLower()// 1 , _interval // 2 , _loadingGifUrl // 3 , _repeat.ToString().ToLower() // 4 , _timeout_sec // 5 , ReferringUrl // 6 , _pauseButtonTextPause // 7 , _pauseButtonTextPlay // 8 , MinusButton.ClientID // 9 , PlusButton.ClientID //10 , PreviousButton.ClientID //11 , PauseButton.ClientID //12 , NextButton.ClientID //13 , _preload_batch //14 );
ScriptManager.RegisterStartupScript(this, this.GetType(), "slideshow_control" + Guid.NewGuid().ToString(), script, true); }
#endregion
#region Private Methods
private static HtmlLink MakeStyleSheetControl(string href) { HtmlLink stylesheet = new HtmlLink(); stylesheet.Href = href; stylesheet.Attributes.Add("rel", "stylesheet"); stylesheet.Attributes.Add("type", "text/css");
return stylesheet; }
private IAlbum GetAlbum() { IAlbum tempAlbum = null; if (this._album == null) { try { if (Util.GetQueryStringParameterInt32("aid") > int.MinValue) { tempAlbum = Factory.LoadAlbumInstance(Util.GetQueryStringParameterInt32("aid"), true); } } catch (GalleryServerPro.ErrorHandler.CustomExceptions.InvalidAlbumException) { tempAlbum = null; } }
return tempAlbum; }
#endregion
} }
|