[asp.net] HtmlForum.Name rendering updates + test updates
[mono.git] / mcs / class / System.Web / System.Web.UI / Page.cs
1 //
2 // System.Web.UI.Page.cs
3 //
4 // Authors:
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)
9 //
10 // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
11 // Copyright (C) 2003-2010 Novell, Inc (http://www.novell.com)
12 //
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:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
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.
31 //
32
33 using System;
34 using System.Collections;
35 using System.Collections.Generic;
36 using System.Collections.Specialized;
37 using System.ComponentModel;
38 using System.ComponentModel.Design;
39 using System.ComponentModel.Design.Serialization;
40 using System.Globalization;
41 using System.IO;
42 using System.Security.Permissions;
43 using System.Security.Principal;
44 using System.Text;
45 using System.Threading;
46 using System.Web;
47 using System.Web.Caching;
48 using System.Web.Compilation;
49 using System.Web.Configuration;
50 using System.Web.Hosting;
51 using System.Web.SessionState;
52 using System.Web.Util;
53 using System.Web.UI.Adapters;
54 using System.Web.UI.HtmlControls;
55 using System.Web.UI.WebControls;
56 using System.Reflection;
57 #if NET_4_0
58 using System.Web.Routing;
59 #endif
60
61 namespace System.Web.UI
62 {
63 // CAS
64 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
65 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
66 [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
67 [ToolboxItem (false)]
68 [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
69 [DesignerSerializer ("Microsoft.VisualStudio.Web.WebForms.WebFormCodeDomSerializer, " + Consts.AssemblyMicrosoft_VisualStudio_Web, "System.ComponentModel.Design.Serialization.TypeCodeDomSerializer, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
70 public partial class Page : TemplateControl, IHttpHandler
71 {
72 //      static string machineKeyConfigPath = "system.web/machineKey";
73         bool _eventValidation = true;
74         object [] _savedControlState;
75         bool _doLoadPreviousPage;
76         string _focusedControlID;
77         bool _hasEnabledControlArray;
78         bool _viewState;
79         bool _viewStateMac;
80         string _errorPage;
81         bool is_validated;
82         bool _smartNavigation;
83         int _transactionMode;
84         ValidatorCollection _validators;
85         bool renderingForm;
86         string _savedViewState;
87         List <string> _requiresPostBack;
88         List <string> _requiresPostBackCopy;
89         List <IPostBackDataHandler> requiresPostDataChanged;
90         IPostBackEventHandler requiresRaiseEvent;
91         IPostBackEventHandler formPostedRequiresRaiseEvent;
92         NameValueCollection secondPostData;
93         bool requiresPostBackScript;
94         bool postBackScriptRendered;
95         bool requiresFormScriptDeclaration;
96         bool formScriptDeclarationRendered;
97         bool handleViewState;
98         string viewStateUserKey;
99         NameValueCollection _requestValueCollection;
100         string clientTarget;
101         ClientScriptManager scriptManager;
102         bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
103         PageStatePersister page_state_persister;
104         CultureInfo _appCulture;
105         CultureInfo _appUICulture;
106
107         // The initial context
108         HttpContext _context;
109         
110         // cached from the initial context
111         HttpApplicationState _application;
112         HttpResponse _response;
113         HttpRequest _request;
114         Cache _cache;
115         
116         HttpSessionState _session;
117         
118         [EditorBrowsable (EditorBrowsableState.Never)]
119         public const string postEventArgumentID = "__EVENTARGUMENT";
120
121         [EditorBrowsable (EditorBrowsableState.Never)]
122         public const string postEventSourceID = "__EVENTTARGET";
123
124         const string ScrollPositionXID = "__SCROLLPOSITIONX";
125         const string ScrollPositionYID = "__SCROLLPOSITIONY";
126         const string EnabledControlArrayID = "__enabledControlArray";
127         internal const string LastFocusID = "__LASTFOCUS";
128         internal const string CallbackArgumentID = "__CALLBACKPARAM";
129         internal const string CallbackSourceID = "__CALLBACKID";
130         internal const string PreviousPageID = "__PREVIOUSPAGE";
131
132         int maxPageStateFieldLength = -1;
133         string uniqueFilePathSuffix;
134         HtmlHead htmlHeader;
135         
136         MasterPage masterPage;
137         string masterPageFile;
138         
139         Page previousPage;
140         bool isCrossPagePostBack;
141         bool isPostBack;
142         bool isCallback;
143         List <Control> requireStateControls;
144         HtmlForm _form;
145
146         string _title;
147         string _theme;
148         string _styleSheetTheme;
149 #if NET_4_0
150         string _metaDescription;
151         string _metaKeywords;
152         Control _autoPostBackControl;
153         
154         bool frameworkInitialized;
155 #endif
156         Hashtable items;
157
158         bool _maintainScrollPositionOnPostBack;
159
160         bool asyncMode = false;
161         TimeSpan asyncTimeout;
162         const double DefaultAsyncTimeout = 45.0;
163         List<PageAsyncTask> parallelTasks;
164         List<PageAsyncTask> serialTasks;
165
166         ViewStateEncryptionMode viewStateEncryptionMode;
167         bool controlRegisteredForViewStateEncryption = false;
168
169         #region Constructors    
170         public Page ()
171         {
172                 scriptManager = new ClientScriptManager (this);
173                 Page = this;
174                 ID = "__Page";
175                 PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
176                 if (ps != null) {
177                         asyncTimeout = ps.AsyncTimeout;
178                         viewStateEncryptionMode = ps.ViewStateEncryptionMode;
179                         _viewState = ps.EnableViewState;
180                         _viewStateMac = ps.EnableViewStateMac;
181                 } else {
182                         asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
183                         viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
184                         _viewState = true;
185                 }
186 #if NET_4_0
187                 this.ViewStateMode = ViewStateMode.Enabled;
188 #endif
189         }
190
191         #endregion              
192
193         #region Properties
194
195         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
196         [Browsable (false)]
197         public HttpApplicationState Application {
198                 get { return _application; }
199         }
200
201         [EditorBrowsable (EditorBrowsableState.Never)]
202         protected bool AspCompatMode {
203                 get { return false; }
204                 set {
205                         // nothing to do
206                 }
207         }
208
209         [EditorBrowsable (EditorBrowsableState.Never)]
210         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
211         [BrowsableAttribute (false)]
212         public bool Buffer {
213                 get { return Response.BufferOutput; }
214                 set { Response.BufferOutput = value; }
215         }
216
217         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
218         [Browsable (false)]
219         public Cache Cache {
220                 get {
221                         if (_cache == null)
222                                 throw new HttpException ("Cache is not available.");
223                         return _cache;
224                 }
225         }
226
227         [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
228         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
229         [Browsable (false), DefaultValue ("")]
230         [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
231         public string ClientTarget {
232                 get { return (clientTarget == null) ? String.Empty : clientTarget; }
233                 set {
234                         clientTarget = value;
235                         if (value == String.Empty)
236                                 clientTarget = null;
237                 }
238         }
239
240         [EditorBrowsable (EditorBrowsableState.Never)]
241         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
242         [BrowsableAttribute (false)]
243         public int CodePage {
244                 get { return Response.ContentEncoding.CodePage; }
245                 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
246         }
247
248         [EditorBrowsable (EditorBrowsableState.Never)]
249         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
250         [BrowsableAttribute (false)]
251         public string ContentType {
252                 get { return Response.ContentType; }
253                 set { Response.ContentType = value; }
254         }
255
256         protected internal override HttpContext Context {
257                 get {
258                         if (_context == null)
259                                 return HttpContext.Current;
260
261                         return _context;
262                 }
263         }
264
265         [EditorBrowsable (EditorBrowsableState.Advanced)]
266         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
267         [BrowsableAttribute (false)]
268         public string Culture {
269                 get { return Thread.CurrentThread.CurrentCulture.Name; }
270                 set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
271         }
272
273         [EditorBrowsable (EditorBrowsableState.Never)]
274         [Browsable (false)]
275         [DefaultValue ("true")]
276         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
277         public virtual bool EnableEventValidation {
278                 get { return _eventValidation; }
279                 set {
280                         if (IsInited)
281                                 throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
282                         _eventValidation = value;
283                 }
284         }
285
286         [Browsable (false)]
287         public override bool EnableViewState {
288                 get { return _viewState; }
289                 set { _viewState = value; }
290         }
291
292         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
293         [BrowsableAttribute (false)]
294         [EditorBrowsable (EditorBrowsableState.Never)]
295         public bool EnableViewStateMac {
296                 get { return _viewStateMac; }
297                 set { _viewStateMac = value; }
298         }
299
300         internal bool EnableViewStateMacInternal {
301                 get { return _viewStateMac; }
302                 set { _viewStateMac = value; }
303         }
304         
305         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
306         [Browsable (false), DefaultValue ("")]
307         [WebSysDescription ("The URL of a page used for error redirection.")]
308         public string ErrorPage {
309                 get { return _errorPage; }
310                 set {
311                         HttpContext ctx = Context;
312                         
313                         _errorPage = value;
314                         if (ctx != null)
315                                 ctx.ErrorPage = value;
316                 }
317         }
318
319         [Obsolete ("The recommended alternative is HttpResponse.AddFileDependencies. http://go.microsoft.com/fwlink/?linkid=14202")]
320         [EditorBrowsable (EditorBrowsableState.Never)]
321         protected ArrayList FileDependencies {
322                 set {
323                         if (Response != null)
324                                 Response.AddFileDependencies (value);
325                 }
326         }
327
328         [Browsable (false)]
329         [EditorBrowsable (EditorBrowsableState.Never)]
330         public override string ID {
331                 get { return base.ID; }
332                 set { base.ID = value; }
333         }
334
335         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
336         [Browsable (false)]
337         public bool IsPostBack {
338                 get { return isPostBack; }
339         }
340
341         public bool IsPostBackEventControlRegistered {
342                 get { return requiresRaiseEvent != null; }
343         }
344         
345         [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
346         public bool IsReusable {
347                 get { return false; }
348         }
349
350         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
351         [Browsable (false)]
352         public bool IsValid {
353                 get {
354                         if (!is_validated)
355                                 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."));
356
357                         foreach (IValidator val in Validators)
358                                 if (!val.IsValid)
359                                         return false;
360                         return true;
361                 }
362         }
363
364         [Browsable (false)]
365         public IDictionary Items {
366                 get {
367                         if (items == null)
368                                 items = new Hashtable ();
369                         return items;
370                 }
371         }
372
373         [EditorBrowsable (EditorBrowsableState.Never)]
374         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
375         [BrowsableAttribute (false)]
376         public int LCID {
377                 get { return Thread.CurrentThread.CurrentCulture.LCID; }
378                 set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
379         }
380
381         [Browsable (false)]
382         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
383         public bool MaintainScrollPositionOnPostBack {
384                 get { return _maintainScrollPositionOnPostBack; }
385                 set { _maintainScrollPositionOnPostBack = value; }
386         }
387
388         public PageAdapter PageAdapter {
389                 get {
390                         return Adapter as PageAdapter;
391                 }
392         }
393
394         string _validationStartupScript;
395         string _validationOnSubmitStatement;
396         string _validationInitializeScript;
397         string _webFormScriptReference;
398
399         internal string WebFormScriptReference {
400                 get {
401                         if (_webFormScriptReference == null)
402                                 _webFormScriptReference = IsMultiForm ? theForm : "window";
403                         return _webFormScriptReference;
404                 }
405         }
406
407         internal string ValidationStartupScript {
408                 get {
409                         if (_validationStartupScript == null) {
410                                 _validationStartupScript =
411 @"
412 " + WebFormScriptReference + @".Page_ValidationActive = false;
413 " + WebFormScriptReference + @".ValidatorOnLoad();
414 " + WebFormScriptReference + @".ValidatorOnSubmit = function () {
415         if (this.Page_ValidationActive) {
416                 return this.ValidatorCommonOnSubmit();
417         }
418         return true;
419 };
420 ";
421                         }
422                         return _validationStartupScript;
423                 }
424         }
425
426         internal string ValidationOnSubmitStatement {
427                 get {
428                         if (_validationOnSubmitStatement == null)
429                                 _validationOnSubmitStatement = "if (!" + WebFormScriptReference + ".ValidatorOnSubmit()) return false;";
430                         return _validationOnSubmitStatement;
431                 }
432         }
433
434         internal string ValidationInitializeScript {
435                 get {
436                         if (_validationInitializeScript == null)
437                                 _validationInitializeScript = "WebFormValidation_Initialize(" + WebFormScriptReference + ");";
438                         return _validationInitializeScript;
439                 }
440         }
441
442         internal IScriptManager ScriptManager {
443                 get { return (IScriptManager) Items [typeof (IScriptManager)]; }
444         }
445 #if !TARGET_J2EE
446         internal string theForm {
447                 get {
448                         return "theForm";
449                 }
450         }
451         
452         internal bool IsMultiForm {
453                 get { return false; }
454         }
455 #endif
456
457         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
458         [Browsable (false)]
459         public HttpRequest Request {
460                 get {
461                         if (_request == null)
462                                 throw new HttpException("Request is not available in this context.");
463                         return RequestInternal;
464                 }
465         }
466
467         internal HttpRequest RequestInternal {
468                 get { return _request; }
469         }
470         
471         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
472         [Browsable (false)]
473         public HttpResponse Response {
474                 get {
475                         if (_response == null)
476                                 throw new HttpException ("Response is not available in this context.");
477                         return _response;
478                 }
479         }
480
481         [EditorBrowsable (EditorBrowsableState.Never)]
482         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
483         [BrowsableAttribute (false)]
484         public string ResponseEncoding {
485                 get { return Response.ContentEncoding.WebName; }
486                 set { Response.ContentEncoding = Encoding.GetEncoding (value); }
487         }
488
489         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
490         [Browsable (false)]
491         public HttpServerUtility Server {
492                 get { return Context.Server; }
493         }
494
495         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
496         [Browsable (false)]
497         public virtual HttpSessionState Session {
498                 get {
499                         if (_session != null)
500                                 return _session;
501
502                         try {
503                                 _session = Context.Session;
504                         } catch {
505                                 // ignore, should not throw
506                         }
507                         
508                         if (_session == null)
509                                 throw new HttpException ("Session state can only be used " +
510                                                 "when enableSessionState is set to true, either " +
511                                                 "in a configuration file or in the Page directive.");
512
513                         return _session;
514                 }
515         }
516
517         [Filterable (false)]
518         [Obsolete ("The recommended alternative is Page.SetFocus and Page.MaintainScrollPositionOnPostBack. http://go.microsoft.com/fwlink/?linkid=14202")]
519         [Browsable (false)]
520         public bool SmartNavigation {
521                 get { return _smartNavigation; }
522                 set { _smartNavigation = value; }
523         }
524
525         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
526         [Filterable (false)]
527         [Browsable (false)]
528         public virtual string StyleSheetTheme {
529                 get { return _styleSheetTheme; }
530                 set { _styleSheetTheme = value; }
531         }
532
533         [Browsable (false)]
534         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
535         public virtual string Theme {
536                 get { return _theme; }
537                 set { _theme = value; }
538         }
539
540         void InitializeStyleSheet ()
541         {
542                 if (_styleSheetTheme == null) {
543                         PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
544                         if (ps != null)
545                                 _styleSheetTheme = ps.StyleSheetTheme;
546                 }
547 #if TARGET_JVM
548                 if (_styleSheetTheme != null && _styleSheetTheme != "")
549                         _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, Context);
550 #else
551                 if (!String.IsNullOrEmpty (_styleSheetTheme)) {
552                         string virtualPath = "~/App_Themes/" + _styleSheetTheme;
553                         _styleSheetPageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
554                 }
555 #endif  
556         }
557
558         void InitializeTheme ()
559         {
560                 if (_theme == null) {
561                         PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
562                         if (ps != null)
563                                 _theme = ps.Theme;
564                 }
565 #if TARGET_JVM
566                 if (_theme != null && _theme != "") {
567                         _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, Context);
568                         _pageTheme.SetPage (this);
569                 }
570 #else
571                 if (!String.IsNullOrEmpty (_theme)) {
572                         string virtualPath = "~/App_Themes/" + _theme;
573                         _pageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
574                         if (_pageTheme != null)
575                                 _pageTheme.SetPage (this);
576                 }
577 #endif  
578         }
579 #if NET_4_0
580         public Control AutoPostBackControl {
581                 get { return _autoPostBackControl; }
582                 set { _autoPostBackControl = value; }
583         }
584         
585         [BrowsableAttribute(false)]
586         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
587         public RouteData RouteData {
588                 get {
589                         if (_request == null)
590                                 return null;
591
592                         RequestContext reqctx = _request.RequestContext;
593                         if (reqctx == null)
594                                 return null;
595
596                         return reqctx.RouteData;
597                 }
598         }
599         
600         [Bindable (true)]
601         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
602         [Localizable (true)]
603         public string MetaDescription {
604                 get {
605                         if (_metaDescription == null) {
606                                 if (htmlHeader == null) {
607                                         if (frameworkInitialized)
608                                                 throw new InvalidOperationException ("A server-side head element is required to set this property.");
609                                         return String.Empty;
610                                 } else
611                                         return htmlHeader.Description;
612                         }
613
614                         return _metaDescription;
615                 }
616                 
617                 set {
618                         if (htmlHeader == null) {
619                                 if (frameworkInitialized)
620                                         throw new InvalidOperationException ("A server-side head element is required to set this property.");
621                                 _metaDescription = value;
622                         } else
623                                 htmlHeader.Description = value;
624                 }
625         }
626
627         [Bindable (true)]
628         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
629         [Localizable (true)]
630         public string MetaKeywords {
631                 get {
632                         if (_metaKeywords == null) {
633                                 if (htmlHeader == null) {
634                                         if (frameworkInitialized)
635                                                 throw new InvalidOperationException ("A server-side head element is required to set this property.");
636                                         return String.Empty;
637                                 } else
638                                         return htmlHeader.Keywords;
639                         }
640
641                         return _metaDescription;
642                 }
643                 
644                 set {
645                         if (htmlHeader == null) {
646                                 if (frameworkInitialized)
647                                         throw new InvalidOperationException ("A server-side head element is required to set this property.");
648                                 _metaKeywords = value;
649                         } else
650                                 htmlHeader.Keywords = value;
651                 }
652         }
653 #endif
654         [Localizable (true)] 
655         [Bindable (true)] 
656         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
657         public string Title {
658                 get {
659                         if (_title == null) {
660                                 if (htmlHeader != null && htmlHeader.Title != null)
661                                         return htmlHeader.Title;
662                                 return String.Empty;
663                         }
664                         return _title;
665                 }
666
667                 set {
668                         if (htmlHeader != null)
669                                 htmlHeader.Title = value;
670                         else
671                                 _title = value;
672                 }
673         }
674
675         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
676         [Browsable (false)]
677         public TraceContext Trace {
678                 get { return Context.Trace; }
679         }
680
681         [EditorBrowsable (EditorBrowsableState.Never)]
682         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
683         [BrowsableAttribute (false)]
684         public bool TraceEnabled {
685                 get { return Trace.IsEnabled; }
686                 set { Trace.IsEnabled = value; }
687         }
688
689         [EditorBrowsable (EditorBrowsableState.Never)]
690         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
691         [BrowsableAttribute (false)]
692         public TraceMode TraceModeValue {
693                 get { return Trace.TraceMode; }
694                 set { Trace.TraceMode = value; }
695         }
696
697         [EditorBrowsable (EditorBrowsableState.Never)]
698         protected int TransactionMode {
699                 get { return _transactionMode; }
700                 set { _transactionMode = value; }
701         }
702
703         [EditorBrowsable (EditorBrowsableState.Advanced)]
704         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
705         [BrowsableAttribute (false)]
706         public string UICulture {
707                 get { return Thread.CurrentThread.CurrentUICulture.Name; }
708                 set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
709         }
710
711         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
712         [Browsable (false)]
713         public IPrincipal User {
714                 get { return Context.User; }
715         }
716
717         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
718         [Browsable (false)]
719         public ValidatorCollection Validators {
720                 get { 
721                         if (_validators == null)
722                                 _validators = new ValidatorCollection ();
723                         return _validators;
724                 }
725         }
726
727         [MonoTODO ("Use this when encrypting/decrypting ViewState")]
728         [Browsable (false)]
729         public string ViewStateUserKey {
730                 get { return viewStateUserKey; }
731                 set { viewStateUserKey = value; }
732         }
733
734         [Browsable (false)]
735         public override bool Visible {
736                 get { return base.Visible; }
737                 set { base.Visible = value; }
738         }
739
740         #endregion
741
742         #region Methods
743
744         CultureInfo GetPageCulture (string culture, CultureInfo deflt)
745         {
746                 if (culture == null)
747                         return deflt;
748                 CultureInfo ret = null;
749                 if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
750 #if TARGET_J2EE
751                         if (!Context.IsServletRequest)
752                                 return deflt;
753 #endif
754                         string[] languages = Request.UserLanguages;
755                         try {
756                                 if (languages != null && languages.Length > 0)
757                                         ret = CultureInfo.CreateSpecificCulture (languages[0]);
758                         } catch {
759                         }
760                         
761                         if (ret == null)
762                                 ret = deflt;
763                 } else
764                         ret = CultureInfo.CreateSpecificCulture (culture);
765
766                 return ret;
767         }
768
769         [EditorBrowsable (EditorBrowsableState.Never)]
770         protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
771                                                              AsyncCallback cb, 
772                                                              object extraData)
773         {
774                 throw new NotImplementedException ();
775         }
776
777         [EditorBrowsable (EditorBrowsableState.Never)]
778         [MonoNotSupported ("Mono does not support classic ASP compatibility mode.")]
779         protected void AspCompatEndProcessRequest (IAsyncResult result)
780         {
781                 throw new NotImplementedException ();
782         }
783         
784         [EditorBrowsable (EditorBrowsableState.Advanced)]
785         protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
786         {
787                 if (Request.BrowserMightHaveSpecialWriter)
788                         return Request.Browser.CreateHtmlTextWriter(tw);
789                 else
790                         return new HtmlTextWriter (tw);
791         }
792
793         [EditorBrowsable (EditorBrowsableState.Never)]
794         public void DesignerInitialize ()
795         {
796                 InitRecursive (null);
797         }
798
799         [EditorBrowsable (EditorBrowsableState.Advanced)]
800         protected internal virtual NameValueCollection DeterminePostBackMode ()
801         {
802                 // if request was transfered from other page such Transfer
803                 if (_context.IsProcessingInclude)
804                         return null;
805                 
806                 HttpRequest req = Request;
807                 if (req == null)
808                         return null;
809
810                 NameValueCollection coll = null;
811                 if (0 == String.Compare (Request.HttpMethod, "POST", true, Helpers.InvariantCulture)
812 #if TARGET_J2EE
813                         || !_context.IsServletRequest
814 #endif
815                         )
816                         coll = req.Form;
817                 else {
818                         string query = Request.QueryStringRaw;
819                         if (query == null || query.Length == 0)
820                                 return null;
821
822                         coll = req.QueryString;
823                 }
824
825                 WebROCollection c = (WebROCollection) coll;
826                 allow_load = !c.GotID;
827                 if (allow_load)
828                         c.ID = GetTypeHashCode ();
829                 else
830                         allow_load = (c.ID == GetTypeHashCode ());
831
832                 if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
833                         return null;
834 #if TARGET_J2EE
835                 if (getFacesContext () != null && _context.Handler != _context.CurrentHandler) {
836                         // check if it is PreviousPage
837                         string prevViewId = coll [PreviousPageID];
838                         if (!String.IsNullOrEmpty (prevViewId)) {
839                                 string appPath = VirtualPathUtility.RemoveTrailingSlash (Request.ApplicationPath);
840                                 prevViewId = prevViewId.Substring (appPath.Length);
841                                 isCrossPagePostBack = String.Compare (prevViewId, getFacesContext ().getExternalContext ().getRequestPathInfo (), StringComparison.OrdinalIgnoreCase) == 0;
842                         }
843                 }
844 #endif
845                 return coll;
846         }
847
848         public override Control FindControl (string id) {
849                 if (id == ID)
850                         return this;
851                 else
852                         return base.FindControl (id);
853         }
854
855         Control FindControl (string id, bool decode) {
856 #if TARGET_J2EE
857                 if (decode)
858                         id = DecodeNamespace (id);
859 #endif
860                 return FindControl (id);
861         }
862
863         [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
864         [EditorBrowsable (EditorBrowsableState.Advanced)]
865         public string GetPostBackClientEvent (Control control, string argument)
866         {
867                 return scriptManager.GetPostBackEventReference (control, argument);
868         }
869
870         [Obsolete ("The recommended alternative is ClientScript.GetPostBackClientHyperlink. http://go.microsoft.com/fwlink/?linkid=14202")]
871         [EditorBrowsable (EditorBrowsableState.Advanced)]
872         public string GetPostBackClientHyperlink (Control control, string argument)
873         {
874                 return scriptManager.GetPostBackClientHyperlink (control, argument);
875         }
876
877         [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
878         [EditorBrowsable (EditorBrowsableState.Advanced)]
879         public string GetPostBackEventReference (Control control)
880         {
881                 return scriptManager.GetPostBackEventReference (control, String.Empty);
882         }
883
884         [Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
885         [EditorBrowsable (EditorBrowsableState.Advanced)]
886         public string GetPostBackEventReference (Control control, string argument)
887         {
888                 return scriptManager.GetPostBackEventReference (control, argument);
889         }
890
891         internal void RequiresFormScriptDeclaration ()
892         {
893                 requiresFormScriptDeclaration = true;
894         }
895         
896         internal void RequiresPostBackScript ()
897         {
898                 if (requiresPostBackScript)
899                         return;
900                 ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
901                 ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
902                 requiresPostBackScript = true;
903                 RequiresFormScriptDeclaration ();
904         }
905
906         [EditorBrowsable (EditorBrowsableState.Never)]
907         public virtual int GetTypeHashCode ()
908         {
909                 return 0;
910         }
911
912         [MonoTODO ("The following properties of OutputCacheParameters are silently ignored: CacheProfile, SqlDependency")]
913         [EditorBrowsable (EditorBrowsableState.Never)]
914         protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
915         {
916                 if (cacheSettings.Enabled) {
917                         InitOutputCache(cacheSettings.Duration,
918                                         cacheSettings.VaryByContentEncoding,
919                                         cacheSettings.VaryByHeader,
920                                         cacheSettings.VaryByCustom,
921                                         cacheSettings.Location,
922                                         cacheSettings.VaryByParam);
923
924                         HttpResponse response = Response;
925                         HttpCachePolicy cache = response != null ? response.Cache : null;
926                         if (cache != null && cacheSettings.NoStore)
927                                 cache.SetNoStore ();
928                 }
929         }
930         
931         [MonoTODO ("varyByContentEncoding is not currently used")]
932         [EditorBrowsable (EditorBrowsableState.Never)]
933         protected virtual void InitOutputCache(int duration,
934                                                string varyByContentEncoding,
935                                                string varyByHeader,
936                                                string varyByCustom,
937                                                OutputCacheLocation location,
938                                                string varyByParam)
939         {
940                 if (duration <= 0)
941                         // No need to do anything, cache will be ineffective anyway
942                         return;
943                 
944                 HttpResponse response = Response;
945                 HttpCachePolicy cache = response.Cache;
946                 bool set_vary = false;
947                 HttpContext ctx = Context;
948                 DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
949                 
950                 switch (location) {
951                         case OutputCacheLocation.Any:
952                                 cache.SetCacheability (HttpCacheability.Public);
953                                 cache.SetMaxAge (new TimeSpan (0, 0, duration));
954                                 cache.SetLastModified (timestamp);
955                                 set_vary = true;
956                                 break;
957                         case OutputCacheLocation.Client:
958                                 cache.SetCacheability (HttpCacheability.Private);
959                                 cache.SetMaxAge (new TimeSpan (0, 0, duration));
960                                 cache.SetLastModified (timestamp);
961                                 break;
962                         case OutputCacheLocation.Downstream:
963                                 cache.SetCacheability (HttpCacheability.Public);
964                                 cache.SetMaxAge (new TimeSpan (0, 0, duration));
965                                 cache.SetLastModified (timestamp);
966                                 break;
967                         case OutputCacheLocation.Server:                        
968                                 cache.SetCacheability (HttpCacheability.Server);
969                                 set_vary = true;
970                                 break;
971                         case OutputCacheLocation.None:
972                                 break;
973                 }
974
975                 if (set_vary) {
976                         if (varyByCustom != null)
977                                 cache.SetVaryByCustom (varyByCustom);
978
979                         if (varyByParam != null && varyByParam.Length > 0) {
980                                 string[] prms = varyByParam.Split (';');
981                                 foreach (string p in prms)
982                                         cache.VaryByParams [p.Trim ()] = true;
983                                 cache.VaryByParams.IgnoreParams = false;
984                         } else {
985                                 cache.VaryByParams.IgnoreParams = true;
986                         }
987                         
988                         if (varyByHeader != null && varyByHeader.Length > 0) {
989                                 string[] hdrs = varyByHeader.Split (';');
990                                 foreach (string h in hdrs)
991                                         cache.VaryByHeaders [h.Trim ()] = true;
992                         }
993
994                         if (PageAdapter != null) {
995                                 if (PageAdapter.CacheVaryByParams != null) {
996                                         foreach (string p in PageAdapter.CacheVaryByParams)
997                                                 cache.VaryByParams [p] = true;
998                                 }
999                                 if (PageAdapter.CacheVaryByHeaders != null) {
1000                                         foreach (string h in PageAdapter.CacheVaryByHeaders)
1001                                                 cache.VaryByHeaders [h] = true;
1002                                 }
1003                         }
1004                 }
1005
1006                 response.IsCached = true;
1007                 cache.Duration = duration;
1008                 cache.SetExpires (timestamp.AddSeconds (duration));
1009         }
1010         
1011
1012         [EditorBrowsable (EditorBrowsableState.Never)]
1013         protected virtual void InitOutputCache (int duration,
1014                                                 string varyByHeader,
1015                                                 string varyByCustom,
1016                                                 OutputCacheLocation location,
1017                                                 string varyByParam)
1018         {
1019                 InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
1020         }
1021
1022         [Obsolete ("The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
1023         public bool IsClientScriptBlockRegistered (string key)
1024         {
1025                 return scriptManager.IsClientScriptBlockRegistered (key);
1026         }
1027
1028         [Obsolete ("The recommended alternative is ClientScript.IsStartupScriptRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
1029         public bool IsStartupScriptRegistered (string key)
1030         {
1031                 return scriptManager.IsStartupScriptRegistered (key);
1032         }
1033
1034         public string MapPath (string virtualPath)
1035         {
1036                 return Request.MapPath (virtualPath);
1037         }
1038         
1039         protected internal override void Render (HtmlTextWriter writer)
1040         {
1041                 if (MaintainScrollPositionOnPostBack) {
1042                         ClientScript.RegisterWebFormClientScript ();
1043
1044                         ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
1045                         ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
1046
1047                         StringBuilder script = new StringBuilder ();
1048                         script.AppendLine ("<script type=\"text/javascript\">");
1049                         script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
1050                         script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
1051                         script.AppendLine (theForm + ".submit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionSubmit(); }");
1052                         script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
1053                         script.AppendLine (theForm + ".onsubmit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionOnSubmit(); }");
1054                         if (IsPostBack) {
1055                                 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
1056                                 script.AppendLine ("window.onload = function () { " + WebFormScriptReference + ".WebForm_RestoreScrollPosition (); };");
1057                         }
1058                         script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
1059                         script.AppendLine ("</script>");
1060                         
1061                         ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
1062                 }
1063 #if TARGET_J2EE
1064                 if (bool.Parse (WebConfigurationManager.AppSettings [RenderBodyContentOnlyKey] ?? "false")) {
1065                         for (Control c = this.Form; c != null; c = c.Parent) {
1066                                 HtmlGenericControl ch = (c as HtmlGenericControl);
1067                                 if (ch != null && ch.TagName == "body") {
1068                                         ch.RenderChildren (writer);
1069                                         return;
1070                                 }
1071                         }
1072                 }
1073 #endif
1074                 base.Render (writer);
1075         }
1076
1077         void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
1078         {
1079                 writer.WriteLine ();
1080                 ClientScriptManager.WriteBeginScriptBlock (writer);
1081                 RenderClientScriptFormDeclaration (writer, formUniqueID);
1082                 writer.WriteLine (WebFormScriptReference + "._form = " + theForm + ";");
1083                 writer.WriteLine (WebFormScriptReference + ".__doPostBack = function (eventTarget, eventArgument) {");
1084                 writer.WriteLine ("\tif(" + theForm + ".onsubmit && " + theForm + ".onsubmit() == false) return;");
1085                 writer.WriteLine ("\t" + theForm + "." + postEventSourceID + ".value = eventTarget;");
1086                 writer.WriteLine ("\t" + theForm + "." + postEventArgumentID + ".value = eventArgument;");
1087                 writer.WriteLine ("\t" + theForm + ".submit();");
1088                 writer.WriteLine ("}");
1089                 ClientScriptManager.WriteEndScriptBlock (writer);
1090         }
1091
1092         void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
1093         {
1094                 if (formScriptDeclarationRendered)
1095                         return;
1096                 
1097                 if (PageAdapter != null) {
1098                         writer.WriteLine ("\tvar {0} = {1};\n", theForm, PageAdapter.GetPostBackFormReference(formUniqueID));
1099                 } else {
1100                         writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
1101                         writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
1102                 }
1103 #if TARGET_J2EE
1104                 // TODO implement callback on portlet
1105                 string serverUrl = Request.RawUrl;
1106                 writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
1107                 writer.WriteLine ("\twindow.TARGET_J2EE = true;");
1108                 writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
1109 #endif
1110                 formScriptDeclarationRendered = true;
1111         }
1112
1113         internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
1114         {
1115                 if (renderingForm)
1116                         throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1117
1118                 renderingForm = true;
1119                 writer.WriteLine ();
1120
1121                 if (requiresFormScriptDeclaration || (scriptManager != null && scriptManager.ScriptsPresent) || PageAdapter != null) {
1122                         ClientScriptManager.WriteBeginScriptBlock (writer);
1123                         RenderClientScriptFormDeclaration (writer, formUniqueID);
1124                         ClientScriptManager.WriteEndScriptBlock (writer);
1125                 }
1126
1127                 if (handleViewState)
1128 #if TARGET_J2EE
1129                         if (getFacesContext () != null) {
1130                                 javax.faces.application.ViewHandler viewHandler = getFacesContext ().getApplication ().getViewHandler ();
1131                                 javax.faces.context.ResponseWriter oldFacesWriter = SetupResponseWriter (writer);
1132                                 try {
1133                                         viewHandler.writeState (getFacesContext ());
1134                                 }
1135                                 finally {
1136                                         getFacesContext ().setResponseWriter (oldFacesWriter);
1137                                 }
1138                         } else
1139 #endif
1140                                 scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1141
1142                 scriptManager.WriteHiddenFields (writer);
1143                 if (requiresPostBackScript) {
1144                         RenderPostBackScript (writer, formUniqueID);
1145                         postBackScriptRendered = true;
1146                 }
1147
1148                 scriptManager.WriteWebFormClientScript (writer);
1149                 scriptManager.WriteClientScriptBlocks (writer);
1150         }
1151
1152         internal IStateFormatter GetFormatter ()
1153         {
1154                 return new ObjectStateFormatter (this);
1155         }
1156
1157         internal string GetSavedViewState ()
1158         {
1159                 return _savedViewState;
1160         }
1161
1162         internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1163         {
1164                 scriptManager.SaveEventValidationState ();
1165                 scriptManager.WriteExpandoAttributes (writer);
1166                 scriptManager.WriteHiddenFields (writer);
1167                 if (!postBackScriptRendered && requiresPostBackScript)
1168                         RenderPostBackScript (writer, formUniqueID);
1169                 scriptManager.WriteWebFormClientScript (writer);
1170                 scriptManager.WriteArrayDeclares (writer);
1171                 scriptManager.WriteStartupScriptBlocks (writer);
1172                 renderingForm = false;
1173                 postBackScriptRendered = false;
1174         }
1175
1176         void ProcessPostData (NameValueCollection data, bool second)
1177         {
1178                 NameValueCollection requestValues = _requestValueCollection == null ? new NameValueCollection () : _requestValueCollection;
1179                 
1180                 if (data != null && data.Count > 0) {
1181                         var used = new Dictionary <string, string> (StringComparer.Ordinal);
1182                         foreach (string id in data.AllKeys) {
1183                                 if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID || id == ClientScriptManager.EventStateFieldName)
1184                                         continue;
1185                         
1186                                 if (used.ContainsKey (id))
1187                                         continue;
1188
1189                                 used.Add (id, id);
1190
1191                                 Control ctrl = FindControl (id, true);
1192                                 if (ctrl != null) {
1193                                         IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1194                                         IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1195
1196                                         if (pbdh == null) {
1197                                                 if (pbeh != null)
1198                                                         formPostedRequiresRaiseEvent = pbeh;
1199                                                 continue;
1200                                         }
1201                 
1202                                         if (pbdh.LoadPostData (id, requestValues) == true) {
1203                                                 if (requiresPostDataChanged == null)
1204                                                         requiresPostDataChanged = new List <IPostBackDataHandler> ();
1205                                                 requiresPostDataChanged.Add (pbdh);
1206                                         }
1207                                 
1208                                         if (_requiresPostBackCopy != null)
1209                                                 _requiresPostBackCopy.Remove (id);
1210
1211                                 } else if (!second) {
1212                                         if (secondPostData == null)
1213                                                 secondPostData = new NameValueCollection ();
1214                                         secondPostData.Add (id, data [id]);
1215                                 }
1216                         }
1217                 }
1218
1219                 List <string> list1 = null;
1220                 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1221                         string [] handlers = (string []) _requiresPostBackCopy.ToArray ();
1222                         foreach (string id in handlers) {
1223                                 IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
1224                                 if (pbdh != null) {                     
1225                                         _requiresPostBackCopy.Remove (id);
1226                                         if (pbdh.LoadPostData (id, requestValues)) {
1227                                                 if (requiresPostDataChanged == null)
1228                                                         requiresPostDataChanged = new List <IPostBackDataHandler> ();
1229         
1230                                                 requiresPostDataChanged.Add (pbdh);
1231                                         }
1232                                 } else if (!second) {
1233                                         if (list1 == null)
1234                                                 list1 = new List <string> ();
1235                                         list1.Add (id);
1236                                 }
1237                         }
1238                 }
1239                 _requiresPostBackCopy = second ? null : list1;
1240                 if (second)
1241                         secondPostData = null;
1242         }
1243
1244         [EditorBrowsable (EditorBrowsableState.Never)]
1245         public virtual void ProcessRequest (HttpContext context)
1246         {
1247                 SetContext (context);
1248 #if TARGET_J2EE
1249                 bool wasException = false;
1250                 IHttpHandler jsfHandler = getFacesContext () != null ? EnterThread () : null;
1251 #endif
1252                 
1253                 if (clientTarget != null)
1254                         Request.ClientTarget = clientTarget;
1255
1256                 WireupAutomaticEvents ();
1257                 //-- Control execution lifecycle in the docs
1258
1259                 // Save culture information because it can be modified in FrameworkInitialize()
1260                 _appCulture = Thread.CurrentThread.CurrentCulture;
1261                 _appUICulture = Thread.CurrentThread.CurrentUICulture;
1262                 FrameworkInitialize ();
1263 #if NET_4_0
1264                 frameworkInitialized = true;
1265 #endif
1266                 context.ErrorPage = _errorPage;
1267
1268                 try {
1269                         InternalProcessRequest ();
1270 #if TARGET_J2EE
1271                 } catch (Exception ex) {
1272                         wasException = true;
1273                         HandleException (ex);
1274 #else
1275                 } catch (ThreadAbortException taex) {
1276                         if (FlagEnd.Value == taex.ExceptionState)
1277                                 Thread.ResetAbort ();
1278                         else
1279                                 throw;
1280                 } catch (Exception e) {
1281                         ProcessException (e);
1282 #endif
1283                 } finally {
1284 #if TARGET_J2EE
1285                         if (getFacesContext () != null)
1286                                 ExitThread (jsfHandler);
1287                         else if (!wasException)
1288 #endif
1289                         ProcessUnload ();
1290                 }
1291         }
1292
1293         void ProcessException (Exception e) {
1294                 // We want to remove that error, as we're rethrowing to stop
1295                 // further processing.
1296                 Trace.Warn ("Unhandled Exception", e.ToString (), e);
1297                 _context.AddError (e); // OnError might access LastError
1298                 OnError (EventArgs.Empty);
1299                 if (_context.HasError (e)) {
1300                         _context.ClearError (e);
1301 #if TARGET_JVM
1302                         vmw.common.TypeUtils.Throw (e);
1303 #else
1304                         throw new HttpUnhandledException (null, e);
1305 #endif
1306                 }
1307         }
1308
1309         void ProcessUnload () {
1310                         try {
1311                                 RenderTrace ();
1312                                 UnloadRecursive (true);
1313                         } catch {}
1314 #if TARGET_J2EE
1315                         if (getFacesContext () != null) {
1316                                 if(IsCrossPagePostBack)
1317                                         _context.Items [CrossPagePostBack] = this;
1318                         }
1319 #endif
1320                         if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
1321                                 Thread.CurrentThread.CurrentCulture = _appCulture;
1322
1323                         if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
1324                                 Thread.CurrentThread.CurrentUICulture = _appUICulture;
1325                         
1326                         _appCulture = null;
1327                         _appUICulture = null;
1328         }
1329         
1330         delegate void ProcessRequestDelegate (HttpContext context);
1331
1332         sealed class DummyAsyncResult : IAsyncResult
1333         {
1334                 readonly object state;
1335                 readonly WaitHandle asyncWaitHandle;
1336                 readonly bool completedSynchronously;
1337                 readonly bool isCompleted;
1338
1339                 public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state) 
1340                 {
1341                         this.isCompleted = isCompleted;
1342                         this.completedSynchronously = completedSynchronously;
1343                         this.state = state;
1344                         if (isCompleted) {
1345                                 asyncWaitHandle = new ManualResetEvent (true);
1346                         }
1347                         else {
1348                                 asyncWaitHandle = new ManualResetEvent (false);
1349                         }
1350                 }
1351
1352                 #region IAsyncResult Members
1353
1354                 public object AsyncState {
1355                         get { return state; }
1356                 }
1357
1358                 public WaitHandle AsyncWaitHandle {
1359                         get { return asyncWaitHandle; }
1360                 }
1361
1362                 public bool CompletedSynchronously {
1363                         get { return completedSynchronously; }
1364                 }
1365
1366                 public bool IsCompleted {
1367                         get { return isCompleted; }
1368                 }
1369
1370                 #endregion
1371         }
1372
1373         [EditorBrowsable (EditorBrowsableState.Never)]
1374         protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData) 
1375         {
1376                 ProcessRequest (context);
1377                 DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
1378
1379                 if (callback != null) {
1380                         callback (asyncResult);
1381                 }
1382                 
1383                 return asyncResult;
1384         }
1385
1386         [EditorBrowsable (EditorBrowsableState.Never)]
1387         protected void AsyncPageEndProcessRequest (IAsyncResult result) 
1388         {
1389         }
1390         
1391         void InternalProcessRequest ()
1392         {
1393                 if (PageAdapter != null)
1394                         _requestValueCollection = PageAdapter.DeterminePostBackMode();
1395                 else
1396                         _requestValueCollection = this.DeterminePostBackMode();
1397
1398                 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1399                 if (_requestValueCollection != null) {
1400                         if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1401                                 _doLoadPreviousPage = true;
1402                         } else {
1403                                 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1404                                 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1405                                 //isPostBack = !isCallback;
1406                                 isPostBack = true;
1407                         }
1408                         
1409                         string lastFocus = _requestValueCollection [LastFocusID];
1410                         if (!String.IsNullOrEmpty (lastFocus))
1411                                 _focusedControlID = UniqueID2ClientID (lastFocus);
1412                 }
1413                 
1414                 if (!isCrossPagePostBack) {
1415                         if (_context.PreviousHandler is Page)
1416                                 previousPage = (Page) _context.PreviousHandler;
1417                 }
1418
1419                 Trace.Write ("aspx.page", "Begin PreInit");
1420                 OnPreInit (EventArgs.Empty);
1421                 Trace.Write ("aspx.page", "End PreInit");
1422
1423                 InitializeTheme ();
1424                 ApplyMasterPage ();
1425                 Trace.Write ("aspx.page", "Begin Init");
1426                 InitRecursive (null);
1427                 Trace.Write ("aspx.page", "End Init");
1428
1429                 Trace.Write ("aspx.page", "Begin InitComplete");
1430                 OnInitComplete (EventArgs.Empty);
1431                 Trace.Write ("aspx.page", "End InitComplete");
1432                         
1433                 renderingForm = false;  
1434
1435 #if TARGET_J2EE
1436                 if (getFacesContext () != null)
1437                         if (IsPostBack || IsCallback)
1438                                 return;
1439 #endif
1440
1441                 RestorePageState ();
1442                 ProcessPostData ();
1443                 ProcessRaiseEvents ();
1444                 if (ProcessLoadComplete ())
1445                         return;
1446 #if TARGET_J2EE
1447                 if (getFacesContext () != null) {
1448                         getFacesContext ().renderResponse ();
1449                         return;
1450                 }
1451 #endif
1452                 RenderPage ();
1453         }
1454
1455         void RestorePageState ()
1456         {
1457                 if (IsPostBack || IsCallback) {
1458                         if (_requestValueCollection != null)
1459                                 scriptManager.RestoreEventValidationState (
1460                                         _requestValueCollection [ClientScriptManager.EventStateFieldName]);
1461                         Trace.Write ("aspx.page", "Begin LoadViewState");
1462                         LoadPageViewState ();
1463                         Trace.Write ("aspx.page", "End LoadViewState");
1464                 }
1465         }
1466
1467         void ProcessPostData ()
1468         {
1469                 if (IsPostBack || IsCallback) {
1470                         Trace.Write ("aspx.page", "Begin ProcessPostData");
1471                         ProcessPostData (_requestValueCollection, false);
1472                         Trace.Write ("aspx.page", "End ProcessPostData");
1473                 }
1474
1475                 ProcessLoad ();
1476                 if (IsPostBack || IsCallback) {
1477                         Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1478                         ProcessPostData (secondPostData, true);
1479                         Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1480                 }
1481         }
1482
1483         void ProcessLoad ()
1484         { 
1485                 Trace.Write ("aspx.page", "Begin PreLoad");
1486                 OnPreLoad (EventArgs.Empty);
1487                 Trace.Write ("aspx.page", "End PreLoad");
1488
1489                 Trace.Write ("aspx.page", "Begin Load");
1490                 LoadRecursive ();
1491                 Trace.Write ("aspx.page", "End Load");
1492         }
1493
1494         void ProcessRaiseEvents ()
1495         {
1496                 if (IsPostBack || IsCallback) {
1497                         Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1498                         RaiseChangedEvents ();
1499                         Trace.Write ("aspx.page", "End Raise ChangedEvents");
1500                         Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1501                         RaisePostBackEvents ();
1502                         Trace.Write ("aspx.page", "End Raise PostBackEvent");
1503                 }
1504         }
1505
1506         bool ProcessLoadComplete ()
1507         {
1508                 Trace.Write ("aspx.page", "Begin LoadComplete");
1509                 OnLoadComplete (EventArgs.Empty);
1510                 Trace.Write ("aspx.page", "End LoadComplete");
1511
1512                 if (IsCrossPagePostBack)
1513                         return true;
1514
1515                 if (IsCallback) {
1516 #if TARGET_J2EE
1517                         if (getFacesContext () != null) {
1518                                 _callbackTarget = GetCallbackTarget ();
1519                                 ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError);
1520                                 return true;
1521                         }
1522 #endif
1523                         string result = ProcessCallbackData ();
1524                         HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
1525                         callbackOutput.Write (result);
1526                         callbackOutput.Flush ();
1527                         return true;
1528                 }
1529                 
1530                 Trace.Write ("aspx.page", "Begin PreRender");
1531                 PreRenderRecursiveInternal ();
1532                 Trace.Write ("aspx.page", "End PreRender");
1533                 
1534                 ExecuteRegisteredAsyncTasks ();
1535
1536                 Trace.Write ("aspx.page", "Begin PreRenderComplete");
1537                 OnPreRenderComplete (EventArgs.Empty);
1538                 Trace.Write ("aspx.page", "End PreRenderComplete");
1539
1540                 Trace.Write ("aspx.page", "Begin SaveViewState");
1541                 SavePageViewState ();
1542                 Trace.Write ("aspx.page", "End SaveViewState");
1543                 
1544                 Trace.Write ("aspx.page", "Begin SaveStateComplete");
1545                 OnSaveStateComplete (EventArgs.Empty);
1546                 Trace.Write ("aspx.page", "End SaveStateComplete");
1547                 return false;
1548         }
1549
1550         internal void RenderPage ()
1551         {
1552                 scriptManager.ResetEventValidationState ();
1553                 
1554                 //--
1555                 Trace.Write ("aspx.page", "Begin Render");
1556                 HtmlTextWriter output = CreateHtmlTextWriter (Response.Output);
1557                 RenderControl (output);
1558                 Trace.Write ("aspx.page", "End Render");
1559         }
1560
1561         internal void SetContext (HttpContext context)
1562         {
1563                 _context = context;
1564
1565                 _application = context.Application;
1566                 _response = context.Response;
1567                 _request = context.Request;
1568                 _cache = context.Cache;
1569         }
1570
1571         void RenderTrace ()
1572         {
1573                 TraceManager traceManager = HttpRuntime.TraceManager;
1574
1575                 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1576                         return;
1577                 
1578                 Trace.SaveData ();
1579
1580                 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput) 
1581                         return;
1582
1583                 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1584                         HtmlTextWriter output = new HtmlTextWriter (Response.Output);
1585                         Trace.Render (output);
1586                 }
1587         }
1588         
1589         void RaisePostBackEvents ()
1590         {
1591                 if (requiresRaiseEvent != null) {
1592                         RaisePostBackEvent (requiresRaiseEvent, null);
1593                         return;
1594                 }
1595
1596                 if (formPostedRequiresRaiseEvent != null) {
1597                         RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1598                         return;
1599                 }
1600                 
1601                 NameValueCollection postdata = _requestValueCollection;
1602                 if (postdata == null)
1603                         return;
1604
1605                 string eventTarget = postdata [postEventSourceID];
1606                 IPostBackEventHandler target;
1607                 if (String.IsNullOrEmpty (eventTarget)) {
1608 #if NET_4_0
1609                         target = AutoPostBackControl as IPostBackEventHandler;
1610                         if (target != null)
1611                                 RaisePostBackEvent (target, null);
1612                         else
1613 #endif
1614                         if (formPostedRequiresRaiseEvent != null)
1615                                 RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
1616                         else
1617                                 Validate ();
1618                         return;
1619                 }
1620
1621                 target = FindControl (eventTarget, true) as IPostBackEventHandler;
1622 #if NET_4_0
1623                 if (target == null)
1624                         target = AutoPostBackControl as IPostBackEventHandler;
1625 #endif
1626                 if (target == null)
1627                         return;
1628
1629                 string eventArgument = postdata [postEventArgumentID];
1630                 RaisePostBackEvent (target, eventArgument);
1631         }
1632
1633         internal void RaiseChangedEvents ()
1634         {
1635                 if (requiresPostDataChanged == null)
1636                         return;
1637
1638                 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1639                         ipdh.RaisePostDataChangedEvent ();
1640
1641                 requiresPostDataChanged = null;
1642         }
1643
1644         [EditorBrowsable (EditorBrowsableState.Advanced)]
1645         protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1646         {
1647                 sourceControl.RaisePostBackEvent (eventArgument);
1648         }
1649         
1650         [Obsolete ("The recommended alternative is ClientScript.RegisterArrayDeclaration(string arrayName, string arrayValue). http://go.microsoft.com/fwlink/?linkid=14202")]
1651         [EditorBrowsable (EditorBrowsableState.Advanced)]
1652         public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1653         {
1654                 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1655         }
1656
1657         [Obsolete ("The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1658         [EditorBrowsable (EditorBrowsableState.Advanced)]
1659         public virtual void RegisterClientScriptBlock (string key, string script)
1660         {
1661                 scriptManager.RegisterClientScriptBlock (key, script);
1662         }
1663
1664         [Obsolete]
1665         [EditorBrowsable (EditorBrowsableState.Advanced)]
1666         public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1667         {
1668                 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1669         }
1670
1671         [MonoTODO("Not implemented, Used in HtmlForm")]
1672         internal void RegisterClientScriptFile (string a, string b, string c)
1673         {
1674                 throw new NotImplementedException ();
1675         }
1676
1677         [Obsolete ("The recommended alternative is ClientScript.RegisterOnSubmitStatement(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1678         [EditorBrowsable (EditorBrowsableState.Advanced)]
1679         public void RegisterOnSubmitStatement (string key, string script)
1680         {
1681                 scriptManager.RegisterOnSubmitStatement (key, script);
1682         }
1683
1684         internal string GetSubmitStatements ()
1685         {
1686                 return scriptManager.WriteSubmitStatements ();
1687         }
1688
1689         [EditorBrowsable (EditorBrowsableState.Advanced)]
1690         public void RegisterRequiresPostBack (Control control)
1691         {
1692                 if (!(control is IPostBackDataHandler))
1693                         throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
1694                 
1695                 if (_requiresPostBack == null)
1696                         _requiresPostBack = new List <string> ();
1697
1698                 string uniqueID = control.UniqueID;
1699                 if (_requiresPostBack.Contains (uniqueID))
1700                         return;
1701
1702                 _requiresPostBack.Add (uniqueID);
1703         }
1704
1705         [EditorBrowsable (EditorBrowsableState.Advanced)]
1706         public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1707         {
1708                 requiresRaiseEvent = control;
1709         }
1710
1711         [Obsolete ("The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
1712         [EditorBrowsable (EditorBrowsableState.Advanced)]
1713         public virtual void RegisterStartupScript (string key, string script)
1714         {
1715                 scriptManager.RegisterStartupScript (key, script);
1716         }
1717
1718         [EditorBrowsable (EditorBrowsableState.Advanced)]
1719         public void RegisterViewStateHandler ()
1720         {
1721                 handleViewState = true;
1722         }
1723
1724         [EditorBrowsable (EditorBrowsableState.Advanced)]
1725         protected virtual void SavePageStateToPersistenceMedium (object viewState)
1726         {
1727                 PageStatePersister persister = this.PageStatePersister;
1728                 if (persister == null)
1729                         return;
1730                 Pair pair = viewState as Pair;
1731                 if (pair != null) {
1732                         persister.ViewState = pair.First;
1733                         persister.ControlState = pair.Second;
1734                 } else
1735                         persister.ViewState = viewState;
1736                 persister.Save ();
1737         }
1738
1739         internal string RawViewState {
1740                 get {
1741                         NameValueCollection postdata = _requestValueCollection;
1742                         string view_state;
1743                         if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1744                                 return null;
1745
1746                         if (view_state == String.Empty)
1747                                 return null;
1748                         return view_state;
1749                 }
1750                 
1751                 set { _savedViewState = value; }
1752         }
1753
1754
1755         protected virtual PageStatePersister PageStatePersister {
1756                 get {
1757                         if (page_state_persister == null && PageAdapter != null)
1758                                         page_state_persister = PageAdapter.GetStatePersister();                                 
1759                         if (page_state_persister == null)
1760                                 page_state_persister = new HiddenFieldPageStatePersister (this);
1761                         return page_state_persister;
1762                 }
1763         }
1764         
1765         [EditorBrowsable (EditorBrowsableState.Advanced)]
1766         protected virtual object LoadPageStateFromPersistenceMedium ()
1767         {
1768                 PageStatePersister persister = this.PageStatePersister;
1769                 if (persister == null)
1770                         return null;
1771                 persister.Load ();
1772                 return new Pair (persister.ViewState, persister.ControlState);
1773         }
1774
1775         internal void LoadPageViewState ()
1776         {
1777                 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1778                 if (sState != null) {
1779                         if (allow_load || isCrossPagePostBack) {
1780                                 LoadPageControlState (sState.Second);
1781
1782                                 Pair vsr = sState.First as Pair;
1783                                 if (vsr != null) {
1784                                         LoadViewStateRecursive (vsr.First);
1785                                         _requiresPostBackCopy = vsr.Second as List <string>;
1786                                 }
1787                         }
1788                 }
1789         }
1790
1791         internal void SavePageViewState ()
1792         {
1793                 if (!handleViewState)
1794                         return;
1795
1796                 object controlState = SavePageControlState ();
1797                 Pair vsr = null;
1798                 object viewState = null;
1799                 
1800                 if (EnableViewState
1801 #if NET_4_0
1802                     && this.ViewStateMode == ViewStateMode.Enabled
1803 #endif
1804                 )
1805                         viewState = SaveViewStateRecursive ();
1806                 
1807                 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1808                 if (viewState != null || reqPostback != null)
1809                         vsr = new Pair (viewState, reqPostback);
1810
1811                 Pair pair = new Pair ();
1812                 pair.First = vsr;
1813                 pair.Second = controlState;
1814                 if (pair.First == null && pair.Second == null)
1815                         SavePageStateToPersistenceMedium (null);
1816                 else
1817                         SavePageStateToPersistenceMedium (pair);
1818
1819         }
1820
1821         public virtual void Validate ()
1822         {
1823                 is_validated = true;
1824                 ValidateCollection (_validators);
1825         }
1826
1827         internal bool AreValidatorsUplevel ()
1828         {
1829                 return AreValidatorsUplevel (String.Empty);
1830         }
1831
1832         internal bool AreValidatorsUplevel (string valGroup)
1833         {
1834                 bool uplevel = false;
1835
1836                 foreach (IValidator v in Validators) {
1837                         BaseValidator bv = v as BaseValidator;
1838                         if (bv == null)
1839                                 continue;
1840
1841                         if (valGroup != bv.ValidationGroup)
1842                                 continue;
1843                         if (bv.GetRenderUplevel()) {
1844                                 uplevel = true;
1845                                 break;
1846                         }
1847                 }
1848
1849                 return uplevel;
1850         }
1851
1852         bool ValidateCollection (ValidatorCollection validators)
1853         {
1854                 if (validators == null || validators.Count == 0)
1855                         return true;
1856
1857                 bool all_valid = true;
1858                 foreach (IValidator v in validators){
1859                         v.Validate ();
1860                         if (v.IsValid == false)
1861                                 all_valid = false;
1862                 }
1863
1864                 return all_valid;
1865         }
1866
1867         [EditorBrowsable (EditorBrowsableState.Advanced)]
1868         public virtual void VerifyRenderingInServerForm (Control control)
1869         {
1870                 if (Context == null)
1871                         return;
1872                 if (IsCallback)
1873                         return;
1874                 if (!renderingForm)
1875                         throw new HttpException ("Control '" +
1876                                                  control.ClientID +
1877                                                  "' of type '" +
1878                                                  control.GetType ().Name +
1879                                                  "' must be placed inside a form tag with runat=server.");
1880         }
1881
1882         protected override void FrameworkInitialize ()
1883         {
1884                 base.FrameworkInitialize ();
1885                 InitializeStyleSheet ();
1886         }
1887 #endregion
1888         
1889         public ClientScriptManager ClientScript {
1890                 get { return scriptManager; }
1891         }
1892
1893         internal static readonly object InitCompleteEvent = new object ();
1894         internal static readonly object LoadCompleteEvent = new object ();
1895         internal static readonly object PreInitEvent = new object ();
1896         internal static readonly object PreLoadEvent = new object ();
1897         internal static readonly object PreRenderCompleteEvent = new object ();
1898         internal static readonly object SaveStateCompleteEvent = new object ();
1899         int event_mask;
1900         const int initcomplete_mask = 1;
1901         const int loadcomplete_mask = 1 << 1;
1902         const int preinit_mask = 1 << 2;
1903         const int preload_mask = 1 << 3;
1904         const int prerendercomplete_mask = 1 << 4;
1905         const int savestatecomplete_mask = 1 << 5;
1906         
1907         [EditorBrowsable (EditorBrowsableState.Advanced)]
1908         public event EventHandler InitComplete {
1909                 add {
1910                         event_mask |= initcomplete_mask;
1911                         Events.AddHandler (InitCompleteEvent, value);
1912                 }
1913                 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1914         }
1915         
1916         [EditorBrowsable (EditorBrowsableState.Advanced)]
1917         public event EventHandler LoadComplete {
1918                 add {
1919                         event_mask |= loadcomplete_mask;
1920                         Events.AddHandler (LoadCompleteEvent, value);
1921                 }
1922                 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1923         }
1924         
1925         public event EventHandler PreInit {
1926                 add {
1927                         event_mask |= preinit_mask;
1928                         Events.AddHandler (PreInitEvent, value);
1929                 }
1930                 remove { Events.RemoveHandler (PreInitEvent, value); }
1931         }
1932         
1933         [EditorBrowsable (EditorBrowsableState.Advanced)]
1934         public event EventHandler PreLoad {
1935                 add {
1936                         event_mask |= preload_mask;
1937                         Events.AddHandler (PreLoadEvent, value);
1938                 }
1939                 remove { Events.RemoveHandler (PreLoadEvent, value); }
1940         }
1941         
1942         [EditorBrowsable (EditorBrowsableState.Advanced)]
1943         public event EventHandler PreRenderComplete {
1944                 add {
1945                         event_mask |= prerendercomplete_mask;
1946                         Events.AddHandler (PreRenderCompleteEvent, value);
1947                 }
1948                 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1949         }
1950         
1951         [EditorBrowsable (EditorBrowsableState.Advanced)]
1952         public event EventHandler SaveStateComplete {
1953                 add {
1954                         event_mask |= savestatecomplete_mask;
1955                         Events.AddHandler (SaveStateCompleteEvent, value);
1956                 }
1957                 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1958         }
1959         
1960         protected virtual void OnInitComplete (EventArgs e)
1961         {
1962                 if ((event_mask & initcomplete_mask) != 0) {
1963                         EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1964                         if (eh != null) eh (this, e);
1965                 }
1966         }
1967         
1968         protected virtual void OnLoadComplete (EventArgs e)
1969         {
1970                 if ((event_mask & loadcomplete_mask) != 0) {
1971                         EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1972                         if (eh != null) eh (this, e);
1973                 }
1974         }
1975         
1976         protected virtual void OnPreInit (EventArgs e)
1977         {
1978                 if ((event_mask & preinit_mask) != 0) {
1979                         EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1980                         if (eh != null) eh (this, e);
1981                 }
1982         }
1983         
1984         protected virtual void OnPreLoad (EventArgs e)
1985         {
1986                 if ((event_mask & preload_mask) != 0) {
1987                         EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1988                         if (eh != null) eh (this, e);
1989                 }
1990         }
1991         
1992         protected virtual void OnPreRenderComplete (EventArgs e)
1993         {
1994                 if ((event_mask & prerendercomplete_mask) != 0) {
1995                         EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1996                         if (eh != null) eh (this, e);
1997                 }
1998
1999                 if (Form == null)
2000                         return;
2001                 if (!Form.DetermineRenderUplevel ())
2002                         return;
2003
2004                 string defaultButtonId = Form.DefaultButton;
2005                 /* figure out if we have some control we're going to focus */
2006                 if (String.IsNullOrEmpty (_focusedControlID)) {
2007                         _focusedControlID = Form.DefaultFocus;
2008                         if (String.IsNullOrEmpty (_focusedControlID))
2009                                 _focusedControlID = defaultButtonId;
2010                 }
2011
2012                 if (!String.IsNullOrEmpty (_focusedControlID)) {
2013                         ClientScript.RegisterWebFormClientScript ();
2014                         
2015                         ClientScript.RegisterStartupScript (
2016                                 typeof(Page),
2017                                 "HtmlForm-DefaultButton-StartupScript",
2018                                 "\n" + WebFormScriptReference + ".WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
2019                 }
2020                 
2021                 if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
2022                         ClientScript.RegisterWebFormClientScript ();
2023
2024                         ClientScript.RegisterOnSubmitStatement (
2025                                 typeof (Page),
2026                                 "HtmlForm-SubmitDisabledControls-SubmitStatement",
2027                                 WebFormScriptReference + ".WebForm_ReEnableControls();");
2028                 }
2029         }
2030
2031         internal void RegisterEnabledControl (Control control)
2032         {
2033                 if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
2034                         return;
2035                 _hasEnabledControlArray = true;
2036                 Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
2037         }
2038         
2039         protected virtual void OnSaveStateComplete (EventArgs e)
2040         {
2041                 if ((event_mask & savestatecomplete_mask) != 0) {
2042                         EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
2043                         if (eh != null) eh (this, e);
2044                 }
2045         }
2046         
2047         public HtmlForm Form {
2048                 get { return _form; }
2049         }
2050         
2051         internal void RegisterForm (HtmlForm form)
2052         {
2053                 _form = form;
2054         }
2055
2056         public string ClientQueryString {
2057                 get { return Request.UrlComponents.Query; }
2058         }
2059
2060         [BrowsableAttribute (false)]
2061         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2062         public Page PreviousPage {
2063                 get {
2064                         if (_doLoadPreviousPage) {
2065                                 _doLoadPreviousPage = false;
2066                                 LoadPreviousPageReference ();
2067                         }
2068                         return previousPage;
2069                 }
2070         }
2071
2072         
2073         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2074         [BrowsableAttribute (false)]
2075         public bool IsCallback {
2076                 get { return isCallback; }
2077         }
2078         
2079         [BrowsableAttribute (false)]
2080         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2081         public bool IsCrossPagePostBack {
2082                 get { return isCrossPagePostBack; }
2083         }
2084
2085         [Browsable (false)]
2086         [EditorBrowsable (EditorBrowsableState.Never)]
2087         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2088         public new virtual char IdSeparator {
2089                 get {
2090                         //TODO: why override?
2091                         return base.IdSeparator;
2092                 }
2093         }
2094         
2095         string ProcessCallbackData ()
2096         {
2097                 ICallbackEventHandler target = GetCallbackTarget ();
2098                 string callbackEventError = String.Empty;
2099                 ProcessRaiseCallbackEvent (target, ref callbackEventError);
2100                 return ProcessGetCallbackResult (target, callbackEventError);
2101         }
2102
2103         ICallbackEventHandler GetCallbackTarget ()
2104         {
2105                 string callbackTarget = _requestValueCollection [CallbackSourceID];
2106                 if (callbackTarget == null || callbackTarget.Length == 0)
2107                         throw new HttpException ("Callback target not provided.");
2108
2109                 Control targetControl = FindControl (callbackTarget, true);
2110                 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
2111                 if (target == null)
2112                         throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
2113                 return target;
2114         }
2115
2116         void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError)
2117         {
2118                 string callbackArgument = _requestValueCollection [CallbackArgumentID];
2119
2120                 try {
2121                         target.RaiseCallbackEvent (callbackArgument);
2122                 } catch (Exception ex) {
2123                         callbackEventError = String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2124                 }
2125                 
2126         }
2127
2128         string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError)
2129         {
2130                 string callBackResult;
2131                 try {
2132                         callBackResult = target.GetCallbackResult ();
2133                 } catch (Exception ex) {
2134                         return String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
2135                 }
2136                 
2137                 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
2138                 return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
2139                         eventValidation + callBackResult;
2140         }
2141
2142         [BrowsableAttribute (false)]
2143         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2144         public HtmlHead Header {
2145                 get { return htmlHeader; }
2146         }
2147         
2148         internal void SetHeader (HtmlHead header)
2149         {
2150                 htmlHeader = header;
2151                 if (header == null)
2152                         return;
2153                 
2154                 if (_title != null) {
2155                         htmlHeader.Title = _title;
2156                         _title = null;
2157                 }
2158 #if NET_4_0
2159                 if (_metaDescription != null) {
2160                         htmlHeader.Description = _metaDescription;
2161                         _metaDescription = null;
2162                 }
2163
2164                 if (_metaKeywords != null) {
2165                         htmlHeader.Keywords = _metaKeywords;
2166                         _metaKeywords = null;
2167                 }
2168 #endif
2169         }
2170
2171         [EditorBrowsable (EditorBrowsableState.Never)]
2172         protected bool AsyncMode {
2173                 get { return asyncMode; }
2174                 set { asyncMode = value; }
2175         }
2176
2177         [Browsable (false)]
2178         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2179         [EditorBrowsable (EditorBrowsableState.Advanced)]
2180         public TimeSpan AsyncTimeout {
2181                 get { return asyncTimeout; }
2182                 set { asyncTimeout = value; }
2183         }
2184
2185         public bool IsAsync {
2186                 get { return AsyncMode; }
2187         }       
2188
2189         protected internal virtual string UniqueFilePathSuffix {
2190                 get {
2191                         if (String.IsNullOrEmpty (uniqueFilePathSuffix))
2192                                 uniqueFilePathSuffix = "__ufps=" + AppRelativeVirtualPath.GetHashCode ().ToString ("x");
2193                         return uniqueFilePathSuffix;
2194                 }
2195         }
2196
2197         [MonoTODO ("Actually use the value in code.")]
2198         [Browsable (false)]
2199         [EditorBrowsable (EditorBrowsableState.Never)]
2200         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2201         public int MaxPageStateFieldLength {
2202                 get { return maxPageStateFieldLength; }
2203                 set { maxPageStateFieldLength = value; }
2204         }
2205
2206         public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
2207         {
2208                 AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
2209         }
2210
2211         public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
2212         {
2213                 if (!IsAsync) {
2214                         throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
2215                 }
2216
2217                 if (IsPrerendered) {
2218                         throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
2219                 }
2220
2221                 if (beginHandler == null) {
2222                         throw new ArgumentNullException ("beginHandler");
2223                 }
2224
2225                 if (endHandler == null) {
2226                         throw new ArgumentNullException ("endHandler");
2227                 }
2228
2229                 RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
2230         }
2231
2232         List<PageAsyncTask> ParallelTasks {
2233                 get {
2234                         if (parallelTasks == null)
2235                                 parallelTasks = new List<PageAsyncTask>();
2236                         return parallelTasks;
2237                 }
2238         }
2239
2240         List<PageAsyncTask> SerialTasks {
2241                 get {
2242                         if (serialTasks == null)
2243                                 serialTasks = new List<PageAsyncTask> ();
2244                         return serialTasks;
2245                 }
2246         }
2247
2248         public void RegisterAsyncTask (PageAsyncTask task) 
2249         {
2250                 if (task == null)
2251                         throw new ArgumentNullException ("task");
2252
2253                 if (task.ExecuteInParallel)
2254                         ParallelTasks.Add (task);
2255                 else
2256                         SerialTasks.Add (task);
2257         }
2258
2259         public void ExecuteRegisteredAsyncTasks ()
2260         {
2261                 if ((parallelTasks == null || parallelTasks.Count == 0) &&
2262                         (serialTasks == null || serialTasks.Count == 0)){
2263                         return;
2264                 }
2265
2266                 if (parallelTasks != null) {
2267                         DateTime startExecution = DateTime.Now;
2268                         List<PageAsyncTask> localParallelTasks = parallelTasks;
2269                         parallelTasks = null; // Shouldn't execute tasks twice
2270                         List<IAsyncResult> asyncResults = new List<IAsyncResult>();
2271                         foreach (PageAsyncTask parallelTask in localParallelTasks) {
2272                                 IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
2273                                 if (result.CompletedSynchronously)
2274                                         parallelTask.EndHandler (result);
2275                                 else
2276                                         asyncResults.Add (result);
2277                         }
2278
2279                         if (asyncResults.Count > 0) {
2280 #if TARGET_JVM
2281                                 TimeSpan timeout = AsyncTimeout;
2282                                 long t1 = DateTime.Now.Ticks;
2283                                 bool signalled = true;
2284                                 for (int i = 0; i < asyncResults.Count; i++) {
2285                                         if (asyncResults [i].IsCompleted)
2286                                                 continue;
2287
2288                                         if (signalled)
2289                                                 signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
2290
2291                                         if (signalled) {
2292                                                 long t2 = DateTime.Now.Ticks;
2293                                                 timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
2294                                                 if (timeout.Ticks <= 0)
2295                                                         signalled = false;
2296                                         } else
2297                                                 localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2298                                 }
2299 #else
2300                                 WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
2301                                 int i = 0;
2302                                 for (i = 0; i < asyncResults.Count; i++) {
2303                                         waitArray [i] = asyncResults [i].AsyncWaitHandle;
2304                                 }
2305                                 
2306                                 bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
2307                                 if (!allSignalled) {
2308                                         for (i = 0; i < asyncResults.Count; i++) {
2309                                                 if (!asyncResults [i].IsCompleted) {
2310                                                         localParallelTasks [i].TimeoutHandler (asyncResults [i]);
2311                                                 }
2312                                         }
2313                                 }
2314 #endif
2315                         }
2316                         DateTime endWait = DateTime.Now;
2317                         TimeSpan elapsed = endWait - startExecution;
2318                         if (elapsed <= AsyncTimeout)
2319                                 AsyncTimeout -= elapsed;
2320                         else
2321                                 AsyncTimeout = TimeSpan.FromTicks(0);
2322                 }
2323
2324                 if (serialTasks != null) {
2325                         List<PageAsyncTask> localSerialTasks = serialTasks;
2326                         serialTasks = null; // Shouldn't execute tasks twice
2327                         foreach (PageAsyncTask serialTask in localSerialTasks) {
2328                                 DateTime startExecution = DateTime.Now;
2329
2330                                 IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
2331                                 if (result.CompletedSynchronously)
2332                                         serialTask.EndHandler (result);
2333                                 else {
2334                                         bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
2335                                         if (!done && !result.IsCompleted) {
2336                                                 serialTask.TimeoutHandler (result);
2337                                         }
2338                                 }
2339                                 DateTime endWait = DateTime.Now;
2340                                 TimeSpan elapsed = endWait - startExecution;
2341                                 if (elapsed <= AsyncTimeout)
2342                                         AsyncTimeout -= elapsed;
2343                                 else
2344                                         AsyncTimeout = TimeSpan.FromTicks (0);
2345                         }
2346                 }
2347                 AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
2348         }
2349
2350         void EndAsyncTaskCallback (IAsyncResult result) 
2351         {
2352                 PageAsyncTask task = (PageAsyncTask)result.AsyncState;
2353                 task.EndHandler (result);
2354         }
2355
2356         public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
2357         {
2358                 Type htmlTextWriterType = typeof (HtmlTextWriter);
2359                 
2360                 if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
2361                         throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
2362                 }
2363
2364                 ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
2365                 if (constructor == null) {
2366                         throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
2367                 }
2368
2369                 return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
2370         }
2371
2372         [Browsable (false)]
2373         [DefaultValue ("0")]
2374         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2375         [EditorBrowsable (EditorBrowsableState.Never)]
2376         public ViewStateEncryptionMode ViewStateEncryptionMode {
2377                 get { return viewStateEncryptionMode; }
2378                 set { viewStateEncryptionMode = value; }
2379         }
2380
2381         public void RegisterRequiresViewStateEncryption ()
2382         {
2383                 controlRegisteredForViewStateEncryption = true;
2384         }
2385
2386         internal bool NeedViewStateEncryption {
2387                 get {
2388                         return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
2389                                         (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
2390                                          controlRegisteredForViewStateEncryption));
2391
2392                 }
2393         }
2394
2395         void ApplyMasterPage ()
2396         {
2397                 if (masterPageFile != null && masterPageFile.Length > 0) {
2398                         MasterPage master = Master;
2399                         
2400                         if (master != null) {
2401                                 var appliedMasterPageFiles = new Dictionary <string, bool> (StringComparer.Ordinal);
2402                                 MasterPage.ApplyMasterPageRecursive (Request.CurrentExecutionFilePath, HostingEnvironment.VirtualPathProvider, master, appliedMasterPageFiles);
2403                                 master.Page = this;
2404                                 Controls.Clear ();
2405                                 Controls.Add (master);
2406                         }
2407                 }
2408         }
2409
2410         [DefaultValueAttribute ("")]
2411         public virtual string MasterPageFile {
2412                 get { return masterPageFile; }
2413                 set {
2414                         masterPageFile = value;
2415                         masterPage = null;
2416                 }
2417         }
2418         
2419         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2420         [BrowsableAttribute (false)]
2421         public MasterPage Master {
2422                 get {
2423                         if (Context == null || String.IsNullOrEmpty (masterPageFile))
2424                                 return null;
2425
2426                         if (masterPage == null)
2427                                 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2428
2429                         return masterPage;
2430                 }
2431         }
2432         
2433         public void SetFocus (string clientID)
2434         {
2435                 if (String.IsNullOrEmpty (clientID))
2436                         throw new ArgumentNullException ("control");
2437
2438                 if (IsPrerendered)
2439                         throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2440
2441                 if(Form==null)
2442                         throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2443
2444                 _focusedControlID = clientID;
2445         }
2446
2447         public void SetFocus (Control control)
2448         {
2449                 if (control == null)
2450                         throw new ArgumentNullException ("control");
2451
2452                 SetFocus (control.ClientID);
2453         }
2454         
2455         [EditorBrowsable (EditorBrowsableState.Advanced)]
2456         public void RegisterRequiresControlState (Control control)
2457         {
2458                 if (control == null)
2459                         throw new ArgumentNullException ("control");
2460
2461                 if (RequiresControlState (control))
2462                         return;
2463
2464                 if (requireStateControls == null)
2465                         requireStateControls = new List <Control> ();
2466                 requireStateControls.Add (control);
2467                 int n = requireStateControls.Count - 1;
2468                 
2469                 if (_savedControlState == null || n >= _savedControlState.Length) 
2470                         return;
2471
2472                 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2473                         if (parent.IsChildControlStateCleared)
2474                                 return;
2475
2476                 object state = _savedControlState [n];
2477                 if (state != null)
2478                         control.LoadControlState (state);
2479         }
2480         
2481         public bool RequiresControlState (Control control)
2482         {
2483                 if (requireStateControls == null)
2484                         return false;
2485                 return requireStateControls.Contains (control);
2486         }
2487         
2488         [EditorBrowsable (EditorBrowsableState.Advanced)]
2489         public void UnregisterRequiresControlState (Control control)
2490         {
2491                 if (requireStateControls != null)
2492                         requireStateControls.Remove (control);
2493         }
2494         
2495         public ValidatorCollection GetValidators (string validationGroup)
2496         {                       
2497                 if (validationGroup == String.Empty)
2498                         validationGroup = null;
2499
2500                 ValidatorCollection col = new ValidatorCollection ();
2501                 if (_validators == null)
2502                         return col;
2503                 
2504                 foreach (IValidator v in _validators)
2505                         if (BelongsToGroup(v, validationGroup))
2506                                 col.Add(v);
2507
2508                 return col;
2509         }
2510         
2511         bool BelongsToGroup(IValidator v, string validationGroup)
2512         {
2513                 BaseValidator validator = v as BaseValidator;
2514                 if (validationGroup == null)
2515                         return validator == null || String.IsNullOrEmpty (validator.ValidationGroup); 
2516                 else
2517                         return validator != null && validator.ValidationGroup == validationGroup;                       
2518         }
2519         
2520         public virtual void Validate (string validationGroup)
2521         {
2522                 is_validated = true;
2523                 ValidateCollection (GetValidators (validationGroup));
2524         }
2525
2526         object SavePageControlState ()
2527         {
2528                 int count = requireStateControls == null ? 0 : requireStateControls.Count;
2529                 if (count == 0)
2530                         return null;
2531                 
2532                 object state;
2533                 object[] controlStates = new object [count];
2534                 object[] adapterState = new object [count];
2535                 Control control;
2536                 ControlAdapter adapter;
2537                 bool allNull = true;
2538                 TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
2539                 
2540                 for (int n = 0; n < count; n++) {
2541                         control = requireStateControls [n];
2542                         state = controlStates [n] = control.SaveControlState ();
2543                         if (state != null)
2544                                 allNull = false;
2545                         
2546                         if (trace != null)
2547                                 trace.SaveControlState (control, state);
2548
2549                         adapter = control.Adapter;
2550                         if (adapter != null) {
2551                                 adapterState [n] = adapter.SaveAdapterControlState ();
2552                                 if (adapterState [n] != null) allNull = false;
2553                         }
2554                 }
2555                 
2556                 if (allNull)
2557                         return null;
2558                 else
2559                         return new Pair (controlStates, adapterState);
2560         }
2561         
2562         void LoadPageControlState (object data)
2563         {
2564                 _savedControlState = null;
2565                 if (data == null) return;
2566                 Pair statePair = (Pair)data;
2567                 _savedControlState = (object[]) statePair.First;
2568                 object[] adapterState = (object[]) statePair.Second;
2569
2570                 if (requireStateControls == null) return;
2571
2572                 int min = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2573                 for (int n=0; n < min; n++) {
2574                         Control ctl = (Control) requireStateControls [n];
2575                         ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2576                         if (ctl.Adapter != null)
2577                                 ctl.Adapter.LoadAdapterControlState (adapterState != null ? adapterState [n] : null);
2578                 }
2579         }
2580
2581         void LoadPreviousPageReference ()
2582         {
2583                 if (_requestValueCollection != null) {
2584                         string prevPage = _requestValueCollection [PreviousPageID];
2585                         if (prevPage != null) {
2586 #if TARGET_J2EE
2587                                 if (getFacesContext () != null) {
2588                                         IHttpHandler handler = Context.ApplicationInstance.GetHandler (Context, prevPage);
2589                                         Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2590                                         if (_context.Items.Contains (CrossPagePostBack)) {
2591                                                 previousPage = (Page) _context.Items [CrossPagePostBack];
2592                                                 _context.Items.Remove (CrossPagePostBack);
2593                                         }
2594                                         return;
2595                                 }
2596 #else
2597                                 IHttpHandler handler;
2598                                 handler = BuildManager.CreateInstanceFromVirtualPath (prevPage, typeof (IHttpHandler)) as IHttpHandler;
2599                                 previousPage = (Page) handler;
2600                                 previousPage.isCrossPagePostBack = true;
2601                                 Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
2602 #endif
2603                         } 
2604                 }
2605         }
2606
2607         Hashtable contentTemplates;
2608         [EditorBrowsable (EditorBrowsableState.Never)]
2609         protected internal void AddContentTemplate (string templateName, ITemplate template)
2610         {
2611                 if (contentTemplates == null)
2612                         contentTemplates = new Hashtable ();
2613                 contentTemplates [templateName] = template;
2614         }
2615
2616         PageTheme _pageTheme;
2617         internal PageTheme PageTheme {
2618                 get { return _pageTheme; }
2619         }
2620
2621         PageTheme _styleSheetPageTheme;
2622         internal PageTheme StyleSheetPageTheme {
2623                 get { return _styleSheetPageTheme; }
2624         }
2625
2626         Stack dataItemCtx;
2627         
2628         internal void PushDataItemContext (object o) {
2629                 if (dataItemCtx == null)
2630                         dataItemCtx = new Stack ();
2631                 
2632                 dataItemCtx.Push (o);
2633         }
2634         
2635         internal void PopDataItemContext () {
2636                 if (dataItemCtx == null)
2637                         throw new InvalidOperationException ();
2638                 
2639                 dataItemCtx.Pop ();
2640         }
2641         
2642         public object GetDataItem() {
2643                 if (dataItemCtx == null || dataItemCtx.Count == 0)
2644                         throw new InvalidOperationException ("No data item");
2645                 
2646                 return dataItemCtx.Peek ();
2647         }
2648
2649         void AddStyleSheets (PageTheme theme, ref List <string> links)
2650         {
2651                 if (theme == null)
2652                         return;
2653
2654                 string[] tmpThemes = theme != null ? theme.GetStyleSheets () : null;
2655                 if (tmpThemes == null || tmpThemes.Length == 0)
2656                         return;
2657
2658                 if (links == null)
2659                         links = new List <string> ();
2660
2661                 links.AddRange (tmpThemes);
2662         }
2663         
2664         protected internal override void OnInit (EventArgs e)
2665         {
2666                 base.OnInit (e);
2667
2668                 List <string> themes = null;
2669                 AddStyleSheets (StyleSheetPageTheme, ref themes);
2670                 AddStyleSheets (PageTheme, ref themes);
2671
2672                 if (themes == null)
2673                         return;
2674                 
2675                 HtmlHead header = Header;
2676                 if (themes != null && header == null)
2677                         throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
2678                 
2679                 ControlCollection headerControls = header.Controls;
2680                 string lss;
2681                 for (int i = themes.Count - 1; i >= 0; i--) {
2682                         lss = themes [i];
2683                         HtmlLink hl = new HtmlLink ();
2684                         hl.Href = lss;
2685                         hl.Attributes["type"] = "text/css";
2686                         hl.Attributes["rel"] = "stylesheet";
2687                         headerControls.AddAt (0, hl);
2688                 }
2689         }
2690
2691         [MonoDocumentationNote ("Not implemented.  Only used by .net aspx parser")]
2692         [EditorBrowsable (EditorBrowsableState.Never)]
2693         protected object GetWrappedFileDependencies (string [] list)
2694         {
2695                 return list;
2696         }
2697
2698         [MonoDocumentationNote ("Does nothing.  Used by .net aspx parser")]
2699         protected virtual void InitializeCulture ()
2700         {
2701         }
2702
2703         [MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
2704         [EditorBrowsable (EditorBrowsableState.Never)]
2705         protected internal void AddWrappedFileDependencies (object virtualFileDependencies)
2706         {
2707         }
2708 }
2709 }