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