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);
174 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
176 asyncTimeout = ps.AsyncTimeout;
177 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
179 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
180 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
189 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
191 public HttpApplicationState Application
194 if (_context == null)
196 return _context.Application;
200 [EditorBrowsable (EditorBrowsableState.Never)]
201 protected bool AspCompatMode
204 get { return false; }
206 set { throw new NotImplementedException (); }
209 [EditorBrowsable (EditorBrowsableState.Never)]
211 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
212 [BrowsableAttribute (false)]
215 get { return Response.BufferOutput; }
216 set { Response.BufferOutput = value; }
219 protected bool Buffer
221 set { Response.BufferOutput = value; }
225 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
230 if (_context == null)
231 throw new HttpException ("No cache available without a context.");
232 return _context.Cache;
237 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
239 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
240 [Browsable (false), DefaultValue ("")]
241 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
242 public string ClientTarget
244 get { return (clientTarget == null) ? "" : clientTarget; }
246 clientTarget = value;
252 [EditorBrowsable (EditorBrowsableState.Never)]
254 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
255 [BrowsableAttribute (false)]
258 get { return Response.ContentEncoding.CodePage; }
259 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
262 protected int CodePage
264 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
268 [EditorBrowsable (EditorBrowsableState.Never)]
270 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
271 [BrowsableAttribute (false)]
272 public string ContentType
274 get { return Response.ContentType; }
275 set { Response.ContentType = value; }
278 protected string ContentType
280 set { Response.ContentType = value; }
284 protected override HttpContext Context
287 if (_context == null)
288 return HttpContext.Current;
295 [EditorBrowsable (EditorBrowsableState.Advanced)]
296 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
297 [BrowsableAttribute (false)]
298 public string Culture
300 get { return Thread.CurrentThread.CurrentCulture.Name; }
301 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
304 [EditorBrowsable (EditorBrowsableState.Never)]
305 protected string Culture
307 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
312 public virtual bool EnableEventValidation {
313 get { return _eventValidation; }
315 if (_lifeCycle > PageLifeCycle.Init)
316 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
317 _eventValidation = value;
321 internal PageLifeCycle LifeCycle {
322 get { return _lifeCycle; }
327 public override bool EnableViewState
329 get { return _viewState; }
330 set { _viewState = value; }
334 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
335 [BrowsableAttribute (false)]
337 [EditorBrowsable (EditorBrowsableState.Never)]
343 bool EnableViewStateMac
345 get { return _viewStateMac; }
346 set { _viewStateMac = value; }
350 internal bool EnableViewStateMacInternal {
351 get { return _viewStateMac; }
352 set { _viewStateMac = value; }
356 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
357 [Browsable (false), DefaultValue ("")]
358 [WebSysDescription ("The URL of a page used for error redirection.")]
359 public string ErrorPage
361 get { return _errorPage; }
364 if (_context != null)
365 _context.ErrorPage = value;
372 [EditorBrowsable (EditorBrowsableState.Never)]
373 protected ArrayList FileDependencies
376 if (Response != null)
377 Response.AddFileDependencies (value);
383 [EditorBrowsable (EditorBrowsableState.Never)]
385 public override string ID
387 get { return base.ID; }
388 set { base.ID = value; }
391 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
393 public bool IsPostBack
399 return _requestValueCollection != null;
404 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
405 public bool IsReusable {
406 get { return false; }
409 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
411 public bool IsValid {
414 throw new HttpException (Locale.GetText ("Page hasn't been validated."));
417 foreach (IValidator val in Validators)
422 return ValidateCollection (_validators);
427 public IDictionary Items {
430 items = new Hashtable ();
436 [EditorBrowsable (EditorBrowsableState.Never)]
438 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
439 [BrowsableAttribute (false)]
441 get { return Thread.CurrentThread.CurrentCulture.LCID; }
442 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
446 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
452 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
453 public bool MaintainScrollPositionOnPostBack {
454 get { return _maintainScrollPositionOnPostBack; }
455 set { _maintainScrollPositionOnPostBack = value; }
460 public PageAdapter PageAdapter {
462 return (PageAdapter)Adapter;
468 internal string theForm {
474 internal bool IsMultiForm {
475 get { return false; }
479 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
481 public HttpRequest Request
484 if (_context != null)
485 return _context.Request;
487 throw new HttpException("Request is not available without context");
491 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
493 public HttpResponse Response
496 if (_context != null)
497 return _context.Response;
499 throw new HttpException ("Response is not available without context");
503 [EditorBrowsable (EditorBrowsableState.Never)]
505 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
506 [BrowsableAttribute (false)]
507 public string ResponseEncoding
509 get { return Response.ContentEncoding.WebName; }
510 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
513 protected string ResponseEncoding
515 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
519 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
521 public HttpServerUtility Server
524 return Context.Server;
528 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
530 public virtual HttpSessionState Session
533 if (_context == null)
534 _context = HttpContext.Current;
536 if (_context == null)
537 throw new HttpException ("Session is not available without context");
539 if (_context.Session == null)
540 throw new HttpException ("Session state can only be used " +
541 "when enableSessionState is set to true, either " +
542 "in a configuration file or in the Page directive.");
544 return _context.Session;
549 [FilterableAttribute (false)]
553 public bool SmartNavigation
555 get { return _smartNavigation; }
556 set { _smartNavigation = value; }
560 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
563 public virtual string StyleSheetTheme {
564 get { return _styleSheetTheme; }
565 set { _styleSheetTheme = value; }
569 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
570 public virtual string Theme {
571 get { return _theme; }
572 set { _theme = value; }
575 void InitializeStyleSheet ()
577 if (_styleSheetTheme == null) {
578 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
580 _styleSheetTheme = ps.StyleSheetTheme;
582 if (_styleSheetTheme != null && _styleSheetTheme != "")
583 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, _context);
586 void InitializeTheme ()
588 if (_theme == null) {
589 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
593 if (_theme != null && _theme != "") {
594 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, _context);
595 _pageTheme.SetPage (this);
604 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
605 public string Title {
607 if (_title == null) {
608 if (htmlHeader != null)
609 return htmlHeader.Title;
615 if (htmlHeader != null)
616 htmlHeader.Title = value;
623 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
625 public TraceContext Trace
627 get { return Context.Trace; }
630 [EditorBrowsable (EditorBrowsableState.Never)]
632 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
633 [BrowsableAttribute (false)]
634 public bool TraceEnabled
636 get { return Trace.IsEnabled; }
637 set { Trace.IsEnabled = value; }
640 protected bool TraceEnabled
642 set { Trace.IsEnabled = value; }
646 [EditorBrowsable (EditorBrowsableState.Never)]
648 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
649 [BrowsableAttribute (false)]
650 public TraceMode TraceModeValue
652 get { return Trace.TraceMode; }
653 set { Trace.TraceMode = value; }
656 protected TraceMode TraceModeValue
658 set { Trace.TraceMode = value; }
662 [EditorBrowsable (EditorBrowsableState.Never)]
663 protected int TransactionMode
666 get { return _transactionMode; }
668 set { _transactionMode = value; }
673 // This method is here just to remove the warning about "_transactionMode" not being
674 // used. We probably will use it internally at some point.
676 internal int GetTransactionMode ()
678 return _transactionMode;
683 [EditorBrowsable (EditorBrowsableState.Advanced)]
684 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
685 [BrowsableAttribute (false)]
686 public string UICulture
688 get { return Thread.CurrentThread.CurrentUICulture.Name; }
689 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
692 [EditorBrowsable (EditorBrowsableState.Never)]
693 protected string UICulture
695 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
699 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
701 public IPrincipal User
703 get { return Context.User; }
706 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
708 public ValidatorCollection Validators
711 if (_validators == null)
712 _validators = new ValidatorCollection ();
717 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
719 public string ViewStateUserKey {
720 get { return viewStateUserKey; }
721 set { viewStateUserKey = value; }
725 public override bool Visible
727 get { return base.Visible; }
728 set { base.Visible = value; }
736 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
740 CultureInfo ret = null;
741 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
743 if (Context.IsPortletRequest)
746 string[] languages = Request.UserLanguages;
748 if (languages != null && languages.Length > 0)
749 ret = CultureInfo.CreateSpecificCulture (languages[0]);
756 ret = CultureInfo.CreateSpecificCulture (culture);
762 [EditorBrowsable (EditorBrowsableState.Never)]
763 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
767 throw new NotImplementedException ();
770 [EditorBrowsable (EditorBrowsableState.Never)]
771 protected void AspCompatEndProcessRequest (IAsyncResult result)
773 throw new NotImplementedException ();
776 [EditorBrowsable (EditorBrowsableState.Advanced)]
777 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
779 return new HtmlTextWriter (tw);
782 [EditorBrowsable (EditorBrowsableState.Never)]
783 public void DesignerInitialize ()
785 InitRecursive (null);
788 [EditorBrowsable (EditorBrowsableState.Advanced)]
789 protected virtual NameValueCollection DeterminePostBackMode ()
791 if (_context == null)
794 HttpRequest req = _context.Request;
798 NameValueCollection coll = null;
799 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
802 else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
806 coll = req.QueryString;
808 WebROCollection c = (WebROCollection) coll;
809 allow_load = !c.GotID;
811 c.ID = GetTypeHashCode ();
813 allow_load = (c.ID == GetTypeHashCode ());
815 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
822 public override Control FindControl (string id) {
826 return base.FindControl (id);
833 [EditorBrowsable (EditorBrowsableState.Advanced)]
834 public string GetPostBackClientEvent (Control control, string argument)
836 return scriptManager.GetPostBackEventReference (control, argument);
842 [EditorBrowsable (EditorBrowsableState.Advanced)]
843 public string GetPostBackClientHyperlink (Control control, string argument)
845 return scriptManager.GetPostBackClientHyperlink (control, argument);
851 [EditorBrowsable (EditorBrowsableState.Advanced)]
852 public string GetPostBackEventReference (Control control)
854 return scriptManager.GetPostBackEventReference (control, "");
860 [EditorBrowsable (EditorBrowsableState.Advanced)]
861 public string GetPostBackEventReference (Control control, string argument)
863 return scriptManager.GetPostBackEventReference (control, argument);
866 internal void RequiresPostBackScript ()
869 if (requiresPostBackScript)
871 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
872 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
874 requiresPostBackScript = true;
877 [EditorBrowsable (EditorBrowsableState.Never)]
878 public virtual int GetTypeHashCode ()
884 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
885 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
887 if (cacheSettings.Enabled)
888 InitOutputCache(cacheSettings.Duration,
889 cacheSettings.VaryByHeader,
890 cacheSettings.VaryByCustom,
891 cacheSettings.Location,
892 cacheSettings.VaryByParam);
896 [EditorBrowsable (EditorBrowsableState.Never)]
897 protected virtual void InitOutputCache (int duration,
900 OutputCacheLocation location,
903 HttpCachePolicy cache = _context.Response.Cache;
904 bool set_vary = false;
907 case OutputCacheLocation.Any:
908 cache.SetCacheability (HttpCacheability.Public);
909 cache.SetMaxAge (new TimeSpan (0, 0, duration));
910 cache.SetLastModified (_context.Timestamp);
913 case OutputCacheLocation.Client:
914 cache.SetCacheability (HttpCacheability.Private);
915 cache.SetMaxAge (new TimeSpan (0, 0, duration));
916 cache.SetLastModified (_context.Timestamp);
918 case OutputCacheLocation.Downstream:
919 cache.SetCacheability (HttpCacheability.Public);
920 cache.SetMaxAge (new TimeSpan (0, 0, duration));
921 cache.SetLastModified (_context.Timestamp);
923 case OutputCacheLocation.Server:
924 cache.SetCacheability (HttpCacheability.Server);
927 case OutputCacheLocation.None:
932 if (varyByCustom != null)
933 cache.SetVaryByCustom (varyByCustom);
935 if (varyByParam != null && varyByParam.Length > 0) {
936 string[] prms = varyByParam.Split (';');
937 foreach (string p in prms)
938 cache.VaryByParams [p.Trim ()] = true;
939 cache.VaryByParams.IgnoreParams = false;
941 cache.VaryByParams.IgnoreParams = true;
944 if (varyByHeader != null && varyByHeader.Length > 0) {
945 string[] hdrs = varyByHeader.Split (';');
946 foreach (string h in hdrs)
947 cache.VaryByHeaders [h.Trim ()] = true;
951 cache.Duration = duration;
952 cache.SetExpires (_context.Timestamp.AddSeconds (duration));
958 [EditorBrowsable (EditorBrowsableState.Advanced)]
960 public bool IsClientScriptBlockRegistered (string key)
962 return scriptManager.IsClientScriptBlockRegistered (key);
968 [EditorBrowsable (EditorBrowsableState.Advanced)]
970 public bool IsStartupScriptRegistered (string key)
972 return scriptManager.IsStartupScriptRegistered (key);
975 public string MapPath (string virtualPath)
977 return Request.MapPath (virtualPath);
981 protected internal override void Render (HtmlTextWriter writer) {
982 if (MaintainScrollPositionOnPostBack) {
983 ClientScript.RegisterWebFormClientScript ();
985 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
986 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
988 StringBuilder script = new StringBuilder ();
989 script.AppendLine ("<script type=\"text/javascript\">");
990 script.AppendLine ("<!--");
991 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
992 script.AppendLine (theForm + ".submit = WebForm_SaveScrollPositionSubmit;");
993 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
994 script.AppendLine (theForm + ".onsubmit = WebForm_SaveScrollPositionOnSubmit;");
996 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
997 script.AppendLine ("window.onload = function () { WebForm_RestoreScrollPosition (" + theForm + "); };");
999 script.AppendLine ("// -->");
1000 script.AppendLine ("</script>");
1002 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1004 scriptManager.ResetEventValidationState ();
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)
1115 Hashtable used = new Hashtable ();
1116 foreach (string id in data.AllKeys){
1117 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
1120 string real_id = id;
1121 int dot = real_id.IndexOf ('.');
1123 real_id = real_id.Substring (0, dot);
1125 if (real_id == null || used.ContainsKey (real_id))
1128 used.Add (real_id, real_id);
1130 Control ctrl = FindControl (real_id);
1132 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1133 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1137 RegisterRequiresRaiseEvent (pbeh);
1141 if (pbdh.LoadPostData (real_id, data) == true) {
1142 if (requiresPostDataChanged == null)
1143 requiresPostDataChanged = new ArrayList ();
1144 requiresPostDataChanged.Add (pbdh);
1147 if (_requiresPostBackCopy != null)
1148 _requiresPostBackCopy.Remove (real_id);
1150 } else if (!second) {
1151 if (secondPostData == null)
1152 secondPostData = new NameValueCollection ();
1153 secondPostData.Add (real_id, data [id]);
1158 ArrayList list1 = null;
1159 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1160 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1161 foreach (string id in handlers) {
1162 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1164 _requiresPostBackCopy.Remove (id);
1165 if (pbdh.LoadPostData (id, data)) {
1166 if (requiresPostDataChanged == null)
1167 requiresPostDataChanged = new ArrayList ();
1169 requiresPostDataChanged.Add (pbdh);
1171 } else if (!second) {
1173 list1 = new ArrayList ();
1178 _requiresPostBackCopy = second ? null : list1;
1180 secondPostData = null;
1183 [EditorBrowsable (EditorBrowsableState.Never)]
1185 public virtual void ProcessRequest (HttpContext context)
1187 public void ProcessRequest (HttpContext context)
1191 _lifeCycle = PageLifeCycle.Unknown;
1194 if (clientTarget != null)
1195 Request.ClientTarget = clientTarget;
1197 WireupAutomaticEvents ();
1198 //-- Control execution lifecycle in the docs
1200 // Save culture information because it can be modified in FrameworkInitialize()
1201 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1202 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1203 FrameworkInitialize ();
1204 context.ErrorPage = _errorPage;
1207 InternalProcessRequest ();
1208 } catch (ThreadAbortException) {
1209 // Do nothing, just ignore it by now.
1210 } catch (Exception e) {
1211 context.AddError (e); // OnError might access LastError
1212 OnError (EventArgs.Empty);
1213 context.ClearError (e);
1214 // We want to remove that error, as we're rethrowing to stop
1215 // further processing.
1216 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1221 _lifeCycle = PageLifeCycle.Unload;
1224 UnloadRecursive (true);
1226 _lifeCycle = PageLifeCycle.End;
1229 if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1230 Thread.CurrentThread.CurrentCulture = culture;
1232 if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1233 Thread.CurrentThread.CurrentUICulture = uiculture;
1238 delegate void ProcessRequestDelegate (HttpContext context);
1240 private sealed class DummyAsyncResult : IAsyncResult
1242 readonly object state;
1243 readonly WaitHandle asyncWaitHandle;
1244 readonly bool completedSynchronously;
1245 readonly bool isCompleted;
1247 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1249 this.isCompleted = isCompleted;
1250 this.completedSynchronously = completedSynchronously;
1253 asyncWaitHandle = new ManualResetEvent (true);
1256 asyncWaitHandle = new ManualResetEvent (false);
1260 #region IAsyncResult Members
1262 public object AsyncState {
1263 get { return state; }
1266 public WaitHandle AsyncWaitHandle {
1267 get { return asyncWaitHandle; }
1270 public bool CompletedSynchronously {
1271 get { return completedSynchronously; }
1274 public bool IsCompleted {
1275 get { return isCompleted; }
1281 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1283 ProcessRequest (context);
1284 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1286 if (callback != null) {
1287 callback (asyncResult);
1293 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1297 internal void ProcessCrossPagePostBack (HttpContext context)
1299 isCrossPagePostBack = true;
1300 ProcessRequest (context);
1304 void InternalProcessRequest ()
1306 _requestValueCollection = this.DeterminePostBackMode();
1309 _lifeCycle = PageLifeCycle.Start;
1310 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1311 if (_requestValueCollection != null) {
1312 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1313 _doLoadPreviousPage = true;
1316 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1317 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1318 //isPostBack = !isCallback;
1321 string lastFocus = _requestValueCollection [LastFocusID];
1322 if (!String.IsNullOrEmpty (lastFocus)) {
1323 _focusedControlID = UniqueID2ClientID (lastFocus);
1327 // if request was transfered from other page - track Prev. Page
1328 previousPage = _context.LastPage;
1329 _context.LastPage = this;
1331 _lifeCycle = PageLifeCycle.PreInit;
1332 OnPreInit (EventArgs.Empty);
1336 _lifeCycle = PageLifeCycle.Init;
1338 Trace.Write ("aspx.page", "Begin Init");
1339 InitRecursive (null);
1340 Trace.Write ("aspx.page", "End Init");
1343 _lifeCycle = PageLifeCycle.InitComplete;
1344 OnInitComplete (EventArgs.Empty);
1347 renderingForm = false;
1349 if (IsPostBack || IsCallback) {
1350 _lifeCycle = PageLifeCycle.PreLoad;
1351 if (_requestValueCollection != null)
1352 scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
1356 Trace.Write ("aspx.page", "Begin LoadViewState");
1357 LoadPageViewState ();
1358 Trace.Write ("aspx.page", "End LoadViewState");
1359 Trace.Write ("aspx.page", "Begin ProcessPostData");
1363 ProcessPostData (_requestValueCollection, false);
1364 Trace.Write ("aspx.page", "End ProcessPostData");
1368 OnPreLoad (EventArgs.Empty);
1369 _lifeCycle = PageLifeCycle.Load;
1377 if (IsPostBack || IsCallback) {
1378 _lifeCycle = PageLifeCycle.ControlEvents;
1382 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1383 ProcessPostData (secondPostData, true);
1384 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1385 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1386 RaiseChangedEvents ();
1387 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1388 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1389 RaisePostBackEvents ();
1390 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1394 _lifeCycle = PageLifeCycle.LoadComplete;
1395 OnLoadComplete (EventArgs.Empty);
1397 if (IsCrossPagePostBack)
1401 string result = ProcessCallbackData ();
1402 HtmlTextWriter callbackOutput = new HtmlTextWriter (_context.Response.Output);
1403 callbackOutput.Write (result);
1404 callbackOutput.Flush ();
1408 _lifeCycle = PageLifeCycle.PreRender;
1411 Trace.Write ("aspx.page", "Begin PreRender");
1412 PreRenderRecursiveInternal ();
1413 Trace.Write ("aspx.page", "End PreRender");
1416 ExecuteRegisteredAsyncTasks ();
1418 _lifeCycle = PageLifeCycle.PreRenderComplete;
1419 OnPreRenderComplete (EventArgs.Empty);
1422 Trace.Write ("aspx.page", "Begin SaveViewState");
1423 SavePageViewState ();
1424 Trace.Write ("aspx.page", "End SaveViewState");
1427 _lifeCycle = PageLifeCycle.SaveStateComplete;
1428 OnSaveStateComplete (EventArgs.Empty);
1430 if (OnSaveStateCompleteForPortlet ())
1432 #endif // TARGET_J2EE
1436 _lifeCycle = PageLifeCycle.Render;
1440 Trace.Write ("aspx.page", "Begin Render");
1441 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1442 RenderControl (output);
1443 Trace.Write ("aspx.page", "End Render");
1446 private void RenderTrace ()
1448 TraceManager traceManager = HttpRuntime.TraceManager;
1450 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1455 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1458 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1459 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1460 Trace.Render (output);
1465 bool CheckForValidationSupport (Control targetControl)
1467 if (targetControl == null)
1469 Type type = targetControl.GetType ();
1470 object[] attributes = type.GetCustomAttributes (false);
1471 foreach (object attr in attributes)
1472 if (attr is SupportsEventValidationAttribute)
1478 void RaisePostBackEvents ()
1481 Control targetControl;
1483 if (requiresRaiseEvent != null) {
1484 RaisePostBackEvent (requiresRaiseEvent, null);
1488 NameValueCollection postdata = _requestValueCollection;
1489 if (postdata == null)
1492 string eventTarget = postdata [postEventSourceID];
1493 if (eventTarget == null || eventTarget.Length == 0) {
1499 targetControl = FindControl (eventTarget);
1500 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1502 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1508 string eventArgument = postdata [postEventArgumentID];
1509 RaisePostBackEvent (target, eventArgument);
1512 internal void RaiseChangedEvents ()
1514 if (requiresPostDataChanged == null)
1517 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1518 ipdh.RaisePostDataChangedEvent ();
1520 requiresPostDataChanged = null;
1523 [EditorBrowsable (EditorBrowsableState.Advanced)]
1524 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1527 Control targetControl = sourceControl as Control;
1528 if (targetControl != null && CheckForValidationSupport (targetControl))
1529 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1531 sourceControl.RaisePostBackEvent (eventArgument);
1537 [EditorBrowsable (EditorBrowsableState.Advanced)]
1538 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1540 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1546 [EditorBrowsable (EditorBrowsableState.Advanced)]
1547 public virtual void RegisterClientScriptBlock (string key, string script)
1549 scriptManager.RegisterClientScriptBlock (key, script);
1555 [EditorBrowsable (EditorBrowsableState.Advanced)]
1556 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1558 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1561 [MonoTODO("Not implemented, Used in HtmlForm")]
1562 internal void RegisterClientScriptFile (string a, string b, string c)
1564 throw new NotImplementedException ();
1570 [EditorBrowsable (EditorBrowsableState.Advanced)]
1571 public void RegisterOnSubmitStatement (string key, string script)
1573 scriptManager.RegisterOnSubmitStatement (key, script);
1576 internal string GetSubmitStatements ()
1578 return scriptManager.WriteSubmitStatements ();
1581 [EditorBrowsable (EditorBrowsableState.Advanced)]
1582 public void RegisterRequiresPostBack (Control control)
1585 if (!(control is IPostBackDataHandler))
1586 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1589 if (_requiresPostBack == null)
1590 _requiresPostBack = new ArrayList ();
1592 if (_requiresPostBack.Contains (control.UniqueID))
1595 _requiresPostBack.Add (control.UniqueID);
1598 [EditorBrowsable (EditorBrowsableState.Advanced)]
1599 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1601 requiresRaiseEvent = control;
1607 [EditorBrowsable (EditorBrowsableState.Advanced)]
1608 public virtual void RegisterStartupScript (string key, string script)
1610 scriptManager.RegisterStartupScript (key, script);
1613 [EditorBrowsable (EditorBrowsableState.Advanced)]
1614 public void RegisterViewStateHandler ()
1616 handleViewState = true;
1619 [EditorBrowsable (EditorBrowsableState.Advanced)]
1620 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1622 PageStatePersister persister = this.PageStatePersister;
1623 if (persister == null)
1625 Pair pair = viewState as Pair;
1627 persister.ViewState = pair.First;
1628 persister.ControlState = pair.Second;
1630 persister.ViewState = viewState;
1634 internal string RawViewState {
1636 NameValueCollection postdata = _requestValueCollection;
1638 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1641 if (view_state == "")
1645 set { _savedViewState = value; }
1653 PageStatePersister PageStatePersister {
1655 if (page_state_persister == null)
1656 page_state_persister = new HiddenFieldPageStatePersister (this);
1657 return page_state_persister;
1661 [EditorBrowsable (EditorBrowsableState.Advanced)]
1662 protected virtual object LoadPageStateFromPersistenceMedium ()
1664 PageStatePersister persister = this.PageStatePersister;
1665 if (persister == null)
1668 return new Pair (persister.ViewState, persister.ControlState);
1671 internal void LoadPageViewState()
1673 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1674 if (sState != null) {
1677 LoadPageControlState (sState.Second);
1679 Pair vsr = sState.First as Pair;
1681 LoadViewStateRecursive (vsr.First);
1682 _requiresPostBackCopy = vsr.Second as ArrayList;
1688 internal void SavePageViewState ()
1690 if (!handleViewState)
1694 object controlState = SavePageControlState ();
1697 object viewState = SaveViewStateRecursive ();
1698 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1701 if (viewState != null || reqPostback != null)
1702 vsr = new Pair (viewState, reqPostback);
1703 Pair pair = new Pair ();
1707 pair.Second = controlState;
1711 if (pair.First == null && pair.Second == null)
1712 SavePageStateToPersistenceMedium (null);
1714 SavePageStateToPersistenceMedium (pair);
1718 public virtual void Validate ()
1720 is_validated = true;
1721 ValidateCollection (_validators);
1725 internal bool AreValidatorsUplevel () {
1726 return AreValidatorsUplevel (String.Empty);
1729 internal bool AreValidatorsUplevel (string valGroup)
1731 internal virtual bool AreValidatorsUplevel ()
1734 bool uplevel = false;
1736 foreach (IValidator v in Validators) {
1737 BaseValidator bv = v as BaseValidator;
1738 if (bv == null) continue;
1741 if (valGroup != bv.ValidationGroup)
1744 if (bv.GetRenderUplevel()) {
1753 bool ValidateCollection (ValidatorCollection validators)
1756 if (!_eventValidation)
1760 if (validators == null || validators.Count == 0)
1763 bool all_valid = true;
1764 foreach (IValidator v in validators){
1766 if (v.IsValid == false)
1773 [EditorBrowsable (EditorBrowsableState.Advanced)]
1774 public virtual void VerifyRenderingInServerForm (Control control)
1776 if (_context == null)
1783 throw new HttpException ("Control '" +
1786 control.GetType ().Name +
1787 "' must be placed inside a form tag with runat=server.");
1790 protected override void FrameworkInitialize ()
1792 base.FrameworkInitialize ();
1794 InitializeStyleSheet ();
1805 ClientScriptManager ClientScript {
1806 get { return scriptManager; }
1811 static readonly object InitCompleteEvent = new object ();
1812 static readonly object LoadCompleteEvent = new object ();
1813 static readonly object PreInitEvent = new object ();
1814 static readonly object PreLoadEvent = new object ();
1815 static readonly object PreRenderCompleteEvent = new object ();
1816 static readonly object SaveStateCompleteEvent = new object ();
1818 const int initcomplete_mask = 1;
1819 const int loadcomplete_mask = 1 << 1;
1820 const int preinit_mask = 1 << 2;
1821 const int preload_mask = 1 << 3;
1822 const int prerendercomplete_mask = 1 << 4;
1823 const int savestatecomplete_mask = 1 << 5;
1825 [EditorBrowsable (EditorBrowsableState.Advanced)]
1826 public event EventHandler InitComplete {
1828 event_mask |= initcomplete_mask;
1829 Events.AddHandler (InitCompleteEvent, value);
1831 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1834 [EditorBrowsable (EditorBrowsableState.Advanced)]
1835 public event EventHandler LoadComplete {
1837 event_mask |= loadcomplete_mask;
1838 Events.AddHandler (LoadCompleteEvent, value);
1840 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1843 public event EventHandler PreInit {
1845 event_mask |= preinit_mask;
1846 Events.AddHandler (PreInitEvent, value);
1848 remove { Events.RemoveHandler (PreInitEvent, value); }
1851 [EditorBrowsable (EditorBrowsableState.Advanced)]
1852 public event EventHandler PreLoad {
1854 event_mask |= preload_mask;
1855 Events.AddHandler (PreLoadEvent, value);
1857 remove { Events.RemoveHandler (PreLoadEvent, value); }
1860 [EditorBrowsable (EditorBrowsableState.Advanced)]
1861 public event EventHandler PreRenderComplete {
1863 event_mask |= prerendercomplete_mask;
1864 Events.AddHandler (PreRenderCompleteEvent, value);
1866 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1869 [EditorBrowsable (EditorBrowsableState.Advanced)]
1870 public event EventHandler SaveStateComplete {
1872 event_mask |= savestatecomplete_mask;
1873 Events.AddHandler (SaveStateCompleteEvent, value);
1875 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1878 protected virtual void OnInitComplete (EventArgs e)
1880 if ((event_mask & initcomplete_mask) != 0) {
1881 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1882 if (eh != null) eh (this, e);
1886 protected virtual void OnLoadComplete (EventArgs e)
1888 if ((event_mask & loadcomplete_mask) != 0) {
1889 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1890 if (eh != null) eh (this, e);
1894 protected virtual void OnPreInit (EventArgs e)
1896 if ((event_mask & preinit_mask) != 0) {
1897 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1898 if (eh != null) eh (this, e);
1902 protected virtual void OnPreLoad (EventArgs e)
1904 if ((event_mask & preload_mask) != 0) {
1905 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1906 if (eh != null) eh (this, e);
1910 protected virtual void OnPreRenderComplete (EventArgs e)
1912 if ((event_mask & prerendercomplete_mask) != 0) {
1913 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1914 if (eh != null) eh (this, e);
1919 if (!Form.DetermineRenderUplevel ())
1922 /* figure out if we have some control we're going to focus */
1923 if (String.IsNullOrEmpty (_focusedControlID)) {
1924 _focusedControlID = Form.DefaultFocus;
1925 if (String.IsNullOrEmpty (_focusedControlID))
1926 _focusedControlID = Form.DefaultButton;
1929 if (!String.IsNullOrEmpty (_focusedControlID)) {
1930 ClientScript.RegisterWebFormClientScript ();
1931 ClientScript.RegisterStartupScript ("HtmlForm-DefaultButton-StartupScript",
1932 String.Format ("<script type=\"text/javascript\">\n" +
1934 "WebForm_AutoFocus('{0}');// -->\n" +
1935 "</script>\n", _focusedControlID));
1938 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1939 ClientScript.RegisterWebFormClientScript ();
1940 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1941 "WebForm_ReEnableControls(this);");
1945 internal void RegisterEnabledControl (Control control)
1947 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1949 _hasEnabledControlArray = true;
1950 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Format ("'{0}'", control.ClientID));
1953 protected virtual void OnSaveStateComplete (EventArgs e)
1955 if ((event_mask & savestatecomplete_mask) != 0) {
1956 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1957 if (eh != null) eh (this, e);
1961 public HtmlForm Form {
1962 get { return _form; }
1965 internal void RegisterForm (HtmlForm form)
1970 [BrowsableAttribute (false)]
1971 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1972 public Page PreviousPage {
1974 if (_doLoadPreviousPage) {
1975 _doLoadPreviousPage = false;
1976 LoadPreviousPageReference ();
1978 return previousPage;
1983 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1984 [BrowsableAttribute (false)]
1985 public bool IsCallback {
1986 get { return isCallback; }
1989 [BrowsableAttribute (false)]
1990 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1991 public bool IsCrossPagePostBack {
1992 get { return isCrossPagePostBack; }
1995 public new virtual char IdSeparator {
1997 //TODO: why override?
1998 return base.IdSeparator;
2002 string ProcessCallbackData ()
2004 string callbackTarget = _requestValueCollection [CallbackSourceID];
2005 if (callbackTarget == null || callbackTarget.Length == 0)
2006 throw new HttpException ("Callback target not provided.");
2008 Control targetControl = FindControl (callbackTarget);
2009 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2011 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2013 string callbackEventError = String.Empty;
2014 string callBackResult;
2015 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2018 target.RaiseCallbackEvent (callbackArgument);
2020 catch (Exception ex) {
2021 callbackEventError = String.Format ("e{0}", ex.Message);
2025 callBackResult = target.GetCallbackResult ();
2027 catch (Exception ex) {
2028 return String.Format ("e{0}", ex.Message);
2031 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2032 return String.Format ("{0}{1}|{2}{3}", callbackEventError, eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
2035 [BrowsableAttribute (false)]
2036 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2037 public HtmlHead Header {
2038 get { return htmlHeader; }
2041 internal void SetHeader (HtmlHead header)
2043 htmlHeader = header;
2044 if (_title != null) {
2045 htmlHeader.Title = _title;
2050 protected bool AsyncMode {
2051 get { return asyncMode; }
2052 set { asyncMode = value; }
2055 public TimeSpan AsyncTimeout {
2056 get { return asyncTimeout; }
2057 set { asyncTimeout = value; }
2060 public bool IsAsync {
2061 get { return AsyncMode; }
2064 [MonoTODO ("Not Implemented")]
2065 protected internal virtual string UniqueFilePathSuffix {
2067 throw new NotImplementedException ();
2071 [MonoTODO ("Not Implemented")]
2072 public int MaxPageStateFieldLength {
2074 throw new NotImplementedException ();
2077 throw new NotImplementedException ();
2081 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2083 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2086 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2089 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2092 if (_lifeCycle >= PageLifeCycle.PreRender) {
2093 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
2096 if (beginHandler == null) {
2097 throw new ArgumentNullException ("beginHandler");
2100 if (endHandler == null) {
2101 throw new ArgumentNullException ("endHandler");
2104 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2107 private List<PageAsyncTask> ParallelTasks {
2110 if (parallelTasks == null) {
2111 parallelTasks = new List<PageAsyncTask>();
2113 return parallelTasks;
2117 private List<PageAsyncTask> SerialTasks {
2119 if (serialTasks == null) {
2120 serialTasks = new List<PageAsyncTask> ();
2126 public void RegisterAsyncTask (PageAsyncTask task)
2129 throw new ArgumentNullException ("task");
2132 if (task.ExecuteInParallel) {
2133 ParallelTasks.Add (task);
2136 SerialTasks.Add (task);
2140 public void ExecuteRegisteredAsyncTasks ()
2142 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2143 (serialTasks == null || serialTasks.Count == 0)){
2147 if (parallelTasks != null) {
2148 DateTime startExecution = DateTime.Now;
2149 List<PageAsyncTask> localParallelTasks = parallelTasks;
2150 parallelTasks = null; // Shouldn't execute tasks twice
2151 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2152 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2153 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2154 if (result.CompletedSynchronously) {
2155 parallelTask.EndHandler (result);
2158 asyncResults.Add (result);
2162 if (asyncResults.Count > 0) {
2164 TimeSpan timeout = AsyncTimeout;
2165 long t1 = DateTime.Now.Ticks;
2166 bool signalled = true;
2167 for (int i = 0; i < asyncResults.Count; i++) {
2168 if (asyncResults [i].IsCompleted)
2172 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2175 long t2 = DateTime.Now.Ticks;
2176 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2177 if (timeout.Ticks <= 0)
2181 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2185 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2187 for (i = 0; i < asyncResults.Count; i++) {
2188 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2190 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2191 if (!allSignalled) {
2192 for (i = 0; i < asyncResults.Count; i++) {
2193 if (!asyncResults [i].IsCompleted) {
2194 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2200 DateTime endWait = DateTime.Now;
2201 TimeSpan elapsed = endWait - startExecution;
2202 if (elapsed <= AsyncTimeout) {
2203 AsyncTimeout -= elapsed;
2206 AsyncTimeout = TimeSpan.FromTicks(0);
2210 if (serialTasks != null) {
2211 List<PageAsyncTask> localSerialTasks = serialTasks;
2212 serialTasks = null; // Shouldn't execute tasks twice
2213 foreach (PageAsyncTask serialTask in localSerialTasks) {
2214 DateTime startExecution = DateTime.Now;
2216 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2217 if (result.CompletedSynchronously) {
2218 serialTask.EndHandler (result);
2221 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2222 if (!done && !result.IsCompleted) {
2223 serialTask.TimeoutHandler (result);
2226 DateTime endWait = DateTime.Now;
2227 TimeSpan elapsed = endWait - startExecution;
2228 if (elapsed <= AsyncTimeout) {
2229 AsyncTimeout -= elapsed;
2232 AsyncTimeout = TimeSpan.FromTicks (0);
2236 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2239 void EndAsyncTaskCallback (IAsyncResult result)
2241 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2242 task.EndHandler (result);
2245 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2247 Type htmlTextWriterType = typeof (HtmlTextWriter);
2249 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2250 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2253 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2254 if (constructor == null) {
2255 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2258 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2261 public ViewStateEncryptionMode ViewStateEncryptionMode {
2262 get { return viewStateEncryptionMode; }
2263 set { viewStateEncryptionMode = value; }
2266 public void RegisterRequiresViewStateEncryption ()
2268 controlRegisteredForViewStateEncryption = true;
2271 private static byte [] AES_IV = null;
2272 private static byte [] TripleDES_IV = null;
2273 private static object locker = new object ();
2274 private static bool isEncryptionInitialized = false;
2276 private static void InitializeEncryption ()
2278 if (isEncryptionInitialized) {
2283 if (isEncryptionInitialized) {
2287 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2288 AES_IV = new byte [16];
2289 TripleDES_IV = new byte [8];
2292 for (i = 0; i < AES_IV.Length; i++) {
2293 AES_IV [i] = (byte) iv_string [i];
2296 for (i = 0; i < TripleDES_IV.Length; i++) {
2297 TripleDES_IV [i] = (byte) iv_string [i];
2300 isEncryptionInitialized = true;
2304 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2306 ICryptoTransform transform = null;
2307 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2308 byte [] vk = config.ValidationKeyBytes;
2310 switch (config.Validation) {
2311 case MachineKeyValidation.SHA1:
2312 transform = SHA1.Create ();
2315 case MachineKeyValidation.MD5:
2316 transform = MD5.Create ();
2319 case MachineKeyValidation.AES:
2320 if (cryptoStreamMode == CryptoStreamMode.Read){
2321 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2323 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2327 case MachineKeyValidation.TripleDES:
2328 if (cryptoStreamMode == CryptoStreamMode.Read){
2329 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2331 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2339 internal bool NeedViewStateEncryption {
2341 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2342 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2343 controlRegisteredForViewStateEncryption));
2348 void ApplyMasterPage ()
2350 if (masterPageFile != null && masterPageFile.Length > 0) {
2351 ArrayList appliedMasterPageFiles = new ArrayList ();
2353 if (Master != null) {
2354 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2358 Controls.Add (Master);
2363 [DefaultValueAttribute ("")]
2364 public virtual string MasterPageFile {
2365 get { return masterPageFile; }
2367 masterPageFile = value;
2372 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2373 [BrowsableAttribute (false)]
2374 public MasterPage Master {
2376 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2379 if (masterPage == null)
2380 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2386 public void SetFocus (string clientID)
2388 if (String.IsNullOrEmpty (clientID))
2389 throw new ArgumentNullException ("control");
2391 if (_lifeCycle > PageLifeCycle.PreRender)
2392 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2395 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2397 _focusedControlID = clientID;
2400 public void SetFocus (Control control)
2402 if (control == null)
2403 throw new ArgumentNullException ("control");
2405 SetFocus (control.ClientID);
2408 [EditorBrowsable (EditorBrowsableState.Advanced)]
2409 public void RegisterRequiresControlState (Control control)
2411 if (control == null)
2412 throw new ArgumentNullException ("control");
2414 if (RequiresControlState (control))
2417 if (requireStateControls == null)
2418 requireStateControls = new ArrayList ();
2419 int n = requireStateControls.Add (control);
2421 if (_savedControlState == null || n >= _savedControlState.Length)
2424 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2425 if (parent.IsChildControlStateCleared)
2428 object state = _savedControlState [n];
2430 control.LoadControlState (state);
2433 public bool RequiresControlState (Control control)
2435 if (requireStateControls == null) return false;
2436 return requireStateControls.Contains (control);
2439 [EditorBrowsable (EditorBrowsableState.Advanced)]
2440 public void UnregisterRequiresControlState (Control control)
2442 if (requireStateControls != null)
2443 requireStateControls.Remove (control);
2446 public ValidatorCollection GetValidators (string validationGroup)
2448 string valgr = validationGroup;
2450 valgr = String.Empty;
2452 if (_validatorsByGroup == null) _validatorsByGroup = new Hashtable ();
2453 ValidatorCollection col = _validatorsByGroup [valgr] as ValidatorCollection;
2455 col = new ValidatorCollection ();
2456 _validatorsByGroup [valgr] = col;
2461 public virtual void Validate (string validationGroup)
2463 is_validated = true;
2464 if (validationGroup == null)
2465 ValidateCollection (_validatorsByGroup [String.Empty] as ValidatorCollection);
2466 else if (_validatorsByGroup != null) {
2467 ValidateCollection (_validatorsByGroup [validationGroup] as ValidatorCollection);
2471 object SavePageControlState ()
2473 if (requireStateControls == null) return null;
2474 object[] state = new object [requireStateControls.Count];
2476 bool allNull = true;
2477 for (int n=0; n<state.Length; n++) {
2478 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2479 if (state [n] != null) allNull = false;
2481 if (allNull) return null;
2485 void LoadPageControlState (object data)
2487 _savedControlState = (object []) data;
2489 if (requireStateControls == null) return;
2491 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2492 for (int n=0; n < max; n++) {
2493 Control ctl = (Control) requireStateControls [n];
2494 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2498 void LoadPreviousPageReference ()
2500 if (_requestValueCollection != null) {
2501 string prevPage = _requestValueCollection [PreviousPageID];
2502 if (prevPage != null) {
2503 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2504 previousPage.ProcessCrossPagePostBack (_context);
2510 Hashtable contentTemplates;
2511 [EditorBrowsable (EditorBrowsableState.Never)]
2512 protected internal void AddContentTemplate (string templateName, ITemplate template)
2514 if (contentTemplates == null)
2515 contentTemplates = new Hashtable ();
2516 contentTemplates [templateName] = template;
2519 PageTheme _pageTheme;
2520 internal PageTheme PageTheme {
2521 get { return _pageTheme; }
2524 PageTheme _styleSheetPageTheme;
2525 internal PageTheme StyleSheetPageTheme {
2526 get { return _styleSheetPageTheme; }
2531 internal void PushDataItemContext (object o) {
2532 if (dataItemCtx == null)
2533 dataItemCtx = new Stack ();
2535 dataItemCtx.Push (o);
2538 internal void PopDataItemContext () {
2539 if (dataItemCtx == null)
2540 throw new InvalidOperationException ();
2545 public object GetDataItem() {
2546 if (dataItemCtx == null || dataItemCtx.Count == 0)
2547 throw new InvalidOperationException ("No data item");
2549 return dataItemCtx.Peek ();
2552 protected internal override void OnInit (EventArgs e)
2556 ArrayList themes = new ArrayList();
2558 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2559 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2560 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2561 themes.AddRange (PageTheme.GetStyleSheets ());
2563 if (themes.Count > 0 && Header == null)
2564 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2566 foreach (string lss in themes) {
2567 HtmlLink hl = new HtmlLink ();
2568 hl.Href = ResolveUrl (lss);
2569 hl.Attributes["type"] = "text/css";
2570 hl.Attributes["rel"] = "stylesheet";
2571 Header.Controls.Add (hl);
2578 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2579 protected object GetWrappedFileDependencies (string [] list)
2584 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2585 protected virtual void InitializeCulture ()
2589 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2590 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)