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

Control.cs « UI « System.Web « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7a21a881ad31bc5c73e652ddcd35b79bf8875b50 (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
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
//------------------------------------------------------------------------------
// <copyright file="Control.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI {
    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.ComponentModel.Design.Serialization;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Security.Permissions;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Caching;
    using System.Web.Configuration;
    using System.Web.Hosting;
    using System.Web.Routing;
    using System.Web.UI.Adapters;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.Util;
    using HttpException = System.Web.HttpException;

    // Delegate used for the compiled template
    public delegate void RenderMethod(HtmlTextWriter output, Control container);

    public delegate Control BuildMethod();

    // Defines the properties, methods, and events that are shared by all server
    // controls in the Web Forms page framework.</para>
    [
    Bindable(true),
    DefaultProperty("ID"),
    DesignerCategory("Code"),
    Designer("System.Web.UI.Design.ControlDesigner, " + AssemblyRef.SystemDesign),
    DesignerSerializer("Microsoft.VisualStudio.Web.WebForms.ControlCodeDomSerializer, " + AssemblyRef.MicrosoftVisualStudioWeb,  "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign),
    Themeable(false),
    ToolboxItemFilter("System.Web.UI", ToolboxItemFilterType.Require),
    ToolboxItemAttribute("System.Web.UI.Design.WebControlToolboxItem, " + AssemblyRef.SystemDesign)
    ]
    public class Control : IComponent, IParserAccessor, IUrlResolutionService, IDataBindingsAccessor, IControlBuilderAccessor, IControlDesignerAccessor, IExpressionsAccessor {

        internal static readonly object EventDataBinding = new object();
        internal static readonly object EventInit = new object();
        internal static readonly object EventLoad = new object();
        internal static readonly object EventUnload = new object();
        internal static readonly object EventPreRender = new object();
        private static readonly object EventDisposed = new object();

        internal const bool EnableViewStateDefault = true;
        internal const char ID_SEPARATOR = '$';
        private const char ID_RENDER_SEPARATOR = '_';
        internal const char LEGACY_ID_SEPARATOR = ':';

        private string _id;
        // allows us to reuse the id variable to store a calculated id w/o polluting the public getter
        private string _cachedUniqueID;
        private string _cachedPredictableID;
        private Control _parent;

        // fields related to being a container
        private ControlState _controlState;
        private StateBag _viewState;

        private EventHandlerList _events;
        private ControlCollection _controls;

        // The naming container that this control leaves in.  Note that even if
        // this ctrl is a naming container, it will not point to itself, but to
        // the naming container that contains it.
        private Control _namingContainer;
        internal Page _page;
        private OccasionalFields _occasionalFields;
        // The virtual directory of the Page or UserControl that hosts this control.

        // const masks into the BitVector32
        private const int idNotCalculated           = 0x00000001;
        private const int marked                    = 0x00000002;
        private const int disableViewState          = 0x00000004;
        private const int controlsCreated           = 0x00000008;
        private const int invisible                 = 0x00000010;
        private const int visibleDirty              = 0x00000020;
        private const int idNotRequired             = 0x00000040;
        private const int isNamingContainer         = 0x00000080;
        private const int creatingControls          = 0x00000100;
        private const int notVisibleOnPage          = 0x00000200;
        private const int themeApplied              = 0x00000400;
        private const int mustRenderID              = 0x00000800;
        private const int disableTheming            = 0x00001000;
        private const int enableThemingSet          = 0x00002000;
        private const int styleSheetApplied         = 0x00004000;
        private const int controlAdapterResolved    = 0x00008000;
        private const int designMode                = 0x00010000;
        private const int designModeChecked         = 0x00020000;
        private const int disableChildControlState  = 0x00040000;
        internal const int isWebControlDisabled     = 0x00080000;
        private const int controlStateApplied       = 0x00100000;
        private const int useGeneratedID            = 0x00200000;
        private const int validateRequestModeDirty  = 0x00400000;
        private const int viewStateNotInherited     = 0x00800000;
        private const int viewStateMode             = 0x01000000;
        private const int clientIDMode              = 0x06000000;
        private const int clientIDModeOffset        = 25;
        private const int effectiveClientIDMode     = 0x18000000;
        private const int effectiveClientIDModeOffset = 27;
        private const int validateRequestMode       = 0x60000000;
        private const int validateRequestModeOffset = 29;
        #pragma warning disable 0649
        internal SimpleBitVector32 flags;
        #pragma warning restore 0649

        private const string automaticIDPrefix = "ctl";
        private const string automaticLegacyIDPrefix = "_ctl";
        private const int automaticIDCount = 128;
        private static readonly string[] automaticIDs = new string [automaticIDCount] {
            "ctl00", "ctl01", "ctl02", "ctl03", "ctl04", "ctl05", "ctl06",
            "ctl07", "ctl08", "ctl09", "ctl10", "ctl11", "ctl12", "ctl13",
            "ctl14", "ctl15", "ctl16", "ctl17", "ctl18", "ctl19", "ctl20",
            "ctl21", "ctl22", "ctl23", "ctl24", "ctl25", "ctl26", "ctl27",
            "ctl28", "ctl29", "ctl30", "ctl31", "ctl32", "ctl33", "ctl34",
            "ctl35", "ctl36", "ctl37", "ctl38", "ctl39", "ctl40", "ctl41",
            "ctl42", "ctl43", "ctl44", "ctl45", "ctl46", "ctl47", "ctl48",
            "ctl49", "ctl50", "ctl51", "ctl52", "ctl53", "ctl54", "ctl55",
            "ctl56", "ctl57", "ctl58", "ctl59", "ctl60", "ctl61", "ctl62",
            "ctl63", "ctl64", "ctl65", "ctl66", "ctl67", "ctl68", "ctl69",
            "ctl70", "ctl71", "ctl72", "ctl73", "ctl74", "ctl75", "ctl76",
            "ctl77", "ctl78", "ctl79", "ctl80", "ctl81", "ctl82", "ctl83",
            "ctl84", "ctl85", "ctl86", "ctl87", "ctl88", "ctl89", "ctl90",
            "ctl91", "ctl92", "ctl93", "ctl94", "ctl95", "ctl96", "ctl97",
            "ctl98", "ctl99",
            "ctl100", "ctl101", "ctl102", "ctl103", "ctl104", "ctl105", "ctl106",
            "ctl107", "ctl108", "ctl109", "ctl110", "ctl111", "ctl112", "ctl113",
            "ctl114", "ctl115", "ctl116", "ctl117", "ctl118", "ctl119", "ctl120",
            "ctl121", "ctl122", "ctl123", "ctl124", "ctl125", "ctl126", "ctl127"

        };

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Web.UI.Control'/> class.</para>
        /// </devdoc>
        public Control() {
            if (this is INamingContainer)
                flags.Set(isNamingContainer);
        }

        private ClientIDMode ClientIDModeValue {
            get {
                return (ClientIDMode)flags[clientIDMode, clientIDModeOffset];
            }
            set {
                flags[clientIDMode, clientIDModeOffset] = (int)value;
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId="Member")]
        [
        DefaultValue(ClientIDMode.Inherit),
        Themeable(false),
        WebCategory("Behavior"),
        WebSysDescription(SR.Control_ClientIDMode)
        ]
        public virtual ClientIDMode ClientIDMode {
            get {
                return ClientIDModeValue;
            }
            set {
                if (ClientIDModeValue != value) {
                    if (value != EffectiveClientIDModeValue) {
                        ClearEffectiveClientIDMode();
                        ClearCachedClientID();
                    }
                    ClientIDModeValue = value;
                }
            }
        }

        private ClientIDMode EffectiveClientIDModeValue {
            get {
                return (ClientIDMode)flags[effectiveClientIDMode, effectiveClientIDModeOffset];
            }
            set {
                flags[effectiveClientIDMode, effectiveClientIDModeOffset] = (int)value;
            }
        }

        internal virtual ClientIDMode EffectiveClientIDMode {
            get {
                if (EffectiveClientIDModeValue == ClientIDMode.Inherit) {
                    EffectiveClientIDModeValue = ClientIDMode;
                    if (EffectiveClientIDModeValue == ClientIDMode.Inherit) {
                        if (NamingContainer != null) {
                            EffectiveClientIDModeValue = NamingContainer.EffectiveClientIDMode;
                        }
                        else {
                            HttpContext context = Context;
                            if (context != null) {
                                EffectiveClientIDModeValue = RuntimeConfig.GetConfig(context).Pages.ClientIDMode;
                            }
                            else {
                                EffectiveClientIDModeValue = RuntimeConfig.GetConfig().Pages.ClientIDMode;
                            }
                        }
                    }
                }
                return EffectiveClientIDModeValue;
            }
        }

        internal string UniqueClientID {
            get {
                string uniqueID = UniqueID;
                if(uniqueID != null && uniqueID.IndexOf(IdSeparator) >= 0) {
                    return uniqueID.Replace(IdSeparator, ID_RENDER_SEPARATOR);
                }
                return uniqueID;
            }
        }

        internal string StaticClientID {
            get {
                return flags[useGeneratedID] ? String.Empty : ID ?? String.Empty;
            }
        }

        internal ControlAdapter AdapterInternal {
            get {
                if (_occasionalFields == null ||
                    _occasionalFields.RareFields == null ||
                    _occasionalFields.RareFields.Adapter == null) {
                        return null;
                }
                return _occasionalFields.RareFields.Adapter;
            }
            set {
                if (value != null) {
                    RareFieldsEnsured.Adapter = value;
                }
                else {
                    if (_occasionalFields != null &&
                        _occasionalFields.RareFields != null &&
                        _occasionalFields.RareFields.Adapter != null) {
                            _occasionalFields.RareFields.Adapter = null;
                    }
                }
            }
        }
        
        private string GetClientID() {
            switch (EffectiveClientIDMode) {
                case ClientIDMode.Predictable:
                    return PredictableClientID;
                case ClientIDMode.Static:
                    return StaticClientID;
                default:
                    return UniqueClientID;
            }
        }

        private string GetPredictableClientIDPrefix() {
            string predictableIDPrefix;

            Control namingContainer = NamingContainer;
            if (namingContainer != null) {
                if (_id == null) {
                    GenerateAutomaticID();
                }
                if (namingContainer is Page || namingContainer is MasterPage) {
                    predictableIDPrefix = _id;
                }
                else {
                    predictableIDPrefix = namingContainer.GetClientID();
                    if (String.IsNullOrEmpty(predictableIDPrefix)) {
                        predictableIDPrefix = _id;
                    }
                    else {
                        if (!String.IsNullOrEmpty(_id) && (!(this is IDataItemContainer) || (this is IDataBoundItemControl))) {
                            predictableIDPrefix = predictableIDPrefix + ID_RENDER_SEPARATOR + _id;
                        }
                    }
                }
            }
            else {
                predictableIDPrefix = _id;
            }
            return predictableIDPrefix;
        }

        private string GetPredictableClientIDSuffix() {
            string predictableIDSuffix = null;

            Control dataItemContainer = DataItemContainer;
            if (dataItemContainer != null && 
                !(dataItemContainer is IDataBoundItemControl) &&
                (!(this is IDataItemContainer) || (this is IDataBoundItemControl))) {
                Control dataKeysContainer = dataItemContainer.DataKeysContainer;
                if (dataKeysContainer != null && (((IDataKeysControl)dataKeysContainer).ClientIDRowSuffix != null) && (((IDataKeysControl)dataKeysContainer).ClientIDRowSuffix.Length > 0)) {
                    predictableIDSuffix = String.Empty;
                    IOrderedDictionary dataKey = ((IDataKeysControl)dataKeysContainer).ClientIDRowSuffixDataKeys[((IDataItemContainer)dataItemContainer).DisplayIndex].Values;
                    foreach (string suffixName in ((IDataKeysControl)dataKeysContainer).ClientIDRowSuffix) {
                        predictableIDSuffix = predictableIDSuffix + ID_RENDER_SEPARATOR + dataKey[suffixName].ToString();
                    }
                }
                else {
                    int index = ((IDataItemContainer)dataItemContainer).DisplayIndex;
                    if (index >= 0) {
                        predictableIDSuffix = ID_RENDER_SEPARATOR + index.ToString(CultureInfo.InvariantCulture);
                    }
                }
            }
            return predictableIDSuffix;
        }

        internal string PredictableClientID {
            get {
                if (_cachedPredictableID != null) {
                    return _cachedPredictableID;
                }

                _cachedPredictableID = GetPredictableClientIDPrefix();
                string suffixID = GetPredictableClientIDSuffix();

                // Concatenates Predictable clientID and ClientIDRowSuffix if available
                if (!String.IsNullOrEmpty(suffixID)) {
                    if (!String.IsNullOrEmpty(_cachedPredictableID)) {
                        _cachedPredictableID = _cachedPredictableID + suffixID;
                    }
                    else {
                        _cachedPredictableID = suffixID.Substring(1);
                    }
                }
                return String.IsNullOrEmpty(_cachedPredictableID) ? String.Empty : _cachedPredictableID;
            }
        }

        /// <devdoc>
        ///    <para>Indicates the control identifier generated by the ASP.NET framework. </para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_ClientID)
        ]
        public virtual string ClientID {
            // This property is required to render a unique client-friendly id.
            get {
                if (EffectiveClientIDMode != ClientIDMode.Static) {
                    // Ensure that ID is set. The assumption being made is that the caller
                    // is likely to use the client ID in script, and to support that the
                    // control should render out an ID attribute
                    EnsureID();
                }
                return GetClientID();
            }
        }

        protected char ClientIDSeparator {
            get {
                return ID_RENDER_SEPARATOR;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        WebSysDescription(SR.Control_OnDisposed)
        ]
        public event EventHandler Disposed {
            add {
                Events.AddHandler(EventDisposed, value);
            }
            remove {
                Events.RemoveHandler(EventDisposed, value);
            }
        }

        /// <devdoc>
        /// <para>Gets the <see langword='HttpContext'/> object of the current Web request. If
        ///    the control's context is <see langword='null'/>, this will be the context of the
        ///    control's parent, unless the parent control's context is <see langword='null'/>.
        ///    If this is the case, this will be equal to the HttpContext property.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        protected internal virtual HttpContext Context {
            //  Request context containing the intrinsics
            get {
                Page page = Page;
                if(page != null) {
                    return page.Context;
                }
                return HttpContext.Current;
            }
        }

        protected virtual ControlAdapter ResolveAdapter() {
            if(flags[controlAdapterResolved]) {
                return AdapterInternal;
            }
            if (DesignMode) {
                flags.Set(controlAdapterResolved);
                return null;
            }

            HttpContext context = Context;
            if (context != null && context.Request.Browser != null) {
                AdapterInternal = context.Request.Browser.GetAdapter(this);
            }
            flags.Set(controlAdapterResolved);
            return AdapterInternal;
        }

        /// <devdoc>
        ///    <para>Indicates the list of event handler delegates for the control. This property
        ///       is read-only.</para>
        /// </devdoc>
        protected ControlAdapter Adapter {
            get {
                if(flags[controlAdapterResolved]) {
                    return AdapterInternal;
                }
                AdapterInternal = ResolveAdapter();
                flags.Set(controlAdapterResolved);
                return AdapterInternal;
            }
        }

        /// <devdoc>
        /// Indicates whether a control is being used in the context of a design surface.
        /// </devdoc>
        protected internal bool DesignMode {
            get {
                if(!flags[designModeChecked]) {
                    Page page = Page;
                    if(page != null )  {
                        if(page.GetDesignModeInternal()) {
                            flags.Set(designMode);
                        }
                        else {
                            flags.Clear(designMode);
                        }
                    }
                    else {
                        if(Site != null) {
                            if(Site.DesignMode) {
                                flags.Set(designMode);
                            }
                            else {
                                flags.Clear(designMode);
                            }
                        }
                        else if (Parent != null) {
                            if(Parent.DesignMode) {
                                flags.Set(designMode);
                            }

                            // VSWhidbey 535747: If Page, Site and Parent are all null, do not change the 
                            // designMode flag since it might had been previously set by the controlBuilder.
                            // This does not affect runtime since designMode is by-default false.
                            /*
                            else {
                                flags.Clear(designMode);
                            }
                            */
                        }
                    }
                    flags.Set(designModeChecked);
                }
                return flags[designMode];

            }
        }

        // Helper function to call validateEvent.
        internal void ValidateEvent(string uniqueID) {
            ValidateEvent(uniqueID, String.Empty);
        }

        // Helper function to call validateEvent.
        internal void ValidateEvent(string uniqueID, string eventArgument) {
            if (Page != null && SupportsEventValidation) {
                Page.ClientScript.ValidateEvent(uniqueID, eventArgument);
            }
        }

        // Indicates whether the control supports event validation
        // By default, all web controls in System.Web assembly supports it but not custom controls.
        private bool SupportsEventValidation {
            get {
                return SupportsEventValidationAttribute.SupportsEventValidation(this.GetType());
            }
        }

        /// <devdoc>
        ///    <para>Indicates the list of event handler delegates for the control. This property
        ///       is read-only.</para>
        /// </devdoc>
        protected EventHandlerList Events {
            get {
                if (_events == null) {
                    _events = new EventHandlerList();
                }
                return _events;
            }
        }

        protected bool HasEvents() {
            return (_events != null);
        }

        /// <devdoc>
        ///    <para> Gets or sets the identifier for the control. Setting the
        ///       property on a control allows programmatic access to the control's properties. If
        ///       this property is not specified on a control, either declaratively or
        ///       programmatically, then you cannot write event handlers and the like for the control.</para>
        /// </devdoc>
        [
        ParenthesizePropertyName(true),
        MergableProperty(false),
        Filterable(false),
        Themeable(false),
        WebSysDescription(SR.Control_ID)
        ]
        public virtual string ID {
            get {
                if (!flags[idNotCalculated] && !flags[mustRenderID]) {
                    return null;
                }
                return _id;
            }
            set {
                // allow the id to be unset
                if (value != null && value.Length == 0)
                    value = null;

                string oldID = _id;

                _id = value;
                ClearCachedUniqueIDRecursive();
                flags.Set(idNotCalculated);
                flags.Clear(useGeneratedID);

                // Update the ID in the naming container
                if ((_namingContainer != null) && (oldID != null)) {
                    _namingContainer.DirtyNameTable();
                }

                if (oldID != null && oldID != _id) {
                    ClearCachedClientID();
                }
            }
        }


        /// <devdoc>
        ///    <para>Gets and sets a value indicating whether theme is enabled.</para>
        /// </devdoc>
        [
        Browsable(false),
        DefaultValue(true),
        Themeable(false),
        WebCategory("Behavior"),
        WebSysDescription(SR.Control_EnableTheming)
        ]
        public virtual bool EnableTheming {
            get {
                if (flags[enableThemingSet]) {
                    return !flags[disableTheming];
                }

                if (Parent != null) {
                    return Parent.EnableTheming;
                }

                return !flags[disableTheming];
            }
            set {
                if ((_controlState >= ControlState.FrameworkInitialized) && !DesignMode) {
                    throw new InvalidOperationException(SR.GetString(SR.PropertySetBeforePreInitOrAddToControls, "EnableTheming"));
                }

                if(!value) {
                    flags.Set(disableTheming);
                }
                else {
                    flags.Clear(disableTheming);
                }

                flags.Set(enableThemingSet);
            }
        }

        // Serialzie the value if it's set explicitely.
        internal bool ShouldSerializeEnableTheming() {
            return flags[enableThemingSet];;
        }

        internal bool IsBindingContainer {
            get {
                return this is INamingContainer && !(this is INonBindingContainer);
            }
        }

        protected internal bool IsChildControlStateCleared {
            get {
                return flags[disableChildControlState];
            }
        }


        /// <devdoc>
        ///    <para>Gets and sets the skinID of the control.</para>
        /// </devdoc>
        [
        Browsable(false),
        DefaultValue(""),
        Filterable(false),
        WebCategory("Behavior"),
        WebSysDescription(SR.Control_SkinId),
        ]
        public virtual string SkinID {
            get {
                if(_occasionalFields != null) {
                    return _occasionalFields.SkinId == null ? String.Empty : _occasionalFields.SkinId;
                }
                return String.Empty;
            }
            set {
                if (!DesignMode) {
                    if (flags[styleSheetApplied]) {
                        throw new InvalidOperationException(SR.GetString(SR.PropertySetBeforeStyleSheetApplied, "SkinId"));
                    }

                    if (_controlState >= ControlState.FrameworkInitialized) {
                        throw new InvalidOperationException(SR.GetString(SR.PropertySetBeforePreInitOrAddToControls, "SkinId"));
                    }
                }

                EnsureOccasionalFields();
                _occasionalFields.SkinId = value;
            }
        }

        private ControlRareFields RareFieldsEnsured {
            get {
                EnsureOccasionalFields();
                ControlRareFields rareFields = _occasionalFields.RareFields;
                if(rareFields == null) {
                    rareFields = new ControlRareFields();
                    _occasionalFields.RareFields = rareFields;
                }

                return rareFields;
            }
        }

        private ControlRareFields RareFields {
            get {
                if(_occasionalFields != null) {
                    return _occasionalFields.RareFields;
                }
                return null;
            }
        }

        private void EnsureOccasionalFields() {
            if(_occasionalFields == null) {
                _occasionalFields = new OccasionalFields();
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Gets or sets a value indicating whether the control should maintain its view
        ///       state, and the view state of any child control in contains, when the current
        ///       page request ends.
        ///    </para>
        /// </devdoc>
        [
        DefaultValue(EnableViewStateDefault),
        Themeable(false),
        WebCategory("Behavior"),
        WebSysDescription(SR.Control_MaintainState)
        ]
        public virtual bool EnableViewState {
            get {
                return !flags[disableViewState];
            }
            set {
                SetEnableViewStateInternal(value);
            }
        }

        [
        DefaultValue(ViewStateMode.Inherit),
        Themeable(false),
        WebCategory("Behavior"),
        WebSysDescription(SR.Control_ViewStateMode)
        ]
        public virtual ViewStateMode ViewStateMode {
            get {
                return flags[viewStateNotInherited] ?
                    (flags[viewStateMode] ? ViewStateMode.Enabled : ViewStateMode.Disabled) :
                    ViewStateMode.Inherit;
            }
            set {
                if ((value < ViewStateMode.Inherit) || (value > ViewStateMode.Disabled)) {
                    throw new ArgumentOutOfRangeException("value");
                }
                if (value == ViewStateMode.Inherit) {
                    flags.Clear(viewStateNotInherited);
                }
                else {
                    flags.Set(viewStateNotInherited);
                    if (value == ViewStateMode.Enabled) { 
                        flags.Set(viewStateMode);
                    }
                    else {
                        flags.Clear(viewStateMode);
                    }
                }
            }
        }


        internal void SetEnableViewStateInternal(bool value) {
            if (!value)
                flags.Set(disableViewState);
            else
                flags.Clear(disableViewState);
        }


        /// <devdoc>
        /// Gets a value indicating whether the control is maintaining its view
        /// state, when the current page request ends by looking at its own EnableViewState
        /// value, and the value for all its parents.
        /// </devdoc>
        protected internal bool IsViewStateEnabled {
            get {
                Control current = this;
                while (current != null) {
                    if (current.EnableViewState == false) {
                        return false;
                    }
                    ViewStateMode mode = current.ViewStateMode;
                    if (mode != ViewStateMode.Inherit) {
                        return (mode == ViewStateMode.Enabled);
                    }
                    current = current.Parent;
                }
                return true;
            }
        }


        /// <devdoc>
        ///    <para>Gets the reference to the current control's naming container.</para>
        /// </devdoc>
        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_NamingContainer)
        ]
        public virtual Control NamingContainer {
            get {
                if (_namingContainer == null) {
                    if (Parent != null) {
                        // Search for the closest naming container in the tree
                        if (Parent.flags[isNamingContainer])
                            _namingContainer = Parent;
                        else
                            _namingContainer = Parent.NamingContainer;
                    }
                }

                return _namingContainer;
            }
        }

        /// <internalonly/>
        /// <devdoc>
        ///    <para>Returns the databinding container of this control.  In most cases,
        ///     this is the same as the NamingContainer. But when using LoadTemplate(),
        ///     we get into a situation where that is not the case (ASURT 94138)</para>
        ///     The behavior is different than V1 that Usercontrol.BindingContainer is no
        ///     longer the UserControl but the control contains it. The behavior is consistent
        ///     with LoadTemplate() case.
        /// </devdoc>
        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public Control BindingContainer {
            get {
                Control bindingContainer = NamingContainer;
                while (bindingContainer is INonBindingContainer) {
                    bindingContainer = bindingContainer.BindingContainer;
                }

                return bindingContainer;
            }
        }

        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public Control DataItemContainer {
            get {
                Control dataItemContainer = NamingContainer;
                while (dataItemContainer != null && !(dataItemContainer is IDataItemContainer)) {
                    dataItemContainer = dataItemContainer.DataItemContainer;
                }

                return dataItemContainer;
            }
        }

        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never)
        ]
        public Control DataKeysContainer {
            get {
                Control dataKeysContainer = NamingContainer;
                while (dataKeysContainer != null && !(dataKeysContainer is IDataKeysControl)) {
                    dataKeysContainer = dataKeysContainer.DataKeysContainer;
                }

                return dataKeysContainer;
            }
        }



        /// <internalonly/>
        /// <devdoc>
        /// VSWhidbey 80467: Need to adapt id separator.
        /// </devdoc>
        protected char IdSeparator {
            get {
                if (Page != null) {
                    return Page.IdSeparator;
                }
                return IdSeparatorFromConfig;
            }
        }

        // VSWhidbey 475945: Use the old id separator if configured
        internal char IdSeparatorFromConfig {
            get {
                return ((EnableLegacyRendering) ? LEGACY_ID_SEPARATOR : ID_SEPARATOR);
            }
        }

        // VSWhidbey 244374: Allow controls to opt into loading view state by ID instead of index (perf hit)
        protected bool LoadViewStateByID {
            get {
                return ViewStateModeByIdAttribute.IsEnabled(GetType());
            }
        }

        /// <devdoc>
        /// <para> Gets the <see cref='System.Web.UI.Page'/> object that contains the
        ///    current control.</para>
        /// </devdoc>
        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_Page)
        ]
        public virtual Page Page {
            get {
                if (_page == null) {
                    if (Parent != null) {
                        _page = Parent.Page;
                    }
                }
                return _page;
            }

            set {
                if (OwnerControl != null) {
                    throw new InvalidOperationException();
                }
                // This is necessary because we need to set the page in generated
                // code before controls are added to the tree (ASURT 75330)
                Debug.Assert(_page == null);
                Debug.Assert(Parent == null || Parent.Page == null);
                _page = value;
            }
        }

        internal RouteCollection RouteCollection {
            get {
                if (_occasionalFields == null ||
                    _occasionalFields.RareFields == null ||
                    _occasionalFields.RareFields.RouteCollection == null) {
                        return RouteTable.Routes;
                }
                return _occasionalFields.RareFields.RouteCollection;
            }
            set {
                if (value != null) {
                    RareFieldsEnsured.RouteCollection = value;
                }
                else {
                    if (_occasionalFields != null &&
                        _occasionalFields.RareFields != null &&
                        _occasionalFields.RareFields.RouteCollection != null) {
                            _occasionalFields.RareFields.RouteCollection = null;
                    }
                }
            }
        }

        // VSWhidbey 244999
        internal virtual bool IsReloadable {
            get {
                return false;
            }
        }

        // DevDiv 33149, 43258: A backward compat. switch for Everett rendering
        internal bool EnableLegacyRendering {
            get {
                Page page = Page;
                if (page != null) {
                    return (page.XhtmlConformanceMode == XhtmlConformanceMode.Legacy);
                }
                else if (DesignMode || Adapter != null) {
                    return false;
                }
                else {
                    return (GetXhtmlConformanceSection().Mode == XhtmlConformanceMode.Legacy);
                }
            }
        }

        internal XhtmlConformanceSection GetXhtmlConformanceSection() {
            HttpContext context = Context;
            XhtmlConformanceSection xhtmlConformanceSection;
            if (context != null) {
                // if context is available, use the most efficient way to get the section
                xhtmlConformanceSection = RuntimeConfig.GetConfig(context).XhtmlConformance;
            }
            else {
                xhtmlConformanceSection = RuntimeConfig.GetConfig().XhtmlConformance;
            }
            Debug.Assert(xhtmlConformanceSection != null);
            return xhtmlConformanceSection;
        }

        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ]
        public virtual Version RenderingCompatibility {
            get {
                if (_occasionalFields == null ||
                    _occasionalFields.RareFields == null ||
                    _occasionalFields.RareFields.RenderingCompatibility == null) {
                        return RuntimeConfig.Pages.ControlRenderingCompatibilityVersion;
                }
                return _occasionalFields.RareFields.RenderingCompatibility;
            }
            set {
                if (value != null) {
                    RareFieldsEnsured.RenderingCompatibility = value;
                }
                else {
                    if (_occasionalFields != null &&
                        _occasionalFields.RareFields != null &&
                        _occasionalFields.RareFields.RenderingCompatibility != null) {
                            _occasionalFields.RareFields.RenderingCompatibility = null;
                    }
                }
            }
        }

        private RuntimeConfig RuntimeConfig {
            get {
                HttpContext context = Context;
                if (context != null) {
                    // if context is available, use the most efficient way to get the config
                    return RuntimeConfig.GetConfig(context);
                } else {
                    return RuntimeConfig.GetConfig();
                }
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
            Justification = "Consistent with other URL properties in ASP.NET.")]
        public string GetRouteUrl(object routeParameters) {
            return GetRouteUrl(new RouteValueDictionary(routeParameters));
        }

        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
            Justification = "Consistent with other URL properties in ASP.NET.")]
        public string GetRouteUrl(string routeName, object routeParameters) {
            return GetRouteUrl(routeName, new RouteValueDictionary(routeParameters));
        }

        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
            Justification = "Consistent with other URL properties in ASP.NET.")]
        public string GetRouteUrl(RouteValueDictionary routeParameters) {
            return GetRouteUrl(null, routeParameters);
        }

        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
            Justification = "Consistent with other URL properties in ASP.NET.")]
        public string GetRouteUrl(string routeName, RouteValueDictionary routeParameters) {
            VirtualPathData data = RouteCollection.GetVirtualPath(Context.Request.RequestContext, routeName, routeParameters);
            if (data != null) {
                return data.VirtualPath;
            }
            return null;
        }

        /// <devdoc>
        ///    <para>Gets the reference to the <see cref='System.Web.UI.TemplateControl'/>
        ///    that hosts the control.</para>
        /// </devdoc>
        internal virtual TemplateControl GetTemplateControl() {
            if (_occasionalFields == null || _occasionalFields.TemplateControl == null) {
                if (Parent != null) {
                    TemplateControl templateControl = Parent.GetTemplateControl();
                    if (templateControl != null) {
                        EnsureOccasionalFields();
                        _occasionalFields.TemplateControl = templateControl;
                    }
                }
            }
            return (_occasionalFields != null) ? _occasionalFields.TemplateControl : null;
        }


        /// <devdoc>
        ///    <para>Gets the reference to the <see cref='System.Web.UI.TemplateControl'/>
        ///    that hosts the control.</para>
        /// </devdoc>
        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_TemplateControl)
        ]
        public TemplateControl TemplateControl {
            get {
                return GetTemplateControl();
            }

            [EditorBrowsable(EditorBrowsableState.Never)]
            set {
                // This setter is necessary so that controls inside templates are based on
                // hosting pages not where the templates are used.
                if (value != null) {
                    EnsureOccasionalFields();
                    _occasionalFields.TemplateControl = value;
                }
                else {
                    if (_occasionalFields != null &&
                        _occasionalFields.TemplateControl != null) {
                            _occasionalFields.TemplateControl = null;
                    }
                }
            }
        }

        /*
         * Determine whether this control is a descendent of the passed in control
         */
        internal bool IsDescendentOf(Control ancestor) {
            Control current = this;
            while (current != ancestor && current.Parent != null) {
                current = current.Parent;
            }
            return (current == ancestor);
        }


        /// <devdoc>
        ///    <para> Gets the current control's parent control in the UI hierarchy.</para>
        /// </devdoc>
        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_Parent)
        ]
        public virtual Control Parent {
            get {
                return _parent;
            }
        }

        internal bool IsParentedToUpdatePanel {
            get {
                Control parent = Parent;
                while (parent != null) {
                    if (parent is IUpdatePanel) {
                        return true;
                    }
                    parent = parent.Parent;
                }
                return false;
            }
        }

        /// <devdoc>
        ///    <para> Gets the virtual directory of the Page or UserControl that contains this control.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_TemplateSourceDirectory)
        ]
        public virtual string TemplateSourceDirectory {
            get {
                if (TemplateControlVirtualDirectory == null)
                    return String.Empty;

                return TemplateControlVirtualDirectory.VirtualPathStringNoTrailingSlash;
            }
        }


        /// <devdoc>
        ///    <para> Gets the virtual directory of the Page or UserControl that contains this control.
        ///         Unlike TemplateSourceDirectory, this returns an app relative path (e.g. "~/sub")</para>
        /// </devdoc>
        [
        Browsable(false),
        EditorBrowsable(EditorBrowsableState.Advanced),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_TemplateSourceDirectory)
        ]
        public string AppRelativeTemplateSourceDirectory {
            get {
                return VirtualPath.GetAppRelativeVirtualPathStringOrEmpty(TemplateControlVirtualDirectory);
            }

            [EditorBrowsable(EditorBrowsableState.Never)]
            set {
                // This setter is necessary so that skins are based on hosting skin file.
                this.TemplateControlVirtualDirectory = VirtualPath.CreateNonRelativeAllowNull(value);
            }
        }

        internal VirtualPath TemplateControlVirtualDirectory {
            get {
                if (_occasionalFields != null && _occasionalFields.TemplateSourceVirtualDirectory != null)
                    return _occasionalFields.TemplateSourceVirtualDirectory;

                TemplateControl control = TemplateControl;
                if (control == null) {
                    HttpContext context = Context;
                    if (context != null) {
                        VirtualPath templateSourceVirtualDirectory = context.Request.CurrentExecutionFilePathObject.Parent;
                        if (templateSourceVirtualDirectory != null) {
                            EnsureOccasionalFields();
                            _occasionalFields.TemplateSourceVirtualDirectory = templateSourceVirtualDirectory;
                        }
                    }
                    return (_occasionalFields != null) ? _occasionalFields.TemplateSourceVirtualDirectory : null;
                }
                // Prevent recursion if this is the TemplateControl
                if (control != this) {
                    VirtualPath templateSourceVirtualDirectory = control.TemplateControlVirtualDirectory;
                    if (templateSourceVirtualDirectory != null) {
                        EnsureOccasionalFields();
                        _occasionalFields.TemplateSourceVirtualDirectory = templateSourceVirtualDirectory;
                    }
                }
                return (_occasionalFields != null) ? _occasionalFields.TemplateSourceVirtualDirectory : null;
            }

            set {
                // This setter is necessary so that skins are based on hosting skin file.
                if (value != null) {
                    EnsureOccasionalFields();
                    _occasionalFields.TemplateSourceVirtualDirectory = value;
                }
                else {
                    if (_occasionalFields != null &&
                        _occasionalFields.TemplateSourceVirtualDirectory != null) {
                            _occasionalFields.TemplateSourceVirtualDirectory = null;
                    }
                }
            }
        }

        internal ControlState ControlState {
            get { return _controlState; }
            set { _controlState = value; }
        }


        /// <devdoc>
        ///    <para>Indicates the site information for the control.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Advanced),
        WebSysDescription(SR.Control_Site)
        ]
        public ISite Site {
            get {
                if (OwnerControl != null) {
                    return OwnerControl.Site;
                }

                if (RareFields != null) {
                    return RareFields.Site;
                }
                return null;
            }
            set {
                if (OwnerControl != null) {
                    throw new InvalidOperationException(SR.GetString(SR.Substitution_SiteNotAllowed));
                }

                RareFieldsEnsured.Site = value;
                flags.Clear(designModeChecked);
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Gets or sets a value that indicates whether a control should be rendered on
        ///       the page.
        ///    </para>
        /// </devdoc>
        [
        Bindable(true),
        DefaultValue(true),
        WebCategory("Behavior"),
        WebSysDescription(SR.Control_Visible)
        ]
        public virtual bool Visible {
            get {
                if (flags[invisible])
                    return false;
                else if ((_parent != null) && !DesignMode)
                    return _parent.Visible;
                else
                    return true;
            }
            set {
                if (flags[marked]) {
                    bool visible = !flags[invisible];
                    if (visible != value) {
                        flags.Set(visibleDirty);
                    }
                }

                if(!value) {
                    flags.Set(invisible);
                }
                else {
                    flags.Clear(invisible);
                }
            }
        }


        /// <devdoc>
        /// Do not remove or change the signature. It is called via reflection.
        /// This allows for correct serialization, since Visible is implemented as a
        /// recursive property.
        /// </devdoc>
        private void ResetVisible() {
            Visible = true;
        }


        /// <devdoc>
        /// Do not remove or change the signature. It is called via reflection.
        /// This allows for correct serialization, since Visible is implemented as a
        /// recursive property.
        /// </devdoc>
        private bool ShouldSerializeVisible() {
            return flags[invisible];
        }


        /// <devdoc>
        ///    <para> Gets the unique, hierarchically-qualified identifier for
        ///       a control. This is different from the ID property, in that the fully-qualified
        ///       identifier includes the identifier for the control's naming container.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_UniqueID)
        ]
        public virtual string UniqueID {
            get {
                if (_cachedUniqueID != null) {
                    return _cachedUniqueID;
                }

                Control namingContainer = NamingContainer;
                if (namingContainer != null) {
                    // if the ID is null at this point, we need to have one created and the control added to the
                    // naming container.
                    if (_id == null) {
                        GenerateAutomaticID();
                    }

                    if (Page == namingContainer) {
                        _cachedUniqueID = _id;
                    }
                    else {
                        string uniqueIDPrefix = namingContainer.GetUniqueIDPrefix();
                        if (uniqueIDPrefix.Length == 0) {
                            // In this case, it is probably a naming container that is not sited, so we don't want to cache it
                            return _id;
                        }
                        else {
                            _cachedUniqueID = uniqueIDPrefix + _id;
                        }
                    }

                    return _cachedUniqueID;
                }
                else {
                    // no naming container
                    return _id;
                }
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification="This is consistent with UniqueID")]
        [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId = "Member", Justification="This is consistent with UniqueID")]
        public string GetUniqueIDRelativeTo(Control control) {
            if (control == null) {
                throw new ArgumentNullException("control");
            }

            if (!IsDescendentOf(control.NamingContainer)) {
                throw new InvalidOperationException(SR.GetString(SR.Control_NotADescendentOfNamingContainer, control.ID));
            }

            if (control.NamingContainer == Page) {
                return UniqueID;
            } else {
                return UniqueID.Substring(control.NamingContainer.UniqueID.Length + 1); // add 1 for the ID seperator (which is a char)
            }
        }

        /// <devdoc>
        ///    <para>Occurs when the control binds to a data source. Notifies the control to perform any data binding during this event.</para>
        /// </devdoc>
        [
        WebCategory("Data"),
        WebSysDescription(SR.Control_OnDataBind)
        ]
        public event EventHandler DataBinding {
            add {
                Events.AddHandler(EventDataBinding, value);
            }
            remove {
                Events.RemoveHandler(EventDataBinding, value);
            }
        }


        /// <devdoc>
        ///    <para>Occurs when the control is initialized, the first step in the page lifecycle. Controls should
        ///       perform any initialization steps that are required to create and set up an
        ///       instantiation.</para>
        /// </devdoc>
        [
        WebSysDescription(SR.Control_OnInit)
        ]
        public event EventHandler Init {
            add {
                Events.AddHandler(EventInit, value);
            }
            remove {
                Events.RemoveHandler(EventInit, value);
            }
        }


        /// <devdoc>
        /// <para>Occurs when the control is loaded to the <see cref='System.Web.UI.Page'/> object. Notifies the control to perform any steps that
        ///    need to occur on each page request.</para>
        /// </devdoc>
        [
        WebSysDescription(SR.Control_OnLoad)
        ]
        public event EventHandler Load {
            add {
                Events.AddHandler(EventLoad, value);
            }
            remove {
                Events.RemoveHandler(EventLoad, value);
            }
        }


        /// <devdoc>
        ///    <para>Occurs when the control is about to render. Controls
        ///       should perform any pre-rendering steps necessary before saving view state and
        ///       rendering content to the <see cref='System.Web.UI.Page'/> object.</para>
        /// </devdoc>
        [
        WebSysDescription(SR.Control_OnPreRender)
        ]
        public event EventHandler PreRender {
            add {
                Events.AddHandler(EventPreRender, value);
            }
            remove {
                Events.RemoveHandler(EventPreRender, value);
            }
        }


        /// <devdoc>
        ///    <para>Occurs when the control is unloaded from memory. Controls should perform any
        ///       final cleanup before this instance of it is </para>
        /// </devdoc>
        [
        WebSysDescription(SR.Control_OnUnload)
        ]
        public event EventHandler Unload {
            add {
                Events.AddHandler(EventUnload, value);
            }
            remove {
                Events.RemoveHandler(EventUnload, value);
            }
        }

        /// <devdoc>
        /// <para>Apply stylesheet skin on the control.</para>
        /// </devdoc>
        [
        EditorBrowsable(EditorBrowsableState.Advanced),
        ]
        public virtual void ApplyStyleSheetSkin(Page page) {
            // Nothing to do if the control is not in a Page.
            if (page == null) {
                return;
            }

            // Only apply stylesheet if not already applied.
            if (flags[styleSheetApplied]) {
                throw new InvalidOperationException(SR.GetString(SR.StyleSheetAreadyAppliedOnControl));
            }

            if (page.ApplyControlStyleSheet(this)) {
                flags.Set(styleSheetApplied);
            }
        }

        /// <devdoc>
        /// <para>Apply theme on the control.</para>
        /// </devdoc>
        private void ApplySkin(Page page) {
            if (page == null) {
                throw new ArgumentNullException("page");
            }

            if (flags[themeApplied]) {
                return;
            }

            if (ThemeableAttribute.IsTypeThemeable(this.GetType())) {
                page.ApplyControlSkin(this);
                flags.Set(themeApplied);
            }
        }


        /// <devdoc>
        /// <para>Raises the <see langword='DataBinding'/> event. This
        ///    notifies a control to perform any data binding logic that is associated with it.</para>
        /// </devdoc>
        protected virtual void OnDataBinding(EventArgs e) {
            if(HasEvents()) {
                EventHandler handler = _events[EventDataBinding] as EventHandler;
                if(handler != null) {
                    handler(this, e);
                }
            }
        }


        /// <devdoc>
        ///    <para> Causes data binding to occur on the invoked control and all of its child
        ///       controls.</para>
        /// </devdoc>
        public virtual void DataBind() {
            DataBind(true);
        }

        /// <devdoc>
        ///    <para> Causes the invoked controls' context to be pushed on the stack,
        ///       then conditionally call OnDataBinging on the invoked control, and databind all of its child
        ///       controls.  A control would call this with false if it overrides DataBind without calling
        ///       Control.DataBind, but still wants to be an IDataItemContainer.  FormView and DetailsView
        ///       are good examples of this.</para>
        /// </devdoc>
        protected virtual void DataBind(bool raiseOnDataBinding) {
            bool inDataBind = false;

            if (IsBindingContainer) {
                bool foundDataItem;

                object dataItem = DataBinder.GetDataItem(this, out foundDataItem);

                if (foundDataItem && (Page != null)) {
                    Page.PushDataBindingContext(dataItem);
                    inDataBind = true;
                }
            }
            try {
                if (raiseOnDataBinding) {
                    // Do our own databinding
                    OnDataBinding(EventArgs.Empty);
                }

                // Do all of our children's databinding
                DataBindChildren();
            }
            finally {
                if (inDataBind) {
                    Page.PopDataBindingContext();
                }
            }
        }


        /// <devdoc>
        /// <para> Causes data binding to occur on all of the child controls.</para>
        /// </devdoc>
        protected virtual void DataBindChildren() {
            if (HasControls()) {
                string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                try {
                    try {
                        int controlCount = _controls.Count;
                        for (int i=0; i < controlCount; i++)
                            _controls[i].DataBind();
                    }
                    finally {
                        _controls.SetCollectionReadOnly(oldmsg);
                    }
                }
                catch {
                    throw;
                }
            }
        }

        internal void PreventAutoID() {
            // controls that are also naming containers must always get an id
            if (flags[isNamingContainer] == false) {
                flags.Set(idNotRequired);
            }
        }


        /// <devdoc>
        ///    <para>Notifies the control that an element, XML or HTML, was parsed, and adds it to
        ///       the control.</para>
        /// </devdoc>
        protected virtual void AddParsedSubObject(object obj) {
            Control control = obj as Control;
            if (control != null) {
                Controls.Add(control);
            }
        }

        private void UpdateNamingContainer(Control namingContainer) {
            // Remove the cached uniqueID if the control already had a namingcontainer
            // and the namingcontainer is changed.
            if (_namingContainer == null || (_namingContainer != null && _namingContainer != namingContainer)) {
                ClearCachedUniqueIDRecursive();
            }

            // No need to clear the cache if never been initialized
            if (EffectiveClientIDModeValue != ClientIDMode.Inherit) {
                ClearCachedClientID();
                ClearEffectiveClientIDMode();
            }

            _namingContainer = namingContainer;
        }

        private void ClearCachedUniqueIDRecursive() {
            _cachedUniqueID = null;

            if (_occasionalFields != null) {
                _occasionalFields.UniqueIDPrefix = null;
            }

            if (_controls != null) {
                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++) {
                    _controls[i].ClearCachedUniqueIDRecursive();
                }
            }
        }

        protected void EnsureID() {
            if (_namingContainer != null) {
                if (_id == null) {
                    GenerateAutomaticID();
                }
                flags.Set(mustRenderID);
            }
        }

        private void GenerateAutomaticID() {
            Debug.Assert(_namingContainer != null);
            Debug.Assert(_id == null);

            // Remember that a generated ID is used for this control.
            flags.Set(useGeneratedID);

            // Calculate the automatic ID. For performance and memory reasons
            // we look up a static table entry if possible
            _namingContainer.EnsureOccasionalFields();
            int idNo = _namingContainer._occasionalFields.NamedControlsID++;
            if (EnableLegacyRendering) {
                // VSWhidbey 517118
                _id = automaticLegacyIDPrefix + idNo.ToString(NumberFormatInfo.InvariantInfo);
            }
            else {
                if (idNo < automaticIDCount) {
                    _id = automaticIDs[idNo];
                }
                else {
                    _id = automaticIDPrefix + idNo.ToString(NumberFormatInfo.InvariantInfo);
                }
            }

            _namingContainer.DirtyNameTable();
        }

        internal virtual string GetUniqueIDPrefix() {
            EnsureOccasionalFields();

            if (_occasionalFields.UniqueIDPrefix == null) {
                string uniqueID = UniqueID;
                if (!String.IsNullOrEmpty(uniqueID)) {
                    _occasionalFields.UniqueIDPrefix = uniqueID + IdSeparator;
                }
                else {
                    _occasionalFields.UniqueIDPrefix = String.Empty;
                }
            }

            return _occasionalFields.UniqueIDPrefix;
        }

        /// <devdoc>
        /// <para>Raises the <see langword='Init'/> event. This notifies the control to perform
        ///    any steps necessary for its creation on a page request.</para>
        /// </devdoc>
        protected internal virtual void OnInit(EventArgs e) {
            if(HasEvents()) {
                EventHandler handler = _events[EventInit] as EventHandler;
                if(handler != null) {
                    handler(this, e);
                }
            }
        }

        // !! IMPORTANT !!
        // If you make changes to this method, also change InitRecursiveAsync.
        internal virtual void InitRecursive(Control namingContainer) {
            ResolveAdapter();
            if (_controls != null) {
                if (flags[isNamingContainer]) {
                    namingContainer = this;
                }
                string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++) {
                    Control control = _controls[i];

                    // Propagate the page and namingContainer
                    control.UpdateNamingContainer(namingContainer);

                    if ((control._id == null) && (namingContainer != null) && !control.flags[idNotRequired]) {
                        control.GenerateAutomaticID();
                    }
                    control._page = Page;

                    control.InitRecursive(namingContainer);
                }
                _controls.SetCollectionReadOnly(oldmsg);

            }

            // Only make the actual call if it hasn't already happened (ASURT 111303)
            if (_controlState < ControlState.Initialized) {
                _controlState = ControlState.ChildrenInitialized; // framework also initialized

                if ((Page != null) && !DesignMode) {
                    if (Page.ContainsTheme && EnableTheming) {
                        ApplySkin(Page);
                    }
                }

                if (AdapterInternal != null) {
                    AdapterInternal.OnInit(EventArgs.Empty);
                }
                else {
                    OnInit(EventArgs.Empty);
                }

                _controlState = ControlState.Initialized;
            }

            // track all subsequent state changes
            TrackViewState();

