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;
58 using System.Web.Routing;
61 namespace System.Web.UI
64 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
65 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
66 [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
68 [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
69 [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")]
70 public partial class Page : TemplateControl, IHttpHandler
72 // static string machineKeyConfigPath = "system.web/machineKey";
73 bool _eventValidation = true;
74 object [] _savedControlState;
75 bool _doLoadPreviousPage;
76 string _focusedControlID;
77 bool _hasEnabledControlArray;
82 bool _smartNavigation;
84 ValidatorCollection _validators;
86 string _savedViewState;
87 List <string> _requiresPostBack;
88 List <string> _requiresPostBackCopy;
89 List <IPostBackDataHandler> requiresPostDataChanged;
90 IPostBackEventHandler requiresRaiseEvent;
91 IPostBackEventHandler formPostedRequiresRaiseEvent;
92 NameValueCollection secondPostData;
93 bool requiresPostBackScript;
94 bool postBackScriptRendered;
95 bool requiresFormScriptDeclaration;
96 bool formScriptDeclarationRendered;
98 string viewStateUserKey;
99 NameValueCollection _requestValueCollection;
101 ClientScriptManager scriptManager;
102 bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
103 PageStatePersister page_state_persister;
104 CultureInfo _appCulture;
105 CultureInfo _appUICulture;
107 // The initial context
108 HttpContext _context;
110 // cached from the initial context
111 HttpApplicationState _application;
112 HttpResponse _response;
113 HttpRequest _request;
116 HttpSessionState _session;
118 [EditorBrowsable (EditorBrowsableState.Never)]
119 public const string postEventArgumentID = "__EVENTARGUMENT";
121 [EditorBrowsable (EditorBrowsableState.Never)]
122 public const string postEventSourceID = "__EVENTTARGET";
124 const string ScrollPositionXID = "__SCROLLPOSITIONX";
125 const string ScrollPositionYID = "__SCROLLPOSITIONY";
126 const string EnabledControlArrayID = "__enabledControlArray";
127 internal const string LastFocusID = "__LASTFOCUS";
128 internal const string CallbackArgumentID = "__CALLBACKPARAM";
129 internal const string CallbackSourceID = "__CALLBACKID";
130 internal const string PreviousPageID = "__PREVIOUSPAGE";
132 int maxPageStateFieldLength = -1;
133 string uniqueFilePathSuffix;
136 MasterPage masterPage;
137 string masterPageFile;
140 bool isCrossPagePostBack;
143 List <Control> requireStateControls;
148 string _styleSheetTheme;
150 string _metaDescription;
151 string _metaKeywords;
152 Control _autoPostBackControl;
154 bool frameworkInitialized;
158 bool _maintainScrollPositionOnPostBack;
160 bool asyncMode = false;
161 TimeSpan asyncTimeout;
162 const double DefaultAsyncTimeout = 45.0;
163 List<PageAsyncTask> parallelTasks;
164 List<PageAsyncTask> serialTasks;
166 ViewStateEncryptionMode viewStateEncryptionMode;
167 bool controlRegisteredForViewStateEncryption = false;
172 scriptManager = new ClientScriptManager (this);
175 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
177 asyncTimeout = ps.AsyncTimeout;
178 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
179 _viewState = ps.EnableViewState;
180 _viewStateMac = ps.EnableViewStateMac;
182 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
183 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
187 this.ViewStateMode = ViewStateMode.Enabled;
195 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
197 public HttpApplicationState Application {
198 get { return _application; }
201 [EditorBrowsable (EditorBrowsableState.Never)]
202 protected bool AspCompatMode {
203 get { return false; }
209 [EditorBrowsable (EditorBrowsableState.Never)]
210 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
211 [BrowsableAttribute (false)]
213 get { return Response.BufferOutput; }
214 set { Response.BufferOutput = value; }
217 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
222 throw new HttpException ("Cache is not available.");
227 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
228 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
229 [Browsable (false), DefaultValue ("")]
230 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
231 public string ClientTarget {
232 get { return (clientTarget == null) ? String.Empty : clientTarget; }
234 clientTarget = value;
235 if (value == String.Empty)
240 [EditorBrowsable (EditorBrowsableState.Never)]
241 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
242 [BrowsableAttribute (false)]
243 public int CodePage {
244 get { return Response.ContentEncoding.CodePage; }
245 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
248 [EditorBrowsable (EditorBrowsableState.Never)]
249 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
250 [BrowsableAttribute (false)]
251 public string ContentType {
252 get { return Response.ContentType; }
253 set { Response.ContentType = value; }
256 protected internal override HttpContext Context {
258 if (_context == null)
259 return HttpContext.Current;
265 [EditorBrowsable (EditorBrowsableState.Advanced)]
266 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
267 [BrowsableAttribute (false)]
268 public string Culture {
269 get { return Thread.CurrentThread.CurrentCulture.Name; }
270 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
273 [EditorBrowsable (EditorBrowsableState.Never)]
275 [DefaultValue ("true")]
276 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
277 public virtual bool EnableEventValidation {
278 get { return _eventValidation; }
281 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
282 _eventValidation = value;
287 public override bool EnableViewState {
288 get { return _viewState; }
289 set { _viewState = value; }
292 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
293 [BrowsableAttribute (false)]
294 [EditorBrowsable (EditorBrowsableState.Never)]
295 public bool EnableViewStateMac {
296 get { return _viewStateMac; }
297 set { _viewStateMac = value; }
300 internal bool EnableViewStateMacInternal {
301 get { return _viewStateMac; }
302 set { _viewStateMac = value; }
305 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
306 [Browsable (false), DefaultValue ("")]
307 [WebSysDescription ("The URL of a page used for error redirection.")]
308 public string ErrorPage {
309 get { return _errorPage; }
311 HttpContext ctx = Context;
315 ctx.ErrorPage = value;
319 [Obsolete ("The recommended alternative is HttpResponse.AddFileDependencies. http://go.microsoft.com/fwlink/?linkid=14202")]
320 [EditorBrowsable (EditorBrowsableState.Never)]
321 protected ArrayList FileDependencies {
323 if (Response != null)
324 Response.AddFileDependencies (value);
329 [EditorBrowsable (EditorBrowsableState.Never)]
330 public override string ID {
331 get { return base.ID; }
332 set { base.ID = value; }
335 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
337 public bool IsPostBack {
338 get { return isPostBack; }
341 public bool IsPostBackEventControlRegistered {
342 get { return requiresRaiseEvent != null; }
345 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
346 public bool IsReusable {
347 get { return false; }
350 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
352 public bool IsValid {
355 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."));
357 foreach (IValidator val in Validators)
365 public IDictionary Items {
368 items = new Hashtable ();
373 [EditorBrowsable (EditorBrowsableState.Never)]
374 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
375 [BrowsableAttribute (false)]
377 get { return Thread.CurrentThread.CurrentCulture.LCID; }
378 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
382 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
383 public bool MaintainScrollPositionOnPostBack {
384 get { return _maintainScrollPositionOnPostBack; }
385 set { _maintainScrollPositionOnPostBack = value; }
388 public PageAdapter PageAdapter {
390 return Adapter as PageAdapter;
394 string _validationStartupScript;
395 string _validationOnSubmitStatement;
396 string _validationInitializeScript;
397 string _webFormScriptReference;
399 internal string WebFormScriptReference {
401 if (_webFormScriptReference == null)
402 _webFormScriptReference = IsMultiForm ? theForm : "window";
403 return _webFormScriptReference;
407 internal string ValidationStartupScript {
409 if (_validationStartupScript == null) {
410 _validationStartupScript =
412 " + WebFormScriptReference + @".Page_ValidationActive = false;
413 " + WebFormScriptReference + @".ValidatorOnLoad();
414 " + WebFormScriptReference + @".ValidatorOnSubmit = function () {
415 if (this.Page_ValidationActive) {
416 return this.ValidatorCommonOnSubmit();
422 return _validationStartupScript;
426 internal string ValidationOnSubmitStatement {
428 if (_validationOnSubmitStatement == null)
429 _validationOnSubmitStatement = "if (!" + WebFormScriptReference + ".ValidatorOnSubmit()) return false;";
430 return _validationOnSubmitStatement;
434 internal string ValidationInitializeScript {
436 if (_validationInitializeScript == null)
437 _validationInitializeScript = "WebFormValidation_Initialize(" + WebFormScriptReference + ");";
438 return _validationInitializeScript;
442 internal IScriptManager ScriptManager {
443 get { return (IScriptManager) Items [typeof (IScriptManager)]; }
446 internal string theForm {
452 internal bool IsMultiForm {
453 get { return false; }
457 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
459 public HttpRequest Request {
461 if (_request == null)
462 throw new HttpException("Request is not available in this context.");
463 return RequestInternal;
467 internal HttpRequest RequestInternal {
468 get { return _request; }
471 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
473 public HttpResponse Response {
475 if (_response == null)
476 throw new HttpException ("Response is not available in this context.");
481 [EditorBrowsable (EditorBrowsableState.Never)]
482 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
483 [BrowsableAttribute (false)]
484 public string ResponseEncoding {
485 get { return Response.ContentEncoding.WebName; }
486 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
489 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
491 public HttpServerUtility Server {
492 get { return Context.Server; }
495 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
497 public virtual HttpSessionState Session {
499 if (_session != null)
503 _session = Context.Session;
505 // ignore, should not throw
508 if (_session == null)
509 throw new HttpException ("Session state can only be used " +
510 "when enableSessionState is set to true, either " +
511 "in a configuration file or in the Page directive.");
518 [Obsolete ("The recommended alternative is Page.SetFocus and Page.MaintainScrollPositionOnPostBack. http://go.microsoft.com/fwlink/?linkid=14202")]
520 public bool SmartNavigation {
521 get { return _smartNavigation; }
522 set { _smartNavigation = value; }
525 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
528 public virtual string StyleSheetTheme {
529 get { return _styleSheetTheme; }
530 set { _styleSheetTheme = value; }
534 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
535 public virtual string Theme {
536 get { return _theme; }
537 set { _theme = value; }
540 void InitializeStyleSheet ()
542 if (_styleSheetTheme == null) {
543 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
545 _styleSheetTheme = ps.StyleSheetTheme;
548 if (_styleSheetTheme != null && _styleSheetTheme != "")
549 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, Context);
551 if (!String.IsNullOrEmpty (_styleSheetTheme)) {
552 string virtualPath = "~/App_Themes/" + _styleSheetTheme;
553 _styleSheetPageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
558 void InitializeTheme ()
560 if (_theme == null) {
561 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
566 if (_theme != null && _theme != "") {
567 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, Context);
568 _pageTheme.SetPage (this);
571 if (!String.IsNullOrEmpty (_theme)) {
572 string virtualPath = "~/App_Themes/" + _theme;
573 _pageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
574 if (_pageTheme != null)
575 _pageTheme.SetPage (this);
580 public Control AutoPostBackControl {
581 get { return _autoPostBackControl; }
582 set { _autoPostBackControl = value; }
585 [BrowsableAttribute(false)]
586 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
587 public RouteData RouteData {
589 if (_request == null)
592 RequestContext reqctx = _request.RequestContext;
596 return reqctx.RouteData;
601 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
603 public string MetaDescription {
605 if (_metaDescription == null) {
606 if (htmlHeader == null) {
607 if (frameworkInitialized)
608 throw new InvalidOperationException ("A server-side head element is required to set this property.");
611 return htmlHeader.Description;
614 return _metaDescription;
618 if (htmlHeader == null) {
619 if (frameworkInitialized)
620 throw new InvalidOperationException ("A server-side head element is required to set this property.");
621 _metaDescription = value;
623 htmlHeader.Description = value;
628 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
630 public string MetaKeywords {
632 if (_metaKeywords == null) {
633 if (htmlHeader == null) {
634 if (frameworkInitialized)
635 throw new InvalidOperationException ("A server-side head element is required to set this property.");
638 return htmlHeader.Keywords;
641 return _metaDescription;
645 if (htmlHeader == null) {
646 if (frameworkInitialized)
647 throw new InvalidOperationException ("A server-side head element is required to set this property.");
648 _metaKeywords = value;
650 htmlHeader.Keywords = value;
656 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
657 public string Title {
659 if (_title == null) {
660 if (htmlHeader != null && htmlHeader.Title != null)
661 return htmlHeader.Title;
668 if (htmlHeader != null)
669 htmlHeader.Title = value;
675 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
677 public TraceContext Trace {
678 get { return Context.Trace; }
681 [EditorBrowsable (EditorBrowsableState.Never)]
682 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
683 [BrowsableAttribute (false)]
684 public bool TraceEnabled {
685 get { return Trace.IsEnabled; }
686 set { Trace.IsEnabled = value; }
689 [EditorBrowsable (EditorBrowsableState.Never)]
690 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
691 [BrowsableAttribute (false)]
692 public TraceMode TraceModeValue {
693 get { return Trace.TraceMode; }
694 set { Trace.TraceMode = value; }
697 [EditorBrowsable (EditorBrowsableState.Never)]
698 protected int TransactionMode {
699 get { return _transactionMode; }
700 set { _transactionMode = value; }
703 [EditorBrowsable (EditorBrowsableState.Advanced)]
704 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
705 [BrowsableAttribute (false)]
706 public string UICulture {
707 get { return Thread.CurrentThread.CurrentUICulture.Name; }
708 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
711 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
713 public IPrincipal User {
714 get { return Context.User; }
717 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
719 public ValidatorCollection Validators {
721 if (_validators == null)
722 _validators = new ValidatorCollection ();
727 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
729 public string ViewStateUserKey {
730 get { return viewStateUserKey; }
731 set { viewStateUserKey = value; }
735 public override bool Visible {
736 get { return base.Visible; }
737 set { base.Visible = value; }
744 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
748 CultureInfo ret = null;
749 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
751 if (!Context.IsServletRequest)
754 string[] languages = Request.UserLanguages;
756 if (languages != null && languages.Length > 0)
757 ret = CultureInfo.CreateSpecificCulture (languages[0]);
764 ret = CultureInfo.CreateSpecificCulture (culture);
769 [EditorBrowsable (EditorBrowsableState.Never)]
770 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
774 throw new NotImplementedException ();
777 [EditorBrowsable (EditorBrowsableState.Never)]
778 [MonoNotSupported ("Mono does not support classic ASP compatibility mode.")]
779 protected void AspCompatEndProcessRequest (IAsyncResult result)
781 throw new NotImplementedException ();
784 [EditorBrowsable (EditorBrowsableState.Advanced)]
785 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
787 if (Request.BrowserMightHaveSpecialWriter)
788 return Request.Browser.CreateHtmlTextWriter(tw);
790 return new HtmlTextWriter (tw);
793 [EditorBrowsable (EditorBrowsableState.Never)]
794 public void DesignerInitialize ()
796 InitRecursive (null);
799 [EditorBrowsable (EditorBrowsableState.Advanced)]
800 protected internal virtual NameValueCollection DeterminePostBackMode ()
802 // if request was transfered from other page such Transfer
803 if (_context.IsProcessingInclude)
806 HttpRequest req = Request;
810 NameValueCollection coll = null;
811 if (0 == String.Compare (Request.HttpMethod, "POST", true, Helpers.InvariantCulture)
813 || !_context.IsServletRequest
818 string query = Request.QueryStringRaw;
819 if (query == null || query.Length == 0)
822 coll = req.QueryString;
825 WebROCollection c = (WebROCollection) coll;
826 allow_load = !c.GotID;
828 c.ID = GetTypeHashCode ();
830 allow_load = (c.ID == GetTypeHashCode ());
832 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
835 if (getFacesContext () != null && _context.Handler != _context.CurrentHandler) {
836 // check if it is PreviousPage
837 string prevViewId = coll [PreviousPageID];
838 if (!String.IsNullOrEmpty (prevViewId)) {
839 string appPath = VirtualPathUtility.RemoveTrailingSlash (Request.ApplicationPath);
840 prevViewId = prevViewId.Substring (appPath.Length);
841 isCrossPagePostBack = String.Compare (prevViewId, getFacesContext ().getExternalContext ().getRequestPathInfo (), StringComparison.OrdinalIgnoreCase) == 0;
848 public override Control FindControl (string id) {
852 return base.FindControl (id);
855 Control FindControl (string id, bool decode) {
858 id = DecodeNamespace (id);
860 return FindControl (id);
863 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
864 [EditorBrowsable (EditorBrowsableState.Advanced)]
865 public string GetPostBackClientEvent (Control control, string argument)
867 return scriptManager.GetPostBackEventReference (control, argument);
870 [Obsolete ("The recommended alternative is ClientScript.GetPostBackClientHyperlink. http://go.microsoft.com/fwlink/?linkid=14202")]
871 [EditorBrowsable (EditorBrowsableState.Advanced)]
872 public string GetPostBackClientHyperlink (Control control, string argument)
874 return scriptManager.GetPostBackClientHyperlink (control, argument);
877 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
878 [EditorBrowsable (EditorBrowsableState.Advanced)]
879 public string GetPostBackEventReference (Control control)
881 return scriptManager.GetPostBackEventReference (control, String.Empty);
884 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
885 [EditorBrowsable (EditorBrowsableState.Advanced)]
886 public string GetPostBackEventReference (Control control, string argument)
888 return scriptManager.GetPostBackEventReference (control, argument);
891 internal void RequiresFormScriptDeclaration ()
893 requiresFormScriptDeclaration = true;
896 internal void RequiresPostBackScript ()
898 if (requiresPostBackScript)
900 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
901 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
902 requiresPostBackScript = true;
903 RequiresFormScriptDeclaration ();
906 [EditorBrowsable (EditorBrowsableState.Never)]
907 public virtual int GetTypeHashCode ()
912 [MonoTODO ("The following properties of OutputCacheParameters are silently ignored: CacheProfile, SqlDependency")]
913 [EditorBrowsable (EditorBrowsableState.Never)]
914 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
916 if (cacheSettings.Enabled) {
917 InitOutputCache(cacheSettings.Duration,
918 cacheSettings.VaryByContentEncoding,
919 cacheSettings.VaryByHeader,
920 cacheSettings.VaryByCustom,
921 cacheSettings.Location,
922 cacheSettings.VaryByParam);
924 HttpResponse response = Response;
925 HttpCachePolicy cache = response != null ? response.Cache : null;
926 if (cache != null && cacheSettings.NoStore)
931 [MonoTODO ("varyByContentEncoding is not currently used")]
932 [EditorBrowsable (EditorBrowsableState.Never)]
933 protected virtual void InitOutputCache(int duration,
934 string varyByContentEncoding,
937 OutputCacheLocation location,
941 // No need to do anything, cache will be ineffective anyway
944 HttpResponse response = Response;
945 HttpCachePolicy cache = response.Cache;
946 bool set_vary = false;
947 HttpContext ctx = Context;
948 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
951 case OutputCacheLocation.Any:
952 cache.SetCacheability (HttpCacheability.Public);
953 cache.SetMaxAge (new TimeSpan (0, 0, duration));
954 cache.SetLastModified (timestamp);
957 case OutputCacheLocation.Client:
958 cache.SetCacheability (HttpCacheability.Private);
959 cache.SetMaxAge (new TimeSpan (0, 0, duration));
960 cache.SetLastModified (timestamp);
962 case OutputCacheLocation.Downstream:
963 cache.SetCacheability (HttpCacheability.Public);
964 cache.SetMaxAge (new TimeSpan (0, 0, duration));
965 cache.SetLastModified (timestamp);
967 case OutputCacheLocation.Server:
968 cache.SetCacheability (HttpCacheability.Server);
971 case OutputCacheLocation.None:
976 if (varyByCustom != null)
977 cache.SetVaryByCustom (varyByCustom);
979 if (varyByParam != null && varyByParam.Length > 0) {
980 string[] prms = varyByParam.Split (';');
981 foreach (string p in prms)
982 cache.VaryByParams [p.Trim ()] = true;
983 cache.VaryByParams.IgnoreParams = false;
985 cache.VaryByParams.IgnoreParams = true;
988 if (varyByHeader != null && varyByHeader.Length > 0) {
989 string[] hdrs = varyByHeader.Split (';');
990 foreach (string h in hdrs)
991 cache.VaryByHeaders [h.Trim ()] = true;
994 if (PageAdapter != null) {
995 if (PageAdapter.CacheVaryByParams != null) {
996 foreach (string p in PageAdapter.CacheVaryByParams)
997 cache.VaryByParams [p] = true;
999 if (PageAdapter.CacheVaryByHeaders != null) {
1000 foreach (string h in PageAdapter.CacheVaryByHeaders)
1001 cache.VaryByHeaders [h] = true;
1006 response.IsCached = true;
1007 cache.Duration = duration;
1008 cache.SetExpires (timestamp.AddSeconds (duration));
1012 [EditorBrowsable (EditorBrowsableState.Never)]
1013 protected virtual void InitOutputCache (int duration,
1014 string varyByHeader,
1015 string varyByCustom,
1016 OutputCacheLocation location,
1019 InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
1022 [Obsolete ("The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
1023 public bool IsClientScriptBlockRegistered (string key)
1025 return scriptManager.IsClientScriptBlockRegistered (key);
1028 [Obsolete ("The recommended alternative is ClientScript.IsStartupScriptRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
1029 public bool IsStartupScriptRegistered (string key)
1031 return scriptManager.IsStartupScriptRegistered (key);
1034 public string MapPath (string virtualPath)
1036 return Request.MapPath (virtualPath);
1039 protected internal override void Render (HtmlTextWriter writer)
1041 if (MaintainScrollPositionOnPostBack) {
1042 ClientScript.RegisterWebFormClientScript ();
1044 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
1045 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
1047 StringBuilder script = new StringBuilder ();
1048 script.AppendLine ("<script type=\"text/javascript\">");
1049 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
1050 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
1051 script.AppendLine (theForm + ".submit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionSubmit(); }");
1052 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
1053 script.AppendLine (theForm + ".onsubmit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionOnSubmit(); }");
1055 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
1056 script.AppendLine ("window.onload = function () { " + WebFormScriptReference + ".WebForm_RestoreScrollPosition (); };");
1058 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
1059 script.AppendLine ("</script>");
1061 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1064 if (bool.Parse (WebConfigurationManager.AppSettings [RenderBodyContentOnlyKey] ?? "false")) {
1065 for (Control c = this.Form; c != null; c = c.Parent) {
1066 HtmlGenericControl ch = (c as HtmlGenericControl);
1067 if (ch != null && ch.TagName == "body") {
1068 ch.RenderChildren (writer);
1074 base.Render (writer);
1077 void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1079 writer.WriteLine ();
1080 ClientScriptManager.WriteBeginScriptBlock (writer);
1081 RenderClientScriptFormDeclaration (writer, formUniqueID);
1082 writer.WriteLine (WebFormScriptReference + "._form = " + theForm + ";");
1083 writer.WriteLine (WebFormScriptReference + ".__doPostBack = function (eventTarget, eventArgument) {");
1084 writer.WriteLine ("\tif(" + theForm + ".onsubmit && " + theForm + ".onsubmit() == false) return;");
1085 writer.WriteLine ("\t" + theForm + "." + postEventSourceID + ".value = eventTarget;");
1086 writer.WriteLine ("\t" + theForm + "." + postEventArgumentID + ".value = eventArgument;");
1087 writer.WriteLine ("\t" + theForm + ".submit();");
1088 writer.WriteLine ("}");
1089 ClientScriptManager.WriteEndScriptBlock (writer);
1092 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1094 if (formScriptDeclarationRendered)
1097 if (PageAdapter != null) {
1098 writer.WriteLine ("\tvar {0} = {1};\n", theForm, PageAdapter.GetPostBackFormReference(formUniqueID));
1100 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1101 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1104 // TODO implement callback on portlet
1105 string serverUrl = Request.RawUrl;
1106 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1107 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1108 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1110 formScriptDeclarationRendered = true;
1113 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1116 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1118 renderingForm = true;
1119 writer.WriteLine ();
1121 if (requiresFormScriptDeclaration || (scriptManager != null && scriptManager.ScriptsPresent) || PageAdapter != null) {
1122 ClientScriptManager.WriteBeginScriptBlock (writer);
1123 RenderClientScriptFormDeclaration (writer, formUniqueID);
1124 ClientScriptManager.WriteEndScriptBlock (writer);
1127 if (handleViewState)
1129 if (getFacesContext () != null) {
1130 javax.faces.application.ViewHandler viewHandler = getFacesContext ().getApplication ().getViewHandler ();
1131 javax.faces.context.ResponseWriter oldFacesWriter = SetupResponseWriter (writer);
1133 viewHandler.writeState (getFacesContext ());
1136 getFacesContext ().setResponseWriter (oldFacesWriter);
1140 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1142 scriptManager.WriteHiddenFields (writer);
1143 if (requiresPostBackScript) {
1144 RenderPostBackScript (writer, formUniqueID);
1145 postBackScriptRendered = true;
1148 scriptManager.WriteWebFormClientScript (writer);
1149 scriptManager.WriteClientScriptBlocks (writer);
1152 internal IStateFormatter GetFormatter ()
1154 return new ObjectStateFormatter (this);
1157 internal string GetSavedViewState ()
1159 return _savedViewState;
1162 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1164 scriptManager.SaveEventValidationState ();
1165 scriptManager.WriteExpandoAttributes (writer);
1166 scriptManager.WriteHiddenFields (writer);
1167 if (!postBackScriptRendered && requiresPostBackScript)
1168 RenderPostBackScript (writer, formUniqueID);
1169 scriptManager.WriteWebFormClientScript (writer);
1170 scriptManager.WriteArrayDeclares (writer);
1171 scriptManager.WriteStartupScriptBlocks (writer);
1172 renderingForm = false;
1173 postBackScriptRendered = false;
1176 void ProcessPostData (NameValueCollection data, bool second)
1178 NameValueCollection requestValues = _requestValueCollection == null ? new NameValueCollection () : _requestValueCollection;
1180 if (data != null && data.Count > 0) {
1181 var used = new Dictionary <string, string> (StringComparer.Ordinal);
1182 foreach (string id in data.AllKeys) {
1183 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID || id == ClientScriptManager.EventStateFieldName)
1186 if (used.ContainsKey (id))
1191 Control ctrl = FindControl (id, true);
1193 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1194 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1198 formPostedRequiresRaiseEvent = pbeh;
1202 if (pbdh.LoadPostData (id, requestValues) == true) {
1203 if (requiresPostDataChanged == null)
1204 requiresPostDataChanged = new List <IPostBackDataHandler> ();
1205 requiresPostDataChanged.Add (pbdh);
1208 if (_requiresPostBackCopy != null)
1209 _requiresPostBackCopy.Remove (id);
1211 } else if (!second) {
1212 if (secondPostData == null)
1213 secondPostData = new NameValueCollection ();
1214 secondPostData.Add (id, data [id]);
1219 List <string> list1 = null;
1220 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1221 string [] handlers = (string []) _requiresPostBackCopy.ToArray ();
1222 foreach (string id in handlers) {
1223 IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
1225 _requiresPostBackCopy.Remove (id);
1226 if (pbdh.LoadPostData (id, requestValues)) {
1227 if (requiresPostDataChanged == null)
1228 requiresPostDataChanged = new List <IPostBackDataHandler> ();
1230 requiresPostDataChanged.Add (pbdh);
1232 } else if (!second) {
1234 list1 = new List <string> ();
1239 _requiresPostBackCopy = second ? null : list1;
1241 secondPostData = null;
1244 [EditorBrowsable (EditorBrowsableState.Never)]
1245 public virtual void ProcessRequest (HttpContext context)
1247 SetContext (context);
1249 bool wasException = false;
1250 IHttpHandler jsfHandler = getFacesContext () != null ? EnterThread () : null;
1253 if (clientTarget != null)
1254 Request.ClientTarget = clientTarget;
1256 WireupAutomaticEvents ();
1257 //-- Control execution lifecycle in the docs
1259 // Save culture information because it can be modified in FrameworkInitialize()
1260 _appCulture = Thread.CurrentThread.CurrentCulture;
1261 _appUICulture = Thread.CurrentThread.CurrentUICulture;
1262 FrameworkInitialize ();
1264 frameworkInitialized = true;
1266 context.ErrorPage = _errorPage;
1269 InternalProcessRequest ();
1271 } catch (Exception ex) {
1272 wasException = true;
1273 HandleException (ex);
1275 } catch (ThreadAbortException taex) {
1276 if (FlagEnd.Value == taex.ExceptionState)
1277 Thread.ResetAbort ();
1280 } catch (Exception e) {
1281 ProcessException (e);
1285 if (getFacesContext () != null)
1286 ExitThread (jsfHandler);
1287 else if (!wasException)
1293 void ProcessException (Exception e) {
1294 // We want to remove that error, as we're rethrowing to stop
1295 // further processing.
1296 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1297 _context.AddError (e); // OnError might access LastError
1298 OnError (EventArgs.Empty);
1299 if (_context.HasError (e)) {
1300 _context.ClearError (e);
1302 vmw.common.TypeUtils.Throw (e);
1304 throw new HttpUnhandledException (null, e);
1309 void ProcessUnload () {
1312 UnloadRecursive (true);
1315 if (getFacesContext () != null) {
1316 if(IsCrossPagePostBack)
1317 _context.Items [CrossPagePostBack] = this;
1320 if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
1321 Thread.CurrentThread.CurrentCulture = _appCulture;
1323 if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
1324 Thread.CurrentThread.CurrentUICulture = _appUICulture;
1327 _appUICulture = null;
1330 delegate void ProcessRequestDelegate (HttpContext context);
1332 sealed class DummyAsyncResult : IAsyncResult
1334 readonly object state;
1335 readonly WaitHandle asyncWaitHandle;
1336 readonly bool completedSynchronously;
1337 readonly bool isCompleted;
1339 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1341 this.isCompleted = isCompleted;
1342 this.completedSynchronously = completedSynchronously;
1345 asyncWaitHandle = new ManualResetEvent (true);
1348 asyncWaitHandle = new ManualResetEvent (false);
1352 #region IAsyncResult Members
1354 public object AsyncState {
1355 get { return state; }
1358 public WaitHandle AsyncWaitHandle {
1359 get { return asyncWaitHandle; }
1362 public bool CompletedSynchronously {
1363 get { return completedSynchronously; }
1366 public bool IsCompleted {
1367 get { return isCompleted; }
1373 [EditorBrowsable (EditorBrowsableState.Never)]
1374 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1376 ProcessRequest (context);
1377 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1379 if (callback != null) {
1380 callback (asyncResult);
1386 [EditorBrowsable (EditorBrowsableState.Never)]
1387 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1391 void InternalProcessRequest ()
1393 if (PageAdapter != null)
1394 _requestValueCollection = PageAdapter.DeterminePostBackMode();
1396 _requestValueCollection = this.DeterminePostBackMode();
1398 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1399 if (_requestValueCollection != null) {
1400 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1401 _doLoadPreviousPage = true;
1403 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1404 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1405 //isPostBack = !isCallback;
1409 string lastFocus = _requestValueCollection [LastFocusID];
1410 if (!String.IsNullOrEmpty (lastFocus))
1411 _focusedControlID = UniqueID2ClientID (lastFocus);
1414 if (!isCrossPagePostBack) {
1415 if (_context.PreviousHandler is Page)
1416 previousPage = (Page) _context.PreviousHandler;
1419 Trace.Write ("aspx.page", "Begin PreInit");
1420 OnPreInit (EventArgs.Empty);
1421 Trace.Write ("aspx.page", "End PreInit");
1425 Trace.Write ("aspx.page", "Begin Init");
1426 InitRecursive (null);
1427 Trace.Write ("aspx.page", "End Init");
1429 Trace.Write ("aspx.page", "Begin InitComplete");
1430 OnInitComplete (EventArgs.Empty);
1431 Trace.Write ("aspx.page", "End InitComplete");
1433 renderingForm = false;
1436 if (getFacesContext () != null)
1437 if (IsPostBack || IsCallback)
1441 RestorePageState ();
1443 ProcessRaiseEvents ();
1444 if (ProcessLoadComplete ())
1447 if (getFacesContext () != null) {
1448 getFacesContext ().renderResponse ();
1455 void RestorePageState ()
1457 if (IsPostBack || IsCallback) {
1458 if (_requestValueCollection != null)
1459 scriptManager.RestoreEventValidationState (
1460 _requestValueCollection [ClientScriptManager.EventStateFieldName]);
1461 Trace.Write ("aspx.page", "Begin LoadViewState");
1462 LoadPageViewState ();
1463 Trace.Write ("aspx.page", "End LoadViewState");
1467 void ProcessPostData ()
1469 if (IsPostBack || IsCallback) {
1470 Trace.Write ("aspx.page", "Begin ProcessPostData");
1471 ProcessPostData (_requestValueCollection, false);
1472 Trace.Write ("aspx.page", "End ProcessPostData");
1476 if (IsPostBack || IsCallback) {
1477 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1478 ProcessPostData (secondPostData, true);
1479 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1485 Trace.Write ("aspx.page", "Begin PreLoad");
1486 OnPreLoad (EventArgs.Empty);
1487 Trace.Write ("aspx.page", "End PreLoad");
1489 Trace.Write ("aspx.page", "Begin Load");
1491 Trace.Write ("aspx.page", "End Load");
1494 void ProcessRaiseEvents ()
1496 if (IsPostBack || IsCallback) {
1497 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1498 RaiseChangedEvents ();
1499 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1500 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1501 RaisePostBackEvents ();
1502 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1506 bool ProcessLoadComplete ()
1508 Trace.Write ("aspx.page", "Begin LoadComplete");
1509 OnLoadComplete (EventArgs.Empty);
1510 Trace.Write ("aspx.page", "End LoadComplete");
1512 if (IsCrossPagePostBack)
1517 if (getFacesContext () != null) {
1518 _callbackTarget = GetCallbackTarget ();
1519 ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError);
1523 string result = ProcessCallbackData ();
1524 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1525 callbackOutput.Write (result);
1526 callbackOutput.Flush ();
1530 Trace.Write ("aspx.page", "Begin PreRender");
1531 PreRenderRecursiveInternal ();
1532 Trace.Write ("aspx.page", "End PreRender");
1534 ExecuteRegisteredAsyncTasks ();
1536 Trace.Write ("aspx.page", "Begin PreRenderComplete");
1537 OnPreRenderComplete (EventArgs.Empty);
1538 Trace.Write ("aspx.page", "End PreRenderComplete");
1540 Trace.Write ("aspx.page", "Begin SaveViewState");
1541 SavePageViewState ();
1542 Trace.Write ("aspx.page", "End SaveViewState");
1544 Trace.Write ("aspx.page", "Begin SaveStateComplete");
1545 OnSaveStateComplete (EventArgs.Empty);
1546 Trace.Write ("aspx.page", "End SaveStateComplete");
1550 internal void RenderPage ()
1552 scriptManager.ResetEventValidationState ();
1555 Trace.Write ("aspx.page", "Begin Render");
1556 HtmlTextWriter output = CreateHtmlTextWriter (Response.Output);
1557 RenderControl (output);
1558 Trace.Write ("aspx.page", "End Render");
1561 internal void SetContext (HttpContext context)
1565 _application = context.Application;
1566 _response = context.Response;
1567 _request = context.Request;
1568 _cache = context.Cache;
1573 TraceManager traceManager = HttpRuntime.TraceManager;
1575 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1580 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1583 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1584 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1585 Trace.Render (output);
1589 void RaisePostBackEvents ()
1591 if (requiresRaiseEvent != null) {
1592 RaisePostBackEvent (requiresRaiseEvent, null);
1596 if (formPostedRequiresRaiseEvent != null) {
1597 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1601 NameValueCollection postdata = _requestValueCollection;
1602 if (postdata == null)
1605 string eventTarget = postdata [postEventSourceID];
1606 IPostBackEventHandler target;
1607 if (String.IsNullOrEmpty (eventTarget)) {
1609 target = AutoPostBackControl as IPostBackEventHandler;
1611 RaisePostBackEvent (target, null);
1614 if (formPostedRequiresRaiseEvent != null)
1615 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1621 target = FindControl (eventTarget, true) as IPostBackEventHandler;
1624 target = AutoPostBackControl as IPostBackEventHandler;
1629 string eventArgument = postdata [postEventArgumentID];
1630 RaisePostBackEvent (target, eventArgument);
1633 internal void RaiseChangedEvents ()
1635 if (requiresPostDataChanged == null)
1638 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1639 ipdh.RaisePostDataChangedEvent ();
1641 requiresPostDataChanged = null;
1644 [EditorBrowsable (EditorBrowsableState.Advanced)]
1645 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1647 sourceControl.RaisePostBackEvent (eventArgument);
1650 [Obsolete ("The recommended alternative is ClientScript.RegisterArrayDeclaration(string arrayName, string arrayValue). http://go.microsoft.com/fwlink/?linkid=14202")]
1651 [EditorBrowsable (EditorBrowsableState.Advanced)]
1652 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1654 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1657 [Obsolete ("The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1658 [EditorBrowsable (EditorBrowsableState.Advanced)]
1659 public virtual void RegisterClientScriptBlock (string key, string script)
1661 scriptManager.RegisterClientScriptBlock (key, script);
1665 [EditorBrowsable (EditorBrowsableState.Advanced)]
1666 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1668 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1671 [MonoTODO("Not implemented, Used in HtmlForm")]
1672 internal void RegisterClientScriptFile (string a, string b, string c)
1674 throw new NotImplementedException ();
1677 [Obsolete ("The recommended alternative is ClientScript.RegisterOnSubmitStatement(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1678 [EditorBrowsable (EditorBrowsableState.Advanced)]
1679 public void RegisterOnSubmitStatement (string key, string script)
1681 scriptManager.RegisterOnSubmitStatement (key, script);
1684 internal string GetSubmitStatements ()
1686 return scriptManager.WriteSubmitStatements ();
1689 [EditorBrowsable (EditorBrowsableState.Advanced)]
1690 public void RegisterRequiresPostBack (Control control)
1692 if (!(control is IPostBackDataHandler))
1693 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1695 if (_requiresPostBack == null)
1696 _requiresPostBack = new List <string> ();
1698 string uniqueID = control.UniqueID;
1699 if (_requiresPostBack.Contains (uniqueID))
1702 _requiresPostBack.Add (uniqueID);
1705 [EditorBrowsable (EditorBrowsableState.Advanced)]
1706 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1708 requiresRaiseEvent = control;
1711 [Obsolete ("The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1712 [EditorBrowsable (EditorBrowsableState.Advanced)]
1713 public virtual void RegisterStartupScript (string key, string script)
1715 scriptManager.RegisterStartupScript (key, script);
1718 [EditorBrowsable (EditorBrowsableState.Advanced)]
1719 public void RegisterViewStateHandler ()
1721 handleViewState = true;
1724 [EditorBrowsable (EditorBrowsableState.Advanced)]
1725 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1727 PageStatePersister persister = this.PageStatePersister;
1728 if (persister == null)
1730 Pair pair = viewState as Pair;
1732 persister.ViewState = pair.First;
1733 persister.ControlState = pair.Second;
1735 persister.ViewState = viewState;
1739 internal string RawViewState {
1741 NameValueCollection postdata = _requestValueCollection;
1743 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1746 if (view_state == String.Empty)
1751 set { _savedViewState = value; }
1755 protected virtual PageStatePersister PageStatePersister {
1757 if (page_state_persister == null && PageAdapter != null)
1758 page_state_persister = PageAdapter.GetStatePersister();
1759 if (page_state_persister == null)
1760 page_state_persister = new HiddenFieldPageStatePersister (this);
1761 return page_state_persister;
1765 [EditorBrowsable (EditorBrowsableState.Advanced)]
1766 protected virtual object LoadPageStateFromPersistenceMedium ()
1768 PageStatePersister persister = this.PageStatePersister;
1769 if (persister == null)
1772 return new Pair (persister.ViewState, persister.ControlState);
1775 internal void LoadPageViewState ()
1777 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1778 if (sState != null) {
1779 if (allow_load || isCrossPagePostBack) {
1780 LoadPageControlState (sState.Second);
1782 Pair vsr = sState.First as Pair;
1784 LoadViewStateRecursive (vsr.First);
1785 _requiresPostBackCopy = vsr.Second as List <string>;
1791 internal void SavePageViewState ()
1793 if (!handleViewState)
1796 object controlState = SavePageControlState ();
1798 object viewState = null;
1802 && this.ViewStateMode == ViewStateMode.Enabled
1805 viewState = SaveViewStateRecursive ();
1807 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1808 if (viewState != null || reqPostback != null)
1809 vsr = new Pair (viewState, reqPostback);
1811 Pair pair = new Pair ();
1813 pair.Second = controlState;
1814 if (pair.First == null && pair.Second == null)
1815 SavePageStateToPersistenceMedium (null);
1817 SavePageStateToPersistenceMedium (pair);
1821 public virtual void Validate ()
1823 is_validated = true;
1824 ValidateCollection (_validators);
1827 internal bool AreValidatorsUplevel ()
1829 return AreValidatorsUplevel (String.Empty);
1832 internal bool AreValidatorsUplevel (string valGroup)
1834 bool uplevel = false;
1836 foreach (IValidator v in Validators) {
1837 BaseValidator bv = v as BaseValidator;
1841 if (valGroup != bv.ValidationGroup)
1843 if (bv.GetRenderUplevel()) {
1852 bool ValidateCollection (ValidatorCollection validators)
1854 if (validators == null || validators.Count == 0)
1857 bool all_valid = true;
1858 foreach (IValidator v in validators){
1860 if (v.IsValid == false)
1867 [EditorBrowsable (EditorBrowsableState.Advanced)]
1868 public virtual void VerifyRenderingInServerForm (Control control)
1870 if (Context == null)
1875 throw new HttpException ("Control '" +
1878 control.GetType ().Name +
1879 "' must be placed inside a form tag with runat=server.");
1882 protected override void FrameworkInitialize ()
1884 base.FrameworkInitialize ();
1885 InitializeStyleSheet ();
1889 public ClientScriptManager ClientScript {
1890 get { return scriptManager; }
1893 internal static readonly object InitCompleteEvent = new object ();
1894 internal static readonly object LoadCompleteEvent = new object ();
1895 internal static readonly object PreInitEvent = new object ();
1896 internal static readonly object PreLoadEvent = new object ();
1897 internal static readonly object PreRenderCompleteEvent = new object ();
1898 internal static readonly object SaveStateCompleteEvent = new object ();
1900 const int initcomplete_mask = 1;
1901 const int loadcomplete_mask = 1 << 1;
1902 const int preinit_mask = 1 << 2;
1903 const int preload_mask = 1 << 3;
1904 const int prerendercomplete_mask = 1 << 4;
1905 const int savestatecomplete_mask = 1 << 5;
1907 [EditorBrowsable (EditorBrowsableState.Advanced)]
1908 public event EventHandler InitComplete {
1910 event_mask |= initcomplete_mask;
1911 Events.AddHandler (InitCompleteEvent, value);
1913 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1916 [EditorBrowsable (EditorBrowsableState.Advanced)]
1917 public event EventHandler LoadComplete {
1919 event_mask |= loadcomplete_mask;
1920 Events.AddHandler (LoadCompleteEvent, value);
1922 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1925 public event EventHandler PreInit {
1927 event_mask |= preinit_mask;
1928 Events.AddHandler (PreInitEvent, value);
1930 remove { Events.RemoveHandler (PreInitEvent, value); }
1933 [EditorBrowsable (EditorBrowsableState.Advanced)]
1934 public event EventHandler PreLoad {
1936 event_mask |= preload_mask;
1937 Events.AddHandler (PreLoadEvent, value);
1939 remove { Events.RemoveHandler (PreLoadEvent, value); }
1942 [EditorBrowsable (EditorBrowsableState.Advanced)]
1943 public event EventHandler PreRenderComplete {
1945 event_mask |= prerendercomplete_mask;
1946 Events.AddHandler (PreRenderCompleteEvent, value);
1948 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1951 [EditorBrowsable (EditorBrowsableState.Advanced)]
1952 public event EventHandler SaveStateComplete {
1954 event_mask |= savestatecomplete_mask;
1955 Events.AddHandler (SaveStateCompleteEvent, value);
1957 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1960 protected virtual void OnInitComplete (EventArgs e)
1962 if ((event_mask & initcomplete_mask) != 0) {
1963 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1964 if (eh != null) eh (this, e);
1968 protected virtual void OnLoadComplete (EventArgs e)
1970 if ((event_mask & loadcomplete_mask) != 0) {
1971 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1972 if (eh != null) eh (this, e);
1976 protected virtual void OnPreInit (EventArgs e)
1978 if ((event_mask & preinit_mask) != 0) {
1979 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1980 if (eh != null) eh (this, e);
1984 protected virtual void OnPreLoad (EventArgs e)
1986 if ((event_mask & preload_mask) != 0) {
1987 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1988 if (eh != null) eh (this, e);
1992 protected virtual void OnPreRenderComplete (EventArgs e)
1994 if ((event_mask & prerendercomplete_mask) != 0) {
1995 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1996 if (eh != null) eh (this, e);
2001 if (!Form.DetermineRenderUplevel ())
2004 string defaultButtonId = Form.DefaultButton;
2005 /* figure out if we have some control we're going to focus */
2006 if (String.IsNullOrEmpty (_focusedControlID)) {
2007 _focusedControlID = Form.DefaultFocus;
2008 if (String.IsNullOrEmpty (_focusedControlID))
2009 _focusedControlID = defaultButtonId;
2012 if (!String.IsNullOrEmpty (_focusedControlID)) {
2013 ClientScript.RegisterWebFormClientScript ();
2015 ClientScript.RegisterStartupScript (
2017 "HtmlForm-DefaultButton-StartupScript",
2018 "\n" + WebFormScriptReference + ".WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
2021 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
2022 ClientScript.RegisterWebFormClientScript ();
2024 ClientScript.RegisterOnSubmitStatement (
2026 "HtmlForm-SubmitDisabledControls-SubmitStatement",
2027 WebFormScriptReference + ".WebForm_ReEnableControls();");
2031 internal void RegisterEnabledControl (Control control)
2033 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
2035 _hasEnabledControlArray = true;
2036 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
2039 protected virtual void OnSaveStateComplete (EventArgs e)
2041 if ((event_mask & savestatecomplete_mask) != 0) {
2042 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
2043 if (eh != null) eh (this, e);
2047 public HtmlForm Form {
2048 get { return _form; }
2051 internal void RegisterForm (HtmlForm form)
2056 public string ClientQueryString {
2057 get { return Request.UrlComponents.Query; }
2060 [BrowsableAttribute (false)]
2061 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2062 public Page PreviousPage {
2064 if (_doLoadPreviousPage) {
2065 _doLoadPreviousPage = false;
2066 LoadPreviousPageReference ();
2068 return previousPage;
2073 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2074 [BrowsableAttribute (false)]
2075 public bool IsCallback {
2076 get { return isCallback; }
2079 [BrowsableAttribute (false)]
2080 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2081 public bool IsCrossPagePostBack {
2082 get { return isCrossPagePostBack; }
2086 [EditorBrowsable (EditorBrowsableState.Never)]
2087 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2088 public new virtual char IdSeparator {
2090 //TODO: why override?
2091 return base.IdSeparator;
2095 string ProcessCallbackData ()
2097 ICallbackEventHandler target = GetCallbackTarget ();
2098 string callbackEventError = String.Empty;
2099 ProcessRaiseCallbackEvent (target, ref callbackEventError);
2100 return ProcessGetCallbackResult (target, callbackEventError);
2103 ICallbackEventHandler GetCallbackTarget ()
2105 string callbackTarget = _requestValueCollection [CallbackSourceID];
2106 if (callbackTarget == null || callbackTarget.Length == 0)
2107 throw new HttpException ("Callback target not provided.");
2109 Control targetControl = FindControl (callbackTarget, true);
2110 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2112 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2116 void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError)
2118 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2121 target.RaiseCallbackEvent (callbackArgument);
2122 } catch (Exception ex) {
2123 callbackEventError = String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2128 string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError)
2130 string callBackResult;
2132 callBackResult = target.GetCallbackResult ();
2133 } catch (Exception ex) {
2134 return String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2137 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2138 return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
2139 eventValidation + callBackResult;
2142 [BrowsableAttribute (false)]
2143 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2144 public HtmlHead Header {
2145 get { return htmlHeader; }
2148 internal void SetHeader (HtmlHead header)
2150 htmlHeader = header;
2154 if (_title != null) {
2155 htmlHeader.Title = _title;
2159 if (_metaDescription != null) {
2160 htmlHeader.Description = _metaDescription;
2161 _metaDescription = null;
2164 if (_metaKeywords != null) {
2165 htmlHeader.Keywords = _metaKeywords;
2166 _metaKeywords = null;
2171 [EditorBrowsable (EditorBrowsableState.Never)]
2172 protected bool AsyncMode {
2173 get { return asyncMode; }
2174 set { asyncMode = value; }
2178 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2179 [EditorBrowsable (EditorBrowsableState.Advanced)]
2180 public TimeSpan AsyncTimeout {
2181 get { return asyncTimeout; }
2182 set { asyncTimeout = value; }
2185 public bool IsAsync {
2186 get { return AsyncMode; }
2189 protected internal virtual string UniqueFilePathSuffix {
2191 if (String.IsNullOrEmpty (uniqueFilePathSuffix))
2192 uniqueFilePathSuffix = "__ufps=" + AppRelativeVirtualPath.GetHashCode ().ToString ("x");
2193 return uniqueFilePathSuffix;
2197 [MonoTODO ("Actually use the value in code.")]
2199 [EditorBrowsable (EditorBrowsableState.Never)]
2200 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2201 public int MaxPageStateFieldLength {
2202 get { return maxPageStateFieldLength; }
2203 set { maxPageStateFieldLength = value; }
2206 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2208 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2211 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2214 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2217 if (IsPrerendered) {
2218 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
2221 if (beginHandler == null) {
2222 throw new ArgumentNullException ("beginHandler");
2225 if (endHandler == null) {
2226 throw new ArgumentNullException ("endHandler");
2229 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2232 List<PageAsyncTask> ParallelTasks {
2234 if (parallelTasks == null)
2235 parallelTasks = new List<PageAsyncTask>();
2236 return parallelTasks;
2240 List<PageAsyncTask> SerialTasks {
2242 if (serialTasks == null)
2243 serialTasks = new List<PageAsyncTask> ();
2248 public void RegisterAsyncTask (PageAsyncTask task)
2251 throw new ArgumentNullException ("task");
2253 if (task.ExecuteInParallel)
2254 ParallelTasks.Add (task);
2256 SerialTasks.Add (task);
2259 public void ExecuteRegisteredAsyncTasks ()
2261 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2262 (serialTasks == null || serialTasks.Count == 0)){
2266 if (parallelTasks != null) {
2267 DateTime startExecution = DateTime.Now;
2268 List<PageAsyncTask> localParallelTasks = parallelTasks;
2269 parallelTasks = null; // Shouldn't execute tasks twice
2270 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2271 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2272 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2273 if (result.CompletedSynchronously)
2274 parallelTask.EndHandler (result);
2276 asyncResults.Add (result);
2279 if (asyncResults.Count > 0) {
2281 TimeSpan timeout = AsyncTimeout;
2282 long t1 = DateTime.Now.Ticks;
2283 bool signalled = true;
2284 for (int i = 0; i < asyncResults.Count; i++) {
2285 if (asyncResults [i].IsCompleted)
2289 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2292 long t2 = DateTime.Now.Ticks;
2293 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2294 if (timeout.Ticks <= 0)
2297 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2300 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2302 for (i = 0; i < asyncResults.Count; i++) {
2303 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2306 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2307 if (!allSignalled) {
2308 for (i = 0; i < asyncResults.Count; i++) {
2309 if (!asyncResults [i].IsCompleted) {
2310 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2316 DateTime endWait = DateTime.Now;
2317 TimeSpan elapsed = endWait - startExecution;
2318 if (elapsed <= AsyncTimeout)
2319 AsyncTimeout -= elapsed;
2321 AsyncTimeout = TimeSpan.FromTicks(0);
2324 if (serialTasks != null) {
2325 List<PageAsyncTask> localSerialTasks = serialTasks;
2326 serialTasks = null; // Shouldn't execute tasks twice
2327 foreach (PageAsyncTask serialTask in localSerialTasks) {
2328 DateTime startExecution = DateTime.Now;
2330 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2331 if (result.CompletedSynchronously)
2332 serialTask.EndHandler (result);
2334 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2335 if (!done && !result.IsCompleted) {
2336 serialTask.TimeoutHandler (result);
2339 DateTime endWait = DateTime.Now;
2340 TimeSpan elapsed = endWait - startExecution;
2341 if (elapsed <= AsyncTimeout)
2342 AsyncTimeout -= elapsed;
2344 AsyncTimeout = TimeSpan.FromTicks (0);
2347 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2350 void EndAsyncTaskCallback (IAsyncResult result)
2352 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2353 task.EndHandler (result);
2356 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2358 Type htmlTextWriterType = typeof (HtmlTextWriter);
2360 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2361 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2364 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2365 if (constructor == null) {
2366 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2369 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2373 [DefaultValue ("0")]
2374 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2375 [EditorBrowsable (EditorBrowsableState.Never)]
2376 public ViewStateEncryptionMode ViewStateEncryptionMode {
2377 get { return viewStateEncryptionMode; }
2378 set { viewStateEncryptionMode = value; }
2381 public void RegisterRequiresViewStateEncryption ()
2383 controlRegisteredForViewStateEncryption = true;
2386 internal bool NeedViewStateEncryption {
2388 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2389 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2390 controlRegisteredForViewStateEncryption));
2395 void ApplyMasterPage ()
2397 if (masterPageFile != null && masterPageFile.Length > 0) {
2398 MasterPage master = Master;
2400 if (master != null) {
2401 var appliedMasterPageFiles = new Dictionary <string, bool> (StringComparer.Ordinal);
2402 MasterPage.ApplyMasterPageRecursive (Request.CurrentExecutionFilePath, HostingEnvironment.VirtualPathProvider, master, appliedMasterPageFiles);
2405 Controls.Add (master);
2410 [DefaultValueAttribute ("")]
2411 public virtual string MasterPageFile {
2412 get { return masterPageFile; }
2414 masterPageFile = value;
2419 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2420 [BrowsableAttribute (false)]
2421 public MasterPage Master {
2423 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2426 if (masterPage == null)
2427 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2433 public void SetFocus (string clientID)
2435 if (String.IsNullOrEmpty (clientID))
2436 throw new ArgumentNullException ("control");
2439 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2442 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2444 _focusedControlID = clientID;
2447 public void SetFocus (Control control)
2449 if (control == null)
2450 throw new ArgumentNullException ("control");
2452 SetFocus (control.ClientID);
2455 [EditorBrowsable (EditorBrowsableState.Advanced)]
2456 public void RegisterRequiresControlState (Control control)
2458 if (control == null)
2459 throw new ArgumentNullException ("control");
2461 if (RequiresControlState (control))
2464 if (requireStateControls == null)
2465 requireStateControls = new List <Control> ();
2466 requireStateControls.Add (control);
2467 int n = requireStateControls.Count - 1;
2469 if (_savedControlState == null || n >= _savedControlState.Length)
2472 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2473 if (parent.IsChildControlStateCleared)
2476 object state = _savedControlState [n];
2478 control.LoadControlState (state);
2481 public bool RequiresControlState (Control control)
2483 if (requireStateControls == null)
2485 return requireStateControls.Contains (control);
2488 [EditorBrowsable (EditorBrowsableState.Advanced)]
2489 public void UnregisterRequiresControlState (Control control)
2491 if (requireStateControls != null)
2492 requireStateControls.Remove (control);
2495 public ValidatorCollection GetValidators (string validationGroup)
2497 if (validationGroup == String.Empty)
2498 validationGroup = null;
2500 ValidatorCollection col = new ValidatorCollection ();
2501 if (_validators == null)
2504 foreach (IValidator v in _validators)
2505 if (BelongsToGroup(v, validationGroup))
2511 bool BelongsToGroup(IValidator v, string validationGroup)
2513 BaseValidator validator = v as BaseValidator;
2514 if (validationGroup == null)
2515 return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
2517 return validator != null && validator.ValidationGroup == validationGroup;
2520 public virtual void Validate (string validationGroup)
2522 is_validated = true;
2523 ValidateCollection (GetValidators (validationGroup));
2526 object SavePageControlState ()
2528 int count = requireStateControls == null ? 0 : requireStateControls.Count;
2533 object[] controlStates = new object [count];
2534 object[] adapterState = new object [count];
2536 ControlAdapter adapter;
2537 bool allNull = true;
2538 TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
2540 for (int n = 0; n < count; n++) {
2541 control = requireStateControls [n];
2542 state = controlStates [n] = control.SaveControlState ();
2547 trace.SaveControlState (control, state);
2549 adapter = control.Adapter;
2550 if (adapter != null) {
2551 adapterState [n] = adapter.SaveAdapterControlState ();
2552 if (adapterState [n] != null) allNull = false;
2559 return new Pair (controlStates, adapterState);
2562 void LoadPageControlState (object data)
2564 _savedControlState = null;
2565 if (data == null) return;
2566 Pair statePair = (Pair)data;
2567 _savedControlState = (object[]) statePair.First;
2568 object[] adapterState = (object[]) statePair.Second;
2570 if (requireStateControls == null) return;
2572 int min = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2573 for (int n=0; n < min; n++) {
2574 Control ctl = (Control) requireStateControls [n];
2575 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2576 if (ctl.Adapter != null)
2577 ctl.Adapter.LoadAdapterControlState (adapterState != null ? adapterState [n] : null);
2581 void LoadPreviousPageReference ()
2583 if (_requestValueCollection != null) {
2584 string prevPage = _requestValueCollection [PreviousPageID];
2585 if (prevPage != null) {
2587 if (getFacesContext () != null) {
2588 IHttpHandler handler = Context.ApplicationInstance.GetHandler (Context, prevPage);
2589 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2590 if (_context.Items.Contains (CrossPagePostBack)) {
2591 previousPage = (Page) _context.Items [CrossPagePostBack];
2592 _context.Items.Remove (CrossPagePostBack);
2597 IHttpHandler handler;
2598 handler = BuildManager.CreateInstanceFromVirtualPath (prevPage, typeof (IHttpHandler)) as IHttpHandler;
2599 previousPage = (Page) handler;
2600 previousPage.isCrossPagePostBack = true;
2601 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2607 Hashtable contentTemplates;
2608 [EditorBrowsable (EditorBrowsableState.Never)]
2609 protected internal void AddContentTemplate (string templateName, ITemplate template)
2611 if (contentTemplates == null)
2612 contentTemplates = new Hashtable ();
2613 contentTemplates [templateName] = template;
2616 PageTheme _pageTheme;
2617 internal PageTheme PageTheme {
2618 get { return _pageTheme; }
2621 PageTheme _styleSheetPageTheme;
2622 internal PageTheme StyleSheetPageTheme {
2623 get { return _styleSheetPageTheme; }
2628 internal void PushDataItemContext (object o) {
2629 if (dataItemCtx == null)
2630 dataItemCtx = new Stack ();
2632 dataItemCtx.Push (o);
2635 internal void PopDataItemContext () {
2636 if (dataItemCtx == null)
2637 throw new InvalidOperationException ();
2642 public object GetDataItem() {
2643 if (dataItemCtx == null || dataItemCtx.Count == 0)
2644 throw new InvalidOperationException ("No data item");
2646 return dataItemCtx.Peek ();
2649 void AddStyleSheets (PageTheme theme, ref List <string> links)
2654 string[] tmpThemes = theme != null ? theme.GetStyleSheets () : null;
2655 if (tmpThemes == null || tmpThemes.Length == 0)
2659 links = new List <string> ();
2661 links.AddRange (tmpThemes);
2664 protected internal override void OnInit (EventArgs e)
2668 List <string> themes = null;
2669 AddStyleSheets (StyleSheetPageTheme, ref themes);
2670 AddStyleSheets (PageTheme, ref themes);
2675 HtmlHead header = Header;
2676 if (themes != null && header == null)
2677 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2679 ControlCollection headerControls = header.Controls;
2681 for (int i = themes.Count - 1; i >= 0; i--) {
2683 HtmlLink hl = new HtmlLink ();
2685 hl.Attributes["type"] = "text/css";
2686 hl.Attributes["rel"] = "stylesheet";
2687 headerControls.AddAt (0, hl);
2691 [MonoDocumentationNote ("Not implemented. Only used by .net aspx parser")]
2692 [EditorBrowsable (EditorBrowsableState.Never)]
2693 protected object GetWrappedFileDependencies (string [] list)
2698 [MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
2699 protected virtual void InitializeCulture ()
2703 [MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
2704 [EditorBrowsable (EditorBrowsableState.Never)]
2705 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)