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