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