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