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