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-2008 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.Specialized;
36 using System.ComponentModel;
37 using System.ComponentModel.Design;
38 using System.ComponentModel.Design.Serialization;
39 using System.Globalization;
41 using System.Security.Cryptography;
42 using System.Security.Permissions;
43 using System.Security.Principal;
45 using System.Threading;
47 using System.Web.Caching;
48 using System.Web.Configuration;
49 using System.Web.SessionState;
50 using System.Web.Util;
51 using System.Web.UI.HtmlControls;
52 using System.Web.UI.WebControls;
53 using System.Reflection;
55 using System.Web.Compilation;
56 using System.Web.UI.Adapters;
57 using System.Collections.Generic;
60 namespace System.Web.UI
63 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
64 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
66 [RootDesignerSerializer ("Microsoft.VSDesigner.WebForms.RootCodeDomSerializer, " + Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design, true)]
68 [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
71 [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
73 [Designer ("Microsoft.VSDesigner.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VSDesigner, typeof (IRootDesigner))]
75 public partial class Page : TemplateControl, IHttpHandler
78 static string machineKeyConfigPath = "system.web/machineKey";
79 bool _eventValidation = true;
80 object [] _savedControlState;
81 bool _doLoadPreviousPage;
82 string _focusedControlID;
83 bool _hasEnabledControlArray;
89 bool _smartNavigation;
91 ValidatorCollection _validators;
93 string _savedViewState;
94 ArrayList _requiresPostBack;
95 ArrayList _requiresPostBackCopy;
96 ArrayList requiresPostDataChanged;
97 IPostBackEventHandler requiresRaiseEvent;
98 IPostBackEventHandler formPostedRequiresRaiseEvent;
99 NameValueCollection secondPostData;
100 bool requiresPostBackScript;
101 bool postBackScriptRendered;
102 bool requiresFormScriptDeclaration;
103 bool formScriptDeclarationRendered;
104 bool handleViewState;
105 string viewStateUserKey;
106 NameValueCollection _requestValueCollection;
108 ClientScriptManager scriptManager;
109 bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
110 PageStatePersister page_state_persister;
111 CultureInfo _appCulture;
112 CultureInfo _appUICulture;
114 // The initial context
115 HttpContext _context;
117 // cached from the initial context
118 HttpApplicationState _application;
119 HttpResponse _response;
120 HttpRequest _request;
123 HttpSessionState _session;
125 [EditorBrowsable (EditorBrowsableState.Never)]
131 const string postEventArgumentID = "__EVENTARGUMENT";
133 [EditorBrowsable (EditorBrowsableState.Never)]
139 const string postEventSourceID = "__EVENTTARGET";
142 const string ScrollPositionXID = "__SCROLLPOSITIONX";
143 const string ScrollPositionYID = "__SCROLLPOSITIONY";
144 const string EnabledControlArrayID = "__enabledControlArray";
148 internal const string LastFocusID = "__LASTFOCUS";
149 internal const string CallbackArgumentID = "__CALLBACKARGUMENT";
150 internal const string CallbackSourceID = "__CALLBACKTARGET";
151 internal const string PreviousPageID = "__PREVIOUSPAGE";
153 int maxPageStateFieldLength = -1;
154 string uniqueFilePathSuffix;
157 MasterPage masterPage;
158 string masterPageFile;
161 bool isCrossPagePostBack;
164 List <Control> requireStateControls;
169 string _styleSheetTheme;
172 bool _maintainScrollPositionOnPostBack;
174 bool asyncMode = false;
175 TimeSpan asyncTimeout;
176 const double DefaultAsyncTimeout = 45.0;
177 List<PageAsyncTask> parallelTasks;
178 List<PageAsyncTask> serialTasks;
180 ViewStateEncryptionMode viewStateEncryptionMode;
181 bool controlRegisteredForViewStateEncryption = false;
187 scriptManager = new ClientScriptManager (this);
192 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
194 asyncTimeout = ps.AsyncTimeout;
195 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
196 _viewState = ps.EnableViewState;
198 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
199 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
209 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
211 public HttpApplicationState Application {
212 get { return _application; }
215 [EditorBrowsable (EditorBrowsableState.Never)]
216 protected bool AspCompatMode {
218 get { return false; }
220 set { throw new NotImplementedException (); }
223 [EditorBrowsable (EditorBrowsableState.Never)]
225 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
226 [BrowsableAttribute (false)]
228 get { return Response.BufferOutput; }
229 set { Response.BufferOutput = value; }
232 protected bool Buffer {
233 set { Response.BufferOutput = value; }
237 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
242 throw new HttpException ("Cache is not available.");
248 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
250 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
251 [Browsable (false), DefaultValue ("")]
252 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
253 public string ClientTarget {
254 get { return (clientTarget == null) ? "" : clientTarget; }
256 clientTarget = value;
262 [EditorBrowsable (EditorBrowsableState.Never)]
264 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
265 [BrowsableAttribute (false)]
266 public int CodePage {
267 get { return Response.ContentEncoding.CodePage; }
268 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
271 protected int CodePage {
272 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
276 [EditorBrowsable (EditorBrowsableState.Never)]
278 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
279 [BrowsableAttribute (false)]
280 public string ContentType {
281 get { return Response.ContentType; }
282 set { Response.ContentType = value; }
285 protected string ContentType {
286 set { Response.ContentType = value; }
295 override HttpContext Context {
297 if (_context == null)
298 return HttpContext.Current;
305 [EditorBrowsable (EditorBrowsableState.Advanced)]
306 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
307 [BrowsableAttribute (false)]
308 public string Culture {
309 get { return Thread.CurrentThread.CurrentCulture.Name; }
310 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
313 [EditorBrowsable (EditorBrowsableState.Never)]
314 protected string Culture {
315 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
320 public virtual bool EnableEventValidation {
321 get { return _eventValidation; }
324 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
325 _eventValidation = value;
331 public override bool EnableViewState {
332 get { return _viewState; }
333 set { _viewState = value; }
337 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
338 [BrowsableAttribute (false)]
340 [EditorBrowsable (EditorBrowsableState.Never)]
346 bool EnableViewStateMac {
347 get { return _viewStateMac; }
348 set { _viewStateMac = value; }
352 internal bool EnableViewStateMacInternal {
353 get { return _viewStateMac; }
354 set { _viewStateMac = value; }
358 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
359 [Browsable (false), DefaultValue ("")]
360 [WebSysDescription ("The URL of a page used for error redirection.")]
361 public string ErrorPage {
362 get { return _errorPage; }
364 HttpContext ctx = Context;
368 ctx.ErrorPage = value;
375 [EditorBrowsable (EditorBrowsableState.Never)]
376 protected ArrayList FileDependencies {
378 if (Response != null)
379 Response.AddFileDependencies (value);
385 [EditorBrowsable (EditorBrowsableState.Never)]
387 public override string ID {
388 get { return base.ID; }
389 set { base.ID = value; }
392 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
394 public bool IsPostBack {
399 return _requestValueCollection != null;
404 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
405 public bool IsReusable {
406 get { return false; }
409 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
411 public bool IsValid {
414 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."));
417 foreach (IValidator val in Validators)
422 return ValidateCollection (_validators);
427 public IDictionary Items {
430 items = new Hashtable ();
436 [EditorBrowsable (EditorBrowsableState.Never)]
438 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
439 [BrowsableAttribute (false)]
441 get { return Thread.CurrentThread.CurrentCulture.LCID; }
442 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
446 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
452 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
453 public bool MaintainScrollPositionOnPostBack {
454 get { return _maintainScrollPositionOnPostBack; }
455 set { _maintainScrollPositionOnPostBack = value; }
460 public PageAdapter PageAdapter {
462 return Adapter as PageAdapter;
466 string _validationStartupScript;
467 string _validationOnSubmitStatement;
468 string _validationInitializeScript;
469 string _webFormScriptReference;
471 internal string WebFormScriptReference {
473 if (_webFormScriptReference == null)
474 _webFormScriptReference = IsMultiForm ? theForm : "window";
475 return _webFormScriptReference;
479 internal string ValidationStartupScript {
481 if (_validationStartupScript == null) {
482 _validationStartupScript =
484 " + WebFormScriptReference + @".Page_ValidationActive = false;
485 " + WebFormScriptReference + @".ValidatorOnLoad();
486 " + WebFormScriptReference + @".ValidatorOnSubmit = function () {
487 if (this.Page_ValidationActive) {
488 return this.ValidatorCommonOnSubmit();
494 return _validationStartupScript;
498 internal string ValidationOnSubmitStatement {
500 if (_validationOnSubmitStatement == null)
501 _validationOnSubmitStatement = "if (!" + WebFormScriptReference + ".ValidatorOnSubmit()) return false;";
502 return _validationOnSubmitStatement;
506 internal string ValidationInitializeScript {
508 if (_validationInitializeScript == null)
509 _validationInitializeScript = "WebFormValidation_Initialize(" + WebFormScriptReference + ");";
510 return _validationInitializeScript;
514 internal IScriptManager ScriptManager {
515 get { return (IScriptManager) Items [typeof (IScriptManager)]; }
521 internal string theForm {
527 internal bool IsMultiForm {
528 get { return false; }
532 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
534 public HttpRequest Request {
536 if (_request == null)
537 throw new HttpException("Request is not available in this context.");
542 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
544 public HttpResponse Response {
546 if (_response == null)
547 throw new HttpException ("Response is not available in this context.");
552 [EditorBrowsable (EditorBrowsableState.Never)]
554 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
555 [BrowsableAttribute (false)]
556 public string ResponseEncoding {
557 get { return Response.ContentEncoding.WebName; }
558 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
561 protected string ResponseEncoding {
562 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
566 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
568 public HttpServerUtility Server {
569 get { return Context.Server; }
572 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
574 public virtual HttpSessionState Session {
576 if (_session != null)
580 _session = Context.Session;
582 // ignore, should not throw
585 if (_session == null)
586 throw new HttpException ("Session state can only be used " +
587 "when enableSessionState is set to true, either " +
588 "in a configuration file or in the Page directive.");
595 [FilterableAttribute (false)]
599 public bool SmartNavigation {
600 get { return _smartNavigation; }
601 set { _smartNavigation = value; }
605 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
608 public virtual string StyleSheetTheme {
609 get { return _styleSheetTheme; }
610 set { _styleSheetTheme = value; }
614 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
615 public virtual string Theme {
616 get { return _theme; }
617 set { _theme = value; }
620 void InitializeStyleSheet ()
622 if (_styleSheetTheme == null) {
623 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
625 _styleSheetTheme = ps.StyleSheetTheme;
628 if (_styleSheetTheme != null && _styleSheetTheme != "")
629 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, Context);
631 if (!String.IsNullOrEmpty (_styleSheetTheme)) {
632 string virtualPath = "~/App_Themes/" + _styleSheetTheme;
633 _styleSheetPageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
638 void InitializeTheme ()
640 if (_theme == null) {
641 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
646 if (_theme != null && _theme != "") {
647 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, Context);
648 _pageTheme.SetPage (this);
651 if (!String.IsNullOrEmpty (_theme)) {
652 string virtualPath = "~/App_Themes/" + _theme;
653 _pageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
654 if (_pageTheme != null)
655 _pageTheme.SetPage (this);
665 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
666 public string Title {
668 if (_title == null) {
669 if (htmlHeader != null && htmlHeader.Title != null)
670 return htmlHeader.Title;
677 if (htmlHeader != null)
678 htmlHeader.Title = value;
685 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
687 public TraceContext Trace {
688 get { return Context.Trace; }
691 [EditorBrowsable (EditorBrowsableState.Never)]
693 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
694 [BrowsableAttribute (false)]
695 public bool TraceEnabled {
696 get { return Trace.IsEnabled; }
697 set { Trace.IsEnabled = value; }
700 protected bool TraceEnabled {
701 set { Trace.IsEnabled = value; }
705 [EditorBrowsable (EditorBrowsableState.Never)]
707 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
708 [BrowsableAttribute (false)]
709 public TraceMode TraceModeValue {
710 get { return Trace.TraceMode; }
711 set { Trace.TraceMode = value; }
714 protected TraceMode TraceModeValue {
715 set { Trace.TraceMode = value; }
719 [EditorBrowsable (EditorBrowsableState.Never)]
720 protected int TransactionMode {
722 get { return _transactionMode; }
724 set { _transactionMode = value; }
729 // This method is here just to remove the warning about "_transactionMode" not being
730 // used. We probably will use it internally at some point.
732 internal int GetTransactionMode ()
734 return _transactionMode;
739 [EditorBrowsable (EditorBrowsableState.Advanced)]
740 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
741 [BrowsableAttribute (false)]
742 public string UICulture {
743 get { return Thread.CurrentThread.CurrentUICulture.Name; }
744 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
747 [EditorBrowsable (EditorBrowsableState.Never)]
748 protected string UICulture {
749 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
753 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
755 public IPrincipal User {
756 get { return Context.User; }
759 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
761 public ValidatorCollection Validators {
763 if (_validators == null)
764 _validators = new ValidatorCollection ();
769 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
771 public string ViewStateUserKey {
772 get { return viewStateUserKey; }
773 set { viewStateUserKey = value; }
777 public override bool Visible {
778 get { return base.Visible; }
779 set { base.Visible = value; }
787 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
791 CultureInfo ret = null;
792 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
794 if (!Context.IsServletRequest)
797 string[] languages = Request.UserLanguages;
799 if (languages != null && languages.Length > 0)
800 ret = CultureInfo.CreateSpecificCulture (languages[0]);
807 ret = CultureInfo.CreateSpecificCulture (culture);
813 [EditorBrowsable (EditorBrowsableState.Never)]
814 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
818 throw new NotImplementedException ();
821 [EditorBrowsable (EditorBrowsableState.Never)]
822 protected void AspCompatEndProcessRequest (IAsyncResult result)
824 throw new NotImplementedException ();
827 [EditorBrowsable (EditorBrowsableState.Advanced)]
828 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
831 if (Request.BrowserMightHaveSpecialWriter)
832 return Request.Browser.CreateHtmlTextWriter(tw);
835 return new HtmlTextWriter (tw);
838 [EditorBrowsable (EditorBrowsableState.Never)]
839 public void DesignerInitialize ()
841 InitRecursive (null);
844 [EditorBrowsable (EditorBrowsableState.Advanced)]
849 virtual NameValueCollection DeterminePostBackMode ()
851 // if request was transfered from other page such Transfer
852 if (_context.IsProcessingInclude)
855 HttpRequest req = Request;
859 NameValueCollection coll = null;
860 if (0 == String.Compare (Request.HttpMethod, "POST", true, Helpers.InvariantCulture)
862 || !_context.IsServletRequest
867 string query = Request.QueryStringRaw;
868 if (query == null || query.Length == 0)
871 coll = req.QueryString;
874 WebROCollection c = (WebROCollection) coll;
875 allow_load = !c.GotID;
877 c.ID = GetTypeHashCode ();
879 allow_load = (c.ID == GetTypeHashCode ());
881 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
884 if (getFacesContext () != null && _context.Handler != _context.CurrentHandler) {
885 // check if it is PreviousPage
886 string prevViewId = coll [PreviousPageID];
887 if (!String.IsNullOrEmpty (prevViewId)) {
888 string appPath = VirtualPathUtility.RemoveTrailingSlash (Request.ApplicationPath);
889 prevViewId = prevViewId.Substring (appPath.Length);
890 isCrossPagePostBack = String.Compare (prevViewId, getFacesContext ().getExternalContext ().getRequestPathInfo (), StringComparison.OrdinalIgnoreCase) == 0;
898 public override Control FindControl (string id) {
902 return base.FindControl (id);
906 Control FindControl (string id, bool decode) {
909 id = DecodeNamespace (id);
911 return FindControl (id);
917 [EditorBrowsable (EditorBrowsableState.Advanced)]
918 public string GetPostBackClientEvent (Control control, string argument)
920 return scriptManager.GetPostBackEventReference (control, argument);
926 [EditorBrowsable (EditorBrowsableState.Advanced)]
927 public string GetPostBackClientHyperlink (Control control, string argument)
929 return scriptManager.GetPostBackClientHyperlink (control, argument);
935 [EditorBrowsable (EditorBrowsableState.Advanced)]
936 public string GetPostBackEventReference (Control control)
938 return scriptManager.GetPostBackEventReference (control, "");
944 [EditorBrowsable (EditorBrowsableState.Advanced)]
945 public string GetPostBackEventReference (Control control, string argument)
947 return scriptManager.GetPostBackEventReference (control, argument);
950 internal void RequiresFormScriptDeclaration ()
952 requiresFormScriptDeclaration = true;
955 internal void RequiresPostBackScript ()
958 if (requiresPostBackScript)
960 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
961 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
963 requiresPostBackScript = true;
964 RequiresFormScriptDeclaration ();
967 [EditorBrowsable (EditorBrowsableState.Never)]
968 public virtual int GetTypeHashCode ()
974 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, SqlDependency")]
975 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
977 if (cacheSettings.Enabled) {
978 InitOutputCache(cacheSettings.Duration,
979 cacheSettings.VaryByContentEncoding,
980 cacheSettings.VaryByHeader,
981 cacheSettings.VaryByCustom,
982 cacheSettings.Location,
983 cacheSettings.VaryByParam);
985 HttpResponse response = Response;
986 HttpCachePolicy cache = response != null ? response.Cache : null;
987 if (cache != null && cacheSettings.NoStore)
994 [MonoTODO ("varyByContentEncoding is not currently used")]
997 void InitOutputCache(int duration,
998 string varyByContentEncoding,
1000 string varyByCustom,
1001 OutputCacheLocation location,
1004 HttpResponse response = Response;
1005 HttpCachePolicy cache = response.Cache;
1006 bool set_vary = false;
1007 HttpContext ctx = Context;
1008 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
1011 case OutputCacheLocation.Any:
1012 cache.SetCacheability (HttpCacheability.Public);
1013 cache.SetMaxAge (new TimeSpan (0, 0, duration));
1014 cache.SetLastModified (timestamp);
1017 case OutputCacheLocation.Client:
1018 cache.SetCacheability (HttpCacheability.Private);
1019 cache.SetMaxAge (new TimeSpan (0, 0, duration));
1020 cache.SetLastModified (timestamp);
1022 case OutputCacheLocation.Downstream:
1023 cache.SetCacheability (HttpCacheability.Public);
1024 cache.SetMaxAge (new TimeSpan (0, 0, duration));
1025 cache.SetLastModified (timestamp);
1027 case OutputCacheLocation.Server:
1028 cache.SetCacheability (HttpCacheability.Server);
1031 case OutputCacheLocation.None:
1036 if (varyByCustom != null)
1037 cache.SetVaryByCustom (varyByCustom);
1039 if (varyByParam != null && varyByParam.Length > 0) {
1040 string[] prms = varyByParam.Split (';');
1041 foreach (string p in prms)
1042 cache.VaryByParams [p.Trim ()] = true;
1043 cache.VaryByParams.IgnoreParams = false;
1045 cache.VaryByParams.IgnoreParams = true;
1048 if (varyByHeader != null && varyByHeader.Length > 0) {
1049 string[] hdrs = varyByHeader.Split (';');
1050 foreach (string h in hdrs)
1051 cache.VaryByHeaders [h.Trim ()] = true;
1054 if (PageAdapter != null) {
1055 if (PageAdapter.CacheVaryByParams != null) {
1056 foreach (string p in PageAdapter.CacheVaryByParams)
1057 cache.VaryByParams [p] = true;
1059 if (PageAdapter.CacheVaryByHeaders != null) {
1060 foreach (string h in PageAdapter.CacheVaryByHeaders)
1061 cache.VaryByHeaders [h] = true;
1067 response.IsCached = true;
1068 cache.Duration = duration;
1069 cache.SetExpires (timestamp.AddSeconds (duration));
1073 [EditorBrowsable (EditorBrowsableState.Never)]
1074 protected virtual void InitOutputCache (int duration,
1075 string varyByHeader,
1076 string varyByCustom,
1077 OutputCacheLocation location,
1080 InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
1086 [EditorBrowsable (EditorBrowsableState.Advanced)]
1088 public bool IsClientScriptBlockRegistered (string key)
1090 return scriptManager.IsClientScriptBlockRegistered (key);
1096 [EditorBrowsable (EditorBrowsableState.Advanced)]
1098 public bool IsStartupScriptRegistered (string key)
1100 return scriptManager.IsStartupScriptRegistered (key);
1103 public string MapPath (string virtualPath)
1105 return Request.MapPath (virtualPath);
1109 protected internal override void Render (HtmlTextWriter writer)
1111 if (MaintainScrollPositionOnPostBack) {
1112 ClientScript.RegisterWebFormClientScript ();
1114 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
1115 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
1117 StringBuilder script = new StringBuilder ();
1118 script.AppendLine ("<script type=\"text/javascript\">");
1119 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
1120 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
1121 script.AppendLine (theForm + ".submit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionSubmit(); }");
1122 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
1123 script.AppendLine (theForm + ".onsubmit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionOnSubmit(); }");
1125 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
1126 script.AppendLine ("window.onload = function () { " + WebFormScriptReference + ".WebForm_RestoreScrollPosition (); };");
1128 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
1129 script.AppendLine ("</script>");
1131 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1134 if (bool.Parse (WebConfigurationManager.AppSettings [RenderBodyContentOnlyKey] ?? "false")) {
1135 for (Control c = this.Form; c != null; c = c.Parent) {
1136 HtmlGenericControl ch = (c as HtmlGenericControl);
1137 if (ch != null && ch.TagName == "body") {
1138 ch.RenderChildren (writer);
1144 base.Render (writer);
1148 void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1151 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
1152 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
1154 writer.WriteLine ();
1156 ClientScriptManager.WriteBeginScriptBlock (writer);
1159 RenderClientScriptFormDeclaration (writer, formUniqueID);
1162 writer.WriteLine (WebFormScriptReference + "._form = " + theForm + ";");
1163 writer.WriteLine (WebFormScriptReference + ".__doPostBack = function (eventTarget, eventArgument) {");
1164 writer.WriteLine ("\tif(" + theForm + ".onsubmit && " + theForm + ".onsubmit() == false) return;");
1166 writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
1167 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1169 writer.WriteLine ("\t" + theForm + "." + postEventSourceID + ".value = eventTarget;");
1170 writer.WriteLine ("\t" + theForm + "." + postEventArgumentID + ".value = eventArgument;");
1171 writer.WriteLine ("\t" + theForm + ".submit();");
1172 writer.WriteLine ("}");
1173 ClientScriptManager.WriteEndScriptBlock (writer);
1176 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1178 if (formScriptDeclarationRendered)
1182 if (PageAdapter != null) {
1183 writer.WriteLine ("\tvar {0} = {1};\n", theForm, PageAdapter.GetPostBackFormReference(formUniqueID));
1187 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1188 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1191 // TODO implement callback on portlet
1192 string serverUrl = Request.RawUrl;
1193 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1194 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1195 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1197 formScriptDeclarationRendered = true;
1200 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1203 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1205 renderingForm = true;
1206 writer.WriteLine ();
1209 if (requiresFormScriptDeclaration || (scriptManager != null && scriptManager.ScriptsPresent) || PageAdapter != null) {
1210 ClientScriptManager.WriteBeginScriptBlock (writer);
1211 RenderClientScriptFormDeclaration (writer, formUniqueID);
1212 ClientScriptManager.WriteEndScriptBlock (writer);
1216 if (handleViewState)
1218 if (getFacesContext () != null) {
1219 javax.faces.application.ViewHandler viewHandler = getFacesContext ().getApplication ().getViewHandler ();
1220 javax.faces.context.ResponseWriter oldFacesWriter = SetupResponseWriter (writer);
1222 viewHandler.writeState (getFacesContext ());
1225 getFacesContext ().setResponseWriter (oldFacesWriter);
1229 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1231 scriptManager.WriteHiddenFields (writer);
1232 if (requiresPostBackScript) {
1233 RenderPostBackScript (writer, formUniqueID);
1234 postBackScriptRendered = true;
1237 scriptManager.WriteWebFormClientScript (writer);
1239 scriptManager.WriteClientScriptBlocks (writer);
1242 internal IStateFormatter GetFormatter ()
1244 return new ObjectStateFormatter (this);
1247 internal string GetSavedViewState ()
1249 return _savedViewState;
1252 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1255 scriptManager.SaveEventValidationState ();
1256 scriptManager.WriteExpandoAttributes (writer);
1258 scriptManager.WriteHiddenFields (writer);
1259 if (!postBackScriptRendered && requiresPostBackScript)
1260 RenderPostBackScript (writer, formUniqueID);
1262 scriptManager.WriteWebFormClientScript (writer);
1265 scriptManager.WriteArrayDeclares (writer);
1266 scriptManager.WriteStartupScriptBlocks (writer);
1267 renderingForm = false;
1268 postBackScriptRendered = false;
1271 void ProcessPostData (NameValueCollection data, bool second)
1273 NameValueCollection requestValues = _requestValueCollection == null ?
1274 new NameValueCollection () :
1275 _requestValueCollection;
1277 if (data != null && data.Count > 0) {
1278 Hashtable used = new Hashtable ();
1279 foreach (string id in data.AllKeys) {
1280 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID || id == ClientScriptManager.EventStateFieldName)
1283 if (used.ContainsKey (id))
1288 Control ctrl = FindControl (id, true);
1290 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1291 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1295 formPostedRequiresRaiseEvent = pbeh;
1299 if (pbdh.LoadPostData (id, requestValues) == true) {
1300 if (requiresPostDataChanged == null)
1301 requiresPostDataChanged = new ArrayList ();
1302 requiresPostDataChanged.Add (pbdh);
1305 if (_requiresPostBackCopy != null)
1306 _requiresPostBackCopy.Remove (id);
1308 } else if (!second) {
1309 if (secondPostData == null)
1310 secondPostData = new NameValueCollection ();
1311 secondPostData.Add (id, data [id]);
1316 ArrayList list1 = null;
1317 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1318 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1319 foreach (string id in handlers) {
1320 IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
1322 _requiresPostBackCopy.Remove (id);
1323 if (pbdh.LoadPostData (id, requestValues)) {
1324 if (requiresPostDataChanged == null)
1325 requiresPostDataChanged = new ArrayList ();
1327 requiresPostDataChanged.Add (pbdh);
1329 } else if (!second) {
1331 list1 = new ArrayList ();
1336 _requiresPostBackCopy = second ? null : list1;
1338 secondPostData = null;
1341 [EditorBrowsable (EditorBrowsableState.Never)]
1343 public virtual void ProcessRequest (HttpContext context)
1345 public void ProcessRequest (HttpContext context)
1348 SetContext (context);
1350 bool wasException = false;
1351 IHttpHandler jsfHandler = getFacesContext () != null ? EnterThread () : null;
1354 if (clientTarget != null)
1355 Request.ClientTarget = clientTarget;
1357 WireupAutomaticEvents ();
1358 //-- Control execution lifecycle in the docs
1360 // Save culture information because it can be modified in FrameworkInitialize()
1361 _appCulture = Thread.CurrentThread.CurrentCulture;
1362 _appUICulture = Thread.CurrentThread.CurrentUICulture;
1363 FrameworkInitialize ();
1364 context.ErrorPage = _errorPage;
1367 InternalProcessRequest ();
1369 } catch (Exception ex) {
1370 wasException = true;
1371 HandleException (ex);
1373 } catch (ThreadAbortException taex) {
1374 if (FlagEnd.Value == taex.ExceptionState)
1375 Thread.ResetAbort ();
1378 } catch (Exception e) {
1379 ProcessException (e);
1383 if (getFacesContext () != null)
1384 ExitThread (jsfHandler);
1385 else if (!wasException)
1391 void ProcessException (Exception e) {
1392 // We want to remove that error, as we're rethrowing to stop
1393 // further processing.
1394 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1395 _context.AddError (e); // OnError might access LastError
1396 OnError (EventArgs.Empty);
1397 if (_context.HasError (e)) {
1398 _context.ClearError (e);
1400 vmw.common.TypeUtils.Throw (e);
1402 throw new HttpUnhandledException (null, e);
1407 void ProcessUnload () {
1410 UnloadRecursive (true);
1413 if (getFacesContext () != null) {
1414 if(IsCrossPagePostBack)
1415 _context.Items [CrossPagePostBack] = this;
1418 if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
1419 Thread.CurrentThread.CurrentCulture = _appCulture;
1421 if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
1422 Thread.CurrentThread.CurrentUICulture = _appUICulture;
1425 _appUICulture = null;
1429 delegate void ProcessRequestDelegate (HttpContext context);
1431 sealed class DummyAsyncResult : IAsyncResult
1433 readonly object state;
1434 readonly WaitHandle asyncWaitHandle;
1435 readonly bool completedSynchronously;
1436 readonly bool isCompleted;
1438 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1440 this.isCompleted = isCompleted;
1441 this.completedSynchronously = completedSynchronously;
1444 asyncWaitHandle = new ManualResetEvent (true);
1447 asyncWaitHandle = new ManualResetEvent (false);
1451 #region IAsyncResult Members
1453 public object AsyncState {
1454 get { return state; }
1457 public WaitHandle AsyncWaitHandle {
1458 get { return asyncWaitHandle; }
1461 public bool CompletedSynchronously {
1462 get { return completedSynchronously; }
1465 public bool IsCompleted {
1466 get { return isCompleted; }
1472 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1474 ProcessRequest (context);
1475 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1477 if (callback != null) {
1478 callback (asyncResult);
1484 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1489 void InternalProcessRequest ()
1492 if (PageAdapter != null) {
1493 _requestValueCollection = PageAdapter.DeterminePostBackMode();
1497 _requestValueCollection = this.DeterminePostBackMode();
1501 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1502 if (_requestValueCollection != null) {
1503 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1504 _doLoadPreviousPage = true;
1506 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1507 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1508 //isPostBack = !isCallback;
1512 string lastFocus = _requestValueCollection [LastFocusID];
1513 if (!String.IsNullOrEmpty (lastFocus))
1514 _focusedControlID = UniqueID2ClientID (lastFocus);
1517 if (!isCrossPagePostBack) {
1518 if (_context.PreviousHandler is Page)
1519 previousPage = (Page) _context.PreviousHandler;
1522 Trace.Write ("aspx.page", "Begin PreInit");
1523 OnPreInit (EventArgs.Empty);
1524 Trace.Write ("aspx.page", "End PreInit");
1529 Trace.Write ("aspx.page", "Begin Init");
1530 InitRecursive (null);
1531 Trace.Write ("aspx.page", "End Init");
1534 Trace.Write ("aspx.page", "Begin InitComplete");
1535 OnInitComplete (EventArgs.Empty);
1536 Trace.Write ("aspx.page", "End InitComplete");
1539 renderingForm = false;
1542 if (getFacesContext () != null)
1543 if (IsPostBack || IsCallback)
1547 RestorePageState ();
1549 ProcessRaiseEvents ();
1550 if (ProcessLoadComplete ())
1553 if (getFacesContext () != null) {
1554 getFacesContext ().renderResponse ();
1561 void RestorePageState ()
1564 if (IsPostBack || IsCallback) {
1565 if (_requestValueCollection != null)
1566 scriptManager.RestoreEventValidationState (
1567 _requestValueCollection [ClientScriptManager.EventStateFieldName]);
1571 Trace.Write ("aspx.page", "Begin LoadViewState");
1572 LoadPageViewState ();
1573 Trace.Write ("aspx.page", "End LoadViewState");
1577 void ProcessPostData ()
1581 if (IsPostBack || IsCallback) {
1585 Trace.Write ("aspx.page", "Begin ProcessPostData");
1586 ProcessPostData (_requestValueCollection, false);
1587 Trace.Write ("aspx.page", "End ProcessPostData");
1593 if (IsPostBack || IsCallback) {
1597 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1598 ProcessPostData (secondPostData, true);
1599 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1606 Trace.Write ("aspx.page", "Begin PreLoad");
1607 OnPreLoad (EventArgs.Empty);
1608 Trace.Write ("aspx.page", "End PreLoad");
1611 Trace.Write ("aspx.page", "Begin Load");
1613 Trace.Write ("aspx.page", "End Load");
1616 void ProcessRaiseEvents ()
1620 if (IsPostBack || IsCallback) {
1624 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1625 RaiseChangedEvents ();
1626 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1627 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1628 RaisePostBackEvents ();
1629 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1633 bool ProcessLoadComplete ()
1637 Trace.Write ("aspx.page", "Begin LoadComplete");
1638 OnLoadComplete (EventArgs.Empty);
1639 Trace.Write ("aspx.page", "End LoadComplete");
1641 if (IsCrossPagePostBack)
1646 if (getFacesContext () != null) {
1647 _callbackTarget = GetCallbackTarget ();
1648 ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError);
1652 string result = ProcessCallbackData ();
1653 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1654 callbackOutput.Write (result);
1655 callbackOutput.Flush ();
1660 Trace.Write ("aspx.page", "Begin PreRender");
1661 PreRenderRecursiveInternal ();
1662 Trace.Write ("aspx.page", "End PreRender");
1665 ExecuteRegisteredAsyncTasks ();
1667 Trace.Write ("aspx.page", "Begin PreRenderComplete");
1668 OnPreRenderComplete (EventArgs.Empty);
1669 Trace.Write ("aspx.page", "End PreRenderComplete");
1672 Trace.Write ("aspx.page", "Begin SaveViewState");
1673 SavePageViewState ();
1674 Trace.Write ("aspx.page", "End SaveViewState");
1677 Trace.Write ("aspx.page", "Begin SaveStateComplete");
1678 OnSaveStateComplete (EventArgs.Empty);
1679 Trace.Write ("aspx.page", "End SaveStateComplete");
1684 internal void RenderPage ()
1687 scriptManager.ResetEventValidationState ();
1691 Trace.Write ("aspx.page", "Begin Render");
1692 HtmlTextWriter output = CreateHtmlTextWriter (Response.Output);
1693 RenderControl (output);
1694 Trace.Write ("aspx.page", "End Render");
1697 internal void SetContext (HttpContext context)
1701 _application = context.Application;
1702 _response = context.Response;
1703 _request = context.Request;
1704 _cache = context.Cache;
1709 TraceManager traceManager = HttpRuntime.TraceManager;
1711 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1716 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1719 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1720 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1721 Trace.Render (output);
1725 void RaisePostBackEvents ()
1728 Control targetControl;
1730 if (requiresRaiseEvent != null) {
1731 RaisePostBackEvent (requiresRaiseEvent, null);
1735 if (formPostedRequiresRaiseEvent != null) {
1736 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1740 NameValueCollection postdata = _requestValueCollection;
1741 if (postdata == null)
1744 string eventTarget = postdata [postEventSourceID];
1745 if (eventTarget == null || eventTarget.Length == 0) {
1746 if (formPostedRequiresRaiseEvent != null)
1747 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1754 targetControl = FindControl (eventTarget, true);
1755 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1757 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1763 string eventArgument = postdata [postEventArgumentID];
1764 RaisePostBackEvent (target, eventArgument);
1767 internal void RaiseChangedEvents ()
1769 if (requiresPostDataChanged == null)
1772 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1773 ipdh.RaisePostDataChangedEvent ();
1775 requiresPostDataChanged = null;
1778 [EditorBrowsable (EditorBrowsableState.Advanced)]
1779 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1781 sourceControl.RaisePostBackEvent (eventArgument);
1787 [EditorBrowsable (EditorBrowsableState.Advanced)]
1788 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1790 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1796 [EditorBrowsable (EditorBrowsableState.Advanced)]
1797 public virtual void RegisterClientScriptBlock (string key, string script)
1799 scriptManager.RegisterClientScriptBlock (key, script);
1805 [EditorBrowsable (EditorBrowsableState.Advanced)]
1806 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1808 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1811 [MonoTODO("Not implemented, Used in HtmlForm")]
1812 internal void RegisterClientScriptFile (string a, string b, string c)
1814 throw new NotImplementedException ();
1820 [EditorBrowsable (EditorBrowsableState.Advanced)]
1821 public void RegisterOnSubmitStatement (string key, string script)
1823 scriptManager.RegisterOnSubmitStatement (key, script);
1826 internal string GetSubmitStatements ()
1828 return scriptManager.WriteSubmitStatements ();
1831 [EditorBrowsable (EditorBrowsableState.Advanced)]
1832 public void RegisterRequiresPostBack (Control control)
1835 if (!(control is IPostBackDataHandler))
1836 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1839 if (_requiresPostBack == null)
1840 _requiresPostBack = new ArrayList ();
1842 if (_requiresPostBack.Contains (control.UniqueID))
1845 _requiresPostBack.Add (control.UniqueID);
1848 [EditorBrowsable (EditorBrowsableState.Advanced)]
1849 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1851 requiresRaiseEvent = control;
1857 [EditorBrowsable (EditorBrowsableState.Advanced)]
1858 public virtual void RegisterStartupScript (string key, string script)
1860 scriptManager.RegisterStartupScript (key, script);
1863 [EditorBrowsable (EditorBrowsableState.Advanced)]
1864 public void RegisterViewStateHandler ()
1866 handleViewState = true;
1869 [EditorBrowsable (EditorBrowsableState.Advanced)]
1870 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1872 PageStatePersister persister = this.PageStatePersister;
1873 if (persister == null)
1875 Pair pair = viewState as Pair;
1877 persister.ViewState = pair.First;
1878 persister.ControlState = pair.Second;
1880 persister.ViewState = viewState;
1884 internal string RawViewState {
1886 NameValueCollection postdata = _requestValueCollection;
1888 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1891 if (view_state == "")
1896 set { _savedViewState = value; }
1904 PageStatePersister PageStatePersister {
1907 if (page_state_persister == null && PageAdapter != null)
1908 page_state_persister = PageAdapter.GetStatePersister();
1910 if (page_state_persister == null)
1911 page_state_persister = new HiddenFieldPageStatePersister (this);
1912 return page_state_persister;
1916 [EditorBrowsable (EditorBrowsableState.Advanced)]
1917 protected virtual object LoadPageStateFromPersistenceMedium ()
1919 PageStatePersister persister = this.PageStatePersister;
1920 if (persister == null)
1923 return new Pair (persister.ViewState, persister.ControlState);
1926 internal void LoadPageViewState ()
1928 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1929 if (sState != null) {
1932 || isCrossPagePostBack
1936 LoadPageControlState (sState.Second);
1938 Pair vsr = sState.First as Pair;
1940 LoadViewStateRecursive (vsr.First);
1941 _requiresPostBackCopy = vsr.Second as ArrayList;
1947 internal void SavePageViewState ()
1949 if (!handleViewState)
1953 object controlState = SavePageControlState ();
1957 object viewState = null;
1959 if (EnableViewState)
1960 viewState = SaveViewStateRecursive ();
1962 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1963 if (viewState != null || reqPostback != null)
1964 vsr = new Pair (viewState, reqPostback);
1966 Pair pair = new Pair ();
1969 pair.Second = controlState;
1973 if (pair.First == null && pair.Second == null)
1974 SavePageStateToPersistenceMedium (null);
1976 SavePageStateToPersistenceMedium (pair);
1980 public virtual void Validate ()
1982 is_validated = true;
1983 ValidateCollection (_validators);
1987 internal bool AreValidatorsUplevel ()
1989 return AreValidatorsUplevel (String.Empty);
1992 internal bool AreValidatorsUplevel (string valGroup)
1994 internal virtual bool AreValidatorsUplevel ()
1997 bool uplevel = false;
1999 foreach (IValidator v in Validators) {
2000 BaseValidator bv = v as BaseValidator;
2001 if (bv == null) continue;
2004 if (valGroup != bv.ValidationGroup)
2007 if (bv.GetRenderUplevel()) {
2016 bool ValidateCollection (ValidatorCollection validators)
2018 if (validators == null || validators.Count == 0)
2021 bool all_valid = true;
2022 foreach (IValidator v in validators){
2024 if (v.IsValid == false)
2031 [EditorBrowsable (EditorBrowsableState.Advanced)]
2032 public virtual void VerifyRenderingInServerForm (Control control)
2034 if (Context == null)
2041 throw new HttpException ("Control '" +
2044 control.GetType ().Name +
2045 "' must be placed inside a form tag with runat=server.");
2048 protected override void FrameworkInitialize ()
2050 base.FrameworkInitialize ();
2052 InitializeStyleSheet ();
2063 ClientScriptManager ClientScript {
2064 get { return scriptManager; }
2068 internal static readonly object InitCompleteEvent = new object ();
2069 internal static readonly object LoadCompleteEvent = new object ();
2070 internal static readonly object PreInitEvent = new object ();
2071 internal static readonly object PreLoadEvent = new object ();
2072 internal static readonly object PreRenderCompleteEvent = new object ();
2073 internal static readonly object SaveStateCompleteEvent = new object ();
2075 const int initcomplete_mask = 1;
2076 const int loadcomplete_mask = 1 << 1;
2077 const int preinit_mask = 1 << 2;
2078 const int preload_mask = 1 << 3;
2079 const int prerendercomplete_mask = 1 << 4;
2080 const int savestatecomplete_mask = 1 << 5;
2082 [EditorBrowsable (EditorBrowsableState.Advanced)]
2083 public event EventHandler InitComplete {
2085 event_mask |= initcomplete_mask;
2086 Events.AddHandler (InitCompleteEvent, value);
2088 remove { Events.RemoveHandler (InitCompleteEvent, value); }
2091 [EditorBrowsable (EditorBrowsableState.Advanced)]
2092 public event EventHandler LoadComplete {
2094 event_mask |= loadcomplete_mask;
2095 Events.AddHandler (LoadCompleteEvent, value);
2097 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
2100 public event EventHandler PreInit {
2102 event_mask |= preinit_mask;
2103 Events.AddHandler (PreInitEvent, value);
2105 remove { Events.RemoveHandler (PreInitEvent, value); }
2108 [EditorBrowsable (EditorBrowsableState.Advanced)]
2109 public event EventHandler PreLoad {
2111 event_mask |= preload_mask;
2112 Events.AddHandler (PreLoadEvent, value);
2114 remove { Events.RemoveHandler (PreLoadEvent, value); }
2117 [EditorBrowsable (EditorBrowsableState.Advanced)]
2118 public event EventHandler PreRenderComplete {
2120 event_mask |= prerendercomplete_mask;
2121 Events.AddHandler (PreRenderCompleteEvent, value);
2123 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
2126 [EditorBrowsable (EditorBrowsableState.Advanced)]
2127 public event EventHandler SaveStateComplete {
2129 event_mask |= savestatecomplete_mask;
2130 Events.AddHandler (SaveStateCompleteEvent, value);
2132 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
2135 protected virtual void OnInitComplete (EventArgs e)
2137 if ((event_mask & initcomplete_mask) != 0) {
2138 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
2139 if (eh != null) eh (this, e);
2143 protected virtual void OnLoadComplete (EventArgs e)
2145 if ((event_mask & loadcomplete_mask) != 0) {
2146 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
2147 if (eh != null) eh (this, e);
2151 protected virtual void OnPreInit (EventArgs e)
2153 if ((event_mask & preinit_mask) != 0) {
2154 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
2155 if (eh != null) eh (this, e);
2159 protected virtual void OnPreLoad (EventArgs e)
2161 if ((event_mask & preload_mask) != 0) {
2162 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
2163 if (eh != null) eh (this, e);
2167 protected virtual void OnPreRenderComplete (EventArgs e)
2169 if ((event_mask & prerendercomplete_mask) != 0) {
2170 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
2171 if (eh != null) eh (this, e);
2176 if (!Form.DetermineRenderUplevel ())
2179 string defaultButtonId = Form.DefaultButton;
2180 /* figure out if we have some control we're going to focus */
2181 if (String.IsNullOrEmpty (_focusedControlID)) {
2182 _focusedControlID = Form.DefaultFocus;
2183 if (String.IsNullOrEmpty (_focusedControlID))
2184 _focusedControlID = defaultButtonId;
2187 if (!String.IsNullOrEmpty (_focusedControlID)) {
2188 ClientScript.RegisterWebFormClientScript ();
2190 ClientScript.RegisterStartupScript (
2192 "HtmlForm-DefaultButton-StartupScript",
2193 "\n" + WebFormScriptReference + ".WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
2196 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
2197 ClientScript.RegisterWebFormClientScript ();
2199 ClientScript.RegisterOnSubmitStatement (
2201 "HtmlForm-SubmitDisabledControls-SubmitStatement",
2202 WebFormScriptReference + ".WebForm_ReEnableControls();");
2206 internal void RegisterEnabledControl (Control control)
2208 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
2210 _hasEnabledControlArray = true;
2211 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
2214 protected virtual void OnSaveStateComplete (EventArgs e)
2216 if ((event_mask & savestatecomplete_mask) != 0) {
2217 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
2218 if (eh != null) eh (this, e);
2222 public HtmlForm Form {
2223 get { return _form; }
2226 internal void RegisterForm (HtmlForm form)
2231 public string ClientQueryString {
2232 get { return Request.UrlComponents.Query; }
2235 [BrowsableAttribute (false)]
2236 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2237 public Page PreviousPage {
2239 if (_doLoadPreviousPage) {
2240 _doLoadPreviousPage = false;
2241 LoadPreviousPageReference ();
2243 return previousPage;
2248 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2249 [BrowsableAttribute (false)]
2250 public bool IsCallback {
2251 get { return isCallback; }
2254 [BrowsableAttribute (false)]
2255 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2256 public bool IsCrossPagePostBack {
2257 get { return isCrossPagePostBack; }
2260 public new virtual char IdSeparator {
2262 //TODO: why override?
2263 return base.IdSeparator;
2267 string ProcessCallbackData ()
2269 ICallbackEventHandler target = GetCallbackTarget ();
2270 string callbackEventError = String.Empty;
2271 ProcessRaiseCallbackEvent (target, ref callbackEventError);
2272 return ProcessGetCallbackResult (target, callbackEventError);
2275 ICallbackEventHandler GetCallbackTarget ()
2277 string callbackTarget = _requestValueCollection [CallbackSourceID];
2278 if (callbackTarget == null || callbackTarget.Length == 0)
2279 throw new HttpException ("Callback target not provided.");
2281 Control targetControl = FindControl (callbackTarget, true);
2282 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2284 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2288 void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError)
2290 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2293 target.RaiseCallbackEvent (callbackArgument);
2294 } catch (Exception ex) {
2295 callbackEventError = String.Concat ("e", HttpRuntime.IsDebuggingEnabled ? ex.ToString () : ex.Message);
2300 string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError)
2302 string callBackResult;
2304 callBackResult = target.GetCallbackResult ();
2305 } catch (Exception ex) {
2306 return String.Concat ("e", HttpRuntime.IsDebuggingEnabled ? ex.ToString () : ex.Message);
2309 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2310 return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
2311 eventValidation + callBackResult;
2314 [BrowsableAttribute (false)]
2315 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2316 public HtmlHead Header {
2317 get { return htmlHeader; }
2320 internal void SetHeader (HtmlHead header)
2322 htmlHeader = header;
2323 if (_title != null) {
2324 htmlHeader.Title = _title;
2329 protected bool AsyncMode {
2330 get { return asyncMode; }
2331 set { asyncMode = value; }
2334 public TimeSpan AsyncTimeout {
2335 get { return asyncTimeout; }
2336 set { asyncTimeout = value; }
2339 public bool IsAsync {
2340 get { return AsyncMode; }
2343 protected internal virtual string UniqueFilePathSuffix {
2345 if (String.IsNullOrEmpty (uniqueFilePathSuffix))
2346 uniqueFilePathSuffix = "__ufps=" + AppRelativeVirtualPath.GetHashCode ().ToString ("x");
2347 return uniqueFilePathSuffix;
2351 [MonoTODO ("Actually use the value in code.")]
2352 public int MaxPageStateFieldLength {
2353 get { return maxPageStateFieldLength; }
2354 set { maxPageStateFieldLength = value; }
2357 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2359 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2362 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2365 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2368 if (IsPrerendered) {
2369 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
2372 if (beginHandler == null) {
2373 throw new ArgumentNullException ("beginHandler");
2376 if (endHandler == null) {
2377 throw new ArgumentNullException ("endHandler");
2380 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2383 List<PageAsyncTask> ParallelTasks {
2385 if (parallelTasks == null)
2386 parallelTasks = new List<PageAsyncTask>();
2387 return parallelTasks;
2391 List<PageAsyncTask> SerialTasks {
2393 if (serialTasks == null)
2394 serialTasks = new List<PageAsyncTask> ();
2399 public void RegisterAsyncTask (PageAsyncTask task)
2402 throw new ArgumentNullException ("task");
2404 if (task.ExecuteInParallel)
2405 ParallelTasks.Add (task);
2407 SerialTasks.Add (task);
2410 public void ExecuteRegisteredAsyncTasks ()
2412 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2413 (serialTasks == null || serialTasks.Count == 0)){
2417 if (parallelTasks != null) {
2418 DateTime startExecution = DateTime.Now;
2419 List<PageAsyncTask> localParallelTasks = parallelTasks;
2420 parallelTasks = null; // Shouldn't execute tasks twice
2421 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2422 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2423 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2424 if (result.CompletedSynchronously)
2425 parallelTask.EndHandler (result);
2427 asyncResults.Add (result);
2430 if (asyncResults.Count > 0) {
2432 TimeSpan timeout = AsyncTimeout;
2433 long t1 = DateTime.Now.Ticks;
2434 bool signalled = true;
2435 for (int i = 0; i < asyncResults.Count; i++) {
2436 if (asyncResults [i].IsCompleted)
2440 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2443 long t2 = DateTime.Now.Ticks;
2444 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2445 if (timeout.Ticks <= 0)
2448 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2451 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2453 for (i = 0; i < asyncResults.Count; i++) {
2454 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2457 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2458 if (!allSignalled) {
2459 for (i = 0; i < asyncResults.Count; i++) {
2460 if (!asyncResults [i].IsCompleted) {
2461 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2467 DateTime endWait = DateTime.Now;
2468 TimeSpan elapsed = endWait - startExecution;
2469 if (elapsed <= AsyncTimeout)
2470 AsyncTimeout -= elapsed;
2472 AsyncTimeout = TimeSpan.FromTicks(0);
2475 if (serialTasks != null) {
2476 List<PageAsyncTask> localSerialTasks = serialTasks;
2477 serialTasks = null; // Shouldn't execute tasks twice
2478 foreach (PageAsyncTask serialTask in localSerialTasks) {
2479 DateTime startExecution = DateTime.Now;
2481 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2482 if (result.CompletedSynchronously)
2483 serialTask.EndHandler (result);
2485 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2486 if (!done && !result.IsCompleted) {
2487 serialTask.TimeoutHandler (result);
2490 DateTime endWait = DateTime.Now;
2491 TimeSpan elapsed = endWait - startExecution;
2492 if (elapsed <= AsyncTimeout)
2493 AsyncTimeout -= elapsed;
2495 AsyncTimeout = TimeSpan.FromTicks (0);
2498 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2501 void EndAsyncTaskCallback (IAsyncResult result)
2503 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2504 task.EndHandler (result);
2507 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2509 Type htmlTextWriterType = typeof (HtmlTextWriter);
2511 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2512 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2515 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2516 if (constructor == null) {
2517 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2520 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2523 public ViewStateEncryptionMode ViewStateEncryptionMode {
2524 get { return viewStateEncryptionMode; }
2525 set { viewStateEncryptionMode = value; }
2528 public void RegisterRequiresViewStateEncryption ()
2530 controlRegisteredForViewStateEncryption = true;
2533 static byte [] AES_IV = null;
2534 static byte [] TripleDES_IV = null;
2535 static object locker = new object ();
2536 static bool isEncryptionInitialized = false;
2538 static void InitializeEncryption ()
2540 if (isEncryptionInitialized)
2544 if (isEncryptionInitialized)
2547 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2548 AES_IV = new byte [16];
2549 TripleDES_IV = new byte [8];
2552 for (i = 0; i < AES_IV.Length; i++) {
2553 AES_IV [i] = (byte) iv_string [i];
2556 for (i = 0; i < TripleDES_IV.Length; i++) {
2557 TripleDES_IV [i] = (byte) iv_string [i];
2560 isEncryptionInitialized = true;
2564 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2566 ICryptoTransform transform = null;
2567 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2568 byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
2570 switch (config.Validation) {
2571 case MachineKeyValidation.SHA1:
2572 transform = SHA1.Create ();
2575 case MachineKeyValidation.MD5:
2576 transform = MD5.Create ();
2579 case MachineKeyValidation.AES:
2580 InitializeEncryption ();
2581 if (cryptoStreamMode == CryptoStreamMode.Read){
2582 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2584 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2588 case MachineKeyValidation.TripleDES:
2589 InitializeEncryption ();
2590 if (cryptoStreamMode == CryptoStreamMode.Read){
2591 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2593 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2601 internal bool NeedViewStateEncryption {
2603 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2604 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2605 controlRegisteredForViewStateEncryption));
2610 void ApplyMasterPage ()
2612 if (masterPageFile != null && masterPageFile.Length > 0) {
2613 ArrayList appliedMasterPageFiles = new ArrayList ();
2615 if (Master != null) {
2616 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2620 Controls.Add (Master);
2625 [DefaultValueAttribute ("")]
2626 public virtual string MasterPageFile {
2627 get { return masterPageFile; }
2629 masterPageFile = value;
2634 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2635 [BrowsableAttribute (false)]
2636 public MasterPage Master {
2638 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2641 if (masterPage == null)
2642 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2648 public void SetFocus (string clientID)
2650 if (String.IsNullOrEmpty (clientID))
2651 throw new ArgumentNullException ("control");
2654 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2657 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2659 _focusedControlID = clientID;
2662 public void SetFocus (Control control)
2664 if (control == null)
2665 throw new ArgumentNullException ("control");
2667 SetFocus (control.ClientID);
2670 [EditorBrowsable (EditorBrowsableState.Advanced)]
2671 public void RegisterRequiresControlState (Control control)
2673 if (control == null)
2674 throw new ArgumentNullException ("control");
2676 if (RequiresControlState (control))
2679 if (requireStateControls == null)
2680 requireStateControls = new List <Control> ();
2681 requireStateControls.Add (control);
2682 int n = requireStateControls.Count - 1;
2684 if (_savedControlState == null || n >= _savedControlState.Length)
2687 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2688 if (parent.IsChildControlStateCleared)
2691 object state = _savedControlState [n];
2693 control.LoadControlState (state);
2696 public bool RequiresControlState (Control control)
2698 if (requireStateControls == null)
2700 return requireStateControls.Contains (control);
2703 [EditorBrowsable (EditorBrowsableState.Advanced)]
2704 public void UnregisterRequiresControlState (Control control)
2706 if (requireStateControls != null)
2707 requireStateControls.Remove (control);
2710 public ValidatorCollection GetValidators (string validationGroup)
2712 if (validationGroup == String.Empty)
2713 validationGroup = null;
2715 ValidatorCollection col = new ValidatorCollection ();
2716 if (_validators == null)
2719 foreach (IValidator v in _validators)
2720 if (BelongsToGroup(v, validationGroup))
2726 bool BelongsToGroup(IValidator v, string validationGroup)
2728 BaseValidator validator = v as BaseValidator;
2729 if (validationGroup == null)
2730 return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
2732 return validator != null && validator.ValidationGroup == validationGroup;
2735 public virtual void Validate (string validationGroup)
2737 is_validated = true;
2738 ValidateCollection (GetValidators (validationGroup));
2741 object SavePageControlState ()
2743 int count = requireStateControls == null ? 0 : requireStateControls.Count;
2748 object[] controlStates = new object [count];
2749 object[] adapterState = new object [count];
2751 ControlAdapter adapter;
2752 bool allNull = true;
2753 TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
2755 for (int n = 0; n < count; n++) {
2756 control = requireStateControls [n];
2757 state = controlStates [n] = control.SaveControlState ();
2762 trace.SaveControlState (control, state);
2764 adapter = control.Adapter;
2765 if (adapter != null) {
2766 adapterState [n] = adapter.SaveAdapterControlState ();
2767 if (adapterState [n] != null) allNull = false;
2774 return new Pair (controlStates, adapterState);
2777 void LoadPageControlState (object data)
2779 _savedControlState = null;
2780 if (data == null) return;
2781 Pair statePair = (Pair)data;
2782 _savedControlState = (object[]) statePair.First;
2783 object[] adapterState = (object[]) statePair.Second;
2785 if (requireStateControls == null) return;
2787 int min = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2788 for (int n=0; n < min; n++) {
2789 Control ctl = (Control) requireStateControls [n];
2790 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2791 if (ctl.Adapter != null)
2792 ctl.Adapter.LoadAdapterControlState (adapterState != null ? adapterState [n] : null);
2796 void LoadPreviousPageReference ()
2798 if (_requestValueCollection != null) {
2799 string prevPage = _requestValueCollection [PreviousPageID];
2800 if (prevPage != null) {
2802 if (getFacesContext () != null) {
2803 IHttpHandler handler = Context.ApplicationInstance.GetHandler (Context, prevPage);
2804 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2805 if (_context.Items.Contains (CrossPagePostBack)) {
2806 previousPage = (Page) _context.Items [CrossPagePostBack];
2807 _context.Items.Remove (CrossPagePostBack);
2812 IHttpHandler handler;
2814 handler = BuildManager.CreateInstanceFromVirtualPath (prevPage, typeof (IHttpHandler)) as IHttpHandler;
2816 handler = PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2818 previousPage = (Page) handler;
2819 previousPage.isCrossPagePostBack = true;
2820 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2827 Hashtable contentTemplates;
2828 [EditorBrowsable (EditorBrowsableState.Never)]
2829 protected internal void AddContentTemplate (string templateName, ITemplate template)
2831 if (contentTemplates == null)
2832 contentTemplates = new Hashtable ();
2833 contentTemplates [templateName] = template;
2836 PageTheme _pageTheme;
2837 internal PageTheme PageTheme {
2838 get { return _pageTheme; }
2841 PageTheme _styleSheetPageTheme;
2842 internal PageTheme StyleSheetPageTheme {
2843 get { return _styleSheetPageTheme; }
2848 internal void PushDataItemContext (object o) {
2849 if (dataItemCtx == null)
2850 dataItemCtx = new Stack ();
2852 dataItemCtx.Push (o);
2855 internal void PopDataItemContext () {
2856 if (dataItemCtx == null)
2857 throw new InvalidOperationException ();
2862 public object GetDataItem() {
2863 if (dataItemCtx == null || dataItemCtx.Count == 0)
2864 throw new InvalidOperationException ("No data item");
2866 return dataItemCtx.Peek ();
2869 protected internal override void OnInit (EventArgs e)
2873 ArrayList themes = new ArrayList();
2875 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2876 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2878 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2879 themes.AddRange (PageTheme.GetStyleSheets ());
2881 if (themes.Count > 0 && Header == null)
2882 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2884 foreach (string lss in themes) {
2885 HtmlLink hl = new HtmlLink ();
2887 hl.Attributes["type"] = "text/css";
2888 hl.Attributes["rel"] = "stylesheet";
2889 Header.Controls.Add (hl);
2896 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2897 protected object GetWrappedFileDependencies (string [] list)
2902 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2903 protected virtual void InitializeCulture ()
2907 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2908 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)