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