Make sure to create specific cultures.
[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 = CultureInfo.CreateSpecificCulture (languages[0]);
714                         } catch {
715                         }
716                         
717                         if (ret == null)
718                                 ret = deflt;
719                 } else
720                         ret = CultureInfo.CreateSpecificCulture (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                         ClientScript.RegisterWebFormClientScript ();
947
948                         ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
949                         ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
950                         
951                         StringBuilder script = new StringBuilder ();
952                         script.AppendLine ("<script type=\"text/javascript\">");
953                         script.AppendLine ("<!--");
954                         script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
955                         script.AppendLine (theForm + ".submit = WebForm_SaveScrollPositionSubmit;");
956                         script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
957                         script.AppendLine (theForm + ".onsubmit = WebForm_SaveScrollPositionOnSubmit;");
958                         if (IsPostBack) {
959                                 script.AppendLine (theForm + ".oldOnLoad = window.onload;");
960                                 script.AppendLine ("window.onload = function () { WebForm_RestoreScrollPosition (" + theForm + "); };");
961                         }
962                         script.AppendLine ("// -->");
963                         script.AppendLine ("</script>");
964                         
965                         ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
966                 }
967                 base.Render (writer);
968         }
969 #endif
970
971         private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
972         {
973                 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
974                 writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
975                 writer.WriteLine ();
976                 writer.WriteLine ("<script language=\"javascript\">");
977                 writer.WriteLine ("<!--");
978
979                 writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
980                 writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
981                 writer.WriteLine ("\t{0}.isAspForm = true;", theForm);
982                 writer.WriteLine ("\tfunction __doPostBack(eventTarget, eventArgument) {");
983                 writer.WriteLine ("\t\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
984                 writer.WriteLine ("\t\tvar myForm = " + theForm + ";");
985 #if NET_2_0
986                 writer.WriteLine ("\t\tif(document.WebForm_GetFormFromCtrl) myForm = WebForm_GetFormFromCtrl (eventTarget);");
987 #endif
988                 writer.WriteLine ("\t\tmyForm.{0}.value = eventTarget;", postEventSourceID);
989                 writer.WriteLine ("\t\tmyForm.{0}.value = eventArgument;", postEventArgumentID);
990                 writer.WriteLine ("\t\tmyForm.submit();");
991                 writer.WriteLine ("\t}");
992                 writer.WriteLine ("// -->");
993                 writer.WriteLine ("</script>");
994         }
995
996         internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
997         {
998                 if (renderingForm)
999                         throw new HttpException ("Only 1 HtmlForm is allowed per page.");
1000
1001                 renderingForm = true;
1002                 writer.WriteLine ();
1003
1004                 if (handleViewState)
1005                         scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
1006
1007                 scriptManager.WriteHiddenFields (writer);
1008                 if (requiresPostBackScript) {
1009                         RenderPostBackScript (writer, formUniqueID);
1010                         postBackScriptRendered = true;
1011                 }
1012                 scriptManager.WriteClientScriptIncludes (writer);
1013                 scriptManager.WriteClientScriptBlocks (writer);
1014         }
1015
1016         internal IStateFormatter GetFormatter ()
1017         {
1018                 return new ObjectStateFormatter (this);
1019         }
1020
1021         internal string GetSavedViewState ()
1022         {
1023                 return _savedViewState;
1024         }
1025
1026         internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
1027         {
1028                 if (!postBackScriptRendered && requiresPostBackScript)
1029                         RenderPostBackScript (writer, formUniqueID);
1030
1031                 scriptManager.WriteArrayDeclares (writer);
1032                 
1033 #if NET_2_0
1034                 scriptManager.SaveEventValidationState ();
1035                 scriptManager.WriteExpandoAttributes (writer);
1036 #endif
1037                 scriptManager.WriteHiddenFields (writer);
1038                 scriptManager.WriteClientScriptIncludes (writer);
1039                 scriptManager.WriteStartupScriptBlocks (writer);
1040                 renderingForm = false;
1041                 postBackScriptRendered = false;
1042         }
1043
1044         private void ProcessPostData (NameValueCollection data, bool second)
1045         {
1046                 if (data != null) {
1047
1048                 Hashtable used = new Hashtable ();
1049                 foreach (string id in data.AllKeys){
1050                         if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
1051                                 continue;
1052
1053                         string real_id = id;
1054                         int dot = real_id.IndexOf ('.');
1055                         if (dot >= 1)
1056                                 real_id = real_id.Substring (0, dot);
1057                         
1058                         if (real_id == null || used.ContainsKey (real_id))
1059                                 continue;
1060
1061                         used.Add (real_id, real_id);
1062
1063                         Control ctrl = FindControl (real_id);
1064                         if (ctrl != null){
1065                                 IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
1066                                 IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
1067
1068                                 if (pbdh == null) {
1069                                         if (pbeh != null)
1070                                                 RegisterRequiresRaiseEvent (pbeh);
1071                                         continue;
1072                                 }
1073                 
1074                                 if (pbdh.LoadPostData (real_id, data) == true) {
1075                                         if (requiresPostDataChanged == null)
1076                                                 requiresPostDataChanged = new ArrayList ();
1077                                         requiresPostDataChanged.Add (pbdh);
1078                                 }
1079                                 
1080                                 if (_requiresPostBackCopy != null)
1081                                         _requiresPostBackCopy.Remove (real_id);
1082
1083                         } else if (!second) {
1084                                 if (secondPostData == null)
1085                                         secondPostData = new NameValueCollection ();
1086                                 secondPostData.Add (real_id, data [id]);
1087                         }
1088                 }
1089                 }
1090
1091                 ArrayList list1 = null;
1092                 if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
1093                         string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
1094                         foreach (string id in handlers) {
1095                                 IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
1096                                 if (pbdh != null) {                     
1097                                         _requiresPostBackCopy.Remove (id);
1098                                         if (pbdh.LoadPostData (id, data)) {
1099                                                 if (requiresPostDataChanged == null)
1100                                                         requiresPostDataChanged = new ArrayList ();
1101         
1102                                                 requiresPostDataChanged.Add (pbdh);
1103                                         }
1104                                 } else if (!second) {
1105                                         if (list1 == null)
1106                                                 list1 = new ArrayList ();
1107                                         list1.Add (id);
1108                                 }
1109                         }
1110                 }
1111                 _requiresPostBackCopy = second ? null : list1;
1112                 if (second)
1113                         secondPostData = null;
1114         }
1115
1116         [EditorBrowsable (EditorBrowsableState.Never)]
1117 #if NET_2_0 || TARGET_JVM
1118         public virtual void ProcessRequest (HttpContext context)
1119 #else
1120         public void ProcessRequest (HttpContext context)
1121 #endif
1122         {
1123 #if NET_2_0
1124                 _lifeCycle = PageLifeCycle.Unknown;
1125 #endif
1126                 _context = context;
1127                 if (clientTarget != null)
1128                         Request.ClientTarget = clientTarget;
1129
1130                 WireupAutomaticEvents ();
1131                 //-- Control execution lifecycle in the docs
1132
1133                 // Save culture information because it can be modified in FrameworkInitialize()
1134                 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
1135                 CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
1136                 FrameworkInitialize ();
1137                 context.ErrorPage = _errorPage;
1138
1139                 try {
1140                         InternalProcessRequest ();
1141                 } catch (ThreadAbortException) {
1142                         // Do nothing, just ignore it by now.
1143                 } catch (Exception e) {
1144                         context.AddError (e); // OnError might access LastError
1145                         OnError (EventArgs.Empty);
1146                         context.ClearError (e);
1147                         // We want to remove that error, as we're rethrowing to stop
1148                         // further processing.
1149                         Trace.Warn ("Unhandled Exception", e.ToString (), e);
1150                         throw;
1151                 } finally {
1152                         try {
1153 #if NET_2_0
1154                                 _lifeCycle = PageLifeCycle.Unload;
1155 #endif
1156                                 RenderTrace ();
1157                                 UnloadRecursive (true);
1158 #if NET_2_0
1159                                 _lifeCycle = PageLifeCycle.End;
1160 #endif
1161                         } catch {}
1162                         if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
1163                                 Thread.CurrentThread.CurrentCulture = culture;
1164
1165                         if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
1166                                 Thread.CurrentThread.CurrentUICulture = uiculture;
1167                 }
1168         }
1169         
1170 #if NET_2_0
1171         internal void ProcessCrossPagePostBack (HttpContext context)
1172         {
1173                 isCrossPagePostBack = true;
1174                 ProcessRequest (context);
1175         }
1176 #endif
1177
1178         void InternalProcessRequest ()
1179         {
1180                 _requestValueCollection = this.DeterminePostBackMode();
1181
1182 #if NET_2_0
1183                 _lifeCycle = PageLifeCycle.Start;
1184                 // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
1185                 if (_requestValueCollection != null) {
1186                         if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
1187                                 _doLoadPreviousPage = true;
1188                         }
1189                         else {
1190                                 isCallback = _requestValueCollection [CallbackArgumentID] != null;
1191                                 // LAMESPEC: on Callback IsPostBack is set to false, but true.
1192                                 //isPostBack = !isCallback;
1193                                 isPostBack = true;
1194                         }
1195                 }
1196                 
1197                 // if request was transfered from other page - track Prev. Page
1198                 previousPage = _context.LastPage;
1199                 _context.LastPage = this;
1200
1201                 _lifeCycle = PageLifeCycle.PreInit;
1202                 OnPreInit (EventArgs.Empty);
1203
1204                 InitializeTheme ();
1205                 ApplyMasterPage ();
1206                 _lifeCycle = PageLifeCycle.Init;
1207 #endif
1208                 Trace.Write ("aspx.page", "Begin Init");
1209                 InitRecursive (null);
1210                 Trace.Write ("aspx.page", "End Init");
1211
1212 #if NET_2_0
1213                 _lifeCycle = PageLifeCycle.InitComplete;
1214                 OnInitComplete (EventArgs.Empty);
1215 #endif
1216                         
1217                 renderingForm = false;  
1218 #if NET_2_0
1219                 if (IsPostBack || IsCallback) {
1220                         _lifeCycle = PageLifeCycle.PreLoad;
1221                         if (_requestValueCollection != null)
1222                                 scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
1223 #else
1224                 if (IsPostBack) {
1225 #endif
1226                         Trace.Write ("aspx.page", "Begin LoadViewState");
1227                         LoadPageViewState ();
1228                         Trace.Write ("aspx.page", "End LoadViewState");
1229                         Trace.Write ("aspx.page", "Begin ProcessPostData");
1230                         ProcessPostData (_requestValueCollection, false);
1231                         Trace.Write ("aspx.page", "End ProcessPostData");
1232                 }
1233
1234 #if NET_2_0
1235                 OnPreLoad (EventArgs.Empty);
1236                 _lifeCycle = PageLifeCycle.Load;
1237 #endif
1238
1239                 LoadRecursive ();
1240 #if NET_2_0
1241                 if (IsPostBack || IsCallback) {
1242                         _lifeCycle = PageLifeCycle.ControlEvents;
1243 #else
1244                 if (IsPostBack) {
1245 #endif
1246                         Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
1247                         ProcessPostData (secondPostData, true);
1248                         Trace.Write ("aspx.page", "End ProcessPostData Second Try");
1249                         Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
1250                         RaiseChangedEvents ();
1251                         Trace.Write ("aspx.page", "End Raise ChangedEvents");
1252                         Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
1253                         RaisePostBackEvents ();
1254                         Trace.Write ("aspx.page", "End Raise PostBackEvent");
1255                 }
1256                 
1257 #if NET_2_0
1258                 _lifeCycle = PageLifeCycle.LoadComplete;
1259                 OnLoadComplete (EventArgs.Empty);
1260
1261                 if (IsCrossPagePostBack)
1262                         return;
1263
1264                 if (IsCallback) {
1265                         string result = ProcessCallbackData ();
1266                         HtmlTextWriter callbackOutput = new HtmlTextWriter (_context.Response.Output);
1267                         callbackOutput.Write (result);
1268                         callbackOutput.Flush ();
1269                         return;
1270                 }
1271
1272                 _lifeCycle = PageLifeCycle.PreRender;
1273 #endif
1274                 
1275                 Trace.Write ("aspx.page", "Begin PreRender");
1276                 PreRenderRecursiveInternal ();
1277                 Trace.Write ("aspx.page", "End PreRender");
1278                 
1279 #if NET_2_0
1280                 _lifeCycle = PageLifeCycle.PreRenderComplete;
1281                 OnPreRenderComplete (EventArgs.Empty);
1282 #endif
1283
1284                 Trace.Write ("aspx.page", "Begin SaveViewState");
1285                 SavePageViewState ();
1286                 Trace.Write ("aspx.page", "End SaveViewState");
1287                 
1288 #if NET_2_0
1289                 _lifeCycle = PageLifeCycle.SaveStateComplete;
1290                 OnSaveStateComplete (EventArgs.Empty);
1291 #endif
1292
1293 #if TARGET_J2EE
1294                 if (SaveViewStateForNextPortletRender())
1295                         return;
1296 #endif
1297
1298 #if NET_2_0
1299                 _lifeCycle = PageLifeCycle.Render;
1300 #endif
1301                 
1302                 //--
1303                 Trace.Write ("aspx.page", "Begin Render");
1304                 HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1305                 RenderControl (output);
1306                 Trace.Write ("aspx.page", "End Render");
1307         }
1308
1309         private void RenderTrace ()
1310         {
1311                 TraceManager traceManager = HttpRuntime.TraceManager;
1312
1313                 if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
1314                         return;
1315                 
1316                 Trace.SaveData ();
1317
1318                 if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput) 
1319                         return;
1320
1321                 if (!traceManager.LocalOnly || Context.Request.IsLocal) {
1322                         HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
1323                         Trace.Render (output);
1324                 }
1325         }
1326         
1327 #if NET_2_0
1328         bool CheckForValidationSupport (Control targetControl)
1329         {
1330                 if (targetControl == null)
1331                         return false;
1332                 Type type = targetControl.GetType ();
1333                 object[] attributes = type.GetCustomAttributes (false);
1334                 foreach (object attr in attributes)
1335                         if (attr is SupportsEventValidationAttribute)
1336                                 return true;
1337                 return false;
1338         }
1339 #endif
1340         
1341         void RaisePostBackEvents ()
1342         {
1343 #if NET_2_0
1344                 Control targetControl;
1345 #endif
1346                 if (requiresRaiseEvent != null) {
1347                         RaisePostBackEvent (requiresRaiseEvent, null);
1348                         return;
1349                 }
1350
1351                 NameValueCollection postdata = _requestValueCollection;
1352                 if (postdata == null)
1353                         return;
1354
1355                 string eventTarget = postdata [postEventSourceID];
1356                 if (eventTarget == null || eventTarget.Length == 0) {
1357                         Validate ();
1358                         return;
1359                 }
1360
1361 #if NET_2_0
1362                 targetControl = FindControl (eventTarget);
1363                 IPostBackEventHandler target = targetControl as IPostBackEventHandler;
1364 #else
1365                 IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
1366 #endif
1367                         
1368                 if (target == null)
1369                         return;
1370
1371                 string eventArgument = postdata [postEventArgumentID];
1372                 RaisePostBackEvent (target, eventArgument);
1373         }
1374
1375         internal void RaiseChangedEvents ()
1376         {
1377                 if (requiresPostDataChanged == null)
1378                         return;
1379
1380                 foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
1381                         ipdh.RaisePostDataChangedEvent ();
1382
1383                 requiresPostDataChanged = null;
1384         }
1385
1386         [EditorBrowsable (EditorBrowsableState.Advanced)]
1387         protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
1388         {
1389 #if NET_2_0
1390                 Control targetControl = sourceControl as Control;
1391                 if (targetControl != null && CheckForValidationSupport (targetControl))
1392                         scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
1393 #endif
1394                 sourceControl.RaisePostBackEvent (eventArgument);
1395         }
1396         
1397 #if NET_2_0
1398         [Obsolete]
1399 #endif
1400         [EditorBrowsable (EditorBrowsableState.Advanced)]
1401         public void RegisterArrayDeclaration (string arrayName, string arrayValue)
1402         {
1403                 scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
1404         }
1405
1406 #if NET_2_0
1407         [Obsolete]
1408 #endif
1409         [EditorBrowsable (EditorBrowsableState.Advanced)]
1410         public virtual void RegisterClientScriptBlock (string key, string script)
1411         {
1412                 scriptManager.RegisterClientScriptBlock (key, script);
1413         }
1414
1415 #if NET_2_0
1416         [Obsolete]
1417 #endif
1418         [EditorBrowsable (EditorBrowsableState.Advanced)]
1419         public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
1420         {
1421                 scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
1422         }
1423
1424         [MonoTODO("Not implemented, Used in HtmlForm")]
1425         internal void RegisterClientScriptFile (string a, string b, string c)
1426         {
1427                 throw new NotImplementedException ();
1428         }
1429
1430 #if NET_2_0
1431         [Obsolete]
1432 #endif
1433         [EditorBrowsable (EditorBrowsableState.Advanced)]
1434         public void RegisterOnSubmitStatement (string key, string script)
1435         {
1436                 scriptManager.RegisterOnSubmitStatement (key, script);
1437         }
1438
1439         internal string GetSubmitStatements ()
1440         {
1441                 return scriptManager.WriteSubmitStatements ();
1442         }
1443
1444         [EditorBrowsable (EditorBrowsableState.Advanced)]
1445         public void RegisterRequiresPostBack (Control control)
1446         {
1447                 if (_requiresPostBack == null)
1448                         _requiresPostBack = new ArrayList ();
1449
1450                 if (_requiresPostBack.Contains (control.UniqueID))
1451                         return;
1452
1453                 _requiresPostBack.Add (control.UniqueID);
1454         }
1455
1456         [EditorBrowsable (EditorBrowsableState.Advanced)]
1457         public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
1458         {
1459                 requiresRaiseEvent = control;
1460         }
1461
1462 #if NET_2_0
1463         [Obsolete]
1464 #endif
1465         [EditorBrowsable (EditorBrowsableState.Advanced)]
1466         public virtual void RegisterStartupScript (string key, string script)
1467         {
1468                 scriptManager.RegisterStartupScript (key, script);
1469         }
1470
1471         [EditorBrowsable (EditorBrowsableState.Advanced)]
1472         public void RegisterViewStateHandler ()
1473         {
1474                 handleViewState = true;
1475         }
1476
1477         [EditorBrowsable (EditorBrowsableState.Advanced)]
1478         protected virtual void SavePageStateToPersistenceMedium (object viewState)
1479         {
1480                 PageStatePersister persister = this.PageStatePersister;
1481                 if (persister == null)
1482                         return;
1483                 Pair pair = viewState as Pair;
1484                 if (pair != null) {
1485                         persister.ViewState = pair.First;
1486                         persister.ControlState = pair.Second;
1487                 } else
1488                         persister.ViewState = viewState;
1489                 persister.Save ();
1490         }
1491
1492         internal string RawViewState {
1493                 get {
1494                         NameValueCollection postdata = _requestValueCollection;
1495                         string view_state;
1496                         if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
1497                                 return null;
1498
1499                         if (view_state == "")
1500                                 return null;
1501                         return view_state;
1502                 }
1503                 set { _savedViewState = value; }
1504         }
1505
1506 #if NET_2_0
1507         protected virtual 
1508 #else
1509         internal
1510 #endif
1511         PageStatePersister PageStatePersister {
1512                 get {
1513                         if (page_state_persister == null)
1514                                 page_state_persister = new HiddenFieldPageStatePersister (this);
1515                         return page_state_persister;
1516                 }
1517         }
1518         
1519         [EditorBrowsable (EditorBrowsableState.Advanced)]
1520         protected virtual object LoadPageStateFromPersistenceMedium ()
1521         {
1522                 PageStatePersister persister = this.PageStatePersister;
1523                 if (persister == null)
1524                         return null;
1525                 persister.Load ();
1526                 return new Pair (persister.ViewState, persister.ControlState);
1527         }
1528
1529         internal void LoadPageViewState()
1530         {
1531                 Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
1532                 if (sState != null) {
1533                         if (allow_load) {
1534 #if NET_2_0
1535                                 LoadPageControlState (sState.Second);
1536 #endif
1537                                 Pair vsr = sState.First as Pair;
1538                                 if (vsr != null) {
1539                                         LoadViewStateRecursive (vsr.First);
1540                                         _requiresPostBackCopy = vsr.Second as ArrayList;
1541                                 }
1542                         }
1543                 }
1544         }
1545
1546         internal void SavePageViewState ()
1547         {
1548                 if (!handleViewState)
1549                         return;
1550
1551 #if NET_2_0
1552                 object controlState = SavePageControlState ();
1553 #endif
1554
1555                 object viewState = SaveViewStateRecursive ();
1556                 object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
1557                 Pair vsr = null;
1558
1559                 if (viewState != null || reqPostback != null)
1560                         vsr = new Pair (viewState, reqPostback);
1561                 Pair pair = new Pair ();
1562
1563                 pair.First = vsr;
1564 #if NET_2_0
1565                 pair.Second = controlState;
1566 #else
1567                 pair.Second = null;
1568 #endif
1569                 if (pair.First == null && pair.Second == null)
1570                         SavePageStateToPersistenceMedium (null);
1571                 else
1572                         SavePageStateToPersistenceMedium (pair);                
1573
1574         }
1575
1576         public virtual void Validate ()
1577         {
1578                 is_validated = true;
1579                 ValidateCollection (_validators);
1580         }
1581
1582 #if NET_2_0
1583         internal bool AreValidatorsUplevel () {
1584                 return AreValidatorsUplevel (String.Empty);
1585         }
1586
1587         internal bool AreValidatorsUplevel (string valGroup)
1588 #else
1589         internal virtual bool AreValidatorsUplevel ()
1590 #endif
1591         {
1592                 bool uplevel = false;
1593
1594                 foreach (IValidator v in Validators) {
1595                         BaseValidator bv = v as BaseValidator;
1596                         if (bv == null) continue;
1597
1598 #if NET_2_0
1599                         if (valGroup != bv.ValidationGroup)
1600                                 continue;
1601 #endif
1602                         if (bv.GetRenderUplevel()) {
1603                                 uplevel = true;
1604                                 break;
1605                         }
1606                 }
1607
1608                 return uplevel;
1609         }
1610
1611         bool ValidateCollection (ValidatorCollection validators)
1612         {
1613 #if NET_2_0
1614                 if (!_eventValidation)
1615                         return true;
1616 #endif
1617
1618                 if (validators == null || validators.Count == 0)
1619                         return true;
1620
1621                 bool all_valid = true;
1622                 foreach (IValidator v in validators){
1623                         v.Validate ();
1624                         if (v.IsValid == false)
1625                                 all_valid = false;
1626                 }
1627
1628                 return all_valid;
1629         }
1630
1631         [EditorBrowsable (EditorBrowsableState.Advanced)]
1632         public virtual void VerifyRenderingInServerForm (Control control)
1633         {
1634                 if (_context == null)
1635                         return;
1636 #if NET_2_0
1637                 if (IsCallback)
1638                         return;
1639 #endif
1640                 if (!renderingForm)
1641                         throw new HttpException ("Control '" +
1642                                                  control.ClientID +
1643                                                  "' of type '" +
1644                                                  control.GetType ().Name +
1645                                                  "' must be placed inside a form tag with runat=server.");
1646         }
1647
1648         protected override void FrameworkInitialize ()
1649         {
1650                 base.FrameworkInitialize ();
1651 #if NET_2_0
1652                 InitializeStyleSheet ();
1653 #endif
1654         }
1655
1656         #endregion
1657         
1658         #if NET_2_0
1659         public
1660         #else
1661         internal
1662         #endif
1663                 ClientScriptManager ClientScript {
1664                 get { return scriptManager; }
1665         }
1666         
1667         #if NET_2_0
1668         
1669         static readonly object InitCompleteEvent = new object ();
1670         static readonly object LoadCompleteEvent = new object ();
1671         static readonly object PreInitEvent = new object ();
1672         static readonly object PreLoadEvent = new object ();
1673         static readonly object PreRenderCompleteEvent = new object ();
1674         static readonly object SaveStateCompleteEvent = new object ();
1675         int event_mask;
1676         const int initcomplete_mask = 1;
1677         const int loadcomplete_mask = 1 << 1;
1678         const int preinit_mask = 1 << 2;
1679         const int preload_mask = 1 << 3;
1680         const int prerendercomplete_mask = 1 << 4;
1681         const int savestatecomplete_mask = 1 << 5;
1682         
1683         [EditorBrowsable (EditorBrowsableState.Advanced)]
1684         public event EventHandler InitComplete {
1685                 add {
1686                         event_mask |= initcomplete_mask;
1687                         Events.AddHandler (InitCompleteEvent, value);
1688                 }
1689                 remove { Events.RemoveHandler (InitCompleteEvent, value); }
1690         }
1691         
1692         [EditorBrowsable (EditorBrowsableState.Advanced)]
1693         public event EventHandler LoadComplete {
1694                 add {
1695                         event_mask |= loadcomplete_mask;
1696                         Events.AddHandler (LoadCompleteEvent, value);
1697                 }
1698                 remove { Events.RemoveHandler (LoadCompleteEvent, value); }
1699         }
1700         
1701         public event EventHandler PreInit {
1702                 add {
1703                         event_mask |= preinit_mask;
1704                         Events.AddHandler (PreInitEvent, value);
1705                 }
1706                 remove { Events.RemoveHandler (PreInitEvent, value); }
1707         }
1708         
1709         [EditorBrowsable (EditorBrowsableState.Advanced)]
1710         public event EventHandler PreLoad {
1711                 add {
1712                         event_mask |= preload_mask;
1713                         Events.AddHandler (PreLoadEvent, value);
1714                 }
1715                 remove { Events.RemoveHandler (PreLoadEvent, value); }
1716         }
1717         
1718         [EditorBrowsable (EditorBrowsableState.Advanced)]
1719         public event EventHandler PreRenderComplete {
1720                 add {
1721                         event_mask |= prerendercomplete_mask;
1722                         Events.AddHandler (PreRenderCompleteEvent, value);
1723                 }
1724                 remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
1725         }
1726         
1727         [EditorBrowsable (EditorBrowsableState.Advanced)]
1728         public event EventHandler SaveStateComplete {
1729                 add {
1730                         event_mask |= savestatecomplete_mask;
1731                         Events.AddHandler (SaveStateCompleteEvent, value);
1732                 }
1733                 remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
1734         }
1735         
1736         protected virtual void OnInitComplete (EventArgs e)
1737         {
1738                 if ((event_mask & initcomplete_mask) != 0) {
1739                         EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
1740                         if (eh != null) eh (this, e);
1741                 }
1742         }
1743         
1744         protected virtual void OnLoadComplete (EventArgs e)
1745         {
1746                 if ((event_mask & loadcomplete_mask) != 0) {
1747                         EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
1748                         if (eh != null) eh (this, e);
1749                 }
1750         }
1751         
1752         protected virtual void OnPreInit (EventArgs e)
1753         {
1754                 if ((event_mask & preinit_mask) != 0) {
1755                         EventHandler eh = (EventHandler) (Events [PreInitEvent]);
1756                         if (eh != null) eh (this, e);
1757                 }
1758         }
1759         
1760         protected virtual void OnPreLoad (EventArgs e)
1761         {
1762                 if ((event_mask & preload_mask) != 0) {
1763                         EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
1764                         if (eh != null) eh (this, e);
1765                 }
1766         }
1767         
1768         protected virtual void OnPreRenderComplete (EventArgs e)
1769         {
1770                 if ((event_mask & prerendercomplete_mask) != 0) {
1771                         EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
1772                         if (eh != null) eh (this, e);
1773                 }
1774
1775                 if (Form == null)
1776                         return;
1777                 if (!Form.DetermineRenderUplevel ())
1778                         return;
1779
1780                 /* figure out if we have some control we're going to focus */
1781                 if (String.IsNullOrEmpty (_focusedControlID)) {
1782                         _focusedControlID = Form.DefaultFocus;
1783                         if (String.IsNullOrEmpty (_focusedControlID))
1784                                 _focusedControlID = Form.DefaultButton;
1785                 }
1786
1787                 if (!String.IsNullOrEmpty (_focusedControlID) || Form.SubmitDisabledControls) {
1788
1789                         RequiresPostBackScript ();
1790                         ClientScript.RegisterWebFormClientScript ();
1791
1792                         if (!String.IsNullOrEmpty (_focusedControlID)) {
1793                                 ClientScript.RegisterStartupScript ("HtmlForm-DefaultButton-StartupScript",
1794                                                                          String.Format ("<script type=\"text/javascript\">\n" +
1795                                                                                         "<!--\n" +
1796                                                                                         "WebForm_AutoFocus('{0}');// -->\n" +
1797                                                                                         "</script>\n", _focusedControlID));
1798                         }
1799
1800                         if (Form.SubmitDisabledControls) {
1801                                 ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
1802                                                                                  "javascript: return WebForm_OnSubmit(" + theForm + ");");
1803                                 ClientScript.RegisterStartupScript ("HtmlForm-SubmitDisabledControls-StartupScript",
1804 @"<script language=""JavaScript"">
1805 <!--
1806 function WebForm_OnSubmit(currForm) {
1807 WebForm_ReEnableControls(currForm);
1808 return true;
1809 } // -->
1810 </script>");
1811                         }
1812                 }
1813         }
1814         
1815         protected virtual void OnSaveStateComplete (EventArgs e)
1816         {
1817                 if ((event_mask & savestatecomplete_mask) != 0) {
1818                         EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
1819                         if (eh != null) eh (this, e);
1820                 }
1821         }
1822         
1823         public HtmlForm Form {
1824                 get { return _form; }
1825         }
1826         
1827         internal void RegisterForm (HtmlForm form)
1828         {
1829                 _form = form;
1830         }
1831         
1832         [BrowsableAttribute (false)]
1833         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1834         public Page PreviousPage {
1835                 get {
1836                         if (_doLoadPreviousPage) {
1837                                 _doLoadPreviousPage = false;
1838                                 LoadPreviousPageReference ();
1839                         }
1840                         return previousPage;
1841                 }
1842         }
1843
1844         
1845         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1846         [BrowsableAttribute (false)]
1847         public bool IsCallback {
1848                 get { return isCallback; }
1849         }
1850         
1851         [BrowsableAttribute (false)]
1852         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1853         public bool IsCrossPagePostBack {
1854                 get { return isCrossPagePostBack; }
1855         }
1856
1857         public new virtual char IdSeparator {
1858                 get {
1859                         //TODO: why override?
1860                         return base.IdSeparator;
1861                 }
1862         }
1863         
1864         string ProcessCallbackData ()
1865         {
1866                 string callbackTarget = _requestValueCollection [CallbackSourceID];
1867                 if (callbackTarget == null || callbackTarget.Length == 0)
1868                         throw new HttpException ("Callback target not provided.");
1869
1870                 Control targetControl = FindControl (callbackTarget);
1871                 ICallbackEventHandler target = targetControl as ICallbackEventHandler;
1872                 if (target == null)
1873                         throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
1874
1875                 string callbackArgument = _requestValueCollection [CallbackArgumentID];
1876                 target.RaiseCallbackEvent (callbackArgument);
1877
1878                 string eventValidation = ClientScript.GetEventValidationStateFormatted ();
1879                 string callBackResult= target.GetCallbackResult ();
1880
1881                 return String.Format ("{0}|{1}{2}", eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
1882         }
1883
1884         [BrowsableAttribute (false)]
1885         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1886         public HtmlHead Header {
1887                 get { return htmlHeader; }
1888         }
1889         
1890         internal void SetHeader (HtmlHead header)
1891         {
1892                 htmlHeader = header;
1893                 if (_title != null) {
1894                         htmlHeader.Title = _title;
1895                         _title = null;
1896                 }
1897         }
1898
1899         [MonoTODO("Not Implemented")]
1900         protected bool AsyncMode {
1901                 get {
1902                         throw new NotImplementedException ();
1903                 }
1904                 set {
1905                         throw new NotImplementedException ();
1906                 }
1907         }
1908
1909         [MonoTODO ("Not Implemented")]
1910         public TimeSpan AsyncTimeout {
1911                 get {
1912                         throw new NotImplementedException ();
1913                 }
1914                 set {
1915                         throw new NotImplementedException ();
1916                 }
1917         }
1918
1919         [MonoTODO ("Not Implemented")]
1920         public bool IsAsync {
1921                 get {
1922                         throw new NotImplementedException ();
1923                 }
1924         }
1925         
1926         [MonoTODO ("Not Implemented")]
1927         protected internal virtual string UniqueFilePathSuffix {
1928                 get {
1929                         throw new NotImplementedException ();
1930                 }
1931         }
1932
1933         [MonoTODO ("Not Implemented")]
1934         public int MaxPageStateFieldLength {
1935                 get {
1936                         throw new NotImplementedException ();
1937                 }
1938                 set {
1939                         throw new NotImplementedException ();
1940                 }
1941         }
1942
1943         [MonoTODO ("Not Implemented")]
1944         public ViewStateEncryptionMode ViewStateEncryptionMode {
1945                 get {
1946                         throw new NotImplementedException ();
1947                 }
1948                 set {
1949                         throw new NotImplementedException ();
1950                 }
1951         }
1952
1953         [MonoTODO ("Not Implemented")]
1954         public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
1955         {
1956                 throw new NotImplementedException ();
1957         }
1958
1959         [MonoTODO ("Not Implemented")]
1960         public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
1961         {
1962                 throw new NotImplementedException ();
1963         }
1964
1965         [MonoTODO ("Not Implemented")]
1966         public void ExecuteRegisteredAsyncTasks ()
1967         {
1968                 throw new NotImplementedException ();
1969         }
1970
1971         [MonoTODO ("Not Implemented")]
1972         public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
1973         {
1974                 throw new NotImplementedException ();
1975         }
1976
1977         [MonoTODO ("Not Implemented")]
1978         public void RegisterRequiresViewStateEncryption ()
1979         {
1980                 throw new NotImplementedException ();
1981         }
1982
1983         void ApplyMasterPage ()
1984         {
1985                 if (masterPageFile != null && masterPageFile.Length > 0) {
1986                         ArrayList appliedMasterPageFiles = new ArrayList ();
1987
1988                         if (Master != null) {
1989                                 MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
1990
1991                                 Master.Page = this;
1992                                 Controls.Clear ();
1993                                 Controls.Add (Master);
1994                         }
1995                 }
1996         }
1997
1998         [DefaultValueAttribute ("")]
1999         public virtual string MasterPageFile {
2000                 get { return masterPageFile; }
2001                 set {
2002                         masterPageFile = value;
2003                         masterPage = null;
2004                 }
2005         }
2006         
2007         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2008         [BrowsableAttribute (false)]
2009         public MasterPage Master {
2010                 get {
2011                         if (Context == null || String.IsNullOrEmpty (masterPageFile))
2012                                 return null;
2013
2014                         if (masterPage == null)
2015                                 masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
2016
2017                         return masterPage;
2018                 }
2019         }
2020         
2021         public void SetFocus (string clientID)
2022         {
2023                 if (String.IsNullOrEmpty (clientID))
2024                         throw new ArgumentNullException ("control");
2025
2026                 if (_lifeCycle > PageLifeCycle.PreRender)
2027                         throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
2028
2029                 if(Form==null)
2030                         throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
2031
2032                 _focusedControlID = clientID;
2033         }
2034
2035         public void SetFocus (Control control)
2036         {
2037                 if (control == null)
2038                         throw new ArgumentNullException ("control");
2039
2040                 SetFocus (control.ClientID);
2041         }
2042         
2043         [EditorBrowsable (EditorBrowsableState.Advanced)]
2044         public void RegisterRequiresControlState (Control control)
2045         {
2046                 if (control == null)
2047                         throw new ArgumentNullException ("control");
2048
2049                 if (RequiresControlState (control))
2050                         return;
2051
2052                 if (requireStateControls == null)
2053                         requireStateControls = new ArrayList ();
2054                 int n = requireStateControls.Add (control);
2055
2056                 if (_savedControlState == null || n >= _savedControlState.Length) 
2057                         return;
2058
2059                 for (Control parent = control.Parent; parent != null; parent = parent.Parent)
2060                         if (parent.IsChildControlStateCleared)
2061                                 return;
2062
2063                 object state = _savedControlState [n];
2064                 if (state != null)
2065                         control.LoadControlState (state);
2066         }
2067         
2068         public bool RequiresControlState (Control control)
2069         {
2070                 if (requireStateControls == null) return false;
2071                 return requireStateControls.Contains (control);
2072         }
2073         
2074         [EditorBrowsable (EditorBrowsableState.Advanced)]
2075         public void UnregisterRequiresControlState (Control control)
2076         {
2077                 if (requireStateControls != null)
2078                         requireStateControls.Remove (control);
2079         }
2080         
2081         public ValidatorCollection GetValidators (string validationGroup)
2082         {
2083                 string valgr = validationGroup;
2084                 if (valgr == null)
2085                         valgr = String.Empty;
2086
2087                 if (_validatorsByGroup == null) _validatorsByGroup = new Hashtable ();
2088                 ValidatorCollection col = _validatorsByGroup [valgr] as ValidatorCollection;
2089                 if (col == null) {
2090                         col = new ValidatorCollection ();
2091                         _validatorsByGroup [valgr] = col;
2092                 }
2093                 return col;
2094         }
2095         
2096         public virtual void Validate (string validationGroup)
2097         {
2098                 is_validated = true;
2099                 if (validationGroup == null)
2100                         ValidateCollection (_validatorsByGroup [String.Empty] as ValidatorCollection);
2101                 else if (_validatorsByGroup != null) {
2102                         ValidateCollection (_validatorsByGroup [validationGroup] as ValidatorCollection);
2103                 }
2104         }
2105
2106         object SavePageControlState ()
2107         {
2108                 if (requireStateControls == null) return null;
2109                 object[] state = new object [requireStateControls.Count];
2110                 
2111                 bool allNull = true;
2112                 for (int n=0; n<state.Length; n++) {
2113                         state [n] = ((Control) requireStateControls [n]).SaveControlState ();
2114                         if (state [n] != null) allNull = false;
2115                 }
2116                 if (allNull) return null;
2117                 else return state;
2118         }
2119         
2120         void LoadPageControlState (object data)
2121         {
2122                 _savedControlState = (object []) data;
2123                 
2124                 if (requireStateControls == null) return;
2125
2126                 int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
2127                 for (int n=0; n < max; n++) {
2128                         Control ctl = (Control) requireStateControls [n];
2129                         ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
2130                 }
2131         }
2132
2133         void LoadPreviousPageReference ()
2134         {
2135                 if (_requestValueCollection != null) {
2136                         string prevPage = _requestValueCollection [PreviousPageID];
2137                         if (prevPage != null) {
2138                                 previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
2139                                 previousPage.ProcessCrossPagePostBack (_context);
2140                         } 
2141                 }
2142         }
2143
2144
2145         Hashtable contentTemplates;
2146         [EditorBrowsable (EditorBrowsableState.Never)]
2147         protected internal void AddContentTemplate (string templateName, ITemplate template)
2148         {
2149                 if (contentTemplates == null)
2150                         contentTemplates = new Hashtable ();
2151                 contentTemplates [templateName] = template;
2152         }
2153
2154         PageTheme _pageTheme;
2155         internal PageTheme PageTheme {
2156                 get { return _pageTheme; }
2157         }
2158
2159         PageTheme _styleSheetPageTheme;
2160         internal PageTheme StyleSheetPageTheme {
2161                 get { return _styleSheetPageTheme; }
2162         }
2163
2164         Stack dataItemCtx;
2165         
2166         internal void PushDataItemContext (object o) {
2167                 if (dataItemCtx == null)
2168                         dataItemCtx = new Stack ();
2169                 
2170                 dataItemCtx.Push (o);
2171         }
2172         
2173         internal void PopDataItemContext () {
2174                 if (dataItemCtx == null)
2175                         throw new InvalidOperationException ();
2176                 
2177                 dataItemCtx.Pop ();
2178         }
2179         
2180         public object GetDataItem() {
2181                 if (dataItemCtx == null || dataItemCtx.Count == 0)
2182                         throw new InvalidOperationException ("No data item");
2183                 
2184                 return dataItemCtx.Peek ();
2185         }
2186
2187         protected internal override void OnInit (EventArgs e)
2188         {
2189                 base.OnInit (e);
2190                 if (Header == null)
2191                         return;
2192
2193                 ArrayList themes = new ArrayList();
2194
2195                 if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
2196                         themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
2197                 if (PageTheme != null && PageTheme.GetStyleSheets () != null)
2198                         themes.AddRange (PageTheme.GetStyleSheets ());
2199
2200                 foreach (string lss in themes) {
2201                         HtmlLink hl = new HtmlLink ();
2202                         hl.Href = ResolveUrl (lss);
2203                         hl.Attributes["type"] = "text/css";
2204                         hl.Attributes["rel"] = "stylesheet";
2205                         Header.Controls.Add (hl);
2206                 }
2207         }
2208
2209         #endif
2210
2211 #if NET_2_0
2212         [MonoTODO ("Not implemented.  Only used by .net aspx parser")]
2213         protected object GetWrappedFileDependencies (string [] list)
2214         {
2215                 return null;
2216         }
2217
2218         [MonoTODO ("Does nothing.  Used by .net aspx parser")]
2219         protected virtual void InitializeCulture ()
2220         {
2221         }
2222
2223         [MonoTODO ("Does nothing. Used by .net aspx parser")]
2224         protected internal void AddWrappedFileDependencies (object virtualFileDependencies)
2225         {
2226         }
2227 #endif
2228 }
2229 }