Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Page.cs « System.Web.UI « System.Web « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 95919aba332cf60ff2aa9c68d0e729f13158b2b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
//
// System.Web.UI.Page.cs
//
// Authors:
//   Duncan Mak  (duncan@ximian.com)
//   Gonzalo Paniagua (gonzalo@ximian.com)
//   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//   Marek Habersack (mhabersack@novell.com)
//
// (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
// Copyright (C) 2003-2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.SessionState;
using System.Web.Util;
using System.Web.UI.Adapters;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Reflection;
#if NET_4_0
using System.Web.Routing;
#endif

namespace System.Web.UI
{
// CAS
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
[ToolboxItem (false)]
[Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
[DesignerSerializer ("Microsoft.VisualStudio.Web.WebForms.WebFormCodeDomSerializer, " + Consts.AssemblyMicrosoft_VisualStudio_Web, "System.ComponentModel.Design.Serialization.TypeCodeDomSerializer, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public partial class Page : TemplateControl, IHttpHandler
{
//	static string machineKeyConfigPath = "system.web/machineKey";
	bool _eventValidation = true;
	object [] _savedControlState;
	bool _doLoadPreviousPage;
	string _focusedControlID;
	bool _hasEnabledControlArray;
	bool _viewState;
	bool _viewStateMac;
	string _errorPage;
	bool is_validated;
	bool _smartNavigation;
	int _transactionMode;
	ValidatorCollection _validators;
	bool renderingForm;
	string _savedViewState;
	List <string> _requiresPostBack;
	List <string> _requiresPostBackCopy;
	List <IPostBackDataHandler> requiresPostDataChanged;
	IPostBackEventHandler requiresRaiseEvent;
	IPostBackEventHandler formPostedRequiresRaiseEvent;
	NameValueCollection secondPostData;
	bool requiresPostBackScript;
	bool postBackScriptRendered;
	bool requiresFormScriptDeclaration;
	bool formScriptDeclarationRendered;
	bool handleViewState;
	string viewStateUserKey;
	NameValueCollection _requestValueCollection;
	string clientTarget;
	ClientScriptManager scriptManager;
	bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
	PageStatePersister page_state_persister;
	CultureInfo _appCulture;
	CultureInfo _appUICulture;

	// The initial context
	HttpContext _context;
	
	// cached from the initial context
	HttpApplicationState _application;
	HttpResponse _response;
	HttpRequest _request;
	Cache _cache;
	
	HttpSessionState _session;
	
	[EditorBrowsable (EditorBrowsableState.Never)]
	public const string postEventArgumentID = "__EVENTARGUMENT";

	[EditorBrowsable (EditorBrowsableState.Never)]
	public const string postEventSourceID = "__EVENTTARGET";

	const string ScrollPositionXID = "__SCROLLPOSITIONX";
	const string ScrollPositionYID = "__SCROLLPOSITIONY";
	const string EnabledControlArrayID = "__enabledControlArray";
	internal const string LastFocusID = "__LASTFOCUS";
	internal const string CallbackArgumentID = "__CALLBACKPARAM";
	internal const string CallbackSourceID = "__CALLBACKID";
	internal const string PreviousPageID = "__PREVIOUSPAGE";

	int maxPageStateFieldLength = -1;
	string uniqueFilePathSuffix;
	HtmlHead htmlHeader;
	
	MasterPage masterPage;
	string masterPageFile;
	
	Page previousPage;
	bool isCrossPagePostBack;
	bool isPostBack;
	bool isCallback;
	List <Control> requireStateControls;
	HtmlForm _form;

	string _title;
	string _theme;
	string _styleSheetTheme;
#if NET_4_0
	string _metaDescription;
	string _metaKeywords;
	Control _autoPostBackControl;
	
	bool frameworkInitialized;
#endif
	Hashtable items;

	bool _maintainScrollPositionOnPostBack;

	bool asyncMode = false;
	TimeSpan asyncTimeout;
	const double DefaultAsyncTimeout = 45.0;
	List<PageAsyncTask> parallelTasks;
	List<PageAsyncTask> serialTasks;

	ViewStateEncryptionMode viewStateEncryptionMode;
	bool controlRegisteredForViewStateEncryption = false;

	#region Constructors	
	public Page ()
	{
		scriptManager = new ClientScriptManager (this);
		Page = this;
		ID = "__Page";
		PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
		if (ps != null) {
			asyncTimeout = ps.AsyncTimeout;
			viewStateEncryptionMode = ps.ViewStateEncryptionMode;
			_viewState = ps.EnableViewState;
			_viewStateMac = ps.EnableViewStateMac;
		} else {
			asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
			viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
			_viewState = true;
		}
#if NET_4_0
		this.ViewStateMode = ViewStateMode.Enabled;
#endif
	}

	#endregion		

	#region Properties

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public HttpApplicationState Application {
		get { return _application; }
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	protected bool AspCompatMode {
		get { return false; }
		set {
			// nothing to do
		}
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public bool Buffer {
		get { return Response.BufferOutput; }
		set { Response.BufferOutput = value; }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public Cache Cache {
		get {
			if (_cache == null)
				throw new HttpException ("Cache is not available.");
			return _cache;
		}
	}

	[EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false), DefaultValue ("")]
	[WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
	public string ClientTarget {
		get { return (clientTarget == null) ? String.Empty : clientTarget; }
		set {
			clientTarget = value;
			if (value == String.Empty)
				clientTarget = null;
		}
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public int CodePage {
		get { return Response.ContentEncoding.CodePage; }
		set { Response.ContentEncoding = Encoding.GetEncoding (value); }
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public string ContentType {
		get { return Response.ContentType; }
		set { Response.ContentType = value; }
	}

	protected internal override HttpContext Context {
		get {
			if (_context == null)
				return HttpContext.Current;

			return _context;
		}
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public string Culture {
		get { return Thread.CurrentThread.CurrentCulture.Name; }
		set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[Browsable (false)]
	[DefaultValue ("true")]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public virtual bool EnableEventValidation {
		get { return _eventValidation; }
		set {
			if (IsInited)
				throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
			_eventValidation = value;
		}
	}

	[Browsable (false)]
	public override bool EnableViewState {
		get { return _viewState; }
		set { _viewState = value; }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	[EditorBrowsable (EditorBrowsableState.Never)]
	public bool EnableViewStateMac {
		get { return _viewStateMac; }
		set { _viewStateMac = value; }
	}

	internal bool EnableViewStateMacInternal {
		get { return _viewStateMac; }
		set { _viewStateMac = value; }
	}
	
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false), DefaultValue ("")]
	[WebSysDescription ("The URL of a page used for error redirection.")]
	public string ErrorPage {
		get { return _errorPage; }
		set {
			HttpContext ctx = Context;
			
			_errorPage = value;
			if (ctx != null)
				ctx.ErrorPage = value;
		}
	}

	[Obsolete ("The recommended alternative is HttpResponse.AddFileDependencies. http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Never)]
	protected ArrayList FileDependencies {
		set {
			if (Response != null)
				Response.AddFileDependencies (value);
		}
	}

	[Browsable (false)]
	[EditorBrowsable (EditorBrowsableState.Never)]
	public override string ID {
		get { return base.ID; }
		set { base.ID = value; }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public bool IsPostBack {
		get { return isPostBack; }
	}

	public bool IsPostBackEventControlRegistered {
		get { return requiresRaiseEvent != null; }
	}
	
	[EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
	public bool IsReusable {
		get { return false; }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public bool IsValid {
		get {
			if (!is_validated)
				throw new HttpException (Locale.GetText ("Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate."));

			foreach (IValidator val in Validators)
				if (!val.IsValid)
					return false;
			return true;
		}
	}

	[Browsable (false)]
	public IDictionary Items {
		get {
			if (items == null)
				items = new Hashtable ();
			return items;
		}
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public int LCID {
		get { return Thread.CurrentThread.CurrentCulture.LCID; }
		set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
	}

	[Browsable (false)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public bool MaintainScrollPositionOnPostBack {
		get { return _maintainScrollPositionOnPostBack; }
		set { _maintainScrollPositionOnPostBack = value; }
	}

	public PageAdapter PageAdapter {
		get {
			return Adapter as PageAdapter;
		}
	}

	string _validationStartupScript;
	string _validationOnSubmitStatement;
	string _validationInitializeScript;
	string _webFormScriptReference;

	internal string WebFormScriptReference {
		get {
			if (_webFormScriptReference == null)
				_webFormScriptReference = IsMultiForm ? theForm : "window";
			return _webFormScriptReference;
		}
	}

	internal string ValidationStartupScript {
		get {
			if (_validationStartupScript == null) {
				_validationStartupScript =
@"
" + WebFormScriptReference + @".Page_ValidationActive = false;
" + WebFormScriptReference + @".ValidatorOnLoad();
" + WebFormScriptReference + @".ValidatorOnSubmit = function () {
	if (this.Page_ValidationActive) {
		return this.ValidatorCommonOnSubmit();
	}
	return true;
};
";
			}
			return _validationStartupScript;
		}
	}

	internal string ValidationOnSubmitStatement {
		get {
			if (_validationOnSubmitStatement == null)
				_validationOnSubmitStatement = "if (!" + WebFormScriptReference + ".ValidatorOnSubmit()) return false;";
			return _validationOnSubmitStatement;
		}
	}

	internal string ValidationInitializeScript {
		get {
			if (_validationInitializeScript == null)
				_validationInitializeScript = "WebFormValidation_Initialize(" + WebFormScriptReference + ");";
			return _validationInitializeScript;
		}
	}

	internal IScriptManager ScriptManager {
		get { return (IScriptManager) Items [typeof (IScriptManager)]; }
	}
#if !TARGET_J2EE
	internal string theForm {
		get {
			return "theForm";
		}
	}
	
	internal bool IsMultiForm {
		get { return false; }
	}
#endif

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public HttpRequest Request {
		get {
			if (_request == null)
				throw new HttpException("Request is not available in this context.");
			return RequestInternal;
		}
	}

	internal HttpRequest RequestInternal {
		get { return _request; }
	}
	
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public HttpResponse Response {
		get {
			if (_response == null)
				throw new HttpException ("Response is not available in this context.");
			return _response;
		}
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public string ResponseEncoding {
		get { return Response.ContentEncoding.WebName; }
		set { Response.ContentEncoding = Encoding.GetEncoding (value); }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public HttpServerUtility Server {
		get { return Context.Server; }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public virtual HttpSessionState Session {
		get {
			if (_session != null)
				return _session;

			try {
				_session = Context.Session;
			} catch {
				// ignore, should not throw
			}
			
			if (_session == null)
				throw new HttpException ("Session state can only be used " +
						"when enableSessionState is set to true, either " +
						"in a configuration file or in the Page directive.");

			return _session;
		}
	}

	[Filterable (false)]
	[Obsolete ("The recommended alternative is Page.SetFocus and Page.MaintainScrollPositionOnPostBack. http://go.microsoft.com/fwlink/?linkid=14202")]
	[Browsable (false)]
	public bool SmartNavigation {
		get { return _smartNavigation; }
		set { _smartNavigation = value; }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Filterable (false)]
	[Browsable (false)]
	public virtual string StyleSheetTheme {
		get { return _styleSheetTheme; }
		set { _styleSheetTheme = value; }
	}

	[Browsable (false)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public virtual string Theme {
		get { return _theme; }
		set { _theme = value; }
	}

	void InitializeStyleSheet ()
	{
		if (_styleSheetTheme == null) {
			PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
			if (ps != null)
				_styleSheetTheme = ps.StyleSheetTheme;
		}

		if (!String.IsNullOrEmpty (_styleSheetTheme)) {
			string virtualPath = "~/App_Themes/" + _styleSheetTheme;
			_styleSheetPageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
		}
	}

	void InitializeTheme ()
	{
		if (_theme == null) {
			PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
			if (ps != null)
				_theme = ps.Theme;
		}

		if (!String.IsNullOrEmpty (_theme)) {
			string virtualPath = "~/App_Themes/" + _theme;
			_pageTheme = BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (PageTheme)) as PageTheme;
			if (_pageTheme != null)
				_pageTheme.SetPage (this);
		}
	}
#if NET_4_0
	public Control AutoPostBackControl {
		get { return _autoPostBackControl; }
		set { _autoPostBackControl = value; }
	}
	
	[BrowsableAttribute(false)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public RouteData RouteData {
		get {
			if (_request == null)
				return null;

			RequestContext reqctx = _request.RequestContext;
			if (reqctx == null)
				return null;

			return reqctx.RouteData;
		}
	}
	
	[Bindable (true)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Localizable (true)]
	public string MetaDescription {
		get {
			if (_metaDescription == null) {
				if (htmlHeader == null) {
					if (frameworkInitialized)
						throw new InvalidOperationException ("A server-side head element is required to set this property.");
					return String.Empty;
				} else
					return htmlHeader.Description;
			}

			return _metaDescription;
		}
		
		set {
			if (htmlHeader == null) {
				if (frameworkInitialized)
					throw new InvalidOperationException ("A server-side head element is required to set this property.");
				_metaDescription = value;
			} else
				htmlHeader.Description = value;
		}
	}

	[Bindable (true)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Localizable (true)]
	public string MetaKeywords {
		get {
			if (_metaKeywords == null) {
				if (htmlHeader == null) {
					if (frameworkInitialized)
						throw new InvalidOperationException ("A server-side head element is required to set this property.");
					return String.Empty;
				} else
					return htmlHeader.Keywords;
			}

			return _metaDescription;
		}
		
		set {
			if (htmlHeader == null) {
				if (frameworkInitialized)
					throw new InvalidOperationException ("A server-side head element is required to set this property.");
				_metaKeywords = value;
			} else
				htmlHeader.Keywords = value;
		}
	}
#endif
	[Localizable (true)] 
	[Bindable (true)] 
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public string Title {
		get {
			if (_title == null) {
				if (htmlHeader != null && htmlHeader.Title != null)
					return htmlHeader.Title;
				return String.Empty;
			}
			return _title;
		}

		set {
			if (htmlHeader != null)
				htmlHeader.Title = value;
			else
				_title = value;
		}
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public TraceContext Trace {
		get { return Context.Trace; }
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public bool TraceEnabled {
		get { return Trace.IsEnabled; }
		set { Trace.IsEnabled = value; }
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public TraceMode TraceModeValue {
		get { return Trace.TraceMode; }
		set { Trace.TraceMode = value; }
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	protected int TransactionMode {
		get { return _transactionMode; }
		set { _transactionMode = value; }
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public string UICulture {
		get { return Thread.CurrentThread.CurrentUICulture.Name; }
		set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public IPrincipal User {
		get { return Context.User; }
	}

	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[Browsable (false)]
	public ValidatorCollection Validators {
		get { 
			if (_validators == null)
				_validators = new ValidatorCollection ();
			return _validators;
		}
	}

	[MonoTODO ("Use this when encrypting/decrypting ViewState")]
	[Browsable (false)]
	public string ViewStateUserKey {
		get { return viewStateUserKey; }
		set { viewStateUserKey = value; }
	}

	[Browsable (false)]
	public override bool Visible {
		get { return base.Visible; }
		set { base.Visible = value; }
	}

	#endregion

	#region Methods

	CultureInfo GetPageCulture (string culture, CultureInfo deflt)
	{
		if (culture == null)
			return deflt;
		CultureInfo ret = null;
		if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
#if TARGET_J2EE
			if (!Context.IsServletRequest)
				return deflt;
#endif
			string[] languages = Request.UserLanguages;
			try {
				if (languages != null && languages.Length > 0)
					ret = CultureInfo.CreateSpecificCulture (languages[0]);
			} catch {
			}
			
			if (ret == null)
				ret = deflt;
		} else
			ret = CultureInfo.CreateSpecificCulture (culture);

		return ret;
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
							     AsyncCallback cb, 
							     object extraData)
	{
		throw new NotImplementedException ();
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	[MonoNotSupported ("Mono does not support classic ASP compatibility mode.")]
	protected void AspCompatEndProcessRequest (IAsyncResult result)
	{
		throw new NotImplementedException ();
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
	{
		if (Request.BrowserMightHaveSpecialWriter)
			return Request.Browser.CreateHtmlTextWriter(tw);
		else
			return new HtmlTextWriter (tw);
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	public void DesignerInitialize ()
	{
		InitRecursive (null);
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	protected internal virtual NameValueCollection DeterminePostBackMode ()
	{
		// if request was transfered from other page such Transfer
		if (_context.IsProcessingInclude)
			return null;
		
		HttpRequest req = Request;
		if (req == null)
			return null;

		NameValueCollection coll = null;
		if (0 == String.Compare (Request.HttpMethod, "POST", true, Helpers.InvariantCulture)
#if TARGET_J2EE
			|| !_context.IsServletRequest
#endif
			)
			coll = req.Form;
		else {
			string query = Request.QueryStringRaw;
			if (query == null || query.Length == 0)
				return null;

			coll = req.QueryString;
		}

		WebROCollection c = (WebROCollection) coll;
		allow_load = !c.GotID;
		if (allow_load)
			c.ID = GetTypeHashCode ();
		else
			allow_load = (c.ID == GetTypeHashCode ());

		if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
			return null;
#if TARGET_J2EE
		if (getFacesContext () != null && _context.Handler != _context.CurrentHandler) {
			// check if it is PreviousPage
			string prevViewId = coll [PreviousPageID];
			if (!String.IsNullOrEmpty (prevViewId)) {
				string appPath = VirtualPathUtility.RemoveTrailingSlash (Request.ApplicationPath);
				prevViewId = prevViewId.Substring (appPath.Length);
				isCrossPagePostBack = String.Compare (prevViewId, getFacesContext ().getExternalContext ().getRequestPathInfo (), StringComparison.OrdinalIgnoreCase) == 0;
			}
		}
#endif
		return coll;
	}

	public override Control FindControl (string id) {
		if (id == ID)
			return this;
		else
			return base.FindControl (id);
	}

	Control FindControl (string id, bool decode) {
#if TARGET_J2EE
		if (decode)
			id = DecodeNamespace (id);
#endif
		return FindControl (id);
	}

	[Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public string GetPostBackClientEvent (Control control, string argument)
	{
		return scriptManager.GetPostBackEventReference (control, argument);
	}

	[Obsolete ("The recommended alternative is ClientScript.GetPostBackClientHyperlink. http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public string GetPostBackClientHyperlink (Control control, string argument)
	{
		return scriptManager.GetPostBackClientHyperlink (control, argument);
	}

	[Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public string GetPostBackEventReference (Control control)
	{
		return scriptManager.GetPostBackEventReference (control, String.Empty);
	}

	[Obsolete ("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public string GetPostBackEventReference (Control control, string argument)
	{
		return scriptManager.GetPostBackEventReference (control, argument);
	}

	internal void RequiresFormScriptDeclaration ()
	{
		requiresFormScriptDeclaration = true;
	}
	
	internal void RequiresPostBackScript ()
	{
		if (requiresPostBackScript)
			return;
		ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
		ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
		requiresPostBackScript = true;
		RequiresFormScriptDeclaration ();
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	public virtual int GetTypeHashCode ()
	{
		return 0;
	}

	[MonoTODO ("The following properties of OutputCacheParameters are silently ignored: CacheProfile, SqlDependency")]
	[EditorBrowsable (EditorBrowsableState.Never)]
	protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
	{
		if (cacheSettings.Enabled) {
			InitOutputCache(cacheSettings.Duration,
					cacheSettings.VaryByContentEncoding,
					cacheSettings.VaryByHeader,
					cacheSettings.VaryByCustom,
					cacheSettings.Location,
					cacheSettings.VaryByParam);

			HttpResponse response = Response;
			HttpCachePolicy cache = response != null ? response.Cache : null;
			if (cache != null && cacheSettings.NoStore)
				cache.SetNoStore ();
		}
	}
	
	[MonoTODO ("varyByContentEncoding is not currently used")]
	[EditorBrowsable (EditorBrowsableState.Never)]
	protected virtual void InitOutputCache(int duration,
					       string varyByContentEncoding,
					       string varyByHeader,
					       string varyByCustom,
					       OutputCacheLocation location,
					       string varyByParam)
	{
		if (duration <= 0)
			// No need to do anything, cache will be ineffective anyway
			return;
		
		HttpResponse response = Response;
		HttpCachePolicy cache = response.Cache;
		bool set_vary = false;
		HttpContext ctx = Context;
		DateTime timestamp = ctx != null ? ctx.Timestamp : DateTime.Now;
		
		switch (location) {
			case OutputCacheLocation.Any:
				cache.SetCacheability (HttpCacheability.Public);
				cache.SetMaxAge (new TimeSpan (0, 0, duration));
				cache.SetLastModified (timestamp);
				set_vary = true;
				break;
			case OutputCacheLocation.Client:
				cache.SetCacheability (HttpCacheability.Private);
				cache.SetMaxAge (new TimeSpan (0, 0, duration));
				cache.SetLastModified (timestamp);
				break;
			case OutputCacheLocation.Downstream:
				cache.SetCacheability (HttpCacheability.Public);
				cache.SetMaxAge (new TimeSpan (0, 0, duration));
				cache.SetLastModified (timestamp);
				break;
			case OutputCacheLocation.Server:			
				cache.SetCacheability (HttpCacheability.Server);
				set_vary = true;
				break;
			case OutputCacheLocation.None:
				break;
		}

		if (set_vary) {
			if (varyByCustom != null)
				cache.SetVaryByCustom (varyByCustom);

			if (varyByParam != null && varyByParam.Length > 0) {
				string[] prms = varyByParam.Split (';');
				foreach (string p in prms)
					cache.VaryByParams [p.Trim ()] = true;
				cache.VaryByParams.IgnoreParams = false;
			} else {
				cache.VaryByParams.IgnoreParams = true;
			}
			
			if (varyByHeader != null && varyByHeader.Length > 0) {
				string[] hdrs = varyByHeader.Split (';');
				foreach (string h in hdrs)
					cache.VaryByHeaders [h.Trim ()] = true;
			}

			if (PageAdapter != null) {
				if (PageAdapter.CacheVaryByParams != null) {
					foreach (string p in PageAdapter.CacheVaryByParams)
						cache.VaryByParams [p] = true;
				}
				if (PageAdapter.CacheVaryByHeaders != null) {
					foreach (string h in PageAdapter.CacheVaryByHeaders)
						cache.VaryByHeaders [h] = true;
				}
			}
		}

		response.IsCached = true;
		cache.Duration = duration;
		cache.SetExpires (timestamp.AddSeconds (duration));
	}
	

	[EditorBrowsable (EditorBrowsableState.Never)]
	protected virtual void InitOutputCache (int duration,
						string varyByHeader,
						string varyByCustom,
						OutputCacheLocation location,
						string varyByParam)
	{
		InitOutputCache (duration, null, varyByHeader, varyByCustom, location, varyByParam);
	}

	[Obsolete ("The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
	public bool IsClientScriptBlockRegistered (string key)
	{
		return scriptManager.IsClientScriptBlockRegistered (key);
	}

	[Obsolete ("The recommended alternative is ClientScript.IsStartupScriptRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
	public bool IsStartupScriptRegistered (string key)
	{
		return scriptManager.IsStartupScriptRegistered (key);
	}

	public string MapPath (string virtualPath)
	{
		return Request.MapPath (virtualPath);
	}
	
	protected internal override void Render (HtmlTextWriter writer)
	{
		if (MaintainScrollPositionOnPostBack) {
			ClientScript.RegisterWebFormClientScript ();

			ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
			ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);

			StringBuilder script = new StringBuilder ();
			script.AppendLine ("<script type=\"text/javascript\">");
			script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
			script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
			script.AppendLine (theForm + ".submit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionSubmit(); }");
			script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
			script.AppendLine (theForm + ".onsubmit = function () { " + WebFormScriptReference + ".WebForm_SaveScrollPositionOnSubmit(); }");
			if (IsPostBack) {
				script.AppendLine (theForm + ".oldOnLoad = window.onload;");
				script.AppendLine ("window.onload = function () { " + WebFormScriptReference + ".WebForm_RestoreScrollPosition (); };");
			}
			script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
			script.AppendLine ("</script>");
			
			ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
		}
#if TARGET_J2EE
		if (bool.Parse (WebConfigurationManager.AppSettings [RenderBodyContentOnlyKey] ?? "false")) {
			for (Control c = this.Form; c != null; c = c.Parent) {
				HtmlGenericControl ch = (c as HtmlGenericControl);
				if (ch != null && ch.TagName == "body") {
					ch.RenderChildren (writer);
					return;
				}
			}
		}
#endif
		base.Render (writer);
	}

	void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
	{
		writer.WriteLine ();
		ClientScriptManager.WriteBeginScriptBlock (writer);
		RenderClientScriptFormDeclaration (writer, formUniqueID);
		writer.WriteLine (WebFormScriptReference + "._form = " + theForm + ";");
		writer.WriteLine (WebFormScriptReference + ".__doPostBack = function (eventTarget, eventArgument) {");
		writer.WriteLine ("\tif(" + theForm + ".onsubmit && " + theForm + ".onsubmit() == false) return;");
		writer.WriteLine ("\t" + theForm + "." + postEventSourceID + ".value = eventTarget;");
		writer.WriteLine ("\t" + theForm + "." + postEventArgumentID + ".value = eventArgument;");
		writer.WriteLine ("\t" + theForm + ".submit();");
		writer.WriteLine ("}");
		ClientScriptManager.WriteEndScriptBlock (writer);
	}

	void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
	{
		if (formScriptDeclarationRendered)
			return;
		
		if (PageAdapter != null) {
 			writer.WriteLine ("\tvar {0} = {1};\n", theForm, PageAdapter.GetPostBackFormReference(formUniqueID));
		} else {
			writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
			writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
		}
#if TARGET_J2EE
		// TODO implement callback on portlet
		string serverUrl = Request.RawUrl;
		writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
		writer.WriteLine ("\twindow.TARGET_J2EE = true;");
		writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
#endif
		formScriptDeclarationRendered = true;
	}

	internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
	{
		if (renderingForm)
			throw new HttpException ("Only 1 HtmlForm is allowed per page.");

		renderingForm = true;
		writer.WriteLine ();

		if (requiresFormScriptDeclaration || (scriptManager != null && scriptManager.ScriptsPresent) || PageAdapter != null) {
			ClientScriptManager.WriteBeginScriptBlock (writer);
			RenderClientScriptFormDeclaration (writer, formUniqueID);
			ClientScriptManager.WriteEndScriptBlock (writer);
		}

		if (handleViewState)
#if TARGET_J2EE
			if (getFacesContext () != null) {
				javax.faces.application.ViewHandler viewHandler = getFacesContext ().getApplication ().getViewHandler ();
				javax.faces.context.ResponseWriter oldFacesWriter = SetupResponseWriter (writer);
				try {
					viewHandler.writeState (getFacesContext ());
				}
				finally {
					getFacesContext ().setResponseWriter (oldFacesWriter);
				}
			} else
#endif
				scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);

		scriptManager.WriteHiddenFields (writer);
		if (requiresPostBackScript) {
			RenderPostBackScript (writer, formUniqueID);
			postBackScriptRendered = true;
		}

		scriptManager.WriteWebFormClientScript (writer);
		scriptManager.WriteClientScriptBlocks (writer);
	}

	internal IStateFormatter GetFormatter ()
	{
		return new ObjectStateFormatter (this);
	}

	internal string GetSavedViewState ()
	{
		return _savedViewState;
	}

	internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
	{
		scriptManager.SaveEventValidationState ();
		scriptManager.WriteExpandoAttributes (writer);
		scriptManager.WriteHiddenFields (writer);
		if (!postBackScriptRendered && requiresPostBackScript)
			RenderPostBackScript (writer, formUniqueID);
		scriptManager.WriteWebFormClientScript (writer);
		scriptManager.WriteArrayDeclares (writer);
		scriptManager.WriteStartupScriptBlocks (writer);
		renderingForm = false;
		postBackScriptRendered = false;
	}

	void ProcessPostData (NameValueCollection data, bool second)
	{
		NameValueCollection requestValues = _requestValueCollection == null ? new NameValueCollection (SecureHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant) : _requestValueCollection;
		
		if (data != null && data.Count > 0) {
			var used = new Dictionary <string, string> (StringComparer.Ordinal);
			foreach (string id in data.AllKeys) {
				if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID || id == ClientScriptManager.EventStateFieldName)
					continue;
			
				if (used.ContainsKey (id))
					continue;

				used.Add (id, id);

				Control ctrl = FindControl (id, true);
				if (ctrl != null) {
					IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
					IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;

					if (pbdh == null) {
						if (pbeh != null)
							formPostedRequiresRaiseEvent = pbeh;
						continue;
					}
		
					if (pbdh.LoadPostData (id, requestValues) == true) {
						if (requiresPostDataChanged == null)
							requiresPostDataChanged = new List <IPostBackDataHandler> ();
						requiresPostDataChanged.Add (pbdh);
					}
				
					if (_requiresPostBackCopy != null)
						_requiresPostBackCopy.Remove (id);

				} else if (!second) {
					if (secondPostData == null)
						secondPostData = new NameValueCollection (SecureHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant);
					secondPostData.Add (id, data [id]);
				}
			}
		}

		List <string> list1 = null;
		if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
			string [] handlers = (string []) _requiresPostBackCopy.ToArray ();
			foreach (string id in handlers) {
				IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
				if (pbdh != null) {			
					_requiresPostBackCopy.Remove (id);
					if (pbdh.LoadPostData (id, requestValues)) {
						if (requiresPostDataChanged == null)
							requiresPostDataChanged = new List <IPostBackDataHandler> ();
	
						requiresPostDataChanged.Add (pbdh);
					}
				} else if (!second) {
					if (list1 == null)
						list1 = new List <string> ();
					list1.Add (id);
				}
			}
		}
		_requiresPostBackCopy = second ? null : list1;
		if (second)
			secondPostData = null;
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	public virtual void ProcessRequest (HttpContext context)
	{
		SetContext (context);
#if TARGET_J2EE
		bool wasException = false;
		IHttpHandler jsfHandler = getFacesContext () != null ? EnterThread () : null;
#endif
		
		if (clientTarget != null)
			Request.ClientTarget = clientTarget;

		WireupAutomaticEvents ();
		//-- Control execution lifecycle in the docs

		// Save culture information because it can be modified in FrameworkInitialize()
		_appCulture = Thread.CurrentThread.CurrentCulture;
		_appUICulture = Thread.CurrentThread.CurrentUICulture;
		FrameworkInitialize ();
#if NET_4_0
		frameworkInitialized = true;
#endif
		context.ErrorPage = _errorPage;

		try {
			InternalProcessRequest ();
#if TARGET_J2EE
		} catch (Exception ex) {
			wasException = true;
			HandleException (ex);
#else
		} catch (ThreadAbortException taex) {
			if (FlagEnd.Value == taex.ExceptionState)
				Thread.ResetAbort ();
			else
				throw;
		} catch (Exception e) {
			ProcessException (e);
#endif
		} finally {
#if TARGET_J2EE
			if (getFacesContext () != null)
				ExitThread (jsfHandler);
			else if (!wasException)
#endif
			ProcessUnload ();
		}
	}

	void ProcessException (Exception e) {
		// We want to remove that error, as we're rethrowing to stop
		// further processing.
		Trace.Warn ("Unhandled Exception", e.ToString (), e);
		_context.AddError (e); // OnError might access LastError
		OnError (EventArgs.Empty);
		if (_context.HasError (e)) {
			_context.ClearError (e);
			throw new HttpUnhandledException (null, e);
		}
	}

	void ProcessUnload () {
			try {
				RenderTrace ();
				UnloadRecursive (true);
			} catch {}
#if TARGET_J2EE
			if (getFacesContext () != null) {
				if(IsCrossPagePostBack)
					_context.Items [CrossPagePostBack] = this;
			}
#endif
			if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
				Thread.CurrentThread.CurrentCulture = _appCulture;

			if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
				Thread.CurrentThread.CurrentUICulture = _appUICulture;
			
			_appCulture = null;
			_appUICulture = null;
	}
	
	delegate void ProcessRequestDelegate (HttpContext context);

	sealed class DummyAsyncResult : IAsyncResult
	{
		readonly object state;
		readonly WaitHandle asyncWaitHandle;
		readonly bool completedSynchronously;
		readonly bool isCompleted;

		public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state) 
		{
			this.isCompleted = isCompleted;
			this.completedSynchronously = completedSynchronously;
			this.state = state;
			if (isCompleted) {
				asyncWaitHandle = new ManualResetEvent (true);
			}
			else {
				asyncWaitHandle = new ManualResetEvent (false);
			}
		}

		#region IAsyncResult Members

		public object AsyncState {
			get { return state; }
		}

		public WaitHandle AsyncWaitHandle {
			get { return asyncWaitHandle; }
		}

		public bool CompletedSynchronously {
			get { return completedSynchronously; }
		}

		public bool IsCompleted {
			get { return isCompleted; }
		}

		#endregion
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData) 
	{
		ProcessRequest (context);
		DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);

		if (callback != null) {
			callback (asyncResult);
		}
		
		return asyncResult;
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	protected void AsyncPageEndProcessRequest (IAsyncResult result) 
	{
	}
	
	void InternalProcessRequest ()
	{
		if (PageAdapter != null)
			_requestValueCollection = PageAdapter.DeterminePostBackMode();
		else
			_requestValueCollection = this.DeterminePostBackMode();

		// http://msdn2.microsoft.com/en-us/library/ms178141.aspx
		if (_requestValueCollection != null) {
			if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
				_doLoadPreviousPage = true;
			} else {
				isCallback = _requestValueCollection [CallbackArgumentID] != null;
				// LAMESPEC: on Callback IsPostBack is set to false, but true.
				//isPostBack = !isCallback;
				isPostBack = true;
			}
			
			string lastFocus = _requestValueCollection [LastFocusID];
			if (!String.IsNullOrEmpty (lastFocus))
				_focusedControlID = UniqueID2ClientID (lastFocus);
		}
		
		if (!isCrossPagePostBack) {
			if (_context.PreviousHandler is Page)
				previousPage = (Page) _context.PreviousHandler;
		}

		Trace.Write ("aspx.page", "Begin PreInit");
		OnPreInit (EventArgs.Empty);
		Trace.Write ("aspx.page", "End PreInit");

		InitializeTheme ();
		ApplyMasterPage ();
		Trace.Write ("aspx.page", "Begin Init");
		InitRecursive (null);
		Trace.Write ("aspx.page", "End Init");

		Trace.Write ("aspx.page", "Begin InitComplete");
		OnInitComplete (EventArgs.Empty);
		Trace.Write ("aspx.page", "End InitComplete");
			
		renderingForm = false;	

#if TARGET_J2EE
		if (getFacesContext () != null)
			if (IsPostBack || IsCallback)
				return;
#endif

		RestorePageState ();
		ProcessPostData ();
		ProcessRaiseEvents ();
		if (ProcessLoadComplete ())
			return;
#if TARGET_J2EE
		if (getFacesContext () != null) {
			getFacesContext ().renderResponse ();
			return;
		}
#endif
		RenderPage ();
	}

	void RestorePageState ()
	{
		if (IsPostBack || IsCallback) {
			if (_requestValueCollection != null)
				scriptManager.RestoreEventValidationState (
					_requestValueCollection [ClientScriptManager.EventStateFieldName]);
			Trace.Write ("aspx.page", "Begin LoadViewState");
			LoadPageViewState ();
			Trace.Write ("aspx.page", "End LoadViewState");
		}
	}

	void ProcessPostData ()
	{
		if (IsPostBack || IsCallback) {
			Trace.Write ("aspx.page", "Begin ProcessPostData");
			ProcessPostData (_requestValueCollection, false);
			Trace.Write ("aspx.page", "End ProcessPostData");
		}

		ProcessLoad ();
		if (IsPostBack || IsCallback) {
			Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
			ProcessPostData (secondPostData, true);
			Trace.Write ("aspx.page", "End ProcessPostData Second Try");
		}
	}

	void ProcessLoad ()
	{ 
		Trace.Write ("aspx.page", "Begin PreLoad");
		OnPreLoad (EventArgs.Empty);
		Trace.Write ("aspx.page", "End PreLoad");

		Trace.Write ("aspx.page", "Begin Load");
		LoadRecursive ();
		Trace.Write ("aspx.page", "End Load");
	}

	void ProcessRaiseEvents ()
	{
		if (IsPostBack || IsCallback) {
			Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
			RaiseChangedEvents ();
			Trace.Write ("aspx.page", "End Raise ChangedEvents");
			Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
			RaisePostBackEvents ();
			Trace.Write ("aspx.page", "End Raise PostBackEvent");
		}
	}

	bool ProcessLoadComplete ()
	{
		Trace.Write ("aspx.page", "Begin LoadComplete");
		OnLoadComplete (EventArgs.Empty);
		Trace.Write ("aspx.page", "End LoadComplete");

		if (IsCrossPagePostBack)
			return true;

		if (IsCallback) {
#if TARGET_J2EE
			if (getFacesContext () != null) {
				_callbackTarget = GetCallbackTarget ();
				ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError);
				return true;
			}
#endif
			string result = ProcessCallbackData ();
			HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
			callbackOutput.Write (result);
			callbackOutput.Flush ();
			return true;
		}
		
		Trace.Write ("aspx.page", "Begin PreRender");
		PreRenderRecursiveInternal ();
		Trace.Write ("aspx.page", "End PreRender");
		
		ExecuteRegisteredAsyncTasks ();

		Trace.Write ("aspx.page", "Begin PreRenderComplete");
		OnPreRenderComplete (EventArgs.Empty);
		Trace.Write ("aspx.page", "End PreRenderComplete");

		Trace.Write ("aspx.page", "Begin SaveViewState");
		SavePageViewState ();
		Trace.Write ("aspx.page", "End SaveViewState");
		
		Trace.Write ("aspx.page", "Begin SaveStateComplete");
		OnSaveStateComplete (EventArgs.Empty);
		Trace.Write ("aspx.page", "End SaveStateComplete");
		return false;
	}

	internal void RenderPage ()
	{
		scriptManager.ResetEventValidationState ();
		
		//--
		Trace.Write ("aspx.page", "Begin Render");
 		HtmlTextWriter output = CreateHtmlTextWriter (Response.Output);
		RenderControl (output);
		Trace.Write ("aspx.page", "End Render");
	}

	internal void SetContext (HttpContext context)
	{
		_context = context;

		_application = context.Application;
		_response = context.Response;
		_request = context.Request;
		_cache = context.Cache;
	}

	void RenderTrace ()
	{
		TraceManager traceManager = HttpRuntime.TraceManager;

		if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
			return;
		
		Trace.SaveData ();

		if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput) 
			return;

		if (!traceManager.LocalOnly || Context.Request.IsLocal) {
			HtmlTextWriter output = new HtmlTextWriter (Response.Output);
			Trace.Render (output);
		}
	}
	
	void RaisePostBackEvents ()
	{
		if (requiresRaiseEvent != null) {
			RaisePostBackEvent (requiresRaiseEvent, null);
			return;
		}

		if (formPostedRequiresRaiseEvent != null) {
			RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
			return;
		}
		
		NameValueCollection postdata = _requestValueCollection;
		if (postdata == null)
			return;

		string eventTarget = postdata [postEventSourceID];
		IPostBackEventHandler target;
		if (String.IsNullOrEmpty (eventTarget)) {
#if NET_4_0
			target = AutoPostBackControl as IPostBackEventHandler;
			if (target != null)
				RaisePostBackEvent (target, null);
			else
#endif
			if (formPostedRequiresRaiseEvent != null)
				RaisePostBackEvent (formPostedRequiresRaiseEvent, null);
			else
				Validate ();
			return;
		}

		target = FindControl (eventTarget, true) as IPostBackEventHandler;
#if NET_4_0
		if (target == null)
			target = AutoPostBackControl as IPostBackEventHandler;
#endif
		if (target == null)
			return;

		string eventArgument = postdata [postEventArgumentID];
		RaisePostBackEvent (target, eventArgument);
	}

	internal void RaiseChangedEvents ()
	{
		if (requiresPostDataChanged == null)
			return;

		foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
			ipdh.RaisePostDataChangedEvent ();

		requiresPostDataChanged = null;
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
	{
		sourceControl.RaisePostBackEvent (eventArgument);
	}
	
	[Obsolete ("The recommended alternative is ClientScript.RegisterArrayDeclaration(string arrayName, string arrayValue). http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public void RegisterArrayDeclaration (string arrayName, string arrayValue)
	{
		scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
	}

	[Obsolete ("The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public virtual void RegisterClientScriptBlock (string key, string script)
	{
		scriptManager.RegisterClientScriptBlock (key, script);
	}

	[Obsolete]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
	{
		scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
	}

	[MonoTODO("Not implemented, Used in HtmlForm")]
	internal void RegisterClientScriptFile (string a, string b, string c)
	{
		throw new NotImplementedException ();
	}

	[Obsolete ("The recommended alternative is ClientScript.RegisterOnSubmitStatement(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public void RegisterOnSubmitStatement (string key, string script)
	{
		scriptManager.RegisterOnSubmitStatement (key, script);
	}

	internal string GetSubmitStatements ()
	{
		return scriptManager.WriteSubmitStatements ();
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public void RegisterRequiresPostBack (Control control)
	{
		if (!(control is IPostBackDataHandler))
			throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
		
		if (_requiresPostBack == null)
			_requiresPostBack = new List <string> ();

		string uniqueID = control.UniqueID;
		if (_requiresPostBack.Contains (uniqueID))
			return;

		_requiresPostBack.Add (uniqueID);
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
	{
		requiresRaiseEvent = control;
	}

	[Obsolete ("The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public virtual void RegisterStartupScript (string key, string script)
	{
		scriptManager.RegisterStartupScript (key, script);
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public void RegisterViewStateHandler ()
	{
		handleViewState = true;
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	protected virtual void SavePageStateToPersistenceMedium (object viewState)
	{
		PageStatePersister persister = this.PageStatePersister;
		if (persister == null)
			return;
		Pair pair = viewState as Pair;
		if (pair != null) {
			persister.ViewState = pair.First;
			persister.ControlState = pair.Second;
		} else
			persister.ViewState = viewState;
		persister.Save ();
	}

	internal string RawViewState {
		get {
			NameValueCollection postdata = _requestValueCollection;
			string view_state;
			if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
				return null;

			if (view_state == String.Empty)
				return null;
			return view_state;
		}
		
		set { _savedViewState = value; }
	}


	protected virtual PageStatePersister PageStatePersister {
		get {
			if (page_state_persister == null && PageAdapter != null)
					page_state_persister = PageAdapter.GetStatePersister();					
			if (page_state_persister == null)
				page_state_persister = new HiddenFieldPageStatePersister (this);
			return page_state_persister;
		}
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	protected virtual object LoadPageStateFromPersistenceMedium ()
	{
		PageStatePersister persister = this.PageStatePersister;
		if (persister == null)
			return null;
		persister.Load ();
		return new Pair (persister.ViewState, persister.ControlState);
	}

	internal void LoadPageViewState ()
	{
		Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
		if (sState != null) {
			if (allow_load || isCrossPagePostBack) {
				LoadPageControlState (sState.Second);

				Pair vsr = sState.First as Pair;
				if (vsr != null) {
					LoadViewStateRecursive (vsr.First);
					_requiresPostBackCopy = vsr.Second as List <string>;
				}
			}
		}
	}

	internal void SavePageViewState ()
	{
		if (!handleViewState)
			return;

		object controlState = SavePageControlState ();
		Pair vsr = null;
		object viewState = null;
		
		if (EnableViewState
#if NET_4_0
		    && this.ViewStateMode == ViewStateMode.Enabled
#endif
		)
			viewState = SaveViewStateRecursive ();
		
		object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
		if (viewState != null || reqPostback != null)
			vsr = new Pair (viewState, reqPostback);

		Pair pair = new Pair ();
		pair.First = vsr;
		pair.Second = controlState;
		if (pair.First == null && pair.Second == null)
			SavePageStateToPersistenceMedium (null);
		else
			SavePageStateToPersistenceMedium (pair);

	}

	public virtual void Validate ()
	{
		is_validated = true;
		ValidateCollection (_validators);
	}

	internal bool AreValidatorsUplevel ()
	{
		return AreValidatorsUplevel (String.Empty);
	}

	internal bool AreValidatorsUplevel (string valGroup)
	{
		bool uplevel = false;

		foreach (IValidator v in Validators) {
			BaseValidator bv = v as BaseValidator;
			if (bv == null)
				continue;

			if (valGroup != bv.ValidationGroup)
				continue;
			if (bv.GetRenderUplevel()) {
				uplevel = true;
				break;
			}
		}

		return uplevel;
	}

	bool ValidateCollection (ValidatorCollection validators)
	{
		if (validators == null || validators.Count == 0)
			return true;

		bool all_valid = true;
		foreach (IValidator v in validators){
			v.Validate ();
			if (v.IsValid == false)
				all_valid = false;
		}

		return all_valid;
	}

	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public virtual void VerifyRenderingInServerForm (Control control)
	{
		if (Context == null)
			return;
		if (IsCallback)
			return;
		if (!renderingForm)
			throw new HttpException ("Control '" +
						 control.ClientID +
						 "' of type '" +
						 control.GetType ().Name +
						 "' must be placed inside a form tag with runat=server.");
	}

	protected override void FrameworkInitialize ()
	{
		base.FrameworkInitialize ();
		InitializeStyleSheet ();
	}
#endregion
	
	public ClientScriptManager ClientScript {
		get { return scriptManager; }
	}

	internal static readonly object InitCompleteEvent = new object ();
	internal static readonly object LoadCompleteEvent = new object ();
	internal static readonly object PreInitEvent = new object ();
	internal static readonly object PreLoadEvent = new object ();
	internal static readonly object PreRenderCompleteEvent = new object ();
	internal static readonly object SaveStateCompleteEvent = new object ();
	int event_mask;
	const int initcomplete_mask = 1;
	const int loadcomplete_mask = 1 << 1;
	const int preinit_mask = 1 << 2;
	const int preload_mask = 1 << 3;
	const int prerendercomplete_mask = 1 << 4;
	const int savestatecomplete_mask = 1 << 5;
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public event EventHandler InitComplete {
		add {
			event_mask |= initcomplete_mask;
			Events.AddHandler (InitCompleteEvent, value);
		}
		remove { Events.RemoveHandler (InitCompleteEvent, value); }
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public event EventHandler LoadComplete {
		add {
			event_mask |= loadcomplete_mask;
			Events.AddHandler (LoadCompleteEvent, value);
		}
		remove { Events.RemoveHandler (LoadCompleteEvent, value); }
	}
	
	public event EventHandler PreInit {
		add {
			event_mask |= preinit_mask;
			Events.AddHandler (PreInitEvent, value);
		}
		remove { Events.RemoveHandler (PreInitEvent, value); }
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public event EventHandler PreLoad {
		add {
			event_mask |= preload_mask;
			Events.AddHandler (PreLoadEvent, value);
		}
		remove { Events.RemoveHandler (PreLoadEvent, value); }
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public event EventHandler PreRenderComplete {
		add {
			event_mask |= prerendercomplete_mask;
			Events.AddHandler (PreRenderCompleteEvent, value);
		}
		remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public event EventHandler SaveStateComplete {
		add {
			event_mask |= savestatecomplete_mask;
			Events.AddHandler (SaveStateCompleteEvent, value);
		}
		remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
	}
	
	protected virtual void OnInitComplete (EventArgs e)
	{
		if ((event_mask & initcomplete_mask) != 0) {
			EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
			if (eh != null) eh (this, e);
		}
	}
	
	protected virtual void OnLoadComplete (EventArgs e)
	{
		if ((event_mask & loadcomplete_mask) != 0) {
			EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
			if (eh != null) eh (this, e);
		}
	}
	
	protected virtual void OnPreInit (EventArgs e)
	{
		if ((event_mask & preinit_mask) != 0) {
			EventHandler eh = (EventHandler) (Events [PreInitEvent]);
			if (eh != null) eh (this, e);
		}
	}
	
	protected virtual void OnPreLoad (EventArgs e)
	{
		if ((event_mask & preload_mask) != 0) {
			EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
			if (eh != null) eh (this, e);
		}
	}
	
	protected virtual void OnPreRenderComplete (EventArgs e)
	{
		if ((event_mask & prerendercomplete_mask) != 0) {
			EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
			if (eh != null) eh (this, e);
		}

		if (Form == null)
			return;
		if (!Form.DetermineRenderUplevel ())
			return;

		string defaultButtonId = Form.DefaultButton;
		/* figure out if we have some control we're going to focus */
		if (String.IsNullOrEmpty (_focusedControlID)) {
			_focusedControlID = Form.DefaultFocus;
			if (String.IsNullOrEmpty (_focusedControlID))
				_focusedControlID = defaultButtonId;
		}

		if (!String.IsNullOrEmpty (_focusedControlID)) {
			ClientScript.RegisterWebFormClientScript ();
			
			ClientScript.RegisterStartupScript (
				typeof(Page),
				"HtmlForm-DefaultButton-StartupScript",
				"\n" + WebFormScriptReference + ".WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
		}
		
		if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
			ClientScript.RegisterWebFormClientScript ();

			ClientScript.RegisterOnSubmitStatement (
				typeof (Page),
				"HtmlForm-SubmitDisabledControls-SubmitStatement",
				WebFormScriptReference + ".WebForm_ReEnableControls();");
		}
	}

	internal void RegisterEnabledControl (Control control)
	{
		if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
			return;
		_hasEnabledControlArray = true;
		Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
	}
	
	protected virtual void OnSaveStateComplete (EventArgs e)
	{
		if ((event_mask & savestatecomplete_mask) != 0) {
			EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
			if (eh != null) eh (this, e);
		}
	}
	
	public HtmlForm Form {
		get { return _form; }
	}
	
	internal void RegisterForm (HtmlForm form)
	{
		_form = form;
	}

	public string ClientQueryString {
		get { return Request.UrlComponents.Query; }
	}

	[BrowsableAttribute (false)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public Page PreviousPage {
		get {
			if (_doLoadPreviousPage) {
				_doLoadPreviousPage = false;
				LoadPreviousPageReference ();
			}
			return previousPage;
		}
	}

	
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public bool IsCallback {
		get { return isCallback; }
	}
	
	[BrowsableAttribute (false)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public bool IsCrossPagePostBack {
		get { return isCrossPagePostBack; }
	}

	[Browsable (false)]
	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public new virtual char IdSeparator {
		get {
			//TODO: why override?
			return base.IdSeparator;
		}
	}
	
	string ProcessCallbackData ()
	{
		ICallbackEventHandler target = GetCallbackTarget ();
		string callbackEventError = String.Empty;
		ProcessRaiseCallbackEvent (target, ref callbackEventError);
		return ProcessGetCallbackResult (target, callbackEventError);
	}

	ICallbackEventHandler GetCallbackTarget ()
	{
		string callbackTarget = _requestValueCollection [CallbackSourceID];
		if (callbackTarget == null || callbackTarget.Length == 0)
			throw new HttpException ("Callback target not provided.");

		Control targetControl = FindControl (callbackTarget, true);
		ICallbackEventHandler target = targetControl as ICallbackEventHandler;
		if (target == null)
			throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
		return target;
	}

	void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError)
	{
		string callbackArgument = _requestValueCollection [CallbackArgumentID];

		try {
			target.RaiseCallbackEvent (callbackArgument);
		} catch (Exception ex) {
			callbackEventError = String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
		}
		
	}

	string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError)
	{
		string callBackResult;
		try {
			callBackResult = target.GetCallbackResult ();
		} catch (Exception ex) {
			return String.Concat ("e", RuntimeHelpers.DebuggingEnabled ? ex.ToString () : ex.Message);
		}
		
		string eventValidation = ClientScript.GetEventValidationStateFormatted ();
		return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
			eventValidation + callBackResult;
	}

	[BrowsableAttribute (false)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public HtmlHead Header {
		get { return htmlHeader; }
	}
	
	internal void SetHeader (HtmlHead header)
	{
		htmlHeader = header;
		if (header == null)
			return;
		
		if (_title != null) {
			htmlHeader.Title = _title;
			_title = null;
		}
#if NET_4_0
		if (_metaDescription != null) {
			htmlHeader.Description = _metaDescription;
			_metaDescription = null;
		}

		if (_metaKeywords != null) {
			htmlHeader.Keywords = _metaKeywords;
			_metaKeywords = null;
		}
#endif
	}

	[EditorBrowsable (EditorBrowsableState.Never)]
	protected bool AsyncMode {
		get { return asyncMode; }
		set { asyncMode = value; }
	}

	[Browsable (false)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public TimeSpan AsyncTimeout {
		get { return asyncTimeout; }
		set { asyncTimeout = value; }
	}

	public bool IsAsync {
		get { return AsyncMode; }
	}	

	protected internal virtual string UniqueFilePathSuffix {
		get {
			if (String.IsNullOrEmpty (uniqueFilePathSuffix))
				uniqueFilePathSuffix = "__ufps=" + AppRelativeVirtualPath.GetHashCode ().ToString ("x");
			return uniqueFilePathSuffix;
		}
	}

	[MonoTODO ("Actually use the value in code.")]
	[Browsable (false)]
	[EditorBrowsable (EditorBrowsableState.Never)]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	public int MaxPageStateFieldLength {
		get { return maxPageStateFieldLength; }
		set { maxPageStateFieldLength = value; }
	}

	public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
	{
		AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
	}

	public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
	{
		if (!IsAsync) {
			throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
		}

		if (IsPrerendered) {
			throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
		}

		if (beginHandler == null) {
			throw new ArgumentNullException ("beginHandler");
		}

		if (endHandler == null) {
			throw new ArgumentNullException ("endHandler");
		}

		RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
	}

	List<PageAsyncTask> ParallelTasks {
		get {
			if (parallelTasks == null)
				parallelTasks = new List<PageAsyncTask>();
			return parallelTasks;
		}
	}

	List<PageAsyncTask> SerialTasks {
		get {
			if (serialTasks == null)
				serialTasks = new List<PageAsyncTask> ();
			return serialTasks;
		}
	}

	public void RegisterAsyncTask (PageAsyncTask task) 
	{
		if (task == null)
			throw new ArgumentNullException ("task");

		if (task.ExecuteInParallel)
			ParallelTasks.Add (task);
		else
			SerialTasks.Add (task);
	}

	public void ExecuteRegisteredAsyncTasks ()
	{
		if ((parallelTasks == null || parallelTasks.Count == 0) &&
			(serialTasks == null || serialTasks.Count == 0)){
			return;
		}

		if (parallelTasks != null) {
			DateTime startExecution = DateTime.Now;
			List<PageAsyncTask> localParallelTasks = parallelTasks;
			parallelTasks = null; // Shouldn't execute tasks twice
			List<IAsyncResult> asyncResults = new List<IAsyncResult>();
			foreach (PageAsyncTask parallelTask in localParallelTasks) {
				IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask);
				if (result.CompletedSynchronously)
					parallelTask.EndHandler (result);
				else
					asyncResults.Add (result);
			}

			if (asyncResults.Count > 0) {
				WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
				int i = 0;
				for (i = 0; i < asyncResults.Count; i++) {
					waitArray [i] = asyncResults [i].AsyncWaitHandle;
				}
				
				bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
				if (!allSignalled) {
					for (i = 0; i < asyncResults.Count; i++) {
						if (!asyncResults [i].IsCompleted) {
							localParallelTasks [i].TimeoutHandler (asyncResults [i]);
						}
					}
				}
			}
			DateTime endWait = DateTime.Now;
			TimeSpan elapsed = endWait - startExecution;
			if (elapsed <= AsyncTimeout)
				AsyncTimeout -= elapsed;
			else
				AsyncTimeout = TimeSpan.FromTicks(0);
		}

		if (serialTasks != null) {
			List<PageAsyncTask> localSerialTasks = serialTasks;
			serialTasks = null; // Shouldn't execute tasks twice
			foreach (PageAsyncTask serialTask in localSerialTasks) {
				DateTime startExecution = DateTime.Now;

				IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
				if (result.CompletedSynchronously)
					serialTask.EndHandler (result);
				else {
					bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
					if (!done && !result.IsCompleted) {
						serialTask.TimeoutHandler (result);
					}
				}
				DateTime endWait = DateTime.Now;
				TimeSpan elapsed = endWait - startExecution;
				if (elapsed <= AsyncTimeout)
					AsyncTimeout -= elapsed;
				else
					AsyncTimeout = TimeSpan.FromTicks (0);
			}
		}
		AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
	}

	void EndAsyncTaskCallback (IAsyncResult result) 
	{
		PageAsyncTask task = (PageAsyncTask)result.AsyncState;
		task.EndHandler (result);
	}

	public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
	{
		Type htmlTextWriterType = typeof (HtmlTextWriter);
		
		if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
			throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
		}

		ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
		if (constructor == null) {
			throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
		}

		return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
	}

	[Browsable (false)]
	[DefaultValue ("0")]
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[EditorBrowsable (EditorBrowsableState.Never)]
	public ViewStateEncryptionMode ViewStateEncryptionMode {
		get { return viewStateEncryptionMode; }
		set { viewStateEncryptionMode = value; }
	}

	public void RegisterRequiresViewStateEncryption ()
	{
		controlRegisteredForViewStateEncryption = true;
	}

	internal bool NeedViewStateEncryption {
		get {
			return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
					(ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
					 controlRegisteredForViewStateEncryption));

		}
	}

	void ApplyMasterPage ()
	{
		if (masterPageFile != null && masterPageFile.Length > 0) {
			MasterPage master = Master;
			
			if (master != null) {
				var appliedMasterPageFiles = new Dictionary <string, bool> (StringComparer.Ordinal);
				MasterPage.ApplyMasterPageRecursive (Request.CurrentExecutionFilePath, HostingEnvironment.VirtualPathProvider, master, appliedMasterPageFiles);
				master.Page = this;
				Controls.Clear ();
				Controls.Add (master);
			}
		}
	}

	[DefaultValueAttribute ("")]
	public virtual string MasterPageFile {
		get { return masterPageFile; }
		set {
			masterPageFile = value;
			masterPage = null;
		}
	}
	
	[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
	[BrowsableAttribute (false)]
	public MasterPage Master {
		get {
			if (Context == null || String.IsNullOrEmpty (masterPageFile))
				return null;

			if (masterPage == null)
				masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);

			return masterPage;
		}
	}
	
	public void SetFocus (string clientID)
	{
		if (String.IsNullOrEmpty (clientID))
			throw new ArgumentNullException ("control");

		if (IsPrerendered)
			throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");

		if(Form==null)
			throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");

		_focusedControlID = clientID;
	}

	public void SetFocus (Control control)
	{
		if (control == null)
			throw new ArgumentNullException ("control");

		SetFocus (control.ClientID);
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public void RegisterRequiresControlState (Control control)
	{
		if (control == null)
			throw new ArgumentNullException ("control");

		if (RequiresControlState (control))
			return;

		if (requireStateControls == null)
			requireStateControls = new List <Control> ();
		requireStateControls.Add (control);
		int n = requireStateControls.Count - 1;
		
		if (_savedControlState == null || n >= _savedControlState.Length) 
			return;

		for (Control parent = control.Parent; parent != null; parent = parent.Parent)
			if (parent.IsChildControlStateCleared)
				return;

		object state = _savedControlState [n];
		if (state != null)
			control.LoadControlState (state);
	}
	
	public bool RequiresControlState (Control control)
	{
		if (requireStateControls == null)
			return false;
		return requireStateControls.Contains (control);
	}
	
	[EditorBrowsable (EditorBrowsableState.Advanced)]
	public void UnregisterRequiresControlState (Control control)
	{
		if (requireStateControls != null)
			requireStateControls.Remove (control);
	}
	
	public ValidatorCollection GetValidators (string validationGroup)
	{			
		if (validationGroup == String.Empty)
			validationGroup = null;

		ValidatorCollection col = new ValidatorCollection ();
		if (_validators == null)
			return col;
		
		foreach (IValidator v in _validators)
			if (BelongsToGroup(v, validationGroup))
				col.Add(v);

		return col;
	}
	
	bool BelongsToGroup(IValidator v, string validationGroup)
	{
		BaseValidator validator = v as BaseValidator;
		if (validationGroup == null)
			return validator == null || String.IsNullOrEmpty (validator.ValidationGroup); 
		else
			return validator != null && validator.ValidationGroup == validationGroup; 			
	}
	
	public virtual void Validate (string validationGroup)
	{
		is_validated = true;
		ValidateCollection (GetValidators (validationGroup));
	}

	object SavePageControlState ()
	{
		int count = requireStateControls == null ? 0 : requireStateControls.Count;
		if (count == 0)
			return null;
		
		object state;
		object[] controlStates = new object [count];
		object[] adapterState = new object [count];
		Control control;
		ControlAdapter adapter;
		bool allNull = true;
		TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
		
		for (int n = 0; n < count; n++) {
			control = requireStateControls [n];
			state = controlStates [n] = control.SaveControlState ();
			if (state != null)
				allNull = false;
			
			if (trace != null)
				trace.SaveControlState (control, state);

			adapter = control.Adapter;
			if (adapter != null) {
				adapterState [n] = adapter.SaveAdapterControlState ();
				if (adapterState [n] != null) allNull = false;
			}
		}
		
		if (allNull)
			return null;
		else
			return new Pair (controlStates, adapterState);
	}
	
	void LoadPageControlState (object data)
	{
		_savedControlState = null;
		if (data == null) return;
		Pair statePair = (Pair)data;
		_savedControlState = (object[]) statePair.First;
		object[] adapterState = (object[]) statePair.Second;

		if (requireStateControls == null) return;

		int min = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
		for (int n=0; n < min; n++) {
			Control ctl = (Control) requireStateControls [n];
			ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
			if (ctl.Adapter != null)
				ctl.Adapter.LoadAdapterControlState (adapterState != null ? adapterState [n] : null);
		}
	}

	void LoadPreviousPageReference ()
	{
		if (_requestValueCollection != null) {
			string prevPage = _requestValueCollection [PreviousPageID];
			if (prevPage != null) {
#if TARGET_J2EE
				if (getFacesContext () != null) {
					IHttpHandler handler = Context.ApplicationInstance.GetHandler (Context, prevPage);
					Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
					if (_context.Items.Contains (CrossPagePostBack)) {
						previousPage = (Page) _context.Items [CrossPagePostBack];
						_context.Items.Remove (CrossPagePostBack);
					}
					return;
				}
#else
				IHttpHandler handler;
				handler = BuildManager.CreateInstanceFromVirtualPath (prevPage, typeof (IHttpHandler)) as IHttpHandler;
				previousPage = (Page) handler;
				previousPage.isCrossPagePostBack = true;
				Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
#endif
			} 
		}
	}

	Hashtable contentTemplates;
	[EditorBrowsable (EditorBrowsableState.Never)]
	protected internal void AddContentTemplate (string templateName, ITemplate template)
	{
		if (contentTemplates == null)
			contentTemplates = new Hashtable ();
		contentTemplates [templateName] = template;
	}

	PageTheme _pageTheme;
	internal PageTheme PageTheme {
		get { return _pageTheme; }
	}

	PageTheme _styleSheetPageTheme;
	internal PageTheme StyleSheetPageTheme {
		get { return _styleSheetPageTheme; }
	}

	Stack dataItemCtx;
	
	internal void PushDataItemContext (object o) {
		if (dataItemCtx == null)
			dataItemCtx = new Stack ();
		
		dataItemCtx.Push (o);
	}
	
	internal void PopDataItemContext () {
		if (dataItemCtx == null)
			throw new InvalidOperationException ();
		
		dataItemCtx.Pop ();
	}
	
	public object GetDataItem() {
		if (dataItemCtx == null || dataItemCtx.Count == 0)
			throw new InvalidOperationException ("No data item");
		
		return dataItemCtx.Peek ();
	}

	void AddStyleSheets (PageTheme theme, ref List <string> links)
	{
		if (theme == null)
			return;

		string[] tmpThemes = theme != null ? theme.GetStyleSheets () : null;
		if (tmpThemes == null || tmpThemes.Length == 0)
			return;

		if (links == null)
			links = new List <string> ();

		links.AddRange (tmpThemes);
	}
	
	protected internal override void OnInit (EventArgs e)
	{
		base.OnInit (e);

		List <string> themes = null;
		AddStyleSheets (StyleSheetPageTheme, ref themes);
		AddStyleSheets (PageTheme, ref themes);

		if (themes == null)
			return;
		
		HtmlHead header = Header;
		if (themes != null && header == null)
			throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
		
		ControlCollection headerControls = header.Controls;
		string lss;
		for (int i = themes.Count - 1; i >= 0; i--) {
			lss = themes [i];
			HtmlLink hl = new HtmlLink ();
			hl.Href = lss;
			hl.Attributes["type"] = "text/css";
			hl.Attributes["rel"] = "stylesheet";
			headerControls.AddAt (0, hl);
		}
	}

	[MonoDocumentationNote ("Not implemented.  Only used by .net aspx parser")]
	[EditorBrowsable (EditorBrowsableState.Never)]
	protected object GetWrappedFileDependencies (string [] list)
	{
		return list;
	}

	[MonoDocumentationNote ("Does nothing.  Used by .net aspx parser")]
	protected virtual void InitializeCulture ()
	{
	}

	[MonoDocumentationNote ("Does nothing. Used by .net aspx parser")]
	[EditorBrowsable (EditorBrowsableState.Never)]
	protected internal void AddWrappedFileDependencies (object virtualFileDependencies)
	{
	}
}
}