2 // System.Web.UI.Page.cs
5 // Duncan Mak (duncan@ximian.com)
6 // Gonzalo Paniagua (gonzalo@ximian.com)
7 // Andreas Nahr (ClassDevelopment@A-SoftTech.com)
8 // Marek Habersack (mhabersack@novell.com)
10 // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
11 // Copyright (C) 2003-2010 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections;
35 using System.Collections.Generic;
36 using System.Collections.Specialized;
37 using System.ComponentModel;
38 using System.ComponentModel.Design;
39 using System.ComponentModel.Design.Serialization;
40 using System.Globalization;
42 using System.Security.Permissions;
43 using System.Security.Principal;
45 using System.Threading;
47 using System.Web.Caching;
48 using System.Web.Compilation;
49 using System.Web.Configuration;
50 using System.Web.Hosting;
51 using System.Web.SessionState;
52 using System.Web.Util;
53 using System.Web.UI.Adapters;
54 using System.Web.UI.HtmlControls;
55 using System.Web.UI.WebControls;
56 using System.Reflection;
57 using System.Web.Routing;
59 namespace System.Web.UI
62 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
63 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
64 [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
66 [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
67 [DesignerSerializer ("Microsoft.VisualStudio.Web.WebForms.WebFormCodeDomSerializer, " + Consts.AssemblyMicrosoft_VisualStudio_Web, "System.ComponentModel.Design.Serialization.TypeCodeDomSerializer, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
68 public partial class Page : TemplateControl, IHttpHandler
70 // static string machineKeyConfigPath = "system.web/machineKey";
71 bool _eventValidation = true;
72 object [] _savedControlState;
73 bool _doLoadPreviousPage;
74 string _focusedControlID;
75 bool _hasEnabledControlArray;
80 bool _smartNavigation;
82 ValidatorCollection _validators;
84 string _savedViewState;
85 List <string> _requiresPostBack;
86 List <string> _requiresPostBackCopy;
87 List <IPostBackDataHandler> requiresPostDataChanged;
88 IPostBackEventHandler requiresRaiseEvent;
89 IPostBackEventHandler formPostedRequiresRaiseEvent;
90 NameValueCollection secondPostData;
91 bool requiresPostBackScript;
92 bool postBackScriptRendered;
93 bool requiresFormScriptDeclaration;
94 bool formScriptDeclarationRendered;
96 string viewStateUserKey;
97 NameValueCollection _requestValueCollection;
99 ClientScriptManager scriptManager;
100 bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
101 PageStatePersister page_state_persister;
102 CultureInfo _appCulture;
103 CultureInfo _appUICulture;
105 // The initial context
106 HttpContext _context;
108 // cached from the initial context
109 HttpApplicationState _application;
110 HttpResponse _response;
111 HttpRequest _request;
114 HttpSessionState _session;
116 [EditorBrowsable (EditorBrowsableState.Never)]
117 public const string postEventArgumentID = "__EVENTARGUMENT";
119 [EditorBrowsable (EditorBrowsableState.Never)]
120 public const string postEventSourceID = "__EVENTTARGET";
122 const string ScrollPositionXID = "__SCROLLPOSITIONX";
123 const string ScrollPositionYID = "__SCROLLPOSITIONY";
124 const string EnabledControlArrayID = "__enabledControlArray";
125 internal const string LastFocusID = "__LASTFOCUS";
126 internal const string CallbackArgumentID = "__CALLBACKPARAM";
127 internal const string CallbackSourceID = "__CALLBACKID";
128 internal const string PreviousPageID = "__PREVIOUSPAGE";
130 int maxPageStateFieldLength = -1;
131 string uniqueFilePathSuffix;
134 MasterPage masterPage;
135 string masterPageFile;
138 bool isCrossPagePostBack;
141 List <Control> requireStateControls;
146 string _styleSheetTheme;
147 string _metaDescription;
148 string _metaKeywords;
149 Control _autoPostBackControl;
151 bool frameworkInitialized;
154 bool _maintainScrollPositionOnPostBack;
156 bool asyncMode = false;
157 TimeSpan asyncTimeout;
158 const double DefaultAsyncTimeout = 45.0;
159 List<PageAsyncTask> parallelTasks;
160 List<PageAsyncTask> serialTasks;
162 ViewStateEncryptionMode viewStateEncryptionMode;
163 bool controlRegisteredForViewStateEncryption = false;
168 scriptManager = new ClientScriptManager (this);
171 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
173 asyncTimeout = ps.AsyncTimeout;
174 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
175 _viewState = ps.EnableViewState;
176 _viewStateMac = ps.EnableViewStateMac;
178 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
179 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
182 this.ViewStateMode = ViewStateMode.Enabled;
189 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
191 public HttpApplicationState Application {
192 get { return _application; }
195 [EditorBrowsable (EditorBrowsableState.Never)]
196 protected bool AspCompatMode {
197 get { return false; }
203 [EditorBrowsable (EditorBrowsableState.Never)]
204 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
205 [BrowsableAttribute (false)]
207 get { return Response.BufferOutput; }
208 set { Response.BufferOutput = value; }
211 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
216 throw new HttpException ("Cache is not available.");
221 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
222 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
223 [Browsable (false), DefaultValue ("")]
224 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
225 public string ClientTarget {
226 get { return (clientTarget == null) ? String.Empty : clientTarget; }
228 clientTarget = value;
229 if (value == String.Empty)
234 [EditorBrowsable (EditorBrowsableState.Never)]
235 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
236 [BrowsableAttribute (false)]
237 public int CodePage {
238 get { return Response.ContentEncoding.CodePage; }
239 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
242 [EditorBrowsable (EditorBrowsableState.Never)]
243 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
244 [BrowsableAttribute (false)]
245 public string ContentType {
246 get { return Response.ContentType; }
247 set { Response.ContentType = value; }
250 protected internal override HttpContext Context {
252 if (_context == null)
253 return HttpContext.Current;
259 [EditorBrowsable (EditorBrowsableState.Advanced)]
260 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
261 [BrowsableAttribute (false)]
262 public string Culture {
263 get { return Thread.CurrentThread.CurrentCulture.Name; }
264 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
267 [EditorBrowsable (EditorBrowsableState.Never)]
269 [DefaultValue ("true")]
270 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
271 public virtual bool EnableEventValidation {
272 get { return _eventValidation; }
275 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
276 _eventValidation = value;
281 public override bool EnableViewState {
282 get { return _viewState; }
283 set { _viewState = value; }
286 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
287 [BrowsableAttribute (false)]
288 [EditorBrowsable (EditorBrowsableState.Never)]
289 public bool EnableViewStateMac {
290 get { return _viewStateMac; }
291 set { _viewStateMac = value; }
294 internal bool EnableViewStateMacInternal {
295 get { return _viewStateMac; }
296 set { _viewStateMac = value; }
299 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
300 [Browsable (false), DefaultValue ("")]
301 [WebSysDescription ("The URL of a page used for error redirection.")]
302 public string ErrorPage {
303 get { return _errorPage; }
305 HttpContext ctx = Context;
309 ctx.ErrorPage = value;
313 [Obsolete ("The recommended alternative is HttpResponse.AddFileDependencies. http://go.microsoft.com/fwlink/?linkid=14202")]
314 [EditorBrowsable (EditorBrowsableState.Never)]
315 protected ArrayList FileDependencies {
317 if (Response != null)
318 Response.AddFileDependencies (value);
323 [EditorBrowsable (EditorBrowsableState.Never)]
324 public override string ID {
325 get { return base.ID; }
326 set { base.ID = value; }
329 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
331 public bool IsPostBack {
332 get { return isPostBack; }
335 public bool IsPostBackEventControlRegistered {
336 get { return requiresRaiseEvent != null; }
339 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
340 public bool IsReusable {
341 get { return false; }
344 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
346 public bool IsValid {
349 throw new HttpException (Locale.GetText ("Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate."));
351 foreach (IValidator val in Validators)
359 public IDictionary Items {
362 items = new Hashtable ();
367 [EditorBrowsable (EditorBrowsableState.Never)]
368 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
369 [BrowsableAttribute (false)]
371 get { return Thread.CurrentThread.CurrentCulture.LCID; }
372 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
376 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
377 public bool MaintainScrollPositionOnPostBack {
378 get { return _maintainScrollPositionOnPostBack; }
379 set { _maintainScrollPositionOnPostBack = value; }
382 public PageAdapter PageAdapter {
384 return Adapter as PageAdapter;
388 string _validationStartupScript;
389 string _validationOnSubmitStatement;
390 string _validationInitializeScript;
391 string _webFormScriptReference;
393 internal string WebFormScriptReference {
395 if (_webFormScriptReference == null)
396 _webFormScriptReference = IsMultiForm ? theForm : "window";
397 return _webFormScriptReference;
401 internal string ValidationStartupScript {
403 if (_validationStartupScript == null) {
404 _validationStartupScript =
406 " + WebFormScriptReference + @".Page_ValidationActive = false;
407 " + WebFormScriptReference + @".ValidatorOnLoad();
408 " + WebFormScriptReference + @".ValidatorOnSubmit = function () {
409 if (this.Page_ValidationActive) {
410 return this.ValidatorCommonOnSubmit();
416 return _validationStartupScript;
420 internal string ValidationOnSubmitStatement {
422 if (_validationOnSubmitStatement == null)
423 _validationOnSubmitStatement = "if (!" + WebFormScriptReference + ".ValidatorOnSubmit()) return false;";
424 return _validationOnSubmitStatement;
428 internal string ValidationInitializeScript {
430 if (_validationInitializeScript == null)
431 _validationInitializeScript = "WebFormValidation_Initialize(" + WebFormScriptReference + ");";
432 return _validationInitializeScript;
436 internal IScriptManager ScriptManager {
437 get { return (IScriptManager) Items [typeof (IScriptManager)]; }
439 internal string theForm {
445 internal bool IsMultiForm {
446 get { return false; }
449 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
451 public HttpRequest Request {
453 if (_request == null)
454 throw new HttpException("Request is not available in this context.");
455 return RequestInternal;
459 internal HttpRequest RequestInternal {
460 get { return _request; }
463 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
465 public HttpResponse Response {
467 if (_response == null)
468 throw new HttpException ("Response is not available in this context.");
473 [EditorBrowsable (EditorBrowsableState.Never)]
474 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
475 [BrowsableAttribute (false)]
476 public string ResponseEncoding {
477 get { return Response.ContentEncoding.WebName; }
478 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
481 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
483 public HttpServerUtility Server {
484 get { return Context.Server; }
487 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
489 public virtual HttpSessionState Session {
491 if (_session != null)
495 _session = Context.Session;
497 // ignore, should not throw
500 if (_session == null)
501 throw new HttpException ("Session state can only be used " +
502 "when enableSessionState is set to true, either " +
503 "in a configuration file or in the Page directive.");
510 [Obsolete ("The recommended alternative is Page.SetFocus and Page.MaintainScrollPositionOnPostBack. http://go.microsoft.com/fwlink/?linkid=14202")]
512 public bool SmartNavigation {
513 get { return _smartNavigation; }
514 set { _smartNavigation = value; }
517 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
520 public virtual string StyleSheetTheme {
521 get { return _styleSheetTheme; }
522 set { _styleSheetTheme = value; }
526 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
527 public virtual string Theme {
528 get { return _theme; }
529 set { _theme = value; }
532 void InitializeStyleSheet ()
534 if (_styleSheetTheme == null) {
535 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
537 _styleSheetTheme = ps.StyleSheetTheme;
540 if (!String.IsNullOrEmpty (_styleSheetTheme)) {
541 string virtualPath = "~/App_Themes/" + _styleSheetTheme;
542 _styleSheetPageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
546 void InitializeTheme ()
548 if (_theme == null) {
549 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
554 if (!String.IsNullOrEmpty (_theme)) {
555 string virtualPath = "~/App_Themes/" + _theme;
556 _pageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
557 if (_pageTheme != null)
558 _pageTheme.SetPage (this);
561 public Control AutoPostBackControl {
562 get { return _autoPostBackControl; }
563 set { _autoPostBackControl = value; }
566 [BrowsableAttribute(false)]
567 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
568 public RouteData RouteData {
570 if (_request == null)
573 RequestContext reqctx = _request.RequestContext;
577 return reqctx.RouteData;
582 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
584 public string MetaDescription {
586 if (_metaDescription == null) {
587 if (htmlHeader == null) {
588 if (frameworkInitialized)
589 throw new InvalidOperationException ("A server-side head element is required to set this property.");
592 return htmlHeader.Description;
595 return _metaDescription;
599 if (htmlHeader == null) {
600 if (frameworkInitialized)
601 throw new InvalidOperationException ("A server-side head element is required to set this property.");
602 _metaDescription = value;
604 htmlHeader.Description = value;
609 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
611 public string MetaKeywords {
613 if (_metaKeywords == null) {
614 if (htmlHeader == null) {
615 if (frameworkInitialized)
616 throw new InvalidOperationException ("A server-side head element is required to set this property.");
619 return htmlHeader.Keywords;
622 return _metaDescription;
626 if (htmlHeader == null) {
627 if (frameworkInitialized)
628 throw new InvalidOperationException ("A server-side head element is required to set this property.");
629 _metaKeywords = value;
631 htmlHeader.Keywords = value;
636 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
637 public string Title {
639 if (_title == null) {
640 if (htmlHeader != null && htmlHeader.Title != null)
641 return htmlHeader.Title;
648 if (htmlHeader != null)
649 htmlHeader.Title = value;
655 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
657 public TraceContext Trace {
658 get { return Context.Trace; }
661 [EditorBrowsable (EditorBrowsableState.Never)]
662 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
663 [BrowsableAttribute (false)]
664 public bool TraceEnabled {
665 get { return Trace.IsEnabled; }
666 set { Trace.IsEnabled = value; }
669 [EditorBrowsable (EditorBrowsableState.Never)]
670 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
671 [BrowsableAttribute (false)]
672 public TraceMode TraceModeValue {
673 get { return Trace.TraceMode; }
674 set { Trace.TraceMode = value; }
677 [EditorBrowsable (EditorBrowsableState.Never)]
678 protected int TransactionMode {
679 get { return _transactionMode; }
680 set { _transactionMode = value; }
683 [EditorBrowsable (EditorBrowsableState.Advanced)]
684 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
685 [BrowsableAttribute (false)]
686 public string UICulture {
687 get { return Thread.CurrentThread.CurrentUICulture.Name; }
688 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
691 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
693 public IPrincipal User {
694 get { return Context.User; }
697 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
699 public ValidatorCollection Validators {
701 if (_validators == null)
702 _validators = new ValidatorCollection ();
707 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
709 public string ViewStateUserKey {
710 get { return viewStateUserKey; }
711 set { viewStateUserKey = value; }
715 public override bool Visible {
716 get { return base.Visible; }
717 set { base.Visible = value; }
724 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
728 CultureInfo ret = null;
729 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
730 string[] languages = Request.UserLanguages;
732 if (languages != null && languages.Length > 0)
733 ret = CultureInfo.CreateSpecificCulture (languages[0]);
740 ret = CultureInfo.CreateSpecificCulture (culture);
745 [EditorBrowsable (EditorBrowsableState.Never)]
746 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
750 throw new NotImplementedException ();
753 [EditorBrowsable (EditorBrowsableState.Never)]
754 [MonoNotSupported ("Mono does not support classic ASP compatibility mode.")]
755 protected void AspCompatEndProcessRequest (IAsyncResult result)
757 throw new NotImplementedException ();
760 [EditorBrowsable (EditorBrowsableState.Advanced)]
761 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
763 if (Request.BrowserMightHaveSpecialWriter)
764 return Request.Browser.CreateHtmlTextWriter(tw);
766 return new HtmlTextWriter (tw);
769 [EditorBrowsable (EditorBrowsableState.Never)]
770 public void DesignerInitialize ()
772 InitRecursive (null);
775 [EditorBrowsable (EditorBrowsableState.Advanced)]
776 protected internal virtual NameValueCollection DeterminePostBackMode ()
778 // if request was transfered from other page such Transfer
779 if (_context.IsProcessingInclude)
782 HttpRequest req = Request;
786 NameValueCollection coll = null;
787 if (0 == String.Compare (Request.HttpMethod, "POST", true, Helpers.InvariantCulture))
790 string query = Request.QueryStringRaw;
791 if (query == null || query.Length == 0)
794 coll = req.QueryString;
797 WebROCollection c = (WebROCollection) coll;
798 allow_load = !c.GotID;
800 c.ID = GetTypeHashCode ();
802 allow_load = (c.ID == GetTypeHashCode ());
804 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
809 public override Control FindControl (string id) {
813 return base.FindControl (id);
816 Control FindControl (string id, bool decode) {
817 return FindControl (id);
820 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
821 [EditorBrowsable (EditorBrowsableState.Advanced)]
822 public string GetPostBackClientEvent (Control control, string argument)
824 return scriptManager.GetPostBackEventReference (control, argument);
827 [Obsolete ("The recommended alternative is ClientScript.GetPostBackClientHyperlink. http://go.microsoft.com/fwlink/?linkid=14202")]
828 [EditorBrowsable (EditorBrowsableState.Advanced)]
829 public string GetPostBackClientHyperlink (Control control, string argument)
831 return scriptManager.GetPostBackClientHyperlink (control, argument);
834 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
835 [EditorBrowsable (EditorBrowsableState.Advanced)]
836 public string GetPostBackEventReference (Control control)
838 return scriptManager.GetPostBackEventReference (control, String.Empty);
841 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
842 [EditorBrowsable (EditorBrowsableState.Advanced)]
843 public string GetPostBackEventReference (Control control, string argument)
845 return scriptManager.GetPostBackEventReference (control, argument);
848 internal void RequiresFormScriptDeclaration ()
850 requiresFormScriptDeclaration = true;
853 internal void RequiresPostBackScript ()
855 if (requiresPostBackScript)
857 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
858 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
859 requiresPostBackScript = true;
860 RequiresFormScriptDeclaration ();
863 [EditorBrowsable (EditorBrowsableState.Never)]
864 public virtual int GetTypeHashCode ()
869 [MonoTODO ("The following properties of OutputCacheParameters are silently ignored: CacheProfile, SqlDependency")]
870 [EditorBrowsable (EditorBrowsableState.Never)]
871 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
873 if (cacheSettings.Enabled) {
874 InitOutputCache(cacheSettings.Duration,
875 cacheSettings.VaryByContentEncoding,
876 cacheSettings.VaryByHeader,
877 cacheSettings.VaryByCustom,
878 cacheSettings.Location,
879 cacheSettings.VaryByParam);
881 HttpResponse response = Response;
882 HttpCachePolicy cache = response != null ? response.Cache : null;
883 if (cache != null && cacheSettings.NoStore)
888 [MonoTODO ("varyByContentEncoding is not currently used")]
889 [EditorBrowsable (EditorBrowsableState.Never)]
890 protected virtual void InitOutputCache(int duration,
891 string varyByContentEncoding,
894 OutputCacheLocation location,
898 // No need to do anything, cache will be ineffective anyway
901 HttpResponse response = Response;
902 HttpCachePolicy cache = response.Cache;
903 bool set_vary = false;
904 HttpContext ctx = Context;
905 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
908 case OutputCacheLocation.Any:
909 cache.SetCacheability (HttpCacheability.Public);
910 cache.SetMaxAge (new TimeSpan (0, 0, duration));
911 cache.SetLastModified (timestamp);
914 case OutputCacheLocation.Client:
915 cache.SetCacheability (HttpCacheability.Private);
916 cache.SetMaxAge (new TimeSpan (0, 0, duration));
917 cache.SetLastModified (timestamp);
919 case OutputCacheLocation.Downstream:
920 cache.SetCacheability (HttpCacheability.Public);
921 cache.SetMaxAge (new TimeSpan (0, 0, duration));
922 cache.SetLastModified (timestamp);
924 case OutputCacheLocation.Server:
925 cache.SetCacheability (HttpCacheability.Server);
928 case OutputCacheLocation.None:
933 if (varyByCustom != null)
934 cache.SetVaryByCustom (varyByCustom);
936 if (varyByParam != null && varyByParam.Length > 0) {
937 string[] prms = varyByParam.Split (';');
938 foreach (string p in prms)
939 cache.VaryByParams [p.Trim ()] = true;
940 cache.VaryByParams.IgnoreParams = false;
942 cache.VaryByParams.IgnoreParams = true;
945 if (varyByHeader != null && varyByHeader.Length > 0) {
946 string[] hdrs = varyByHeader.Split (';');
947 foreach (string h in hdrs)
948 cache.VaryByHeaders [h.Trim ()] = true;
951 if (PageAdapter != null) {
952 if (PageAdapter.CacheVaryByParams != null) {
953 foreach (string p in PageAdapter.CacheVaryByParams)
954 cache.VaryByParams [p] = true;
956 if (PageAdapter.CacheVaryByHeaders != null) {
957 foreach (string h in PageAdapter.CacheVaryByHeaders)
958 cache.VaryByHeaders [h] = true;
963 response.IsCached = true;
964 cache.Duration = duration;
965 cache.SetExpires (timestamp.AddSeconds (duration));
969 [EditorBrowsable (EditorBrowsableState.Never)]
970 protected virtual void InitOutputCache (int duration,
973 OutputCacheLocation location,
976 InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
979 [Obsolete ("The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
980 public bool IsClientScriptBlockRegistered (string key)
982 return scriptManager.IsClientScriptBlockRegistered (key);
985 [Obsolete ("The recommended alternative is ClientScript.IsStartupScriptRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
986 public bool IsStartupScriptRegistered (string key)
988 return scriptManager.IsStartupScriptRegistered (key);
991 public string MapPath (string virtualPath)
993 return Request.MapPath (virtualPath);
996 protected internal override void Render (HtmlTextWriter writer)
998 if (MaintainScrollPositionOnPostBack) {
999 ClientScript.RegisterWebFormClientScript ();
1001 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
1002 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
1004 StringBuilder script = new StringBuilder ();
1005 script.AppendLine ("<script type=\"text/javascript\">");
1006 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
1007 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
1008 script.AppendLine (theForm + ".submit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionSubmit(); }");
1009 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
1010 script.AppendLine (theForm + ".onsubmit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionOnSubmit(); }");
1012 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
1013 script.AppendLine ("window.onload = function () { " + WebFormScriptReference + ".WebForm_RestoreScrollPosition (); };");
1015 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
1016 script.AppendLine ("</script>");
1018 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1020 base.Render (writer);
1023 void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1025 writer.WriteLine ();
1026 ClientScriptManager.WriteBeginScriptBlock (writer);
1027 RenderClientScriptFormDeclaration (writer, formUniqueID);
1028 writer.WriteLine (WebFormScriptReference + "._form = " + theForm + ";");
1029 writer.WriteLine (WebFormScriptReference + ".__doPostBack = function (eventTarget, eventArgument) {");
1030 writer.WriteLine ("\tif(" + theForm + ".onsubmit && " + theForm + ".onsubmit() == false) return;");
1031 writer.WriteLine ("\t" + theForm + "." + postEventSourceID + ".value = eventTarget;");
1032 writer.WriteLine ("\t" + theForm + "." + postEventArgumentID + ".value = eventArgument;");
1033 writer.WriteLine ("\t" + theForm + ".submit();");
1034 writer.WriteLine ("}");
1035 ClientScriptManager.WriteEndScriptBlock (writer);
1038 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1040 if (formScriptDeclarationRendered)
1043 if (PageAdapter != null) {
1044 writer.WriteLine ("\tvar {0} = {1};\n", theForm, PageAdapter.GetPostBackFormReference(formUniqueID));
1046 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1047 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1049 formScriptDeclarationRendered = true;
1052 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1055 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1057 renderingForm = true;
1058 writer.WriteLine ();
1060 if (requiresFormScriptDeclaration || (scriptManager != null && scriptManager.ScriptsPresent) || PageAdapter != null) {
1061 ClientScriptManager.WriteBeginScriptBlock (writer);
1062 RenderClientScriptFormDeclaration (writer, formUniqueID);
1063 ClientScriptManager.WriteEndScriptBlock (writer);
1066 if (handleViewState)
1067 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1069 scriptManager.WriteHiddenFields (writer);
1070 if (requiresPostBackScript) {
1071 RenderPostBackScript (writer, formUniqueID);
1072 postBackScriptRendered = true;
1075 scriptManager.WriteWebFormClientScript (writer);
1076 scriptManager.WriteClientScriptBlocks (writer);
1079 internal IStateFormatter GetFormatter ()
1081 return new ObjectStateFormatter (this);
1084 internal string GetSavedViewState ()
1086 return _savedViewState;
1089 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1091 scriptManager.SaveEventValidationState ();
1092 scriptManager.WriteExpandoAttributes (writer);
1093 scriptManager.WriteHiddenFields (writer);
1094 if (!postBackScriptRendered && requiresPostBackScript)
1095 RenderPostBackScript (writer, formUniqueID);
1096 scriptManager.WriteWebFormClientScript (writer);
1097 scriptManager.WriteArrayDeclares (writer);
1098 scriptManager.WriteStartupScriptBlocks (writer);
1099 renderingForm = false;
1100 postBackScriptRendered = false;
1103 void ProcessPostData (NameValueCollection data, bool second)
1105 NameValueCollection requestValues = _requestValueCollection == null ? new NameValueCollection (SecureHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant) : _requestValueCollection;
1107 if (data != null && data.Count > 0) {
1108 var used = new Dictionary <string, string> (StringComparer.Ordinal);
1109 foreach (string id in data.AllKeys) {
1110 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID || id == ClientScriptManager.EventStateFieldName)
1113 if (used.ContainsKey (id))
1118 Control ctrl = FindControl (id, true);
1120 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1121 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1125 formPostedRequiresRaiseEvent = pbeh;
1129 if (pbdh.LoadPostData (id, requestValues) == true) {
1130 if (requiresPostDataChanged == null)
1131 requiresPostDataChanged = new List <IPostBackDataHandler> ();
1132 requiresPostDataChanged.Add (pbdh);
1135 if (_requiresPostBackCopy != null)
1136 _requiresPostBackCopy.Remove (id);
1138 } else if (!second) {
1139 if (secondPostData == null)
1140 secondPostData = new NameValueCollection (SecureHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant);
1141 secondPostData.Add (id, data [id]);
1146 List <string> list1 = null;
1147 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1148 string [] handlers = (string []) _requiresPostBackCopy.ToArray ();
1149 foreach (string id in handlers) {
1150 IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
1152 _requiresPostBackCopy.Remove (id);
1153 if (pbdh.LoadPostData (id, requestValues)) {
1154 if (requiresPostDataChanged == null)
1155 requiresPostDataChanged = new List <IPostBackDataHandler> ();
1157 requiresPostDataChanged.Add (pbdh);
1159 } else if (!second) {
1161 list1 = new List <string> ();
1166 _requiresPostBackCopy = second ? null : list1;
1168 secondPostData = null;
1171 [EditorBrowsable (EditorBrowsableState.Never)]
1172 public virtual void ProcessRequest (HttpContext context)
1174 SetContext (context);
1176 if (clientTarget != null)
1177 Request.ClientTarget = clientTarget;
1179 WireupAutomaticEvents ();
1180 //-- Control execution lifecycle in the docs
1182 // Save culture information because it can be modified in FrameworkInitialize()
1183 _appCulture = Thread.CurrentThread.CurrentCulture;
1184 _appUICulture = Thread.CurrentThread.CurrentUICulture;
1185 FrameworkInitialize ();
1186 frameworkInitialized = true;
1187 context.ErrorPage = _errorPage;
1190 InternalProcessRequest ();
1191 } catch (ThreadAbortException taex) {
1192 if (FlagEnd.Value == taex.ExceptionState)
1193 Thread.ResetAbort ();
1196 } catch (Exception e) {
1197 ProcessException (e);
1203 void ProcessException (Exception e) {
1204 // We want to remove that error, as we're rethrowing to stop
1205 // further processing.
1206 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1207 _context.AddError (e); // OnError might access LastError
1208 OnError (EventArgs.Empty);
1209 if (_context.HasError (e)) {
1210 _context.ClearError (e);
1211 throw new HttpUnhandledException (null, e);
1215 void ProcessUnload () {
1218 UnloadRecursive (true);
1220 if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
1221 Thread.CurrentThread.CurrentCulture = _appCulture;
1223 if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
1224 Thread.CurrentThread.CurrentUICulture = _appUICulture;
1227 _appUICulture = null;
1230 delegate void ProcessRequestDelegate (HttpContext context);
1232 sealed class DummyAsyncResult : IAsyncResult
1234 readonly object state;
1235 readonly WaitHandle asyncWaitHandle;
1236 readonly bool completedSynchronously;
1237 readonly bool isCompleted;
1239 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1241 this.isCompleted = isCompleted;
1242 this.completedSynchronously = completedSynchronously;
1245 asyncWaitHandle = new ManualResetEvent (true);
1248 asyncWaitHandle = new ManualResetEvent (false);
1252 #region IAsyncResult Members
1254 public object AsyncState {
1255 get { return state; }
1258 public WaitHandle AsyncWaitHandle {
1259 get { return asyncWaitHandle; }
1262 public bool CompletedSynchronously {
1263 get { return completedSynchronously; }
1266 public bool IsCompleted {
1267 get { return isCompleted; }
1273 [EditorBrowsable (EditorBrowsableState.Never)]
1274 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1276 ProcessRequest (context);
1277 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1279 if (callback != null) {
1280 callback (asyncResult);
1286 [EditorBrowsable (EditorBrowsableState.Never)]
1287 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1291 void InternalProcessRequest ()
1293 if (PageAdapter != null)
1294 _requestValueCollection = PageAdapter.DeterminePostBackMode();
1296 _requestValueCollection = this.DeterminePostBackMode();
1298 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1299 if (_requestValueCollection != null) {
1300 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1301 _doLoadPreviousPage = true;
1303 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1304 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1305 //isPostBack = !isCallback;
1309 string lastFocus = _requestValueCollection [LastFocusID];
1310 if (!String.IsNullOrEmpty (lastFocus))
1311 _focusedControlID = UniqueID2ClientID (lastFocus);
1314 if (!isCrossPagePostBack) {
1315 if (_context.PreviousHandler is Page)
1316 previousPage = (Page) _context.PreviousHandler;
1319 Trace.Write ("aspx.page", "Begin PreInit");
1320 OnPreInit (EventArgs.Empty);
1321 Trace.Write ("aspx.page", "End PreInit");
1325 Trace.Write ("aspx.page", "Begin Init");
1326 InitRecursive (null);
1327 Trace.Write ("aspx.page", "End Init");
1329 Trace.Write ("aspx.page", "Begin InitComplete");
1330 OnInitComplete (EventArgs.Empty);
1331 Trace.Write ("aspx.page", "End InitComplete");
1333 renderingForm = false;
1336 RestorePageState ();
1338 ProcessRaiseEvents ();
1339 if (ProcessLoadComplete ())
1344 void RestorePageState ()
1346 if (IsPostBack || IsCallback) {
1347 if (_requestValueCollection != null)
1348 scriptManager.RestoreEventValidationState (
1349 _requestValueCollection [ClientScriptManager.EventStateFieldName]);
1350 Trace.Write ("aspx.page", "Begin LoadViewState");
1351 LoadPageViewState ();
1352 Trace.Write ("aspx.page", "End LoadViewState");
1356 void ProcessPostData ()
1358 if (IsPostBack || IsCallback) {
1359 Trace.Write ("aspx.page", "Begin ProcessPostData");
1360 ProcessPostData (_requestValueCollection, false);
1361 Trace.Write ("aspx.page", "End ProcessPostData");
1365 if (IsPostBack || IsCallback) {
1366 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1367 ProcessPostData (secondPostData, true);
1368 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1374 Trace.Write ("aspx.page", "Begin PreLoad");
1375 OnPreLoad (EventArgs.Empty);
1376 Trace.Write ("aspx.page", "End PreLoad");
1378 Trace.Write ("aspx.page", "Begin Load");
1380 Trace.Write ("aspx.page", "End Load");
1383 void ProcessRaiseEvents ()
1385 if (IsPostBack || IsCallback) {
1386 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1387 RaiseChangedEvents ();
1388 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1389 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1390 RaisePostBackEvents ();
1391 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1395 bool ProcessLoadComplete ()
1397 Trace.Write ("aspx.page", "Begin LoadComplete");
1398 OnLoadComplete (EventArgs.Empty);
1399 Trace.Write ("aspx.page", "End LoadComplete");
1401 if (IsCrossPagePostBack)
1405 string result = ProcessCallbackData ();
1406 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1407 callbackOutput.Write (result);
1408 callbackOutput.Flush ();
1412 Trace.Write ("aspx.page", "Begin PreRender");
1413 PreRenderRecursiveInternal ();
1414 Trace.Write ("aspx.page", "End PreRender");
1416 ExecuteRegisteredAsyncTasks ();
1418 Trace.Write ("aspx.page", "Begin PreRenderComplete");
1419 OnPreRenderComplete (EventArgs.Empty);
1420 Trace.Write ("aspx.page", "End PreRenderComplete");
1422 Trace.Write ("aspx.page", "Begin SaveViewState");
1423 SavePageViewState ();
1424 Trace.Write ("aspx.page", "End SaveViewState");
1426 Trace.Write ("aspx.page", "Begin SaveStateComplete");
1427 OnSaveStateComplete (EventArgs.Empty);
1428 Trace.Write ("aspx.page", "End SaveStateComplete");
1432 internal void RenderPage ()
1434 scriptManager.ResetEventValidationState ();
1437 Trace.Write ("aspx.page", "Begin Render");
1438 HtmlTextWriter output = CreateHtmlTextWriter (Response.Output);
1439 RenderControl (output);
1440 Trace.Write ("aspx.page", "End Render");
1443 internal void SetContext (HttpContext context)
1447 _application = context.Application;
1448 _response = context.Response;
1449 _request = context.Request;
1450 _cache = context.Cache;
1455 TraceManager traceManager = HttpRuntime.TraceManager;
1457 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1462 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1465 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1466 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1467 Trace.Render (output);
1471 void RaisePostBackEvents ()
1473 if (requiresRaiseEvent != null) {
1474 RaisePostBackEvent (requiresRaiseEvent, null);
1478 if (formPostedRequiresRaiseEvent != null) {
1479 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1483 NameValueCollection postdata = _requestValueCollection;
1484 if (postdata == null)
1487 string eventTarget = postdata [postEventSourceID];
1488 IPostBackEventHandler target;
1489 if (String.IsNullOrEmpty (eventTarget)) {
1490 target = AutoPostBackControl as IPostBackEventHandler;
1492 RaisePostBackEvent (target, null);
1494 if (formPostedRequiresRaiseEvent != null)
1495 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1501 target = FindControl (eventTarget, true) as IPostBackEventHandler;
1503 target = AutoPostBackControl as IPostBackEventHandler;
1507 string eventArgument = postdata [postEventArgumentID];
1508 RaisePostBackEvent (target, eventArgument);
1511 internal void RaiseChangedEvents ()
1513 if (requiresPostDataChanged == null)
1516 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1517 ipdh.RaisePostDataChangedEvent ();
1519 requiresPostDataChanged = null;
1522 [EditorBrowsable (EditorBrowsableState.Advanced)]
1523 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1525 sourceControl.RaisePostBackEvent (eventArgument);
1528 [Obsolete ("The recommended alternative is ClientScript.RegisterArrayDeclaration(string arrayName, string arrayValue). http://go.microsoft.com/fwlink/?linkid=14202")]
1529 [EditorBrowsable (EditorBrowsableState.Advanced)]
1530 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1532 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1535 [Obsolete ("The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1536 [EditorBrowsable (EditorBrowsableState.Advanced)]
1537 public virtual void RegisterClientScriptBlock (string key, string script)
1539 scriptManager.RegisterClientScriptBlock (key, script);
1543 [EditorBrowsable (EditorBrowsableState.Advanced)]
1544 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1546 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1549 [MonoTODO("Not implemented, Used in HtmlForm")]
1550 internal void RegisterClientScriptFile (string a, string b, string c)
1552 throw new NotImplementedException ();
1555 [Obsolete ("The recommended alternative is ClientScript.RegisterOnSubmitStatement(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1556 [EditorBrowsable (EditorBrowsableState.Advanced)]
1557 public void RegisterOnSubmitStatement (string key, string script)
1559 scriptManager.RegisterOnSubmitStatement (key, script);
1562 internal string GetSubmitStatements ()
1564 return scriptManager.WriteSubmitStatements ();
1567 [EditorBrowsable (EditorBrowsableState.Advanced)]
1568 public void RegisterRequiresPostBack (Control control)
1570 if (!(control is IPostBackDataHandler))
1571 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1573 if (_requiresPostBack == null)
1574 _requiresPostBack = new List <string> ();
1576 string uniqueID = control.UniqueID;
1577 if (_requiresPostBack.Contains (uniqueID))
1580 _requiresPostBack.Add (uniqueID);
1583 [EditorBrowsable (EditorBrowsableState.Advanced)]
1584 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1586 requiresRaiseEvent = control;
1589 [Obsolete ("The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1590 [EditorBrowsable (EditorBrowsableState.Advanced)]
1591 public virtual void RegisterStartupScript (string key, string script)
1593 scriptManager.RegisterStartupScript (key, script);
1596 [EditorBrowsable (EditorBrowsableState.Advanced)]
1597 public void RegisterViewStateHandler ()
1599 handleViewState = true;
1602 [EditorBrowsable (EditorBrowsableState.Advanced)]
1603 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1605 PageStatePersister persister = this.PageStatePersister;
1606 if (persister == null)
1608 Pair pair = viewState as Pair;
1610 persister.ViewState = pair.First;
1611 persister.ControlState = pair.Second;
1613 persister.ViewState = viewState;
1617 internal string RawViewState {
1619 NameValueCollection postdata = _requestValueCollection;
1621 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1624 if (view_state == String.Empty)
1629 set { _savedViewState = value; }
1633 protected virtual PageStatePersister PageStatePersister {
1635 if (page_state_persister == null && PageAdapter != null)
1636 page_state_persister = PageAdapter.GetStatePersister();
1637 if (page_state_persister == null)
1638 page_state_persister = new HiddenFieldPageStatePersister (this);
1639 return page_state_persister;
1643 [EditorBrowsable (EditorBrowsableState.Advanced)]
1644 protected virtual object LoadPageStateFromPersistenceMedium ()
1646 PageStatePersister persister = this.PageStatePersister;
1647 if (persister == null)
1650 return new Pair (persister.ViewState, persister.ControlState);
1653 internal void LoadPageViewState ()
1655 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1656 if (sState != null) {
1657 if (allow_load || isCrossPagePostBack) {
1658 LoadPageControlState (sState.Second);
1660 Pair vsr = sState.First as Pair;
1662 LoadViewStateRecursive (vsr.First);
1663 _requiresPostBackCopy = vsr.Second as List <string>;
1669 internal void SavePageViewState ()
1671 if (!handleViewState)
1674 object controlState = SavePageControlState ();
1676 object viewState = null;
1679 && this.ViewStateMode == ViewStateMode.Enabled
1681 viewState = SaveViewStateRecursive ();
1683 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1684 if (viewState != null || reqPostback != null)
1685 vsr = new Pair (viewState, reqPostback);
1687 Pair pair = new Pair ();
1689 pair.Second = controlState;
1690 if (pair.First == null && pair.Second == null)
1691 SavePageStateToPersistenceMedium (null);
1693 SavePageStateToPersistenceMedium (pair);
1697 public virtual void Validate ()
1699 is_validated = true;
1700 ValidateCollection (_validators);
1703 internal bool AreValidatorsUplevel ()
1705 return AreValidatorsUplevel (String.Empty);
1708 internal bool AreValidatorsUplevel (string valGroup)
1710 bool uplevel = false;
1712 foreach (IValidator v in Validators) {
1713 BaseValidator bv = v as BaseValidator;
1717 if (valGroup != bv.ValidationGroup)
1719 if (bv.GetRenderUplevel()) {
1728 bool ValidateCollection (ValidatorCollection validators)
1730 if (validators == null || validators.Count == 0)
1733 bool all_valid = true;
1734 foreach (IValidator v in validators){
1736 if (v.IsValid == false)
1743 [EditorBrowsable (EditorBrowsableState.Advanced)]
1744 public virtual void VerifyRenderingInServerForm (Control control)
1746 if (Context == null)
1751 throw new HttpException ("Control '" +
1754 control.GetType ().Name +
1755 "' must be placed inside a form tag with runat=server.");
1758 protected override void FrameworkInitialize ()
1760 base.FrameworkInitialize ();
1761 InitializeStyleSheet ();
1765 public ClientScriptManager ClientScript {
1766 get { return scriptManager; }
1769 internal static readonly object InitCompleteEvent = new object ();
1770 internal static readonly object LoadCompleteEvent = new object ();
1771 internal static readonly object PreInitEvent = new object ();
1772 internal static readonly object PreLoadEvent = new object ();
1773 internal static readonly object PreRenderCompleteEvent = new object ();
1774 internal static readonly object SaveStateCompleteEvent = new object ();
1776 const int initcomplete_mask = 1;
1777 const int loadcomplete_mask = 1 << 1;
1778 const int preinit_mask = 1 << 2;
1779 const int preload_mask = 1 << 3;
1780 const int prerendercomplete_mask = 1 << 4;
1781 const int savestatecomplete_mask = 1 << 5;
1783 [EditorBrowsable (EditorBrowsableState.Advanced)]
1784 public event EventHandler InitComplete {
1786 event_mask |= initcomplete_mask;
1787 Events.AddHandler (InitCompleteEvent, value);
1789 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1792 [EditorBrowsable (EditorBrowsableState.Advanced)]
1793 public event EventHandler LoadComplete {
1795 event_mask |= loadcomplete_mask;
1796 Events.AddHandler (LoadCompleteEvent, value);
1798 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1801 public event EventHandler PreInit {
1803 event_mask |= preinit_mask;
1804 Events.AddHandler (PreInitEvent, value);
1806 remove { Events.RemoveHandler (PreInitEvent, value); }
1809 [EditorBrowsable (EditorBrowsableState.Advanced)]
1810 public event EventHandler PreLoad {
1812 event_mask |= preload_mask;
1813 Events.AddHandler (PreLoadEvent, value);
1815 remove { Events.RemoveHandler (PreLoadEvent, value); }
1818 [EditorBrowsable (EditorBrowsableState.Advanced)]
1819 public event EventHandler PreRenderComplete {
1821 event_mask |= prerendercomplete_mask;
1822 Events.AddHandler (PreRenderCompleteEvent, value);
1824 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1827 [EditorBrowsable (EditorBrowsableState.Advanced)]
1828 public event EventHandler SaveStateComplete {
1830 event_mask |= savestatecomplete_mask;
1831 Events.AddHandler (SaveStateCompleteEvent, value);
1833 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1836 protected virtual void OnInitComplete (EventArgs e)
1838 if ((event_mask & initcomplete_mask) != 0) {
1839 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1840 if (eh != null) eh (this, e);
1844 protected virtual void OnLoadComplete (EventArgs e)
1846 if ((event_mask & loadcomplete_mask) != 0) {
1847 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1848 if (eh != null) eh (this, e);
1852 protected virtual void OnPreInit (EventArgs e)
1854 if ((event_mask & preinit_mask) != 0) {
1855 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1856 if (eh != null) eh (this, e);
1860 protected virtual void OnPreLoad (EventArgs e)
1862 if ((event_mask & preload_mask) != 0) {
1863 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1864 if (eh != null) eh (this, e);
1868 protected virtual void OnPreRenderComplete (EventArgs e)
1870 if ((event_mask & prerendercomplete_mask) != 0) {
1871 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1872 if (eh != null) eh (this, e);
1877 if (!Form.DetermineRenderUplevel ())
1880 string defaultButtonId = Form.DefaultButton;
1881 /* figure out if we have some control we're going to focus */
1882 if (String.IsNullOrEmpty (_focusedControlID)) {
1883 _focusedControlID = Form.DefaultFocus;
1884 if (String.IsNullOrEmpty (_focusedControlID))
1885 _focusedControlID = defaultButtonId;
1888 if (!String.IsNullOrEmpty (_focusedControlID)) {
1889 ClientScript.RegisterWebFormClientScript ();
1891 ClientScript.RegisterStartupScript (
1893 "HtmlForm-DefaultButton-StartupScript",
1894 "\n" + WebFormScriptReference + ".WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
1897 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1898 ClientScript.RegisterWebFormClientScript ();
1900 ClientScript.RegisterOnSubmitStatement (
1902 "HtmlForm-SubmitDisabledControls-SubmitStatement",
1903 WebFormScriptReference + ".WebForm_ReEnableControls();");
1907 internal void RegisterEnabledControl (Control control)
1909 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1911 _hasEnabledControlArray = true;
1912 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
1915 protected virtual void OnSaveStateComplete (EventArgs e)
1917 if ((event_mask & savestatecomplete_mask) != 0) {
1918 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1919 if (eh != null) eh (this, e);
1923 public HtmlForm Form {
1924 get { return _form; }
1927 internal void RegisterForm (HtmlForm form)
1932 public string ClientQueryString {
1933 get { return Request.UrlComponents.Query; }
1936 [BrowsableAttribute (false)]
1937 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1938 public Page PreviousPage {
1940 if (_doLoadPreviousPage) {
1941 _doLoadPreviousPage = false;
1942 LoadPreviousPageReference ();
1944 return previousPage;
1949 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1950 [BrowsableAttribute (false)]
1951 public bool IsCallback {
1952 get { return isCallback; }
1955 [BrowsableAttribute (false)]
1956 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1957 public bool IsCrossPagePostBack {
1958 get { return isCrossPagePostBack; }
1962 [EditorBrowsable (EditorBrowsableState.Never)]
1963 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1964 public new virtual char IdSeparator {
1966 //TODO: why override?
1967 return base.IdSeparator;
1971 string ProcessCallbackData ()
1973 ICallbackEventHandler target = GetCallbackTarget ();
1974 string callbackEventError = String.Empty;
1975 ProcessRaiseCallbackEvent (target, ref callbackEventError);
1976 return ProcessGetCallbackResult (target, callbackEventError);
1979 ICallbackEventHandler GetCallbackTarget ()
1981 string callbackTarget = _requestValueCollection [CallbackSourceID];
1982 if (callbackTarget == null || callbackTarget.Length == 0)
1983 throw new HttpException ("Callback target not provided.");
1985 Control targetControl = FindControl (callbackTarget, true);
1986 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
1988 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
1992 void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError)
1994 string callbackArgument = _requestValueCollection [CallbackArgumentID];
1997 target.RaiseCallbackEvent (callbackArgument);
1998 } catch (Exception ex) {
1999 callbackEventError = String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2004 string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError)
2006 string callBackResult;
2008 callBackResult = target.GetCallbackResult ();
2009 } catch (Exception ex) {
2010 return String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2013 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2014 return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
2015 eventValidation + callBackResult;
2018 [BrowsableAttribute (false)]
2019 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2020 public HtmlHead Header {
2021 get { return htmlHeader; }
2024 internal void SetHeader (HtmlHead header)
2026 htmlHeader = header;
2030 if (_title != null) {
2031 htmlHeader.Title = _title;
2034 if (_metaDescription != null) {
2035 htmlHeader.Description = _metaDescription;
2036 _metaDescription = null;
2039 if (_metaKeywords != null) {
2040 htmlHeader.Keywords = _metaKeywords;
2041 _metaKeywords = null;
2045 [EditorBrowsable (EditorBrowsableState.Never)]
2046 protected bool AsyncMode {
2047 get { return asyncMode; }
2048 set { asyncMode = value; }
2052 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2053 [EditorBrowsable (EditorBrowsableState.Advanced)]
2054 public TimeSpan AsyncTimeout {
2055 get { return asyncTimeout; }
2056 set { asyncTimeout = value; }
2059 public bool IsAsync {
2060 get { return AsyncMode; }
2063 protected internal virtual string UniqueFilePathSuffix {
2065 if (String.IsNullOrEmpty (uniqueFilePathSuffix))
2066 uniqueFilePathSuffix = "__ufps=" + AppRelativeVirtualPath.GetHashCode ().ToString ("x");
2067 return uniqueFilePathSuffix;
2071 [MonoTODO ("Actually use the value in code.")]
2073 [EditorBrowsable (EditorBrowsableState.Never)]
2074 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2075 public int MaxPageStateFieldLength {
2076 get { return maxPageStateFieldLength; }
2077 set { maxPageStateFieldLength = value; }
2080 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2082 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2085 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2088 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2091 if (IsPrerendered) {
2092 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
2095 if (beginHandler == null) {
2096 throw new ArgumentNullException ("beginHandler");
2099 if (endHandler == null) {
2100 throw new ArgumentNullException ("endHandler");
2103 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2106 List<PageAsyncTask> ParallelTasks {
2108 if (parallelTasks == null)
2109 parallelTasks = new List<PageAsyncTask>();
2110 return parallelTasks;
2114 List<PageAsyncTask> SerialTasks {
2116 if (serialTasks == null)
2117 serialTasks = new List<PageAsyncTask> ();
2122 public void RegisterAsyncTask (PageAsyncTask task)
2125 throw new ArgumentNullException ("task");
2127 if (task.ExecuteInParallel)
2128 ParallelTasks.Add (task);
2130 SerialTasks.Add (task);
2133 public void ExecuteRegisteredAsyncTasks ()
2135 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2136 (serialTasks == null || serialTasks.Count == 0)){
2140 if (parallelTasks != null) {
2141 DateTime startExecution = DateTime.Now;
2142 List<PageAsyncTask> localParallelTasks = parallelTasks;
2143 parallelTasks = null; // Shouldn't execute tasks twice
2144 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2145 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2146 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask);
2147 if (result.CompletedSynchronously)
2148 parallelTask.EndHandler (result);
2150 asyncResults.Add (result);
2153 if (asyncResults.Count > 0) {
2154 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2156 for (i = 0; i < asyncResults.Count; i++) {
2157 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2160 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2161 if (!allSignalled) {
2162 for (i = 0; i < asyncResults.Count; i++) {
2163 if (!asyncResults [i].IsCompleted) {
2164 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2169 DateTime endWait = DateTime.Now;
2170 TimeSpan elapsed = endWait - startExecution;
2171 if (elapsed <= AsyncTimeout)
2172 AsyncTimeout -= elapsed;
2174 AsyncTimeout = TimeSpan.FromTicks(0);
2177 if (serialTasks != null) {
2178 List<PageAsyncTask> localSerialTasks = serialTasks;
2179 serialTasks = null; // Shouldn't execute tasks twice
2180 foreach (PageAsyncTask serialTask in localSerialTasks) {
2181 DateTime startExecution = DateTime.Now;
2183 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2184 if (result.CompletedSynchronously)
2185 serialTask.EndHandler (result);
2187 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2188 if (!done && !result.IsCompleted) {
2189 serialTask.TimeoutHandler (result);
2192 DateTime endWait = DateTime.Now;
2193 TimeSpan elapsed = endWait - startExecution;
2194 if (elapsed <= AsyncTimeout)
2195 AsyncTimeout -= elapsed;
2197 AsyncTimeout = TimeSpan.FromTicks (0);
2200 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2203 void EndAsyncTaskCallback (IAsyncResult result)
2205 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2206 task.EndHandler (result);
2209 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2211 Type htmlTextWriterType = typeof (HtmlTextWriter);
2213 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2214 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2217 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2218 if (constructor == null) {
2219 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2222 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2226 [DefaultValue ("0")]
2227 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2228 [EditorBrowsable (EditorBrowsableState.Never)]
2229 public ViewStateEncryptionMode ViewStateEncryptionMode {
2230 get { return viewStateEncryptionMode; }
2231 set { viewStateEncryptionMode = value; }
2234 public void RegisterRequiresViewStateEncryption ()
2236 controlRegisteredForViewStateEncryption = true;
2239 internal bool NeedViewStateEncryption {
2241 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2242 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2243 controlRegisteredForViewStateEncryption));
2248 void ApplyMasterPage ()
2250 if (masterPageFile != null && masterPageFile.Length > 0) {
2251 MasterPage master = Master;
2253 if (master != null) {
2254 var appliedMasterPageFiles = new Dictionary <string, bool> (StringComparer.Ordinal);
2255 MasterPage.ApplyMasterPageRecursive (Request.CurrentExecutionFilePath, HostingEnvironment.VirtualPathProvider, master, appliedMasterPageFiles);
2258 Controls.Add (master);
2263 [DefaultValueAttribute ("")]
2264 public virtual string MasterPageFile {
2265 get { return masterPageFile; }
2267 masterPageFile = value;
2272 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2273 [BrowsableAttribute (false)]
2274 public MasterPage Master {
2276 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2279 if (masterPage == null)
2280 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2286 public void SetFocus (string clientID)
2288 if (String.IsNullOrEmpty (clientID))
2289 throw new ArgumentNullException ("control");
2292 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2295 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2297 _focusedControlID = clientID;
2300 public void SetFocus (Control control)
2302 if (control == null)
2303 throw new ArgumentNullException ("control");
2305 SetFocus (control.ClientID);
2308 [EditorBrowsable (EditorBrowsableState.Advanced)]
2309 public void RegisterRequiresControlState (Control control)
2311 if (control == null)
2312 throw new ArgumentNullException ("control");
2314 if (RequiresControlState (control))
2317 if (requireStateControls == null)
2318 requireStateControls = new List <Control> ();
2319 requireStateControls.Add (control);
2320 int n = requireStateControls.Count - 1;
2322 if (_savedControlState == null || n >= _savedControlState.Length)
2325 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2326 if (parent.IsChildControlStateCleared)
2329 object state = _savedControlState [n];
2331 control.LoadControlState (state);
2334 public bool RequiresControlState (Control control)
2336 if (requireStateControls == null)
2338 return requireStateControls.Contains (control);
2341 [EditorBrowsable (EditorBrowsableState.Advanced)]
2342 public void UnregisterRequiresControlState (Control control)
2344 if (requireStateControls != null)
2345 requireStateControls.Remove (control);
2348 public ValidatorCollection GetValidators (string validationGroup)
2350 if (validationGroup == String.Empty)
2351 validationGroup = null;
2353 ValidatorCollection col = new ValidatorCollection ();
2354 if (_validators == null)
2357 foreach (IValidator v in _validators)
2358 if (BelongsToGroup(v, validationGroup))
2364 bool BelongsToGroup(IValidator v, string validationGroup)
2366 BaseValidator validator = v as BaseValidator;
2367 if (validationGroup == null)
2368 return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
2370 return validator != null && validator.ValidationGroup == validationGroup;
2373 public virtual void Validate (string validationGroup)
2375 is_validated = true;
2376 ValidateCollection (GetValidators (validationGroup));
2379 object SavePageControlState ()
2381 int count = requireStateControls == null ? 0 : requireStateControls.Count;
2386 object[] controlStates = new object [count];
2387 object[] adapterState = new object [count];
2389 ControlAdapter adapter;
2390 bool allNull = true;
2391 TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
2393 for (int n = 0; n < count; n++) {
2394 control = requireStateControls [n];
2395 state = controlStates [n] = control.SaveControlState ();
2400 trace.SaveControlState (control, state);
2402 adapter = control.Adapter;
2403 if (adapter != null) {
2404 adapterState [n] = adapter.SaveAdapterControlState ();
2405 if (adapterState [n] != null) allNull = false;
2412 return new Pair (controlStates, adapterState);
2415 void LoadPageControlState (object data)
2417 _savedControlState = null;
2418 if (data == null) return;
2419 Pair statePair = (Pair)data;
2420 _savedControlState = (object[]) statePair.First;
2421 object[] adapterState = (object[]) statePair.Second;
2423 if (requireStateControls == null) return;
2425 int min = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2426 for (int n=0; n < min; n++) {
2427 Control ctl = (Control) requireStateControls [n];
2428 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2429 if (ctl.Adapter != null)
2430 ctl.Adapter.LoadAdapterControlState (adapterState != null ? adapterState [n] : null);
2434 void LoadPreviousPageReference ()
2436 if (_requestValueCollection != null) {
2437 string prevPage = _requestValueCollection [PreviousPageID];
2438 if (prevPage != null) {
2439 IHttpHandler handler;
2440 handler = BuildManager.CreateInstanceFromVirtualPath (prevPage, typeof (IHttpHandler)) as IHttpHandler;
2441 previousPage = (Page) handler;
2442 previousPage.isCrossPagePostBack = true;
2443 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2448 Hashtable contentTemplates;
2449 [EditorBrowsable (EditorBrowsableState.Never)]
2450 protected internal void AddContentTemplate (string templateName, ITemplate template)
2452 if (contentTemplates == null)
2453 contentTemplates = new Hashtable ();
2454 contentTemplates [templateName] = template;
2457 PageTheme _pageTheme;
2458 internal PageTheme PageTheme {
2459 get { return _pageTheme; }
2462 PageTheme _styleSheetPageTheme;
2463 internal PageTheme StyleSheetPageTheme {
2464 get { return _styleSheetPageTheme; }
2469 internal void PushDataItemContext (object o) {
2470 if (dataItemCtx == null)
2471 dataItemCtx = new Stack ();
2473 dataItemCtx.Push (o);
2476 internal void PopDataItemContext () {
2477 if (dataItemCtx == null)
2478 throw new InvalidOperationException ();
2483 public object GetDataItem() {
2484 if (dataItemCtx == null || dataItemCtx.Count == 0)
2485 throw new InvalidOperationException ("No data item");
2487 return dataItemCtx.Peek ();
2490 void AddStyleSheets (PageTheme theme, ref List <string> links)
2495 string[] tmpThemes = theme != null ? theme.GetStyleSheets () : null;
2496 if (tmpThemes == null || tmpThemes.Length == 0)
2500 links = new List <string> ();
2502 links.AddRange (tmpThemes);
2505 protected internal override void OnInit (EventArgs e)
2509 List <string> themes = null;
2510 AddStyleSheets (StyleSheetPageTheme, ref themes);
2511 AddStyleSheets (PageTheme, ref themes);
2516 HtmlHead header = Header;
2517 if (themes != null && header == null)
2518 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2520 ControlCollection headerControls = header.Controls;
2522 for (int i = themes.Count - 1; i >= 0; i--) {
2524 HtmlLink hl = new HtmlLink ();
2526 hl.Attributes["type"] = "text/css";
2527 hl.Attributes["rel"] = "stylesheet";
2528 headerControls.AddAt (0, hl);
2532 [MonoDocumentationNote ("Not implemented. Only used by .net aspx parser")]
2533 [EditorBrowsable (EditorBrowsableState.Never)]
2534 protected object GetWrappedFileDependencies (string [] list)
2539 [MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
2540 protected virtual void InitializeCulture ()
2544 [MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
2545 [EditorBrowsable (EditorBrowsableState.Never)]
2546 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)