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 HttpContext _context;
91 private ValidatorCollection _validators;
92 private bool renderingForm;
93 private string _savedViewState;
94 private ArrayList _requiresPostBack;
95 private ArrayList _requiresPostBackCopy;
96 private ArrayList requiresPostDataChanged;
97 private IPostBackEventHandler requiresRaiseEvent;
98 private NameValueCollection secondPostData;
99 private bool requiresPostBackScript;
100 private bool postBackScriptRendered;
101 bool handleViewState;
102 string viewStateUserKey;
103 NameValueCollection _requestValueCollection;
105 ClientScriptManager scriptManager;
106 bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
107 PageStatePersister page_state_persister;
109 [EditorBrowsable (EditorBrowsableState.Never)]
115 const string postEventArgumentID = "__EVENTARGUMENT";
117 [EditorBrowsable (EditorBrowsableState.Never)]
123 const string postEventSourceID = "__EVENTTARGET";
126 const string ScrollPositionXID = "__SCROLLPOSITIONX";
127 const string ScrollPositionYID = "__SCROLLPOSITIONY";
128 const string EnabledControlArrayID = "__enabledControlArray";
132 internal const string LastFocusID = "__LASTFOCUS";
133 internal const string CallbackArgumentID = "__CALLBACKARGUMENT";
134 internal const string CallbackSourceID = "__CALLBACKTARGET";
135 internal const string PreviousPageID = "__PREVIOUSPAGE";
139 MasterPage masterPage;
140 string masterPageFile;
143 bool isCrossPagePostBack;
146 ArrayList requireStateControls;
147 Hashtable _validatorsByGroup;
152 string _styleSheetTheme;
155 bool _maintainScrollPositionOnPostBack;
157 private bool asyncMode = false;
158 private TimeSpan asyncTimeout;
159 private const double DefaultAsyncTimeout = 45.0;
160 private List<PageAsyncTask> parallelTasks;
161 private List<PageAsyncTask> serialTasks;
163 private ViewStateEncryptionMode viewStateEncryptionMode;
164 private bool controlRegisteredForViewStateEncryption = false;
170 scriptManager = new ClientScriptManager (this);
175 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
177 asyncTimeout = ps.AsyncTimeout;
178 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
180 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
181 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
190 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
192 public HttpApplicationState Application
195 if (_context == null)
197 return _context.Application;
201 [EditorBrowsable (EditorBrowsableState.Never)]
202 protected bool AspCompatMode
205 get { return false; }
207 set { throw new NotImplementedException (); }
210 [EditorBrowsable (EditorBrowsableState.Never)]
212 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
213 [BrowsableAttribute (false)]
216 get { return Response.BufferOutput; }
217 set { Response.BufferOutput = value; }
220 protected bool Buffer
222 set { Response.BufferOutput = value; }
226 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
231 if (_context == null)
232 throw new HttpException ("No cache available without a context.");
233 return _context.Cache;
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
245 get { return (clientTarget == null) ? "" : clientTarget; }
247 clientTarget = value;
253 [EditorBrowsable (EditorBrowsableState.Never)]
255 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
256 [BrowsableAttribute (false)]
259 get { return Response.ContentEncoding.CodePage; }
260 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
263 protected int CodePage
265 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
269 [EditorBrowsable (EditorBrowsableState.Never)]
271 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
272 [BrowsableAttribute (false)]
273 public string ContentType
275 get { return Response.ContentType; }
276 set { Response.ContentType = value; }
279 protected string ContentType
281 set { Response.ContentType = value; }
285 protected override HttpContext Context
288 if (_context == null)
289 return HttpContext.Current;
296 [EditorBrowsable (EditorBrowsableState.Advanced)]
297 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
298 [BrowsableAttribute (false)]
299 public string Culture
301 get { return Thread.CurrentThread.CurrentCulture.Name; }
302 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
305 [EditorBrowsable (EditorBrowsableState.Never)]
306 protected string Culture
308 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
313 public virtual bool EnableEventValidation {
314 get { return _eventValidation; }
316 if (_lifeCycle > PageLifeCycle.Init)
317 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
318 _eventValidation = value;
322 internal PageLifeCycle LifeCycle {
323 get { return _lifeCycle; }
328 public override bool EnableViewState
330 get { return _viewState; }
331 set { _viewState = value; }
335 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
336 [BrowsableAttribute (false)]
338 [EditorBrowsable (EditorBrowsableState.Never)]
344 bool EnableViewStateMac
346 get { return _viewStateMac; }
347 set { _viewStateMac = value; }
351 internal bool EnableViewStateMacInternal {
352 get { return _viewStateMac; }
353 set { _viewStateMac = value; }
357 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
358 [Browsable (false), DefaultValue ("")]
359 [WebSysDescription ("The URL of a page used for error redirection.")]
360 public string ErrorPage
362 get { return _errorPage; }
365 if (_context != null)
366 _context.ErrorPage = value;
373 [EditorBrowsable (EditorBrowsableState.Never)]
374 protected ArrayList FileDependencies
377 if (Response != null)
378 Response.AddFileDependencies (value);
384 [EditorBrowsable (EditorBrowsableState.Never)]
386 public override string ID
388 get { return base.ID; }
389 set { base.ID = value; }
392 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
394 public bool IsPostBack
400 return _requestValueCollection != null;
405 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
406 public bool IsReusable {
407 get { return false; }
410 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
412 public bool IsValid {
415 throw new HttpException (Locale.GetText ("Page hasn't been validated."));
418 foreach (IValidator val in Validators)
423 return ValidateCollection (_validators);
428 public IDictionary Items {
431 items = new Hashtable ();
437 [EditorBrowsable (EditorBrowsableState.Never)]
439 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
440 [BrowsableAttribute (false)]
442 get { return Thread.CurrentThread.CurrentCulture.LCID; }
443 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
447 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
453 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
454 public bool MaintainScrollPositionOnPostBack {
455 get { return _maintainScrollPositionOnPostBack; }
456 set { _maintainScrollPositionOnPostBack = value; }
461 public PageAdapter PageAdapter {
463 return (PageAdapter)Adapter;
469 internal string theForm {
475 internal bool IsMultiForm {
476 get { return false; }
480 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
482 public HttpRequest Request
485 if (_context != null)
486 return _context.Request;
488 throw new HttpException("Request is not available without context");
492 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
494 public HttpResponse Response
497 if (_context != null)
498 return _context.Response;
500 throw new HttpException ("Response is not available without context");
504 [EditorBrowsable (EditorBrowsableState.Never)]
506 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
507 [BrowsableAttribute (false)]
508 public string ResponseEncoding
510 get { return Response.ContentEncoding.WebName; }
511 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
514 protected string ResponseEncoding
516 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
520 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
522 public HttpServerUtility Server
525 return Context.Server;
529 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
531 public virtual HttpSessionState Session
534 if (_context == null)
535 _context = HttpContext.Current;
537 if (_context == null)
538 throw new HttpException ("Session is not available without context");
540 if (_context.Session == null)
541 throw new HttpException ("Session state can only be used " +
542 "when enableSessionState is set to true, either " +
543 "in a configuration file or in the Page directive.");
545 return _context.Session;
550 [FilterableAttribute (false)]
554 public bool SmartNavigation
556 get { return _smartNavigation; }
557 set { _smartNavigation = value; }
561 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
564 public virtual string StyleSheetTheme {
565 get { return _styleSheetTheme; }
566 set { _styleSheetTheme = value; }
570 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
571 public virtual string Theme {
572 get { return _theme; }
573 set { _theme = value; }
576 void InitializeStyleSheet ()
578 if (_styleSheetTheme == null) {
579 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
581 _styleSheetTheme = ps.StyleSheetTheme;
583 if (_styleSheetTheme != null && _styleSheetTheme != "")
584 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, _context);
587 void InitializeTheme ()
589 if (_theme == null) {
590 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
594 if (_theme != null && _theme != "") {
595 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, _context);
596 _pageTheme.SetPage (this);
605 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
606 public string Title {
608 if (_title == null) {
609 if (htmlHeader != null)
610 return htmlHeader.Title;
616 if (htmlHeader != null)
617 htmlHeader.Title = value;
624 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
626 public TraceContext Trace
628 get { return Context.Trace; }
631 [EditorBrowsable (EditorBrowsableState.Never)]
633 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
634 [BrowsableAttribute (false)]
635 public bool TraceEnabled
637 get { return Trace.IsEnabled; }
638 set { Trace.IsEnabled = value; }
641 protected bool TraceEnabled
643 set { Trace.IsEnabled = value; }
647 [EditorBrowsable (EditorBrowsableState.Never)]
649 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
650 [BrowsableAttribute (false)]
651 public TraceMode TraceModeValue
653 get { return Trace.TraceMode; }
654 set { Trace.TraceMode = value; }
657 protected TraceMode TraceModeValue
659 set { Trace.TraceMode = value; }
663 [EditorBrowsable (EditorBrowsableState.Never)]
664 protected int TransactionMode
667 get { return _transactionMode; }
669 set { _transactionMode = value; }
674 // This method is here just to remove the warning about "_transactionMode" not being
675 // used. We probably will use it internally at some point.
677 internal int GetTransactionMode ()
679 return _transactionMode;
684 [EditorBrowsable (EditorBrowsableState.Advanced)]
685 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
686 [BrowsableAttribute (false)]
687 public string UICulture
689 get { return Thread.CurrentThread.CurrentUICulture.Name; }
690 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
693 [EditorBrowsable (EditorBrowsableState.Never)]
694 protected string UICulture
696 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
700 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
702 public IPrincipal User
704 get { return Context.User; }
707 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
709 public ValidatorCollection Validators
712 if (_validators == null)
713 _validators = new ValidatorCollection ();
718 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
720 public string ViewStateUserKey {
721 get { return viewStateUserKey; }
722 set { viewStateUserKey = value; }
726 public override bool Visible
728 get { return base.Visible; }
729 set { base.Visible = value; }
737 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
741 CultureInfo ret = null;
742 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
744 if (Context.IsPortletRequest)
747 string[] languages = Request.UserLanguages;
749 if (languages != null && languages.Length > 0)
750 ret = CultureInfo.CreateSpecificCulture (languages[0]);
757 ret = CultureInfo.CreateSpecificCulture (culture);
763 [EditorBrowsable (EditorBrowsableState.Never)]
764 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
768 throw new NotImplementedException ();
771 [EditorBrowsable (EditorBrowsableState.Never)]
772 protected void AspCompatEndProcessRequest (IAsyncResult result)
774 throw new NotImplementedException ();
777 [EditorBrowsable (EditorBrowsableState.Advanced)]
778 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
780 return new HtmlTextWriter (tw);
783 [EditorBrowsable (EditorBrowsableState.Never)]
784 public void DesignerInitialize ()
786 InitRecursive (null);
789 [EditorBrowsable (EditorBrowsableState.Advanced)]
790 protected virtual NameValueCollection DeterminePostBackMode ()
792 if (_context == null)
795 HttpRequest req = _context.Request;
799 NameValueCollection coll = null;
800 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
803 else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
807 coll = req.QueryString;
809 WebROCollection c = (WebROCollection) coll;
810 allow_load = !c.GotID;
812 c.ID = GetTypeHashCode ();
814 allow_load = (c.ID == GetTypeHashCode ());
816 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
823 public override Control FindControl (string id) {
827 return base.FindControl (id);
834 [EditorBrowsable (EditorBrowsableState.Advanced)]
835 public string GetPostBackClientEvent (Control control, string argument)
837 return scriptManager.GetPostBackEventReference (control, argument);
843 [EditorBrowsable (EditorBrowsableState.Advanced)]
844 public string GetPostBackClientHyperlink (Control control, string argument)
846 return scriptManager.GetPostBackClientHyperlink (control, argument);
852 [EditorBrowsable (EditorBrowsableState.Advanced)]
853 public string GetPostBackEventReference (Control control)
855 return scriptManager.GetPostBackEventReference (control, "");
861 [EditorBrowsable (EditorBrowsableState.Advanced)]
862 public string GetPostBackEventReference (Control control, string argument)
864 return scriptManager.GetPostBackEventReference (control, argument);
867 internal void RequiresPostBackScript ()
870 if (requiresPostBackScript)
872 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
873 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
875 requiresPostBackScript = true;
878 [EditorBrowsable (EditorBrowsableState.Never)]
879 public virtual int GetTypeHashCode ()
885 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
886 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
888 if (cacheSettings.Enabled)
889 InitOutputCache(cacheSettings.Duration,
890 cacheSettings.VaryByHeader,
891 cacheSettings.VaryByCustom,
892 cacheSettings.Location,
893 cacheSettings.VaryByParam);
897 [EditorBrowsable (EditorBrowsableState.Never)]
898 protected virtual void InitOutputCache (int duration,
901 OutputCacheLocation location,
904 HttpCachePolicy cache = _context.Response.Cache;
905 bool set_vary = false;
908 case OutputCacheLocation.Any:
909 cache.SetCacheability (HttpCacheability.Public);
910 cache.SetMaxAge (new TimeSpan (0, 0, duration));
911 cache.SetLastModified (_context.Timestamp);
914 case OutputCacheLocation.Client:
915 cache.SetCacheability (HttpCacheability.Private);
916 cache.SetMaxAge (new TimeSpan (0, 0, duration));
917 cache.SetLastModified (_context.Timestamp);
919 case OutputCacheLocation.Downstream:
920 cache.SetCacheability (HttpCacheability.Public);
921 cache.SetMaxAge (new TimeSpan (0, 0, duration));
922 cache.SetLastModified (_context.Timestamp);
924 case OutputCacheLocation.Server:
925 cache.SetCacheability (HttpCacheability.Server);
928 case OutputCacheLocation.None:
933 if (varyByCustom != null)
934 cache.SetVaryByCustom (varyByCustom);
936 if (varyByParam != null && varyByParam.Length > 0) {
937 string[] prms = varyByParam.Split (';');
938 foreach (string p in prms)
939 cache.VaryByParams [p.Trim ()] = true;
940 cache.VaryByParams.IgnoreParams = false;
942 cache.VaryByParams.IgnoreParams = true;
945 if (varyByHeader != null && varyByHeader.Length > 0) {
946 string[] hdrs = varyByHeader.Split (';');
947 foreach (string h in hdrs)
948 cache.VaryByHeaders [h.Trim ()] = true;
952 cache.Duration = duration;
953 cache.SetExpires (_context.Timestamp.AddSeconds (duration));
959 [EditorBrowsable (EditorBrowsableState.Advanced)]
961 public bool IsClientScriptBlockRegistered (string key)
963 return scriptManager.IsClientScriptBlockRegistered (key);
969 [EditorBrowsable (EditorBrowsableState.Advanced)]
971 public bool IsStartupScriptRegistered (string key)
973 return scriptManager.IsStartupScriptRegistered (key);
976 public string MapPath (string virtualPath)
978 return Request.MapPath (virtualPath);
982 protected internal override void Render (HtmlTextWriter writer) {
983 if (MaintainScrollPositionOnPostBack) {
984 ClientScript.RegisterWebFormClientScript ();
986 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
987 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
989 StringBuilder script = new StringBuilder ();
990 script.AppendLine ("<script type=\"text/javascript\">");
991 script.AppendLine ("<!--");
992 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
993 script.AppendLine (theForm + ".submit = WebForm_SaveScrollPositionSubmit;");
994 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
995 script.AppendLine (theForm + ".onsubmit = WebForm_SaveScrollPositionOnSubmit;");
997 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
998 script.AppendLine ("window.onload = function () { WebForm_RestoreScrollPosition (" + theForm + "); };");
1000 script.AppendLine ("// -->");
1001 script.AppendLine ("</script>");
1003 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1005 base.Render (writer);
1009 private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1012 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
1013 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
1015 writer.WriteLine ();
1017 ClientScriptManager.WriteBeginScriptBlock (writer);
1020 RenderClientScriptFormDeclaration (writer, formUniqueID);
1023 writer.WriteLine ("{0}._form = {0};", theForm);
1024 writer.Write (theForm + ".");
1027 writer.WriteLine ("window._form = {0};", theForm);
1029 writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
1031 writer.WriteLine ("\tif(this._form.onsubmit && this._form.onsubmit() == false) return;");
1033 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1035 writer.WriteLine ("\tthis._form.{0}.value = eventTarget;", postEventSourceID);
1036 writer.WriteLine ("\tthis._form.{0}.value = eventArgument;", postEventArgumentID);
1037 writer.WriteLine ("\tthis._form.submit();");
1038 writer.WriteLine ("}");
1039 ClientScriptManager.WriteEndScriptBlock (writer);
1042 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1044 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1045 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1046 writer.WriteLine ("\t{0}._instanceVariableName = '{0}';", theForm);
1048 string serverUrl = Context.ServletResponse.encodeURL (Request.RawUrl);
1049 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1050 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1051 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1055 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1058 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1060 renderingForm = true;
1061 writer.WriteLine ();
1064 ClientScriptManager.WriteBeginScriptBlock (writer);
1065 RenderClientScriptFormDeclaration (writer, formUniqueID);
1066 ClientScriptManager.WriteEndScriptBlock (writer);
1069 if (handleViewState)
1070 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1072 scriptManager.WriteHiddenFields (writer);
1073 if (requiresPostBackScript) {
1074 RenderPostBackScript (writer, formUniqueID);
1075 postBackScriptRendered = true;
1078 scriptManager.WriteWebFormClientScript (writer);
1080 scriptManager.WriteClientScriptBlocks (writer);
1083 internal IStateFormatter GetFormatter ()
1085 return new ObjectStateFormatter (this);
1088 internal string GetSavedViewState ()
1090 return _savedViewState;
1093 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1096 scriptManager.SaveEventValidationState ();
1097 scriptManager.WriteExpandoAttributes (writer);
1099 scriptManager.WriteHiddenFields (writer);
1100 if (!postBackScriptRendered && requiresPostBackScript)
1101 RenderPostBackScript (writer, formUniqueID);
1103 scriptManager.WriteWebFormClientScript (writer);
1106 scriptManager.WriteArrayDeclares (writer);
1107 scriptManager.WriteStartupScriptBlocks (writer);
1108 renderingForm = false;
1109 postBackScriptRendered = false;
1112 private void ProcessPostData (NameValueCollection data, bool second)
1114 NameValueCollection requestValues = _requestValueCollection == null ?
1115 new NameValueCollection () :
1116 _requestValueCollection;
1118 if (data != null && data.Count > 0) {
1119 Hashtable used = new Hashtable ();
1120 foreach (string id in data.AllKeys){
1121 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
1124 string real_id = id;
1125 int dot = real_id.IndexOf ('.');
1127 real_id = real_id.Substring (0, dot);
1129 if (real_id == null || used.ContainsKey (real_id))
1132 used.Add (real_id, real_id);
1134 Control ctrl = FindControl (real_id);
1136 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1137 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1141 RegisterRequiresRaiseEvent (pbeh);
1145 if (pbdh.LoadPostData (real_id, requestValues) == true) {
1146 if (requiresPostDataChanged == null)
1147 requiresPostDataChanged = new ArrayList ();
1148 requiresPostDataChanged.Add (pbdh);
1151 if (_requiresPostBackCopy != null)
1152 _requiresPostBackCopy.Remove (real_id);
1154 } else if (!second) {
1155 if (secondPostData == null)
1156 secondPostData = new NameValueCollection ();
1157 secondPostData.Add (real_id, data [id]);
1162 ArrayList list1 = null;
1163 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1164 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1165 foreach (string id in handlers) {
1166 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1168 _requiresPostBackCopy.Remove (id);
1169 if (pbdh.LoadPostData (id, requestValues)) {
1170 if (requiresPostDataChanged == null)
1171 requiresPostDataChanged = new ArrayList ();
1173 requiresPostDataChanged.Add (pbdh);
1175 } else if (!second) {
1177 list1 = new ArrayList ();
1182 _requiresPostBackCopy = second ? null : list1;
1184 secondPostData = null;
1187 [EditorBrowsable (EditorBrowsableState.Never)]
1189 public virtual void ProcessRequest (HttpContext context)
1191 public void ProcessRequest (HttpContext context)
1195 _lifeCycle = PageLifeCycle.Unknown;
1198 if (clientTarget != null)
1199 Request.ClientTarget = clientTarget;
1201 WireupAutomaticEvents ();
1202 //-- Control execution lifecycle in the docs
1204 // Save culture information because it can be modified in FrameworkInitialize()
1205 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1206 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1207 FrameworkInitialize ();
1208 context.ErrorPage = _errorPage;
1211 InternalProcessRequest ();
1212 } catch (ThreadAbortException) {
1213 // Do nothing, just ignore it by now.
1214 } catch (Exception e) {
1215 context.AddError (e); // OnError might access LastError
1216 OnError (EventArgs.Empty);
1217 context.ClearError (e);
1218 // We want to remove that error, as we're rethrowing to stop
1219 // further processing.
1220 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1225 _lifeCycle = PageLifeCycle.Unload;
1228 UnloadRecursive (true);
1230 _lifeCycle = PageLifeCycle.End;
1233 if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1234 Thread.CurrentThread.CurrentCulture = culture;
1236 if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1237 Thread.CurrentThread.CurrentUICulture = uiculture;
1242 delegate void ProcessRequestDelegate (HttpContext context);
1244 private sealed class DummyAsyncResult : IAsyncResult
1246 readonly object state;
1247 readonly WaitHandle asyncWaitHandle;
1248 readonly bool completedSynchronously;
1249 readonly bool isCompleted;
1251 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1253 this.isCompleted = isCompleted;
1254 this.completedSynchronously = completedSynchronously;
1257 asyncWaitHandle = new ManualResetEvent (true);
1260 asyncWaitHandle = new ManualResetEvent (false);
1264 #region IAsyncResult Members
1266 public object AsyncState {
1267 get { return state; }
1270 public WaitHandle AsyncWaitHandle {
1271 get { return asyncWaitHandle; }
1274 public bool CompletedSynchronously {
1275 get { return completedSynchronously; }
1278 public bool IsCompleted {
1279 get { return isCompleted; }
1285 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1287 ProcessRequest (context);
1288 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1290 if (callback != null) {
1291 callback (asyncResult);
1297 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1301 internal void ProcessCrossPagePostBack (HttpContext context)
1303 isCrossPagePostBack = true;
1304 ProcessRequest (context);
1308 void InternalProcessRequest ()
1310 _requestValueCollection = this.DeterminePostBackMode();
1313 _lifeCycle = PageLifeCycle.Start;
1314 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1315 if (_requestValueCollection != null) {
1316 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1317 _doLoadPreviousPage = true;
1320 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1321 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1322 //isPostBack = !isCallback;
1325 string lastFocus = _requestValueCollection [LastFocusID];
1326 if (!String.IsNullOrEmpty (lastFocus)) {
1327 _focusedControlID = UniqueID2ClientID (lastFocus);
1331 // if request was transfered from other page - track Prev. Page
1332 previousPage = _context.LastPage;
1333 _context.LastPage = this;
1335 _lifeCycle = PageLifeCycle.PreInit;
1336 OnPreInit (EventArgs.Empty);
1340 _lifeCycle = PageLifeCycle.Init;
1342 Trace.Write ("aspx.page", "Begin Init");
1343 InitRecursive (null);
1344 Trace.Write ("aspx.page", "End Init");
1347 _lifeCycle = PageLifeCycle.InitComplete;
1348 OnInitComplete (EventArgs.Empty);
1351 renderingForm = false;
1353 if (IsPostBack || IsCallback) {
1354 _lifeCycle = PageLifeCycle.PreLoad;
1355 if (_requestValueCollection != null)
1356 scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
1360 Trace.Write ("aspx.page", "Begin LoadViewState");
1361 LoadPageViewState ();
1362 Trace.Write ("aspx.page", "End LoadViewState");
1363 Trace.Write ("aspx.page", "Begin ProcessPostData");
1367 ProcessPostData (_requestValueCollection, false);
1368 Trace.Write ("aspx.page", "End ProcessPostData");
1372 OnPreLoad (EventArgs.Empty);
1373 _lifeCycle = PageLifeCycle.Load;
1381 if (IsPostBack || IsCallback) {
1382 _lifeCycle = PageLifeCycle.ControlEvents;
1386 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1387 ProcessPostData (secondPostData, true);
1388 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1389 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1390 RaiseChangedEvents ();
1391 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1392 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1393 RaisePostBackEvents ();
1394 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1398 _lifeCycle = PageLifeCycle.LoadComplete;
1399 OnLoadComplete (EventArgs.Empty);
1401 if (IsCrossPagePostBack)
1405 string result = ProcessCallbackData ();
1406 HtmlTextWriter callbackOutput = new HtmlTextWriter (_context.Response.Output);
1407 callbackOutput.Write (result);
1408 callbackOutput.Flush ();
1412 _lifeCycle = PageLifeCycle.PreRender;
1415 Trace.Write ("aspx.page", "Begin PreRender");
1416 PreRenderRecursiveInternal ();
1417 Trace.Write ("aspx.page", "End PreRender");
1420 ExecuteRegisteredAsyncTasks ();
1422 _lifeCycle = PageLifeCycle.PreRenderComplete;
1423 OnPreRenderComplete (EventArgs.Empty);
1426 Trace.Write ("aspx.page", "Begin SaveViewState");
1427 SavePageViewState ();
1428 Trace.Write ("aspx.page", "End SaveViewState");
1431 _lifeCycle = PageLifeCycle.SaveStateComplete;
1432 OnSaveStateComplete (EventArgs.Empty);
1434 if (OnSaveStateCompleteForPortlet ())
1436 #endif // TARGET_J2EE
1440 _lifeCycle = PageLifeCycle.Render;
1441 scriptManager.ResetEventValidationState ();
1445 Trace.Write ("aspx.page", "Begin Render");
1446 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1447 RenderControl (output);
1448 Trace.Write ("aspx.page", "End Render");
1451 private void RenderTrace ()
1453 TraceManager traceManager = HttpRuntime.TraceManager;
1455 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1460 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1463 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1464 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1465 Trace.Render (output);
1470 bool CheckForValidationSupport (Control targetControl)
1472 if (targetControl == null)
1474 Type type = targetControl.GetType ();
1475 object[] attributes = type.GetCustomAttributes (false);
1476 foreach (object attr in attributes)
1477 if (attr is SupportsEventValidationAttribute)
1483 void RaisePostBackEvents ()
1486 Control targetControl;
1488 if (requiresRaiseEvent != null) {
1489 RaisePostBackEvent (requiresRaiseEvent, null);
1493 NameValueCollection postdata = _requestValueCollection;
1494 if (postdata == null)
1497 string eventTarget = postdata [postEventSourceID];
1498 if (eventTarget == null || eventTarget.Length == 0) {
1504 targetControl = FindControl (eventTarget);
1505 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1507 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1513 string eventArgument = postdata [postEventArgumentID];
1514 RaisePostBackEvent (target, eventArgument);
1517 internal void RaiseChangedEvents ()
1519 if (requiresPostDataChanged == null)
1522 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1523 ipdh.RaisePostDataChangedEvent ();
1525 requiresPostDataChanged = null;
1528 [EditorBrowsable (EditorBrowsableState.Advanced)]
1529 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1532 Control targetControl = sourceControl as Control;
1533 if (targetControl != null && CheckForValidationSupport (targetControl))
1534 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1536 sourceControl.RaisePostBackEvent (eventArgument);
1542 [EditorBrowsable (EditorBrowsableState.Advanced)]
1543 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1545 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1551 [EditorBrowsable (EditorBrowsableState.Advanced)]
1552 public virtual void RegisterClientScriptBlock (string key, string script)
1554 scriptManager.RegisterClientScriptBlock (key, script);
1560 [EditorBrowsable (EditorBrowsableState.Advanced)]
1561 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1563 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1566 [MonoTODO("Not implemented, Used in HtmlForm")]
1567 internal void RegisterClientScriptFile (string a, string b, string c)
1569 throw new NotImplementedException ();
1575 [EditorBrowsable (EditorBrowsableState.Advanced)]
1576 public void RegisterOnSubmitStatement (string key, string script)
1578 scriptManager.RegisterOnSubmitStatement (key, script);
1581 internal string GetSubmitStatements ()
1583 return scriptManager.WriteSubmitStatements ();
1586 [EditorBrowsable (EditorBrowsableState.Advanced)]
1587 public void RegisterRequiresPostBack (Control control)
1590 if (!(control is IPostBackDataHandler))
1591 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1594 if (_requiresPostBack == null)
1595 _requiresPostBack = new ArrayList ();
1597 if (_requiresPostBack.Contains (control.UniqueID))
1600 _requiresPostBack.Add (control.UniqueID);
1603 [EditorBrowsable (EditorBrowsableState.Advanced)]
1604 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1606 requiresRaiseEvent = control;
1612 [EditorBrowsable (EditorBrowsableState.Advanced)]
1613 public virtual void RegisterStartupScript (string key, string script)
1615 scriptManager.RegisterStartupScript (key, script);
1618 [EditorBrowsable (EditorBrowsableState.Advanced)]
1619 public void RegisterViewStateHandler ()
1621 handleViewState = true;
1624 [EditorBrowsable (EditorBrowsableState.Advanced)]
1625 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1627 PageStatePersister persister = this.PageStatePersister;
1628 if (persister == null)
1630 Pair pair = viewState as Pair;
1632 persister.ViewState = pair.First;
1633 persister.ControlState = pair.Second;
1635 persister.ViewState = viewState;
1639 internal string RawViewState {
1641 NameValueCollection postdata = _requestValueCollection;
1643 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1646 if (view_state == "")
1650 set { _savedViewState = value; }
1658 PageStatePersister PageStatePersister {
1660 if (page_state_persister == null)
1661 page_state_persister = new HiddenFieldPageStatePersister (this);
1662 return page_state_persister;
1666 [EditorBrowsable (EditorBrowsableState.Advanced)]
1667 protected virtual object LoadPageStateFromPersistenceMedium ()
1669 PageStatePersister persister = this.PageStatePersister;
1670 if (persister == null)
1673 return new Pair (persister.ViewState, persister.ControlState);
1676 internal void LoadPageViewState()
1678 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1679 if (sState != null) {
1682 LoadPageControlState (sState.Second);
1684 Pair vsr = sState.First as Pair;
1686 LoadViewStateRecursive (vsr.First);
1687 _requiresPostBackCopy = vsr.Second as ArrayList;
1693 internal void SavePageViewState ()
1695 if (!handleViewState)
1699 object controlState = SavePageControlState ();
1702 object viewState = SaveViewStateRecursive ();
1703 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1706 if (viewState != null || reqPostback != null)
1707 vsr = new Pair (viewState, reqPostback);
1708 Pair pair = new Pair ();
1712 pair.Second = controlState;
1716 if (pair.First == null && pair.Second == null)
1717 SavePageStateToPersistenceMedium (null);
1719 SavePageStateToPersistenceMedium (pair);
1723 public virtual void Validate ()
1725 is_validated = true;
1726 ValidateCollection (_validators);
1730 internal bool AreValidatorsUplevel () {
1731 return AreValidatorsUplevel (String.Empty);
1734 internal bool AreValidatorsUplevel (string valGroup)
1736 internal virtual bool AreValidatorsUplevel ()
1739 bool uplevel = false;
1741 foreach (IValidator v in Validators) {
1742 BaseValidator bv = v as BaseValidator;
1743 if (bv == null) continue;
1746 if (valGroup != bv.ValidationGroup)
1749 if (bv.GetRenderUplevel()) {
1758 bool ValidateCollection (ValidatorCollection validators)
1761 if (!_eventValidation)
1765 if (validators == null || validators.Count == 0)
1768 bool all_valid = true;
1769 foreach (IValidator v in validators){
1771 if (v.IsValid == false)
1778 [EditorBrowsable (EditorBrowsableState.Advanced)]
1779 public virtual void VerifyRenderingInServerForm (Control control)
1781 if (_context == null)
1788 throw new HttpException ("Control '" +
1791 control.GetType ().Name +
1792 "' must be placed inside a form tag with runat=server.");
1795 protected override void FrameworkInitialize ()
1797 base.FrameworkInitialize ();
1799 InitializeStyleSheet ();
1810 ClientScriptManager ClientScript {
1811 get { return scriptManager; }
1816 static readonly object InitCompleteEvent = new object ();
1817 static readonly object LoadCompleteEvent = new object ();
1818 static readonly object PreInitEvent = new object ();
1819 static readonly object PreLoadEvent = new object ();
1820 static readonly object PreRenderCompleteEvent = new object ();
1821 static readonly object SaveStateCompleteEvent = new object ();
1823 const int initcomplete_mask = 1;
1824 const int loadcomplete_mask = 1 << 1;
1825 const int preinit_mask = 1 << 2;
1826 const int preload_mask = 1 << 3;
1827 const int prerendercomplete_mask = 1 << 4;
1828 const int savestatecomplete_mask = 1 << 5;
1830 [EditorBrowsable (EditorBrowsableState.Advanced)]
1831 public event EventHandler InitComplete {
1833 event_mask |= initcomplete_mask;
1834 Events.AddHandler (InitCompleteEvent, value);
1836 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1839 [EditorBrowsable (EditorBrowsableState.Advanced)]
1840 public event EventHandler LoadComplete {
1842 event_mask |= loadcomplete_mask;
1843 Events.AddHandler (LoadCompleteEvent, value);
1845 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1848 public event EventHandler PreInit {
1850 event_mask |= preinit_mask;
1851 Events.AddHandler (PreInitEvent, value);
1853 remove { Events.RemoveHandler (PreInitEvent, value); }
1856 [EditorBrowsable (EditorBrowsableState.Advanced)]
1857 public event EventHandler PreLoad {
1859 event_mask |= preload_mask;
1860 Events.AddHandler (PreLoadEvent, value);
1862 remove { Events.RemoveHandler (PreLoadEvent, value); }
1865 [EditorBrowsable (EditorBrowsableState.Advanced)]
1866 public event EventHandler PreRenderComplete {
1868 event_mask |= prerendercomplete_mask;
1869 Events.AddHandler (PreRenderCompleteEvent, value);
1871 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1874 [EditorBrowsable (EditorBrowsableState.Advanced)]
1875 public event EventHandler SaveStateComplete {
1877 event_mask |= savestatecomplete_mask;
1878 Events.AddHandler (SaveStateCompleteEvent, value);
1880 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1883 protected virtual void OnInitComplete (EventArgs e)
1885 if ((event_mask & initcomplete_mask) != 0) {
1886 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1887 if (eh != null) eh (this, e);
1891 protected virtual void OnLoadComplete (EventArgs e)
1893 if ((event_mask & loadcomplete_mask) != 0) {
1894 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1895 if (eh != null) eh (this, e);
1899 protected virtual void OnPreInit (EventArgs e)
1901 if ((event_mask & preinit_mask) != 0) {
1902 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1903 if (eh != null) eh (this, e);
1907 protected virtual void OnPreLoad (EventArgs e)
1909 if ((event_mask & preload_mask) != 0) {
1910 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1911 if (eh != null) eh (this, e);
1915 protected virtual void OnPreRenderComplete (EventArgs e)
1917 if ((event_mask & prerendercomplete_mask) != 0) {
1918 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1919 if (eh != null) eh (this, e);
1924 if (!Form.DetermineRenderUplevel ())
1927 /* figure out if we have some control we're going to focus */
1928 if (String.IsNullOrEmpty (_focusedControlID)) {
1929 _focusedControlID = Form.DefaultFocus;
1930 if (String.IsNullOrEmpty (_focusedControlID))
1931 _focusedControlID = Form.DefaultButton;
1934 if (!String.IsNullOrEmpty (_focusedControlID)) {
1935 ClientScript.RegisterWebFormClientScript ();
1936 ClientScript.RegisterStartupScript ("HtmlForm-DefaultButton-StartupScript",
1937 String.Format ("<script type=\"text/javascript\">\n" +
1939 "WebForm_AutoFocus('{0}');// -->\n" +
1940 "</script>\n", _focusedControlID));
1943 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1944 ClientScript.RegisterWebFormClientScript ();
1945 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1946 "WebForm_ReEnableControls(this);");
1950 internal void RegisterEnabledControl (Control control)
1952 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1954 _hasEnabledControlArray = true;
1955 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Format ("'{0}'", control.ClientID));
1958 protected virtual void OnSaveStateComplete (EventArgs e)
1960 if ((event_mask & savestatecomplete_mask) != 0) {
1961 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1962 if (eh != null) eh (this, e);
1966 public HtmlForm Form {
1967 get { return _form; }
1970 internal void RegisterForm (HtmlForm form)
1975 [BrowsableAttribute (false)]
1976 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1977 public Page PreviousPage {
1979 if (_doLoadPreviousPage) {
1980 _doLoadPreviousPage = false;
1981 LoadPreviousPageReference ();
1983 return previousPage;
1988 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1989 [BrowsableAttribute (false)]
1990 public bool IsCallback {
1991 get { return isCallback; }
1994 [BrowsableAttribute (false)]
1995 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1996 public bool IsCrossPagePostBack {
1997 get { return isCrossPagePostBack; }
2000 public new virtual char IdSeparator {
2002 //TODO: why override?
2003 return base.IdSeparator;
2007 string ProcessCallbackData ()
2009 string callbackTarget = _requestValueCollection [CallbackSourceID];
2010 if (callbackTarget == null || callbackTarget.Length == 0)
2011 throw new HttpException ("Callback target not provided.");
2013 Control targetControl = FindControl (callbackTarget);
2014 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2016 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2018 string callbackEventError = String.Empty;
2019 string callBackResult;
2020 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2023 target.RaiseCallbackEvent (callbackArgument);
2025 catch (Exception ex) {
2026 callbackEventError = String.Format ("e{0}", ex.Message);
2030 callBackResult = target.GetCallbackResult ();
2032 catch (Exception ex) {
2033 return String.Format ("e{0}", ex.Message);
2036 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2037 return String.Format ("{0}{1}|{2}{3}", callbackEventError, eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
2040 [BrowsableAttribute (false)]
2041 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2042 public HtmlHead Header {
2043 get { return htmlHeader; }
2046 internal void SetHeader (HtmlHead header)
2048 htmlHeader = header;
2049 if (_title != null) {
2050 htmlHeader.Title = _title;
2055 protected bool AsyncMode {
2056 get { return asyncMode; }
2057 set { asyncMode = value; }
2060 public TimeSpan AsyncTimeout {
2061 get { return asyncTimeout; }
2062 set { asyncTimeout = value; }
2065 public bool IsAsync {
2066 get { return AsyncMode; }
2069 [MonoTODO ("Not Implemented")]
2070 protected internal virtual string UniqueFilePathSuffix {
2072 throw new NotImplementedException ();
2076 [MonoTODO ("Not Implemented")]
2077 public int MaxPageStateFieldLength {
2079 throw new NotImplementedException ();
2082 throw new NotImplementedException ();
2086 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2088 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2091 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2094 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2097 if (_lifeCycle >= PageLifeCycle.PreRender) {
2098 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
2101 if (beginHandler == null) {
2102 throw new ArgumentNullException ("beginHandler");
2105 if (endHandler == null) {
2106 throw new ArgumentNullException ("endHandler");
2109 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2112 private List<PageAsyncTask> ParallelTasks {
2115 if (parallelTasks == null) {
2116 parallelTasks = new List<PageAsyncTask>();
2118 return parallelTasks;
2122 private List<PageAsyncTask> SerialTasks {
2124 if (serialTasks == null) {
2125 serialTasks = new List<PageAsyncTask> ();
2131 public void RegisterAsyncTask (PageAsyncTask task)
2134 throw new ArgumentNullException ("task");
2137 if (task.ExecuteInParallel) {
2138 ParallelTasks.Add (task);
2141 SerialTasks.Add (task);
2145 public void ExecuteRegisteredAsyncTasks ()
2147 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2148 (serialTasks == null || serialTasks.Count == 0)){
2152 if (parallelTasks != null) {
2153 DateTime startExecution = DateTime.Now;
2154 List<PageAsyncTask> localParallelTasks = parallelTasks;
2155 parallelTasks = null; // Shouldn't execute tasks twice
2156 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2157 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2158 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2159 if (result.CompletedSynchronously) {
2160 parallelTask.EndHandler (result);
2163 asyncResults.Add (result);
2167 if (asyncResults.Count > 0) {
2169 TimeSpan timeout = AsyncTimeout;
2170 long t1 = DateTime.Now.Ticks;
2171 bool signalled = true;
2172 for (int i = 0; i < asyncResults.Count; i++) {
2173 if (asyncResults [i].IsCompleted)
2177 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2180 long t2 = DateTime.Now.Ticks;
2181 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2182 if (timeout.Ticks <= 0)
2186 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2190 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2192 for (i = 0; i < asyncResults.Count; i++) {
2193 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2195 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2196 if (!allSignalled) {
2197 for (i = 0; i < asyncResults.Count; i++) {
2198 if (!asyncResults [i].IsCompleted) {
2199 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2205 DateTime endWait = DateTime.Now;
2206 TimeSpan elapsed = endWait - startExecution;
2207 if (elapsed <= AsyncTimeout) {
2208 AsyncTimeout -= elapsed;
2211 AsyncTimeout = TimeSpan.FromTicks(0);
2215 if (serialTasks != null) {
2216 List<PageAsyncTask> localSerialTasks = serialTasks;
2217 serialTasks = null; // Shouldn't execute tasks twice
2218 foreach (PageAsyncTask serialTask in localSerialTasks) {
2219 DateTime startExecution = DateTime.Now;
2221 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2222 if (result.CompletedSynchronously) {
2223 serialTask.EndHandler (result);
2226 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2227 if (!done && !result.IsCompleted) {
2228 serialTask.TimeoutHandler (result);
2231 DateTime endWait = DateTime.Now;
2232 TimeSpan elapsed = endWait - startExecution;
2233 if (elapsed <= AsyncTimeout) {
2234 AsyncTimeout -= elapsed;
2237 AsyncTimeout = TimeSpan.FromTicks (0);
2241 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2244 void EndAsyncTaskCallback (IAsyncResult result)
2246 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2247 task.EndHandler (result);
2250 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2252 Type htmlTextWriterType = typeof (HtmlTextWriter);
2254 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2255 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2258 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2259 if (constructor == null) {
2260 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2263 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2266 public ViewStateEncryptionMode ViewStateEncryptionMode {
2267 get { return viewStateEncryptionMode; }
2268 set { viewStateEncryptionMode = value; }
2271 public void RegisterRequiresViewStateEncryption ()
2273 controlRegisteredForViewStateEncryption = true;
2276 private static byte [] AES_IV = null;
2277 private static byte [] TripleDES_IV = null;
2278 private static object locker = new object ();
2279 private static bool isEncryptionInitialized = false;
2281 private static void InitializeEncryption ()
2283 if (isEncryptionInitialized) {
2288 if (isEncryptionInitialized) {
2292 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2293 AES_IV = new byte [16];
2294 TripleDES_IV = new byte [8];
2297 for (i = 0; i < AES_IV.Length; i++) {
2298 AES_IV [i] = (byte) iv_string [i];
2301 for (i = 0; i < TripleDES_IV.Length; i++) {
2302 TripleDES_IV [i] = (byte) iv_string [i];
2305 isEncryptionInitialized = true;
2309 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2311 ICryptoTransform transform = null;
2312 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2313 byte [] vk = config.ValidationKeyBytes;
2315 switch (config.Validation) {
2316 case MachineKeyValidation.SHA1:
2317 transform = SHA1.Create ();
2320 case MachineKeyValidation.MD5:
2321 transform = MD5.Create ();
2324 case MachineKeyValidation.AES:
2325 if (cryptoStreamMode == CryptoStreamMode.Read){
2326 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2328 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2332 case MachineKeyValidation.TripleDES:
2333 if (cryptoStreamMode == CryptoStreamMode.Read){
2334 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2336 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2344 internal bool NeedViewStateEncryption {
2346 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2347 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2348 controlRegisteredForViewStateEncryption));
2353 void ApplyMasterPage ()
2355 if (masterPageFile != null && masterPageFile.Length > 0) {
2356 ArrayList appliedMasterPageFiles = new ArrayList ();
2358 if (Master != null) {
2359 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2363 Controls.Add (Master);
2368 [DefaultValueAttribute ("")]
2369 public virtual string MasterPageFile {
2370 get { return masterPageFile; }
2372 masterPageFile = value;
2377 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2378 [BrowsableAttribute (false)]
2379 public MasterPage Master {
2381 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2384 if (masterPage == null)
2385 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2391 public void SetFocus (string clientID)
2393 if (String.IsNullOrEmpty (clientID))
2394 throw new ArgumentNullException ("control");
2396 if (_lifeCycle > PageLifeCycle.PreRender)
2397 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2400 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2402 _focusedControlID = clientID;
2405 public void SetFocus (Control control)
2407 if (control == null)
2408 throw new ArgumentNullException ("control");
2410 SetFocus (control.ClientID);
2413 [EditorBrowsable (EditorBrowsableState.Advanced)]
2414 public void RegisterRequiresControlState (Control control)
2416 if (control == null)
2417 throw new ArgumentNullException ("control");
2419 if (RequiresControlState (control))
2422 if (requireStateControls == null)
2423 requireStateControls = new ArrayList ();
2424 int n = requireStateControls.Add (control);
2426 if (_savedControlState == null || n >= _savedControlState.Length)
2429 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2430 if (parent.IsChildControlStateCleared)
2433 object state = _savedControlState [n];
2435 control.LoadControlState (state);
2438 public bool RequiresControlState (Control control)
2440 if (requireStateControls == null) return false;
2441 return requireStateControls.Contains (control);
2444 [EditorBrowsable (EditorBrowsableState.Advanced)]
2445 public void UnregisterRequiresControlState (Control control)
2447 if (requireStateControls != null)
2448 requireStateControls.Remove (control);
2451 public ValidatorCollection GetValidators (string validationGroup)
2453 string valgr = validationGroup;
2455 valgr = String.Empty;
2457 if (_validatorsByGroup == null) _validatorsByGroup = new Hashtable ();
2458 ValidatorCollection col = _validatorsByGroup [valgr] as ValidatorCollection;
2460 col = new ValidatorCollection ();
2461 _validatorsByGroup [valgr] = col;
2466 public virtual void Validate (string validationGroup)
2468 is_validated = true;
2469 if (validationGroup == null)
2470 ValidateCollection (_validatorsByGroup [String.Empty] as ValidatorCollection);
2471 else if (_validatorsByGroup != null) {
2472 ValidateCollection (_validatorsByGroup [validationGroup] as ValidatorCollection);
2476 object SavePageControlState ()
2478 if (requireStateControls == null) return null;
2479 object[] state = new object [requireStateControls.Count];
2481 bool allNull = true;
2482 for (int n=0; n<state.Length; n++) {
2483 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2484 if (state [n] != null) allNull = false;
2486 if (allNull) return null;
2490 void LoadPageControlState (object data)
2492 _savedControlState = (object []) data;
2494 if (requireStateControls == null) return;
2496 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2497 for (int n=0; n < max; n++) {
2498 Control ctl = (Control) requireStateControls [n];
2499 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2503 void LoadPreviousPageReference ()
2505 if (_requestValueCollection != null) {
2506 string prevPage = _requestValueCollection [PreviousPageID];
2507 if (prevPage != null) {
2508 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2509 previousPage.ProcessCrossPagePostBack (_context);
2515 Hashtable contentTemplates;
2516 [EditorBrowsable (EditorBrowsableState.Never)]
2517 protected internal void AddContentTemplate (string templateName, ITemplate template)
2519 if (contentTemplates == null)
2520 contentTemplates = new Hashtable ();
2521 contentTemplates [templateName] = template;
2524 PageTheme _pageTheme;
2525 internal PageTheme PageTheme {
2526 get { return _pageTheme; }
2529 PageTheme _styleSheetPageTheme;
2530 internal PageTheme StyleSheetPageTheme {
2531 get { return _styleSheetPageTheme; }
2536 internal void PushDataItemContext (object o) {
2537 if (dataItemCtx == null)
2538 dataItemCtx = new Stack ();
2540 dataItemCtx.Push (o);
2543 internal void PopDataItemContext () {
2544 if (dataItemCtx == null)
2545 throw new InvalidOperationException ();
2550 public object GetDataItem() {
2551 if (dataItemCtx == null || dataItemCtx.Count == 0)
2552 throw new InvalidOperationException ("No data item");
2554 return dataItemCtx.Peek ();
2557 protected internal override void OnInit (EventArgs e)
2561 ArrayList themes = new ArrayList();
2563 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2564 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2565 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2566 themes.AddRange (PageTheme.GetStyleSheets ());
2568 if (themes.Count > 0 && Header == null)
2569 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2571 foreach (string lss in themes) {
2572 HtmlLink hl = new HtmlLink ();
2573 hl.Href = ResolveUrl (lss);
2574 hl.Attributes["type"] = "text/css";
2575 hl.Attributes["rel"] = "stylesheet";
2576 Header.Controls.Add (hl);
2583 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2584 protected object GetWrappedFileDependencies (string [] list)
2589 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2590 protected virtual void InitializeCulture ()
2594 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2595 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)