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