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