#if DEBUG
            ControlInvariant();
#endif
        }

        // TAP version of InitRecursive
        // !! IMPORTANT !!
        // If you make changes to this method, also change InitRecursive.
        internal async Task InitRecursiveAsync(Control namingContainer, Page page) {
            ResolveAdapter();
            if (_controls != null) {
                if (flags[isNamingContainer]) {
                    namingContainer = this;
                }
                string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++) {
                    Control control = _controls[i];

                    // Propagate the page and namingContainer
                    control.UpdateNamingContainer(namingContainer);

                    if ((control._id == null) && (namingContainer != null) && !control.flags[idNotRequired]) {
                        control.GenerateAutomaticID();
                    }
                    control._page = Page;

                    control.InitRecursive(namingContainer);
                }
                _controls.SetCollectionReadOnly(oldmsg);

            }

            // Only make the actual call if it hasn't already happened (ASURT 111303)
            if (_controlState < ControlState.Initialized) {
                _controlState = ControlState.ChildrenInitialized; // framework also initialized

                if ((Page != null) && !DesignMode) {
                    if (Page.ContainsTheme && EnableTheming) {
                        ApplySkin(Page);
                    }
                }

                using (page.Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
                    if (AdapterInternal != null) {
                        AdapterInternal.OnInit(EventArgs.Empty);
                    }
                    else {
                        OnInit(EventArgs.Empty);
                    }
                    await page.GetWaitForPreviousStepCompletionAwaitable();
                }

                _controlState = ControlState.Initialized;
            }

            // track all subsequent state changes
            TrackViewState();

