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)
8 // Marek Habersack (mhabersack@novell.com)
10 // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
11 // Copyright (C) 2003-2008 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections;
35 using System.Collections.Specialized;
36 using System.ComponentModel;
37 using System.ComponentModel.Design;
38 using System.ComponentModel.Design.Serialization;
39 using System.Globalization;
41 using System.Security.Cryptography;
42 using System.Security.Permissions;
43 using System.Security.Principal;
45 using System.Threading;
47 using System.Web.Caching;
48 using System.Web.Configuration;
49 using System.Web.SessionState;
50 using System.Web.Util;
51 using System.Web.UI.HtmlControls;
52 using System.Web.UI.WebControls;
53 using System.Reflection;
55 using System.Web.Compilation;
56 using System.Web.UI.Adapters;
57 using System.Collections.Generic;
60 namespace System.Web.UI
63 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
64 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
66 [RootDesignerSerializer ("Microsoft.VSDesigner.WebForms.RootCodeDomSerializer, " + Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design, true)]
68 [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
71 [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
73 [Designer ("Microsoft.VSDesigner.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VSDesigner, typeof (IRootDesigner))]
75 public partial class Page : TemplateControl, IHttpHandler
78 static string machineKeyConfigPath = "system.web/machineKey";
79 private bool _eventValidation = true;
80 private object [] _savedControlState;
81 private bool _doLoadPreviousPage;
82 string _focusedControlID;
83 bool _hasEnabledControlArray;
85 private bool _viewState = true;
86 private bool _viewStateMac;
87 private string _errorPage;
88 private bool is_validated;
89 private bool _smartNavigation;
90 private int _transactionMode;
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 IPostBackEventHandler formPostedRequiresRaiseEvent;
99 private NameValueCollection secondPostData;
100 private bool requiresPostBackScript;
101 private bool postBackScriptRendered;
102 bool handleViewState;
103 string viewStateUserKey;
104 NameValueCollection _requestValueCollection;
106 ClientScriptManager scriptManager;
107 bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
108 PageStatePersister page_state_persister;
109 CultureInfo _appCulture;
110 CultureInfo _appUICulture;
112 // The initial context
113 private HttpContext _context;
115 // cached from the initial context
116 HttpApplicationState _application;
117 HttpResponse _response;
118 HttpRequest _request;
121 HttpSessionState _session;
123 [EditorBrowsable (EditorBrowsableState.Never)]
129 const string postEventArgumentID = "__EVENTARGUMENT";
131 [EditorBrowsable (EditorBrowsableState.Never)]
137 const string postEventSourceID = "__EVENTTARGET";
140 const string ScrollPositionXID = "__SCROLLPOSITIONX";
141 const string ScrollPositionYID = "__SCROLLPOSITIONY";
142 const string EnabledControlArrayID = "__enabledControlArray";
146 internal const string LastFocusID = "__LASTFOCUS";
147 internal const string CallbackArgumentID = "__CALLBACKARGUMENT";
148 internal const string CallbackSourceID = "__CALLBACKTARGET";
149 internal const string PreviousPageID = "__PREVIOUSPAGE";
153 MasterPage masterPage;
154 string masterPageFile;
157 bool isCrossPagePostBack;
160 ArrayList requireStateControls;
165 string _styleSheetTheme;
168 bool _maintainScrollPositionOnPostBack;
170 private bool asyncMode = false;
171 private TimeSpan asyncTimeout;
172 private const double DefaultAsyncTimeout = 45.0;
173 private List<PageAsyncTask> parallelTasks;
174 private List<PageAsyncTask> serialTasks;
176 private ViewStateEncryptionMode viewStateEncryptionMode;
177 private bool controlRegisteredForViewStateEncryption = false;
183 scriptManager = new ClientScriptManager (this);
188 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
190 asyncTimeout = ps.AsyncTimeout;
191 viewStateEncryptionMode = ps.ViewStateEncryptionMode;
193 asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
194 viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
203 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
205 public HttpApplicationState Application {
206 get { return _application; }
209 [EditorBrowsable (EditorBrowsableState.Never)]
210 protected bool AspCompatMode {
212 get { return false; }
214 set { throw new NotImplementedException (); }
217 [EditorBrowsable (EditorBrowsableState.Never)]
219 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
220 [BrowsableAttribute (false)]
222 get { return Response.BufferOutput; }
223 set { Response.BufferOutput = value; }
226 protected bool Buffer {
227 set { Response.BufferOutput = value; }
231 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
236 throw new HttpException ("Cache is not available.");
242 [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
244 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
245 [Browsable (false), DefaultValue ("")]
246 [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
247 public string ClientTarget {
248 get { return (clientTarget == null) ? "" : clientTarget; }
250 clientTarget = value;
256 [EditorBrowsable (EditorBrowsableState.Never)]
258 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
259 [BrowsableAttribute (false)]
260 public int CodePage {
261 get { return Response.ContentEncoding.CodePage; }
262 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
265 protected int CodePage {
266 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
270 [EditorBrowsable (EditorBrowsableState.Never)]
272 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
273 [BrowsableAttribute (false)]
274 public string ContentType {
275 get { return Response.ContentType; }
276 set { Response.ContentType = value; }
279 protected string ContentType {
280 set { Response.ContentType = value; }
289 override HttpContext Context {
291 if (_context == null)
292 return HttpContext.Current;
299 [EditorBrowsable (EditorBrowsableState.Advanced)]
300 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
301 [BrowsableAttribute (false)]
302 public string Culture {
303 get { return Thread.CurrentThread.CurrentCulture.Name; }
304 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
307 [EditorBrowsable (EditorBrowsableState.Never)]
308 protected string Culture {
309 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
314 public virtual bool EnableEventValidation {
315 get { return _eventValidation; }
318 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
319 _eventValidation = value;
325 public override bool EnableViewState {
326 get { return _viewState; }
327 set { _viewState = value; }
331 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
332 [BrowsableAttribute (false)]
334 [EditorBrowsable (EditorBrowsableState.Never)]
340 bool EnableViewStateMac {
341 get { return _viewStateMac; }
342 set { _viewStateMac = value; }
346 internal bool EnableViewStateMacInternal {
347 get { return _viewStateMac; }
348 set { _viewStateMac = value; }
352 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
353 [Browsable (false), DefaultValue ("")]
354 [WebSysDescription ("The URL of a page used for error redirection.")]
355 public string ErrorPage {
356 get { return _errorPage; }
358 HttpContext ctx = Context;
362 ctx.ErrorPage = value;
369 [EditorBrowsable (EditorBrowsableState.Never)]
370 protected ArrayList FileDependencies {
372 if (Response != null)
373 Response.AddFileDependencies (value);
379 [EditorBrowsable (EditorBrowsableState.Never)]
381 public override string ID {
382 get { return base.ID; }
383 set { base.ID = value; }
386 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
388 public bool IsPostBack {
393 return _requestValueCollection != null;
398 [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
399 public bool IsReusable {
400 get { return false; }
403 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
405 public bool IsValid {
408 throw new HttpException (Locale.GetText ("Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate."));
411 foreach (IValidator val in Validators)
416 return ValidateCollection (_validators);
421 public IDictionary Items {
424 items = new Hashtable ();
430 [EditorBrowsable (EditorBrowsableState.Never)]
432 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
433 [BrowsableAttribute (false)]
435 get { return Thread.CurrentThread.CurrentCulture.LCID; }
436 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
440 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
446 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
447 public bool MaintainScrollPositionOnPostBack {
448 get { return _maintainScrollPositionOnPostBack; }
449 set { _maintainScrollPositionOnPostBack = value; }
454 public PageAdapter PageAdapter {
456 return Adapter as PageAdapter;
460 string _validationStartupScript;
461 string _validationOnSubmitStatement;
462 string _validationInitializeScript;
463 string _webFormScriptReference;
465 internal string WebFormScriptReference {
467 if (_webFormScriptReference == null)
468 _webFormScriptReference = IsMultiForm ? theForm : "window";
469 return _webFormScriptReference;
473 internal string ValidationStartupScript {
475 if (_validationStartupScript == null) {
476 _validationStartupScript =
478 " + WebFormScriptReference + @".Page_ValidationActive = false;
479 " + WebFormScriptReference + @".ValidatorOnLoad();
480 " + WebFormScriptReference + @".ValidatorOnSubmit = function () {
481 if (this.Page_ValidationActive) {
482 return this.ValidatorCommonOnSubmit();
488 return _validationStartupScript;
492 internal string ValidationOnSubmitStatement {
494 if (_validationOnSubmitStatement == null)
495 _validationOnSubmitStatement = "if (!" + WebFormScriptReference + ".ValidatorOnSubmit()) return false;";
496 return _validationOnSubmitStatement;
500 internal string ValidationInitializeScript {
502 if (_validationInitializeScript == null)
503 _validationInitializeScript = "WebFormValidation_Initialize(" + WebFormScriptReference + ");";
504 return _validationInitializeScript;
508 internal IScriptManager ScriptManager {
509 get { return (IScriptManager) Items [typeof (IScriptManager)]; }
515 internal string theForm {
521 internal bool IsMultiForm {
522 get { return false; }
526 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
528 public HttpRequest Request {
530 if (_request == null)
531 throw new HttpException("Request is not available in this context.");
536 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
538 public HttpResponse Response {
540 if (_response == null)
541 throw new HttpException ("Response is not available in this context.");
546 [EditorBrowsable (EditorBrowsableState.Never)]
548 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
549 [BrowsableAttribute (false)]
550 public string ResponseEncoding {
551 get { return Response.ContentEncoding.WebName; }
552 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
555 protected string ResponseEncoding {
556 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
560 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
562 public HttpServerUtility Server {
563 get { return Context.Server; }
566 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
568 public virtual HttpSessionState Session {
570 if (_session != null)
574 _session = Context.Session;
576 // ignore, should not throw
579 if (_session == null)
580 throw new HttpException ("Session state can only be used " +
581 "when enableSessionState is set to true, either " +
582 "in a configuration file or in the Page directive.");
589 [FilterableAttribute (false)]
593 public bool SmartNavigation {
594 get { return _smartNavigation; }
595 set { _smartNavigation = value; }
599 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
602 public virtual string StyleSheetTheme {
603 get { return _styleSheetTheme; }
604 set { _styleSheetTheme = value; }
608 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
609 public virtual string Theme {
610 get { return _theme; }
611 set { _theme = value; }
614 void InitializeStyleSheet ()
616 if (_styleSheetTheme == null) {
617 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
619 _styleSheetTheme = ps.StyleSheetTheme;
622 if (_styleSheetTheme != null && _styleSheetTheme != "")
623 _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, Context);
625 if (!String.IsNullOrEmpty (_styleSheetTheme)) {
626 string virtualPath = "~/App_Themes/" + _styleSheetTheme;
627 _styleSheetPageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
632 void InitializeTheme ()
634 if (_theme == null) {
635 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
640 if (_theme != null && _theme != "") {
641 _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, Context);
642 _pageTheme.SetPage (this);
645 if (!String.IsNullOrEmpty (_theme)) {
646 string virtualPath = "~/App_Themes/" + _theme;
647 _pageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
648 if (_pageTheme != null)
649 _pageTheme.SetPage (this);
659 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
660 public string Title {
662 if (_title == null) {
663 if (htmlHeader != null)
664 return htmlHeader.Title;
670 if (htmlHeader != null)
671 htmlHeader.Title = value;
678 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
680 public TraceContext Trace {
681 get { return Context.Trace; }
684 [EditorBrowsable (EditorBrowsableState.Never)]
686 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
687 [BrowsableAttribute (false)]
688 public bool TraceEnabled {
689 get { return Trace.IsEnabled; }
690 set { Trace.IsEnabled = value; }
693 protected bool TraceEnabled {
694 set { Trace.IsEnabled = value; }
698 [EditorBrowsable (EditorBrowsableState.Never)]
700 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
701 [BrowsableAttribute (false)]
702 public TraceMode TraceModeValue {
703 get { return Trace.TraceMode; }
704 set { Trace.TraceMode = value; }
707 protected TraceMode TraceModeValue {
708 set { Trace.TraceMode = value; }
712 [EditorBrowsable (EditorBrowsableState.Never)]
713 protected int TransactionMode {
715 get { return _transactionMode; }
717 set { _transactionMode = value; }
722 // This method is here just to remove the warning about "_transactionMode" not being
723 // used. We probably will use it internally at some point.
725 internal int GetTransactionMode ()
727 return _transactionMode;
732 [EditorBrowsable (EditorBrowsableState.Advanced)]
733 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
734 [BrowsableAttribute (false)]
735 public string UICulture {
736 get { return Thread.CurrentThread.CurrentUICulture.Name; }
737 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
740 [EditorBrowsable (EditorBrowsableState.Never)]
741 protected string UICulture {
742 set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
746 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
748 public IPrincipal User {
749 get { return Context.User; }
752 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
754 public ValidatorCollection Validators {
756 if (_validators == null)
757 _validators = new ValidatorCollection ();
762 [MonoTODO ("Use this when encrypting/decrypting ViewState")]
764 public string ViewStateUserKey {
765 get { return viewStateUserKey; }
766 set { viewStateUserKey = value; }
770 public override bool Visible {
771 get { return base.Visible; }
772 set { base.Visible = value; }
780 CultureInfo GetPageCulture (string culture, CultureInfo deflt)
784 CultureInfo ret = null;
785 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
787 if (!Context.IsServletRequest)
790 string[] languages = Request.UserLanguages;
792 if (languages != null && languages.Length > 0)
793 ret = CultureInfo.CreateSpecificCulture (languages[0]);
800 ret = CultureInfo.CreateSpecificCulture (culture);
806 [EditorBrowsable (EditorBrowsableState.Never)]
807 protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
811 throw new NotImplementedException ();
814 [EditorBrowsable (EditorBrowsableState.Never)]
815 protected void AspCompatEndProcessRequest (IAsyncResult result)
817 throw new NotImplementedException ();
820 [EditorBrowsable (EditorBrowsableState.Advanced)]
821 protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
824 if (Request.BrowserMightHaveSpecialWriter)
825 return Request.Browser.CreateHtmlTextWriter(tw);
828 return new HtmlTextWriter (tw);
831 [EditorBrowsable (EditorBrowsableState.Never)]
832 public void DesignerInitialize ()
834 InitRecursive (null);
837 [EditorBrowsable (EditorBrowsableState.Advanced)]
842 virtual NameValueCollection DeterminePostBackMode ()
844 // if request was transfered from other page such Transfer
845 if (_context.IsProcessingInclude)
848 HttpRequest req = Request;
852 NameValueCollection coll = null;
853 if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture)
855 || !_context.IsServletRequest
860 string query = Request.QueryStringRaw;
861 if (query == null || query.Length == 0)
864 coll = req.QueryString;
867 WebROCollection c = (WebROCollection) coll;
868 allow_load = !c.GotID;
870 c.ID = GetTypeHashCode ();
872 allow_load = (c.ID == GetTypeHashCode ());
874 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
877 if (getFacesContext () != null && _context.Handler != _context.CurrentHandler) {
878 // check if it is PreviousPage
879 string prevViewId = coll [PreviousPageID];
880 if (!String.IsNullOrEmpty (prevViewId)) {
881 string appPath = VirtualPathUtility.RemoveTrailingSlash (Request.ApplicationPath);
882 prevViewId = prevViewId.Substring (appPath.Length);
883 isCrossPagePostBack = String.Compare (prevViewId, getFacesContext ().getExternalContext ().getRequestPathInfo (), StringComparison.OrdinalIgnoreCase) == 0;
891 public override Control FindControl (string id) {
895 return base.FindControl (id);
899 Control FindControl (string id, bool decode) {
902 id = DecodeNamespace (id);
904 return FindControl (id);
910 [EditorBrowsable (EditorBrowsableState.Advanced)]
911 public string GetPostBackClientEvent (Control control, string argument)
913 return scriptManager.GetPostBackEventReference (control, argument);
919 [EditorBrowsable (EditorBrowsableState.Advanced)]
920 public string GetPostBackClientHyperlink (Control control, string argument)
922 return scriptManager.GetPostBackClientHyperlink (control, argument);
928 [EditorBrowsable (EditorBrowsableState.Advanced)]
929 public string GetPostBackEventReference (Control control)
931 return scriptManager.GetPostBackEventReference (control, "");
937 [EditorBrowsable (EditorBrowsableState.Advanced)]
938 public string GetPostBackEventReference (Control control, string argument)
940 return scriptManager.GetPostBackEventReference (control, argument);
943 internal void RequiresPostBackScript ()
946 if (requiresPostBackScript)
948 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
949 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
951 requiresPostBackScript = true;
954 [EditorBrowsable (EditorBrowsableState.Never)]
955 public virtual int GetTypeHashCode ()
961 [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
962 protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
964 if (cacheSettings.Enabled)
965 InitOutputCache(cacheSettings.Duration,
966 cacheSettings.VaryByContentEncoding,
967 cacheSettings.VaryByHeader,
968 cacheSettings.VaryByCustom,
969 cacheSettings.Location,
970 cacheSettings.VaryByParam);
975 [MonoTODO ("varyByContentEncoding is not currently used")]
978 void InitOutputCache(int duration,
979 string varyByContentEncoding,
982 OutputCacheLocation location,
985 HttpCachePolicy cache = Response.Cache;
986 bool set_vary = false;
987 HttpContext ctx = Context;
988 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
991 case OutputCacheLocation.Any:
992 cache.SetCacheability (HttpCacheability.Public);
993 cache.SetMaxAge (new TimeSpan (0, 0, duration));
994 cache.SetLastModified (timestamp);
997 case OutputCacheLocation.Client:
998 cache.SetCacheability (HttpCacheability.Private);
999 cache.SetMaxAge (new TimeSpan (0, 0, duration));
1000 cache.SetLastModified (timestamp);
1002 case OutputCacheLocation.Downstream:
1003 cache.SetCacheability (HttpCacheability.Public);
1004 cache.SetMaxAge (new TimeSpan (0, 0, duration));
1005 cache.SetLastModified (timestamp);
1007 case OutputCacheLocation.Server:
1008 cache.SetCacheability (HttpCacheability.Server);
1011 case OutputCacheLocation.None:
1016 if (varyByCustom != null)
1017 cache.SetVaryByCustom (varyByCustom);
1019 if (varyByParam != null && varyByParam.Length > 0) {
1020 string[] prms = varyByParam.Split (';');
1021 foreach (string p in prms)
1022 cache.VaryByParams [p.Trim ()] = true;
1023 cache.VaryByParams.IgnoreParams = false;
1025 cache.VaryByParams.IgnoreParams = true;
1028 if (varyByHeader != null && varyByHeader.Length > 0) {
1029 string[] hdrs = varyByHeader.Split (';');
1030 foreach (string h in hdrs)
1031 cache.VaryByHeaders [h.Trim ()] = true;
1034 if (PageAdapter != null)
1036 if (PageAdapter.CacheVaryByParams != null) {
1037 foreach (string p in PageAdapter.CacheVaryByParams)
1038 cache.VaryByParams [p] = true;
1040 if (PageAdapter.CacheVaryByHeaders != null) {
1041 foreach (string h in PageAdapter.CacheVaryByHeaders)
1042 cache.VaryByHeaders [h] = true;
1048 cache.Duration = duration;
1049 cache.SetExpires (timestamp.AddSeconds (duration));
1053 [EditorBrowsable (EditorBrowsableState.Never)]
1054 protected virtual void InitOutputCache (int duration,
1055 string varyByHeader,
1056 string varyByCustom,
1057 OutputCacheLocation location,
1060 InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
1066 [EditorBrowsable (EditorBrowsableState.Advanced)]
1068 public bool IsClientScriptBlockRegistered (string key)
1070 return scriptManager.IsClientScriptBlockRegistered (key);
1076 [EditorBrowsable (EditorBrowsableState.Advanced)]
1078 public bool IsStartupScriptRegistered (string key)
1080 return scriptManager.IsStartupScriptRegistered (key);
1083 public string MapPath (string virtualPath)
1085 return Request.MapPath (virtualPath);
1089 protected internal override void Render (HtmlTextWriter writer) {
1090 if (MaintainScrollPositionOnPostBack) {
1091 ClientScript.RegisterWebFormClientScript ();
1093 ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
1094 ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
1096 StringBuilder script = new StringBuilder ();
1097 script.AppendLine ("<script type=\"text/javascript\">");
1098 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
1099 script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
1100 script.AppendLine (theForm + ".submit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionSubmit(); }");
1101 script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
1102 script.AppendLine (theForm + ".onsubmit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionOnSubmit(); }");
1104 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
1105 script.AppendLine ("window.onload = function () { " + WebFormScriptReference + ".WebForm_RestoreScrollPosition (); };");
1107 script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
1108 script.AppendLine ("</script>");
1110 ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1113 if (bool.Parse (WebConfigurationManager.AppSettings [RenderBodyContentOnlyKey] ?? "false")) {
1114 for (Control c = this.Form; c != null; c = c.Parent) {
1115 HtmlGenericControl ch = (c as HtmlGenericControl);
1116 if (ch != null && ch.TagName == "body") {
1117 ch.RenderChildren (writer);
1123 base.Render (writer);
1127 private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1130 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
1131 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
1133 writer.WriteLine ();
1135 ClientScriptManager.WriteBeginScriptBlock (writer);
1138 RenderClientScriptFormDeclaration (writer, formUniqueID);
1141 writer.WriteLine (WebFormScriptReference + "._form = " + theForm + ";");
1142 writer.WriteLine (WebFormScriptReference + ".__doPostBack = function (eventTarget, eventArgument) {");
1143 writer.WriteLine ("\tif(" + theForm + ".onsubmit && " + theForm + ".onsubmit() == false) return;");
1145 writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
1146 writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
1148 writer.WriteLine ("\t" + theForm + "." + postEventSourceID + ".value = eventTarget;");
1149 writer.WriteLine ("\t" + theForm + "." + postEventArgumentID + ".value = eventArgument;");
1150 writer.WriteLine ("\t" + theForm + ".submit();");
1151 writer.WriteLine ("}");
1152 ClientScriptManager.WriteEndScriptBlock (writer);
1155 void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1158 if (PageAdapter != null) {
1159 writer.WriteLine ("\tvar {0} = {1};\n", theForm, PageAdapter.GetPostBackFormReference(formUniqueID));
1163 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1164 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1167 // TODO implement callback on portlet
1168 string serverUrl = Request.RawUrl;
1169 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1170 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1171 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1175 internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1178 throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1180 renderingForm = true;
1181 writer.WriteLine ();
1184 ClientScriptManager.WriteBeginScriptBlock (writer);
1185 RenderClientScriptFormDeclaration (writer, formUniqueID);
1186 ClientScriptManager.WriteEndScriptBlock (writer);
1189 if (handleViewState)
1191 if (getFacesContext () != null) {
1192 javax.faces.application.ViewHandler viewHandler = getFacesContext ().getApplication ().getViewHandler ();
1193 javax.faces.context.ResponseWriter oldFacesWriter = SetupResponseWriter (writer);
1195 viewHandler.writeState (getFacesContext ());
1198 getFacesContext ().setResponseWriter (oldFacesWriter);
1202 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1204 scriptManager.WriteHiddenFields (writer);
1205 if (requiresPostBackScript) {
1206 RenderPostBackScript (writer, formUniqueID);
1207 postBackScriptRendered = true;
1210 scriptManager.WriteWebFormClientScript (writer);
1212 scriptManager.WriteClientScriptBlocks (writer);
1215 internal IStateFormatter GetFormatter ()
1217 return new ObjectStateFormatter (this);
1220 internal string GetSavedViewState ()
1222 return _savedViewState;
1225 internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1228 scriptManager.SaveEventValidationState ();
1229 scriptManager.WriteExpandoAttributes (writer);
1231 scriptManager.WriteHiddenFields (writer);
1232 if (!postBackScriptRendered && requiresPostBackScript)
1233 RenderPostBackScript (writer, formUniqueID);
1235 scriptManager.WriteWebFormClientScript (writer);
1238 scriptManager.WriteArrayDeclares (writer);
1239 scriptManager.WriteStartupScriptBlocks (writer);
1240 renderingForm = false;
1241 postBackScriptRendered = false;
1244 private void ProcessPostData (NameValueCollection data, bool second)
1246 NameValueCollection requestValues = _requestValueCollection == null ?
1247 new NameValueCollection () :
1248 _requestValueCollection;
1250 if (data != null && data.Count > 0) {
1251 Hashtable used = new Hashtable ();
1252 foreach (string id in data.AllKeys){
1253 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID ||
1254 id == ClientScriptManager.EventStateFieldName)
1257 if (used.ContainsKey (id))
1262 Control ctrl = FindControl (id, true);
1264 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1265 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1269 formPostedRequiresRaiseEvent = pbeh;
1273 if (pbdh.LoadPostData (id, requestValues) == true) {
1274 if (requiresPostDataChanged == null)
1275 requiresPostDataChanged = new ArrayList ();
1276 requiresPostDataChanged.Add (pbdh);
1279 if (_requiresPostBackCopy != null)
1280 _requiresPostBackCopy.Remove (id);
1282 } else if (!second) {
1283 if (secondPostData == null)
1284 secondPostData = new NameValueCollection ();
1285 secondPostData.Add (id, data [id]);
1290 ArrayList list1 = null;
1291 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1292 string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1293 foreach (string id in handlers) {
1294 IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
1296 _requiresPostBackCopy.Remove (id);
1297 if (pbdh.LoadPostData (id, requestValues)) {
1298 if (requiresPostDataChanged == null)
1299 requiresPostDataChanged = new ArrayList ();
1301 requiresPostDataChanged.Add (pbdh);
1303 } else if (!second) {
1305 list1 = new ArrayList ();
1310 _requiresPostBackCopy = second ? null : list1;
1312 secondPostData = null;
1315 [EditorBrowsable (EditorBrowsableState.Never)]
1317 public virtual void ProcessRequest (HttpContext context)
1319 public void ProcessRequest (HttpContext context)
1322 SetContext (context);
1324 bool wasException = false;
1325 IHttpHandler jsfHandler = getFacesContext () != null ? EnterThread () : null;
1328 if (clientTarget != null)
1329 Request.ClientTarget = clientTarget;
1331 WireupAutomaticEvents ();
1332 //-- Control execution lifecycle in the docs
1334 // Save culture information because it can be modified in FrameworkInitialize()
1335 _appCulture = Thread.CurrentThread.CurrentCulture;
1336 _appUICulture = Thread.CurrentThread.CurrentUICulture;
1337 FrameworkInitialize ();
1338 context.ErrorPage = _errorPage;
1341 InternalProcessRequest ();
1343 } catch (Exception ex) {
1344 wasException = true;
1345 HandleException (ex);
1347 } catch (ThreadAbortException taex) {
1348 if (FlagEnd.Value == taex.ExceptionState)
1349 Thread.ResetAbort ();
1352 } catch (Exception e) {
1353 ProcessException (e);
1357 if (getFacesContext () != null)
1358 ExitThread (jsfHandler);
1359 else if (!wasException)
1365 void ProcessException (Exception e) {
1366 // We want to remove that error, as we're rethrowing to stop
1367 // further processing.
1368 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1369 _context.AddError (e); // OnError might access LastError
1370 OnError (EventArgs.Empty);
1371 if (_context.HasError (e)) {
1372 _context.ClearError (e);
1374 vmw.common.TypeUtils.Throw (e);
1376 throw new HttpUnhandledException (null, e);
1381 void ProcessUnload () {
1384 UnloadRecursive (true);
1387 if (getFacesContext () != null) {
1388 if(IsCrossPagePostBack)
1389 _context.Items [CrossPagePostBack] = this;
1392 if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
1393 Thread.CurrentThread.CurrentCulture = _appCulture;
1395 if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
1396 Thread.CurrentThread.CurrentUICulture = _appUICulture;
1399 _appUICulture = null;
1403 delegate void ProcessRequestDelegate (HttpContext context);
1405 private sealed class DummyAsyncResult : IAsyncResult
1407 readonly object state;
1408 readonly WaitHandle asyncWaitHandle;
1409 readonly bool completedSynchronously;
1410 readonly bool isCompleted;
1412 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
1414 this.isCompleted = isCompleted;
1415 this.completedSynchronously = completedSynchronously;
1418 asyncWaitHandle = new ManualResetEvent (true);
1421 asyncWaitHandle = new ManualResetEvent (false);
1425 #region IAsyncResult Members
1427 public object AsyncState {
1428 get { return state; }
1431 public WaitHandle AsyncWaitHandle {
1432 get { return asyncWaitHandle; }
1435 public bool CompletedSynchronously {
1436 get { return completedSynchronously; }
1439 public bool IsCompleted {
1440 get { return isCompleted; }
1446 protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
1448 ProcessRequest (context);
1449 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1451 if (callback != null) {
1452 callback (asyncResult);
1458 protected void AsyncPageEndProcessRequest (IAsyncResult result)
1463 void InternalProcessRequest ()
1466 if (PageAdapter != null) {
1467 _requestValueCollection = PageAdapter.DeterminePostBackMode();
1472 _requestValueCollection = this.DeterminePostBackMode();
1476 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1477 if (_requestValueCollection != null) {
1478 if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1479 _doLoadPreviousPage = true;
1482 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1483 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1484 //isPostBack = !isCallback;
1487 string lastFocus = _requestValueCollection [LastFocusID];
1488 if (!String.IsNullOrEmpty (lastFocus)) {
1489 _focusedControlID = UniqueID2ClientID (lastFocus);
1493 if (!isCrossPagePostBack) {
1494 if (_context.PreviousHandler is Page) {
1495 previousPage = (Page) _context.PreviousHandler;
1499 Trace.Write ("aspx.page", "Begin PreInit");
1500 OnPreInit (EventArgs.Empty);
1501 Trace.Write ("aspx.page", "End PreInit");
1506 Trace.Write ("aspx.page", "Begin Init");
1507 InitRecursive (null);
1508 Trace.Write ("aspx.page", "End Init");
1511 Trace.Write ("aspx.page", "Begin InitComplete");
1512 OnInitComplete (EventArgs.Empty);
1513 Trace.Write ("aspx.page", "End InitComplete");
1516 renderingForm = false;
1519 if (getFacesContext () != null)
1520 if (IsPostBack || IsCallback)
1524 RestorePageState ();
1526 ProcessRaiseEvents ();
1527 if (ProcessLoadComplete ())
1530 if (getFacesContext () != null) {
1531 getFacesContext ().renderResponse ();
1538 void RestorePageState () {
1540 if (IsPostBack || IsCallback) {
1541 if (_requestValueCollection != null)
1542 scriptManager.RestoreEventValidationState (
1543 _requestValueCollection [ClientScriptManager.EventStateFieldName]);
1547 Trace.Write ("aspx.page", "Begin LoadViewState");
1548 LoadPageViewState ();
1549 Trace.Write ("aspx.page", "End LoadViewState");
1553 void ProcessPostData () {
1556 if (IsPostBack || IsCallback) {
1560 Trace.Write ("aspx.page", "Begin ProcessPostData");
1561 ProcessPostData (_requestValueCollection, false);
1562 Trace.Write ("aspx.page", "End ProcessPostData");
1568 if (IsPostBack || IsCallback) {
1572 Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1573 ProcessPostData (secondPostData, true);
1574 Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1578 void ProcessLoad () {
1580 Trace.Write ("aspx.page", "Begin PreLoad");
1581 OnPreLoad (EventArgs.Empty);
1582 Trace.Write ("aspx.page", "End PreLoad");
1585 Trace.Write ("aspx.page", "Begin Load");
1587 Trace.Write ("aspx.page", "End Load");
1590 void ProcessRaiseEvents () {
1593 if (IsPostBack || IsCallback) {
1597 Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1598 RaiseChangedEvents ();
1599 Trace.Write ("aspx.page", "End Raise ChangedEvents");
1600 Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1601 RaisePostBackEvents ();
1602 Trace.Write ("aspx.page", "End Raise PostBackEvent");
1606 bool ProcessLoadComplete() {
1609 Trace.Write ("aspx.page", "Begin LoadComplete");
1610 OnLoadComplete (EventArgs.Empty);
1611 Trace.Write ("aspx.page", "End LoadComplete");
1613 if (IsCrossPagePostBack)
1618 if (getFacesContext () != null) {
1619 _callbackTarget = GetCallbackTarget ();
1620 ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError);
1624 string result = ProcessCallbackData ();
1625 HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1626 callbackOutput.Write (result);
1627 callbackOutput.Flush ();
1632 Trace.Write ("aspx.page", "Begin PreRender");
1633 PreRenderRecursiveInternal ();
1634 Trace.Write ("aspx.page", "End PreRender");
1637 ExecuteRegisteredAsyncTasks ();
1639 Trace.Write ("aspx.page", "Begin PreRenderComplete");
1640 OnPreRenderComplete (EventArgs.Empty);
1641 Trace.Write ("aspx.page", "End PreRenderComplete");
1644 Trace.Write ("aspx.page", "Begin SaveViewState");
1645 SavePageViewState ();
1646 Trace.Write ("aspx.page", "End SaveViewState");
1649 Trace.Write ("aspx.page", "Begin SaveStateComplete");
1650 OnSaveStateComplete (EventArgs.Empty);
1651 Trace.Write ("aspx.page", "End SaveStateComplete");
1656 internal void RenderPage () {
1658 scriptManager.ResetEventValidationState ();
1662 Trace.Write ("aspx.page", "Begin Render");
1663 HtmlTextWriter output = CreateHtmlTextWriter (Response.Output);
1664 RenderControl (output);
1665 Trace.Write ("aspx.page", "End Render");
1668 internal void SetContext (HttpContext context) {
1671 _application = context.Application;
1672 _response = context.Response;
1673 _request = context.Request;
1674 _cache = context.Cache;
1677 private void RenderTrace ()
1679 TraceManager traceManager = HttpRuntime.TraceManager;
1681 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1686 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
1689 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1690 HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1691 Trace.Render (output);
1696 bool CheckForValidationSupport (Control targetControl)
1698 if (targetControl == null)
1700 Type type = targetControl.GetType ();
1701 object[] attributes = type.GetCustomAttributes (false);
1702 foreach (object attr in attributes)
1703 if (attr is SupportsEventValidationAttribute)
1708 void RaisePostBackEvents ()
1711 Control targetControl;
1713 if (requiresRaiseEvent != null) {
1714 RaisePostBackEvent (requiresRaiseEvent, null);
1718 if (formPostedRequiresRaiseEvent != null) {
1719 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1723 NameValueCollection postdata = _requestValueCollection;
1724 if (postdata == null)
1727 string eventTarget = postdata [postEventSourceID];
1728 if (eventTarget == null || eventTarget.Length == 0) {
1729 if (formPostedRequiresRaiseEvent != null)
1730 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1737 targetControl = FindControl (eventTarget, true);
1738 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1740 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1746 string eventArgument = postdata [postEventArgumentID];
1747 RaisePostBackEvent (target, eventArgument);
1750 internal void RaiseChangedEvents ()
1752 if (requiresPostDataChanged == null)
1755 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1756 ipdh.RaisePostDataChangedEvent ();
1758 requiresPostDataChanged = null;
1761 [EditorBrowsable (EditorBrowsableState.Advanced)]
1762 protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1765 Control targetControl = sourceControl as Control;
1766 if (targetControl != null && CheckForValidationSupport (targetControl))
1767 scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1769 sourceControl.RaisePostBackEvent (eventArgument);
1775 [EditorBrowsable (EditorBrowsableState.Advanced)]
1776 public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1778 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1784 [EditorBrowsable (EditorBrowsableState.Advanced)]
1785 public virtual void RegisterClientScriptBlock (string key, string script)
1787 scriptManager.RegisterClientScriptBlock (key, script);
1793 [EditorBrowsable (EditorBrowsableState.Advanced)]
1794 public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1796 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1799 [MonoTODO("Not implemented, Used in HtmlForm")]
1800 internal void RegisterClientScriptFile (string a, string b, string c)
1802 throw new NotImplementedException ();
1808 [EditorBrowsable (EditorBrowsableState.Advanced)]
1809 public void RegisterOnSubmitStatement (string key, string script)
1811 scriptManager.RegisterOnSubmitStatement (key, script);
1814 internal string GetSubmitStatements ()
1816 return scriptManager.WriteSubmitStatements ();
1819 [EditorBrowsable (EditorBrowsableState.Advanced)]
1820 public void RegisterRequiresPostBack (Control control)
1823 if (!(control is IPostBackDataHandler))
1824 throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1827 if (_requiresPostBack == null)
1828 _requiresPostBack = new ArrayList ();
1830 if (_requiresPostBack.Contains (control.UniqueID))
1833 _requiresPostBack.Add (control.UniqueID);
1836 [EditorBrowsable (EditorBrowsableState.Advanced)]
1837 public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1839 requiresRaiseEvent = control;
1845 [EditorBrowsable (EditorBrowsableState.Advanced)]
1846 public virtual void RegisterStartupScript (string key, string script)
1848 scriptManager.RegisterStartupScript (key, script);
1851 [EditorBrowsable (EditorBrowsableState.Advanced)]
1852 public void RegisterViewStateHandler ()
1854 handleViewState = true;
1857 [EditorBrowsable (EditorBrowsableState.Advanced)]
1858 protected virtual void SavePageStateToPersistenceMedium (object viewState)
1860 PageStatePersister persister = this.PageStatePersister;
1861 if (persister == null)
1863 Pair pair = viewState as Pair;
1865 persister.ViewState = pair.First;
1866 persister.ControlState = pair.Second;
1868 persister.ViewState = viewState;
1872 internal string RawViewState {
1874 NameValueCollection postdata = _requestValueCollection;
1876 if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1879 if (view_state == "")
1883 set { _savedViewState = value; }
1891 PageStatePersister PageStatePersister {
1894 if (page_state_persister == null && PageAdapter != null)
1895 page_state_persister = PageAdapter.GetStatePersister();
1897 if (page_state_persister == null)
1898 page_state_persister = new HiddenFieldPageStatePersister (this);
1899 return page_state_persister;
1903 [EditorBrowsable (EditorBrowsableState.Advanced)]
1904 protected virtual object LoadPageStateFromPersistenceMedium ()
1906 PageStatePersister persister = this.PageStatePersister;
1907 if (persister == null)
1910 return new Pair (persister.ViewState, persister.ControlState);
1913 internal void LoadPageViewState()
1915 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1916 if (sState != null) {
1919 LoadPageControlState (sState.Second);
1921 Pair vsr = sState.First as Pair;
1923 LoadViewStateRecursive (vsr.First);
1924 _requiresPostBackCopy = vsr.Second as ArrayList;
1930 internal void SavePageViewState ()
1932 if (!handleViewState)
1936 object controlState = SavePageControlState ();
1939 object viewState = SaveViewStateRecursive ();
1940 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1943 if (viewState != null || reqPostback != null)
1944 vsr = new Pair (viewState, reqPostback);
1945 Pair pair = new Pair ();
1949 pair.Second = controlState;
1953 if (pair.First == null && pair.Second == null)
1954 SavePageStateToPersistenceMedium (null);
1956 SavePageStateToPersistenceMedium (pair);
1960 public virtual void Validate ()
1962 is_validated = true;
1963 ValidateCollection (_validators);
1967 internal bool AreValidatorsUplevel () {
1968 return AreValidatorsUplevel (String.Empty);
1971 internal bool AreValidatorsUplevel (string valGroup)
1973 internal virtual bool AreValidatorsUplevel ()
1976 bool uplevel = false;
1978 foreach (IValidator v in Validators) {
1979 BaseValidator bv = v as BaseValidator;
1980 if (bv == null) continue;
1983 if (valGroup != bv.ValidationGroup)
1986 if (bv.GetRenderUplevel()) {
1995 bool ValidateCollection (ValidatorCollection validators)
1997 if (validators == null || validators.Count == 0)
2000 bool all_valid = true;
2001 foreach (IValidator v in validators){
2003 if (v.IsValid == false)
2010 [EditorBrowsable (EditorBrowsableState.Advanced)]
2011 public virtual void VerifyRenderingInServerForm (Control control)
2013 if (Context == null)
2020 throw new HttpException ("Control '" +
2023 control.GetType ().Name +
2024 "' must be placed inside a form tag with runat=server.");
2027 protected override void FrameworkInitialize ()
2029 base.FrameworkInitialize ();
2031 InitializeStyleSheet ();
2042 ClientScriptManager ClientScript {
2043 get { return scriptManager; }
2047 internal static readonly object InitCompleteEvent = new object ();
2048 internal static readonly object LoadCompleteEvent = new object ();
2049 internal static readonly object PreInitEvent = new object ();
2050 internal static readonly object PreLoadEvent = new object ();
2051 internal static readonly object PreRenderCompleteEvent = new object ();
2052 internal static readonly object SaveStateCompleteEvent = new object ();
2054 const int initcomplete_mask = 1;
2055 const int loadcomplete_mask = 1 << 1;
2056 const int preinit_mask = 1 << 2;
2057 const int preload_mask = 1 << 3;
2058 const int prerendercomplete_mask = 1 << 4;
2059 const int savestatecomplete_mask = 1 << 5;
2061 [EditorBrowsable (EditorBrowsableState.Advanced)]
2062 public event EventHandler InitComplete {
2064 event_mask |= initcomplete_mask;
2065 Events.AddHandler (InitCompleteEvent, value);
2067 remove { Events.RemoveHandler (InitCompleteEvent, value); }
2070 [EditorBrowsable (EditorBrowsableState.Advanced)]
2071 public event EventHandler LoadComplete {
2073 event_mask |= loadcomplete_mask;
2074 Events.AddHandler (LoadCompleteEvent, value);
2076 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
2079 public event EventHandler PreInit {
2081 event_mask |= preinit_mask;
2082 Events.AddHandler (PreInitEvent, value);
2084 remove { Events.RemoveHandler (PreInitEvent, value); }
2087 [EditorBrowsable (EditorBrowsableState.Advanced)]
2088 public event EventHandler PreLoad {
2090 event_mask |= preload_mask;
2091 Events.AddHandler (PreLoadEvent, value);
2093 remove { Events.RemoveHandler (PreLoadEvent, value); }
2096 [EditorBrowsable (EditorBrowsableState.Advanced)]
2097 public event EventHandler PreRenderComplete {
2099 event_mask |= prerendercomplete_mask;
2100 Events.AddHandler (PreRenderCompleteEvent, value);
2102 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
2105 [EditorBrowsable (EditorBrowsableState.Advanced)]
2106 public event EventHandler SaveStateComplete {
2108 event_mask |= savestatecomplete_mask;
2109 Events.AddHandler (SaveStateCompleteEvent, value);
2111 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
2114 protected virtual void OnInitComplete (EventArgs e)
2116 if ((event_mask & initcomplete_mask) != 0) {
2117 EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
2118 if (eh != null) eh (this, e);
2122 protected virtual void OnLoadComplete (EventArgs e)
2124 if ((event_mask & loadcomplete_mask) != 0) {
2125 EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
2126 if (eh != null) eh (this, e);
2130 protected virtual void OnPreInit (EventArgs e)
2132 if ((event_mask & preinit_mask) != 0) {
2133 EventHandler eh = (EventHandler) (Events [PreInitEvent]);
2134 if (eh != null) eh (this, e);
2138 protected virtual void OnPreLoad (EventArgs e)
2140 if ((event_mask & preload_mask) != 0) {
2141 EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
2142 if (eh != null) eh (this, e);
2146 protected virtual void OnPreRenderComplete (EventArgs e)
2148 if ((event_mask & prerendercomplete_mask) != 0) {
2149 EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
2150 if (eh != null) eh (this, e);
2155 if (!Form.DetermineRenderUplevel ())
2158 string defaultButtonId = Form.DefaultButton;
2159 /* figure out if we have some control we're going to focus */
2160 if (String.IsNullOrEmpty (_focusedControlID)) {
2161 _focusedControlID = Form.DefaultFocus;
2162 if (String.IsNullOrEmpty (_focusedControlID))
2163 _focusedControlID = defaultButtonId;
2166 if (!String.IsNullOrEmpty (_focusedControlID)) {
2167 ClientScript.RegisterWebFormClientScript ();
2169 ClientScript.RegisterStartupScript (
2171 "HtmlForm-DefaultButton-StartupScript",
2172 "\n" + WebFormScriptReference + ".WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
2175 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
2176 ClientScript.RegisterWebFormClientScript ();
2178 ClientScript.RegisterOnSubmitStatement (
2180 "HtmlForm-SubmitDisabledControls-SubmitStatement",
2181 WebFormScriptReference + ".WebForm_ReEnableControls();");
2185 internal void RegisterEnabledControl (Control control)
2187 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
2189 _hasEnabledControlArray = true;
2190 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
2193 protected virtual void OnSaveStateComplete (EventArgs e)
2195 if ((event_mask & savestatecomplete_mask) != 0) {
2196 EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
2197 if (eh != null) eh (this, e);
2201 public HtmlForm Form {
2202 get { return _form; }
2205 internal void RegisterForm (HtmlForm form)
2210 public string ClientQueryString {
2211 get { return Request.UrlComponents.Query; }
2214 [BrowsableAttribute (false)]
2215 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2216 public Page PreviousPage {
2218 if (_doLoadPreviousPage) {
2219 _doLoadPreviousPage = false;
2220 LoadPreviousPageReference ();
2222 return previousPage;
2227 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2228 [BrowsableAttribute (false)]
2229 public bool IsCallback {
2230 get { return isCallback; }
2233 [BrowsableAttribute (false)]
2234 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2235 public bool IsCrossPagePostBack {
2236 get { return isCrossPagePostBack; }
2239 public new virtual char IdSeparator {
2241 //TODO: why override?
2242 return base.IdSeparator;
2246 string ProcessCallbackData ()
2248 ICallbackEventHandler target = GetCallbackTarget ();
2249 string callbackEventError = String.Empty;
2250 ProcessRaiseCallbackEvent (target, ref callbackEventError);
2251 return ProcessGetCallbackResult (target, callbackEventError);
2254 ICallbackEventHandler GetCallbackTarget () {
2255 string callbackTarget = _requestValueCollection [CallbackSourceID];
2256 if (callbackTarget == null || callbackTarget.Length == 0)
2257 throw new HttpException ("Callback target not provided.");
2259 Control targetControl = FindControl (callbackTarget, true);
2260 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2262 throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2266 void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError) {
2267 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2270 target.RaiseCallbackEvent (callbackArgument);
2271 } catch (Exception ex) {
2272 callbackEventError = String.Concat ("e", ex.Message);
2277 string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError) {
2278 string callBackResult;
2280 callBackResult = target.GetCallbackResult ();
2281 } catch (Exception ex) {
2282 return String.Concat ("e", ex.Message);
2285 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2286 return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
2287 eventValidation + callBackResult;
2290 [BrowsableAttribute (false)]
2291 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2292 public HtmlHead Header {
2293 get { return htmlHeader; }
2296 internal void SetHeader (HtmlHead header)
2298 htmlHeader = header;
2299 if (_title != null) {
2300 htmlHeader.Title = _title;
2305 protected bool AsyncMode {
2306 get { return asyncMode; }
2307 set { asyncMode = value; }
2310 public TimeSpan AsyncTimeout {
2311 get { return asyncTimeout; }
2312 set { asyncTimeout = value; }
2315 public bool IsAsync {
2316 get { return AsyncMode; }
2319 [MonoTODO ("Not Implemented")]
2320 protected internal virtual string UniqueFilePathSuffix {
2322 throw new NotImplementedException ();
2326 [MonoTODO ("Not Implemented")]
2327 public int MaxPageStateFieldLength {
2329 throw new NotImplementedException ();
2332 throw new NotImplementedException ();
2336 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2338 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2341 public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2344 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2347 if (IsPrerendered) {
2348 throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
2351 if (beginHandler == null) {
2352 throw new ArgumentNullException ("beginHandler");
2355 if (endHandler == null) {
2356 throw new ArgumentNullException ("endHandler");
2359 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2362 private List<PageAsyncTask> ParallelTasks {
2364 if (parallelTasks == null) {
2365 parallelTasks = new List<PageAsyncTask>();
2367 return parallelTasks;
2371 private List<PageAsyncTask> SerialTasks {
2373 if (serialTasks == null) {
2374 serialTasks = new List<PageAsyncTask> ();
2380 public void RegisterAsyncTask (PageAsyncTask task)
2383 throw new ArgumentNullException ("task");
2386 if (task.ExecuteInParallel) {
2387 ParallelTasks.Add (task);
2390 SerialTasks.Add (task);
2394 public void ExecuteRegisteredAsyncTasks ()
2396 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2397 (serialTasks == null || serialTasks.Count == 0)){
2401 if (parallelTasks != null) {
2402 DateTime startExecution = DateTime.Now;
2403 List<PageAsyncTask> localParallelTasks = parallelTasks;
2404 parallelTasks = null; // Shouldn't execute tasks twice
2405 List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2406 foreach (PageAsyncTask parallelTask in localParallelTasks) {
2407 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2408 if (result.CompletedSynchronously) {
2409 parallelTask.EndHandler (result);
2412 asyncResults.Add (result);
2416 if (asyncResults.Count > 0) {
2418 TimeSpan timeout = AsyncTimeout;
2419 long t1 = DateTime.Now.Ticks;
2420 bool signalled = true;
2421 for (int i = 0; i < asyncResults.Count; i++) {
2422 if (asyncResults [i].IsCompleted)
2426 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2429 long t2 = DateTime.Now.Ticks;
2430 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2431 if (timeout.Ticks <= 0)
2435 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2439 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2441 for (i = 0; i < asyncResults.Count; i++) {
2442 waitArray [i] = asyncResults [i].AsyncWaitHandle;
2444 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2445 if (!allSignalled) {
2446 for (i = 0; i < asyncResults.Count; i++) {
2447 if (!asyncResults [i].IsCompleted) {
2448 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2454 DateTime endWait = DateTime.Now;
2455 TimeSpan elapsed = endWait - startExecution;
2456 if (elapsed <= AsyncTimeout) {
2457 AsyncTimeout -= elapsed;
2460 AsyncTimeout = TimeSpan.FromTicks(0);
2464 if (serialTasks != null) {
2465 List<PageAsyncTask> localSerialTasks = serialTasks;
2466 serialTasks = null; // Shouldn't execute tasks twice
2467 foreach (PageAsyncTask serialTask in localSerialTasks) {
2468 DateTime startExecution = DateTime.Now;
2470 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2471 if (result.CompletedSynchronously) {
2472 serialTask.EndHandler (result);
2475 bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2476 if (!done && !result.IsCompleted) {
2477 serialTask.TimeoutHandler (result);
2480 DateTime endWait = DateTime.Now;
2481 TimeSpan elapsed = endWait - startExecution;
2482 if (elapsed <= AsyncTimeout) {
2483 AsyncTimeout -= elapsed;
2486 AsyncTimeout = TimeSpan.FromTicks (0);
2490 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2493 void EndAsyncTaskCallback (IAsyncResult result)
2495 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2496 task.EndHandler (result);
2499 public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2501 Type htmlTextWriterType = typeof (HtmlTextWriter);
2503 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2504 throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2507 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2508 if (constructor == null) {
2509 throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2512 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2515 public ViewStateEncryptionMode ViewStateEncryptionMode {
2516 get { return viewStateEncryptionMode; }
2517 set { viewStateEncryptionMode = value; }
2520 public void RegisterRequiresViewStateEncryption ()
2522 controlRegisteredForViewStateEncryption = true;
2525 private static byte [] AES_IV = null;
2526 private static byte [] TripleDES_IV = null;
2527 private static object locker = new object ();
2528 private static bool isEncryptionInitialized = false;
2530 private static void InitializeEncryption ()
2532 if (isEncryptionInitialized) {
2537 if (isEncryptionInitialized) {
2541 string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
2542 AES_IV = new byte [16];
2543 TripleDES_IV = new byte [8];
2546 for (i = 0; i < AES_IV.Length; i++) {
2547 AES_IV [i] = (byte) iv_string [i];
2550 for (i = 0; i < TripleDES_IV.Length; i++) {
2551 TripleDES_IV [i] = (byte) iv_string [i];
2554 isEncryptionInitialized = true;
2558 internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
2560 ICryptoTransform transform = null;
2561 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
2562 byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
2564 switch (config.Validation) {
2565 case MachineKeyValidation.SHA1:
2566 transform = SHA1.Create ();
2569 case MachineKeyValidation.MD5:
2570 transform = MD5.Create ();
2573 case MachineKeyValidation.AES:
2574 InitializeEncryption ();
2575 if (cryptoStreamMode == CryptoStreamMode.Read){
2576 transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
2578 transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
2582 case MachineKeyValidation.TripleDES:
2583 InitializeEncryption ();
2584 if (cryptoStreamMode == CryptoStreamMode.Read){
2585 transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
2587 transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
2595 internal bool NeedViewStateEncryption {
2597 return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2598 (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2599 controlRegisteredForViewStateEncryption));
2604 void ApplyMasterPage ()
2606 if (masterPageFile != null && masterPageFile.Length > 0) {
2607 ArrayList appliedMasterPageFiles = new ArrayList ();
2609 if (Master != null) {
2610 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
2614 Controls.Add (Master);
2619 [DefaultValueAttribute ("")]
2620 public virtual string MasterPageFile {
2621 get { return masterPageFile; }
2623 masterPageFile = value;
2628 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2629 [BrowsableAttribute (false)]
2630 public MasterPage Master {
2632 if (Context == null || String.IsNullOrEmpty (masterPageFile))
2635 if (masterPage == null)
2636 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2642 public void SetFocus (string clientID)
2644 if (String.IsNullOrEmpty (clientID))
2645 throw new ArgumentNullException ("control");
2648 throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2651 throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2653 _focusedControlID = clientID;
2656 public void SetFocus (Control control)
2658 if (control == null)
2659 throw new ArgumentNullException ("control");
2661 SetFocus (control.ClientID);
2664 [EditorBrowsable (EditorBrowsableState.Advanced)]
2665 public void RegisterRequiresControlState (Control control)
2667 if (control == null)
2668 throw new ArgumentNullException ("control");
2670 if (RequiresControlState (control))
2673 if (requireStateControls == null)
2674 requireStateControls = new ArrayList ();
2675 int n = requireStateControls.Add (control);
2677 if (_savedControlState == null || n >= _savedControlState.Length)
2680 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2681 if (parent.IsChildControlStateCleared)
2684 object state = _savedControlState [n];
2686 control.LoadControlState (state);
2689 public bool RequiresControlState (Control control)
2691 if (requireStateControls == null) return false;
2692 return requireStateControls.Contains (control);
2695 [EditorBrowsable (EditorBrowsableState.Advanced)]
2696 public void UnregisterRequiresControlState (Control control)
2698 if (requireStateControls != null)
2699 requireStateControls.Remove (control);
2702 public ValidatorCollection GetValidators (string validationGroup)
2704 if (validationGroup == String.Empty)
2705 validationGroup = null;
2707 ValidatorCollection col = new ValidatorCollection ();
2708 if (_validators == null)
2711 foreach (IValidator v in _validators)
2712 if (BelongsToGroup(v, validationGroup))
2718 bool BelongsToGroup(IValidator v, string validationGroup) {
2719 BaseValidator validator = v as BaseValidator;
2720 if (validationGroup == null)
2721 return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
2723 return validator != null && validator.ValidationGroup == validationGroup;
2726 public virtual void Validate (string validationGroup)
2728 is_validated = true;
2729 ValidateCollection (GetValidators (validationGroup));
2732 object SavePageControlState ()
2734 if (requireStateControls == null) return null;
2735 object[] state = new object [requireStateControls.Count];
2736 object[] adapterState = new object [requireStateControls.Count];
2737 bool allNull = true;
2738 for (int n=0; n<requireStateControls.Count; n++) {
2739 state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2740 if (state [n] != null) allNull = false;
2742 TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
2744 trace.SaveControlState ((Control) requireStateControls [n], state [n]);
2746 ControlAdapter adapter = ((Control) requireStateControls [n]).Adapter;
2747 if (adapter != null)
2748 adapterState [n] = adapter.SaveAdapterControlState ();
2749 if (adapterState [n] != null) allNull = false;
2751 if (allNull) return null;
2752 else return new Pair (state, adapterState);
2755 void LoadPageControlState (object data)
2757 _savedControlState = null;
2758 if (data == null) return;
2759 Pair statePair = (Pair)data;
2760 _savedControlState = (object[]) statePair.First;
2761 object[] adapterState = (object[]) statePair.Second;
2763 if (requireStateControls == null) return;
2765 int min = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2766 for (int n=0; n < min; n++) {
2767 Control ctl = (Control) requireStateControls [n];
2768 ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2769 if (ctl.Adapter != null)
2770 ctl.Adapter.LoadAdapterControlState (adapterState != null ? adapterState [n] : null);
2774 void LoadPreviousPageReference ()
2776 if (_requestValueCollection != null) {
2777 string prevPage = _requestValueCollection [PreviousPageID];
2778 if (prevPage != null) {
2780 if (getFacesContext () != null) {
2781 IHttpHandler handler = Context.ApplicationInstance.GetHandler (Context, prevPage);
2782 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2783 if (_context.Items.Contains (CrossPagePostBack)) {
2784 previousPage = (Page) _context.Items [CrossPagePostBack];
2785 _context.Items.Remove (CrossPagePostBack);
2790 IHttpHandler handler;
2792 handler = BuildManager.CreateInstanceFromVirtualPath (prevPage, typeof (IHttpHandler)) as IHttpHandler;
2794 handler = PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2796 previousPage = (Page) handler;
2797 previousPage.isCrossPagePostBack = true;
2798 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2805 Hashtable contentTemplates;
2806 [EditorBrowsable (EditorBrowsableState.Never)]
2807 protected internal void AddContentTemplate (string templateName, ITemplate template)
2809 if (contentTemplates == null)
2810 contentTemplates = new Hashtable ();
2811 contentTemplates [templateName] = template;
2814 PageTheme _pageTheme;
2815 internal PageTheme PageTheme {
2816 get { return _pageTheme; }
2819 PageTheme _styleSheetPageTheme;
2820 internal PageTheme StyleSheetPageTheme {
2821 get { return _styleSheetPageTheme; }
2826 internal void PushDataItemContext (object o) {
2827 if (dataItemCtx == null)
2828 dataItemCtx = new Stack ();
2830 dataItemCtx.Push (o);
2833 internal void PopDataItemContext () {
2834 if (dataItemCtx == null)
2835 throw new InvalidOperationException ();
2840 public object GetDataItem() {
2841 if (dataItemCtx == null || dataItemCtx.Count == 0)
2842 throw new InvalidOperationException ("No data item");
2844 return dataItemCtx.Peek ();
2847 protected internal override void OnInit (EventArgs e)
2851 ArrayList themes = new ArrayList();
2853 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2854 themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2855 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2856 themes.AddRange (PageTheme.GetStyleSheets ());
2858 if (themes.Count > 0 && Header == null)
2859 throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2861 foreach (string lss in themes) {
2862 HtmlLink hl = new HtmlLink ();
2864 hl.Attributes["type"] = "text/css";
2865 hl.Attributes["rel"] = "stylesheet";
2866 Header.Controls.Add (hl);
2873 [MonoTODO ("Not implemented. Only used by .net aspx parser")]
2874 protected object GetWrappedFileDependencies (string [] list)
2879 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2880 protected virtual void InitializeCulture ()
2884 [MonoTODO ("Does nothing. Used by .net aspx parser")]
2885 protected internal void AddWrappedFileDependencies (object virtualFileDependencies)