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