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;
157 Hashtable _validatorsByGroup;
162 string _styleSheetTheme;
165 bool _maintainScrollPositionOnPostBack;
167 private bool asyncMode = false;
168 private TimeSpan asyncTimeout;
169 private const double DefaultAsyncTimeout = 45.0;
170 private List<PageAsyncTask> parallelTasks;
171 private List<PageAsyncTask> serialTasks;
173 private ViewStateEncryptionMode viewStateEncryptionMode;
174 private bool controlRegisteredForViewStateEncryption = false;
180 scriptManager = new ClientScriptManager (this);
185 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
187 asyncTimeout = ps.AsyncTimeout;
188 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
190 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
191 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
200 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
202 public HttpApplicationState Application {
203 get { return _application; }
206 [EditorBrowsable (EditorBrowsableState.Never)]
207 protected bool AspCompatMode {
209 get { return false; }
211 set { throw new NotImplementedException (); }
214 [EditorBrowsable (EditorBrowsableState.Never)]
216 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
217 [BrowsableAttribute (false)]
219 get { return Response.BufferOutput; }
220 set { Response.BufferOutput = value; }
223 protected bool Buffer {
224 set { Response.BufferOutput = value; }
228 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
233 throw new HttpException ("Cache is not available.");
239 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
241 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
242 [Browsable (false), DefaultValue ("")]
243 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
244 public string ClientTarget {
245 get { return (clientTarget == null) ? "" : clientTarget; }
247 clientTarget = value;
253 [EditorBrowsable (EditorBrowsableState.Never)]
255 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
256 [BrowsableAttribute (false)]
257 public int CodePage {
258 get { return Response.ContentEncoding.CodePage; }
259 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
262 protected int CodePage {
263 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
267 [EditorBrowsable (EditorBrowsableState.Never)]
269 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
270 [BrowsableAttribute (false)]
271 public string ContentType {
272 get { return Response.ContentType; }
273 set { Response.ContentType = value; }
276 protected string ContentType {
277 set { Response.ContentType = value; }
281 protected override HttpContext Context {
283 if (_context == null)
284 return HttpContext.Current;
291 [EditorBrowsable (EditorBrowsableState.Advanced)]
292 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
293 [BrowsableAttribute (false)]
294 public string Culture {
295 get { return Thread.CurrentThread.CurrentCulture.Name; }
296 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
299 [EditorBrowsable (EditorBrowsableState.Never)]
300 protected string Culture {
301 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
306 public virtual bool EnableEventValidation {
307 get { return _eventValidation; }
309 if (_lifeCycle > PageLifeCycle.Init)
310 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
311 _eventValidation = value;
315 internal PageLifeCycle LifeCycle {
316 get { return _lifeCycle; }
321 public override bool EnableViewState {
322 get { return _viewState; }
323 set { _viewState = value; }
327 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
328 [BrowsableAttribute (false)]
330 [EditorBrowsable (EditorBrowsableState.Never)]
336 bool EnableViewStateMac {
337 get { return _viewStateMac; }
338 set { _viewStateMac = value; }
342 internal bool EnableViewStateMacInternal {
343 get { return _viewStateMac; }
344 set { _viewStateMac = value; }
348 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
349 [Browsable (false), DefaultValue ("")]
350 [WebSysDescription ("The URL of a page used for error redirection.")]
351 public string ErrorPage {
352 get { return _errorPage; }
354 HttpContext ctx = Context;
358 ctx.ErrorPage = value;
365 [EditorBrowsable (EditorBrowsableState.Never)]
366 protected ArrayList FileDependencies {
368 if (Response != null)
369 Response.AddFileDependencies (value);
375 [EditorBrowsable (EditorBrowsableState.Never)]
377 public override string ID {
378 get { return base.ID; }
379 set { base.ID = value; }
382 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
384 public bool IsPostBack {
389 return _requestValueCollection != null;
394 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
395 public bool IsReusable {
396 get { return false; }
399 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
401 public bool IsValid {
404 throw new HttpException (Locale.GetText ("Page hasn't been validated."));
407 foreach (IValidator val in Validators)
412 return ValidateCollection (_validators);
417 public IDictionary Items {
420 items = new Hashtable ();
426 [EditorBrowsable (EditorBrowsableState.Never)]
428 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
429 [BrowsableAttribute (false)]
431 get { return Thread.CurrentThread.CurrentCulture.LCID; }
432 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
436 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
442 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
443 public bool MaintainScrollPositionOnPostBack {
444 get { return _maintainScrollPositionOnPostBack; }
445 set { _maintainScrollPositionOnPostBack = value; }
450 public PageAdapter PageAdapter {
452 return (PageAdapter)Adapter;
458 internal string theForm {
464 internal bool IsMultiForm {
465 get { return false; }
469 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
471 public HttpRequest Request {
473 if (_request == null)
474 throw new HttpException("Request is not available in this context.");
479 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
481 public HttpResponse Response {
483 if (_response == null)
484 throw new HttpException ("Response is not available in this context.");
489 [EditorBrowsable (EditorBrowsableState.Never)]
491 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
492 [BrowsableAttribute (false)]
493 public string ResponseEncoding {
494 get { return Response.ContentEncoding.WebName; }
495 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
498 protected string ResponseEncoding {
499 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
503 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
505 public HttpServerUtility Server {
506 get { return Context.Server; }
509 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
511 public virtual HttpSessionState Session {
513 if (_session != null)
517 _session = Context.Session;
519 // ignore, should not throw
522 if (_session == null)
523 throw new HttpException ("Session state can only be used " +
524 "when enableSessionState is set to true, either " +
525 "in a configuration file or in the Page directive.");
532 [FilterableAttribute (false)]
536 public bool SmartNavigation {
537 get { return _smartNavigation; }
538 set { _smartNavigation = value; }
542 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
545 public virtual string StyleSheetTheme {
546 get { return _styleSheetTheme; }
547 set { _styleSheetTheme = value; }
551 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
552 public virtual string Theme {
553 get { return _theme; }
554 set { _theme = value; }
557 void InitializeStyleSheet ()
559 if (_styleSheetTheme == null) {
560 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
562 _styleSheetTheme = ps.StyleSheetTheme;
564 if (_styleSheetTheme != null && _styleSheetTheme != "")
565 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, Context);
568 void InitializeTheme ()
570 if (_theme == null) {
571 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
575 if (_theme != null && _theme != "") {
576 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, Context);
577 _pageTheme.SetPage (this);
586 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
587 public string Title {
589 if (_title == null) {
590 if (htmlHeader != null)
591 return htmlHeader.Title;
597 if (htmlHeader != null)
598 htmlHeader.Title = value;
605 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
607 public TraceContext Trace {
608 get { return Context.Trace; }
611 [EditorBrowsable (EditorBrowsableState.Never)]
613 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
614 [BrowsableAttribute (false)]
615 public bool TraceEnabled {
616 get { return Trace.IsEnabled; }
617 set { Trace.IsEnabled = value; }
620 protected bool TraceEnabled {
621 set { Trace.IsEnabled = value; }
625 [EditorBrowsable (EditorBrowsableState.Never)]
627 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
628 [BrowsableAttribute (false)]
629 public TraceMode TraceModeValue {
630 get { return Trace.TraceMode; }
631 set { Trace.TraceMode = value; }
634 protected TraceMode TraceModeValue {
635 set { Trace.TraceMode = value; }
639 [EditorBrowsable (EditorBrowsableState.Never)]
640 protected int TransactionMode {
642 get { return _transactionMode; }
644 set { _transactionMode = value; }
649 // This method is here just to remove the warning about "_transactionMode" not being
650 // used. We probably will use it internally at some point.
652 internal int GetTransactionMode ()
654 return _transactionMode;
659 [EditorBrowsable (EditorBrowsableState.Advanced)]
660 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
661 [BrowsableAttribute (false)]
662 public string UICulture {
663 get { return Thread.CurrentThread.CurrentUICulture.Name; }
664 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
667 [EditorBrowsable (EditorBrowsableState.Never)]
668 protected string UICulture {
669 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
673 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
675 public IPrincipal User {
676 get { return Context.User; }
679 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
681 public ValidatorCollection Validators {
683 if (_validators == null)
684 _validators = new ValidatorCollection ();
689 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
691 public string ViewStateUserKey {
692 get { return viewStateUserKey; }
693 set { viewStateUserKey = value; }
697 public override bool Visible {
698 get { return base.Visible; }
699 set { base.Visible = value; }
707 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
711 CultureInfo ret = null;
712 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
714 if (Context.IsPortletRequest)
717 string[] languages = Request.UserLanguages;
719 if (languages != null && languages.Length > 0)
720 ret = CultureInfo.CreateSpecificCulture (languages[0]);
727 ret = CultureInfo.CreateSpecificCulture (culture);
733 [EditorBrowsable (EditorBrowsableState.Never)]
734 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
738 throw new NotImplementedException ();
741 [EditorBrowsable (EditorBrowsableState.Never)]
742 protected void AspCompatEndProcessRequest (IAsyncResult result)
744 throw new NotImplementedException ();
747 [EditorBrowsable (EditorBrowsableState.Advanced)]
748 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
750 return new HtmlTextWriter (tw);
753 [EditorBrowsable (EditorBrowsableState.Never)]
754 public void DesignerInitialize ()
756 InitRecursive (null);
759 [EditorBrowsable (EditorBrowsableState.Advanced)]
760 protected virtual NameValueCollection DeterminePostBackMode ()
762 HttpRequest req = Request;
766 NameValueCollection coll = null;
767 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
770 else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
774 coll = req.QueryString;
776 WebROCollection c = (WebROCollection) coll;
777 allow_load = !c.GotID;
779 c.ID = GetTypeHashCode ();
781 allow_load = (c.ID == GetTypeHashCode ());
783 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
790 public override Control FindControl (string id) {
794 return base.FindControl (id);
801 [EditorBrowsable (EditorBrowsableState.Advanced)]
802 public string GetPostBackClientEvent (Control control, string argument)
804 return scriptManager.GetPostBackEventReference (control, argument);
810 [EditorBrowsable (EditorBrowsableState.Advanced)]
811 public string GetPostBackClientHyperlink (Control control, string argument)
813 return scriptManager.GetPostBackClientHyperlink (control, argument);
819 [EditorBrowsable (EditorBrowsableState.Advanced)]
820 public string GetPostBackEventReference (Control control)
822 return scriptManager.GetPostBackEventReference (control, "");
828 [EditorBrowsable (EditorBrowsableState.Advanced)]
829 public string GetPostBackEventReference (Control control, string argument)
831 return scriptManager.GetPostBackEventReference (control, argument);
834 internal void RequiresPostBackScript ()
837 if (requiresPostBackScript)
839 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
840 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
842 requiresPostBackScript = true;
845 [EditorBrowsable (EditorBrowsableState.Never)]
846 public virtual int GetTypeHashCode ()
852 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
853 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
855 if (cacheSettings.Enabled)
856 InitOutputCache(cacheSettings.Duration,
857 cacheSettings.VaryByHeader,
858 cacheSettings.VaryByCustom,
859 cacheSettings.Location,
860 cacheSettings.VaryByParam);
864 [EditorBrowsable (EditorBrowsableState.Never)]
865 protected virtual void InitOutputCache (int duration,
868 OutputCacheLocation location,
871 HttpCachePolicy cache = Response.Cache;
872 bool set_vary = false;
873 HttpContext ctx = Context;
874 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
877 case OutputCacheLocation.Any:
878 cache.SetCacheability (HttpCacheability.Public);
879 cache.SetMaxAge (new TimeSpan (0, 0, duration));
880 cache.SetLastModified (timestamp);
883 case OutputCacheLocation.Client:
884 cache.SetCacheability (HttpCacheability.Private);
885 cache.SetMaxAge (new TimeSpan (0, 0, duration));
886 cache.SetLastModified (timestamp);
888 case OutputCacheLocation.Downstream:
889 cache.SetCacheability (HttpCacheability.Public);
890 cache.SetMaxAge (new TimeSpan (0, 0, duration));
891 cache.SetLastModified (timestamp);
893 case OutputCacheLocation.Server:
894 cache.SetCacheability (HttpCacheability.Server);
897 case OutputCacheLocation.None:
902 if (varyByCustom != null)
903 cache.SetVaryByCustom (varyByCustom);
905 if (varyByParam != null && varyByParam.Length > 0) {
906 string[] prms = varyByParam.Split (';');
907 foreach (string p in prms)
908 cache.VaryByParams [p.Trim ()] = true;
909 cache.VaryByParams.IgnoreParams = false;
911 cache.VaryByParams.IgnoreParams = true;
914 if (varyByHeader != null && varyByHeader.Length > 0) {
915 string[] hdrs = varyByHeader.Split (';');
916 foreach (string h in hdrs)
917 cache.VaryByHeaders [h.Trim ()] = true;
921 cache.Duration = duration;
922 cache.SetExpires (timestamp.AddSeconds (duration));
928 [EditorBrowsable (EditorBrowsableState.Advanced)]
930 public bool IsClientScriptBlockRegistered (string key)
932 return scriptManager.IsClientScriptBlockRegistered (key);
938 [EditorBrowsable (EditorBrowsableState.Advanced)]
940 public bool IsStartupScriptRegistered (string key)
942 return scriptManager.IsStartupScriptRegistered (key);
945 public string MapPath (string virtualPath)
947 return Request.MapPath (virtualPath);
951 protected internal override void Render (HtmlTextWriter writer) {
952 if (MaintainScrollPositionOnPostBack) {
953 ClientScript.RegisterWebFormClientScript ();
955 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
956 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
958 string webForm = IsMultiForm ? theForm + "." : null;
960 StringBuilder script = new StringBuilder ();
961 script.AppendLine ("<script type=\"text/javascript\">");
962 script.AppendLine ("<!--");
963 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
964 script.AppendLine (theForm + ".submit = function () { " + webForm + "WebForm_SaveScrollPositionSubmit(); }");
965 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
966 script.AppendLine (theForm + ".onsubmit = function () { " + webForm + "WebForm_SaveScrollPositionOnSubmit(); }");
968 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
969 script.AppendLine ("window.onload = function () { " + webForm + "WebForm_RestoreScrollPosition (); };");
971 script.AppendLine ("// -->");
972 script.AppendLine ("</script>");
974 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
976 base.Render (writer);
980 private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
983 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
984 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
988 ClientScriptManager.WriteBeginScriptBlock (writer);
991 RenderClientScriptFormDeclaration (writer, formUniqueID);
994 writer.WriteLine ("{0}._form = {0};", theForm);
995 writer.Write (theForm + ".");
997 writer.WriteLine ("window._form = {0};", theForm);
999 writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
1001 writer.WriteLine ("\tif(this._form.onsubmit && this._form.onsubmit() == false) return;");
1003 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1005 writer.WriteLine ("\tthis._form.{0}.value = eventTarget;", postEventSourceID);
1006 writer.WriteLine ("\tthis._form.{0}.value = eventArgument;", postEventArgumentID);
1007 writer.WriteLine ("\tthis._form.submit();");
1008 writer.WriteLine ("}");
1009 ClientScriptManager.WriteEndScriptBlock (writer);
1012 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1014 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1015 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1016 writer.WriteLine ("\t{0}._instanceVariableName = '{0}';", theForm);
1018 string serverUrl = Context.ServletResponse.encodeURL (Request.RawUrl);
1019 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1020 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1021 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1025 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1028 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1030 renderingForm = true;
1031 writer.WriteLine ();
1034 ClientScriptManager.WriteBeginScriptBlock (writer);
1035 RenderClientScriptFormDeclaration (writer, formUniqueID);
1036 ClientScriptManager.WriteEndScriptBlock (writer);
1039 if (handleViewState)
1040 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1042 scriptManager.WriteHiddenFields (writer);
1043 if (requiresPostBackScript) {
1044 RenderPostBackScript (writer, formUniqueID);
1045 postBackScriptRendered = true;
1048 scriptManager.WriteWebFormClientScript (writer);
1050 scriptManager.WriteClientScriptBlocks (writer);
1053 internal IStateFormatter GetFormatter ()
1055 return new ObjectStateFormatter (this);
1058 internal string GetSavedViewState ()
1060 return _savedViewState;
1063 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1066 scriptManager.SaveEventValidationState ();
1067 scriptManager.WriteExpandoAttributes (writer);
1069 scriptManager.WriteHiddenFields (writer);
1070 if (!postBackScriptRendered && requiresPostBackScript)
1071 RenderPostBackScript (writer, formUniqueID);
1073 scriptManager.WriteWebFormClientScript (writer);
1076 scriptManager.WriteArrayDeclares (writer);
1077 scriptManager.WriteStartupScriptBlocks (writer);
1078 renderingForm = false;
1079 postBackScriptRendered = false;
1082 private void ProcessPostData (NameValueCollection data, bool second)
1084 NameValueCollection requestValues = _requestValueCollection == null ?
1085 new NameValueCollection () :
1086 _requestValueCollection;
1088 if (data != null && data.Count > 0) {
1089 Hashtable used = new Hashtable ();
1090 foreach (string id in data.AllKeys){
1091 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
1094 string real_id = id;
1095 int dot = real_id.IndexOf ('.');
1097 real_id = real_id.Substring (0, dot);
1099 if (real_id == null || used.ContainsKey (real_id))
1102 used.Add (real_id, real_id);
1104 Control ctrl = FindControl (real_id);
1106 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1107 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1111 RegisterRequiresRaiseEvent (pbeh);
1115 if (pbdh.LoadPostData (real_id, requestValues) == true) {
1116 if (requiresPostDataChanged == null)
1117 requiresPostDataChanged = new ArrayList ();
1118 requiresPostDataChanged.Add (pbdh);
1121 if (_requiresPostBackCopy != null)
1122 _requiresPostBackCopy.Remove (real_id);
1124 } else if (!second) {
1125 if (secondPostData == null)
1126 secondPostData = new NameValueCollection ();
1127 secondPostData.Add (real_id, data [id]);
1132 ArrayList list1 = null;
1133 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1134 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1135 foreach (string id in handlers) {
1136 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1138 _requiresPostBackCopy.Remove (id);
1139 if (pbdh.LoadPostData (id, requestValues)) {
1140 if (requiresPostDataChanged == null)
1141 requiresPostDataChanged = new ArrayList ();
1143 requiresPostDataChanged.Add (pbdh);
1145 } else if (!second) {
1147 list1 = new ArrayList ();
1152 _requiresPostBackCopy = second ? null : list1;
1154 secondPostData = null;
1157 [EditorBrowsable (EditorBrowsableState.Never)]
1159 public virtual void ProcessRequest (HttpContext context)
1161 public void ProcessRequest (HttpContext context)
1165 _lifeCycle = PageLifeCycle.Unknown;
1169 _application = context.Application;
1170 _response = context.Response;
1171 _request = context.Request;
1172 _cache = context.Cache;
1174 if (clientTarget != null)
1175 Request.ClientTarget = clientTarget;
1177 WireupAutomaticEvents ();
1178 //-- Control execution lifecycle in the docs
1180 // Save culture information because it can be modified in FrameworkInitialize()
1181 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1182 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1183 FrameworkInitialize ();
1184 context.ErrorPage = _errorPage;
1187 InternalProcessRequest ();
1188 } catch (ThreadAbortException) {
1189 // Do nothing, just ignore it by now.
1190 } catch (Exception e) {
1191 context.AddError (e); // OnError might access LastError
1192 OnError (EventArgs.Empty);
1193 context.ClearError (e);
1194 // We want to remove that error, as we're rethrowing to stop
1195 // further processing.
1196 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1201 _lifeCycle = PageLifeCycle.Unload;
1204 UnloadRecursive (true);
1206 _lifeCycle = PageLifeCycle.End;
1209 if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1210 Thread.CurrentThread.CurrentCulture = culture;
1212 if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1213 Thread.CurrentThread.CurrentUICulture = uiculture;
1218 delegate void ProcessRequestDelegate (HttpContext context);
1220 private sealed class DummyAsyncResult : IAsyncResult
1222 readonly object state;
1223 readonly WaitHandle asyncWaitHandle;
1224 readonly bool completedSynchronously;
1225 readonly bool isCompleted;
1227 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1229 this.isCompleted = isCompleted;
1230 this.completedSynchronously = completedSynchronously;
1233 asyncWaitHandle = new ManualResetEvent (true);
1236 asyncWaitHandle = new ManualResetEvent (false);
1240 #region IAsyncResult Members
1242 public object AsyncState {
1243 get { return state; }
1246 public WaitHandle AsyncWaitHandle {
1247 get { return asyncWaitHandle; }
1250 public bool CompletedSynchronously {
1251 get { return completedSynchronously; }
1254 public bool IsCompleted {
1255 get { return isCompleted; }
1261 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1263 ProcessRequest (context);
1264 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1266 if (callback != null) {
1267 callback (asyncResult);
1273 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1277 internal void ProcessCrossPagePostBack (HttpContext context)
1279 isCrossPagePostBack = true;
1280 ProcessRequest (context);
1284 void InternalProcessRequest ()
1286 _requestValueCollection = this.DeterminePostBackMode();
1289 _lifeCycle = PageLifeCycle.Start;
1290 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1291 if (_requestValueCollection != null) {
1292 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1293 _doLoadPreviousPage = true;
1296 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1297 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1298 //isPostBack = !isCallback;
1301 string lastFocus = _requestValueCollection [LastFocusID];
1302 if (!String.IsNullOrEmpty (lastFocus)) {
1303 _focusedControlID = UniqueID2ClientID (lastFocus);
1307 HttpContext ctx = Context;
1309 // if request was transfered from other page - track Prev. Page
1310 previousPage = ctx.LastPage;
1311 ctx.LastPage = this;
1313 _lifeCycle = PageLifeCycle.PreInit;
1314 OnPreInit (EventArgs.Empty);
1318 _lifeCycle = PageLifeCycle.Init;
1320 Trace.Write ("aspx.page", "Begin Init");
1321 InitRecursive (null);
1322 Trace.Write ("aspx.page", "End Init");
1325 _lifeCycle = PageLifeCycle.InitComplete;
1326 OnInitComplete (EventArgs.Empty);
1329 renderingForm = false;
1331 if (IsPostBack || IsCallback) {
1332 _lifeCycle = PageLifeCycle.PreLoad;
1333 if (_requestValueCollection != null)
1334 scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
1338 Trace.Write ("aspx.page", "Begin LoadViewState");
1339 LoadPageViewState ();
1340 Trace.Write ("aspx.page", "End LoadViewState");
1341 Trace.Write ("aspx.page", "Begin ProcessPostData");
1345 ProcessPostData (_requestValueCollection, false);
1346 Trace.Write ("aspx.page", "End ProcessPostData");
1350 OnPreLoad (EventArgs.Empty);
1351 _lifeCycle = PageLifeCycle.Load;
1359 if (IsPostBack || IsCallback) {
1360 _lifeCycle = PageLifeCycle.ControlEvents;
1364 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1365 ProcessPostData (secondPostData, true);
1366 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1367 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1368 RaiseChangedEvents ();
1369 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1370 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1371 RaisePostBackEvents ();
1372 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1376 _lifeCycle = PageLifeCycle.LoadComplete;
1377 OnLoadComplete (EventArgs.Empty);
1379 if (IsCrossPagePostBack)
1383 string result = ProcessCallbackData ();
1384 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1385 callbackOutput.Write (result);
1386 callbackOutput.Flush ();
1390 _lifeCycle = PageLifeCycle.PreRender;
1393 Trace.Write ("aspx.page", "Begin PreRender");
1394 PreRenderRecursiveInternal ();
1395 Trace.Write ("aspx.page", "End PreRender");
1398 ExecuteRegisteredAsyncTasks ();
1400 _lifeCycle = PageLifeCycle.PreRenderComplete;
1401 OnPreRenderComplete (EventArgs.Empty);
1404 Trace.Write ("aspx.page", "Begin SaveViewState");
1405 SavePageViewState ();
1406 Trace.Write ("aspx.page", "End SaveViewState");
1409 _lifeCycle = PageLifeCycle.SaveStateComplete;
1410 OnSaveStateComplete (EventArgs.Empty);
1412 if (OnSaveStateCompleteForPortlet ())
1414 #endif // TARGET_J2EE
1418 _lifeCycle = PageLifeCycle.Render;
1419 scriptManager.ResetEventValidationState ();
1423 Trace.Write ("aspx.page", "Begin Render");
1424 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1425 RenderControl (output);
1426 Trace.Write ("aspx.page", "End Render");
1429 private void RenderTrace ()
1431 TraceManager traceManager = HttpRuntime.TraceManager;
1433 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1438 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1441 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1442 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1443 Trace.Render (output);
1448 bool CheckForValidationSupport (Control targetControl)
1450 if (targetControl == null)
1452 Type type = targetControl.GetType ();
1453 object[] attributes = type.GetCustomAttributes (false);
1454 foreach (object attr in attributes)
1455 if (attr is SupportsEventValidationAttribute)
1461 void RaisePostBackEvents ()
1464 Control targetControl;
1466 if (requiresRaiseEvent != null) {
1467 RaisePostBackEvent (requiresRaiseEvent, null);
1471 NameValueCollection postdata = _requestValueCollection;
1472 if (postdata == null)
1475 string eventTarget = postdata [postEventSourceID];
1476 if (eventTarget == null || eventTarget.Length == 0) {
1482 targetControl = FindControl (eventTarget);
1483 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1485 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1491 string eventArgument = postdata [postEventArgumentID];
1492 RaisePostBackEvent (target, eventArgument);
1495 internal void RaiseChangedEvents ()
1497 if (requiresPostDataChanged == null)
1500 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1501 ipdh.RaisePostDataChangedEvent ();
1503 requiresPostDataChanged = null;
1506 [EditorBrowsable (EditorBrowsableState.Advanced)]
1507 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1510 Control targetControl = sourceControl as Control;
1511 if (targetControl != null && CheckForValidationSupport (targetControl))
1512 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1514 sourceControl.RaisePostBackEvent (eventArgument);
1520 [EditorBrowsable (EditorBrowsableState.Advanced)]
1521 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1523 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1529 [EditorBrowsable (EditorBrowsableState.Advanced)]
1530 public virtual void RegisterClientScriptBlock (string key, string script)
1532 scriptManager.RegisterClientScriptBlock (key, script);
1538 [EditorBrowsable (EditorBrowsableState.Advanced)]
1539 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1541 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1544 [MonoTODO("Not implemented, Used in HtmlForm")]
1545 internal void RegisterClientScriptFile (string a, string b, string c)
1547 throw new NotImplementedException ();
1553 [EditorBrowsable (EditorBrowsableState.Advanced)]
1554 public void RegisterOnSubmitStatement (string key, string script)
1556 scriptManager.RegisterOnSubmitStatement (key, script);
1559 internal string GetSubmitStatements ()
1561 return scriptManager.WriteSubmitStatements ();
1564 [EditorBrowsable (EditorBrowsableState.Advanced)]
1565 public void RegisterRequiresPostBack (Control control)
1568 if (!(control is IPostBackDataHandler))
1569 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1572 if (_requiresPostBack == null)
1573 _requiresPostBack = new ArrayList ();
1575 if (_requiresPostBack.Contains (control.UniqueID))
1578 _requiresPostBack.Add (control.UniqueID);
1581 [EditorBrowsable (EditorBrowsableState.Advanced)]
1582 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1584 requiresRaiseEvent = control;
1590 [EditorBrowsable (EditorBrowsableState.Advanced)]
1591 public virtual void RegisterStartupScript (string key, string script)
1593 scriptManager.RegisterStartupScript (key, script);
1596 [EditorBrowsable (EditorBrowsableState.Advanced)]
1597 public void RegisterViewStateHandler ()
1599 handleViewState = true;
1602 [EditorBrowsable (EditorBrowsableState.Advanced)]
1603 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1605 PageStatePersister persister = this.PageStatePersister;
1606 if (persister == null)
1608 Pair pair = viewState as Pair;
1610 persister.ViewState = pair.First;
1611 persister.ControlState = pair.Second;
1613 persister.ViewState = viewState;
1617 internal string RawViewState {
1619 NameValueCollection postdata = _requestValueCollection;
1621 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1624 if (view_state == "")
1628 set { _savedViewState = value; }
1636 PageStatePersister PageStatePersister {
1638 if (page_state_persister == null)
1639 page_state_persister = new HiddenFieldPageStatePersister (this);
1640 return page_state_persister;
1644 [EditorBrowsable (EditorBrowsableState.Advanced)]
1645 protected virtual object LoadPageStateFromPersistenceMedium ()
1647 PageStatePersister persister = this.PageStatePersister;
1648 if (persister == null)
1651 return new Pair (persister.ViewState, persister.ControlState);
1654 internal void LoadPageViewState()
1656 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1657 if (sState != null) {
1660 LoadPageControlState (sState.Second);
1662 Pair vsr = sState.First as Pair;
1664 LoadViewStateRecursive (vsr.First);
1665 _requiresPostBackCopy = vsr.Second as ArrayList;
1671 internal void SavePageViewState ()
1673 if (!handleViewState)
1677 object controlState = SavePageControlState ();
1680 object viewState = SaveViewStateRecursive ();
1681 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1684 if (viewState != null || reqPostback != null)
1685 vsr = new Pair (viewState, reqPostback);
1686 Pair pair = new Pair ();
1690 pair.Second = controlState;
1694 if (pair.First == null && pair.Second == null)
1695 SavePageStateToPersistenceMedium (null);
1697 SavePageStateToPersistenceMedium (pair);
1701 public virtual void Validate ()
1703 is_validated = true;
1704 ValidateCollection (_validators);
1708 internal bool AreValidatorsUplevel () {
1709 return AreValidatorsUplevel (String.Empty);
1712 internal bool AreValidatorsUplevel (string valGroup)
1714 internal virtual bool AreValidatorsUplevel ()
1717 bool uplevel = false;
1719 foreach (IValidator v in Validators) {
1720 BaseValidator bv = v as BaseValidator;
1721 if (bv == null) continue;
1724 if (valGroup != bv.ValidationGroup)
1727 if (bv.GetRenderUplevel()) {
1736 bool ValidateCollection (ValidatorCollection validators)
1739 if (!_eventValidation)
1743 if (validators == null || validators.Count == 0)
1746 bool all_valid = true;
1747 foreach (IValidator v in validators){
1749 if (v.IsValid == false)
1756 [EditorBrowsable (EditorBrowsableState.Advanced)]
1757 public virtual void VerifyRenderingInServerForm (Control control)
1759 if (Context == null)
1766 throw new HttpException ("Control '" +
1769 control.GetType ().Name +
1770 "' must be placed inside a form tag with runat=server.");
1773 protected override void FrameworkInitialize ()
1775 base.FrameworkInitialize ();
1777 InitializeStyleSheet ();
1788 ClientScriptManager ClientScript {
1789 get { return scriptManager; }
1794 static readonly object InitCompleteEvent = new object ();
1795 static readonly object LoadCompleteEvent = new object ();
1796 static readonly object PreInitEvent = new object ();
1797 static readonly object PreLoadEvent = new object ();
1798 static readonly object PreRenderCompleteEvent = new object ();
1799 static readonly object SaveStateCompleteEvent = new object ();
1801 const int initcomplete_mask = 1;
1802 const int loadcomplete_mask = 1 << 1;
1803 const int preinit_mask = 1 << 2;
1804 const int preload_mask = 1 << 3;
1805 const int prerendercomplete_mask = 1 << 4;
1806 const int savestatecomplete_mask = 1 << 5;
1808 [EditorBrowsable (EditorBrowsableState.Advanced)]
1809 public event EventHandler InitComplete {
1811 event_mask |= initcomplete_mask;
1812 Events.AddHandler (InitCompleteEvent, value);
1814 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1817 [EditorBrowsable (EditorBrowsableState.Advanced)]
1818 public event EventHandler LoadComplete {
1820 event_mask |= loadcomplete_mask;
1821 Events.AddHandler (LoadCompleteEvent, value);
1823 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1826 public event EventHandler PreInit {
1828 event_mask |= preinit_mask;
1829 Events.AddHandler (PreInitEvent, value);
1831 remove { Events.RemoveHandler (PreInitEvent, value); }
1834 [EditorBrowsable (EditorBrowsableState.Advanced)]
1835 public event EventHandler PreLoad {
1837 event_mask |= preload_mask;
1838 Events.AddHandler (PreLoadEvent, value);
1840 remove { Events.RemoveHandler (PreLoadEvent, value); }
1843 [EditorBrowsable (EditorBrowsableState.Advanced)]
1844 public event EventHandler PreRenderComplete {
1846 event_mask |= prerendercomplete_mask;
1847 Events.AddHandler (PreRenderCompleteEvent, value);
1849 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1852 [EditorBrowsable (EditorBrowsableState.Advanced)]
1853 public event EventHandler SaveStateComplete {
1855 event_mask |= savestatecomplete_mask;
1856 Events.AddHandler (SaveStateCompleteEvent, value);
1858 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1861 protected virtual void OnInitComplete (EventArgs e)
1863 if ((event_mask & initcomplete_mask) != 0) {
1864 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1865 if (eh != null) eh (this, e);
1869 protected virtual void OnLoadComplete (EventArgs e)
1871 if ((event_mask & loadcomplete_mask) != 0) {
1872 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1873 if (eh != null) eh (this, e);
1877 protected virtual void OnPreInit (EventArgs e)
1879 if ((event_mask & preinit_mask) != 0) {
1880 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1881 if (eh != null) eh (this, e);
1885 protected virtual void OnPreLoad (EventArgs e)
1887 if ((event_mask & preload_mask) != 0) {
1888 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1889 if (eh != null) eh (this, e);
1893 protected virtual void OnPreRenderComplete (EventArgs e)
1895 if ((event_mask & prerendercomplete_mask) != 0) {
1896 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1897 if (eh != null) eh (this, e);
1902 if (!Form.DetermineRenderUplevel ())
1905 /* figure out if we have some control we're going to focus */
1906 if (String.IsNullOrEmpty (_focusedControlID)) {
1907 _focusedControlID = Form.DefaultFocus;
1908 if (String.IsNullOrEmpty (_focusedControlID))
1909 _focusedControlID = Form.DefaultButton;
1912 if (!String.IsNullOrEmpty (_focusedControlID)) {
1913 ClientScript.RegisterWebFormClientScript ();
1914 ClientScript.RegisterStartupScript ("HtmlForm-DefaultButton-StartupScript",
1915 String.Format ("<script type=\"text/javascript\">\n" +
1917 "WebForm_AutoFocus('{0}');// -->\n" +
1918 "</script>\n", _focusedControlID));
1921 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1922 ClientScript.RegisterWebFormClientScript ();
1923 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1924 "WebForm_ReEnableControls(this);");
1928 internal void RegisterEnabledControl (Control control)
1930 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1932 _hasEnabledControlArray = true;
1933 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Format ("'{0}'", control.ClientID));
1936 protected virtual void OnSaveStateComplete (EventArgs e)
1938 if ((event_mask & savestatecomplete_mask) != 0) {
1939 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1940 if (eh != null) eh (this, e);
1944 public HtmlForm Form {
1945 get { return _form; }
1948 internal void RegisterForm (HtmlForm form)
1953 [BrowsableAttribute (false)]
1954 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1955 public Page PreviousPage {
1957 if (_doLoadPreviousPage) {
1958 _doLoadPreviousPage = false;
1959 LoadPreviousPageReference ();
1961 return previousPage;
1966 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1967 [BrowsableAttribute (false)]
1968 public bool IsCallback {
1969 get { return isCallback; }
1972 [BrowsableAttribute (false)]
1973 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1974 public bool IsCrossPagePostBack {
1975 get { return isCrossPagePostBack; }
1978 public new virtual char IdSeparator {
1980 //TODO: why override?
1981 return base.IdSeparator;
1985 string ProcessCallbackData ()
1987 string callbackTarget = _requestValueCollection [CallbackSourceID];
1988 if (callbackTarget == null || callbackTarget.Length == 0)
1989 throw new HttpException ("Callback target not provided.");
1991 Control targetControl = FindControl (callbackTarget);
1992 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
1994 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
1996 string callbackEventError = String.Empty;
1997 string callBackResult;
1998 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2001 target.RaiseCallbackEvent (callbackArgument);
2003 catch (Exception ex) {
2004 callbackEventError = String.Format ("e{0}", ex.Message);
2008 callBackResult = target.GetCallbackResult ();
2010 catch (Exception ex) {
2011 return String.Format ("e{0}", ex.Message);
2014 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2015 return String.Format ("{0}{1}|{2}{3}", callbackEventError, eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
2018 [BrowsableAttribute (false)]
2019 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2020 public HtmlHead Header {
2021 get { return htmlHeader; }
2024 internal void SetHeader (HtmlHead header)
2026 htmlHeader = header;
2027 if (_title != null) {
2028 htmlHeader.Title = _title;
2033 protected bool AsyncMode {
2034 get { return asyncMode; }
2035 set { asyncMode = value; }
2038 public TimeSpan AsyncTimeout {
2039 get { return asyncTimeout; }
2040 set { asyncTimeout = value; }
2043 public bool IsAsync {
2044 get { return AsyncMode; }
2047 [MonoTODO ("Not Implemented")]
2048 protected internal virtual string UniqueFilePathSuffix {
2050 throw new NotImplementedException ();
2054 [MonoTODO ("Not Implemented")]
2055 public int MaxPageStateFieldLength {
2057 throw new NotImplementedException ();
2060 throw new NotImplementedException ();
2064 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2066 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2069 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2072 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2075 if (_lifeCycle >= PageLifeCycle.PreRender) {
2076 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
2079 if (beginHandler == null) {
2080 throw new ArgumentNullException ("beginHandler");
2083 if (endHandler == null) {
2084 throw new ArgumentNullException ("endHandler");
2087 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2090 private List<PageAsyncTask> ParallelTasks {
2092 if (parallelTasks == null) {
2093 parallelTasks = new List<PageAsyncTask>();
2095 return parallelTasks;
2099 private List<PageAsyncTask> SerialTasks {
2101 if (serialTasks == null) {
2102 serialTasks = new List<PageAsyncTask> ();
2108 public void RegisterAsyncTask (PageAsyncTask task)
2111 throw new ArgumentNullException ("task");
2114 if (task.ExecuteInParallel) {
2115 ParallelTasks.Add (task);
2118 SerialTasks.Add (task);
2122 public void ExecuteRegisteredAsyncTasks ()
2124 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2125 (serialTasks == null || serialTasks.Count == 0)){
2129 if (parallelTasks != null) {
2130 DateTime startExecution = DateTime.Now;
2131 List<PageAsyncTask> localParallelTasks = parallelTasks;
2132 parallelTasks = null; // Shouldn't execute tasks twice
2133 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2134 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2135 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2136 if (result.CompletedSynchronously) {
2137 parallelTask.EndHandler (result);
2140 asyncResults.Add (result);
2144 if (asyncResults.Count > 0) {
2146 TimeSpan timeout = AsyncTimeout;
2147 long t1 = DateTime.Now.Ticks;
2148 bool signalled = true;
2149 for (int i = 0; i < asyncResults.Count; i++) {
2150 if (asyncResults [i].IsCompleted)
2154 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2157 long t2 = DateTime.Now.Ticks;
2158 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2159 if (timeout.Ticks <= 0)
2163 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2167 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2169 for (i = 0; i < asyncResults.Count; i++) {
2170 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2172 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2173 if (!allSignalled) {
2174 for (i = 0; i < asyncResults.Count; i++) {
2175 if (!asyncResults [i].IsCompleted) {
2176 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2182 DateTime endWait = DateTime.Now;
2183 TimeSpan elapsed = endWait - startExecution;
2184 if (elapsed <= AsyncTimeout) {
2185 AsyncTimeout -= elapsed;
2188 AsyncTimeout = TimeSpan.FromTicks(0);
2192 if (serialTasks != null) {
2193 List<PageAsyncTask> localSerialTasks = serialTasks;
2194 serialTasks = null; // Shouldn't execute tasks twice
2195 foreach (PageAsyncTask serialTask in localSerialTasks) {
2196 DateTime startExecution = DateTime.Now;
2198 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2199 if (result.CompletedSynchronously) {
2200 serialTask.EndHandler (result);
2203 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2204 if (!done && !result.IsCompleted) {
2205 serialTask.TimeoutHandler (result);
2208 DateTime endWait = DateTime.Now;
2209 TimeSpan elapsed = endWait - startExecution;
2210 if (elapsed <= AsyncTimeout) {
2211 AsyncTimeout -= elapsed;
2214 AsyncTimeout = TimeSpan.FromTicks (0);
2218 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2221 void EndAsyncTaskCallback (IAsyncResult result)
2223 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2224 task.EndHandler (result);
2227 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2229 Type htmlTextWriterType = typeof (HtmlTextWriter);
2231 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2232 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2235 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2236 if (constructor == null) {
2237 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2240 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2243 public ViewStateEncryptionMode ViewStateEncryptionMode {
2244 get { return viewStateEncryptionMode; }
2245 set { viewStateEncryptionMode = value; }
2248 public void RegisterRequiresViewStateEncryption ()
2250 controlRegisteredForViewStateEncryption = true;
2253 private static byte [] AES_IV = null;
2254 private static byte [] TripleDES_IV = null;
2255 private static object locker = new object ();
2256 private static bool isEncryptionInitialized = false;
2258 private static void InitializeEncryption ()
2260 if (isEncryptionInitialized) {
2265 if (isEncryptionInitialized) {
2269 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2270 AES_IV = new byte [16];
2271 TripleDES_IV = new byte [8];
2274 for (i = 0; i < AES_IV.Length; i++) {
2275 AES_IV [i] = (byte) iv_string [i];
2278 for (i = 0; i < TripleDES_IV.Length; i++) {
2279 TripleDES_IV [i] = (byte) iv_string [i];
2282 isEncryptionInitialized = true;
2286 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2288 ICryptoTransform transform = null;
2289 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2290 byte [] vk = config.ValidationKeyBytes;
2292 switch (config.Validation) {
2293 case MachineKeyValidation.SHA1:
2294 transform = SHA1.Create ();
2297 case MachineKeyValidation.MD5:
2298 transform = MD5.Create ();
2301 case MachineKeyValidation.AES:
2302 if (cryptoStreamMode == CryptoStreamMode.Read){
2303 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2305 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2309 case MachineKeyValidation.TripleDES:
2310 if (cryptoStreamMode == CryptoStreamMode.Read){
2311 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2313 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2321 internal bool NeedViewStateEncryption {
2323 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2324 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2325 controlRegisteredForViewStateEncryption));
2330 void ApplyMasterPage ()
2332 if (masterPageFile != null && masterPageFile.Length > 0) {
2333 ArrayList appliedMasterPageFiles = new ArrayList ();
2335 if (Master != null) {
2336 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2340 Controls.Add (Master);
2345 [DefaultValueAttribute ("")]
2346 public virtual string MasterPageFile {
2347 get { return masterPageFile; }
2349 masterPageFile = value;
2354 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2355 [BrowsableAttribute (false)]
2356 public MasterPage Master {
2358 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2361 if (masterPage == null)
2362 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2368 public void SetFocus (string clientID)
2370 if (String.IsNullOrEmpty (clientID))
2371 throw new ArgumentNullException ("control");
2373 if (_lifeCycle > PageLifeCycle.PreRender)
2374 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2377 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2379 _focusedControlID = clientID;
2382 public void SetFocus (Control control)
2384 if (control == null)
2385 throw new ArgumentNullException ("control");
2387 SetFocus (control.ClientID);
2390 [EditorBrowsable (EditorBrowsableState.Advanced)]
2391 public void RegisterRequiresControlState (Control control)
2393 if (control == null)
2394 throw new ArgumentNullException ("control");
2396 if (RequiresControlState (control))
2399 if (requireStateControls == null)
2400 requireStateControls = new ArrayList ();
2401 int n = requireStateControls.Add (control);
2403 if (_savedControlState == null || n >= _savedControlState.Length)
2406 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2407 if (parent.IsChildControlStateCleared)
2410 object state = _savedControlState [n];
2412 control.LoadControlState (state);
2415 public bool RequiresControlState (Control control)
2417 if (requireStateControls == null) return false;
2418 return requireStateControls.Contains (control);
2421 [EditorBrowsable (EditorBrowsableState.Advanced)]
2422 public void UnregisterRequiresControlState (Control control)
2424 if (requireStateControls != null)
2425 requireStateControls.Remove (control);
2428 public ValidatorCollection GetValidators (string validationGroup)
2430 string valgr = validationGroup;
2432 valgr = String.Empty;
2434 if (_validatorsByGroup == null) _validatorsByGroup = new Hashtable ();
2435 ValidatorCollection col = _validatorsByGroup [valgr] as ValidatorCollection;
2437 col = new ValidatorCollection ();
2438 _validatorsByGroup [valgr] = col;
2443 public virtual void Validate (string validationGroup)
2445 is_validated = true;
2446 if (validationGroup == null)
2447 ValidateCollection (_validatorsByGroup [String.Empty] as ValidatorCollection);
2448 else if (_validatorsByGroup != null) {
2449 ValidateCollection (_validatorsByGroup [validationGroup] as ValidatorCollection);
2453 object SavePageControlState ()
2455 if (requireStateControls == null) return null;
2456 object[] state = new object [requireStateControls.Count];
2458 bool allNull = true;
2459 for (int n=0; n<state.Length; n++) {
2460 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2461 if (state [n] != null) allNull = false;
2463 if (allNull) return null;
2467 void LoadPageControlState (object data)
2469 _savedControlState = (object []) data;
2471 if (requireStateControls == null) return;
2473 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2474 for (int n=0; n < max; n++) {
2475 Control ctl = (Control) requireStateControls [n];
2476 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2480 void LoadPreviousPageReference ()
2482 if (_requestValueCollection != null) {
2483 string prevPage = _requestValueCollection [PreviousPageID];
2484 if (prevPage != null) {
2485 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2486 previousPage.ProcessCrossPagePostBack (Context);
2492 Hashtable contentTemplates;
2493 [EditorBrowsable (EditorBrowsableState.Never)]
2494 protected internal void AddContentTemplate (string templateName, ITemplate template)
2496 if (contentTemplates == null)
2497 contentTemplates = new Hashtable ();
2498 contentTemplates [templateName] = template;
2501 PageTheme _pageTheme;
2502 internal PageTheme PageTheme {
2503 get { return _pageTheme; }
2506 PageTheme _styleSheetPageTheme;
2507 internal PageTheme StyleSheetPageTheme {
2508 get { return _styleSheetPageTheme; }
2513 internal void PushDataItemContext (object o) {
2514 if (dataItemCtx == null)
2515 dataItemCtx = new Stack ();
2517 dataItemCtx.Push (o);
2520 internal void PopDataItemContext () {
2521 if (dataItemCtx == null)
2522 throw new InvalidOperationException ();
2527 public object GetDataItem() {
2528 if (dataItemCtx == null || dataItemCtx.Count == 0)
2529 throw new InvalidOperationException ("No data item");
2531 return dataItemCtx.Peek ();
2534 protected internal override void OnInit (EventArgs e)
2538 ArrayList themes = new ArrayList();
2540 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2541 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2542 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2543 themes.AddRange (PageTheme.GetStyleSheets ());
2545 if (themes.Count > 0 && Header == null)
2546 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2548 foreach (string lss in themes) {
2549 HtmlLink hl = new HtmlLink ();
2550 hl.Href = ResolveUrl (lss);
2551 hl.Attributes["type"] = "text/css";
2552 hl.Attributes["rel"] = "stylesheet";
2553 Header.Controls.Add (hl);
2560 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2561 protected object GetWrappedFileDependencies (string [] list)
2566 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2567 protected virtual void InitializeCulture ()
2571 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2572 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)