#if DEBUG
            ControlInvariant();
#endif
        }

#if DEBUG

        /// <devdoc>
        ///    <para>This should be used to assert internal state about the control</para>
        /// </devdoc>
        internal void ControlInvariant() {

            // If the control is initialized, the naming container and page should have been pushed in
            if (_controlState >= ControlState.Initialized) {
                if (DesignMode) {
                    // Top-level UserControls do not have a page or a naming container in the designer
                    // hence the special casing.

                    Debug.Assert((_namingContainer != null) || (this is Page) || (this is UserControl));

                    // 



                }
                else {
                    if (!(this is Page)) {
                        Debug.Assert(_namingContainer != null);
                    }
                    Debug.Assert(Page != null);
                }
            }
            // If naming container is set and the name table exists, the ID should exist in it.

            if(_namingContainer != null &&
               _namingContainer._occasionalFields != null &&
               _namingContainer._occasionalFields.NamedControls != null &&
               _id != null) {
                Debug.Assert(_namingContainer._occasionalFields.NamedControls.Contains(_id));
            }
        }

        // Collect some statistic about the number of controls with occasional and
        // rare fields.
        internal void GetRareFieldStatistics(ref int totalControls,
            ref int withOccasionalFields, ref int withRareFields) {
            totalControls++;
            if (_occasionalFields != null) {
                withOccasionalFields++;
                if (_occasionalFields.RareFields != null)
                    withRareFields++;

                // No children: we're done
                if (_controls == null)
                    return;

                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++) {
                    Control control = _controls[i];

                    control.GetRareFieldStatistics(ref totalControls, ref withOccasionalFields,
                        ref withRareFields);
                }
            }
        }
