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)
9 // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
10 // Copyright (C) 2003,2005 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.ComponentModel;
36 using System.ComponentModel.Design;
37 using System.ComponentModel.Design.Serialization;
38 using System.Globalization;
40 using System.Security.Cryptography;
41 using System.Security.Permissions;
42 using System.Security.Principal;
44 using System.Threading;
46 using System.Web.Caching;
47 using System.Web.Configuration;
48 using System.Web.SessionState;
49 using System.Web.Util;
50 using System.Web.UI.HtmlControls;
51 using System.Web.UI.WebControls;
53 using System.Web.UI.Adapters;
54 using System.Collections.Generic;
55 using System.Reflection;
58 namespace System.Web.UI
61 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
62 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
64 [RootDesignerSerializer ("Microsoft.VSDesigner.WebForms.RootCodeDomSerializer, " + Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design, true)]
66 [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
69 [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
71 [Designer ("Microsoft.VSDesigner.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VSDesigner, typeof (IRootDesigner))]
73 public partial class Page : TemplateControl, IHttpHandler
75 static string machineKeyConfigPath = "system.web/machineKey";
77 private PageLifeCycle _lifeCycle = PageLifeCycle.Unknown;
78 private bool _eventValidation = true;
79 private object [] _savedControlState;
80 private bool _doLoadPreviousPage;
81 string _focusedControlID;
82 bool _hasEnabledControlArray;
84 private bool _viewState = true;
85 private bool _viewStateMac;
86 private string _errorPage;
87 private bool is_validated;
88 private bool _smartNavigation;
89 private int _transactionMode;
90 private ValidatorCollection _validators;
91 private bool renderingForm;
92 private string _savedViewState;
93 private ArrayList _requiresPostBack;
94 private ArrayList _requiresPostBackCopy;
95 private ArrayList requiresPostDataChanged;
96 private IPostBackEventHandler requiresRaiseEvent;
97 private NameValueCollection secondPostData;
98 private bool requiresPostBackScript;
99 private bool postBackScriptRendered;
100 bool handleViewState;
101 string viewStateUserKey;
102 NameValueCollection _requestValueCollection;
104 ClientScriptManager scriptManager;
105 bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
106 PageStatePersister page_state_persister;
108 // The initial context
109 private HttpContext _context;
111 // cached from the initial context
112 HttpApplicationState _application;
113 HttpResponse _response;
114 HttpRequest _request;
117 HttpSessionState _session;
119 [EditorBrowsable (EditorBrowsableState.Never)]
125 const string postEventArgumentID = "__EVENTARGUMENT";
127 [EditorBrowsable (EditorBrowsableState.Never)]
133 const string postEventSourceID = "__EVENTTARGET";
136 const string ScrollPositionXID = "__SCROLLPOSITIONX";
137 const string ScrollPositionYID = "__SCROLLPOSITIONY";
138 const string EnabledControlArrayID = "__enabledControlArray";
142 internal const string LastFocusID = "__LASTFOCUS";
143 internal const string CallbackArgumentID = "__CALLBACKARGUMENT";
144 internal const string CallbackSourceID = "__CALLBACKTARGET";
145 internal const string PreviousPageID = "__PREVIOUSPAGE";
149 MasterPage masterPage;
150 string masterPageFile;
153 bool isCrossPagePostBack;
156 ArrayList requireStateControls;
161 string _styleSheetTheme;
164 bool _maintainScrollPositionOnPostBack;
166 private bool asyncMode = false;
167 private TimeSpan asyncTimeout;
168 private const double DefaultAsyncTimeout = 45.0;
169 private List<PageAsyncTask> parallelTasks;
170 private List<PageAsyncTask> serialTasks;
172 private ViewStateEncryptionMode viewStateEncryptionMode;
173 private bool controlRegisteredForViewStateEncryption = false;
179 scriptManager = new ClientScriptManager (this);
184 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
186 asyncTimeout = ps.AsyncTimeout;
187 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
189 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
190 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
199 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
201 public HttpApplicationState Application {
202 get { return _application; }
205 [EditorBrowsable (EditorBrowsableState.Never)]
206 protected bool AspCompatMode {
208 get { return false; }
210 set { throw new NotImplementedException (); }
213 [EditorBrowsable (EditorBrowsableState.Never)]
215 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
216 [BrowsableAttribute (false)]
218 get { return Response.BufferOutput; }
219 set { Response.BufferOutput = value; }
222 protected bool Buffer {
223 set { Response.BufferOutput = value; }
227 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
232 throw new HttpException ("Cache is not available.");
238 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
240 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
241 [Browsable (false), DefaultValue ("")]
242 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
243 public string ClientTarget {
244 get { return (clientTarget == null) ? "" : clientTarget; }
246 clientTarget = value;
252 [EditorBrowsable (EditorBrowsableState.Never)]
254 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
255 [BrowsableAttribute (false)]
256 public int CodePage {
257 get { return Response.ContentEncoding.CodePage; }
258 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
261 protected int CodePage {
262 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
266 [EditorBrowsable (EditorBrowsableState.Never)]
268 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
269 [BrowsableAttribute (false)]
270 public string ContentType {
271 get { return Response.ContentType; }
272 set { Response.ContentType = value; }
275 protected string ContentType {
276 set { Response.ContentType = value; }
280 protected override HttpContext Context {
282 if (_context == null)
283 return HttpContext.Current;
290 [EditorBrowsable (EditorBrowsableState.Advanced)]
291 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
292 [BrowsableAttribute (false)]
293 public string Culture {
294 get { return Thread.CurrentThread.CurrentCulture.Name; }
295 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
298 [EditorBrowsable (EditorBrowsableState.Never)]
299 protected string Culture {
300 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
305 public virtual bool EnableEventValidation {
306 get { return _eventValidation; }
308 if (_lifeCycle > PageLifeCycle.Init)
309 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
310 _eventValidation = value;
314 internal PageLifeCycle LifeCycle {
315 get { return _lifeCycle; }
320 public override bool EnableViewState {
321 get { return _viewState; }
322 set { _viewState = value; }
326 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
327 [BrowsableAttribute (false)]
329 [EditorBrowsable (EditorBrowsableState.Never)]
335 bool EnableViewStateMac {
336 get { return _viewStateMac; }
337 set { _viewStateMac = value; }
341 internal bool EnableViewStateMacInternal {
342 get { return _viewStateMac; }
343 set { _viewStateMac = value; }
347 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
348 [Browsable (false), DefaultValue ("")]
349 [WebSysDescription ("The URL of a page used for error redirection.")]
350 public string ErrorPage {
351 get { return _errorPage; }
353 HttpContext ctx = Context;
357 ctx.ErrorPage = value;
364 [EditorBrowsable (EditorBrowsableState.Never)]
365 protected ArrayList FileDependencies {
367 if (Response != null)
368 Response.AddFileDependencies (value);
374 [EditorBrowsable (EditorBrowsableState.Never)]
376 public override string ID {
377 get { return base.ID; }
378 set { base.ID = value; }
381 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
383 public bool IsPostBack {
388 return _requestValueCollection != null && !HttpContext.Current.InTransit;
393 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
394 public bool IsReusable {
395 get { return false; }
398 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
400 public bool IsValid {
403 throw new HttpException (Locale.GetText ("Page hasn't been validated."));
406 foreach (IValidator val in Validators)
411 return ValidateCollection (_validators);
416 public IDictionary Items {
419 items = new Hashtable ();
425 [EditorBrowsable (EditorBrowsableState.Never)]
427 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
428 [BrowsableAttribute (false)]
430 get { return Thread.CurrentThread.CurrentCulture.LCID; }
431 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
435 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
441 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
442 public bool MaintainScrollPositionOnPostBack {
443 get { return _maintainScrollPositionOnPostBack; }
444 set { _maintainScrollPositionOnPostBack = value; }
449 public PageAdapter PageAdapter {
451 return (PageAdapter)Adapter;
457 internal string theForm {
463 internal bool IsMultiForm {
464 get { return false; }
468 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
470 public HttpRequest Request {
472 if (_request == null)
473 throw new HttpException("Request is not available in this context.");
478 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
480 public HttpResponse Response {
482 if (_response == null)
483 throw new HttpException ("Response is not available in this context.");
488 [EditorBrowsable (EditorBrowsableState.Never)]
490 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
491 [BrowsableAttribute (false)]
492 public string ResponseEncoding {
493 get { return Response.ContentEncoding.WebName; }
494 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
497 protected string ResponseEncoding {
498 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
502 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
504 public HttpServerUtility Server {
505 get { return Context.Server; }
508 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
510 public virtual HttpSessionState Session {
512 if (_session != null)
516 _session = Context.Session;
518 // ignore, should not throw
521 if (_session == null)
522 throw new HttpException ("Session state can only be used " +
523 "when enableSessionState is set to true, either " +
524 "in a configuration file or in the Page directive.");
531 [FilterableAttribute (false)]
535 public bool SmartNavigation {
536 get { return _smartNavigation; }
537 set { _smartNavigation = value; }
541 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
544 public virtual string StyleSheetTheme {
545 get { return _styleSheetTheme; }
546 set { _styleSheetTheme = value; }
550 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
551 public virtual string Theme {
552 get { return _theme; }
553 set { _theme = value; }
556 void InitializeStyleSheet ()
558 if (_styleSheetTheme == null) {
559 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
561 _styleSheetTheme = ps.StyleSheetTheme;
563 if (_styleSheetTheme != null && _styleSheetTheme != "")
564 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, Context);
567 void InitializeTheme ()
569 if (_theme == null) {
570 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
574 if (_theme != null && _theme != "") {
575 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, Context);
576 _pageTheme.SetPage (this);
585 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
586 public string Title {
588 if (_title == null) {
589 if (htmlHeader != null)
590 return htmlHeader.Title;
596 if (htmlHeader != null)
597 htmlHeader.Title = value;
604 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
606 public TraceContext Trace {
607 get { return Context.Trace; }
610 [EditorBrowsable (EditorBrowsableState.Never)]
612 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
613 [BrowsableAttribute (false)]
614 public bool TraceEnabled {
615 get { return Trace.IsEnabled; }
616 set { Trace.IsEnabled = value; }
619 protected bool TraceEnabled {
620 set { Trace.IsEnabled = value; }
624 [EditorBrowsable (EditorBrowsableState.Never)]
626 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
627 [BrowsableAttribute (false)]
628 public TraceMode TraceModeValue {
629 get { return Trace.TraceMode; }
630 set { Trace.TraceMode = value; }
633 protected TraceMode TraceModeValue {
634 set { Trace.TraceMode = value; }
638 [EditorBrowsable (EditorBrowsableState.Never)]
639 protected int TransactionMode {
641 get { return _transactionMode; }
643 set { _transactionMode = value; }
648 // This method is here just to remove the warning about "_transactionMode" not being
649 // used. We probably will use it internally at some point.
651 internal int GetTransactionMode ()
653 return _transactionMode;
658 [EditorBrowsable (EditorBrowsableState.Advanced)]
659 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
660 [BrowsableAttribute (false)]
661 public string UICulture {
662 get { return Thread.CurrentThread.CurrentUICulture.Name; }
663 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
666 [EditorBrowsable (EditorBrowsableState.Never)]
667 protected string UICulture {
668 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
672 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
674 public IPrincipal User {
675 get { return Context.User; }
678 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
680 public ValidatorCollection Validators {
682 if (_validators == null)
683 _validators = new ValidatorCollection ();
688 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
690 public string ViewStateUserKey {
691 get { return viewStateUserKey; }
692 set { viewStateUserKey = value; }
696 public override bool Visible {
697 get { return base.Visible; }
698 set { base.Visible = value; }
706 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
710 CultureInfo ret = null;
711 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
713 if (Context.IsPortletRequest)
716 string[] languages = Request.UserLanguages;
718 if (languages != null && languages.Length > 0)
719 ret = CultureInfo.CreateSpecificCulture (languages[0]);
726 ret = CultureInfo.CreateSpecificCulture (culture);
732 [EditorBrowsable (EditorBrowsableState.Never)]
733 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
737 throw new NotImplementedException ();
740 [EditorBrowsable (EditorBrowsableState.Never)]
741 protected void AspCompatEndProcessRequest (IAsyncResult result)
743 throw new NotImplementedException ();
746 [EditorBrowsable (EditorBrowsableState.Advanced)]
747 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
749 return new HtmlTextWriter (tw);
752 [EditorBrowsable (EditorBrowsableState.Never)]
753 public void DesignerInitialize ()
755 InitRecursive (null);
758 [EditorBrowsable (EditorBrowsableState.Advanced)]
759 protected virtual NameValueCollection DeterminePostBackMode ()
761 HttpRequest req = Request;
765 NameValueCollection coll = null;
766 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
769 else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
773 coll = req.QueryString;
775 WebROCollection c = (WebROCollection) coll;
776 allow_load = !c.GotID;
778 c.ID = GetTypeHashCode ();
780 allow_load = (c.ID == GetTypeHashCode ());
782 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
789 public override Control FindControl (string id) {
793 return base.FindControl (id);
800 [EditorBrowsable (EditorBrowsableState.Advanced)]
801 public string GetPostBackClientEvent (Control control, string argument)
803 return scriptManager.GetPostBackEventReference (control, argument);
809 [EditorBrowsable (EditorBrowsableState.Advanced)]
810 public string GetPostBackClientHyperlink (Control control, string argument)
812 return scriptManager.GetPostBackClientHyperlink (control, argument);
818 [EditorBrowsable (EditorBrowsableState.Advanced)]
819 public string GetPostBackEventReference (Control control)
821 return scriptManager.GetPostBackEventReference (control, "");
827 [EditorBrowsable (EditorBrowsableState.Advanced)]
828 public string GetPostBackEventReference (Control control, string argument)
830 return scriptManager.GetPostBackEventReference (control, argument);
833 internal void RequiresPostBackScript ()
836 if (requiresPostBackScript)
838 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
839 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
841 requiresPostBackScript = true;
844 [EditorBrowsable (EditorBrowsableState.Never)]
845 public virtual int GetTypeHashCode ()
851 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
852 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
854 if (cacheSettings.Enabled)
855 InitOutputCache(cacheSettings.Duration,
856 cacheSettings.VaryByHeader,
857 cacheSettings.VaryByCustom,
858 cacheSettings.Location,
859 cacheSettings.VaryByParam);
863 [EditorBrowsable (EditorBrowsableState.Never)]
864 protected virtual void InitOutputCache (int duration,
867 OutputCacheLocation location,
870 HttpCachePolicy cache = Response.Cache;
871 bool set_vary = false;
872 HttpContext ctx = Context;
873 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
876 case OutputCacheLocation.Any:
877 cache.SetCacheability (HttpCacheability.Public);
878 cache.SetMaxAge (new TimeSpan (0, 0, duration));
879 cache.SetLastModified (timestamp);
882 case OutputCacheLocation.Client:
883 cache.SetCacheability (HttpCacheability.Private);
884 cache.SetMaxAge (new TimeSpan (0, 0, duration));
885 cache.SetLastModified (timestamp);
887 case OutputCacheLocation.Downstream:
888 cache.SetCacheability (HttpCacheability.Public);
889 cache.SetMaxAge (new TimeSpan (0, 0, duration));
890 cache.SetLastModified (timestamp);
892 case OutputCacheLocation.Server:
893 cache.SetCacheability (HttpCacheability.Server);
896 case OutputCacheLocation.None:
901 if (varyByCustom != null)
902 cache.SetVaryByCustom (varyByCustom);
904 if (varyByParam != null && varyByParam.Length > 0) {
905 string[] prms = varyByParam.Split (';');
906 foreach (string p in prms)
907 cache.VaryByParams [p.Trim ()] = true;
908 cache.VaryByParams.IgnoreParams = false;
910 cache.VaryByParams.IgnoreParams = true;
913 if (varyByHeader != null && varyByHeader.Length > 0) {
914 string[] hdrs = varyByHeader.Split (';');
915 foreach (string h in hdrs)
916 cache.VaryByHeaders [h.Trim ()] = true;
920 cache.Duration = duration;
921 cache.SetExpires (timestamp.AddSeconds (duration));
927 [EditorBrowsable (EditorBrowsableState.Advanced)]
929 public bool IsClientScriptBlockRegistered (string key)
931 return scriptManager.IsClientScriptBlockRegistered (key);
937 [EditorBrowsable (EditorBrowsableState.Advanced)]
939 public bool IsStartupScriptRegistered (string key)
941 return scriptManager.IsStartupScriptRegistered (key);
944 public string MapPath (string virtualPath)
946 return Request.MapPath (virtualPath);
950 protected internal override void Render (HtmlTextWriter writer) {
951 if (MaintainScrollPositionOnPostBack) {
952 ClientScript.RegisterWebFormClientScript ();
954 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
955 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
957 string webForm = IsMultiForm ? theForm + "." : null;
959 StringBuilder script = new StringBuilder ();
960 script.AppendLine ("<script type=\"text/javascript\">");
961 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
962 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
963 script.AppendLine (theForm + ".submit = function () { " + webForm + "WebForm_SaveScrollPositionSubmit(); }");
964 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
965 script.AppendLine (theForm + ".onsubmit = function () { " + webForm + "WebForm_SaveScrollPositionOnSubmit(); }");
967 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
968 script.AppendLine ("window.onload = function () { " + webForm + "WebForm_RestoreScrollPosition (); };");
970 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
971 script.AppendLine ("</script>");
973 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
975 base.Render (writer);
979 private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
982 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
983 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
987 ClientScriptManager.WriteBeginScriptBlock (writer);
990 RenderClientScriptFormDeclaration (writer, formUniqueID);
993 writer.WriteLine ("{0}._form = {0};", theForm);
994 writer.Write (theForm + ".");
996 writer.WriteLine ("window._form = {0};", theForm);
998 writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
1000 writer.WriteLine ("\tif(this._form.onsubmit && this._form.onsubmit() == false) return;");
1002 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1004 writer.WriteLine ("\tthis._form.{0}.value = eventTarget;", postEventSourceID);
1005 writer.WriteLine ("\tthis._form.{0}.value = eventArgument;", postEventArgumentID);
1006 writer.WriteLine ("\tthis._form.submit();");
1007 writer.WriteLine ("}");
1008 ClientScriptManager.WriteEndScriptBlock (writer);
1011 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1013 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1014 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1015 writer.WriteLine ("\t{0}._instanceVariableName = '{0}';", theForm);
1017 string serverUrl = Context.ServletResponse.encodeURL (Request.RawUrl);
1018 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1019 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1020 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1024 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1027 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1029 renderingForm = true;
1030 writer.WriteLine ();
1033 ClientScriptManager.WriteBeginScriptBlock (writer);
1034 RenderClientScriptFormDeclaration (writer, formUniqueID);
1035 ClientScriptManager.WriteEndScriptBlock (writer);
1038 if (handleViewState)
1039 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1041 scriptManager.WriteHiddenFields (writer);
1042 if (requiresPostBackScript) {
1043 RenderPostBackScript (writer, formUniqueID);
1044 postBackScriptRendered = true;
1047 scriptManager.WriteWebFormClientScript (writer);
1049 scriptManager.WriteClientScriptBlocks (writer);
1052 internal IStateFormatter GetFormatter ()
1054 return new ObjectStateFormatter (this);
1057 internal string GetSavedViewState ()
1059 return _savedViewState;
1062 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1065 scriptManager.SaveEventValidationState ();
1066 scriptManager.WriteExpandoAttributes (writer);
1068 scriptManager.WriteHiddenFields (writer);
1069 if (!postBackScriptRendered && requiresPostBackScript)
1070 RenderPostBackScript (writer, formUniqueID);
1072 scriptManager.WriteWebFormClientScript (writer);
1075 scriptManager.WriteArrayDeclares (writer);
1076 scriptManager.WriteStartupScriptBlocks (writer);
1077 renderingForm = false;
1078 postBackScriptRendered = false;
1081 private void ProcessPostData (NameValueCollection data, bool second)
1083 NameValueCollection requestValues = _requestValueCollection == null ?
1084 new NameValueCollection () :
1085 _requestValueCollection;
1087 if (data != null && data.Count > 0) {
1088 Hashtable used = new Hashtable ();
1089 foreach (string id in data.AllKeys){
1090 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
1093 string real_id = id;
1094 int dot = real_id.IndexOf ('.');
1096 real_id = real_id.Substring (0, dot);
1098 if (real_id == null || used.ContainsKey (real_id))
1101 used.Add (real_id, real_id);
1103 Control ctrl = FindControl (real_id);
1105 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1106 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1110 RegisterRequiresRaiseEvent (pbeh);
1114 if (pbdh.LoadPostData (real_id, requestValues) == true) {
1115 if (requiresPostDataChanged == null)
1116 requiresPostDataChanged = new ArrayList ();
1117 requiresPostDataChanged.Add (pbdh);
1120 if (_requiresPostBackCopy != null)
1121 _requiresPostBackCopy.Remove (real_id);
1123 } else if (!second) {
1124 if (secondPostData == null)
1125 secondPostData = new NameValueCollection ();
1126 secondPostData.Add (real_id, data [id]);
1131 ArrayList list1 = null;
1132 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1133 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1134 foreach (string id in handlers) {
1135 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1137 _requiresPostBackCopy.Remove (id);
1138 if (pbdh.LoadPostData (id, requestValues)) {
1139 if (requiresPostDataChanged == null)
1140 requiresPostDataChanged = new ArrayList ();
1142 requiresPostDataChanged.Add (pbdh);
1144 } else if (!second) {
1146 list1 = new ArrayList ();
1151 _requiresPostBackCopy = second ? null : list1;
1153 secondPostData = null;
1156 [EditorBrowsable (EditorBrowsableState.Never)]
1158 public virtual void ProcessRequest (HttpContext context)
1160 public void ProcessRequest (HttpContext context)
1164 _lifeCycle = PageLifeCycle.Unknown;
1168 _application = context.Application;
1169 _response = context.Response;
1170 _request = context.Request;
1171 _cache = context.Cache;
1173 if (clientTarget != null)
1174 Request.ClientTarget = clientTarget;
1176 WireupAutomaticEvents ();
1177 //-- Control execution lifecycle in the docs
1179 // Save culture information because it can be modified in FrameworkInitialize()
1180 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1181 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1182 FrameworkInitialize ();
1183 context.ErrorPage = _errorPage;
1186 InternalProcessRequest ();
1187 } catch (ThreadAbortException) {
1188 // Do nothing, just ignore it by now.
1189 } catch (Exception e) {
1190 context.AddError (e); // OnError might access LastError
1191 OnError (EventArgs.Empty);
1192 context.ClearError (e);
1193 // We want to remove that error, as we're rethrowing to stop
1194 // further processing.
1195 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1200 _lifeCycle = PageLifeCycle.Unload;
1203 UnloadRecursive (true);
1205 _lifeCycle = PageLifeCycle.End;
1208 if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1209 Thread.CurrentThread.CurrentCulture = culture;
1211 if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1212 Thread.CurrentThread.CurrentUICulture = uiculture;
1217 delegate void ProcessRequestDelegate (HttpContext context);
1219 private sealed class DummyAsyncResult : IAsyncResult
1221 readonly object state;
1222 readonly WaitHandle asyncWaitHandle;
1223 readonly bool completedSynchronously;
1224 readonly bool isCompleted;
1226 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1228 this.isCompleted = isCompleted;
1229 this.completedSynchronously = completedSynchronously;
1232 asyncWaitHandle = new ManualResetEvent (true);
1235 asyncWaitHandle = new ManualResetEvent (false);
1239 #region IAsyncResult Members
1241 public object AsyncState {
1242 get { return state; }
1245 public WaitHandle AsyncWaitHandle {
1246 get { return asyncWaitHandle; }
1249 public bool CompletedSynchronously {
1250 get { return completedSynchronously; }
1253 public bool IsCompleted {
1254 get { return isCompleted; }
1260 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1262 ProcessRequest (context);
1263 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1265 if (callback != null) {
1266 callback (asyncResult);
1272 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1276 internal void ProcessCrossPagePostBack (HttpContext context)
1278 isCrossPagePostBack = true;
1279 ProcessRequest (context);
1283 void InternalProcessRequest ()
1285 _requestValueCollection = this.DeterminePostBackMode();
1288 HttpContext ctx = Context;
1290 _lifeCycle = PageLifeCycle.Start;
1291 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1292 if (_requestValueCollection != null) {
1293 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1294 _doLoadPreviousPage = true;
1297 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1298 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1299 //isPostBack = !isCallback;
1300 isPostBack = !ctx.InTransit;
1302 string lastFocus = _requestValueCollection [LastFocusID];
1303 if (!String.IsNullOrEmpty (lastFocus)) {
1304 _focusedControlID = UniqueID2ClientID (lastFocus);
1308 // if request was transfered from other page - track Prev. Page
1309 previousPage = ctx.LastPage;
1310 ctx.LastPage = this;
1312 _lifeCycle = PageLifeCycle.PreInit;
1313 OnPreInit (EventArgs.Empty);
1317 _lifeCycle = PageLifeCycle.Init;
1319 Trace.Write ("aspx.page", "Begin Init");
1320 InitRecursive (null);
1321 Trace.Write ("aspx.page", "End Init");
1324 _lifeCycle = PageLifeCycle.InitComplete;
1325 OnInitComplete (EventArgs.Empty);
1328 renderingForm = false;
1330 if (IsPostBack || IsCallback) {
1331 _lifeCycle = PageLifeCycle.PreLoad;
1332 if (_requestValueCollection != null)
1333 scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
1337 Trace.Write ("aspx.page", "Begin LoadViewState");
1338 LoadPageViewState ();
1339 Trace.Write ("aspx.page", "End LoadViewState");
1340 Trace.Write ("aspx.page", "Begin ProcessPostData");
1344 ProcessPostData (_requestValueCollection, false);
1345 Trace.Write ("aspx.page", "End ProcessPostData");
1349 OnPreLoad (EventArgs.Empty);
1350 _lifeCycle = PageLifeCycle.Load;
1358 if (IsPostBack || IsCallback) {
1359 _lifeCycle = PageLifeCycle.ControlEvents;
1363 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1364 ProcessPostData (secondPostData, true);
1365 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1366 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1367 RaiseChangedEvents ();
1368 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1369 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1370 RaisePostBackEvents ();
1371 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1375 _lifeCycle = PageLifeCycle.LoadComplete;
1376 OnLoadComplete (EventArgs.Empty);
1378 if (IsCrossPagePostBack)
1382 string result = ProcessCallbackData ();
1383 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1384 callbackOutput.Write (result);
1385 callbackOutput.Flush ();
1389 _lifeCycle = PageLifeCycle.PreRender;
1392 Trace.Write ("aspx.page", "Begin PreRender");
1393 PreRenderRecursiveInternal ();
1394 Trace.Write ("aspx.page", "End PreRender");
1397 ExecuteRegisteredAsyncTasks ();
1399 _lifeCycle = PageLifeCycle.PreRenderComplete;
1400 OnPreRenderComplete (EventArgs.Empty);
1403 Trace.Write ("aspx.page", "Begin SaveViewState");
1404 SavePageViewState ();
1405 Trace.Write ("aspx.page", "End SaveViewState");
1408 _lifeCycle = PageLifeCycle.SaveStateComplete;
1409 OnSaveStateComplete (EventArgs.Empty);
1411 if (OnSaveStateCompleteForPortlet ())
1413 #endif // TARGET_J2EE
1417 _lifeCycle = PageLifeCycle.Render;
1418 scriptManager.ResetEventValidationState ();
1422 Trace.Write ("aspx.page", "Begin Render");
1423 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1424 RenderControl (output);
1425 Trace.Write ("aspx.page", "End Render");
1428 private void RenderTrace ()
1430 TraceManager traceManager = HttpRuntime.TraceManager;
1432 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1437 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1440 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1441 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1442 Trace.Render (output);
1447 bool CheckForValidationSupport (Control targetControl)
1449 if (targetControl == null)
1451 Type type = targetControl.GetType ();
1452 object[] attributes = type.GetCustomAttributes (false);
1453 foreach (object attr in attributes)
1454 if (attr is SupportsEventValidationAttribute)
1460 void RaisePostBackEvents ()
1463 Control targetControl;
1465 if (requiresRaiseEvent != null) {
1466 RaisePostBackEvent (requiresRaiseEvent, null);
1470 NameValueCollection postdata = _requestValueCollection;
1471 if (postdata == null)
1474 string eventTarget = postdata [postEventSourceID];
1475 if (eventTarget == null || eventTarget.Length == 0) {
1481 targetControl = FindControl (eventTarget);
1482 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1484 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1490 string eventArgument = postdata [postEventArgumentID];
1491 RaisePostBackEvent (target, eventArgument);
1494 internal void RaiseChangedEvents ()
1496 if (requiresPostDataChanged == null)
1499 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1500 ipdh.RaisePostDataChangedEvent ();
1502 requiresPostDataChanged = null;
1505 [EditorBrowsable (EditorBrowsableState.Advanced)]
1506 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1509 Control targetControl = sourceControl as Control;
1510 if (targetControl != null && CheckForValidationSupport (targetControl))
1511 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1513 sourceControl.RaisePostBackEvent (eventArgument);
1519 [EditorBrowsable (EditorBrowsableState.Advanced)]
1520 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1522 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1528 [EditorBrowsable (EditorBrowsableState.Advanced)]
1529 public virtual void RegisterClientScriptBlock (string key, string script)
1531 scriptManager.RegisterClientScriptBlock (key, script);
1537 [EditorBrowsable (EditorBrowsableState.Advanced)]
1538 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1540 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1543 [MonoTODO("Not implemented, Used in HtmlForm")]
1544 internal void RegisterClientScriptFile (string a, string b, string c)
1546 throw new NotImplementedException ();
1552 [EditorBrowsable (EditorBrowsableState.Advanced)]
1553 public void RegisterOnSubmitStatement (string key, string script)
1555 scriptManager.RegisterOnSubmitStatement (key, script);
1558 internal string GetSubmitStatements ()
1560 return scriptManager.WriteSubmitStatements ();
1563 [EditorBrowsable (EditorBrowsableState.Advanced)]
1564 public void RegisterRequiresPostBack (Control control)
1567 if (!(control is IPostBackDataHandler))
1568 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1571 if (_requiresPostBack == null)
1572 _requiresPostBack = new ArrayList ();
1574 if (_requiresPostBack.Contains (control.UniqueID))
1577 _requiresPostBack.Add (control.UniqueID);
1580 [EditorBrowsable (EditorBrowsableState.Advanced)]
1581 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1583 requiresRaiseEvent = control;
1589 [EditorBrowsable (EditorBrowsableState.Advanced)]
1590 public virtual void RegisterStartupScript (string key, string script)
1592 scriptManager.RegisterStartupScript (key, script);
1595 [EditorBrowsable (EditorBrowsableState.Advanced)]
1596 public void RegisterViewStateHandler ()
1598 handleViewState = true;
1601 [EditorBrowsable (EditorBrowsableState.Advanced)]
1602 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1604 PageStatePersister persister = this.PageStatePersister;
1605 if (persister == null)
1607 Pair pair = viewState as Pair;
1609 persister.ViewState = pair.First;
1610 persister.ControlState = pair.Second;
1612 persister.ViewState = viewState;
1616 internal string RawViewState {
1618 NameValueCollection postdata = _requestValueCollection;
1620 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1623 if (view_state == "")
1627 set { _savedViewState = value; }
1635 PageStatePersister PageStatePersister {
1637 if (page_state_persister == null)
1638 page_state_persister = new HiddenFieldPageStatePersister (this);
1639 return page_state_persister;
1643 [EditorBrowsable (EditorBrowsableState.Advanced)]
1644 protected virtual object LoadPageStateFromPersistenceMedium ()
1646 PageStatePersister persister = this.PageStatePersister;
1647 if (persister == null)
1650 return new Pair (persister.ViewState, persister.ControlState);
1653 internal void LoadPageViewState()
1655 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1656 if (sState != null) {
1659 LoadPageControlState (sState.Second);
1661 Pair vsr = sState.First as Pair;
1663 LoadViewStateRecursive (vsr.First);
1664 _requiresPostBackCopy = vsr.Second as ArrayList;
1670 internal void SavePageViewState ()
1672 if (!handleViewState)
1676 object controlState = SavePageControlState ();
1679 object viewState = SaveViewStateRecursive ();
1680 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1683 if (viewState != null || reqPostback != null)
1684 vsr = new Pair (viewState, reqPostback);
1685 Pair pair = new Pair ();
1689 pair.Second = controlState;
1693 if (pair.First == null && pair.Second == null)
1694 SavePageStateToPersistenceMedium (null);
1696 SavePageStateToPersistenceMedium (pair);
1700 public virtual void Validate ()
1702 is_validated = true;
1703 ValidateCollection (_validators);
1707 internal bool AreValidatorsUplevel () {
1708 return AreValidatorsUplevel (String.Empty);
1711 internal bool AreValidatorsUplevel (string valGroup)
1713 internal virtual bool AreValidatorsUplevel ()
1716 bool uplevel = false;
1718 foreach (IValidator v in Validators) {
1719 BaseValidator bv = v as BaseValidator;
1720 if (bv == null) continue;
1723 if (valGroup != bv.ValidationGroup)
1726 if (bv.GetRenderUplevel()) {
1735 bool ValidateCollection (ValidatorCollection validators)
1738 if (!_eventValidation)
1742 if (validators == null || validators.Count == 0)
1745 bool all_valid = true;
1746 foreach (IValidator v in validators){
1748 if (v.IsValid == false)
1755 [EditorBrowsable (EditorBrowsableState.Advanced)]
1756 public virtual void VerifyRenderingInServerForm (Control control)
1758 if (Context == null)
1765 throw new HttpException ("Control '" +
1768 control.GetType ().Name +
1769 "' must be placed inside a form tag with runat=server.");
1772 protected override void FrameworkInitialize ()
1774 base.FrameworkInitialize ();
1776 InitializeStyleSheet ();
1787 ClientScriptManager ClientScript {
1788 get { return scriptManager; }
1793 static readonly object InitCompleteEvent = new object ();
1794 static readonly object LoadCompleteEvent = new object ();
1795 static readonly object PreInitEvent = new object ();
1796 static readonly object PreLoadEvent = new object ();
1797 static readonly object PreRenderCompleteEvent = new object ();
1798 static readonly object SaveStateCompleteEvent = new object ();
1800 const int initcomplete_mask = 1;
1801 const int loadcomplete_mask = 1 << 1;
1802 const int preinit_mask = 1 << 2;
1803 const int preload_mask = 1 << 3;
1804 const int prerendercomplete_mask = 1 << 4;
1805 const int savestatecomplete_mask = 1 << 5;
1807 [EditorBrowsable (EditorBrowsableState.Advanced)]
1808 public event EventHandler InitComplete {
1810 event_mask |= initcomplete_mask;
1811 Events.AddHandler (InitCompleteEvent, value);
1813 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1816 [EditorBrowsable (EditorBrowsableState.Advanced)]
1817 public event EventHandler LoadComplete {
1819 event_mask |= loadcomplete_mask;
1820 Events.AddHandler (LoadCompleteEvent, value);
1822 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1825 public event EventHandler PreInit {
1827 event_mask |= preinit_mask;
1828 Events.AddHandler (PreInitEvent, value);
1830 remove { Events.RemoveHandler (PreInitEvent, value); }
1833 [EditorBrowsable (EditorBrowsableState.Advanced)]
1834 public event EventHandler PreLoad {
1836 event_mask |= preload_mask;
1837 Events.AddHandler (PreLoadEvent, value);
1839 remove { Events.RemoveHandler (PreLoadEvent, value); }
1842 [EditorBrowsable (EditorBrowsableState.Advanced)]
1843 public event EventHandler PreRenderComplete {
1845 event_mask |= prerendercomplete_mask;
1846 Events.AddHandler (PreRenderCompleteEvent, value);
1848 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1851 [EditorBrowsable (EditorBrowsableState.Advanced)]
1852 public event EventHandler SaveStateComplete {
1854 event_mask |= savestatecomplete_mask;
1855 Events.AddHandler (SaveStateCompleteEvent, value);
1857 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1860 protected virtual void OnInitComplete (EventArgs e)
1862 if ((event_mask & initcomplete_mask) != 0) {
1863 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1864 if (eh != null) eh (this, e);
1868 protected virtual void OnLoadComplete (EventArgs e)
1870 if ((event_mask & loadcomplete_mask) != 0) {
1871 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1872 if (eh != null) eh (this, e);
1876 protected virtual void OnPreInit (EventArgs e)
1878 if ((event_mask & preinit_mask) != 0) {
1879 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1880 if (eh != null) eh (this, e);
1884 protected virtual void OnPreLoad (EventArgs e)
1886 if ((event_mask & preload_mask) != 0) {
1887 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1888 if (eh != null) eh (this, e);
1892 protected virtual void OnPreRenderComplete (EventArgs e)
1894 if ((event_mask & prerendercomplete_mask) != 0) {
1895 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1896 if (eh != null) eh (this, e);
1901 if (!Form.DetermineRenderUplevel ())
1904 /* figure out if we have some control we're going to focus */
1905 if (String.IsNullOrEmpty (_focusedControlID)) {
1906 _focusedControlID = Form.DefaultFocus;
1907 if (String.IsNullOrEmpty (_focusedControlID))
1908 _focusedControlID = Form.DefaultButton;
1911 if (!String.IsNullOrEmpty (_focusedControlID)) {
1912 ClientScript.RegisterWebFormClientScript ();
1913 ClientScript.RegisterStartupScript (
1914 "HtmlForm-DefaultButton-StartupScript",
1916 "<script type=\"text/javascript\">\n{0}WebForm_AutoFocus('{1}');{2}\n</script>\n",
1917 ClientScriptManager.SCRIPT_BLOCK_START,
1919 ClientScriptManager.SCRIPT_BLOCK_END)
1923 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1924 ClientScript.RegisterWebFormClientScript ();
1925 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1926 "WebForm_ReEnableControls(this);");
1930 internal void RegisterEnabledControl (Control control)
1932 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1934 _hasEnabledControlArray = true;
1935 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Format ("'{0}'", control.ClientID));
1938 protected virtual void OnSaveStateComplete (EventArgs e)
1940 if ((event_mask & savestatecomplete_mask) != 0) {
1941 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1942 if (eh != null) eh (this, e);
1946 public HtmlForm Form {
1947 get { return _form; }
1950 internal void RegisterForm (HtmlForm form)
1955 [BrowsableAttribute (false)]
1956 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1957 public Page PreviousPage {
1959 if (_doLoadPreviousPage) {
1960 _doLoadPreviousPage = false;
1961 LoadPreviousPageReference ();
1963 return previousPage;
1968 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1969 [BrowsableAttribute (false)]
1970 public bool IsCallback {
1971 get { return isCallback; }
1974 [BrowsableAttribute (false)]
1975 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1976 public bool IsCrossPagePostBack {
1977 get { return isCrossPagePostBack; }
1980 public new virtual char IdSeparator {
1982 //TODO: why override?
1983 return base.IdSeparator;
1987 string ProcessCallbackData ()
1989 string callbackTarget = _requestValueCollection [CallbackSourceID];
1990 if (callbackTarget == null || callbackTarget.Length == 0)
1991 throw new HttpException ("Callback target not provided.");
1993 Control targetControl = FindControl (callbackTarget);
1994 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
1996 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
1998 string callbackEventError = String.Empty;
1999 string callBackResult;
2000 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2003 target.RaiseCallbackEvent (callbackArgument);
2005 catch (Exception ex) {
2006 callbackEventError = String.Format ("e{0}", ex.Message);
2010 callBackResult = target.GetCallbackResult ();
2012 catch (Exception ex) {
2013 return String.Format ("e{0}", ex.Message);
2016 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2017 return String.Format ("{0}{1}|{2}{3}", callbackEventError, eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
2020 [BrowsableAttribute (false)]
2021 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2022 public HtmlHead Header {
2023 get { return htmlHeader; }
2026 internal void SetHeader (HtmlHead header)
2028 htmlHeader = header;
2029 if (_title != null) {
2030 htmlHeader.Title = _title;
2035 protected bool AsyncMode {
2036 get { return asyncMode; }
2037 set { asyncMode = value; }
2040 public TimeSpan AsyncTimeout {
2041 get { return asyncTimeout; }
2042 set { asyncTimeout = value; }
2045 public bool IsAsync {
2046 get { return AsyncMode; }
2049 [MonoTODO ("Not Implemented")]
2050 protected internal virtual string UniqueFilePathSuffix {
2052 throw new NotImplementedException ();
2056 [MonoTODO ("Not Implemented")]
2057 public int MaxPageStateFieldLength {
2059 throw new NotImplementedException ();
2062 throw new NotImplementedException ();
2066 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2068 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2071 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2074 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2077 if (_lifeCycle >= PageLifeCycle.PreRender) {
2078 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
2081 if (beginHandler == null) {
2082 throw new ArgumentNullException ("beginHandler");
2085 if (endHandler == null) {
2086 throw new ArgumentNullException ("endHandler");
2089 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2092 private List<PageAsyncTask> ParallelTasks {
2094 if (parallelTasks == null) {
2095 parallelTasks = new List<PageAsyncTask>();
2097 return parallelTasks;
2101 private List<PageAsyncTask> SerialTasks {
2103 if (serialTasks == null) {
2104 serialTasks = new List<PageAsyncTask> ();
2110 public void RegisterAsyncTask (PageAsyncTask task)
2113 throw new ArgumentNullException ("task");
2116 if (task.ExecuteInParallel) {
2117 ParallelTasks.Add (task);
2120 SerialTasks.Add (task);
2124 public void ExecuteRegisteredAsyncTasks ()
2126 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2127 (serialTasks == null || serialTasks.Count == 0)){
2131 if (parallelTasks != null) {
2132 DateTime startExecution = DateTime.Now;
2133 List<PageAsyncTask> localParallelTasks = parallelTasks;
2134 parallelTasks = null; // Shouldn't execute tasks twice
2135 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2136 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2137 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2138 if (result.CompletedSynchronously) {
2139 parallelTask.EndHandler (result);
2142 asyncResults.Add (result);
2146 if (asyncResults.Count > 0) {
2148 TimeSpan timeout = AsyncTimeout;
2149 long t1 = DateTime.Now.Ticks;
2150 bool signalled = true;
2151 for (int i = 0; i < asyncResults.Count; i++) {
2152 if (asyncResults [i].IsCompleted)
2156 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2159 long t2 = DateTime.Now.Ticks;
2160 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2161 if (timeout.Ticks <= 0)
2165 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2169 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2171 for (i = 0; i < asyncResults.Count; i++) {
2172 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2174 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2175 if (!allSignalled) {
2176 for (i = 0; i < asyncResults.Count; i++) {
2177 if (!asyncResults [i].IsCompleted) {
2178 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2184 DateTime endWait = DateTime.Now;
2185 TimeSpan elapsed = endWait - startExecution;
2186 if (elapsed <= AsyncTimeout) {
2187 AsyncTimeout -= elapsed;
2190 AsyncTimeout = TimeSpan.FromTicks(0);
2194 if (serialTasks != null) {
2195 List<PageAsyncTask> localSerialTasks = serialTasks;
2196 serialTasks = null; // Shouldn't execute tasks twice
2197 foreach (PageAsyncTask serialTask in localSerialTasks) {
2198 DateTime startExecution = DateTime.Now;
2200 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2201 if (result.CompletedSynchronously) {
2202 serialTask.EndHandler (result);
2205 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2206 if (!done && !result.IsCompleted) {
2207 serialTask.TimeoutHandler (result);
2210 DateTime endWait = DateTime.Now;
2211 TimeSpan elapsed = endWait - startExecution;
2212 if (elapsed <= AsyncTimeout) {
2213 AsyncTimeout -= elapsed;
2216 AsyncTimeout = TimeSpan.FromTicks (0);
2220 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2223 void EndAsyncTaskCallback (IAsyncResult result)
2225 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2226 task.EndHandler (result);
2229 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2231 Type htmlTextWriterType = typeof (HtmlTextWriter);
2233 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2234 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2237 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2238 if (constructor == null) {
2239 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2242 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2245 public ViewStateEncryptionMode ViewStateEncryptionMode {
2246 get { return viewStateEncryptionMode; }
2247 set { viewStateEncryptionMode = value; }
2250 public void RegisterRequiresViewStateEncryption ()
2252 controlRegisteredForViewStateEncryption = true;
2255 private static byte [] AES_IV = null;
2256 private static byte [] TripleDES_IV = null;
2257 private static object locker = new object ();
2258 private static bool isEncryptionInitialized = false;
2260 private static void InitializeEncryption ()
2262 if (isEncryptionInitialized) {
2267 if (isEncryptionInitialized) {
2271 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2272 AES_IV = new byte [16];
2273 TripleDES_IV = new byte [8];
2276 for (i = 0; i < AES_IV.Length; i++) {
2277 AES_IV [i] = (byte) iv_string [i];
2280 for (i = 0; i < TripleDES_IV.Length; i++) {
2281 TripleDES_IV [i] = (byte) iv_string [i];
2284 isEncryptionInitialized = true;
2288 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2290 ICryptoTransform transform = null;
2291 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2292 byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
2294 switch (config.Validation) {
2295 case MachineKeyValidation.SHA1:
2296 transform = SHA1.Create ();
2299 case MachineKeyValidation.MD5:
2300 transform = MD5.Create ();
2303 case MachineKeyValidation.AES:
2304 if (cryptoStreamMode == CryptoStreamMode.Read){
2305 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2307 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2311 case MachineKeyValidation.TripleDES:
2312 if (cryptoStreamMode == CryptoStreamMode.Read){
2313 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2315 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2323 internal bool NeedViewStateEncryption {
2325 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2326 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2327 controlRegisteredForViewStateEncryption));
2332 void ApplyMasterPage ()
2334 if (masterPageFile != null && masterPageFile.Length > 0) {
2335 ArrayList appliedMasterPageFiles = new ArrayList ();
2337 if (Master != null) {
2338 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2342 Controls.Add (Master);
2347 [DefaultValueAttribute ("")]
2348 public virtual string MasterPageFile {
2349 get { return masterPageFile; }
2351 masterPageFile = value;
2356 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2357 [BrowsableAttribute (false)]
2358 public MasterPage Master {
2360 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2363 if (masterPage == null)
2364 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2370 public void SetFocus (string clientID)
2372 if (String.IsNullOrEmpty (clientID))
2373 throw new ArgumentNullException ("control");
2375 if (_lifeCycle > PageLifeCycle.PreRender)
2376 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2379 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2381 _focusedControlID = clientID;
2384 public void SetFocus (Control control)
2386 if (control == null)
2387 throw new ArgumentNullException ("control");
2389 SetFocus (control.ClientID);
2392 [EditorBrowsable (EditorBrowsableState.Advanced)]
2393 public void RegisterRequiresControlState (Control control)
2395 if (control == null)
2396 throw new ArgumentNullException ("control");
2398 if (RequiresControlState (control))
2401 if (requireStateControls == null)
2402 requireStateControls = new ArrayList ();
2403 int n = requireStateControls.Add (control);
2405 if (_savedControlState == null || n >= _savedControlState.Length)
2408 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2409 if (parent.IsChildControlStateCleared)
2412 object state = _savedControlState [n];
2414 control.LoadControlState (state);
2417 public bool RequiresControlState (Control control)
2419 if (requireStateControls == null) return false;
2420 return requireStateControls.Contains (control);
2423 [EditorBrowsable (EditorBrowsableState.Advanced)]
2424 public void UnregisterRequiresControlState (Control control)
2426 if (requireStateControls != null)
2427 requireStateControls.Remove (control);
2430 public ValidatorCollection GetValidators (string validationGroup)
2432 if (validationGroup == String.Empty)
2433 validationGroup = null;
2435 ValidatorCollection col = new ValidatorCollection ();
2436 if (_validators == null)
2439 foreach (IValidator v in _validators)
2440 if (BelongsToGroup(v, validationGroup))
2446 bool BelongsToGroup(IValidator v, string validationGroup) {
2447 BaseValidator validator = v as BaseValidator;
2448 if (validationGroup == null)
2449 return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
2451 return validator != null && validator.ValidationGroup == validationGroup;
2454 public virtual void Validate (string validationGroup)
2456 is_validated = true;
2457 ValidateCollection (GetValidators (validationGroup));
2460 object SavePageControlState ()
2462 if (requireStateControls == null) return null;
2463 object[] state = new object [requireStateControls.Count];
2465 bool allNull = true;
2466 for (int n=0; n<state.Length; n++) {
2467 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2468 if (state [n] != null) allNull = false;
2470 if (allNull) return null;
2474 void LoadPageControlState (object data)
2476 _savedControlState = (object []) data;
2478 if (requireStateControls == null) return;
2480 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2481 for (int n=0; n < max; n++) {
2482 Control ctl = (Control) requireStateControls [n];
2483 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2487 void LoadPreviousPageReference ()
2489 if (_requestValueCollection != null) {
2490 string prevPage = _requestValueCollection [PreviousPageID];
2491 if (prevPage != null) {
2492 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2493 previousPage.ProcessCrossPagePostBack (Context);
2499 Hashtable contentTemplates;
2500 [EditorBrowsable (EditorBrowsableState.Never)]
2501 protected internal void AddContentTemplate (string templateName, ITemplate template)
2503 if (contentTemplates == null)
2504 contentTemplates = new Hashtable ();
2505 contentTemplates [templateName] = template;
2508 PageTheme _pageTheme;
2509 internal PageTheme PageTheme {
2510 get { return _pageTheme; }
2513 PageTheme _styleSheetPageTheme;
2514 internal PageTheme StyleSheetPageTheme {
2515 get { return _styleSheetPageTheme; }
2520 internal void PushDataItemContext (object o) {
2521 if (dataItemCtx == null)
2522 dataItemCtx = new Stack ();
2524 dataItemCtx.Push (o);
2527 internal void PopDataItemContext () {
2528 if (dataItemCtx == null)
2529 throw new InvalidOperationException ();
2534 public object GetDataItem() {
2535 if (dataItemCtx == null || dataItemCtx.Count == 0)
2536 throw new InvalidOperationException ("No data item");
2538 return dataItemCtx.Peek ();
2541 protected internal override void OnInit (EventArgs e)
2545 ArrayList themes = new ArrayList();
2547 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2548 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2549 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2550 themes.AddRange (PageTheme.GetStyleSheets ());
2552 if (themes.Count > 0 && Header == null)
2553 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2555 foreach (string lss in themes) {
2556 HtmlLink hl = new HtmlLink ();
2557 hl.Href = ResolveUrl (lss);
2558 hl.Attributes["type"] = "text/css";
2559 hl.Attributes["rel"] = "stylesheet";
2560 Header.Controls.Add (hl);
2567 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2568 protected object GetWrappedFileDependencies (string [] list)
2573 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2574 protected virtual void InitializeCulture ()
2578 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2579 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)