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 {
475 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
477 public HttpRequest Request
480 if (_context != null)
481 return _context.Request;
483 throw new HttpException("Request is not available without context");
487 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
489 public HttpResponse Response
492 if (_context != null)
493 return _context.Response;
495 throw new HttpException ("Response is not available without context");
499 [EditorBrowsable (EditorBrowsableState.Never)]
501 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
502 [BrowsableAttribute (false)]
503 public string ResponseEncoding
505 get { return Response.ContentEncoding.WebName; }
506 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
509 protected string ResponseEncoding
511 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
515 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
517 public HttpServerUtility Server
520 return Context.Server;
524 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
526 public virtual HttpSessionState Session
529 if (_context == null)
530 _context = HttpContext.Current;
532 if (_context == null)
533 throw new HttpException ("Session is not available without context");
535 if (_context.Session == null)
536 throw new HttpException ("Session state can only be used " +
537 "when enableSessionState is set to true, either " +
538 "in a configuration file or in the Page directive.");
540 return _context.Session;
545 [FilterableAttribute (false)]
549 public bool SmartNavigation
551 get { return _smartNavigation; }
552 set { _smartNavigation = value; }
556 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
559 public virtual string StyleSheetTheme {
560 get { return _styleSheetTheme; }
561 set { _styleSheetTheme = value; }
565 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
566 public virtual string Theme {
567 get { return _theme; }
568 set { _theme = value; }
571 void InitializeStyleSheet ()
573 if (_styleSheetTheme == null) {
574 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
576 _styleSheetTheme = ps.StyleSheetTheme;
578 if (_styleSheetTheme != null && _styleSheetTheme != "")
579 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, _context);
582 void InitializeTheme ()
584 if (_theme == null) {
585 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
589 if (_theme != null && _theme != "") {
590 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, _context);
591 _pageTheme.SetPage (this);
600 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
601 public string Title {
604 return htmlHeader.Title;
608 if (htmlHeader != null)
609 htmlHeader.Title = value;
616 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
618 public TraceContext Trace
620 get { return Context.Trace; }
623 [EditorBrowsable (EditorBrowsableState.Never)]
625 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
626 [BrowsableAttribute (false)]
627 public bool TraceEnabled
629 get { return Trace.IsEnabled; }
630 set { Trace.IsEnabled = value; }
633 protected bool TraceEnabled
635 set { Trace.IsEnabled = value; }
639 [EditorBrowsable (EditorBrowsableState.Never)]
641 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
642 [BrowsableAttribute (false)]
643 public TraceMode TraceModeValue
645 get { return Trace.TraceMode; }
646 set { Trace.TraceMode = value; }
649 protected TraceMode TraceModeValue
651 set { Trace.TraceMode = value; }
655 [EditorBrowsable (EditorBrowsableState.Never)]
656 protected int TransactionMode
659 get { return _transactionMode; }
661 set { _transactionMode = value; }
666 // This method is here just to remove the warning about "_transactionMode" not being
667 // used. We probably will use it internally at some point.
669 internal int GetTransactionMode ()
671 return _transactionMode;
676 [EditorBrowsable (EditorBrowsableState.Advanced)]
677 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
678 [BrowsableAttribute (false)]
679 public string UICulture
681 get { return Thread.CurrentThread.CurrentUICulture.Name; }
682 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
685 [EditorBrowsable (EditorBrowsableState.Never)]
686 protected string UICulture
688 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
692 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
694 public IPrincipal User
696 get { return Context.User; }
699 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
701 public ValidatorCollection Validators
704 if (_validators == null)
705 _validators = new ValidatorCollection ();
710 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
712 public string ViewStateUserKey {
713 get { return viewStateUserKey; }
714 set { viewStateUserKey = value; }
718 public override bool Visible
720 get { return base.Visible; }
721 set { base.Visible = value; }
729 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
733 CultureInfo ret = null;
734 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
736 if (Context.IsPortletRequest)
739 string[] languages = Request.UserLanguages;
741 if (languages != null && languages.Length > 0)
742 ret = CultureInfo.CreateSpecificCulture (languages[0]);
749 ret = CultureInfo.CreateSpecificCulture (culture);
755 [EditorBrowsable (EditorBrowsableState.Never)]
756 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
760 throw new NotImplementedException ();
763 [EditorBrowsable (EditorBrowsableState.Never)]
764 protected void AspCompatEndProcessRequest (IAsyncResult result)
766 throw new NotImplementedException ();
769 [EditorBrowsable (EditorBrowsableState.Advanced)]
770 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
772 return new HtmlTextWriter (tw);
775 [EditorBrowsable (EditorBrowsableState.Never)]
776 public void DesignerInitialize ()
778 InitRecursive (null);
781 [EditorBrowsable (EditorBrowsableState.Advanced)]
782 protected virtual NameValueCollection DeterminePostBackMode ()
784 if (_context == null)
787 HttpRequest req = _context.Request;
791 NameValueCollection coll = null;
792 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
795 else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
799 coll = req.QueryString;
801 WebROCollection c = (WebROCollection) coll;
802 allow_load = !c.GotID;
804 c.ID = GetTypeHashCode ();
806 allow_load = (c.ID == GetTypeHashCode ());
808 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
815 public override Control FindControl (string id) {
819 return base.FindControl (id);
826 [EditorBrowsable (EditorBrowsableState.Advanced)]
827 public string GetPostBackClientEvent (Control control, string argument)
829 return scriptManager.GetPostBackEventReference (control, argument);
835 [EditorBrowsable (EditorBrowsableState.Advanced)]
836 public string GetPostBackClientHyperlink (Control control, string argument)
838 return scriptManager.GetPostBackClientHyperlink (control, argument);
844 [EditorBrowsable (EditorBrowsableState.Advanced)]
845 public string GetPostBackEventReference (Control control)
847 return scriptManager.GetPostBackEventReference (control, "");
853 [EditorBrowsable (EditorBrowsableState.Advanced)]
854 public string GetPostBackEventReference (Control control, string argument)
856 return scriptManager.GetPostBackEventReference (control, argument);
859 internal void RequiresPostBackScript ()
862 if (requiresPostBackScript)
864 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
865 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
867 requiresPostBackScript = true;
870 [EditorBrowsable (EditorBrowsableState.Never)]
871 public virtual int GetTypeHashCode ()
877 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
878 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
880 if (cacheSettings.Enabled)
881 InitOutputCache(cacheSettings.Duration,
882 cacheSettings.VaryByHeader,
883 cacheSettings.VaryByCustom,
884 cacheSettings.Location,
885 cacheSettings.VaryByParam);
889 [EditorBrowsable (EditorBrowsableState.Never)]
890 protected virtual void InitOutputCache (int duration,
893 OutputCacheLocation location,
896 HttpCachePolicy cache = _context.Response.Cache;
897 bool set_vary = false;
900 case OutputCacheLocation.Any:
901 cache.SetCacheability (HttpCacheability.Public);
902 cache.SetMaxAge (new TimeSpan (0, 0, duration));
903 cache.SetLastModified (_context.Timestamp);
906 case OutputCacheLocation.Client:
907 cache.SetCacheability (HttpCacheability.Private);
908 cache.SetMaxAge (new TimeSpan (0, 0, duration));
909 cache.SetLastModified (_context.Timestamp);
911 case OutputCacheLocation.Downstream:
912 cache.SetCacheability (HttpCacheability.Public);
913 cache.SetMaxAge (new TimeSpan (0, 0, duration));
914 cache.SetLastModified (_context.Timestamp);
916 case OutputCacheLocation.Server:
917 cache.SetCacheability (HttpCacheability.Server);
920 case OutputCacheLocation.None:
925 if (varyByCustom != null)
926 cache.SetVaryByCustom (varyByCustom);
928 if (varyByParam != null && varyByParam.Length > 0) {
929 string[] prms = varyByParam.Split (';');
930 foreach (string p in prms)
931 cache.VaryByParams [p.Trim ()] = true;
932 cache.VaryByParams.IgnoreParams = false;
934 cache.VaryByParams.IgnoreParams = true;
937 if (varyByHeader != null && varyByHeader.Length > 0) {
938 string[] hdrs = varyByHeader.Split (';');
939 foreach (string h in hdrs)
940 cache.VaryByHeaders [h.Trim ()] = true;
944 cache.Duration = duration;
945 cache.SetExpires (_context.Timestamp.AddSeconds (duration));
951 [EditorBrowsable (EditorBrowsableState.Advanced)]
953 public bool IsClientScriptBlockRegistered (string key)
955 return scriptManager.IsClientScriptBlockRegistered (key);
961 [EditorBrowsable (EditorBrowsableState.Advanced)]
963 public bool IsStartupScriptRegistered (string key)
965 return scriptManager.IsStartupScriptRegistered (key);
968 public string MapPath (string virtualPath)
970 return Request.MapPath (virtualPath);
974 protected internal override void Render (HtmlTextWriter writer) {
975 if (MaintainScrollPositionOnPostBack) {
976 ClientScript.RegisterWebFormClientScript ();
978 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
979 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
981 StringBuilder script = new StringBuilder ();
982 script.AppendLine ("<script type=\"text/javascript\">");
983 script.AppendLine ("<!--");
984 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
985 script.AppendLine (theForm + ".submit = WebForm_SaveScrollPositionSubmit;");
986 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
987 script.AppendLine (theForm + ".onsubmit = WebForm_SaveScrollPositionOnSubmit;");
989 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
990 script.AppendLine ("window.onload = function () { WebForm_RestoreScrollPosition (" + theForm + "); };");
992 script.AppendLine ("// -->");
993 script.AppendLine ("</script>");
995 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
997 base.Render (writer);
1001 private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1004 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
1005 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
1007 writer.WriteLine ();
1009 ClientScript.WriteBeginScriptBlock (writer);
1012 RenderClientScriptFormDeclaration (writer, formUniqueID);
1014 writer.WriteLine ("function __doPostBack(eventTarget, eventArgument) {");
1015 writer.WriteLine ("\tvar currForm = {0};", theForm);
1017 writer.WriteLine ("\tcurrForm.__doPostBack(eventTarget, eventArgument);");
1018 writer.WriteLine ("}");
1019 writer.WriteLine ("{0}.__doPostBack = function (eventTarget, eventArgument) {{", theForm);
1020 writer.WriteLine ("\tvar currForm = this;");
1021 writer.WriteLine ("\tif(currForm.onsubmit && currForm.onsubmit() == false) return;");
1023 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1025 writer.WriteLine ("\tcurrForm.{0}.value = eventTarget;", postEventSourceID);
1026 writer.WriteLine ("\tcurrForm.{0}.value = eventArgument;", postEventArgumentID);
1027 writer.WriteLine ("\tcurrForm.submit();");
1028 writer.WriteLine ("}");
1030 ClientScript.WriteEndScriptBlock (writer);
1033 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1035 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1036 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1037 writer.WriteLine ("\t{0}.isAspForm = true;", theForm);
1039 string serverUrl = Context.ServletResponse.encodeURL (Request.RawUrl);
1040 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1044 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1047 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1049 renderingForm = true;
1050 writer.WriteLine ();
1053 ClientScript.WriteBeginScriptBlock (writer);
1054 RenderClientScriptFormDeclaration (writer, formUniqueID);
1055 ClientScript.WriteEndScriptBlock (writer);
1058 if (handleViewState)
1059 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1061 scriptManager.WriteHiddenFields (writer);
1062 if (requiresPostBackScript) {
1063 RenderPostBackScript (writer, formUniqueID);
1064 postBackScriptRendered = true;
1066 scriptManager.WriteClientScriptIncludes (writer);
1067 scriptManager.WriteClientScriptBlocks (writer);
1070 internal IStateFormatter GetFormatter ()
1072 return new ObjectStateFormatter (this);
1075 internal string GetSavedViewState ()
1077 return _savedViewState;
1080 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1082 if (!postBackScriptRendered && requiresPostBackScript)
1083 RenderPostBackScript (writer, formUniqueID);
1085 scriptManager.WriteArrayDeclares (writer);
1088 scriptManager.SaveEventValidationState ();
1089 scriptManager.WriteExpandoAttributes (writer);
1091 scriptManager.WriteHiddenFields (writer);
1092 scriptManager.WriteClientScriptIncludes (writer);
1093 scriptManager.WriteStartupScriptBlocks (writer);
1094 renderingForm = false;
1095 postBackScriptRendered = false;
1098 private void ProcessPostData (NameValueCollection data, bool second)
1101 Hashtable used = new Hashtable ();
1102 foreach (string id in data.AllKeys){
1103 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
1106 string real_id = id;
1107 int dot = real_id.IndexOf ('.');
1109 real_id = real_id.Substring (0, dot);
1111 if (real_id == null || used.ContainsKey (real_id))
1114 used.Add (real_id, real_id);
1116 Control ctrl = FindControl (real_id);
1118 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1119 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1123 RegisterRequiresRaiseEvent (pbeh);
1127 if (pbdh.LoadPostData (real_id, data) == true) {
1128 if (requiresPostDataChanged == null)
1129 requiresPostDataChanged = new ArrayList ();
1130 requiresPostDataChanged.Add (pbdh);
1133 if (_requiresPostBackCopy != null)
1134 _requiresPostBackCopy.Remove (real_id);
1136 } else if (!second) {
1137 if (secondPostData == null)
1138 secondPostData = new NameValueCollection ();
1139 secondPostData.Add (real_id, data [id]);
1144 ArrayList list1 = null;
1145 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1146 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1147 foreach (string id in handlers) {
1148 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1150 _requiresPostBackCopy.Remove (id);
1151 if (pbdh.LoadPostData (id, data)) {
1152 if (requiresPostDataChanged == null)
1153 requiresPostDataChanged = new ArrayList ();
1155 requiresPostDataChanged.Add (pbdh);
1157 } else if (!second) {
1159 list1 = new ArrayList ();
1164 _requiresPostBackCopy = second ? null : list1;
1166 secondPostData = null;
1169 [EditorBrowsable (EditorBrowsableState.Never)]
1171 public virtual void ProcessRequest (HttpContext context)
1173 public void ProcessRequest (HttpContext context)
1177 _lifeCycle = PageLifeCycle.Unknown;
1180 if (clientTarget != null)
1181 Request.ClientTarget = clientTarget;
1183 WireupAutomaticEvents ();
1184 //-- Control execution lifecycle in the docs
1186 // Save culture information because it can be modified in FrameworkInitialize()
1187 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1188 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1189 FrameworkInitialize ();
1190 context.ErrorPage = _errorPage;
1193 InternalProcessRequest ();
1194 } catch (ThreadAbortException) {
1195 // Do nothing, just ignore it by now.
1196 } catch (Exception e) {
1197 context.AddError (e); // OnError might access LastError
1198 OnError (EventArgs.Empty);
1199 context.ClearError (e);
1200 // We want to remove that error, as we're rethrowing to stop
1201 // further processing.
1202 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1207 _lifeCycle = PageLifeCycle.Unload;
1210 UnloadRecursive (true);
1212 _lifeCycle = PageLifeCycle.End;
1215 if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1216 Thread.CurrentThread.CurrentCulture = culture;
1218 if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1219 Thread.CurrentThread.CurrentUICulture = uiculture;
1224 delegate void ProcessRequestDelegate (HttpContext context);
1226 private sealed class DummyAsyncResult : IAsyncResult
1228 readonly object state;
1229 readonly WaitHandle asyncWaitHandle;
1230 readonly bool completedSynchronously;
1231 readonly bool isCompleted;
1233 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1235 this.isCompleted = isCompleted;
1236 this.completedSynchronously = completedSynchronously;
1239 asyncWaitHandle = new ManualResetEvent (true);
1242 asyncWaitHandle = new ManualResetEvent (false);
1246 #region IAsyncResult Members
1248 public object AsyncState {
1249 get { return state; }
1252 public WaitHandle AsyncWaitHandle {
1253 get { return asyncWaitHandle; }
1256 public bool CompletedSynchronously {
1257 get { return completedSynchronously; }
1260 public bool IsCompleted {
1261 get { return isCompleted; }
1267 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1269 ProcessRequest (context);
1270 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1272 if (callback != null) {
1273 callback (asyncResult);
1279 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1283 internal void ProcessCrossPagePostBack (HttpContext context)
1285 isCrossPagePostBack = true;
1286 ProcessRequest (context);
1290 void InternalProcessRequest ()
1292 _requestValueCollection = this.DeterminePostBackMode();
1295 _lifeCycle = PageLifeCycle.Start;
1296 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1297 if (_requestValueCollection != null) {
1298 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1299 _doLoadPreviousPage = true;
1302 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1303 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1304 //isPostBack = !isCallback;
1307 string lastFocus = _requestValueCollection [LastFocusID];
1308 if (!String.IsNullOrEmpty (lastFocus)) {
1309 _focusedControlID = UniqueID2ClientID (lastFocus);
1313 // if request was transfered from other page - track Prev. Page
1314 previousPage = _context.LastPage;
1315 _context.LastPage = this;
1317 _lifeCycle = PageLifeCycle.PreInit;
1318 OnPreInit (EventArgs.Empty);
1322 _lifeCycle = PageLifeCycle.Init;
1324 Trace.Write ("aspx.page", "Begin Init");
1325 InitRecursive (null);
1326 Trace.Write ("aspx.page", "End Init");
1329 _lifeCycle = PageLifeCycle.InitComplete;
1330 OnInitComplete (EventArgs.Empty);
1333 renderingForm = false;
1335 if (IsPostBack || IsCallback) {
1336 _lifeCycle = PageLifeCycle.PreLoad;
1337 if (_requestValueCollection != null)
1338 scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
1342 Trace.Write ("aspx.page", "Begin LoadViewState");
1343 LoadPageViewState ();
1344 Trace.Write ("aspx.page", "End LoadViewState");
1345 Trace.Write ("aspx.page", "Begin ProcessPostData");
1349 ProcessPostData (_requestValueCollection, false);
1350 Trace.Write ("aspx.page", "End ProcessPostData");
1354 OnPreLoad (EventArgs.Empty);
1355 _lifeCycle = PageLifeCycle.Load;
1363 if (IsPostBack || IsCallback) {
1364 _lifeCycle = PageLifeCycle.ControlEvents;
1368 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1369 ProcessPostData (secondPostData, true);
1370 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1371 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1372 RaiseChangedEvents ();
1373 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1374 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1375 RaisePostBackEvents ();
1376 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1380 _lifeCycle = PageLifeCycle.LoadComplete;
1381 OnLoadComplete (EventArgs.Empty);
1383 if (IsCrossPagePostBack)
1387 string result = ProcessCallbackData ();
1388 HtmlTextWriter callbackOutput = new HtmlTextWriter (_context.Response.Output);
1389 callbackOutput.Write (result);
1390 callbackOutput.Flush ();
1394 _lifeCycle = PageLifeCycle.PreRender;
1397 Trace.Write ("aspx.page", "Begin PreRender");
1398 PreRenderRecursiveInternal ();
1399 Trace.Write ("aspx.page", "End PreRender");
1402 ExecuteRegisteredAsyncTasks ();
1404 _lifeCycle = PageLifeCycle.PreRenderComplete;
1405 OnPreRenderComplete (EventArgs.Empty);
1408 Trace.Write ("aspx.page", "Begin SaveViewState");
1409 SavePageViewState ();
1410 Trace.Write ("aspx.page", "End SaveViewState");
1413 _lifeCycle = PageLifeCycle.SaveStateComplete;
1414 OnSaveStateComplete (EventArgs.Empty);
1416 if (OnSaveStateCompleteForPortlet ())
1418 #endif // TARGET_J2EE
1422 _lifeCycle = PageLifeCycle.Render;
1423 scriptManager.ResetEventValidationState ();
1427 Trace.Write ("aspx.page", "Begin Render");
1428 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1429 RenderControl (output);
1430 Trace.Write ("aspx.page", "End Render");
1433 private void RenderTrace ()
1435 TraceManager traceManager = HttpRuntime.TraceManager;
1437 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1442 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1445 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1446 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1447 Trace.Render (output);
1452 bool CheckForValidationSupport (Control targetControl)
1454 if (targetControl == null)
1456 Type type = targetControl.GetType ();
1457 object[] attributes = type.GetCustomAttributes (false);
1458 foreach (object attr in attributes)
1459 if (attr is SupportsEventValidationAttribute)
1465 void RaisePostBackEvents ()
1468 Control targetControl;
1470 if (requiresRaiseEvent != null) {
1471 RaisePostBackEvent (requiresRaiseEvent, null);
1475 NameValueCollection postdata = _requestValueCollection;
1476 if (postdata == null)
1479 string eventTarget = postdata [postEventSourceID];
1480 if (eventTarget == null || eventTarget.Length == 0) {
1486 targetControl = FindControl (eventTarget);
1487 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1489 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1495 string eventArgument = postdata [postEventArgumentID];
1496 RaisePostBackEvent (target, eventArgument);
1499 internal void RaiseChangedEvents ()
1501 if (requiresPostDataChanged == null)
1504 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1505 ipdh.RaisePostDataChangedEvent ();
1507 requiresPostDataChanged = null;
1510 [EditorBrowsable (EditorBrowsableState.Advanced)]
1511 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1514 Control targetControl = sourceControl as Control;
1515 if (targetControl != null && CheckForValidationSupport (targetControl))
1516 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1518 sourceControl.RaisePostBackEvent (eventArgument);
1524 [EditorBrowsable (EditorBrowsableState.Advanced)]
1525 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1527 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1533 [EditorBrowsable (EditorBrowsableState.Advanced)]
1534 public virtual void RegisterClientScriptBlock (string key, string script)
1536 scriptManager.RegisterClientScriptBlock (key, script);
1542 [EditorBrowsable (EditorBrowsableState.Advanced)]
1543 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1545 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1548 [MonoTODO("Not implemented, Used in HtmlForm")]
1549 internal void RegisterClientScriptFile (string a, string b, string c)
1551 throw new NotImplementedException ();
1557 [EditorBrowsable (EditorBrowsableState.Advanced)]
1558 public void RegisterOnSubmitStatement (string key, string script)
1560 scriptManager.RegisterOnSubmitStatement (key, script);
1563 internal string GetSubmitStatements ()
1565 return scriptManager.WriteSubmitStatements ();
1568 [EditorBrowsable (EditorBrowsableState.Advanced)]
1569 public void RegisterRequiresPostBack (Control control)
1572 if (!(control is IPostBackDataHandler))
1573 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1576 if (_requiresPostBack == null)
1577 _requiresPostBack = new ArrayList ();
1579 if (_requiresPostBack.Contains (control.UniqueID))
1582 _requiresPostBack.Add (control.UniqueID);
1585 [EditorBrowsable (EditorBrowsableState.Advanced)]
1586 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1588 requiresRaiseEvent = control;
1594 [EditorBrowsable (EditorBrowsableState.Advanced)]
1595 public virtual void RegisterStartupScript (string key, string script)
1597 scriptManager.RegisterStartupScript (key, script);
1600 [EditorBrowsable (EditorBrowsableState.Advanced)]
1601 public void RegisterViewStateHandler ()
1603 handleViewState = true;
1606 [EditorBrowsable (EditorBrowsableState.Advanced)]
1607 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1609 PageStatePersister persister = this.PageStatePersister;
1610 if (persister == null)
1612 Pair pair = viewState as Pair;
1614 persister.ViewState = pair.First;
1615 persister.ControlState = pair.Second;
1617 persister.ViewState = viewState;
1621 internal string RawViewState {
1623 NameValueCollection postdata = _requestValueCollection;
1625 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1628 if (view_state == "")
1632 set { _savedViewState = value; }
1640 PageStatePersister PageStatePersister {
1642 if (page_state_persister == null)
1643 page_state_persister = new HiddenFieldPageStatePersister (this);
1644 return page_state_persister;
1648 [EditorBrowsable (EditorBrowsableState.Advanced)]
1649 protected virtual object LoadPageStateFromPersistenceMedium ()
1651 PageStatePersister persister = this.PageStatePersister;
1652 if (persister == null)
1655 return new Pair (persister.ViewState, persister.ControlState);
1658 internal void LoadPageViewState()
1660 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1661 if (sState != null) {
1664 LoadPageControlState (sState.Second);
1666 Pair vsr = sState.First as Pair;
1668 LoadViewStateRecursive (vsr.First);
1669 _requiresPostBackCopy = vsr.Second as ArrayList;
1675 internal void SavePageViewState ()
1677 if (!handleViewState)
1681 object controlState = SavePageControlState ();
1684 object viewState = SaveViewStateRecursive ();
1685 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1688 if (viewState != null || reqPostback != null)
1689 vsr = new Pair (viewState, reqPostback);
1690 Pair pair = new Pair ();
1694 pair.Second = controlState;
1698 if (pair.First == null && pair.Second == null)
1699 SavePageStateToPersistenceMedium (null);
1701 SavePageStateToPersistenceMedium (pair);
1705 public virtual void Validate ()
1707 is_validated = true;
1708 ValidateCollection (_validators);
1712 internal bool AreValidatorsUplevel () {
1713 return AreValidatorsUplevel (String.Empty);
1716 internal bool AreValidatorsUplevel (string valGroup)
1718 internal virtual bool AreValidatorsUplevel ()
1721 bool uplevel = false;
1723 foreach (IValidator v in Validators) {
1724 BaseValidator bv = v as BaseValidator;
1725 if (bv == null) continue;
1728 if (valGroup != bv.ValidationGroup)
1731 if (bv.GetRenderUplevel()) {
1740 bool ValidateCollection (ValidatorCollection validators)
1743 if (!_eventValidation)
1747 if (validators == null || validators.Count == 0)
1750 bool all_valid = true;
1751 foreach (IValidator v in validators){
1753 if (v.IsValid == false)
1760 [EditorBrowsable (EditorBrowsableState.Advanced)]
1761 public virtual void VerifyRenderingInServerForm (Control control)
1763 if (_context == null)
1770 throw new HttpException ("Control '" +
1773 control.GetType ().Name +
1774 "' must be placed inside a form tag with runat=server.");
1777 protected override void FrameworkInitialize ()
1779 base.FrameworkInitialize ();
1781 InitializeStyleSheet ();
1792 ClientScriptManager ClientScript {
1793 get { return scriptManager; }
1798 static readonly object InitCompleteEvent = new object ();
1799 static readonly object LoadCompleteEvent = new object ();
1800 static readonly object PreInitEvent = new object ();
1801 static readonly object PreLoadEvent = new object ();
1802 static readonly object PreRenderCompleteEvent = new object ();
1803 static readonly object SaveStateCompleteEvent = new object ();
1805 const int initcomplete_mask = 1;
1806 const int loadcomplete_mask = 1 << 1;
1807 const int preinit_mask = 1 << 2;
1808 const int preload_mask = 1 << 3;
1809 const int prerendercomplete_mask = 1 << 4;
1810 const int savestatecomplete_mask = 1 << 5;
1812 [EditorBrowsable (EditorBrowsableState.Advanced)]
1813 public event EventHandler InitComplete {
1815 event_mask |= initcomplete_mask;
1816 Events.AddHandler (InitCompleteEvent, value);
1818 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1821 [EditorBrowsable (EditorBrowsableState.Advanced)]
1822 public event EventHandler LoadComplete {
1824 event_mask |= loadcomplete_mask;
1825 Events.AddHandler (LoadCompleteEvent, value);
1827 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1830 public event EventHandler PreInit {
1832 event_mask |= preinit_mask;
1833 Events.AddHandler (PreInitEvent, value);
1835 remove { Events.RemoveHandler (PreInitEvent, value); }
1838 [EditorBrowsable (EditorBrowsableState.Advanced)]
1839 public event EventHandler PreLoad {
1841 event_mask |= preload_mask;
1842 Events.AddHandler (PreLoadEvent, value);
1844 remove { Events.RemoveHandler (PreLoadEvent, value); }
1847 [EditorBrowsable (EditorBrowsableState.Advanced)]
1848 public event EventHandler PreRenderComplete {
1850 event_mask |= prerendercomplete_mask;
1851 Events.AddHandler (PreRenderCompleteEvent, value);
1853 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1856 [EditorBrowsable (EditorBrowsableState.Advanced)]
1857 public event EventHandler SaveStateComplete {
1859 event_mask |= savestatecomplete_mask;
1860 Events.AddHandler (SaveStateCompleteEvent, value);
1862 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1865 protected virtual void OnInitComplete (EventArgs e)
1867 if ((event_mask & initcomplete_mask) != 0) {
1868 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1869 if (eh != null) eh (this, e);
1873 protected virtual void OnLoadComplete (EventArgs e)
1875 if ((event_mask & loadcomplete_mask) != 0) {
1876 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1877 if (eh != null) eh (this, e);
1881 protected virtual void OnPreInit (EventArgs e)
1883 if ((event_mask & preinit_mask) != 0) {
1884 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1885 if (eh != null) eh (this, e);
1889 protected virtual void OnPreLoad (EventArgs e)
1891 if ((event_mask & preload_mask) != 0) {
1892 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1893 if (eh != null) eh (this, e);
1897 protected virtual void OnPreRenderComplete (EventArgs e)
1899 if ((event_mask & prerendercomplete_mask) != 0) {
1900 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1901 if (eh != null) eh (this, e);
1906 if (!Form.DetermineRenderUplevel ())
1909 /* figure out if we have some control we're going to focus */
1910 if (String.IsNullOrEmpty (_focusedControlID)) {
1911 _focusedControlID = Form.DefaultFocus;
1912 if (String.IsNullOrEmpty (_focusedControlID))
1913 _focusedControlID = Form.DefaultButton;
1916 if (!String.IsNullOrEmpty (_focusedControlID)) {
1917 ClientScript.RegisterWebFormClientScript ();
1918 ClientScript.RegisterStartupScript ("HtmlForm-DefaultButton-StartupScript",
1919 String.Format ("<script type=\"text/javascript\">\n" +
1921 "WebForm_AutoFocus('{0}');// -->\n" +
1922 "</script>\n", _focusedControlID));
1925 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
1926 ClientScript.RegisterWebFormClientScript ();
1927 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1928 "WebForm_ReEnableControls(this);");
1932 internal void RegisterEnabledControl (Control control)
1934 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
1936 _hasEnabledControlArray = true;
1937 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Format ("'{0}'", control.ClientID));
1940 protected virtual void OnSaveStateComplete (EventArgs e)
1942 if ((event_mask & savestatecomplete_mask) != 0) {
1943 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1944 if (eh != null) eh (this, e);
1948 public HtmlForm Form {
1949 get { return _form; }
1952 internal void RegisterForm (HtmlForm form)
1957 [BrowsableAttribute (false)]
1958 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1959 public Page PreviousPage {
1961 if (_doLoadPreviousPage) {
1962 _doLoadPreviousPage = false;
1963 LoadPreviousPageReference ();
1965 return previousPage;
1970 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1971 [BrowsableAttribute (false)]
1972 public bool IsCallback {
1973 get { return isCallback; }
1976 [BrowsableAttribute (false)]
1977 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1978 public bool IsCrossPagePostBack {
1979 get { return isCrossPagePostBack; }
1982 public new virtual char IdSeparator {
1984 //TODO: why override?
1985 return base.IdSeparator;
1989 string ProcessCallbackData ()
1991 string callbackTarget = _requestValueCollection [CallbackSourceID];
1992 if (callbackTarget == null || callbackTarget.Length == 0)
1993 throw new HttpException ("Callback target not provided.");
1995 Control targetControl = FindControl (callbackTarget);
1996 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
1998 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2000 string callbackEventError = String.Empty;
2001 string callBackResult;
2002 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2005 target.RaiseCallbackEvent (callbackArgument);
2007 catch (Exception ex) {
2008 callbackEventError = String.Format ("e{0}", ex.Message);
2012 callBackResult = target.GetCallbackResult ();
2014 catch (Exception ex) {
2015 return String.Format ("e{0}", ex.Message);
2018 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2019 return String.Format ("{0}{1}|{2}{3}", callbackEventError, eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
2022 [BrowsableAttribute (false)]
2023 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2024 public HtmlHead Header {
2025 get { return htmlHeader; }
2028 internal void SetHeader (HtmlHead header)
2030 htmlHeader = header;
2031 if (_title != null) {
2032 htmlHeader.Title = _title;
2037 protected bool AsyncMode {
2038 get { return asyncMode; }
2039 set { asyncMode = value; }
2042 public TimeSpan AsyncTimeout {
2043 get { return asyncTimeout; }
2044 set { asyncTimeout = value; }
2047 public bool IsAsync {
2048 get { return AsyncMode; }
2051 [MonoTODO ("Not Implemented")]
2052 protected internal virtual string UniqueFilePathSuffix {
2054 throw new NotImplementedException ();
2058 [MonoTODO ("Not Implemented")]
2059 public int MaxPageStateFieldLength {
2061 throw new NotImplementedException ();
2064 throw new NotImplementedException ();
2068 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2070 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2073 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2076 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2079 if (_lifeCycle >= PageLifeCycle.PreRender) {
2080 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
2083 if (beginHandler == null) {
2084 throw new ArgumentNullException ("beginHandler");
2087 if (endHandler == null) {
2088 throw new ArgumentNullException ("endHandler");
2091 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2094 private List<PageAsyncTask> ParallelTasks {
2097 if (parallelTasks == null) {
2098 parallelTasks = new List<PageAsyncTask>();
2100 return parallelTasks;
2104 private List<PageAsyncTask> SerialTasks {
2106 if (serialTasks == null) {
2107 serialTasks = new List<PageAsyncTask> ();
2113 public void RegisterAsyncTask (PageAsyncTask task)
2116 throw new ArgumentNullException ("task");
2119 if (task.ExecuteInParallel) {
2120 ParallelTasks.Add (task);
2123 SerialTasks.Add (task);
2127 public void ExecuteRegisteredAsyncTasks ()
2129 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2130 (serialTasks == null || serialTasks.Count == 0)){
2134 if (parallelTasks != null) {
2135 DateTime startExecution = DateTime.Now;
2136 List<PageAsyncTask> localParallelTasks = parallelTasks;
2137 parallelTasks = null; // Shouldn't execute tasks twice
2138 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2139 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2140 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2141 if (result.CompletedSynchronously) {
2142 parallelTask.EndHandler (result);
2145 asyncResults.Add (result);
2149 if (asyncResults.Count > 0) {
2151 TimeSpan timeout = AsyncTimeout;
2152 long t1 = DateTime.Now.Ticks;
2153 bool signalled = true;
2154 for (int i = 0; i < asyncResults.Count; i++) {
2155 if (asyncResults [i].IsCompleted)
2159 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2162 long t2 = DateTime.Now.Ticks;
2163 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2164 if (timeout.Ticks <= 0)
2168 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2172 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2174 for (i = 0; i < asyncResults.Count; i++) {
2175 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2177 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2178 if (!allSignalled) {
2179 for (i = 0; i < asyncResults.Count; i++) {
2180 if (!asyncResults [i].IsCompleted) {
2181 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2187 DateTime endWait = DateTime.Now;
2188 TimeSpan elapsed = endWait - startExecution;
2189 if (elapsed <= AsyncTimeout) {
2190 AsyncTimeout -= elapsed;
2193 AsyncTimeout = TimeSpan.FromTicks(0);
2197 if (serialTasks != null) {
2198 List<PageAsyncTask> localSerialTasks = serialTasks;
2199 serialTasks = null; // Shouldn't execute tasks twice
2200 foreach (PageAsyncTask serialTask in localSerialTasks) {
2201 DateTime startExecution = DateTime.Now;
2203 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2204 if (result.CompletedSynchronously) {
2205 serialTask.EndHandler (result);
2208 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2209 if (!done && !result.IsCompleted) {
2210 serialTask.TimeoutHandler (result);
2213 DateTime endWait = DateTime.Now;
2214 TimeSpan elapsed = endWait - startExecution;
2215 if (elapsed <= AsyncTimeout) {
2216 AsyncTimeout -= elapsed;
2219 AsyncTimeout = TimeSpan.FromTicks (0);
2223 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2226 void EndAsyncTaskCallback (IAsyncResult result)
2228 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2229 task.EndHandler (result);
2232 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2234 Type htmlTextWriterType = typeof (HtmlTextWriter);
2236 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2237 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2240 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2241 if (constructor == null) {
2242 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2245 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2248 public ViewStateEncryptionMode ViewStateEncryptionMode {
2249 get { return viewStateEncryptionMode; }
2250 set { viewStateEncryptionMode = value; }
2253 public void RegisterRequiresViewStateEncryption ()
2255 controlRegisteredForViewStateEncryption = true;
2258 private static byte [] AES_IV = null;
2259 private static byte [] TripleDES_IV = null;
2260 private static object locker = new object ();
2261 private static bool isEncryptionInitialized = false;
2263 private static void InitializeEncryption ()
2265 if (isEncryptionInitialized) {
2270 if (isEncryptionInitialized) {
2274 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2275 AES_IV = new byte [16];
2276 TripleDES_IV = new byte [8];
2279 for (i = 0; i < AES_IV.Length; i++) {
2280 AES_IV [i] = (byte) iv_string [i];
2283 for (i = 0; i < TripleDES_IV.Length; i++) {
2284 TripleDES_IV [i] = (byte) iv_string [i];
2287 isEncryptionInitialized = true;
2291 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2293 ICryptoTransform transform = null;
2294 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2295 byte [] vk = config.ValidationKeyBytes;
2297 switch (config.Validation) {
2298 case MachineKeyValidation.SHA1:
2299 transform = SHA1.Create ();
2302 case MachineKeyValidation.MD5:
2303 transform = MD5.Create ();
2306 case MachineKeyValidation.AES:
2307 if (cryptoStreamMode == CryptoStreamMode.Read){
2308 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2310 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2314 case MachineKeyValidation.TripleDES:
2315 if (cryptoStreamMode == CryptoStreamMode.Read){
2316 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2318 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2326 internal bool NeedViewStateEncryption {
2328 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2329 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2330 controlRegisteredForViewStateEncryption));
2335 void ApplyMasterPage ()
2337 if (masterPageFile != null && masterPageFile.Length > 0) {
2338 ArrayList appliedMasterPageFiles = new ArrayList ();
2340 if (Master != null) {
2341 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2345 Controls.Add (Master);
2350 [DefaultValueAttribute ("")]
2351 public virtual string MasterPageFile {
2352 get { return masterPageFile; }
2354 masterPageFile = value;
2359 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2360 [BrowsableAttribute (false)]
2361 public MasterPage Master {
2363 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2366 if (masterPage == null)
2367 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2373 public void SetFocus (string clientID)
2375 if (String.IsNullOrEmpty (clientID))
2376 throw new ArgumentNullException ("control");
2378 if (_lifeCycle > PageLifeCycle.PreRender)
2379 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2382 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2384 _focusedControlID = clientID;
2387 public void SetFocus (Control control)
2389 if (control == null)
2390 throw new ArgumentNullException ("control");
2392 SetFocus (control.ClientID);
2395 [EditorBrowsable (EditorBrowsableState.Advanced)]
2396 public void RegisterRequiresControlState (Control control)
2398 if (control == null)
2399 throw new ArgumentNullException ("control");
2401 if (RequiresControlState (control))
2404 if (requireStateControls == null)
2405 requireStateControls = new ArrayList ();
2406 int n = requireStateControls.Add (control);
2408 if (_savedControlState == null || n >= _savedControlState.Length)
2411 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2412 if (parent.IsChildControlStateCleared)
2415 object state = _savedControlState [n];
2417 control.LoadControlState (state);
2420 public bool RequiresControlState (Control control)
2422 if (requireStateControls == null) return false;
2423 return requireStateControls.Contains (control);
2426 [EditorBrowsable (EditorBrowsableState.Advanced)]
2427 public void UnregisterRequiresControlState (Control control)
2429 if (requireStateControls != null)
2430 requireStateControls.Remove (control);
2433 public ValidatorCollection GetValidators (string validationGroup)
2435 string valgr = validationGroup;
2437 valgr = String.Empty;
2439 if (_validatorsByGroup == null) _validatorsByGroup = new Hashtable ();
2440 ValidatorCollection col = _validatorsByGroup [valgr] as ValidatorCollection;
2442 col = new ValidatorCollection ();
2443 _validatorsByGroup [valgr] = col;
2448 public virtual void Validate (string validationGroup)
2450 is_validated = true;
2451 if (validationGroup == null)
2452 ValidateCollection (_validatorsByGroup [String.Empty] as ValidatorCollection);
2453 else if (_validatorsByGroup != null) {
2454 ValidateCollection (_validatorsByGroup [validationGroup] as ValidatorCollection);
2458 object SavePageControlState ()
2460 if (requireStateControls == null) return null;
2461 object[] state = new object [requireStateControls.Count];
2463 bool allNull = true;
2464 for (int n=0; n<state.Length; n++) {
2465 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2466 if (state [n] != null) allNull = false;
2468 if (allNull) return null;
2472 void LoadPageControlState (object data)
2474 _savedControlState = (object []) data;
2476 if (requireStateControls == null) return;
2478 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2479 for (int n=0; n < max; n++) {
2480 Control ctl = (Control) requireStateControls [n];
2481 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2485 void LoadPreviousPageReference ()
2487 if (_requestValueCollection != null) {
2488 string prevPage = _requestValueCollection [PreviousPageID];
2489 if (prevPage != null) {
2490 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2491 previousPage.ProcessCrossPagePostBack (_context);
2497 Hashtable contentTemplates;
2498 [EditorBrowsable (EditorBrowsableState.Never)]
2499 protected internal void AddContentTemplate (string templateName, ITemplate template)
2501 if (contentTemplates == null)
2502 contentTemplates = new Hashtable ();
2503 contentTemplates [templateName] = template;
2506 PageTheme _pageTheme;
2507 internal PageTheme PageTheme {
2508 get { return _pageTheme; }
2511 PageTheme _styleSheetPageTheme;
2512 internal PageTheme StyleSheetPageTheme {
2513 get { return _styleSheetPageTheme; }
2518 internal void PushDataItemContext (object o) {
2519 if (dataItemCtx == null)
2520 dataItemCtx = new Stack ();
2522 dataItemCtx.Push (o);
2525 internal void PopDataItemContext () {
2526 if (dataItemCtx == null)
2527 throw new InvalidOperationException ();
2532 public object GetDataItem() {
2533 if (dataItemCtx == null || dataItemCtx.Count == 0)
2534 throw new InvalidOperationException ("No data item");
2536 return dataItemCtx.Peek ();
2539 protected internal override void OnInit (EventArgs e)
2543 ArrayList themes = new ArrayList();
2545 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2546 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2547 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2548 themes.AddRange (PageTheme.GetStyleSheets ());
2550 if (themes.Count > 0 && Header == null)
2551 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2553 foreach (string lss in themes) {
2554 HtmlLink hl = new HtmlLink ();
2555 hl.Href = ResolveUrl (lss);
2556 hl.Attributes["type"] = "text/css";
2557 hl.Attributes["rel"] = "stylesheet";
2558 Header.Controls.Add (hl);
2565 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2566 protected object GetWrappedFileDependencies (string [] list)
2571 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2572 protected virtual void InitializeCulture ()
2576 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2577 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)