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