#endif

        protected void ClearChildState() {
            ClearChildControlState();
            ClearChildViewState();
        }

        protected void ClearChildControlState() {
            //VSWhidbey 242621 to be consistent with ClearChildViewState, ignore calls before and during Init
            if (ControlState < ControlState.Initialized) {
                return;
            }
            flags.Set(disableChildControlState);
            if (Page != null) {
                Page.RegisterRequiresClearChildControlState(this);
            }
        }


        /// <devdoc>
        ///    <para>Deletes the view state information for all of the current control's child
        ///       controls.</para>
        /// </devdoc>
        protected void ClearChildViewState() {
            if(_occasionalFields != null) {
                _occasionalFields.ControlsViewState = null;
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId="Member")]
        protected void ClearEffectiveClientIDMode() {
            EffectiveClientIDModeValue = ClientIDMode.Inherit;
            if (HasControls()) {
                foreach (Control control in Controls) {
                    control.ClearEffectiveClientIDMode();
                }
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId="Member")]
        protected void ClearCachedClientID() {
            _cachedPredictableID = null;
            if (HasControls()) {
                foreach (Control control in Controls) {
                    control.ClearCachedClientID();
                }
            }
        }

        /// <devdoc>
        ///    <para>Indicates whether the current control's children have any saved view state
        ///       information. This property is read-only.</para>
        /// </devdoc>
        protected bool HasChildViewState {
            get {
                return ((_occasionalFields != null) &&
                        (_occasionalFields.ControlsViewState != null) &&
                        (_occasionalFields.ControlsViewState.Count > 0));
            }
        }


        /// <devdoc>
        /// Sets initial focus on the control
        /// </devdoc>
        public virtual void Focus() {
            Page.SetFocus(this);
        }

        internal void LoadControlStateInternal(object savedStateObj) {
            // Do not load the control state if it has been applied.
            if (flags[controlStateApplied]) {
                return;
            }

            flags.Set(controlStateApplied);

            Pair savedState = (Pair)savedStateObj;
            if (savedState == null) {
                return;
            }
            Page page = Page;
            if (page != null && !page.ShouldLoadControlState(this)) {
                return;
            }
            // VSWhidbey160650: Only call LoadControlState with non null savedState
            if (savedState.First != null) {
                LoadControlState(savedState.First);
            }
            // VSWhidbey356804: Only call LoadAdapterControlState with non null savedState
            if (AdapterInternal == null || savedState.Second == null) {
                return;
            }
            AdapterInternal.LoadAdapterControlState(savedState.Second);
        }


        /// <devdoc>
        /// Load the control state, which is the essential state information needed even if view state is disabled.
        /// </devdoc>
        protected internal virtual void LoadControlState(object savedState) {
        }


        /// <devdoc>
        ///    <para>Restores the view state information from a previous page
        ///       request that was saved by the Control.SavedState method.</para>
        /// </devdoc>
        protected virtual void LoadViewState(object savedState) {
            if (savedState != null) {
                ViewState.LoadViewState(savedState);

                // Load values cached out of view state
                object visible = ViewState["Visible"];
                if (visible != null) {
                    if(!(bool)visible) {
                        flags.Set(invisible);
                    }
                    else {
                        flags.Clear(invisible);
                    }
                    flags.Set(visibleDirty);
                }

                object validateRequestModeValue = ViewState["ValidateRequestMode"];
                if (validateRequestModeValue != null) {
                    flags[validateRequestMode, validateRequestModeOffset] = (int)validateRequestModeValue;
                    flags.Set(validateRequestModeDirty);
                }
            }
        }

        internal void LoadViewStateRecursive(object savedState) {
            // nothing to do if we have no state
            if (savedState == null || flags[disableViewState])
                return;

            if (Page != null && Page.IsPostBack) {
                object controlState = null;
                object adapterState = null;
                ArrayList childState = null;

                Pair allSavedState = savedState as Pair;
                if (allSavedState != null) {
                    controlState = allSavedState.First;
                    childState = (ArrayList)allSavedState.Second;
                }
                else {
                    Debug.Assert(savedState is Triplet);
                    Triplet t = (Triplet)savedState;

                    controlState = t.First;
                    adapterState = t.Second;
                    childState = (ArrayList)t.Third;
                }

                try {
                    if ((adapterState != null) && (AdapterInternal != null)) {
                        AdapterInternal.LoadAdapterViewState(adapterState);
                    }

                    if (controlState != null) {
                        LoadViewState(controlState);
                    }

                    if (childState != null) {
                        if (LoadViewStateByID) {
                            LoadChildViewStateByID(childState);
                        }
                        else {
                            LoadChildViewStateByIndex(childState);
                        }
                    }
                }
                catch (InvalidCastException) {
                    // catch all viewstate loading problems with casts.  They are most likely changed control trees.
                    throw new HttpException(SR.GetString(SR.Controls_Cant_Change_Between_Posts));
                }
                catch (IndexOutOfRangeException) {
                    // catch all viewstate loading problems with indeces.  They are most likely changed control trees.
                    throw new HttpException(SR.GetString(SR.Controls_Cant_Change_Between_Posts));
                }
            }

            _controlState = ControlState.ViewStateLoaded;
        }

        internal void LoadChildViewStateByID(ArrayList childState) {
            int childStateCount = childState.Count;
            for (int i = 0; i < childStateCount; i += 2) {
                // first element is index or ID of control with state and the
                // next element is state of the control
                string controlId = (string)childState[i];
                object state = childState[i + 1];

                Control childControl = FindControl(controlId);
                if (childControl != null) {
                    childControl.LoadViewStateRecursive(state);
                }
                else {
                    // couldn't find a control for this state blob, save it for later
                    EnsureOccasionalFields();
                    if (_occasionalFields.ControlsViewState == null) {
                        _occasionalFields.ControlsViewState = new Hashtable();
                    }
                    _occasionalFields.ControlsViewState[controlId] = state;
                }
            }
        }

        internal void LoadChildViewStateByIndex(ArrayList childState) {
            ControlCollection ctrlColl = Controls;
            int ctrlCount = ctrlColl.Count;

            int childStateCount = childState.Count;
            for (int i = 0; i < childStateCount; i += 2) {
                // first element is index of control with state and the
                // next element is state of the control
                int controlIndex = (int)childState[i];
                object state = childState[i + 1];

                if (controlIndex < ctrlCount) {
                    // we have a control for this state blob
                    ctrlColl[controlIndex].LoadViewStateRecursive(state);
                }
                else {
                    // couldn't find a control for this state blob, save it for later
                    EnsureOccasionalFields();
                    if (_occasionalFields.ControlsViewState == null) {
                        _occasionalFields.ControlsViewState = new Hashtable();
                    }
                    _occasionalFields.ControlsViewState[controlIndex] = state;
                }
            }
        }

        ///
        /// Figure out if a path is physical or virtual.  This is useful because a number of our controls
        /// accept either type of path for the same attribute.
        ///
        internal void ResolvePhysicalOrVirtualPath(string path, out VirtualPath virtualPath, out string physicalPath) {
            if (System.Web.Util.UrlPath.IsAbsolutePhysicalPath(path)) {
                physicalPath = path;
                virtualPath = null;
            }
            else {
                physicalPath = null;

                // It could be relative, so resolve it
                virtualPath = TemplateControlVirtualDirectory.Combine(VirtualPath.Create(path));
            }
        }


        /// <devdoc>
        /// <para>
        ///   This function takes a virtual path, that is a relative or root relative URL without a protocol.
        ///   It returns the mapped physcial file name relative to the template source. It throws an exception if
        ///   there is insufficient security access to read or investigate the mapped result. This should be used
        ///   by controls that can read files and live in fully trusted DLLs such as System.Web.dll to prevent
        ///   security issues. The exception thrown does not give away information about the mapping.  For absolute
        ///   physical paths, this function checks permission
        /// </para>
        /// </devdoc>
        protected internal string MapPathSecure(string virtualPath) {
            if (String.IsNullOrEmpty(virtualPath)) {
                throw new ArgumentNullException("virtualPath", SR.GetString(SR.VirtualPath_Length_Zero));
            }

            string physicalPath;
            VirtualPath virtualPathObject;
            ResolvePhysicalOrVirtualPath(virtualPath, out virtualPathObject, out physicalPath);
            if (physicalPath == null) {
                physicalPath = virtualPathObject.MapPathInternal(TemplateControlVirtualDirectory,
                    true /*allowCrossAppMapping*/);
            }

            // Security check
            HttpRuntime.CheckFilePermission(physicalPath);

            return physicalPath;
        }


        /// <devdoc>
        /// <para>
        ///   This function takes a virtual path, that is a relative or root relative URL without a protocol.
        ///   It can also take a physical path, either local (c:\) or UNC.
        ///   It returns a stream used to read to contents of the file. It throws an exception if
        ///   there is insufficient security access to read or investigate the mapped result. This should be used
        ///   by controls that can read files and live in fully trusted DLLs such as System.Web.dll to prevent
        ///   security issues. The exception thrown does not give away information about the mapping.  For absolute
        ///   physical paths, this function checks permission
        /// </para>
        /// </devdoc>
        protected internal Stream OpenFile(string path) {

            string physicalPath = null;
            VirtualFile vfile = null;

            // Need to Trim it since MapPath no longer allows trailing space (VSWhidbey 441210)
            path = path.Trim();

            if (UrlPath.IsAbsolutePhysicalPath(path)) {
                // Absolute physical path
                physicalPath = path;
            }
            else {
                vfile = HostingEnvironment.VirtualPathProvider.GetFile(path);
                MapPathBasedVirtualFile mapPathVFile = vfile as MapPathBasedVirtualFile;
                if (mapPathVFile != null) {
                    physicalPath = mapPathVFile.PhysicalPath;
                }
            }

            // If we got a physical path, make sure the user has access to it
            if (physicalPath != null) {
                HttpRuntime.CheckFilePermission(physicalPath);
            }

            if (vfile != null) {
                return vfile.Open();
            }
            else {
                return new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
        }

        ///
        /// Open a stream from either a virtual or physical path, and if possible get a CacheDependency
        /// for the resulting Stream.
        ///
        internal Stream OpenFileAndGetDependency(VirtualPath virtualPath, string physicalPath, out CacheDependency dependency) {

            // Only one of the paths should be non-null
            Debug.Assert((virtualPath == null) != (physicalPath == null));

            // If we got a virtual path, and we're using the default VPP, call MapPath
            if (physicalPath == null && HostingEnvironment.UsingMapPathBasedVirtualPathProvider) {
                physicalPath = virtualPath.MapPathInternal(TemplateControlVirtualDirectory,
                    true /*allowCrossAppMapping*/);
            }

            Stream stream;
            if (physicalPath != null) {
                // Security check
                HttpRuntime.CheckFilePermission(physicalPath);

                // Work directly with the physical file, bypassing the VPP
                stream = new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                dependency = new CacheDependency(0, physicalPath);
            }
            else {
                // It's non file system based, so go though the VirtualPathProvider
                stream = virtualPath.OpenFile();
                dependency = VirtualPathProvider.GetCacheDependency(virtualPath);
            }

            return stream;
        }


        /// <devdoc>
        /// <para>Raises the <see langword='Load'/>
        /// event. This notifies the control that it should perform any work that needs to
        /// occur for each page request.</para>
        /// </devdoc>
        protected internal virtual void OnLoad(EventArgs e) {
            if(HasEvents()) {
                EventHandler handler = _events[EventLoad] as EventHandler;
                if(handler != null) {
                    handler(this, e);
                }
            }
        }

        internal virtual void LoadRecursive() {
            // Only make the actual call if it hasn't already happened (ASURT 111303)
            if (_controlState < ControlState.Loaded) {
                if (AdapterInternal != null) {
                    AdapterInternal.OnLoad(EventArgs.Empty);
                }
                else {
                    OnLoad(EventArgs.Empty);
                }
            }

            // Call Load on all our children
            if (_controls != null) {
                string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++) {
                    _controls[i].LoadRecursive();
                }

                _controls.SetCollectionReadOnly(oldmsg);
            }

            if (_controlState < ControlState.Loaded)
                _controlState = ControlState.Loaded;
        }

        // Same as LoadRecursive, but has an async point immediately after the call to this.OnLoad.
        internal async Task LoadRecursiveAsync(Page page) {
            // Only make the actual call if it hasn't already happened (ASURT 111303)
            if (_controlState < ControlState.Loaded) {
                using (page.Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
                    if (AdapterInternal != null) {
                        AdapterInternal.OnLoad(EventArgs.Empty);
                    }
                    else {
                        OnLoad(EventArgs.Empty);
                    }
                    await page.GetWaitForPreviousStepCompletionAwaitable();
                }
            }

            // Call Load on all our children
            if (_controls != null) {
                string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++) {
                    _controls[i].LoadRecursive();
                }

                _controls.SetCollectionReadOnly(oldmsg);
            }

            if (_controlState < ControlState.Loaded)
                _controlState = ControlState.Loaded;
        }

        /// <devdoc>
        /// <para>Raises the <see langword='PreRender'/> event. This method uses event arguments
        ///    to pass the event data to the control.</para>
        /// </devdoc>
        protected internal virtual void OnPreRender(EventArgs e) {
            if(HasEvents()) {
                EventHandler handler = _events[EventPreRender] as EventHandler;
                if (handler != null) {
                    handler(this, e);
                }
            }
        }

        internal virtual void PreRenderRecursiveInternal() {
            // Call Visible property and cache value in !flags[invisible] to allow Visible to be overridden.
            // This avoids unnecessary virtual property calls in SaveViewState and Render.
            bool visible = Visible;
            if(!visible) {
                flags.Set(invisible);
            }
            else {
                flags.Clear(invisible);
                EnsureChildControls();

                if (AdapterInternal != null) {
                    AdapterInternal.OnPreRender(EventArgs.Empty);
                }
                else {
                    OnPreRender(EventArgs.Empty);
                }

                if (_controls != null) {
                    string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                    int controlCount = _controls.Count;
                    for (int i=0; i < controlCount; i++) {
                        _controls[i].PreRenderRecursiveInternal();
                    }
                    _controls.SetCollectionReadOnly(oldmsg);
                }
            }
            _controlState = ControlState.PreRendered;
        }

        // Same as PreRenderRecursive, but has an async point after the call to this.OnPreRender.
        internal async Task PreRenderRecursiveInternalAsync(Page page) {
            // Call Visible property and cache value in !flags[invisible] to allow Visible to be overridden.
            // This avoids unnecessary virtual property calls in SaveViewState and Render.
            bool visible = Visible;
            if (!visible) {
                flags.Set(invisible);
            }
            else {
                flags.Clear(invisible);
                if (AppSettings.EnableAsyncModelBinding) {
                    using (page.Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
                        EnsureChildControls();
                        await page.GetWaitForPreviousStepCompletionAwaitable();
                    }
                }
                else {
                    EnsureChildControls();
                }                

                using (page.Context.SyncContext.AllowVoidAsyncOperationsBlock()) {
                    if (AdapterInternal != null) {
                        AdapterInternal.OnPreRender(EventArgs.Empty);
                    }
                    else {
                        OnPreRender(EventArgs.Empty);
                    }
                    await page.GetWaitForPreviousStepCompletionAwaitable();
                }

                if (_controls != null) {
                    string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                    int controlCount = _controls.Count;
                    for (int i = 0; i < controlCount; i++) {
                        if (AppSettings.EnableAsyncModelBinding) {
                            // To make sure every OnPreRender is awaited so that _controlState
                            // would not be set to ControlState.PreRendered until the control is
                            // really PreRendered
                            await _controls[i].PreRenderRecursiveInternalAsync(page);
                        }
                        else {
                            _controls[i].PreRenderRecursiveInternal();
                        }
                    }

                    _controls.SetCollectionReadOnly(oldmsg);
                }
            }
            _controlState = ControlState.PreRendered;
        }

        internal int EstimateStateSize(object state) {
            if(state == null) {
                return 0;
            }
            return Util.SerializeWithAssert(new ObjectStateFormatter(), state).Length;
        }

        /*
         * Walk the tree and fill in profile information
         */

        /// <internalonly/>
        /// <devdoc>
        /// <para>Gathers information about the control and delivers it to the <see cref='System.Web.UI.Page.Trace'/>
        /// property to be displayed when tracing is enabled for the page.</para>
        /// </devdoc>
        protected void BuildProfileTree(string parentId, bool calcViewState) {
            // estimate the viewstate size.
            calcViewState = calcViewState && (!flags[disableViewState]);
            int viewstatesize;
            if (calcViewState)
                viewstatesize = EstimateStateSize(SaveViewState());
            else
                viewstatesize = 0;

            int controlstatesize = 0;
            if(Page != null && Page._registeredControlsRequiringControlState != null && Page._registeredControlsRequiringControlState.Contains(this)) {
                controlstatesize = EstimateStateSize(SaveControlStateInternal());
            }

            // give it all to the profiler
            Page.Trace.AddNewControl(UniqueID, parentId, this.GetType().FullName, viewstatesize, controlstatesize);

            if (_controls != null) {
                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++) {
                    _controls[i].BuildProfileTree(UniqueID, calcViewState);
                }
            }
        }


        internal object SaveControlStateInternal() {
            object controlState = SaveControlState();
            object adapterControlState = null;
            if (AdapterInternal != null) {
                adapterControlState = AdapterInternal.SaveAdapterControlState();
            }
            if (controlState != null || adapterControlState != null) {
                return new Pair(controlState, adapterControlState);
            }
            return null;
        }


        /// <devdoc>
        /// Save the control state, which is the essential state information needed even if view state is disabled.
        /// </devdoc>
        protected internal virtual object SaveControlState() {
            return null;
        }

        // Save modified state the control would like restored on the postback.
        // Return null if there is no state to save.

        /// <devdoc>
        ///    <para>
        ///       Saves view state for use with a later <see cref='System.Web.UI.Control.LoadViewState'/>
        ///       request.
        ///    </para>
        /// </devdoc>
        protected virtual object SaveViewState() {
            // Save values cached out of view state
            if (flags[visibleDirty]) {
                ViewState["Visible"] = !flags[invisible];
            }
            if (flags[validateRequestModeDirty]) {
                ViewState["ValidateRequestMode"] = (int)ValidateRequestMode;
            }
            if (_viewState != null)
                return _viewState.SaveViewState();

            return null;
        }

        // Answer any state this control or its descendants want to save on freeze.
        // The format for saving is Triplet(myState, ArrayList childIDs, ArrayList childStates),
        // where myState or childStates and childIDs may be null.
        internal object SaveViewStateRecursive(ViewStateMode inheritedMode) {
            if (flags[disableViewState])
                return null;

            bool saveThisState;
            if (flags[viewStateNotInherited]) {
                if (flags[viewStateMode]) {
                    saveThisState = true;
                    inheritedMode = ViewStateMode.Enabled;
                }
                else {
                    saveThisState = false;
                    inheritedMode = ViewStateMode.Disabled;
                }
            }
            else {
                saveThisState = (inheritedMode == ViewStateMode.Enabled);
            }

            object adapterState = null;
            object controlSavedState = null;

            if (saveThisState) {
                if (AdapterInternal != null) {
                    adapterState = AdapterInternal.SaveAdapterViewState();
                }
                controlSavedState = SaveViewState();    
            }

            ArrayList childStates = null;
            if (HasControls()) {
                ControlCollection occasionalFieldControls = _controls;
                int occasionalFieldControlCount = occasionalFieldControls.Count;

                bool useId = LoadViewStateByID;
                for (int i = 0; i < occasionalFieldControlCount; i++) {
                    Control child = occasionalFieldControls[i];
                    object childState = child.SaveViewStateRecursive(inheritedMode);
                    if (childState != null) {
                        if (childStates == null) {
                            childStates = new ArrayList(occasionalFieldControlCount);
                        }

                        if (useId) {
                            child.EnsureID();
                            childStates.Add(child.ID);
                        }
                        else {
                            childStates.Add(i);
                        }
                        childStates.Add(childState);
                    }
                }
            }

            if (AdapterInternal != null) {
                if ((controlSavedState != null) || (adapterState != null) || (childStates != null)) {
                    return new Triplet(controlSavedState, adapterState, childStates);
                }
            }
            else {
                if ((controlSavedState != null) || (childStates != null)) {
                    return new Pair(controlSavedState, childStates);
                }
            }

            return null;
        }


        /// <devdoc>
        /// <para>Outputs control content to a provided HTMLTextWriter
        /// output stream.</para>
        /// </devdoc>
        protected internal virtual void Render(HtmlTextWriter writer) {
            RenderChildren(writer);
        }

        internal void RenderChildrenInternal(HtmlTextWriter writer, ICollection children) {
            // If we have a delegate, use it for the rendering.
            // This happens when there is some ASP code.  See also Whidbey 33012.
            if(RareFields != null && RareFields.RenderMethod != null ) {
                writer.BeginRender();
                RareFields.RenderMethod(writer, this);
                writer.EndRender();
                return;
            }
            if (children != null) {
                foreach (Control child in children) {
                    child.RenderControl(writer);
                }
            }
        }

        protected internal virtual void RenderChildren(HtmlTextWriter writer) {
            ICollection children = _controls;
            RenderChildrenInternal(writer, children);
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public virtual void RenderControl(HtmlTextWriter writer) {
            //use the Adapter property to ensure it is resolved
            RenderControl(writer, Adapter);
        }

        /// <devdoc>
        ///    <para>Used for MobilePage implementation.</para>
        /// </devdoc>
        protected void RenderControl(HtmlTextWriter writer, ControlAdapter adapter) {
            if (!flags[invisible] && !flags[notVisibleOnPage]) {
                HttpContext context = (Page == null) ? null : Page._context;
                if (context  != null && context.TraceIsEnabled) {
                    int presize = context.Response.GetBufferedLength();
                    RenderControlInternal(writer, adapter);
                    int postsize = context.Response.GetBufferedLength();
                    context.Trace.AddControlSize(UniqueID, postsize - presize);
                }
                else {
                    RenderControlInternal(writer, adapter);
                }
            }
            else {
                TraceNonRenderingControlInternal(writer);
            }
        }

        private void RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) {
            try {
                BeginRenderTracing(writer, this);

                if (adapter != null) {
                    // 
                    adapter.BeginRender(writer);
                    adapter.Render(writer);
                    adapter.EndRender(writer);
                }
                else {
                    Render(writer);
                }
            }
            finally {
                EndRenderTracing(writer, this);
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected internal virtual void OnUnload(EventArgs e) {
            if(HasEvents()) {
                EventHandler handler = _events[EventUnload] as EventHandler;
                if (handler != null) {
                    handler(this, e);
                }
            }
        }


        /// <devdoc>
        ///    <para>Enables a control to perform final cleanup.</para>
        /// </devdoc>
        public virtual void Dispose() {
            IContainer container = null;

            if (Site != null) {
                container = (IContainer)Site.GetService(typeof(IContainer));
                if (container != null) {
                    container.Remove(this);
                    EventHandler disp = Events[EventDisposed] as EventHandler;
                    if (disp != null)
                        disp(this, EventArgs.Empty);
                }
            }

            if (_occasionalFields != null) {
                _occasionalFields.Dispose();
                //do not null out for backwards compat, VSWhidbey 475940
                //_occasionalFields = null;
            }

            if (_events != null) {
                _events.Dispose();
                _events = null;
            }
        }


        internal virtual void UnloadRecursive(bool dispose) {
            Page page = Page;
            if (page != null && page.RequiresControlState(this)) {
                page.UnregisterRequiresControlState(this);
                RareFieldsEnsured.RequiredControlState = true;
            }

            // Remove the generated ID so it will be assigned a different ID next time.
            if (flags[useGeneratedID]) {
                _id = null;
                flags.Clear(useGeneratedID);
            }

            if (_controls != null) {
                string oldmsg = _controls.SetCollectionReadOnly(SR.Parent_collections_readonly);

                int controlCount = _controls.Count;
                for (int i = 0; i < controlCount; i++)
                    _controls[i].UnloadRecursive(dispose);

                _controls.SetCollectionReadOnly(oldmsg);
            }

            if (AdapterInternal != null) {
                AdapterInternal.OnUnload(EventArgs.Empty);
            }
            else {
                OnUnload(EventArgs.Empty);
            }

            // 
            if (dispose)
                Dispose();

            // VSWhidbey 244999: Everett behavior doesn't reset the control state.
            // But for control which requires its OnInit method to be called again
            // to properly initialize when the control is removed and added back
            // to Page's control tree, the control can override IsReloadable
            // to true so the control state is reset.  e.g. Validator, see bug
            if (IsReloadable) {
                _controlState = ControlState.Constructed;
            }
        }


        /// <devdoc>
        ///    <para>Assigns an sources of the event and its information up the page control
        ///       hierarchy until they reach the top of the control tree. </para>
        /// </devdoc>
        protected void RaiseBubbleEvent(object source, EventArgs args) {
            Control currentTarget = Parent;
            while (currentTarget != null) {
                if (currentTarget.OnBubbleEvent(source, args)) {
                    return;
                }
                currentTarget = currentTarget.Parent;
            }
        }


        /// <devdoc>
        ///    <para>Determines whether the event for the control should be passed up the page's
        ///       control hierarchy.</para>
        /// </devdoc>
        protected virtual bool OnBubbleEvent(object source, EventArgs args) {
            return false;
        }


        // Members related to being a container


        /// <devdoc>
        ///    <para> Gets a ControlCollection object that represents the child controls for a specified control in the
        ///       UI hierarchy.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_Controls)
        ]
        public virtual ControlCollection Controls {
            get {
                if (_controls == null) {
                    _controls = CreateControlCollection();
                }
                return _controls;
            }
        }

        [
        WebCategory("Behavior"),
        WebSysDescription(SR.Control_ValidateRequestMode),
        DefaultValue(ValidateRequestMode.Inherit)
        ]
        public virtual ValidateRequestMode ValidateRequestMode {
            get {
                return (ValidateRequestMode)flags[validateRequestMode, validateRequestModeOffset];
            }
            set {
                SetValidateRequestModeInternal(value, setDirty: true);
            }
        }

        internal void SetValidateRequestModeInternal(UI.ValidateRequestMode value, bool setDirty) {
            if (value < ValidateRequestMode.Inherit || value > ValidateRequestMode.Enabled) {
                throw new ArgumentOutOfRangeException("value");
            }

            int oldValue = flags[validateRequestMode, validateRequestModeOffset];
            if (setDirty && (oldValue != (int)value)) {
                flags.Set(validateRequestModeDirty);
            }

            flags[validateRequestMode, validateRequestModeOffset] = (int)value;
        }

        internal bool CalculateEffectiveValidateRequest() {
            RuntimeConfig config = RuntimeConfig.GetConfig();
            HttpRuntimeSection runtimeSection = config.HttpRuntime;
            if (runtimeSection.RequestValidationMode >= VersionUtil.Framework45) {
                Control c = this;
                while (c != null) {
                    ValidateRequestMode mode = c.ValidateRequestMode;
                    if (mode != ValidateRequestMode.Inherit) {
                        return mode == ValidateRequestMode.Enabled;
                    }
                    c = c.Parent;
                }
            }
            return true;
        }


        /// <devdoc>
        ///    <para>Indicates a dictionary of state information that allows you to save and restore
        ///       the state of a control across multiple requests for the same page.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        WebSysDescription(SR.Control_State)
        ]
        protected virtual StateBag ViewState {
            get {
                if (_viewState != null) {   // create a StateBag on demand; WebControl makes its case sensitive
                    return _viewState;
                }

                _viewState = new StateBag(ViewStateIgnoresCase);
                if (IsTrackingViewState)
                    _viewState.TrackViewState();
                return _viewState;
            }
        }

        // fast enough that we cam always use it.

        /// <devdoc>
        /// <para>Indicates whether the <see cref='System.Web.UI.StateBag'/> object is case-insensitive.</para>
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)        
        ]
        protected virtual bool ViewStateIgnoresCase {
            get {
                return false;
            }
        }


        /// <devdoc>
        /// </devdoc>
        protected internal virtual void AddedControl(Control control, int index) {
            if (control.OwnerControl != null) {
                throw new InvalidOperationException(SR.GetString(SR.Substitution_NotAllowed));
            }

            if (control._parent != null) {
                control._parent.Controls.Remove(control);
            }

            control._parent = this;
            control._page = Page;
            control.flags.Clear(designModeChecked);

            // We only add to naming container if it is available. Otherwise, it will be pushed through
            // during InitRecursive
            Control namingContainer = flags[isNamingContainer] ? this : _namingContainer;
            if (namingContainer != null) {
                control.UpdateNamingContainer(namingContainer);
                if (control._id == null && !control.flags[idNotRequired]) {
                    // this will also dirty the name table in the naming container
                    control.GenerateAutomaticID();
                }
                else if (control._id != null || (control._controls != null)) {
                    // If the control has and ID, or has children (which *may* themselves
                    // have ID's), we need to dirty the name table (ASURT 100557)
                    namingContainer.DirtyNameTable();
                }
            }

            /*
             * The following is for times when AddChild is called after CreateChildControls. This
             * allows users to add children at any time in the creation process without having
             * to understand the underlying machinery.
             * Note that if page is null, it means we haven't been attached to a container ourselves.
             * If this is true, when we are, our children will be recursively set up.
             */
            if (_controlState >= ControlState.ChildrenInitialized) {

                Debug.Assert(namingContainer != null);
                control.InitRecursive(namingContainer);

                // VSWhidbey 396372: We need to reregister the control state if the control is reparented because the control
                // is unregistered during unload, but its already been inited once, so it will not get its Init called again
                // which is where most controls call RegisterRequiresControlState
                if (control._controlState >= ControlState.Initialized &&
                    control.RareFields != null &&
                    control.RareFields.RequiredControlState) {
                    Page.RegisterRequiresControlState(control);
                }

                if (_controlState >= ControlState.ViewStateLoaded) {
                    object viewState = null;
                    if(_occasionalFields != null && _occasionalFields.ControlsViewState != null) {
                        viewState = _occasionalFields.ControlsViewState[index];
                        // This solution takes the conservative approach that once viewstate has been
                        // applied to a child control, it is thrown away.  This eliminates inadvertently
                        // setting viewstate on the wrong control, which can occur in scenarios where
                        // the child control collection is being manipulated via code.  Probably need
                        // to provide a feature where programmer can control whether to reapply viewstate
                        // or not.
                        if (LoadViewStateByID) {
                            control.EnsureID();
                            viewState = _occasionalFields.ControlsViewState[control.ID];
                            _occasionalFields.ControlsViewState.Remove(control.ID);
                        }
                        else {
                            viewState = _occasionalFields.ControlsViewState[index];
                            _occasionalFields.ControlsViewState.Remove(index);
                        }
                    }

                    control.LoadViewStateRecursive(viewState);

                    if (_controlState >= ControlState.Loaded) {
                        control.LoadRecursive();

                        if (_controlState >= ControlState.PreRendered)
                            control.PreRenderRecursiveInternal();
                    }
                }
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected virtual ControlCollection CreateControlCollection() {
            return new ControlCollection(this);
        }


        /// <devdoc>
        ///    <para>
        ///       Notifies any controls that use composition-based implementation to create any
        ///       child controls they contain in preperation for postback or rendering.
        ///    </para>
        /// </devdoc>
        protected internal virtual void CreateChildControls() {
        }



        /// <devdoc>
        ///    <para>Indicates whether the control's child controls have been created.</para>
        /// </devdoc>
        protected bool ChildControlsCreated {
            get {
                return flags[controlsCreated];
            }
            set {
                if (!value && flags[controlsCreated]) {
                    Controls.Clear();
                }
                if(value) {
                    flags.Set(controlsCreated);
                }
                else {
                    flags.Clear(controlsCreated);
                }
            }
        }


        /// <devdoc>
        ///    <para>Make a URL absolute using the AppRelativeTemplateSourceDirectory.  The returned URL is for
        ///        client use, and will contain the session cookie if appropriate.</para>
        /// </devdoc>
        public string ResolveUrl(string relativeUrl) {
            if (relativeUrl == null) {
                throw new ArgumentNullException("relativeUrl");
            }

            // check if its empty or already absolute
            if ((relativeUrl.Length == 0) || (UrlPath.IsRelativeUrl(relativeUrl) == false)) {
                return relativeUrl;
            }

            string baseUrl = AppRelativeTemplateSourceDirectory;
            if (String.IsNullOrEmpty(baseUrl)) {
                return relativeUrl;
            }

            // first make it absolute
            string url = UrlPath.Combine(baseUrl, relativeUrl);

            // include the session cookie if available (ASURT 47658)
            // As a side effect, this will change an app relative path (~/...) to app absolute
            return Context.Response.ApplyAppPathModifier(url);
        }


        /// <devdoc>
        ///    <para> Return a URL that is suitable for use on the client.
        ///     If the URL is absolute, return it unchanged.  If it is relative, turn it into a
        ///     relative URL that is correct from the point of view of the current request path
        ///     (which is what the browser uses for resolution).</para>
        /// </devdoc>
        public string ResolveClientUrl(string relativeUrl) {
            if (DesignMode && Page != null && Page.Site != null) {
                IUrlResolutionService resolutionService = (IUrlResolutionService)Page.Site.GetService(typeof(IUrlResolutionService));
                if (resolutionService != null) {
                    return resolutionService.ResolveClientUrl(relativeUrl);
                }
            }

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

            // Get the app absolute TemplateSourceDirectory (not app relative)
            string tplSourceDir = VirtualPath.GetVirtualPathString(TemplateControlVirtualDirectory);
            if (String.IsNullOrEmpty(tplSourceDir))
                return relativeUrl;

            string baseRequestDir = Context.Request.ClientBaseDir.VirtualPathString;

            // If the path is app relative (~/...), we cannot take shortcuts, since
            // the ~ is meaningless on the client, and must be resolved
            if (!UrlPath.IsAppRelativePath(relativeUrl)) {

                // If the template source directory is the same as the directory of the request,
                // we don't need to do any adjustments to the input path
                if (StringUtil.EqualsIgnoreCase(baseRequestDir, tplSourceDir))
                    return relativeUrl;

                // check if it's empty or absolute
                if ((relativeUrl.Length == 0) || (!UrlPath.IsRelativeUrl(relativeUrl))) {
                    return relativeUrl;
                }
            }

            // first make it absolute
            string url = UrlPath.Combine(tplSourceDir, relativeUrl);

            // Make sure the path ends with a slash before calling MakeRelative
            baseRequestDir = UrlPath.AppendSlashToPathIfNeeded(baseRequestDir);

            // Now, make it relative to the current request, so that the client will
            // compute the correct path
            url = HttpUtility.UrlPathEncode(UrlPath.MakeRelative(baseRequestDir, url));
            Debug.Trace("ClientUrl", "*** ResolveClientUrl (" + relativeUrl + ") --> " + url + " ***");
            return url;
        }

        internal void DirtyNameTable() {
            Debug.Assert(this is INamingContainer);
            if(_occasionalFields != null) {
                _occasionalFields.NamedControls = null;
            }
        }

        private void EnsureNamedControlsTable() {
            Debug.Assert(this is INamingContainer);
            Debug.Assert(HasControls());
            Debug.Assert(_occasionalFields != null);
            Debug.Assert(_occasionalFields.NamedControls == null);

            _occasionalFields.NamedControls = new HybridDictionary(/*initialSize*/ _occasionalFields.NamedControlsID, /*caseInsensitive*/ true);
            FillNamedControlsTable(this, _controls);
        }

        private void FillNamedControlsTable(Control namingContainer, ControlCollection controls) {
            Debug.Assert(namingContainer._occasionalFields != null);
            Debug.Assert(namingContainer._occasionalFields.NamedControls != null);
            Debug.Assert((controls != null) && (controls.Count != 0));

            int controlCount = controls.Count;
            for (int i=0; i < controlCount; i++) {
                Control control = controls[i];
                if (control._id != null) {
#if DEBUG
                    if (control._namingContainer != null) {
                        Debug.Assert(control._namingContainer == namingContainer);
                    }
#endif // DEBUG
                    try {
                        namingContainer.EnsureOccasionalFields();
                        namingContainer._occasionalFields.NamedControls.Add(control._id, control);
                    }
                    catch {
                        throw new HttpException(SR.GetString(SR.Duplicate_id_used, control._id, "FindControl"));
                    }
                }
                if (control.HasControls() && (control.flags[isNamingContainer] == false)) {
                    FillNamedControlsTable(namingContainer, control.Controls);
                }
            }
        }


        /// <devdoc>
        ///    <para>Searches the current naming container for a control with
        ///       the specified <paramref name="id"/> .</para>
        /// </devdoc>
        public virtual Control FindControl(String id) {
            return FindControl(id, 0);
        }


        /// <internalonly/>
        /// <devdoc>
        ///    <para>Searches the current naming container for a control with the specified
        ///    <paramref name="id"/> and an offset to aid in the
        ///       search.</para>
        /// </devdoc>
        protected virtual Control FindControl(String id, int pathOffset) {
            // DevDiv #338426 - Since this is a recursive function, malicious clients can send us an id
            // which causes a very deep stack dive, resulting in SO (which terminates the worker process).
            // We avoid this via the following call, which at the time of this writing ensures that at
            // least 50% of the available stack remains. The check is very quick: < 1 microsecond.
            RuntimeHelpers.EnsureSufficientExecutionStack();

            string childID;

            EnsureChildControls();

            // If we're not the naming container, let it do the job
            if (!(flags[isNamingContainer])) {
                Control namingContainer = NamingContainer;
                if (namingContainer != null) {
                    return namingContainer.FindControl(id, pathOffset);
                }
                return null;
            }

            // No registered control, demand create the named controls table
            //call HasControls doesn't ensures _occasionalFields != null
            if (HasControls()) {
                EnsureOccasionalFields();
                if (_occasionalFields.NamedControls == null) {
                    EnsureNamedControlsTable();
                }
            }
            if (_occasionalFields == null || _occasionalFields.NamedControls == null) {
                return null;
            }

            // Need to support ':' for V1 backward compatibility.
            char[] findControlSeparators = { ID_SEPARATOR, LEGACY_ID_SEPARATOR };

            // Is it a hierarchical name?
            int newPathOffset = id.IndexOfAny(findControlSeparators, pathOffset);

            // If not, handle it here
            if (newPathOffset == -1) {
                childID = id.Substring(pathOffset);
                return _occasionalFields.NamedControls[childID] as Control;
            }

            // Get the name of the child, and try to locate it
            childID = id.Substring(pathOffset, newPathOffset - pathOffset);
            Control child =  _occasionalFields.NamedControls[childID] as Control;

            // Child doesn't exist: fail
            if (child == null)
                return null;

            return child.FindControl(id, newPathOffset + 1);
        }

        internal Control FindControlFromPageIfNecessary(string id) {
            Control c = FindControl(id);
            // Find control from the page if it's a hierarchical ID.
            // Dev11 bug 19915
            if (c == null && Page != null) {
                char[] findControlSeparators = { ID_SEPARATOR, LEGACY_ID_SEPARATOR };
                if (id.IndexOfAny(findControlSeparators) != -1) {
                    c = Page.FindControl(id);
                }
            }
            return c;
        }

        /*
         * Called when the controls of a naming container are cleared.
         */
        internal void ClearNamingContainer() {
            Debug.Assert(this is INamingContainer);

            EnsureOccasionalFields();
            _occasionalFields.NamedControlsID = 0;
            DirtyNameTable();
        }


        /// <internalonly/>
        /// <devdoc>
        /// </devdoc>
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        protected virtual IDictionary GetDesignModeState() {
            ControlRareFields rareFields = RareFieldsEnsured;
            if (rareFields.DesignModeState == null) {
                rareFields.DesignModeState = new HybridDictionary();
            }
            return rareFields.DesignModeState;
        }


        /// <devdoc>
        ///    <para>Determines if the current control contains any child
        ///       controls. Since this method simply deteremines if any child controls exist at
        ///       all, it can enhance performance by avoiding a call to the Count property,
        ///       inherited from the <see cref='System.Web.UI.ControlCollection'/> class, on the <see cref='System.Web.UI.Control.Controls'/>
        ///       property.</para>
        /// </devdoc>
        public virtual bool HasControls() {
            return _controls != null && _controls.Count > 0;
        }

        /*
         * Check if a Control either has children or has a compiled render method.
         * This is to address issues like ASURT 94127
         */
        internal bool HasRenderingData() {
            return HasControls() || HasRenderDelegate();
        }

        /*
         * Check if a Control either has children or has a compiled render method.
         * This is to address issues like ASURT 94127
         */
        internal bool HasRenderDelegate() {
            if(RareFields != null) {
                return (RareFields.RenderMethod != null );
            }
            return false;
        }

        /*
         * Returns true if the container contains just a static string, i.e.,
         * when the Controls collection has a single LiteralControl.
         */

        /// <devdoc>
        ///    <para>Determines if the container holds literal content only.
        ///       When this method returns <see langword='true'/>
        ///       , the container collection only holds a single literal control. The
        ///       content is then passed to the requesting browser as HTML.</para>
        /// </devdoc>
        protected bool IsLiteralContent() {
            return (_controls != null) && (_controls.Count == 1) &&
            ((_controls[0] is LiteralControl));
        }


        /// <devdoc>
        ///    <para>Determines if view state changes to the
        ///    <see langword='Control'/>
        ///    are being saved. </para>
        /// </devdoc>
        protected bool IsTrackingViewState {
            get {
                return flags[marked];
            }
        }


        /// <devdoc>
        ///    <para>Turns on tracking of view state changes to the control
        ///       so that they can be stored in the <see langword='StateBag'/>
        ///       object.</para>
        /// </devdoc>
        protected virtual void TrackViewState() {
            if (_viewState != null)
                _viewState.TrackViewState();

            flags.Set(marked);
        }


        /// <devdoc>
        ///    <para>Checks that the control contains child controls; if it does not, it creates
        ///       them. This includes any literal content being parsed as a <see cref='System.Web.UI.LiteralControl'/>
        ///       object. </para>
        /// </devdoc>
        protected virtual void EnsureChildControls() {
            if (!ChildControlsCreated && !flags[creatingControls]) {
                flags.Set(creatingControls);
                try {
                    ResolveAdapter();
                    if (AdapterInternal != null) {
                        AdapterInternal.CreateChildControls();
                    }
                    else {
                        CreateChildControls();
                    }

                    // Only set ChildControlsCreated = true if CreateChildControls() did not throw
                    // an exception (VSWhidbey 465798).
                    ChildControlsCreated = true;
                }
                finally {
                    flags.Clear(creatingControls);
                }
            }
        }

        /// <devdoc>
        /// Used internally to store a ControlBuilder reference for the control.
        /// The builder will be used at design-time to help persist all the filtered properties
        /// of the control.
        /// </devdoc>
        internal void SetControlBuilder(ControlBuilder controlBuilder) {
            RareFieldsEnsured.ControlBuilder = controlBuilder;
        }


        /// <devdoc>
        /// </devdoc>
        protected internal virtual void RemovedControl(Control control) {
            if (control.OwnerControl != null) {
                throw new InvalidOperationException(SR.GetString(SR.Substitution_NotAllowed));
            }

            if ((_namingContainer != null) && (control._id != null)) {
                _namingContainer.DirtyNameTable();
            }

            // Controls may need to do their own cleanup.
            control.UnloadRecursive(false);

            control._parent = null;
            control._page = null;
            control._namingContainer = null;

            // Don't reset template source virtual directory on TemplateControl's, because
            // the path is their own, not their parent. i.e. it doesn't change no matter
            // where in the tree they end up.
            if (!(control is TemplateControl)) {
                if (control._occasionalFields != null) {
                    control._occasionalFields.TemplateSourceVirtualDirectory = null;
                }
            }

            if (control._occasionalFields != null ) {
                control._occasionalFields.TemplateControl = null;
            }

            control.flags.Clear(mustRenderID);
            control.ClearCachedUniqueIDRecursive();
        }

        internal void SetDesignMode() {
            flags.Set(designMode);
            flags.Set(designModeChecked);
        }


        /// <internalonly/>
        /// <devdoc>
        /// </devdoc>
        protected virtual void SetDesignModeState(IDictionary data) {
        }

        // Set the delegate to the render method

        /// <internalonly/>
        /// <devdoc>
        ///    <para>Assigns any event handler delegates for the control to match the parameters
        ///       defined in the <see cref='System.Web.UI.RenderMethod'/>. </para>
        /// </devdoc>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public void SetRenderMethodDelegate(RenderMethod renderMethod) {
            RareFieldsEnsured.RenderMethod = renderMethod;

            // Make the collection readonly if there are code blocks (ASURT 78810)
            Controls.SetCollectionReadOnly(SR.Collection_readonly_Codeblocks);
        }


        /// <internalonly/>
        /// <devdoc>
        ///    <para>Returns whether the control contains any data binding logic. This method is
        ///       only accessed by RAD designers.</para>
        /// </devdoc>
        bool IDataBindingsAccessor.HasDataBindings {
            get {
                return ((RareFields != null) && (RareFields.DataBindings != null) && (RareFields.DataBindings.Count != 0));
            }
        }


        /// <internalonly/>
        /// <devdoc>
        /// <para>Indicates a collection of all data bindings on the control. This property is
        /// read-only.</para>
        /// </devdoc>
        DataBindingCollection IDataBindingsAccessor.DataBindings {
            get {
                ControlRareFields rareFields = RareFieldsEnsured;
                if (rareFields.DataBindings == null) {
                    rareFields.DataBindings = new DataBindingCollection();
                }
                return rareFields.DataBindings;
            }
        }


        // IParserAccessor interface
        // A sub-object tag was parsed by the parser; add it to this control.

        /// <internalonly/>
        /// <devdoc>
        /// <para>Notifies the control that an element, XML or HTML, was parsed, and adds it to
        /// the control.</para>
        /// </devdoc>
        void IParserAccessor.AddParsedSubObject(object obj) {
            AddParsedSubObject(obj);
        }

        internal string SpacerImageUrl {
            get {
                EnsureOccasionalFields();
                if (_occasionalFields.SpacerImageUrl == null) {
                    _occasionalFields.SpacerImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(WebControl), "Spacer.gif");
                }
                return _occasionalFields.SpacerImageUrl;
            }
        }

        private Control OwnerControl {
            get {
                if (RareFields == null) {
                    return null;
                }

                return RareFields.OwnerControl;
            }
            set {
                RareFieldsEnsured.OwnerControl = value;
            }
        }

        internal IPostBackDataHandler PostBackDataHandler {
            get {
                IPostBackDataHandler pbdh = AdapterInternal as IPostBackDataHandler;
                if(pbdh != null)
                    return pbdh;
                pbdh = this as IPostBackDataHandler;
                return pbdh;
            }
        }

        internal IPostBackEventHandler PostBackEventHandler {
            get {
                IPostBackEventHandler pbeh = AdapterInternal as IPostBackEventHandler;
                if(pbeh != null)
                    return pbeh;
                pbeh = this as IPostBackEventHandler;
                return pbeh;
            }
        }

        /// <summary>
        /// This method is used for design-time tracing of rendering data.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        protected void BeginRenderTracing(TextWriter writer, object traceObject) {
            RenderTraceListener.CurrentListeners.BeginRendering(writer, traceObject);
        }

        /// <summary>
        /// This method is used for design-time tracing of rendering data.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        protected void EndRenderTracing(TextWriter writer, object traceObject) {
            RenderTraceListener.CurrentListeners.EndRendering(writer, traceObject);
        }

        private void TraceNonRenderingControlInternal(TextWriter writer) {
            BeginRenderTracing(writer, this);
            EndRenderTracing(writer, this);
        }

        /// <summary>
        /// This method is used for design-time tracing of rendering data.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public void SetTraceData(object traceDataKey, object traceDataValue) {
            SetTraceData(this, traceDataKey, traceDataValue);
        }

        /// <summary>
        /// This method is used for design-time tracing of rendering data.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public void SetTraceData(object tracedObject, object traceDataKey, object traceDataValue) {
            RenderTraceListener.CurrentListeners.SetTraceData(tracedObject, traceDataKey, traceDataValue);
        }

        #region IControlDesignerAccessor implementation

        /// <internalonly/>
        IDictionary IControlDesignerAccessor.UserData {
            get {
                ControlRareFields rareFields = RareFieldsEnsured;
                if (rareFields.ControlDesignerAccessorUserData == null) {
                    rareFields.ControlDesignerAccessorUserData = new HybridDictionary();
                }
                return rareFields.ControlDesignerAccessorUserData;
            }
        }

        /// <internalonly/>
        /// <devdoc>
        /// </devdoc>
        IDictionary IControlDesignerAccessor.GetDesignModeState() {
            return GetDesignModeState();
        }


        /// <internalonly/>
        /// <devdoc>
        /// </devdoc>
        void IControlDesignerAccessor.SetDesignModeState(IDictionary data) {
            SetDesignModeState(data);
        }

        void IControlDesignerAccessor.SetOwnerControl(Control owner) {
            if (owner == this) {
                throw new ArgumentException(SR.GetString(SR.Control_CannotOwnSelf), "owner");
            }
            OwnerControl = owner;
            _parent = owner.Parent;
            _page = owner.Page;
        }
        #endregion

        #region IControlBuilderAccessor implementation

        /// <internalonly/>
        /// <devdoc>
        /// A reference to the ControlBuilder that was used to construct this control (if there was one)
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        ControlBuilder IControlBuilderAccessor.ControlBuilder {
            get {
                return RareFields != null ? RareFields.ControlBuilder : null;
            }
        }
        #endregion IControlBuilderAccessor implementation

        #region IExpressionsAccessor


        /// <internalonly/>
        bool IExpressionsAccessor.HasExpressions {
            get {
                if (RareFields == null) {
                    return false;
                }
                ExpressionBindingCollection expressions = RareFields.ExpressionBindings;
                return ((expressions != null) && (expressions.Count > 0));
            }
        }


        /// <internalonly/>
        ExpressionBindingCollection IExpressionsAccessor.Expressions {
            get {
                ExpressionBindingCollection expressions = RareFieldsEnsured.ExpressionBindings;
                if (expressions == null) {
                    expressions = new ExpressionBindingCollection();
                    RareFields.ExpressionBindings = expressions;
                }
                return expressions;
            }
        }
        #endregion

        private sealed class ControlRareFields : IDisposable {

            internal ControlRareFields() {
            }
            public ISite Site;
            public RenderMethod RenderMethod;
            // Reference to the ControlBuilder used to build this control
            public ControlBuilder ControlBuilder;
            public DataBindingCollection DataBindings;
            public Control OwnerControl;
            public ExpressionBindingCollection ExpressionBindings;
            public bool RequiredControlState = false;

            // These fields are only used in the designer so we
            // keep them here to prevent memory bloat at runtime
            public IDictionary ControlDesignerAccessorUserData;
            public IDictionary DesignModeState;

            public Version RenderingCompatibility;
            public RouteCollection RouteCollection;
            public ControlAdapter Adapter;

            public void Dispose() {
                //do not null out for backwards compat, VSWhidbey 475940
                //Site = null;
                //RenderMethod = null;
                //DataBindings = null;
                //OwnerControl = null;
                //ExpressionBindings = null;
                //Adapter = null;
                ControlBuilder = null;
                if (OwnerControl != null)
                {
                    OwnerControl.Dispose();
                }
                ControlDesignerAccessorUserData = null;
                DesignModeState = null;
                RenderingCompatibility = null;
                RouteCollection = null;
            }
        }

        private sealed class OccasionalFields : IDisposable {
            internal OccasionalFields() {
            }

            public string SkinId;
            public IDictionary ControlsViewState;
            public int NamedControlsID;
            // Only used if we are a naming container.  It contains all the controls
            // in the namespace.
            public IDictionary NamedControls;
            public ControlRareFields RareFields;
            public String UniqueIDPrefix;

            public string SpacerImageUrl;
            public TemplateControl TemplateControl;
            public VirtualPath TemplateSourceVirtualDirectory;

            public void Dispose() {
                if (RareFields != null) {
                    RareFields.Dispose();
                }

                ControlsViewState = null;
                //do not null out for backwards compat, VSWhidbey 475940
                //NamedControls = null;
                //UniqueIDPrefix = null;
                //TemplateControl = null;
                //TemplateSourceVirtualDirectory = null;
            }
        }
    }
}