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.SessionState;
51 using System.Web.Util;
52 using System.Web.UI.Adapters;
53 using System.Web.UI.HtmlControls;
54 using System.Web.UI.WebControls;
55 using System.Reflection;
57 using System.Web.Routing;
60 namespace System.Web.UI
63 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
64 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
65 [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
67 [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
68 [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")]
69 public partial class Page : TemplateControl, IHttpHandler
71 // static string machineKeyConfigPath = "system.web/machineKey";
72 bool _eventValidation = true;
73 object [] _savedControlState;
74 bool _doLoadPreviousPage;
75 string _focusedControlID;
76 bool _hasEnabledControlArray;
81 bool _smartNavigation;
83 ValidatorCollection _validators;
85 string _savedViewState;
86 List <string> _requiresPostBack;
87 List <string> _requiresPostBackCopy;
88 List <IPostBackDataHandler> requiresPostDataChanged;
89 IPostBackEventHandler requiresRaiseEvent;
90 IPostBackEventHandler formPostedRequiresRaiseEvent;
91 NameValueCollection secondPostData;
92 bool requiresPostBackScript;
93 bool postBackScriptRendered;
94 bool requiresFormScriptDeclaration;
95 bool formScriptDeclarationRendered;
97 string viewStateUserKey;
98 NameValueCollection _requestValueCollection;
100 ClientScriptManager scriptManager;
101 bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
102 PageStatePersister page_state_persister;
103 CultureInfo _appCulture;
104 CultureInfo _appUICulture;
106 // The initial context
107 HttpContext _context;
109 // cached from the initial context
110 HttpApplicationState _application;
111 HttpResponse _response;
112 HttpRequest _request;
115 HttpSessionState _session;
117 [EditorBrowsable (EditorBrowsableState.Never)]
118 public const string postEventArgumentID = "__EVENTARGUMENT";
120 [EditorBrowsable (EditorBrowsableState.Never)]
121 public const string postEventSourceID = "__EVENTTARGET";
123 const string ScrollPositionXID = "__SCROLLPOSITIONX";
124 const string ScrollPositionYID = "__SCROLLPOSITIONY";
125 const string EnabledControlArrayID = "__enabledControlArray";
126 internal const string LastFocusID = "__LASTFOCUS";
127 internal const string CallbackArgumentID = "__CALLBACKPARAM";
128 internal const string CallbackSourceID = "__CALLBACKID";
129 internal const string PreviousPageID = "__PREVIOUSPAGE";
131 int maxPageStateFieldLength = -1;
132 string uniqueFilePathSuffix;
135 MasterPage masterPage;
136 string masterPageFile;
139 bool isCrossPagePostBack;
142 List <Control> requireStateControls;
147 string _styleSheetTheme;
149 string _metaDescription;
150 string _metaKeywords;
151 Control _autoPostBackControl;
153 bool frameworkInitialized;
157 bool _maintainScrollPositionOnPostBack;
159 bool asyncMode = false;
160 TimeSpan asyncTimeout;
161 const double DefaultAsyncTimeout = 45.0;
162 List<PageAsyncTask> parallelTasks;
163 List<PageAsyncTask> serialTasks;
165 ViewStateEncryptionMode viewStateEncryptionMode;
166 bool controlRegisteredForViewStateEncryption = false;
171 scriptManager = new ClientScriptManager (this);
174 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
176 asyncTimeout = ps.AsyncTimeout;
177 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
178 _viewState = ps.EnableViewState;
179 _viewStateMac = ps.EnableViewStateMac;
181 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
182 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
186 this.ViewStateMode = ViewStateMode.Enabled;
194 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
196 public HttpApplicationState Application {
197 get { return _application; }
200 [EditorBrowsable (EditorBrowsableState.Never)]
201 protected bool AspCompatMode {
202 get { return false; }
208 [EditorBrowsable (EditorBrowsableState.Never)]
209 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
210 [BrowsableAttribute (false)]
212 get { return Response.BufferOutput; }
213 set { Response.BufferOutput = value; }
216 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
221 throw new HttpException ("Cache is not available.");
226 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
227 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
228 [Browsable (false), DefaultValue ("")]
229 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
230 public string ClientTarget {
231 get { return (clientTarget == null) ? String.Empty : clientTarget; }
233 clientTarget = value;
234 if (value == String.Empty)
239 [EditorBrowsable (EditorBrowsableState.Never)]
240 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
241 [BrowsableAttribute (false)]
242 public int CodePage {
243 get { return Response.ContentEncoding.CodePage; }
244 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
247 [EditorBrowsable (EditorBrowsableState.Never)]
248 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
249 [BrowsableAttribute (false)]
250 public string ContentType {
251 get { return Response.ContentType; }
252 set { Response.ContentType = value; }
255 protected internal override HttpContext Context {
257 if (_context == null)
258 return HttpContext.Current;
264 [EditorBrowsable (EditorBrowsableState.Advanced)]
265 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
266 [BrowsableAttribute (false)]
267 public string Culture {
268 get { return Thread.CurrentThread.CurrentCulture.Name; }
269 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
272 [EditorBrowsable (EditorBrowsableState.Never)]
274 [DefaultValue ("true")]
275 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
276 public virtual bool EnableEventValidation {
277 get { return _eventValidation; }
280 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
281 _eventValidation = value;
286 public override bool EnableViewState {
287 get { return _viewState; }
288 set { _viewState = value; }
291 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
292 [BrowsableAttribute (false)]
293 [EditorBrowsable (EditorBrowsableState.Never)]
294 public bool EnableViewStateMac {
295 get { return _viewStateMac; }
296 set { _viewStateMac = value; }
299 internal bool EnableViewStateMacInternal {
300 get { return _viewStateMac; }
301 set { _viewStateMac = value; }
304 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
305 [Browsable (false), DefaultValue ("")]
306 [WebSysDescription ("The URL of a page used for error redirection.")]
307 public string ErrorPage {
308 get { return _errorPage; }
310 HttpContext ctx = Context;
314 ctx.ErrorPage = value;
318 [Obsolete ("The recommended alternative is HttpResponse.AddFileDependencies. http://go.microsoft.com/fwlink/?linkid=14202")]
319 [EditorBrowsable (EditorBrowsableState.Never)]
320 protected ArrayList FileDependencies {
322 if (Response != null)
323 Response.AddFileDependencies (value);
328 [EditorBrowsable (EditorBrowsableState.Never)]
329 public override string ID {
330 get { return base.ID; }
331 set { base.ID = value; }
334 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
336 public bool IsPostBack {
337 get { return isPostBack; }
340 public bool IsPostBackEventControlRegistered {
341 get { return requiresRaiseEvent != null; }
344 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
345 public bool IsReusable {
346 get { return false; }
349 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
351 public bool IsValid {
354 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."));
356 foreach (IValidator val in Validators)
364 public IDictionary Items {
367 items = new Hashtable ();
372 [EditorBrowsable (EditorBrowsableState.Never)]
373 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
374 [BrowsableAttribute (false)]
376 get { return Thread.CurrentThread.CurrentCulture.LCID; }
377 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
381 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
382 public bool MaintainScrollPositionOnPostBack {
383 get { return _maintainScrollPositionOnPostBack; }
384 set { _maintainScrollPositionOnPostBack = value; }
387 public PageAdapter PageAdapter {
389 return Adapter as PageAdapter;
393 string _validationStartupScript;
394 string _validationOnSubmitStatement;
395 string _validationInitializeScript;
396 string _webFormScriptReference;
398 internal string WebFormScriptReference {
400 if (_webFormScriptReference == null)
401 _webFormScriptReference = IsMultiForm ? theForm : "window";
402 return _webFormScriptReference;
406 internal string ValidationStartupScript {
408 if (_validationStartupScript == null) {
409 _validationStartupScript =
411 " + WebFormScriptReference + @".Page_ValidationActive = false;
412 " + WebFormScriptReference + @".ValidatorOnLoad();
413 " + WebFormScriptReference + @".ValidatorOnSubmit = function () {
414 if (this.Page_ValidationActive) {
415 return this.ValidatorCommonOnSubmit();
421 return _validationStartupScript;
425 internal string ValidationOnSubmitStatement {
427 if (_validationOnSubmitStatement == null)
428 _validationOnSubmitStatement = "if (!" + WebFormScriptReference + ".ValidatorOnSubmit()) return false;";
429 return _validationOnSubmitStatement;
433 internal string ValidationInitializeScript {
435 if (_validationInitializeScript == null)
436 _validationInitializeScript = "WebFormValidation_Initialize(" + WebFormScriptReference + ");";
437 return _validationInitializeScript;
441 internal IScriptManager ScriptManager {
442 get { return (IScriptManager) Items [typeof (IScriptManager)]; }
445 internal string theForm {
451 internal bool IsMultiForm {
452 get { return false; }
456 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
458 public HttpRequest Request {
460 if (_request == null)
461 throw new HttpException("Request is not available in this context.");
466 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
468 public HttpResponse Response {
470 if (_response == null)
471 throw new HttpException ("Response is not available in this context.");
476 [EditorBrowsable (EditorBrowsableState.Never)]
477 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
478 [BrowsableAttribute (false)]
479 public string ResponseEncoding {
480 get { return Response.ContentEncoding.WebName; }
481 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
484 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
486 public HttpServerUtility Server {
487 get { return Context.Server; }
490 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
492 public virtual HttpSessionState Session {
494 if (_session != null)
498 _session = Context.Session;
500 // ignore, should not throw
503 if (_session == null)
504 throw new HttpException ("Session state can only be used " +
505 "when enableSessionState is set to true, either " +
506 "in a configuration file or in the Page directive.");
513 [Obsolete ("The recommended alternative is Page.SetFocus and Page.MaintainScrollPositionOnPostBack. http://go.microsoft.com/fwlink/?linkid=14202")]
515 public bool SmartNavigation {
516 get { return _smartNavigation; }
517 set { _smartNavigation = value; }
520 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
523 public virtual string StyleSheetTheme {
524 get { return _styleSheetTheme; }
525 set { _styleSheetTheme = value; }
529 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
530 public virtual string Theme {
531 get { return _theme; }
532 set { _theme = value; }
535 void InitializeStyleSheet ()
537 if (_styleSheetTheme == null) {
538 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
540 _styleSheetTheme = ps.StyleSheetTheme;
543 if (_styleSheetTheme != null && _styleSheetTheme != "")
544 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, Context);
546 if (!String.IsNullOrEmpty (_styleSheetTheme)) {
547 string virtualPath = "~/App_Themes/" + _styleSheetTheme;
548 _styleSheetPageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
553 void InitializeTheme ()
555 if (_theme == null) {
556 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
561 if (_theme != null && _theme != "") {
562 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, Context);
563 _pageTheme.SetPage (this);
566 if (!String.IsNullOrEmpty (_theme)) {
567 string virtualPath = "~/App_Themes/" + _theme;
568 _pageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
569 if (_pageTheme != null)
570 _pageTheme.SetPage (this);
575 public Control AutoPostBackControl {
576 get { return _autoPostBackControl; }
577 set { _autoPostBackControl = value; }
580 [BrowsableAttribute(false)]
581 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
582 public RouteData RouteData {
584 if (_request == null)
587 RequestContext reqctx = _request.RequestContext;
591 return reqctx.RouteData;
596 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
598 public string MetaDescription {
600 if (_metaDescription == null) {
601 if (htmlHeader == null) {
602 if (frameworkInitialized)
603 throw new InvalidOperationException ("A server-side head element is required to set this property.");
606 return htmlHeader.Description;
609 return _metaDescription;
613 if (htmlHeader == null) {
614 if (frameworkInitialized)
615 throw new InvalidOperationException ("A server-side head element is required to set this property.");
616 _metaDescription = value;
618 htmlHeader.Description = value;
623 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
625 public string MetaKeywords {
627 if (_metaKeywords == null) {
628 if (htmlHeader == null) {
629 if (frameworkInitialized)
630 throw new InvalidOperationException ("A server-side head element is required to set this property.");
633 return htmlHeader.Keywords;
636 return _metaDescription;
640 if (htmlHeader == null) {
641 if (frameworkInitialized)
642 throw new InvalidOperationException ("A server-side head element is required to set this property.");
643 _metaKeywords = value;
645 htmlHeader.Keywords = value;
651 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
652 public string Title {
654 if (_title == null) {
655 if (htmlHeader != null && htmlHeader.Title != null)
656 return htmlHeader.Title;
663 if (htmlHeader != null)
664 htmlHeader.Title = value;
670 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
672 public TraceContext Trace {
673 get { return Context.Trace; }
676 [EditorBrowsable (EditorBrowsableState.Never)]
677 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
678 [BrowsableAttribute (false)]
679 public bool TraceEnabled {
680 get { return Trace.IsEnabled; }
681 set { Trace.IsEnabled = value; }
684 [EditorBrowsable (EditorBrowsableState.Never)]
685 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
686 [BrowsableAttribute (false)]
687 public TraceMode TraceModeValue {
688 get { return Trace.TraceMode; }
689 set { Trace.TraceMode = value; }
692 [EditorBrowsable (EditorBrowsableState.Never)]
693 protected int TransactionMode {
694 get { return _transactionMode; }
695 set { _transactionMode = value; }
698 [EditorBrowsable (EditorBrowsableState.Advanced)]
699 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
700 [BrowsableAttribute (false)]
701 public string UICulture {
702 get { return Thread.CurrentThread.CurrentUICulture.Name; }
703 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
706 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
708 public IPrincipal User {
709 get { return Context.User; }
712 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
714 public ValidatorCollection Validators {
716 if (_validators == null)
717 _validators = new ValidatorCollection ();
722 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
724 public string ViewStateUserKey {
725 get { return viewStateUserKey; }
726 set { viewStateUserKey = value; }
730 public override bool Visible {
731 get { return base.Visible; }
732 set { base.Visible = value; }
739 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
743 CultureInfo ret = null;
744 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
746 if (!Context.IsServletRequest)
749 string[] languages = Request.UserLanguages;
751 if (languages != null && languages.Length > 0)
752 ret = CultureInfo.CreateSpecificCulture (languages[0]);
759 ret = CultureInfo.CreateSpecificCulture (culture);
764 [EditorBrowsable (EditorBrowsableState.Never)]
765 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
769 throw new NotImplementedException ();
772 [EditorBrowsable (EditorBrowsableState.Never)]
773 [MonoNotSupported ("Mono does not support classic ASP compatibility mode.")]
774 protected void AspCompatEndProcessRequest (IAsyncResult result)
776 throw new NotImplementedException ();
779 [EditorBrowsable (EditorBrowsableState.Advanced)]
780 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
782 if (Request.BrowserMightHaveSpecialWriter)
783 return Request.Browser.CreateHtmlTextWriter(tw);
785 return new HtmlTextWriter (tw);
788 [EditorBrowsable (EditorBrowsableState.Never)]
789 public void DesignerInitialize ()
791 InitRecursive (null);
794 [EditorBrowsable (EditorBrowsableState.Advanced)]
795 protected internal virtual NameValueCollection DeterminePostBackMode ()
797 // if request was transfered from other page such Transfer
798 if (_context.IsProcessingInclude)
801 HttpRequest req = Request;
805 NameValueCollection coll = null;
806 if (0 == String.Compare (Request.HttpMethod, "POST", true, Helpers.InvariantCulture)
808 || !_context.IsServletRequest
813 string query = Request.QueryStringRaw;
814 if (query == null || query.Length == 0)
817 coll = req.QueryString;
820 WebROCollection c = (WebROCollection) coll;
821 allow_load = !c.GotID;
823 c.ID = GetTypeHashCode ();
825 allow_load = (c.ID == GetTypeHashCode ());
827 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
830 if (getFacesContext () != null && _context.Handler != _context.CurrentHandler) {
831 // check if it is PreviousPage
832 string prevViewId = coll [PreviousPageID];
833 if (!String.IsNullOrEmpty (prevViewId)) {
834 string appPath = VirtualPathUtility.RemoveTrailingSlash (Request.ApplicationPath);
835 prevViewId = prevViewId.Substring (appPath.Length);
836 isCrossPagePostBack = String.Compare (prevViewId, getFacesContext ().getExternalContext ().getRequestPathInfo (), StringComparison.OrdinalIgnoreCase) == 0;
843 public override Control FindControl (string id) {
847 return base.FindControl (id);
850 Control FindControl (string id, bool decode) {
853 id = DecodeNamespace (id);
855 return FindControl (id);
858 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
859 [EditorBrowsable (EditorBrowsableState.Advanced)]
860 public string GetPostBackClientEvent (Control control, string argument)
862 return scriptManager.GetPostBackEventReference (control, argument);
865 [Obsolete ("The recommended alternative is ClientScript.GetPostBackClientHyperlink. http://go.microsoft.com/fwlink/?linkid=14202")]
866 [EditorBrowsable (EditorBrowsableState.Advanced)]
867 public string GetPostBackClientHyperlink (Control control, string argument)
869 return scriptManager.GetPostBackClientHyperlink (control, argument);
872 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
873 [EditorBrowsable (EditorBrowsableState.Advanced)]
874 public string GetPostBackEventReference (Control control)
876 return scriptManager.GetPostBackEventReference (control, String.Empty);
879 [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
880 [EditorBrowsable (EditorBrowsableState.Advanced)]
881 public string GetPostBackEventReference (Control control, string argument)
883 return scriptManager.GetPostBackEventReference (control, argument);
886 internal void RequiresFormScriptDeclaration ()
888 requiresFormScriptDeclaration = true;
891 internal void RequiresPostBackScript ()
893 if (requiresPostBackScript)
895 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
896 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
897 requiresPostBackScript = true;
898 RequiresFormScriptDeclaration ();
901 [EditorBrowsable (EditorBrowsableState.Never)]
902 public virtual int GetTypeHashCode ()
907 [MonoTODO ("The following properties of OutputCacheParameters are silently ignored: CacheProfile, SqlDependency")]
908 [EditorBrowsable (EditorBrowsableState.Never)]
909 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
911 if (cacheSettings.Enabled) {
912 InitOutputCache(cacheSettings.Duration,
913 cacheSettings.VaryByContentEncoding,
914 cacheSettings.VaryByHeader,
915 cacheSettings.VaryByCustom,
916 cacheSettings.Location,
917 cacheSettings.VaryByParam);
919 HttpResponse response = Response;
920 HttpCachePolicy cache = response != null ? response.Cache : null;
921 if (cache != null && cacheSettings.NoStore)
926 [MonoTODO ("varyByContentEncoding is not currently used")]
927 [EditorBrowsable (EditorBrowsableState.Never)]
928 protected virtual void InitOutputCache(int duration,
929 string varyByContentEncoding,
932 OutputCacheLocation location,
935 HttpResponse response = Response;
936 HttpCachePolicy cache = response.Cache;
937 bool set_vary = false;
938 HttpContext ctx = Context;
939 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
942 case OutputCacheLocation.Any:
943 cache.SetCacheability (HttpCacheability.Public);
944 cache.SetMaxAge (new TimeSpan (0, 0, duration));
945 cache.SetLastModified (timestamp);
948 case OutputCacheLocation.Client:
949 cache.SetCacheability (HttpCacheability.Private);
950 cache.SetMaxAge (new TimeSpan (0, 0, duration));
951 cache.SetLastModified (timestamp);
953 case OutputCacheLocation.Downstream:
954 cache.SetCacheability (HttpCacheability.Public);
955 cache.SetMaxAge (new TimeSpan (0, 0, duration));
956 cache.SetLastModified (timestamp);
958 case OutputCacheLocation.Server:
959 cache.SetCacheability (HttpCacheability.Server);
962 case OutputCacheLocation.None:
967 if (varyByCustom != null)
968 cache.SetVaryByCustom (varyByCustom);
970 if (varyByParam != null && varyByParam.Length > 0) {
971 string[] prms = varyByParam.Split (';');
972 foreach (string p in prms)
973 cache.VaryByParams [p.Trim ()] = true;
974 cache.VaryByParams.IgnoreParams = false;
976 cache.VaryByParams.IgnoreParams = true;
979 if (varyByHeader != null && varyByHeader.Length > 0) {
980 string[] hdrs = varyByHeader.Split (';');
981 foreach (string h in hdrs)
982 cache.VaryByHeaders [h.Trim ()] = true;
985 if (PageAdapter != null) {
986 if (PageAdapter.CacheVaryByParams != null) {
987 foreach (string p in PageAdapter.CacheVaryByParams)
988 cache.VaryByParams [p] = true;
990 if (PageAdapter.CacheVaryByHeaders != null) {
991 foreach (string h in PageAdapter.CacheVaryByHeaders)
992 cache.VaryByHeaders [h] = true;
997 response.IsCached = true;
998 cache.Duration = duration;
999 cache.SetExpires (timestamp.AddSeconds (duration));
1003 [EditorBrowsable (EditorBrowsableState.Never)]
1004 protected virtual void InitOutputCache (int duration,
1005 string varyByHeader,
1006 string varyByCustom,
1007 OutputCacheLocation location,
1010 InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
1013 [Obsolete ("The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
1014 public bool IsClientScriptBlockRegistered (string key)
1016 return scriptManager.IsClientScriptBlockRegistered (key);
1019 [Obsolete ("The recommended alternative is ClientScript.IsStartupScriptRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
1020 public bool IsStartupScriptRegistered (string key)
1022 return scriptManager.IsStartupScriptRegistered (key);
1025 public string MapPath (string virtualPath)
1027 return Request.MapPath (virtualPath);
1030 protected internal override void Render (HtmlTextWriter writer)
1032 if (MaintainScrollPositionOnPostBack) {
1033 ClientScript.RegisterWebFormClientScript ();
1035 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
1036 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
1038 StringBuilder script = new StringBuilder ();
1039 script.AppendLine ("<script type=\"text/javascript\">");
1040 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
1041 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
1042 script.AppendLine (theForm + ".submit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionSubmit(); }");
1043 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
1044 script.AppendLine (theForm + ".onsubmit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionOnSubmit(); }");
1046 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
1047 script.AppendLine ("window.onload = function () { " + WebFormScriptReference + ".WebForm_RestoreScrollPosition (); };");
1049 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
1050 script.AppendLine ("</script>");
1052 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1055 if (bool.Parse (WebConfigurationManager.AppSettings [RenderBodyContentOnlyKey] ?? "false")) {
1056 for (Control c = this.Form; c != null; c = c.Parent) {
1057 HtmlGenericControl ch = (c as HtmlGenericControl);
1058 if (ch != null && ch.TagName == "body") {
1059 ch.RenderChildren (writer);
1065 base.Render (writer);
1068 void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1070 writer.WriteLine ();
1071 ClientScriptManager.WriteBeginScriptBlock (writer);
1072 RenderClientScriptFormDeclaration (writer, formUniqueID);
1073 writer.WriteLine (WebFormScriptReference + "._form = " + theForm + ";");
1074 writer.WriteLine (WebFormScriptReference + ".__doPostBack = function (eventTarget, eventArgument) {");
1075 writer.WriteLine ("\tif(" + theForm + ".onsubmit && " + theForm + ".onsubmit() == false) return;");
1076 writer.WriteLine ("\t" + theForm + "." + postEventSourceID + ".value = eventTarget;");
1077 writer.WriteLine ("\t" + theForm + "." + postEventArgumentID + ".value = eventArgument;");
1078 writer.WriteLine ("\t" + theForm + ".submit();");
1079 writer.WriteLine ("}");
1080 ClientScriptManager.WriteEndScriptBlock (writer);
1083 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1085 if (formScriptDeclarationRendered)
1088 if (PageAdapter != null) {
1089 writer.WriteLine ("\tvar {0} = {1};\n", theForm, PageAdapter.GetPostBackFormReference(formUniqueID));
1091 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1092 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1095 // TODO implement callback on portlet
1096 string serverUrl = Request.RawUrl;
1097 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1098 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1099 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1101 formScriptDeclarationRendered = true;
1104 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1107 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1109 renderingForm = true;
1110 writer.WriteLine ();
1112 if (requiresFormScriptDeclaration || (scriptManager != null && scriptManager.ScriptsPresent) || PageAdapter != null) {
1113 ClientScriptManager.WriteBeginScriptBlock (writer);
1114 RenderClientScriptFormDeclaration (writer, formUniqueID);
1115 ClientScriptManager.WriteEndScriptBlock (writer);
1118 if (handleViewState)
1120 if (getFacesContext () != null) {
1121 javax.faces.application.ViewHandler viewHandler = getFacesContext ().getApplication ().getViewHandler ();
1122 javax.faces.context.ResponseWriter oldFacesWriter = SetupResponseWriter (writer);
1124 viewHandler.writeState (getFacesContext ());
1127 getFacesContext ().setResponseWriter (oldFacesWriter);
1131 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1133 scriptManager.WriteHiddenFields (writer);
1134 if (requiresPostBackScript) {
1135 RenderPostBackScript (writer, formUniqueID);
1136 postBackScriptRendered = true;
1139 scriptManager.WriteWebFormClientScript (writer);
1140 scriptManager.WriteClientScriptBlocks (writer);
1143 internal IStateFormatter GetFormatter ()
1145 return new ObjectStateFormatter (this);
1148 internal string GetSavedViewState ()
1150 return _savedViewState;
1153 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1155 scriptManager.SaveEventValidationState ();
1156 scriptManager.WriteExpandoAttributes (writer);
1157 scriptManager.WriteHiddenFields (writer);
1158 if (!postBackScriptRendered && requiresPostBackScript)
1159 RenderPostBackScript (writer, formUniqueID);
1160 scriptManager.WriteWebFormClientScript (writer);
1161 scriptManager.WriteArrayDeclares (writer);
1162 scriptManager.WriteStartupScriptBlocks (writer);
1163 renderingForm = false;
1164 postBackScriptRendered = false;
1167 void ProcessPostData (NameValueCollection data, bool second)
1169 NameValueCollection requestValues = _requestValueCollection == null ? new NameValueCollection () : _requestValueCollection;
1171 if (data != null && data.Count > 0) {
1172 var used = new Dictionary <string, string> (StringComparer.Ordinal);
1173 foreach (string id in data.AllKeys) {
1174 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID || id == ClientScriptManager.EventStateFieldName)
1177 if (used.ContainsKey (id))
1182 Control ctrl = FindControl (id, true);
1184 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1185 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1189 formPostedRequiresRaiseEvent = pbeh;
1193 if (pbdh.LoadPostData (id, requestValues) == true) {
1194 if (requiresPostDataChanged == null)
1195 requiresPostDataChanged = new List <IPostBackDataHandler> ();
1196 requiresPostDataChanged.Add (pbdh);
1199 if (_requiresPostBackCopy != null)
1200 _requiresPostBackCopy.Remove (id);
1202 } else if (!second) {
1203 if (secondPostData == null)
1204 secondPostData = new NameValueCollection ();
1205 secondPostData.Add (id, data [id]);
1210 List <string> list1 = null;
1211 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1212 string [] handlers = (string []) _requiresPostBackCopy.ToArray ();
1213 foreach (string id in handlers) {
1214 IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
1216 _requiresPostBackCopy.Remove (id);
1217 if (pbdh.LoadPostData (id, requestValues)) {
1218 if (requiresPostDataChanged == null)
1219 requiresPostDataChanged = new List <IPostBackDataHandler> ();
1221 requiresPostDataChanged.Add (pbdh);
1223 } else if (!second) {
1225 list1 = new List <string> ();
1230 _requiresPostBackCopy = second ? null : list1;
1232 secondPostData = null;
1235 [EditorBrowsable (EditorBrowsableState.Never)]
1236 public virtual void ProcessRequest (HttpContext context)
1238 SetContext (context);
1240 bool wasException = false;
1241 IHttpHandler jsfHandler = getFacesContext () != null ? EnterThread () : null;
1244 if (clientTarget != null)
1245 Request.ClientTarget = clientTarget;
1247 WireupAutomaticEvents ();
1248 //-- Control execution lifecycle in the docs
1250 // Save culture information because it can be modified in FrameworkInitialize()
1251 _appCulture = Thread.CurrentThread.CurrentCulture;
1252 _appUICulture = Thread.CurrentThread.CurrentUICulture;
1253 FrameworkInitialize ();
1255 frameworkInitialized = true;
1257 context.ErrorPage = _errorPage;
1260 InternalProcessRequest ();
1262 } catch (Exception ex) {
1263 wasException = true;
1264 HandleException (ex);
1266 } catch (ThreadAbortException taex) {
1267 if (FlagEnd.Value == taex.ExceptionState)
1268 Thread.ResetAbort ();
1271 } catch (Exception e) {
1272 ProcessException (e);
1276 if (getFacesContext () != null)
1277 ExitThread (jsfHandler);
1278 else if (!wasException)
1284 void ProcessException (Exception e) {
1285 // We want to remove that error, as we're rethrowing to stop
1286 // further processing.
1287 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1288 _context.AddError (e); // OnError might access LastError
1289 OnError (EventArgs.Empty);
1290 if (_context.HasError (e)) {
1291 _context.ClearError (e);
1293 vmw.common.TypeUtils.Throw (e);
1295 throw new HttpUnhandledException (null, e);
1300 void ProcessUnload () {
1303 UnloadRecursive (true);
1306 if (getFacesContext () != null) {
1307 if(IsCrossPagePostBack)
1308 _context.Items [CrossPagePostBack] = this;
1311 if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
1312 Thread.CurrentThread.CurrentCulture = _appCulture;
1314 if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
1315 Thread.CurrentThread.CurrentUICulture = _appUICulture;
1318 _appUICulture = null;
1321 delegate void ProcessRequestDelegate (HttpContext context);
1323 sealed class DummyAsyncResult : IAsyncResult
1325 readonly object state;
1326 readonly WaitHandle asyncWaitHandle;
1327 readonly bool completedSynchronously;
1328 readonly bool isCompleted;
1330 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1332 this.isCompleted = isCompleted;
1333 this.completedSynchronously = completedSynchronously;
1336 asyncWaitHandle = new ManualResetEvent (true);
1339 asyncWaitHandle = new ManualResetEvent (false);
1343 #region IAsyncResult Members
1345 public object AsyncState {
1346 get { return state; }
1349 public WaitHandle AsyncWaitHandle {
1350 get { return asyncWaitHandle; }
1353 public bool CompletedSynchronously {
1354 get { return completedSynchronously; }
1357 public bool IsCompleted {
1358 get { return isCompleted; }
1364 [EditorBrowsable (EditorBrowsableState.Never)]
1365 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1367 ProcessRequest (context);
1368 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1370 if (callback != null) {
1371 callback (asyncResult);
1377 [EditorBrowsable (EditorBrowsableState.Never)]
1378 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1382 void InternalProcessRequest ()
1384 if (PageAdapter != null)
1385 _requestValueCollection = PageAdapter.DeterminePostBackMode();
1387 _requestValueCollection = this.DeterminePostBackMode();
1389 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1390 if (_requestValueCollection != null) {
1391 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1392 _doLoadPreviousPage = true;
1394 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1395 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1396 //isPostBack = !isCallback;
1400 string lastFocus = _requestValueCollection [LastFocusID];
1401 if (!String.IsNullOrEmpty (lastFocus))
1402 _focusedControlID = UniqueID2ClientID (lastFocus);
1405 if (!isCrossPagePostBack) {
1406 if (_context.PreviousHandler is Page)
1407 previousPage = (Page) _context.PreviousHandler;
1410 Trace.Write ("aspx.page", "Begin PreInit");
1411 OnPreInit (EventArgs.Empty);
1412 Trace.Write ("aspx.page", "End PreInit");
1416 Trace.Write ("aspx.page", "Begin Init");
1417 InitRecursive (null);
1418 Trace.Write ("aspx.page", "End Init");
1420 Trace.Write ("aspx.page", "Begin InitComplete");
1421 OnInitComplete (EventArgs.Empty);
1422 Trace.Write ("aspx.page", "End InitComplete");
1424 renderingForm = false;
1427 if (getFacesContext () != null)
1428 if (IsPostBack || IsCallback)
1432 RestorePageState ();
1434 ProcessRaiseEvents ();
1435 if (ProcessLoadComplete ())
1438 if (getFacesContext () != null) {
1439 getFacesContext ().renderResponse ();
1446 void RestorePageState ()
1448 if (IsPostBack || IsCallback) {
1449 if (_requestValueCollection != null)
1450 scriptManager.RestoreEventValidationState (
1451 _requestValueCollection [ClientScriptManager.EventStateFieldName]);
1452 Trace.Write ("aspx.page", "Begin LoadViewState");
1453 LoadPageViewState ();
1454 Trace.Write ("aspx.page", "End LoadViewState");
1458 void ProcessPostData ()
1460 if (IsPostBack || IsCallback) {
1461 Trace.Write ("aspx.page", "Begin ProcessPostData");
1462 ProcessPostData (_requestValueCollection, false);
1463 Trace.Write ("aspx.page", "End ProcessPostData");
1467 if (IsPostBack || IsCallback) {
1468 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1469 ProcessPostData (secondPostData, true);
1470 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1476 Trace.Write ("aspx.page", "Begin PreLoad");
1477 OnPreLoad (EventArgs.Empty);
1478 Trace.Write ("aspx.page", "End PreLoad");
1480 Trace.Write ("aspx.page", "Begin Load");
1482 Trace.Write ("aspx.page", "End Load");
1485 void ProcessRaiseEvents ()
1487 if (IsPostBack || IsCallback) {
1488 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1489 RaiseChangedEvents ();
1490 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1491 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1492 RaisePostBackEvents ();
1493 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1497 bool ProcessLoadComplete ()
1499 Trace.Write ("aspx.page", "Begin LoadComplete");
1500 OnLoadComplete (EventArgs.Empty);
1501 Trace.Write ("aspx.page", "End LoadComplete");
1503 if (IsCrossPagePostBack)
1508 if (getFacesContext () != null) {
1509 _callbackTarget = GetCallbackTarget ();
1510 ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError);
1514 string result = ProcessCallbackData ();
1515 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1516 callbackOutput.Write (result);
1517 callbackOutput.Flush ();
1521 Trace.Write ("aspx.page", "Begin PreRender");
1522 PreRenderRecursiveInternal ();
1523 Trace.Write ("aspx.page", "End PreRender");
1525 ExecuteRegisteredAsyncTasks ();
1527 Trace.Write ("aspx.page", "Begin PreRenderComplete");
1528 OnPreRenderComplete (EventArgs.Empty);
1529 Trace.Write ("aspx.page", "End PreRenderComplete");
1531 Trace.Write ("aspx.page", "Begin SaveViewState");
1532 SavePageViewState ();
1533 Trace.Write ("aspx.page", "End SaveViewState");
1535 Trace.Write ("aspx.page", "Begin SaveStateComplete");
1536 OnSaveStateComplete (EventArgs.Empty);
1537 Trace.Write ("aspx.page", "End SaveStateComplete");
1541 internal void RenderPage ()
1543 scriptManager.ResetEventValidationState ();
1546 Trace.Write ("aspx.page", "Begin Render");
1547 HtmlTextWriter output = CreateHtmlTextWriter (Response.Output);
1548 RenderControl (output);
1549 Trace.Write ("aspx.page", "End Render");
1552 internal void SetContext (HttpContext context)
1556 _application = context.Application;
1557 _response = context.Response;
1558 _request = context.Request;
1559 _cache = context.Cache;
1564 TraceManager traceManager = HttpRuntime.TraceManager;
1566 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1571 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1574 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1575 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1576 Trace.Render (output);
1580 void RaisePostBackEvents ()
1582 if (requiresRaiseEvent != null) {
1583 RaisePostBackEvent (requiresRaiseEvent, null);
1587 if (formPostedRequiresRaiseEvent != null) {
1588 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1592 NameValueCollection postdata = _requestValueCollection;
1593 if (postdata == null)
1596 string eventTarget = postdata [postEventSourceID];
1597 IPostBackEventHandler target;
1598 if (String.IsNullOrEmpty (eventTarget)) {
1600 target = AutoPostBackControl as IPostBackEventHandler;
1602 RaisePostBackEvent (target, null);
1605 if (formPostedRequiresRaiseEvent != null)
1606 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1612 target = FindControl (eventTarget, true) as IPostBackEventHandler;
1615 target = AutoPostBackControl as IPostBackEventHandler;
1620 string eventArgument = postdata [postEventArgumentID];
1621 RaisePostBackEvent (target, eventArgument);
1624 internal void RaiseChangedEvents ()
1626 if (requiresPostDataChanged == null)
1629 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1630 ipdh.RaisePostDataChangedEvent ();
1632 requiresPostDataChanged = null;
1635 [EditorBrowsable (EditorBrowsableState.Advanced)]
1636 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1638 sourceControl.RaisePostBackEvent (eventArgument);
1641 [Obsolete ("The recommended alternative is ClientScript.RegisterArrayDeclaration(string arrayName, string arrayValue). http://go.microsoft.com/fwlink/?linkid=14202")]
1642 [EditorBrowsable (EditorBrowsableState.Advanced)]
1643 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1645 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1648 [Obsolete ("The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1649 [EditorBrowsable (EditorBrowsableState.Advanced)]
1650 public virtual void RegisterClientScriptBlock (string key, string script)
1652 scriptManager.RegisterClientScriptBlock (key, script);
1656 [EditorBrowsable (EditorBrowsableState.Advanced)]
1657 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1659 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1662 [MonoTODO("Not implemented, Used in HtmlForm")]
1663 internal void RegisterClientScriptFile (string a, string b, string c)
1665 throw new NotImplementedException ();
1668 [Obsolete ("The recommended alternative is ClientScript.RegisterOnSubmitStatement(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1669 [EditorBrowsable (EditorBrowsableState.Advanced)]
1670 public void RegisterOnSubmitStatement (string key, string script)
1672 scriptManager.RegisterOnSubmitStatement (key, script);
1675 internal string GetSubmitStatements ()
1677 return scriptManager.WriteSubmitStatements ();
1680 [EditorBrowsable (EditorBrowsableState.Advanced)]
1681 public void RegisterRequiresPostBack (Control control)
1683 if (!(control is IPostBackDataHandler))
1684 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1686 if (_requiresPostBack == null)
1687 _requiresPostBack = new List <string> ();
1689 string uniqueID = control.UniqueID;
1690 if (_requiresPostBack.Contains (uniqueID))
1693 _requiresPostBack.Add (uniqueID);
1696 [EditorBrowsable (EditorBrowsableState.Advanced)]
1697 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1699 requiresRaiseEvent = control;
1702 [Obsolete ("The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1703 [EditorBrowsable (EditorBrowsableState.Advanced)]
1704 public virtual void RegisterStartupScript (string key, string script)
1706 scriptManager.RegisterStartupScript (key, script);
1709 [EditorBrowsable (EditorBrowsableState.Advanced)]
1710 public void RegisterViewStateHandler ()
1712 handleViewState = true;
1715 [EditorBrowsable (EditorBrowsableState.Advanced)]
1716 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1718 PageStatePersister persister = this.PageStatePersister;
1719 if (persister == null)
1721 Pair pair = viewState as Pair;
1723 persister.ViewState = pair.First;
1724 persister.ControlState = pair.Second;
1726 persister.ViewState = viewState;
1730 internal string RawViewState {
1732 NameValueCollection postdata = _requestValueCollection;
1734 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1737 if (view_state == String.Empty)
1742 set { _savedViewState = value; }
1746 protected virtual PageStatePersister PageStatePersister {
1748 if (page_state_persister == null && PageAdapter != null)
1749 page_state_persister = PageAdapter.GetStatePersister();
1750 if (page_state_persister == null)
1751 page_state_persister = new HiddenFieldPageStatePersister (this);
1752 return page_state_persister;
1756 [EditorBrowsable (EditorBrowsableState.Advanced)]
1757 protected virtual object LoadPageStateFromPersistenceMedium ()
1759 PageStatePersister persister = this.PageStatePersister;
1760 if (persister == null)
1763 return new Pair (persister.ViewState, persister.ControlState);
1766 internal void LoadPageViewState ()
1768 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1769 if (sState != null) {
1770 if (allow_load || isCrossPagePostBack) {
1771 LoadPageControlState (sState.Second);
1773 Pair vsr = sState.First as Pair;
1775 LoadViewStateRecursive (vsr.First);
1776 _requiresPostBackCopy = vsr.Second as List <string>;
1782 internal void SavePageViewState ()
1784 if (!handleViewState)
1787 object controlState = SavePageControlState ();
1789 object viewState = null;
1793 && this.ViewStateMode == ViewStateMode.Enabled
1796 viewState = SaveViewStateRecursive ();
1798 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1799 if (viewState != null || reqPostback != null)
1800 vsr = new Pair (viewState, reqPostback);
1802 Pair pair = new Pair ();
1804 pair.Second = controlState;
1805 if (pair.First == null && pair.Second == null)
1806 SavePageStateToPersistenceMedium (null);
1808 SavePageStateToPersistenceMedium (pair);
1812 public virtual void Validate ()
1814 is_validated = true;
1815 ValidateCollection (_validators);
1818 internal bool AreValidatorsUplevel ()
1820 return AreValidatorsUplevel (String.Empty);
1823 internal bool AreValidatorsUplevel (string valGroup)
1825 bool uplevel = false;
1827 foreach (IValidator v in Validators) {
1828 BaseValidator bv = v as BaseValidator;
1832 if (valGroup != bv.ValidationGroup)
1834 if (bv.GetRenderUplevel()) {
1843 bool ValidateCollection (ValidatorCollection validators)
1845 if (validators == null || validators.Count == 0)
1848 bool all_valid = true;
1849 foreach (IValidator v in validators){
1851 if (v.IsValid == false)
1858 [EditorBrowsable (EditorBrowsableState.Advanced)]
1859 public virtual void VerifyRenderingInServerForm (Control control)
1861 if (Context == null)
1866 throw new HttpException ("Control '" +
1869 control.GetType ().Name +
1870 "' must be placed inside a form tag with runat=server.");
1873 protected override void FrameworkInitialize ()
1875 base.FrameworkInitialize ();
1876 InitializeStyleSheet ();
1880 public ClientScriptManager ClientScript {
1881 get { return scriptManager; }
1884 internal static readonly object InitCompleteEvent = new object ();
1885 internal static readonly object LoadCompleteEvent = new object ();
1886 internal static readonly object PreInitEvent = new object ();
1887 internal static readonly object PreLoadEvent = new object ();
1888 internal static readonly object PreRenderCompleteEvent = new object ();
1889 internal static readonly object SaveStateCompleteEvent = new object ();
1891 const int initcomplete_mask = 1;
1892 const int loadcomplete_mask = 1 << 1;
1893 const int preinit_mask = 1 << 2;
1894 const int preload_mask = 1 << 3;
1895 const int prerendercomplete_mask = 1 << 4;
1896 const int savestatecomplete_mask = 1 << 5;
1898 [EditorBrowsable (EditorBrowsableState.Advanced)]
1899 public event EventHandler InitComplete {
1901 event_mask |= initcomplete_mask;
1902 Events.AddHandler (InitCompleteEvent, value);
1904 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1907 [EditorBrowsable (EditorBrowsableState.Advanced)]
1908 public event EventHandler LoadComplete {
1910 event_mask |= loadcomplete_mask;
1911 Events.AddHandler (LoadCompleteEvent, value);
1913 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1916 public event EventHandler PreInit {
1918 event_mask |= preinit_mask;
1919 Events.AddHandler (PreInitEvent, value);
1921 remove { Events.RemoveHandler (PreInitEvent, value); }
1924 [EditorBrowsable (EditorBrowsableState.Advanced)]
1925 public event EventHandler PreLoad {
1927 event_mask |= preload_mask;
1928 Events.AddHandler (PreLoadEvent, value);
1930 remove { Events.RemoveHandler (PreLoadEvent, value); }
1933 [EditorBrowsable (EditorBrowsableState.Advanced)]
1934 public event EventHandler PreRenderComplete {
1936 event_mask |= prerendercomplete_mask;
1937 Events.AddHandler (PreRenderCompleteEvent, value);
1939 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1942 [EditorBrowsable (EditorBrowsableState.Advanced)]
1943 public event EventHandler SaveStateComplete {
1945 event_mask |= savestatecomplete_mask;
1946 Events.AddHandler (SaveStateCompleteEvent, value);
1948 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1951 protected virtual void OnInitComplete (EventArgs e)
1953 if ((event_mask & initcomplete_mask) != 0) {
1954 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1955 if (eh != null) eh (this, e);
1959 protected virtual void OnLoadComplete (EventArgs e)
1961 if ((event_mask & loadcomplete_mask) != 0) {
1962 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1963 if (eh != null) eh (this, e);
1967 protected virtual void OnPreInit (EventArgs e)
1969 if ((event_mask & preinit_mask) != 0) {
1970 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1971 if (eh != null) eh (this, e);
1975 protected virtual void OnPreLoad (EventArgs e)
1977 if ((event_mask & preload_mask) != 0) {
1978 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1979 if (eh != null) eh (this, e);
1983 protected virtual void OnPreRenderComplete (EventArgs e)
1985 if ((event_mask & prerendercomplete_mask) != 0) {
1986 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1987 if (eh != null) eh (this, e);
1992 if (!Form.DetermineRenderUplevel ())
1995 string defaultButtonId = Form.DefaultButton;
1996 /* figure out if we have some control we're going to focus */
1997 if (String.IsNullOrEmpty (_focusedControlID)) {
1998 _focusedControlID = Form.DefaultFocus;
1999 if (String.IsNullOrEmpty (_focusedControlID))
2000 _focusedControlID = defaultButtonId;
2003 if (!String.IsNullOrEmpty (_focusedControlID)) {
2004 ClientScript.RegisterWebFormClientScript ();
2006 ClientScript.RegisterStartupScript (
2008 "HtmlForm-DefaultButton-StartupScript",
2009 "\n" + WebFormScriptReference + ".WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
2012 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
2013 ClientScript.RegisterWebFormClientScript ();
2015 ClientScript.RegisterOnSubmitStatement (
2017 "HtmlForm-SubmitDisabledControls-SubmitStatement",
2018 WebFormScriptReference + ".WebForm_ReEnableControls();");
2022 internal void RegisterEnabledControl (Control control)
2024 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
2026 _hasEnabledControlArray = true;
2027 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
2030 protected virtual void OnSaveStateComplete (EventArgs e)
2032 if ((event_mask & savestatecomplete_mask) != 0) {
2033 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
2034 if (eh != null) eh (this, e);
2038 public HtmlForm Form {
2039 get { return _form; }
2042 internal void RegisterForm (HtmlForm form)
2047 public string ClientQueryString {
2048 get { return Request.UrlComponents.Query; }
2051 [BrowsableAttribute (false)]
2052 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2053 public Page PreviousPage {
2055 if (_doLoadPreviousPage) {
2056 _doLoadPreviousPage = false;
2057 LoadPreviousPageReference ();
2059 return previousPage;
2064 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2065 [BrowsableAttribute (false)]
2066 public bool IsCallback {
2067 get { return isCallback; }
2070 [BrowsableAttribute (false)]
2071 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2072 public bool IsCrossPagePostBack {
2073 get { return isCrossPagePostBack; }
2077 [EditorBrowsable (EditorBrowsableState.Never)]
2078 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2079 public new virtual char IdSeparator {
2081 //TODO: why override?
2082 return base.IdSeparator;
2086 string ProcessCallbackData ()
2088 ICallbackEventHandler target = GetCallbackTarget ();
2089 string callbackEventError = String.Empty;
2090 ProcessRaiseCallbackEvent (target, ref callbackEventError);
2091 return ProcessGetCallbackResult (target, callbackEventError);
2094 ICallbackEventHandler GetCallbackTarget ()
2096 string callbackTarget = _requestValueCollection [CallbackSourceID];
2097 if (callbackTarget == null || callbackTarget.Length == 0)
2098 throw new HttpException ("Callback target not provided.");
2100 Control targetControl = FindControl (callbackTarget, true);
2101 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2103 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2107 void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError)
2109 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2112 target.RaiseCallbackEvent (callbackArgument);
2113 } catch (Exception ex) {
2114 callbackEventError = String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2119 string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError)
2121 string callBackResult;
2123 callBackResult = target.GetCallbackResult ();
2124 } catch (Exception ex) {
2125 return String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2128 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2129 return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
2130 eventValidation + callBackResult;
2133 [BrowsableAttribute (false)]
2134 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2135 public HtmlHead Header {
2136 get { return htmlHeader; }
2139 internal void SetHeader (HtmlHead header)
2141 htmlHeader = header;
2145 if (_title != null) {
2146 htmlHeader.Title = _title;
2150 if (_metaDescription != null) {
2151 htmlHeader.Description = _metaDescription;
2152 _metaDescription = null;
2155 if (_metaKeywords != null) {
2156 htmlHeader.Keywords = _metaKeywords;
2157 _metaKeywords = null;
2162 [EditorBrowsable (EditorBrowsableState.Never)]
2163 protected bool AsyncMode {
2164 get { return asyncMode; }
2165 set { asyncMode = value; }
2169 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2170 [EditorBrowsable (EditorBrowsableState.Advanced)]
2171 public TimeSpan AsyncTimeout {
2172 get { return asyncTimeout; }
2173 set { asyncTimeout = value; }
2176 public bool IsAsync {
2177 get { return AsyncMode; }
2180 protected internal virtual string UniqueFilePathSuffix {
2182 if (String.IsNullOrEmpty (uniqueFilePathSuffix))
2183 uniqueFilePathSuffix = "__ufps=" + AppRelativeVirtualPath.GetHashCode ().ToString ("x");
2184 return uniqueFilePathSuffix;
2188 [MonoTODO ("Actually use the value in code.")]
2190 [EditorBrowsable (EditorBrowsableState.Never)]
2191 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2192 public int MaxPageStateFieldLength {
2193 get { return maxPageStateFieldLength; }
2194 set { maxPageStateFieldLength = value; }
2197 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2199 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2202 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2205 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2208 if (IsPrerendered) {
2209 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
2212 if (beginHandler == null) {
2213 throw new ArgumentNullException ("beginHandler");
2216 if (endHandler == null) {
2217 throw new ArgumentNullException ("endHandler");
2220 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2223 List<PageAsyncTask> ParallelTasks {
2225 if (parallelTasks == null)
2226 parallelTasks = new List<PageAsyncTask>();
2227 return parallelTasks;
2231 List<PageAsyncTask> SerialTasks {
2233 if (serialTasks == null)
2234 serialTasks = new List<PageAsyncTask> ();
2239 public void RegisterAsyncTask (PageAsyncTask task)
2242 throw new ArgumentNullException ("task");
2244 if (task.ExecuteInParallel)
2245 ParallelTasks.Add (task);
2247 SerialTasks.Add (task);
2250 public void ExecuteRegisteredAsyncTasks ()
2252 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2253 (serialTasks == null || serialTasks.Count == 0)){
2257 if (parallelTasks != null) {
2258 DateTime startExecution = DateTime.Now;
2259 List<PageAsyncTask> localParallelTasks = parallelTasks;
2260 parallelTasks = null; // Shouldn't execute tasks twice
2261 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2262 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2263 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2264 if (result.CompletedSynchronously)
2265 parallelTask.EndHandler (result);
2267 asyncResults.Add (result);
2270 if (asyncResults.Count > 0) {
2272 TimeSpan timeout = AsyncTimeout;
2273 long t1 = DateTime.Now.Ticks;
2274 bool signalled = true;
2275 for (int i = 0; i < asyncResults.Count; i++) {
2276 if (asyncResults [i].IsCompleted)
2280 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2283 long t2 = DateTime.Now.Ticks;
2284 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2285 if (timeout.Ticks <= 0)
2288 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2291 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2293 for (i = 0; i < asyncResults.Count; i++) {
2294 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2297 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2298 if (!allSignalled) {
2299 for (i = 0; i < asyncResults.Count; i++) {
2300 if (!asyncResults [i].IsCompleted) {
2301 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2307 DateTime endWait = DateTime.Now;
2308 TimeSpan elapsed = endWait - startExecution;
2309 if (elapsed <= AsyncTimeout)
2310 AsyncTimeout -= elapsed;
2312 AsyncTimeout = TimeSpan.FromTicks(0);
2315 if (serialTasks != null) {
2316 List<PageAsyncTask> localSerialTasks = serialTasks;
2317 serialTasks = null; // Shouldn't execute tasks twice
2318 foreach (PageAsyncTask serialTask in localSerialTasks) {
2319 DateTime startExecution = DateTime.Now;
2321 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2322 if (result.CompletedSynchronously)
2323 serialTask.EndHandler (result);
2325 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2326 if (!done && !result.IsCompleted) {
2327 serialTask.TimeoutHandler (result);
2330 DateTime endWait = DateTime.Now;
2331 TimeSpan elapsed = endWait - startExecution;
2332 if (elapsed <= AsyncTimeout)
2333 AsyncTimeout -= elapsed;
2335 AsyncTimeout = TimeSpan.FromTicks (0);
2338 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2341 void EndAsyncTaskCallback (IAsyncResult result)
2343 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2344 task.EndHandler (result);
2347 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2349 Type htmlTextWriterType = typeof (HtmlTextWriter);
2351 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2352 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2355 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2356 if (constructor == null) {
2357 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2360 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2364 [DefaultValue ("0")]
2365 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2366 [EditorBrowsable (EditorBrowsableState.Never)]
2367 public ViewStateEncryptionMode ViewStateEncryptionMode {
2368 get { return viewStateEncryptionMode; }
2369 set { viewStateEncryptionMode = value; }
2372 public void RegisterRequiresViewStateEncryption ()
2374 controlRegisteredForViewStateEncryption = true;
2377 internal bool NeedViewStateEncryption {
2379 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2380 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2381 controlRegisteredForViewStateEncryption));
2386 void ApplyMasterPage ()
2388 if (masterPageFile != null && masterPageFile.Length > 0) {
2389 List <string> appliedMasterPageFiles = new List <string> ();
2391 if (Master != null) {
2392 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2396 Controls.Add (Master);
2401 [DefaultValueAttribute ("")]
2402 public virtual string MasterPageFile {
2403 get { return masterPageFile; }
2405 masterPageFile = value;
2410 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2411 [BrowsableAttribute (false)]
2412 public MasterPage Master {
2414 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2417 if (masterPage == null)
2418 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2424 public void SetFocus (string clientID)
2426 if (String.IsNullOrEmpty (clientID))
2427 throw new ArgumentNullException ("control");
2430 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2433 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2435 _focusedControlID = clientID;
2438 public void SetFocus (Control control)
2440 if (control == null)
2441 throw new ArgumentNullException ("control");
2443 SetFocus (control.ClientID);
2446 [EditorBrowsable (EditorBrowsableState.Advanced)]
2447 public void RegisterRequiresControlState (Control control)
2449 if (control == null)
2450 throw new ArgumentNullException ("control");
2452 if (RequiresControlState (control))
2455 if (requireStateControls == null)
2456 requireStateControls = new List <Control> ();
2457 requireStateControls.Add (control);
2458 int n = requireStateControls.Count - 1;
2460 if (_savedControlState == null || n >= _savedControlState.Length)
2463 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2464 if (parent.IsChildControlStateCleared)
2467 object state = _savedControlState [n];
2469 control.LoadControlState (state);
2472 public bool RequiresControlState (Control control)
2474 if (requireStateControls == null)
2476 return requireStateControls.Contains (control);
2479 [EditorBrowsable (EditorBrowsableState.Advanced)]
2480 public void UnregisterRequiresControlState (Control control)
2482 if (requireStateControls != null)
2483 requireStateControls.Remove (control);
2486 public ValidatorCollection GetValidators (string validationGroup)
2488 if (validationGroup == String.Empty)
2489 validationGroup = null;
2491 ValidatorCollection col = new ValidatorCollection ();
2492 if (_validators == null)
2495 foreach (IValidator v in _validators)
2496 if (BelongsToGroup(v, validationGroup))
2502 bool BelongsToGroup(IValidator v, string validationGroup)
2504 BaseValidator validator = v as BaseValidator;
2505 if (validationGroup == null)
2506 return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
2508 return validator != null && validator.ValidationGroup == validationGroup;
2511 public virtual void Validate (string validationGroup)
2513 is_validated = true;
2514 ValidateCollection (GetValidators (validationGroup));
2517 object SavePageControlState ()
2519 int count = requireStateControls == null ? 0 : requireStateControls.Count;
2524 object[] controlStates = new object [count];
2525 object[] adapterState = new object [count];
2527 ControlAdapter adapter;
2528 bool allNull = true;
2529 TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
2531 for (int n = 0; n < count; n++) {
2532 control = requireStateControls [n];
2533 state = controlStates [n] = control.SaveControlState ();
2538 trace.SaveControlState (control, state);
2540 adapter = control.Adapter;
2541 if (adapter != null) {
2542 adapterState [n] = adapter.SaveAdapterControlState ();
2543 if (adapterState [n] != null) allNull = false;
2550 return new Pair (controlStates, adapterState);
2553 void LoadPageControlState (object data)
2555 _savedControlState = null;
2556 if (data == null) return;
2557 Pair statePair = (Pair)data;
2558 _savedControlState = (object[]) statePair.First;
2559 object[] adapterState = (object[]) statePair.Second;
2561 if (requireStateControls == null) return;
2563 int min = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2564 for (int n=0; n < min; n++) {
2565 Control ctl = (Control) requireStateControls [n];
2566 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2567 if (ctl.Adapter != null)
2568 ctl.Adapter.LoadAdapterControlState (adapterState != null ? adapterState [n] : null);
2572 void LoadPreviousPageReference ()
2574 if (_requestValueCollection != null) {
2575 string prevPage = _requestValueCollection [PreviousPageID];
2576 if (prevPage != null) {
2578 if (getFacesContext () != null) {
2579 IHttpHandler handler = Context.ApplicationInstance.GetHandler (Context, prevPage);
2580 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2581 if (_context.Items.Contains (CrossPagePostBack)) {
2582 previousPage = (Page) _context.Items [CrossPagePostBack];
2583 _context.Items.Remove (CrossPagePostBack);
2588 IHttpHandler handler;
2589 handler = BuildManager.CreateInstanceFromVirtualPath (prevPage, typeof (IHttpHandler)) as IHttpHandler;
2590 previousPage = (Page) handler;
2591 previousPage.isCrossPagePostBack = true;
2592 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2598 Hashtable contentTemplates;
2599 [EditorBrowsable (EditorBrowsableState.Never)]
2600 protected internal void AddContentTemplate (string templateName, ITemplate template)
2602 if (contentTemplates == null)
2603 contentTemplates = new Hashtable ();
2604 contentTemplates [templateName] = template;
2607 PageTheme _pageTheme;
2608 internal PageTheme PageTheme {
2609 get { return _pageTheme; }
2612 PageTheme _styleSheetPageTheme;
2613 internal PageTheme StyleSheetPageTheme {
2614 get { return _styleSheetPageTheme; }
2619 internal void PushDataItemContext (object o) {
2620 if (dataItemCtx == null)
2621 dataItemCtx = new Stack ();
2623 dataItemCtx.Push (o);
2626 internal void PopDataItemContext () {
2627 if (dataItemCtx == null)
2628 throw new InvalidOperationException ();
2633 public object GetDataItem() {
2634 if (dataItemCtx == null || dataItemCtx.Count == 0)
2635 throw new InvalidOperationException ("No data item");
2637 return dataItemCtx.Peek ();
2640 void AddStyleSheets (PageTheme theme, ref List <string> links)
2645 string[] tmpThemes = theme != null ? theme.GetStyleSheets () : null;
2646 if (tmpThemes == null || tmpThemes.Length == 0)
2650 links = new List <string> ();
2652 links.AddRange (tmpThemes);
2655 protected internal override void OnInit (EventArgs e)
2659 List <string> themes = null;
2660 AddStyleSheets (StyleSheetPageTheme, ref themes);
2661 AddStyleSheets (PageTheme, ref themes);
2666 HtmlHead header = Header;
2667 if (themes != null && header == null)
2668 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2670 ControlCollection headerControls = header.Controls;
2672 for (int i = themes.Count - 1; i >= 0; i--) {
2674 HtmlLink hl = new HtmlLink ();
2676 hl.Attributes["type"] = "text/css";
2677 hl.Attributes["rel"] = "stylesheet";
2678 headerControls.AddAt (0, hl);
2682 [MonoDocumentationNote ("Not implemented. Only used by .net aspx parser")]
2683 [EditorBrowsable (EditorBrowsableState.Never)]
2684 protected object GetWrappedFileDependencies (string [] list)
2689 [MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
2690 protected virtual void InitializeCulture ()
2694 [MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
2695 [EditorBrowsable (EditorBrowsableState.Never)]
2696 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)