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