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