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;
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 // if request was transfered from other page such Transfer
763 if(!isCrossPagePostBack)
765 if (this != _context.Handler)
768 HttpRequest req = Request;
772 NameValueCollection coll = null;
773 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
776 else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
780 coll = req.QueryString;
782 WebROCollection c = (WebROCollection) coll;
783 allow_load = !c.GotID;
785 c.ID = GetTypeHashCode ();
787 allow_load = (c.ID == GetTypeHashCode ());
789 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
796 public override Control FindControl (string id) {
800 return base.FindControl (id);
807 [EditorBrowsable (EditorBrowsableState.Advanced)]
808 public string GetPostBackClientEvent (Control control, string argument)
810 return scriptManager.GetPostBackEventReference (control, argument);
816 [EditorBrowsable (EditorBrowsableState.Advanced)]
817 public string GetPostBackClientHyperlink (Control control, string argument)
819 return scriptManager.GetPostBackClientHyperlink (control, argument);
825 [EditorBrowsable (EditorBrowsableState.Advanced)]
826 public string GetPostBackEventReference (Control control)
828 return scriptManager.GetPostBackEventReference (control, "");
834 [EditorBrowsable (EditorBrowsableState.Advanced)]
835 public string GetPostBackEventReference (Control control, string argument)
837 return scriptManager.GetPostBackEventReference (control, argument);
840 internal void RequiresPostBackScript ()
843 if (requiresPostBackScript)
845 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
846 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
848 requiresPostBackScript = true;
851 [EditorBrowsable (EditorBrowsableState.Never)]
852 public virtual int GetTypeHashCode ()
858 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
859 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
861 if (cacheSettings.Enabled)
862 InitOutputCache(cacheSettings.Duration,
863 cacheSettings.VaryByContentEncoding,
864 cacheSettings.VaryByHeader,
865 cacheSettings.VaryByCustom,
866 cacheSettings.Location,
867 cacheSettings.VaryByParam);
872 [MonoTODO ("varyByContentEncoding is not currently used")]
875 void InitOutputCache(int duration,
876 string varyByContentEncoding,
879 OutputCacheLocation location,
882 HttpCachePolicy cache = Response.Cache;
883 bool set_vary = false;
884 HttpContext ctx = Context;
885 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
888 case OutputCacheLocation.Any:
889 cache.SetCacheability (HttpCacheability.Public);
890 cache.SetMaxAge (new TimeSpan (0, 0, duration));
891 cache.SetLastModified (timestamp);
894 case OutputCacheLocation.Client:
895 cache.SetCacheability (HttpCacheability.Private);
896 cache.SetMaxAge (new TimeSpan (0, 0, duration));
897 cache.SetLastModified (timestamp);
899 case OutputCacheLocation.Downstream:
900 cache.SetCacheability (HttpCacheability.Public);
901 cache.SetMaxAge (new TimeSpan (0, 0, duration));
902 cache.SetLastModified (timestamp);
904 case OutputCacheLocation.Server:
905 cache.SetCacheability (HttpCacheability.Server);
908 case OutputCacheLocation.None:
913 if (varyByCustom != null)
914 cache.SetVaryByCustom (varyByCustom);
916 if (varyByParam != null && varyByParam.Length > 0) {
917 string[] prms = varyByParam.Split (';');
918 foreach (string p in prms)
919 cache.VaryByParams [p.Trim ()] = true;
920 cache.VaryByParams.IgnoreParams = false;
922 cache.VaryByParams.IgnoreParams = true;
925 if (varyByHeader != null && varyByHeader.Length > 0) {
926 string[] hdrs = varyByHeader.Split (';');
927 foreach (string h in hdrs)
928 cache.VaryByHeaders [h.Trim ()] = true;
932 cache.Duration = duration;
933 cache.SetExpires (timestamp.AddSeconds (duration));
937 [EditorBrowsable (EditorBrowsableState.Never)]
938 protected virtual void InitOutputCache (int duration,
941 OutputCacheLocation location,
944 InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
950 [EditorBrowsable (EditorBrowsableState.Advanced)]
952 public bool IsClientScriptBlockRegistered (string key)
954 return scriptManager.IsClientScriptBlockRegistered (key);
960 [EditorBrowsable (EditorBrowsableState.Advanced)]
962 public bool IsStartupScriptRegistered (string key)
964 return scriptManager.IsStartupScriptRegistered (key);
967 public string MapPath (string virtualPath)
969 return Request.MapPath (virtualPath);
973 protected internal override void Render (HtmlTextWriter writer) {
974 if (MaintainScrollPositionOnPostBack) {
975 ClientScript.RegisterWebFormClientScript ();
977 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
978 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
980 string webForm = IsMultiForm ? theForm + "." : null;
982 StringBuilder script = new StringBuilder ();
983 script.AppendLine ("<script type=\"text/javascript\">");
984 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
985 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
986 script.AppendLine (theForm + ".submit = function () { " + webForm + "WebForm_SaveScrollPositionSubmit(); }");
987 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
988 script.AppendLine (theForm + ".onsubmit = function () { " + webForm + "WebForm_SaveScrollPositionOnSubmit(); }");
990 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
991 script.AppendLine ("window.onload = function () { " + webForm + "WebForm_RestoreScrollPosition (); };");
993 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
994 script.AppendLine ("</script>");
996 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
998 base.Render (writer);
1002 private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1005 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
1006 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
1008 writer.WriteLine ();
1010 ClientScriptManager.WriteBeginScriptBlock (writer);
1013 RenderClientScriptFormDeclaration (writer, formUniqueID);
1016 writer.WriteLine ("{0}._form = {0};", theForm);
1017 writer.Write (theForm + ".");
1019 writer.WriteLine ("window._form = {0};", theForm);
1021 writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
1023 writer.WriteLine ("\tif(this._form.onsubmit && this._form.onsubmit() == false) return;");
1025 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1027 writer.WriteLine ("\tthis._form.{0}.value = eventTarget;", postEventSourceID);
1028 writer.WriteLine ("\tthis._form.{0}.value = eventArgument;", postEventArgumentID);
1029 writer.WriteLine ("\tthis._form.submit();");
1030 writer.WriteLine ("}");
1031 ClientScriptManager.WriteEndScriptBlock (writer);
1034 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1036 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1037 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1038 writer.WriteLine ("\t{0}._instanceVariableName = '{0}';", theForm);
1040 string serverUrl = Context.ServletResponse.encodeURL (Request.RawUrl);
1041 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1042 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1043 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1047 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1050 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1052 renderingForm = true;
1053 writer.WriteLine ();
1056 ClientScriptManager.WriteBeginScriptBlock (writer);
1057 RenderClientScriptFormDeclaration (writer, formUniqueID);
1058 ClientScriptManager.WriteEndScriptBlock (writer);
1061 if (handleViewState)
1062 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1064 scriptManager.WriteHiddenFields (writer);
1065 if (requiresPostBackScript) {
1066 RenderPostBackScript (writer, formUniqueID);
1067 postBackScriptRendered = true;
1070 scriptManager.WriteWebFormClientScript (writer);
1072 scriptManager.WriteClientScriptBlocks (writer);
1075 internal IStateFormatter GetFormatter ()
1077 return new ObjectStateFormatter (this);
1080 internal string GetSavedViewState ()
1082 return _savedViewState;
1085 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1088 scriptManager.SaveEventValidationState ();
1089 scriptManager.WriteExpandoAttributes (writer);
1091 scriptManager.WriteHiddenFields (writer);
1092 if (!postBackScriptRendered && requiresPostBackScript)
1093 RenderPostBackScript (writer, formUniqueID);
1095 scriptManager.WriteWebFormClientScript (writer);
1098 scriptManager.WriteArrayDeclares (writer);
1099 scriptManager.WriteStartupScriptBlocks (writer);
1100 renderingForm = false;
1101 postBackScriptRendered = false;
1104 private void ProcessPostData (NameValueCollection data, bool second)
1106 NameValueCollection requestValues = _requestValueCollection == null ?
1107 new NameValueCollection () :
1108 _requestValueCollection;
1110 if (data != null && data.Count > 0) {
1111 Hashtable used = new Hashtable ();
1112 foreach (string id in data.AllKeys){
1113 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID ||
1114 id == ClientScriptManager.EventStateFieldName)
1117 if (used.ContainsKey (id))
1122 Control ctrl = FindControl (id);
1124 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1125 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1129 RegisterRequiresRaiseEvent (pbeh);
1133 if (pbdh.LoadPostData (id, requestValues) == true) {
1134 if (requiresPostDataChanged == null)
1135 requiresPostDataChanged = new ArrayList ();
1136 requiresPostDataChanged.Add (pbdh);
1139 if (_requiresPostBackCopy != null)
1140 _requiresPostBackCopy.Remove (id);
1142 } else if (!second) {
1143 if (secondPostData == null)
1144 secondPostData = new NameValueCollection ();
1145 secondPostData.Add (id, data [id]);
1150 ArrayList list1 = null;
1151 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1152 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1153 foreach (string id in handlers) {
1154 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1156 _requiresPostBackCopy.Remove (id);
1157 if (pbdh.LoadPostData (id, requestValues)) {
1158 if (requiresPostDataChanged == null)
1159 requiresPostDataChanged = new ArrayList ();
1161 requiresPostDataChanged.Add (pbdh);
1163 } else if (!second) {
1165 list1 = new ArrayList ();
1170 _requiresPostBackCopy = second ? null : list1;
1172 secondPostData = null;
1175 [EditorBrowsable (EditorBrowsableState.Never)]
1177 public virtual void ProcessRequest (HttpContext context)
1179 public void ProcessRequest (HttpContext context)
1183 _lifeCycle = PageLifeCycle.Unknown;
1187 _application = context.Application;
1188 _response = context.Response;
1189 _request = context.Request;
1190 _cache = context.Cache;
1192 if (clientTarget != null)
1193 Request.ClientTarget = clientTarget;
1195 WireupAutomaticEvents ();
1196 //-- Control execution lifecycle in the docs
1198 // Save culture information because it can be modified in FrameworkInitialize()
1199 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1200 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1201 FrameworkInitialize ();
1202 context.ErrorPage = _errorPage;
1205 InternalProcessRequest ();
1206 } catch (ThreadAbortException) {
1207 // Do nothing, just ignore it by now.
1208 } catch (Exception e) {
1209 context.AddError (e); // OnError might access LastError
1210 OnError (EventArgs.Empty);
1211 context.ClearError (e);
1212 // We want to remove that error, as we're rethrowing to stop
1213 // further processing.
1214 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1219 _lifeCycle = PageLifeCycle.Unload;
1222 UnloadRecursive (true);
1224 _lifeCycle = PageLifeCycle.End;
1227 if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1228 Thread.CurrentThread.CurrentCulture = culture;
1230 if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1231 Thread.CurrentThread.CurrentUICulture = uiculture;
1236 delegate void ProcessRequestDelegate (HttpContext context);
1238 private sealed class DummyAsyncResult : IAsyncResult
1240 readonly object state;
1241 readonly WaitHandle asyncWaitHandle;
1242 readonly bool completedSynchronously;
1243 readonly bool isCompleted;
1245 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1247 this.isCompleted = isCompleted;
1248 this.completedSynchronously = completedSynchronously;
1251 asyncWaitHandle = new ManualResetEvent (true);
1254 asyncWaitHandle = new ManualResetEvent (false);
1258 #region IAsyncResult Members
1260 public object AsyncState {
1261 get { return state; }
1264 public WaitHandle AsyncWaitHandle {
1265 get { return asyncWaitHandle; }
1268 public bool CompletedSynchronously {
1269 get { return completedSynchronously; }
1272 public bool IsCompleted {
1273 get { return isCompleted; }
1279 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1281 ProcessRequest (context);
1282 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1284 if (callback != null) {
1285 callback (asyncResult);
1291 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1296 void InternalProcessRequest ()
1298 _requestValueCollection = this.DeterminePostBackMode();
1301 _lifeCycle = PageLifeCycle.Start;
1302 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1303 if (_requestValueCollection != null) {
1304 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1305 _doLoadPreviousPage = true;
1308 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1309 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1310 //isPostBack = !isCallback;
1313 string lastFocus = _requestValueCollection [LastFocusID];
1314 if (!String.IsNullOrEmpty (lastFocus)) {
1315 _focusedControlID = UniqueID2ClientID (lastFocus);
1319 if (!isCrossPagePostBack) {
1320 if (_context.PreviousHandler is Page) {
1321 previousPage = (Page) _context.PreviousHandler;
1325 _lifeCycle = PageLifeCycle.PreInit;
1326 Trace.Write ("aspx.page", "Begin PreInit");
1327 OnPreInit (EventArgs.Empty);
1328 Trace.Write ("aspx.page", "End PreInit");
1332 _lifeCycle = PageLifeCycle.Init;
1334 Trace.Write ("aspx.page", "Begin Init");
1335 InitRecursive (null);
1336 Trace.Write ("aspx.page", "End Init");
1339 _lifeCycle = PageLifeCycle.InitComplete;
1340 Trace.Write ("aspx.page", "Begin InitComplete");
1341 OnInitComplete (EventArgs.Empty);
1342 Trace.Write ("aspx.page", "End InitComplete");
1345 renderingForm = false;
1347 if (IsPostBack || IsCallback) {
1348 _lifeCycle = PageLifeCycle.PreLoad;
1349 if (_requestValueCollection != null)
1350 scriptManager.RestoreEventValidationState (
1351 _requestValueCollection [ClientScriptManager.EventStateFieldName]);
1355 Trace.Write ("aspx.page", "Begin LoadViewState");
1356 LoadPageViewState ();
1357 Trace.Write ("aspx.page", "End LoadViewState");
1358 Trace.Write ("aspx.page", "Begin ProcessPostData");
1362 ProcessPostData (_requestValueCollection, false);
1363 Trace.Write ("aspx.page", "End ProcessPostData");
1367 Trace.Write ("aspx.page", "Begin PreLoad");
1368 OnPreLoad (EventArgs.Empty);
1369 Trace.Write ("aspx.page", "End PreLoad");
1370 _lifeCycle = PageLifeCycle.Load;
1373 Trace.Write ("aspx.page", "Begin Load");
1375 Trace.Write ("aspx.page", "End Load");
1379 RestoreValidatorsState ();
1382 if (IsPostBack || IsCallback) {
1383 _lifeCycle = PageLifeCycle.ControlEvents;
1387 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1388 ProcessPostData (secondPostData, true);
1389 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1390 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1391 RaiseChangedEvents ();
1392 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1393 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1394 RaisePostBackEvents ();
1395 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1399 _lifeCycle = PageLifeCycle.LoadComplete;
1400 Trace.Write ("aspx.page", "Begin LoadComplete");
1401 OnLoadComplete (EventArgs.Empty);
1402 Trace.Write ("aspx.page", "End LoadComplete");
1404 if (IsCrossPagePostBack)
1408 string result = ProcessCallbackData ();
1409 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1410 callbackOutput.Write (result);
1411 callbackOutput.Flush ();
1415 _lifeCycle = PageLifeCycle.PreRender;
1418 Trace.Write ("aspx.page", "Begin PreRender");
1419 PreRenderRecursiveInternal ();
1420 Trace.Write ("aspx.page", "End PreRender");
1423 ExecuteRegisteredAsyncTasks ();
1425 _lifeCycle = PageLifeCycle.PreRenderComplete;
1426 Trace.Write ("aspx.page", "Begin PreRenderComplete");
1427 OnPreRenderComplete (EventArgs.Empty);
1428 Trace.Write ("aspx.page", "End PreRenderComplete");
1431 Trace.Write ("aspx.page", "Begin SaveViewState");
1432 SavePageViewState ();
1433 Trace.Write ("aspx.page", "End SaveViewState");
1436 _lifeCycle = PageLifeCycle.SaveStateComplete;
1437 Trace.Write ("aspx.page", "Begin SaveStateComplete");
1438 OnSaveStateComplete (EventArgs.Empty);
1439 Trace.Write ("aspx.page", "End SaveStateComplete");
1441 if (OnSaveStateCompleteForPortlet ())
1443 #endif // TARGET_J2EE
1447 _lifeCycle = PageLifeCycle.Render;
1448 scriptManager.ResetEventValidationState ();
1452 Trace.Write ("aspx.page", "Begin Render");
1453 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1454 RenderControl (output);
1455 Trace.Write ("aspx.page", "End Render");
1458 private void RenderTrace ()
1460 TraceManager traceManager = HttpRuntime.TraceManager;
1462 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1467 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1470 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1471 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1472 Trace.Render (output);
1477 bool CheckForValidationSupport (Control targetControl)
1479 if (targetControl == null)
1481 Type type = targetControl.GetType ();
1482 object[] attributes = type.GetCustomAttributes (false);
1483 foreach (object attr in attributes)
1484 if (attr is SupportsEventValidationAttribute)
1490 void RaisePostBackEvents ()
1493 Control targetControl;
1495 if (requiresRaiseEvent != null) {
1496 RaisePostBackEvent (requiresRaiseEvent, null);
1500 NameValueCollection postdata = _requestValueCollection;
1501 if (postdata == null)
1504 string eventTarget = postdata [postEventSourceID];
1505 if (eventTarget == null || eventTarget.Length == 0) {
1511 targetControl = FindControl (eventTarget);
1512 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1514 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1520 string eventArgument = postdata [postEventArgumentID];
1521 RaisePostBackEvent (target, eventArgument);
1524 internal void RaiseChangedEvents ()
1526 if (requiresPostDataChanged == null)
1529 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1530 ipdh.RaisePostDataChangedEvent ();
1532 requiresPostDataChanged = null;
1535 [EditorBrowsable (EditorBrowsableState.Advanced)]
1536 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1539 Control targetControl = sourceControl as Control;
1540 if (targetControl != null && CheckForValidationSupport (targetControl))
1541 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1543 sourceControl.RaisePostBackEvent (eventArgument);
1549 [EditorBrowsable (EditorBrowsableState.Advanced)]
1550 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1552 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1558 [EditorBrowsable (EditorBrowsableState.Advanced)]
1559 public virtual void RegisterClientScriptBlock (string key, string script)
1561 scriptManager.RegisterClientScriptBlock (key, script);
1567 [EditorBrowsable (EditorBrowsableState.Advanced)]
1568 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1570 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1573 [MonoTODO("Not implemented, Used in HtmlForm")]
1574 internal void RegisterClientScriptFile (string a, string b, string c)
1576 throw new NotImplementedException ();
1582 [EditorBrowsable (EditorBrowsableState.Advanced)]
1583 public void RegisterOnSubmitStatement (string key, string script)
1585 scriptManager.RegisterOnSubmitStatement (key, script);
1588 internal string GetSubmitStatements ()
1590 return scriptManager.WriteSubmitStatements ();
1593 [EditorBrowsable (EditorBrowsableState.Advanced)]
1594 public void RegisterRequiresPostBack (Control control)
1597 if (!(control is IPostBackDataHandler))
1598 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1601 if (_requiresPostBack == null)
1602 _requiresPostBack = new ArrayList ();
1604 if (_requiresPostBack.Contains (control.UniqueID))
1607 _requiresPostBack.Add (control.UniqueID);
1610 [EditorBrowsable (EditorBrowsableState.Advanced)]
1611 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1613 requiresRaiseEvent = control;
1619 [EditorBrowsable (EditorBrowsableState.Advanced)]
1620 public virtual void RegisterStartupScript (string key, string script)
1622 scriptManager.RegisterStartupScript (key, script);
1625 [EditorBrowsable (EditorBrowsableState.Advanced)]
1626 public void RegisterViewStateHandler ()
1628 handleViewState = true;
1631 [EditorBrowsable (EditorBrowsableState.Advanced)]
1632 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1634 PageStatePersister persister = this.PageStatePersister;
1635 if (persister == null)
1637 Pair pair = viewState as Pair;
1639 persister.ViewState = pair.First;
1640 persister.ControlState = pair.Second;
1642 persister.ViewState = viewState;
1646 internal string RawViewState {
1648 NameValueCollection postdata = _requestValueCollection;
1650 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1653 if (view_state == "")
1657 set { _savedViewState = value; }
1665 PageStatePersister PageStatePersister {
1667 if (page_state_persister == null)
1668 page_state_persister = new HiddenFieldPageStatePersister (this);
1669 return page_state_persister;
1673 [EditorBrowsable (EditorBrowsableState.Advanced)]
1674 protected virtual object LoadPageStateFromPersistenceMedium ()
1676 PageStatePersister persister = this.PageStatePersister;
1677 if (persister == null)
1680 return new Pair (persister.ViewState, persister.ControlState);
1683 internal void LoadPageViewState()
1685 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1686 if (sState != null) {
1689 LoadPageControlState (sState.Second);
1691 Pair vsr = sState.First as Pair;
1693 LoadViewStateRecursive (vsr.First);
1694 _requiresPostBackCopy = vsr.Second as ArrayList;
1700 internal void SavePageViewState ()
1702 if (!handleViewState)
1706 object controlState = SavePageControlState ();
1709 object viewState = SaveViewStateRecursive ();
1710 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1713 if (viewState != null || reqPostback != null)
1714 vsr = new Pair (viewState, reqPostback);
1715 Pair pair = new Pair ();
1719 pair.Second = controlState;
1723 if (pair.First == null && pair.Second == null)
1724 SavePageStateToPersistenceMedium (null);
1726 SavePageStateToPersistenceMedium (pair);
1730 public virtual void Validate ()
1732 is_validated = true;
1733 ValidateCollection (_validators);
1737 internal bool AreValidatorsUplevel () {
1738 return AreValidatorsUplevel (String.Empty);
1741 internal bool AreValidatorsUplevel (string valGroup)
1743 internal virtual bool AreValidatorsUplevel ()
1746 bool uplevel = false;
1748 foreach (IValidator v in Validators) {
1749 BaseValidator bv = v as BaseValidator;
1750 if (bv == null) continue;
1753 if (valGroup != bv.ValidationGroup)
1756 if (bv.GetRenderUplevel()) {
1765 bool ValidateCollection (ValidatorCollection validators)
1768 if (!_eventValidation)
1772 if (validators == null || validators.Count == 0)
1775 bool all_valid = true;
1776 foreach (IValidator v in validators){
1778 if (v.IsValid == false)
1785 [EditorBrowsable (EditorBrowsableState.Advanced)]
1786 public virtual void VerifyRenderingInServerForm (Control control)
1788 if (Context == null)
1795 throw new HttpException ("Control '" +
1798 control.GetType ().Name +
1799 "' must be placed inside a form tag with runat=server.");
1802 protected override void FrameworkInitialize ()
1804 base.FrameworkInitialize ();
1806 InitializeStyleSheet ();
1817 ClientScriptManager ClientScript {
1818 get { return scriptManager; }
1823 static readonly object InitCompleteEvent = new object ();
1824 static readonly object LoadCompleteEvent = new object ();
1825 static readonly object PreInitEvent = new object ();
1826 static readonly object PreLoadEvent = new object ();
1827 static readonly object PreRenderCompleteEvent = new object ();
1828 static readonly object SaveStateCompleteEvent = new object ();
1830 const int initcomplete_mask = 1;
1831 const int loadcomplete_mask = 1 << 1;
1832 const int preinit_mask = 1 << 2;
1833 const int preload_mask = 1 << 3;
1834 const int prerendercomplete_mask = 1 << 4;
1835 const int savestatecomplete_mask = 1 << 5;
1837 [EditorBrowsable (EditorBrowsableState.Advanced)]
1838 public event EventHandler InitComplete {
1840 event_mask |= initcomplete_mask;
1841 Events.AddHandler (InitCompleteEvent, value);
1843 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1846 [EditorBrowsable (EditorBrowsableState.Advanced)]
1847 public event EventHandler LoadComplete {
1849 event_mask |= loadcomplete_mask;
1850 Events.AddHandler (LoadCompleteEvent, value);
1852 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1855 public event EventHandler PreInit {
1857 event_mask |= preinit_mask;
1858 Events.AddHandler (PreInitEvent, value);
1860 remove { Events.RemoveHandler (PreInitEvent, value); }
1863 [EditorBrowsable (EditorBrowsableState.Advanced)]
1864 public event EventHandler PreLoad {
1866 event_mask |= preload_mask;
1867 Events.AddHandler (PreLoadEvent, value);
1869 remove { Events.RemoveHandler (PreLoadEvent, value); }
1872 [EditorBrowsable (EditorBrowsableState.Advanced)]
1873 public event EventHandler PreRenderComplete {
1875 event_mask |= prerendercomplete_mask;
1876 Events.AddHandler (PreRenderCompleteEvent, value);
1878 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1881 [EditorBrowsable (EditorBrowsableState.Advanced)]
1882 public event EventHandler SaveStateComplete {
1884 event_mask |= savestatecomplete_mask;
1885 Events.AddHandler (SaveStateCompleteEvent, value);
1887 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1890 protected virtual void OnInitComplete (EventArgs e)
1892 if ((event_mask & initcomplete_mask) != 0) {
1893 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1894 if (eh != null) eh (this, e);
1898 protected virtual void OnLoadComplete (EventArgs e)
1900 if ((event_mask & loadcomplete_mask) != 0) {
1901 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1902 if (eh != null) eh (this, e);
1906 protected virtual void OnPreInit (EventArgs e)
1908 if ((event_mask & preinit_mask) != 0) {
1909 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1910 if (eh != null) eh (this, e);
1914 protected virtual void OnPreLoad (EventArgs e)
1916 if ((event_mask & preload_mask) != 0) {
1917 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1918 if (eh != null) eh (this, e);
1922 protected virtual void OnPreRenderComplete (EventArgs e)
1924 if ((event_mask & prerendercomplete_mask) != 0) {
1925 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1926 if (eh != null) eh (this, e);
1931 if (!Form.DetermineRenderUplevel ())
1934 string defaultButtonId = Form.DefaultButton;
1935 /* figure out if we have some control we're going to focus */
1936 if (String.IsNullOrEmpty (_focusedControlID)) {
1937 _focusedControlID = Form.DefaultFocus;
1938 if (String.IsNullOrEmpty (_focusedControlID))
1939 _focusedControlID = defaultButtonId;
1942 if (!String.IsNullOrEmpty (_focusedControlID)) {
1943 ClientScript.RegisterWebFormClientScript ();
1944 ClientScript.RegisterStartupScript (
1945 "HtmlForm-DefaultButton-StartupScript",
1946 "<script type=\"text/javascript\">\n" + ClientScriptManager.SCRIPT_BLOCK_START +
1947 "\nWebForm_AutoFocus('" + _focusedControlID + "');\n" + ClientScriptManager.SCRIPT_BLOCK_END +
1951 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1952 ClientScript.RegisterWebFormClientScript ();
1953 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1954 "WebForm_ReEnableControls(this);");
1958 internal void RegisterEnabledControl (Control control)
1960 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1962 _hasEnabledControlArray = true;
1963 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
1966 protected virtual void OnSaveStateComplete (EventArgs e)
1968 if ((event_mask & savestatecomplete_mask) != 0) {
1969 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1970 if (eh != null) eh (this, e);
1974 public HtmlForm Form {
1975 get { return _form; }
1978 internal void RegisterForm (HtmlForm form)
1983 [BrowsableAttribute (false)]
1984 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1985 public Page PreviousPage {
1987 if (_doLoadPreviousPage) {
1988 _doLoadPreviousPage = false;
1989 LoadPreviousPageReference ();
1991 return previousPage;
1996 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1997 [BrowsableAttribute (false)]
1998 public bool IsCallback {
1999 get { return isCallback; }
2002 [BrowsableAttribute (false)]
2003 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2004 public bool IsCrossPagePostBack {
2005 get { return isCrossPagePostBack; }
2008 public new virtual char IdSeparator {
2010 //TODO: why override?
2011 return base.IdSeparator;
2015 string ProcessCallbackData ()
2017 string callbackTarget = _requestValueCollection [CallbackSourceID];
2018 if (callbackTarget == null || callbackTarget.Length == 0)
2019 throw new HttpException ("Callback target not provided.");
2021 Control targetControl = FindControl (callbackTarget);
2022 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2024 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2026 string callbackEventError = String.Empty;
2027 string callBackResult;
2028 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2031 target.RaiseCallbackEvent (callbackArgument);
2032 } catch (Exception ex) {
2033 callbackEventError = String.Concat ("e", ex.Message);
2037 callBackResult = target.GetCallbackResult ();
2038 } catch (Exception ex) {
2039 return String.Concat ("e", ex.Message);
2042 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2043 return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
2044 eventValidation + callBackResult;
2047 [BrowsableAttribute (false)]
2048 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2049 public HtmlHead Header {
2050 get { return htmlHeader; }
2053 internal void SetHeader (HtmlHead header)
2055 htmlHeader = header;
2056 if (_title != null) {
2057 htmlHeader.Title = _title;
2062 protected bool AsyncMode {
2063 get { return asyncMode; }
2064 set { asyncMode = value; }
2067 public TimeSpan AsyncTimeout {
2068 get { return asyncTimeout; }
2069 set { asyncTimeout = value; }
2072 public bool IsAsync {
2073 get { return AsyncMode; }
2076 [MonoTODO ("Not Implemented")]
2077 protected internal virtual string UniqueFilePathSuffix {
2079 throw new NotImplementedException ();
2083 [MonoTODO ("Not Implemented")]
2084 public int MaxPageStateFieldLength {
2086 throw new NotImplementedException ();
2089 throw new NotImplementedException ();
2093 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2095 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2098 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2101 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2104 if (_lifeCycle >= PageLifeCycle.PreRender) {
2105 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
2108 if (beginHandler == null) {
2109 throw new ArgumentNullException ("beginHandler");
2112 if (endHandler == null) {
2113 throw new ArgumentNullException ("endHandler");
2116 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2119 private List<PageAsyncTask> ParallelTasks {
2121 if (parallelTasks == null) {
2122 parallelTasks = new List<PageAsyncTask>();
2124 return parallelTasks;
2128 private List<PageAsyncTask> SerialTasks {
2130 if (serialTasks == null) {
2131 serialTasks = new List<PageAsyncTask> ();
2137 public void RegisterAsyncTask (PageAsyncTask task)
2140 throw new ArgumentNullException ("task");
2143 if (task.ExecuteInParallel) {
2144 ParallelTasks.Add (task);
2147 SerialTasks.Add (task);
2151 public void ExecuteRegisteredAsyncTasks ()
2153 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2154 (serialTasks == null || serialTasks.Count == 0)){
2158 if (parallelTasks != null) {
2159 DateTime startExecution = DateTime.Now;
2160 List<PageAsyncTask> localParallelTasks = parallelTasks;
2161 parallelTasks = null; // Shouldn't execute tasks twice
2162 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2163 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2164 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2165 if (result.CompletedSynchronously) {
2166 parallelTask.EndHandler (result);
2169 asyncResults.Add (result);
2173 if (asyncResults.Count > 0) {
2175 TimeSpan timeout = AsyncTimeout;
2176 long t1 = DateTime.Now.Ticks;
2177 bool signalled = true;
2178 for (int i = 0; i < asyncResults.Count; i++) {
2179 if (asyncResults [i].IsCompleted)
2183 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2186 long t2 = DateTime.Now.Ticks;
2187 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2188 if (timeout.Ticks <= 0)
2192 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2196 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2198 for (i = 0; i < asyncResults.Count; i++) {
2199 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2201 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2202 if (!allSignalled) {
2203 for (i = 0; i < asyncResults.Count; i++) {
2204 if (!asyncResults [i].IsCompleted) {
2205 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2211 DateTime endWait = DateTime.Now;
2212 TimeSpan elapsed = endWait - startExecution;
2213 if (elapsed <= AsyncTimeout) {
2214 AsyncTimeout -= elapsed;
2217 AsyncTimeout = TimeSpan.FromTicks(0);
2221 if (serialTasks != null) {
2222 List<PageAsyncTask> localSerialTasks = serialTasks;
2223 serialTasks = null; // Shouldn't execute tasks twice
2224 foreach (PageAsyncTask serialTask in localSerialTasks) {
2225 DateTime startExecution = DateTime.Now;
2227 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2228 if (result.CompletedSynchronously) {
2229 serialTask.EndHandler (result);
2232 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2233 if (!done && !result.IsCompleted) {
2234 serialTask.TimeoutHandler (result);
2237 DateTime endWait = DateTime.Now;
2238 TimeSpan elapsed = endWait - startExecution;
2239 if (elapsed <= AsyncTimeout) {
2240 AsyncTimeout -= elapsed;
2243 AsyncTimeout = TimeSpan.FromTicks (0);
2247 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2250 void EndAsyncTaskCallback (IAsyncResult result)
2252 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2253 task.EndHandler (result);
2256 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2258 Type htmlTextWriterType = typeof (HtmlTextWriter);
2260 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2261 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2264 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2265 if (constructor == null) {
2266 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2269 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2272 public ViewStateEncryptionMode ViewStateEncryptionMode {
2273 get { return viewStateEncryptionMode; }
2274 set { viewStateEncryptionMode = value; }
2277 public void RegisterRequiresViewStateEncryption ()
2279 controlRegisteredForViewStateEncryption = true;
2282 private static byte [] AES_IV = null;
2283 private static byte [] TripleDES_IV = null;
2284 private static object locker = new object ();
2285 private static bool isEncryptionInitialized = false;
2287 private static void InitializeEncryption ()
2289 if (isEncryptionInitialized) {
2294 if (isEncryptionInitialized) {
2298 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2299 AES_IV = new byte [16];
2300 TripleDES_IV = new byte [8];
2303 for (i = 0; i < AES_IV.Length; i++) {
2304 AES_IV [i] = (byte) iv_string [i];
2307 for (i = 0; i < TripleDES_IV.Length; i++) {
2308 TripleDES_IV [i] = (byte) iv_string [i];
2311 isEncryptionInitialized = true;
2315 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2317 ICryptoTransform transform = null;
2318 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2319 byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
2321 switch (config.Validation) {
2322 case MachineKeyValidation.SHA1:
2323 transform = SHA1.Create ();
2326 case MachineKeyValidation.MD5:
2327 transform = MD5.Create ();
2330 case MachineKeyValidation.AES:
2331 if (cryptoStreamMode == CryptoStreamMode.Read){
2332 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2334 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2338 case MachineKeyValidation.TripleDES:
2339 if (cryptoStreamMode == CryptoStreamMode.Read){
2340 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2342 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2350 internal bool NeedViewStateEncryption {
2352 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2353 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2354 controlRegisteredForViewStateEncryption));
2359 void ApplyMasterPage ()
2361 if (masterPageFile != null && masterPageFile.Length > 0) {
2362 ArrayList appliedMasterPageFiles = new ArrayList ();
2364 if (Master != null) {
2365 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2369 Controls.Add (Master);
2374 [DefaultValueAttribute ("")]
2375 public virtual string MasterPageFile {
2376 get { return masterPageFile; }
2378 masterPageFile = value;
2383 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2384 [BrowsableAttribute (false)]
2385 public MasterPage Master {
2387 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2390 if (masterPage == null)
2391 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2397 public void SetFocus (string clientID)
2399 if (String.IsNullOrEmpty (clientID))
2400 throw new ArgumentNullException ("control");
2402 if (_lifeCycle > PageLifeCycle.PreRender)
2403 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2406 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2408 _focusedControlID = clientID;
2411 public void SetFocus (Control control)
2413 if (control == null)
2414 throw new ArgumentNullException ("control");
2416 SetFocus (control.ClientID);
2419 [EditorBrowsable (EditorBrowsableState.Advanced)]
2420 public void RegisterRequiresControlState (Control control)
2422 if (control == null)
2423 throw new ArgumentNullException ("control");
2425 if (RequiresControlState (control))
2428 if (requireStateControls == null)
2429 requireStateControls = new ArrayList ();
2430 int n = requireStateControls.Add (control);
2432 if (_savedControlState == null || n >= _savedControlState.Length)
2435 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2436 if (parent.IsChildControlStateCleared)
2439 object state = _savedControlState [n];
2441 control.LoadControlState (state);
2444 public bool RequiresControlState (Control control)
2446 if (requireStateControls == null) return false;
2447 return requireStateControls.Contains (control);
2450 [EditorBrowsable (EditorBrowsableState.Advanced)]
2451 public void UnregisterRequiresControlState (Control control)
2453 if (requireStateControls != null)
2454 requireStateControls.Remove (control);
2457 public ValidatorCollection GetValidators (string validationGroup)
2459 if (validationGroup == String.Empty)
2460 validationGroup = null;
2462 ValidatorCollection col = new ValidatorCollection ();
2463 if (_validators == null)
2466 foreach (IValidator v in _validators)
2467 if (BelongsToGroup(v, validationGroup))
2473 bool BelongsToGroup(IValidator v, string validationGroup) {
2474 BaseValidator validator = v as BaseValidator;
2475 if (validationGroup == null)
2476 return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
2478 return validator != null && validator.ValidationGroup == validationGroup;
2481 public virtual void Validate (string validationGroup)
2483 is_validated = true;
2484 ValidateCollection (GetValidators (validationGroup));
2487 object SavePageControlState ()
2489 if (requireStateControls == null) return null;
2490 object[] state = new object [requireStateControls.Count];
2492 bool allNull = true;
2493 for (int n=0; n<state.Length; n++) {
2494 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2495 if (state [n] != null) allNull = false;
2497 if (allNull) return null;
2501 void LoadPageControlState (object data)
2503 _savedControlState = (object []) data;
2505 if (requireStateControls == null) return;
2507 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2508 for (int n=0; n < max; n++) {
2509 Control ctl = (Control) requireStateControls [n];
2510 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2514 void LoadPreviousPageReference ()
2516 if (_requestValueCollection != null) {
2517 string prevPage = _requestValueCollection [PreviousPageID];
2518 if (prevPage != null) {
2519 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2520 previousPage.isCrossPagePostBack = true;
2521 previousPage.ProcessRequest (Context);
2527 Hashtable contentTemplates;
2528 [EditorBrowsable (EditorBrowsableState.Never)]
2529 protected internal void AddContentTemplate (string templateName, ITemplate template)
2531 if (contentTemplates == null)
2532 contentTemplates = new Hashtable ();
2533 contentTemplates [templateName] = template;
2536 PageTheme _pageTheme;
2537 internal PageTheme PageTheme {
2538 get { return _pageTheme; }
2541 PageTheme _styleSheetPageTheme;
2542 internal PageTheme StyleSheetPageTheme {
2543 get { return _styleSheetPageTheme; }
2548 internal void PushDataItemContext (object o) {
2549 if (dataItemCtx == null)
2550 dataItemCtx = new Stack ();
2552 dataItemCtx.Push (o);
2555 internal void PopDataItemContext () {
2556 if (dataItemCtx == null)
2557 throw new InvalidOperationException ();
2562 public object GetDataItem() {
2563 if (dataItemCtx == null || dataItemCtx.Count == 0)
2564 throw new InvalidOperationException ("No data item");
2566 return dataItemCtx.Peek ();
2569 protected internal override void OnInit (EventArgs e)
2573 ArrayList themes = new ArrayList();
2575 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2576 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2577 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2578 themes.AddRange (PageTheme.GetStyleSheets ());
2580 if (themes.Count > 0 && Header == null)
2581 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2583 foreach (string lss in themes) {
2584 HtmlLink hl = new HtmlLink ();
2585 hl.Href = ResolveUrl (lss);
2586 hl.Attributes["type"] = "text/css";
2587 hl.Attributes["rel"] = "stylesheet";
2588 Header.Controls.Add (hl);
2595 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2596 protected object GetWrappedFileDependencies (string [] list)
2601 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2602 protected virtual void InitializeCulture ()
2606 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2607 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)