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 {
608 return htmlHeader.Title;
612 if (htmlHeader != null)
613 htmlHeader.Title = value;
620 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
622 public TraceContext Trace
624 get { return Context.Trace; }
627 [EditorBrowsable (EditorBrowsableState.Never)]
629 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
630 [BrowsableAttribute (false)]
631 public bool TraceEnabled
633 get { return Trace.IsEnabled; }
634 set { Trace.IsEnabled = value; }
637 protected bool TraceEnabled
639 set { Trace.IsEnabled = value; }
643 [EditorBrowsable (EditorBrowsableState.Never)]
645 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
646 [BrowsableAttribute (false)]
647 public TraceMode TraceModeValue
649 get { return Trace.TraceMode; }
650 set { Trace.TraceMode = value; }
653 protected TraceMode TraceModeValue
655 set { Trace.TraceMode = value; }
659 [EditorBrowsable (EditorBrowsableState.Never)]
660 protected int TransactionMode
663 get { return _transactionMode; }
665 set { _transactionMode = value; }
670 // This method is here just to remove the warning about "_transactionMode" not being
671 // used. We probably will use it internally at some point.
673 internal int GetTransactionMode ()
675 return _transactionMode;
680 [EditorBrowsable (EditorBrowsableState.Advanced)]
681 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
682 [BrowsableAttribute (false)]
683 public string UICulture
685 get { return Thread.CurrentThread.CurrentUICulture.Name; }
686 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
689 [EditorBrowsable (EditorBrowsableState.Never)]
690 protected string UICulture
692 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
696 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
698 public IPrincipal User
700 get { return Context.User; }
703 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
705 public ValidatorCollection Validators
708 if (_validators == null)
709 _validators = new ValidatorCollection ();
714 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
716 public string ViewStateUserKey {
717 get { return viewStateUserKey; }
718 set { viewStateUserKey = value; }
722 public override bool Visible
724 get { return base.Visible; }
725 set { base.Visible = value; }
733 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
737 CultureInfo ret = null;
738 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
740 if (Context.IsPortletRequest)
743 string[] languages = Request.UserLanguages;
745 if (languages != null && languages.Length > 0)
746 ret = CultureInfo.CreateSpecificCulture (languages[0]);
753 ret = CultureInfo.CreateSpecificCulture (culture);
759 [EditorBrowsable (EditorBrowsableState.Never)]
760 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
764 throw new NotImplementedException ();
767 [EditorBrowsable (EditorBrowsableState.Never)]
768 protected void AspCompatEndProcessRequest (IAsyncResult result)
770 throw new NotImplementedException ();
773 [EditorBrowsable (EditorBrowsableState.Advanced)]
774 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
776 return new HtmlTextWriter (tw);
779 [EditorBrowsable (EditorBrowsableState.Never)]
780 public void DesignerInitialize ()
782 InitRecursive (null);
785 [EditorBrowsable (EditorBrowsableState.Advanced)]
786 protected virtual NameValueCollection DeterminePostBackMode ()
788 if (_context == null)
791 HttpRequest req = _context.Request;
795 NameValueCollection coll = null;
796 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
799 else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
803 coll = req.QueryString;
805 WebROCollection c = (WebROCollection) coll;
806 allow_load = !c.GotID;
808 c.ID = GetTypeHashCode ();
810 allow_load = (c.ID == GetTypeHashCode ());
812 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
819 public override Control FindControl (string id) {
823 return base.FindControl (id);
830 [EditorBrowsable (EditorBrowsableState.Advanced)]
831 public string GetPostBackClientEvent (Control control, string argument)
833 return scriptManager.GetPostBackEventReference (control, argument);
839 [EditorBrowsable (EditorBrowsableState.Advanced)]
840 public string GetPostBackClientHyperlink (Control control, string argument)
842 return scriptManager.GetPostBackClientHyperlink (control, argument);
848 [EditorBrowsable (EditorBrowsableState.Advanced)]
849 public string GetPostBackEventReference (Control control)
851 return scriptManager.GetPostBackEventReference (control, "");
857 [EditorBrowsable (EditorBrowsableState.Advanced)]
858 public string GetPostBackEventReference (Control control, string argument)
860 return scriptManager.GetPostBackEventReference (control, argument);
863 internal void RequiresPostBackScript ()
866 if (requiresPostBackScript)
868 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
869 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
871 requiresPostBackScript = true;
874 [EditorBrowsable (EditorBrowsableState.Never)]
875 public virtual int GetTypeHashCode ()
881 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
882 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
884 if (cacheSettings.Enabled)
885 InitOutputCache(cacheSettings.Duration,
886 cacheSettings.VaryByHeader,
887 cacheSettings.VaryByCustom,
888 cacheSettings.Location,
889 cacheSettings.VaryByParam);
893 [EditorBrowsable (EditorBrowsableState.Never)]
894 protected virtual void InitOutputCache (int duration,
897 OutputCacheLocation location,
900 HttpCachePolicy cache = _context.Response.Cache;
901 bool set_vary = false;
904 case OutputCacheLocation.Any:
905 cache.SetCacheability (HttpCacheability.Public);
906 cache.SetMaxAge (new TimeSpan (0, 0, duration));
907 cache.SetLastModified (_context.Timestamp);
910 case OutputCacheLocation.Client:
911 cache.SetCacheability (HttpCacheability.Private);
912 cache.SetMaxAge (new TimeSpan (0, 0, duration));
913 cache.SetLastModified (_context.Timestamp);
915 case OutputCacheLocation.Downstream:
916 cache.SetCacheability (HttpCacheability.Public);
917 cache.SetMaxAge (new TimeSpan (0, 0, duration));
918 cache.SetLastModified (_context.Timestamp);
920 case OutputCacheLocation.Server:
921 cache.SetCacheability (HttpCacheability.Server);
924 case OutputCacheLocation.None:
929 if (varyByCustom != null)
930 cache.SetVaryByCustom (varyByCustom);
932 if (varyByParam != null && varyByParam.Length > 0) {
933 string[] prms = varyByParam.Split (';');
934 foreach (string p in prms)
935 cache.VaryByParams [p.Trim ()] = true;
936 cache.VaryByParams.IgnoreParams = false;
938 cache.VaryByParams.IgnoreParams = true;
941 if (varyByHeader != null && varyByHeader.Length > 0) {
942 string[] hdrs = varyByHeader.Split (';');
943 foreach (string h in hdrs)
944 cache.VaryByHeaders [h.Trim ()] = true;
948 cache.Duration = duration;
949 cache.SetExpires (_context.Timestamp.AddSeconds (duration));
955 [EditorBrowsable (EditorBrowsableState.Advanced)]
957 public bool IsClientScriptBlockRegistered (string key)
959 return scriptManager.IsClientScriptBlockRegistered (key);
965 [EditorBrowsable (EditorBrowsableState.Advanced)]
967 public bool IsStartupScriptRegistered (string key)
969 return scriptManager.IsStartupScriptRegistered (key);
972 public string MapPath (string virtualPath)
974 return Request.MapPath (virtualPath);
978 protected internal override void Render (HtmlTextWriter writer) {
979 if (MaintainScrollPositionOnPostBack) {
980 ClientScript.RegisterWebFormClientScript ();
982 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
983 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
985 StringBuilder script = new StringBuilder ();
986 script.AppendLine ("<script type=\"text/javascript\">");
987 script.AppendLine ("<!--");
988 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
989 script.AppendLine (theForm + ".submit = WebForm_SaveScrollPositionSubmit;");
990 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
991 script.AppendLine (theForm + ".onsubmit = WebForm_SaveScrollPositionOnSubmit;");
993 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
994 script.AppendLine ("window.onload = function () { WebForm_RestoreScrollPosition (" + theForm + "); };");
996 script.AppendLine ("// -->");
997 script.AppendLine ("</script>");
999 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1001 base.Render (writer);
1005 private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1008 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
1009 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
1011 writer.WriteLine ();
1013 ClientScriptManager.WriteBeginScriptBlock (writer);
1016 RenderClientScriptFormDeclaration (writer, formUniqueID);
1019 writer.WriteLine ("{0}._form = {0};", theForm);
1020 writer.Write (theForm + ".");
1023 writer.WriteLine ("window._form = {0};", theForm);
1025 writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
1027 writer.WriteLine ("\tif(this._form.onsubmit && this._form.onsubmit() == false) return;");
1029 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1031 writer.WriteLine ("\tthis._form.{0}.value = eventTarget;", postEventSourceID);
1032 writer.WriteLine ("\tthis._form.{0}.value = eventArgument;", postEventArgumentID);
1033 writer.WriteLine ("\tthis._form.submit();");
1034 writer.WriteLine ("}");
1035 ClientScriptManager.WriteEndScriptBlock (writer);
1038 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1040 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1041 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1042 writer.WriteLine ("\t{0}._instanceVariableName = '{0}';", theForm);
1044 string serverUrl = Context.ServletResponse.encodeURL (Request.RawUrl);
1045 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1046 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1050 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1053 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1055 renderingForm = true;
1056 writer.WriteLine ();
1059 ClientScriptManager.WriteBeginScriptBlock (writer);
1060 RenderClientScriptFormDeclaration (writer, formUniqueID);
1061 ClientScriptManager.WriteEndScriptBlock (writer);
1064 if (handleViewState)
1065 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1067 scriptManager.WriteHiddenFields (writer);
1068 if (requiresPostBackScript) {
1069 RenderPostBackScript (writer, formUniqueID);
1070 postBackScriptRendered = true;
1073 scriptManager.WriteWebFormClientScript (writer);
1075 scriptManager.WriteClientScriptBlocks (writer);
1078 internal IStateFormatter GetFormatter ()
1080 return new ObjectStateFormatter (this);
1083 internal string GetSavedViewState ()
1085 return _savedViewState;
1088 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1091 scriptManager.SaveEventValidationState ();
1092 scriptManager.WriteExpandoAttributes (writer);
1094 scriptManager.WriteHiddenFields (writer);
1095 if (!postBackScriptRendered && requiresPostBackScript)
1096 RenderPostBackScript (writer, formUniqueID);
1098 scriptManager.WriteWebFormClientScript (writer);
1101 scriptManager.WriteArrayDeclares (writer);
1102 scriptManager.WriteStartupScriptBlocks (writer);
1103 renderingForm = false;
1104 postBackScriptRendered = false;
1107 private void ProcessPostData (NameValueCollection data, bool second)
1110 Hashtable used = new Hashtable ();
1111 foreach (string id in data.AllKeys){
1112 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
1115 string real_id = id;
1116 int dot = real_id.IndexOf ('.');
1118 real_id = real_id.Substring (0, dot);
1120 if (real_id == null || used.ContainsKey (real_id))
1123 used.Add (real_id, real_id);
1125 Control ctrl = FindControl (real_id);
1127 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1128 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1132 RegisterRequiresRaiseEvent (pbeh);
1136 if (pbdh.LoadPostData (real_id, data) == true) {
1137 if (requiresPostDataChanged == null)
1138 requiresPostDataChanged = new ArrayList ();
1139 requiresPostDataChanged.Add (pbdh);
1142 if (_requiresPostBackCopy != null)
1143 _requiresPostBackCopy.Remove (real_id);
1145 } else if (!second) {
1146 if (secondPostData == null)
1147 secondPostData = new NameValueCollection ();
1148 secondPostData.Add (real_id, data [id]);
1153 ArrayList list1 = null;
1154 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1155 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1156 foreach (string id in handlers) {
1157 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1159 _requiresPostBackCopy.Remove (id);
1160 if (pbdh.LoadPostData (id, data)) {
1161 if (requiresPostDataChanged == null)
1162 requiresPostDataChanged = new ArrayList ();
1164 requiresPostDataChanged.Add (pbdh);
1166 } else if (!second) {
1168 list1 = new ArrayList ();
1173 _requiresPostBackCopy = second ? null : list1;
1175 secondPostData = null;
1178 [EditorBrowsable (EditorBrowsableState.Never)]
1180 public virtual void ProcessRequest (HttpContext context)
1182 public void ProcessRequest (HttpContext context)
1186 _lifeCycle = PageLifeCycle.Unknown;
1189 if (clientTarget != null)
1190 Request.ClientTarget = clientTarget;
1192 WireupAutomaticEvents ();
1193 //-- Control execution lifecycle in the docs
1195 // Save culture information because it can be modified in FrameworkInitialize()
1196 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1197 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1198 FrameworkInitialize ();
1199 context.ErrorPage = _errorPage;
1202 InternalProcessRequest ();
1203 } catch (ThreadAbortException) {
1204 // Do nothing, just ignore it by now.
1205 } catch (Exception e) {
1206 context.AddError (e); // OnError might access LastError
1207 OnError (EventArgs.Empty);
1208 context.ClearError (e);
1209 // We want to remove that error, as we're rethrowing to stop
1210 // further processing.
1211 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1216 _lifeCycle = PageLifeCycle.Unload;
1219 UnloadRecursive (true);
1221 _lifeCycle = PageLifeCycle.End;
1224 if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1225 Thread.CurrentThread.CurrentCulture = culture;
1227 if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1228 Thread.CurrentThread.CurrentUICulture = uiculture;
1233 delegate void ProcessRequestDelegate (HttpContext context);
1235 private sealed class DummyAsyncResult : IAsyncResult
1237 readonly object state;
1238 readonly WaitHandle asyncWaitHandle;
1239 readonly bool completedSynchronously;
1240 readonly bool isCompleted;
1242 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1244 this.isCompleted = isCompleted;
1245 this.completedSynchronously = completedSynchronously;
1248 asyncWaitHandle = new ManualResetEvent (true);
1251 asyncWaitHandle = new ManualResetEvent (false);
1255 #region IAsyncResult Members
1257 public object AsyncState {
1258 get { return state; }
1261 public WaitHandle AsyncWaitHandle {
1262 get { return asyncWaitHandle; }
1265 public bool CompletedSynchronously {
1266 get { return completedSynchronously; }
1269 public bool IsCompleted {
1270 get { return isCompleted; }
1276 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1278 ProcessRequest (context);
1279 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1281 if (callback != null) {
1282 callback (asyncResult);
1288 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1292 internal void ProcessCrossPagePostBack (HttpContext context)
1294 isCrossPagePostBack = true;
1295 ProcessRequest (context);
1299 void InternalProcessRequest ()
1301 _requestValueCollection = this.DeterminePostBackMode();
1304 _lifeCycle = PageLifeCycle.Start;
1305 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1306 if (_requestValueCollection != null) {
1307 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1308 _doLoadPreviousPage = true;
1311 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1312 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1313 //isPostBack = !isCallback;
1316 string lastFocus = _requestValueCollection [LastFocusID];
1317 if (!String.IsNullOrEmpty (lastFocus)) {
1318 _focusedControlID = UniqueID2ClientID (lastFocus);
1322 // if request was transfered from other page - track Prev. Page
1323 previousPage = _context.LastPage;
1324 _context.LastPage = this;
1326 _lifeCycle = PageLifeCycle.PreInit;
1327 OnPreInit (EventArgs.Empty);
1331 _lifeCycle = PageLifeCycle.Init;
1333 Trace.Write ("aspx.page", "Begin Init");
1334 InitRecursive (null);
1335 Trace.Write ("aspx.page", "End Init");
1338 _lifeCycle = PageLifeCycle.InitComplete;
1339 OnInitComplete (EventArgs.Empty);
1342 renderingForm = false;
1344 if (IsPostBack || IsCallback) {
1345 _lifeCycle = PageLifeCycle.PreLoad;
1346 if (_requestValueCollection != null)
1347 scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
1351 Trace.Write ("aspx.page", "Begin LoadViewState");
1352 LoadPageViewState ();
1353 Trace.Write ("aspx.page", "End LoadViewState");
1354 Trace.Write ("aspx.page", "Begin ProcessPostData");
1358 ProcessPostData (_requestValueCollection, false);
1359 Trace.Write ("aspx.page", "End ProcessPostData");
1363 OnPreLoad (EventArgs.Empty);
1364 _lifeCycle = PageLifeCycle.Load;
1372 if (IsPostBack || IsCallback) {
1373 _lifeCycle = PageLifeCycle.ControlEvents;
1377 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1378 ProcessPostData (secondPostData, true);
1379 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1380 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1381 RaiseChangedEvents ();
1382 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1383 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1384 RaisePostBackEvents ();
1385 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1389 _lifeCycle = PageLifeCycle.LoadComplete;
1390 OnLoadComplete (EventArgs.Empty);
1392 if (IsCrossPagePostBack)
1396 string result = ProcessCallbackData ();
1397 HtmlTextWriter callbackOutput = new HtmlTextWriter (_context.Response.Output);
1398 callbackOutput.Write (result);
1399 callbackOutput.Flush ();
1403 _lifeCycle = PageLifeCycle.PreRender;
1406 Trace.Write ("aspx.page", "Begin PreRender");
1407 PreRenderRecursiveInternal ();
1408 Trace.Write ("aspx.page", "End PreRender");
1411 ExecuteRegisteredAsyncTasks ();
1413 _lifeCycle = PageLifeCycle.PreRenderComplete;
1414 OnPreRenderComplete (EventArgs.Empty);
1417 Trace.Write ("aspx.page", "Begin SaveViewState");
1418 SavePageViewState ();
1419 Trace.Write ("aspx.page", "End SaveViewState");
1422 _lifeCycle = PageLifeCycle.SaveStateComplete;
1423 OnSaveStateComplete (EventArgs.Empty);
1425 if (OnSaveStateCompleteForPortlet ())
1427 #endif // TARGET_J2EE
1431 _lifeCycle = PageLifeCycle.Render;
1432 scriptManager.ResetEventValidationState ();
1436 Trace.Write ("aspx.page", "Begin Render");
1437 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1438 RenderControl (output);
1439 Trace.Write ("aspx.page", "End Render");
1442 private void RenderTrace ()
1444 TraceManager traceManager = HttpRuntime.TraceManager;
1446 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1451 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1454 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1455 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1456 Trace.Render (output);
1461 bool CheckForValidationSupport (Control targetControl)
1463 if (targetControl == null)
1465 Type type = targetControl.GetType ();
1466 object[] attributes = type.GetCustomAttributes (false);
1467 foreach (object attr in attributes)
1468 if (attr is SupportsEventValidationAttribute)
1474 void RaisePostBackEvents ()
1477 Control targetControl;
1479 if (requiresRaiseEvent != null) {
1480 RaisePostBackEvent (requiresRaiseEvent, null);
1484 NameValueCollection postdata = _requestValueCollection;
1485 if (postdata == null)
1488 string eventTarget = postdata [postEventSourceID];
1489 if (eventTarget == null || eventTarget.Length == 0) {
1495 targetControl = FindControl (eventTarget);
1496 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1498 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1504 string eventArgument = postdata [postEventArgumentID];
1505 RaisePostBackEvent (target, eventArgument);
1508 internal void RaiseChangedEvents ()
1510 if (requiresPostDataChanged == null)
1513 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1514 ipdh.RaisePostDataChangedEvent ();
1516 requiresPostDataChanged = null;
1519 [EditorBrowsable (EditorBrowsableState.Advanced)]
1520 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1523 Control targetControl = sourceControl as Control;
1524 if (targetControl != null && CheckForValidationSupport (targetControl))
1525 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1527 sourceControl.RaisePostBackEvent (eventArgument);
1533 [EditorBrowsable (EditorBrowsableState.Advanced)]
1534 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1536 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1542 [EditorBrowsable (EditorBrowsableState.Advanced)]
1543 public virtual void RegisterClientScriptBlock (string key, string script)
1545 scriptManager.RegisterClientScriptBlock (key, script);
1551 [EditorBrowsable (EditorBrowsableState.Advanced)]
1552 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1554 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1557 [MonoTODO("Not implemented, Used in HtmlForm")]
1558 internal void RegisterClientScriptFile (string a, string b, string c)
1560 throw new NotImplementedException ();
1566 [EditorBrowsable (EditorBrowsableState.Advanced)]
1567 public void RegisterOnSubmitStatement (string key, string script)
1569 scriptManager.RegisterOnSubmitStatement (key, script);
1572 internal string GetSubmitStatements ()
1574 return scriptManager.WriteSubmitStatements ();
1577 [EditorBrowsable (EditorBrowsableState.Advanced)]
1578 public void RegisterRequiresPostBack (Control control)
1581 if (!(control is IPostBackDataHandler))
1582 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1585 if (_requiresPostBack == null)
1586 _requiresPostBack = new ArrayList ();
1588 if (_requiresPostBack.Contains (control.UniqueID))
1591 _requiresPostBack.Add (control.UniqueID);
1594 [EditorBrowsable (EditorBrowsableState.Advanced)]
1595 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1597 requiresRaiseEvent = control;
1603 [EditorBrowsable (EditorBrowsableState.Advanced)]
1604 public virtual void RegisterStartupScript (string key, string script)
1606 scriptManager.RegisterStartupScript (key, script);
1609 [EditorBrowsable (EditorBrowsableState.Advanced)]
1610 public void RegisterViewStateHandler ()
1612 handleViewState = true;
1615 [EditorBrowsable (EditorBrowsableState.Advanced)]
1616 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1618 PageStatePersister persister = this.PageStatePersister;
1619 if (persister == null)
1621 Pair pair = viewState as Pair;
1623 persister.ViewState = pair.First;
1624 persister.ControlState = pair.Second;
1626 persister.ViewState = viewState;
1630 internal string RawViewState {
1632 NameValueCollection postdata = _requestValueCollection;
1634 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1637 if (view_state == "")
1641 set { _savedViewState = value; }
1649 PageStatePersister PageStatePersister {
1651 if (page_state_persister == null)
1652 page_state_persister = new HiddenFieldPageStatePersister (this);
1653 return page_state_persister;
1657 [EditorBrowsable (EditorBrowsableState.Advanced)]
1658 protected virtual object LoadPageStateFromPersistenceMedium ()
1660 PageStatePersister persister = this.PageStatePersister;
1661 if (persister == null)
1664 return new Pair (persister.ViewState, persister.ControlState);
1667 internal void LoadPageViewState()
1669 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1670 if (sState != null) {
1673 LoadPageControlState (sState.Second);
1675 Pair vsr = sState.First as Pair;
1677 LoadViewStateRecursive (vsr.First);
1678 _requiresPostBackCopy = vsr.Second as ArrayList;
1684 internal void SavePageViewState ()
1686 if (!handleViewState)
1690 object controlState = SavePageControlState ();
1693 object viewState = SaveViewStateRecursive ();
1694 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1697 if (viewState != null || reqPostback != null)
1698 vsr = new Pair (viewState, reqPostback);
1699 Pair pair = new Pair ();
1703 pair.Second = controlState;
1707 if (pair.First == null && pair.Second == null)
1708 SavePageStateToPersistenceMedium (null);
1710 SavePageStateToPersistenceMedium (pair);
1714 public virtual void Validate ()
1716 is_validated = true;
1717 ValidateCollection (_validators);
1721 internal bool AreValidatorsUplevel () {
1722 return AreValidatorsUplevel (String.Empty);
1725 internal bool AreValidatorsUplevel (string valGroup)
1727 internal virtual bool AreValidatorsUplevel ()
1730 bool uplevel = false;
1732 foreach (IValidator v in Validators) {
1733 BaseValidator bv = v as BaseValidator;
1734 if (bv == null) continue;
1737 if (valGroup != bv.ValidationGroup)
1740 if (bv.GetRenderUplevel()) {
1749 bool ValidateCollection (ValidatorCollection validators)
1752 if (!_eventValidation)
1756 if (validators == null || validators.Count == 0)
1759 bool all_valid = true;
1760 foreach (IValidator v in validators){
1762 if (v.IsValid == false)
1769 [EditorBrowsable (EditorBrowsableState.Advanced)]
1770 public virtual void VerifyRenderingInServerForm (Control control)
1772 if (_context == null)
1779 throw new HttpException ("Control '" +
1782 control.GetType ().Name +
1783 "' must be placed inside a form tag with runat=server.");
1786 protected override void FrameworkInitialize ()
1788 base.FrameworkInitialize ();
1790 InitializeStyleSheet ();
1801 ClientScriptManager ClientScript {
1802 get { return scriptManager; }
1807 static readonly object InitCompleteEvent = new object ();
1808 static readonly object LoadCompleteEvent = new object ();
1809 static readonly object PreInitEvent = new object ();
1810 static readonly object PreLoadEvent = new object ();
1811 static readonly object PreRenderCompleteEvent = new object ();
1812 static readonly object SaveStateCompleteEvent = new object ();
1814 const int initcomplete_mask = 1;
1815 const int loadcomplete_mask = 1 << 1;
1816 const int preinit_mask = 1 << 2;
1817 const int preload_mask = 1 << 3;
1818 const int prerendercomplete_mask = 1 << 4;
1819 const int savestatecomplete_mask = 1 << 5;
1821 [EditorBrowsable (EditorBrowsableState.Advanced)]
1822 public event EventHandler InitComplete {
1824 event_mask |= initcomplete_mask;
1825 Events.AddHandler (InitCompleteEvent, value);
1827 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1830 [EditorBrowsable (EditorBrowsableState.Advanced)]
1831 public event EventHandler LoadComplete {
1833 event_mask |= loadcomplete_mask;
1834 Events.AddHandler (LoadCompleteEvent, value);
1836 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1839 public event EventHandler PreInit {
1841 event_mask |= preinit_mask;
1842 Events.AddHandler (PreInitEvent, value);
1844 remove { Events.RemoveHandler (PreInitEvent, value); }
1847 [EditorBrowsable (EditorBrowsableState.Advanced)]
1848 public event EventHandler PreLoad {
1850 event_mask |= preload_mask;
1851 Events.AddHandler (PreLoadEvent, value);
1853 remove { Events.RemoveHandler (PreLoadEvent, value); }
1856 [EditorBrowsable (EditorBrowsableState.Advanced)]
1857 public event EventHandler PreRenderComplete {
1859 event_mask |= prerendercomplete_mask;
1860 Events.AddHandler (PreRenderCompleteEvent, value);
1862 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1865 [EditorBrowsable (EditorBrowsableState.Advanced)]
1866 public event EventHandler SaveStateComplete {
1868 event_mask |= savestatecomplete_mask;
1869 Events.AddHandler (SaveStateCompleteEvent, value);
1871 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1874 protected virtual void OnInitComplete (EventArgs e)
1876 if ((event_mask & initcomplete_mask) != 0) {
1877 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1878 if (eh != null) eh (this, e);
1882 protected virtual void OnLoadComplete (EventArgs e)
1884 if ((event_mask & loadcomplete_mask) != 0) {
1885 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1886 if (eh != null) eh (this, e);
1890 protected virtual void OnPreInit (EventArgs e)
1892 if ((event_mask & preinit_mask) != 0) {
1893 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1894 if (eh != null) eh (this, e);
1898 protected virtual void OnPreLoad (EventArgs e)
1900 if ((event_mask & preload_mask) != 0) {
1901 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1902 if (eh != null) eh (this, e);
1906 protected virtual void OnPreRenderComplete (EventArgs e)
1908 if ((event_mask & prerendercomplete_mask) != 0) {
1909 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1910 if (eh != null) eh (this, e);
1915 if (!Form.DetermineRenderUplevel ())
1918 /* figure out if we have some control we're going to focus */
1919 if (String.IsNullOrEmpty (_focusedControlID)) {
1920 _focusedControlID = Form.DefaultFocus;
1921 if (String.IsNullOrEmpty (_focusedControlID))
1922 _focusedControlID = Form.DefaultButton;
1925 if (!String.IsNullOrEmpty (_focusedControlID)) {
1926 ClientScript.RegisterWebFormClientScript ();
1927 ClientScript.RegisterStartupScript ("HtmlForm-DefaultButton-StartupScript",
1928 String.Format ("<script type=\"text/javascript\">\n" +
1930 "WebForm_AutoFocus('{0}');// -->\n" +
1931 "</script>\n", _focusedControlID));
1934 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1935 ClientScript.RegisterWebFormClientScript ();
1936 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1937 "WebForm_ReEnableControls(this);");
1941 internal void RegisterEnabledControl (Control control)
1943 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1945 _hasEnabledControlArray = true;
1946 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Format ("'{0}'", control.ClientID));
1949 protected virtual void OnSaveStateComplete (EventArgs e)
1951 if ((event_mask & savestatecomplete_mask) != 0) {
1952 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1953 if (eh != null) eh (this, e);
1957 public HtmlForm Form {
1958 get { return _form; }
1961 internal void RegisterForm (HtmlForm form)
1966 [BrowsableAttribute (false)]
1967 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1968 public Page PreviousPage {
1970 if (_doLoadPreviousPage) {
1971 _doLoadPreviousPage = false;
1972 LoadPreviousPageReference ();
1974 return previousPage;
1979 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1980 [BrowsableAttribute (false)]
1981 public bool IsCallback {
1982 get { return isCallback; }
1985 [BrowsableAttribute (false)]
1986 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1987 public bool IsCrossPagePostBack {
1988 get { return isCrossPagePostBack; }
1991 public new virtual char IdSeparator {
1993 //TODO: why override?
1994 return base.IdSeparator;
1998 string ProcessCallbackData ()
2000 string callbackTarget = _requestValueCollection [CallbackSourceID];
2001 if (callbackTarget == null || callbackTarget.Length == 0)
2002 throw new HttpException ("Callback target not provided.");
2004 Control targetControl = FindControl (callbackTarget);
2005 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2007 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2009 string callbackEventError = String.Empty;
2010 string callBackResult;
2011 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2014 target.RaiseCallbackEvent (callbackArgument);
2016 catch (Exception ex) {
2017 callbackEventError = String.Format ("e{0}", ex.Message);
2021 callBackResult = target.GetCallbackResult ();
2023 catch (Exception ex) {
2024 return String.Format ("e{0}", ex.Message);
2027 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2028 return String.Format ("{0}{1}|{2}{3}", callbackEventError, eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
2031 [BrowsableAttribute (false)]
2032 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2033 public HtmlHead Header {
2034 get { return htmlHeader; }
2037 internal void SetHeader (HtmlHead header)
2039 htmlHeader = header;
2040 if (_title != null) {
2041 htmlHeader.Title = _title;
2046 protected bool AsyncMode {
2047 get { return asyncMode; }
2048 set { asyncMode = value; }
2051 public TimeSpan AsyncTimeout {
2052 get { return asyncTimeout; }
2053 set { asyncTimeout = value; }
2056 public bool IsAsync {
2057 get { return AsyncMode; }
2060 [MonoTODO ("Not Implemented")]
2061 protected internal virtual string UniqueFilePathSuffix {
2063 throw new NotImplementedException ();
2067 [MonoTODO ("Not Implemented")]
2068 public int MaxPageStateFieldLength {
2070 throw new NotImplementedException ();
2073 throw new NotImplementedException ();
2077 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2079 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2082 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2085 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2088 if (_lifeCycle >= PageLifeCycle.PreRender) {
2089 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
2092 if (beginHandler == null) {
2093 throw new ArgumentNullException ("beginHandler");
2096 if (endHandler == null) {
2097 throw new ArgumentNullException ("endHandler");
2100 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2103 private List<PageAsyncTask> ParallelTasks {
2106 if (parallelTasks == null) {
2107 parallelTasks = new List<PageAsyncTask>();
2109 return parallelTasks;
2113 private List<PageAsyncTask> SerialTasks {
2115 if (serialTasks == null) {
2116 serialTasks = new List<PageAsyncTask> ();
2122 public void RegisterAsyncTask (PageAsyncTask task)
2125 throw new ArgumentNullException ("task");
2128 if (task.ExecuteInParallel) {
2129 ParallelTasks.Add (task);
2132 SerialTasks.Add (task);
2136 public void ExecuteRegisteredAsyncTasks ()
2138 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2139 (serialTasks == null || serialTasks.Count == 0)){
2143 if (parallelTasks != null) {
2144 DateTime startExecution = DateTime.Now;
2145 List<PageAsyncTask> localParallelTasks = parallelTasks;
2146 parallelTasks = null; // Shouldn't execute tasks twice
2147 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2148 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2149 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2150 if (result.CompletedSynchronously) {
2151 parallelTask.EndHandler (result);
2154 asyncResults.Add (result);
2158 if (asyncResults.Count > 0) {
2160 TimeSpan timeout = AsyncTimeout;
2161 long t1 = DateTime.Now.Ticks;
2162 bool signalled = true;
2163 for (int i = 0; i < asyncResults.Count; i++) {
2164 if (asyncResults [i].IsCompleted)
2168 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2171 long t2 = DateTime.Now.Ticks;
2172 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2173 if (timeout.Ticks <= 0)
2177 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2181 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2183 for (i = 0; i < asyncResults.Count; i++) {
2184 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2186 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2187 if (!allSignalled) {
2188 for (i = 0; i < asyncResults.Count; i++) {
2189 if (!asyncResults [i].IsCompleted) {
2190 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2196 DateTime endWait = DateTime.Now;
2197 TimeSpan elapsed = endWait - startExecution;
2198 if (elapsed <= AsyncTimeout) {
2199 AsyncTimeout -= elapsed;
2202 AsyncTimeout = TimeSpan.FromTicks(0);
2206 if (serialTasks != null) {
2207 List<PageAsyncTask> localSerialTasks = serialTasks;
2208 serialTasks = null; // Shouldn't execute tasks twice
2209 foreach (PageAsyncTask serialTask in localSerialTasks) {
2210 DateTime startExecution = DateTime.Now;
2212 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2213 if (result.CompletedSynchronously) {
2214 serialTask.EndHandler (result);
2217 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2218 if (!done && !result.IsCompleted) {
2219 serialTask.TimeoutHandler (result);
2222 DateTime endWait = DateTime.Now;
2223 TimeSpan elapsed = endWait - startExecution;
2224 if (elapsed <= AsyncTimeout) {
2225 AsyncTimeout -= elapsed;
2228 AsyncTimeout = TimeSpan.FromTicks (0);
2232 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2235 void EndAsyncTaskCallback (IAsyncResult result)
2237 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2238 task.EndHandler (result);
2241 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2243 Type htmlTextWriterType = typeof (HtmlTextWriter);
2245 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2246 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2249 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2250 if (constructor == null) {
2251 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2254 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2257 public ViewStateEncryptionMode ViewStateEncryptionMode {
2258 get { return viewStateEncryptionMode; }
2259 set { viewStateEncryptionMode = value; }
2262 public void RegisterRequiresViewStateEncryption ()
2264 controlRegisteredForViewStateEncryption = true;
2267 private static byte [] AES_IV = null;
2268 private static byte [] TripleDES_IV = null;
2269 private static object locker = new object ();
2270 private static bool isEncryptionInitialized = false;
2272 private static void InitializeEncryption ()
2274 if (isEncryptionInitialized) {
2279 if (isEncryptionInitialized) {
2283 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2284 AES_IV = new byte [16];
2285 TripleDES_IV = new byte [8];
2288 for (i = 0; i < AES_IV.Length; i++) {
2289 AES_IV [i] = (byte) iv_string [i];
2292 for (i = 0; i < TripleDES_IV.Length; i++) {
2293 TripleDES_IV [i] = (byte) iv_string [i];
2296 isEncryptionInitialized = true;
2300 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2302 ICryptoTransform transform = null;
2303 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2304 byte [] vk = config.ValidationKeyBytes;
2306 switch (config.Validation) {
2307 case MachineKeyValidation.SHA1:
2308 transform = SHA1.Create ();
2311 case MachineKeyValidation.MD5:
2312 transform = MD5.Create ();
2315 case MachineKeyValidation.AES:
2316 if (cryptoStreamMode == CryptoStreamMode.Read){
2317 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2319 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2323 case MachineKeyValidation.TripleDES:
2324 if (cryptoStreamMode == CryptoStreamMode.Read){
2325 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2327 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2335 internal bool NeedViewStateEncryption {
2337 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2338 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2339 controlRegisteredForViewStateEncryption));
2344 void ApplyMasterPage ()
2346 if (masterPageFile != null && masterPageFile.Length > 0) {
2347 ArrayList appliedMasterPageFiles = new ArrayList ();
2349 if (Master != null) {
2350 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2354 Controls.Add (Master);
2359 [DefaultValueAttribute ("")]
2360 public virtual string MasterPageFile {
2361 get { return masterPageFile; }
2363 masterPageFile = value;
2368 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2369 [BrowsableAttribute (false)]
2370 public MasterPage Master {
2372 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2375 if (masterPage == null)
2376 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2382 public void SetFocus (string clientID)
2384 if (String.IsNullOrEmpty (clientID))
2385 throw new ArgumentNullException ("control");
2387 if (_lifeCycle > PageLifeCycle.PreRender)
2388 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2391 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2393 _focusedControlID = clientID;
2396 public void SetFocus (Control control)
2398 if (control == null)
2399 throw new ArgumentNullException ("control");
2401 SetFocus (control.ClientID);
2404 [EditorBrowsable (EditorBrowsableState.Advanced)]
2405 public void RegisterRequiresControlState (Control control)
2407 if (control == null)
2408 throw new ArgumentNullException ("control");
2410 if (RequiresControlState (control))
2413 if (requireStateControls == null)
2414 requireStateControls = new ArrayList ();
2415 int n = requireStateControls.Add (control);
2417 if (_savedControlState == null || n >= _savedControlState.Length)
2420 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2421 if (parent.IsChildControlStateCleared)
2424 object state = _savedControlState [n];
2426 control.LoadControlState (state);
2429 public bool RequiresControlState (Control control)
2431 if (requireStateControls == null) return false;
2432 return requireStateControls.Contains (control);
2435 [EditorBrowsable (EditorBrowsableState.Advanced)]
2436 public void UnregisterRequiresControlState (Control control)
2438 if (requireStateControls != null)
2439 requireStateControls.Remove (control);
2442 public ValidatorCollection GetValidators (string validationGroup)
2444 string valgr = validationGroup;
2446 valgr = String.Empty;
2448 if (_validatorsByGroup == null) _validatorsByGroup = new Hashtable ();
2449 ValidatorCollection col = _validatorsByGroup [valgr] as ValidatorCollection;
2451 col = new ValidatorCollection ();
2452 _validatorsByGroup [valgr] = col;
2457 public virtual void Validate (string validationGroup)
2459 is_validated = true;
2460 if (validationGroup == null)
2461 ValidateCollection (_validatorsByGroup [String.Empty] as ValidatorCollection);
2462 else if (_validatorsByGroup != null) {
2463 ValidateCollection (_validatorsByGroup [validationGroup] as ValidatorCollection);
2467 object SavePageControlState ()
2469 if (requireStateControls == null) return null;
2470 object[] state = new object [requireStateControls.Count];
2472 bool allNull = true;
2473 for (int n=0; n<state.Length; n++) {
2474 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2475 if (state [n] != null) allNull = false;
2477 if (allNull) return null;
2481 void LoadPageControlState (object data)
2483 _savedControlState = (object []) data;
2485 if (requireStateControls == null) return;
2487 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2488 for (int n=0; n < max; n++) {
2489 Control ctl = (Control) requireStateControls [n];
2490 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2494 void LoadPreviousPageReference ()
2496 if (_requestValueCollection != null) {
2497 string prevPage = _requestValueCollection [PreviousPageID];
2498 if (prevPage != null) {
2499 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2500 previousPage.ProcessCrossPagePostBack (_context);
2506 Hashtable contentTemplates;
2507 [EditorBrowsable (EditorBrowsableState.Never)]
2508 protected internal void AddContentTemplate (string templateName, ITemplate template)
2510 if (contentTemplates == null)
2511 contentTemplates = new Hashtable ();
2512 contentTemplates [templateName] = template;
2515 PageTheme _pageTheme;
2516 internal PageTheme PageTheme {
2517 get { return _pageTheme; }
2520 PageTheme _styleSheetPageTheme;
2521 internal PageTheme StyleSheetPageTheme {
2522 get { return _styleSheetPageTheme; }
2527 internal void PushDataItemContext (object o) {
2528 if (dataItemCtx == null)
2529 dataItemCtx = new Stack ();
2531 dataItemCtx.Push (o);
2534 internal void PopDataItemContext () {
2535 if (dataItemCtx == null)
2536 throw new InvalidOperationException ();
2541 public object GetDataItem() {
2542 if (dataItemCtx == null || dataItemCtx.Count == 0)
2543 throw new InvalidOperationException ("No data item");
2545 return dataItemCtx.Peek ();
2548 protected internal override void OnInit (EventArgs e)
2552 ArrayList themes = new ArrayList();
2554 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2555 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2556 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2557 themes.AddRange (PageTheme.GetStyleSheets ());
2559 if (themes.Count > 0 && Header == null)
2560 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2562 foreach (string lss in themes) {
2563 HtmlLink hl = new HtmlLink ();
2564 hl.Href = ResolveUrl (lss);
2565 hl.Attributes["type"] = "text/css";
2566 hl.Attributes["rel"] = "stylesheet";
2567 Header.Controls.Add (hl);
2574 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2575 protected object GetWrappedFileDependencies (string [] list)
2580 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2581 protected virtual void InitializeCulture ()
2585 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2586 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)