File: WebPartManager.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (4632 lines) | stat: -rw-r--r-- 206,910 bytes parent folder | download | duplicates (6)
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
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
//------------------------------------------------------------------------------
// <copyright file="WebPartManager.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.WebControls.WebParts {

    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Security;
    using System.Security.Permissions;
    using System.Text;
    using System.Web;
    using System.Web.Configuration;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Util;
    using System.Xml;

    [
    Bindable(false),
    Designer("System.Web.UI.Design.WebControls.WebParts.WebPartManagerDesigner, " + AssemblyRef.SystemDesign),
    NonVisualControl(),
    ParseChildren(true),
    PersistChildren(false),
    ViewStateModeById(),
    ]
    public class WebPartManager : Control, INamingContainer, IPersonalizable {

        public static readonly WebPartDisplayMode CatalogDisplayMode = new CatalogWebPartDisplayMode();
        public static readonly WebPartDisplayMode ConnectDisplayMode = new ConnectWebPartDisplayMode();
        public static readonly WebPartDisplayMode DesignDisplayMode = new DesignWebPartDisplayMode();
        public static readonly WebPartDisplayMode EditDisplayMode = new EditWebPartDisplayMode();
        public static readonly WebPartDisplayMode BrowseDisplayMode = new BrowseWebPartDisplayMode();

        // Cache collections of ConnectionPoints for each object Type.  We store an array of
        // 2 ConnectionPointCollections (consumer, provider) for each Type.  The Hashtable
        // is synchronized so it is threadsafe with multiple writers.
        private static Hashtable ConnectionPointsCache;

        private static readonly object AuthorizeWebPartEvent = new object();
        private static readonly object ConnectionsActivatedEvent = new object();
        private static readonly object ConnectionsActivatingEvent = new object();
        private static readonly object DisplayModeChangedEvent = new object();
        private static readonly object DisplayModeChangingEvent = new object();
        private static readonly object SelectedWebPartChangingEvent = new object();
        private static readonly object SelectedWebPartChangedEvent = new object();
        private static readonly object WebPartAddedEvent = new object();
        private static readonly object WebPartAddingEvent = new object();
        private static readonly object WebPartClosedEvent = new object();
        private static readonly object WebPartClosingEvent = new object();
        private static readonly object WebPartDeletedEvent = new object();
        private static readonly object WebPartDeletingEvent = new object();
        private static readonly object WebPartMovedEvent = new object();
        private static readonly object WebPartMovingEvent = new object();
        private static readonly object WebPartsConnectedEvent = new object();
        private static readonly object WebPartsConnectingEvent = new object();
        private static readonly object WebPartsDisconnectedEvent = new object();
        private static readonly object WebPartsDisconnectingEvent = new object();

        private PermissionSet _minimalPermissionSet;
        private PermissionSet _mediumPermissionSet;
        private bool? _usePermitOnly;

        private const string DynamicConnectionIDPrefix = "c";
        private const string DynamicWebPartIDPrefix = "wp";

        private const int baseIndex = 0;
        private const int selectedWebPartIndex = 1;
        private const int displayModeIndex = 2;
        private const int controlStateArrayLength = 3;

        private WebPartPersonalization _personalization;
        private WebPartDisplayMode _displayMode;
        private WebPartDisplayModeCollection _displayModes;
        private WebPartDisplayModeCollection _supportedDisplayModes;
        private WebPartManagerInternals _internals;

        private bool _allowCreateDisplayTitles;
        private bool _pageInitComplete;

        // When this flag is set to false, then cancelled events are ignored.  We will not actually
        // cancel the action even though e.Cancel is true.  (VSWhidbey 516012)
        private bool _allowEventCancellation;

        private PersonalizationDictionary _personalizationState;
        private bool _hasDataChanged;

        private WebPartConnectionCollection _staticConnections;
        private WebPartConnectionCollection _dynamicConnections;

        private WebPartZoneCollection _webPartZones;
        private TransformerTypeCollection _availableTransformers;

        // Dictionary mapping a WebPart to its DisplayTitle.  Created and filled on demand when
        // GetDisplayTitle() is called after PreRender.
        private IDictionary _displayTitles;

        // NOTE: We are no longer rendering the LRO or PDF characters (VSWhidbey 364897)
        // LRO is the Unicode left-to-right override marker.  Effectively creates a "run break"
        // so that contents in parentheses et. al. maintain correct reading order regardless
        // of text direction (LTR or RTL).  PDF "pops" the formatting and allows ensuing text
        // to lay out as it would w/o the markers.  The PDF is needed when constructing dialogs
        // that use the web part titles.  We must use the Unicode characters instead of
        // <span dir="ltr">, since the DisplayTitle is HTML Encoded before being rendered.
        // (VSWhidbey 190501)
        // private static string LRO = new String((char)0x202d, 1);  // left-to-right override
        // private static string PDF = new String((char)0x202c, 1);  // pop directional formatting

        // PERF: At compile-time, compute strings to append to DisplayTitle
        // We chose to compute suffixes up to 20, since it is unlikely there will be more than
        // 20 WebParts with the same title.
        // The 0 element is currently not used, but is a placeholder so the index into the array
        // matches the string.
        private static string[] displayTitleSuffix = new string[] {
            " [0]", " [1]", " [2]", " [3]", " [4]", " [5]", " [6]", " [7]", " [8]", " [9]", " [10]",
            " [11]", " [12]", " [13]", " [14]", " [15]", " [16]", " [17]", " [18]", " [19]", " [20]" };

        // Dictionary mapping a zone to the parts in the zone.  Used by GetAllWebPartsForZone
        // to improve performance.
        private IDictionary _partsForZone;

        // Contains the IDs of WebParts and Child Controls already added.  WebParts and the child
        // controls of GenericWebParts share the same namespace, meaning you cannot have a WebPart
        // and a Child Control with the same ID. An exception is thrown if a WebPart or Child Control
        // is added with a duplicate ID.
        private IDictionary _partAndChildControlIDs;

        // Contains the IDs of Zones already added.  An exception is thrown if a Zone is added with
        // a duplicate ID.
        private IDictionary _zoneIDs;

        private WebPart _selectedWebPart;

        private bool _renderClientScript;

        private const string DragOverlayElementHtmlTemplate = @"
<div id=""{0}___Drag"" style=""display:none; position:absolute; z-index: 32000; filter:alpha(opacity=75)""></div>";
        private const string ExportSensitiveDataWarningDeclaration = "ExportSensitiveDataWarningDeclaration";
        private const string CloseProviderWarningDeclaration = "CloseProviderWarningDeclaration";
        private const string DeleteWarningDeclaration = "DeleteWarningDeclaration";
        private const string StartupScript = @"
<script type=""text/javascript"">

__wpm = new WebPartManager();
__wpm.overlayContainerElement = {0};
__wpm.personalizationScopeShared = {1};

var zoneElement;
var zoneObject;
{2}
</script>
";
        private const string ZoneScript = @"
zoneElement = document.getElementById('{0}');
if (zoneElement != null) {{
    zoneObject = __wpm.AddZone(zoneElement, '{1}', {2}, {3}, '{4}');";

        private const string ZonePartScript = @"
    zoneObject.AddWebPart(document.getElementById('{0}'), {1}, {2});";

        private const string ZoneEndScript = @"
}";

        private const string AuthorizationFilterName = "AuthorizationFilter";
        private const string ImportErrorMessageName = "ImportErrorMessage";
        private const string ZoneIDName = "ZoneID";
        private const string ZoneIndexName = "ZoneIndex";

        internal const string ExportRootElement = "webParts";
        internal const string ExportPartElement = "webPart";
        internal const string ExportPartNamespaceAttribute = "xmlns";
        internal const string ExportPartNamespaceValue = "http://schemas.microsoft.com/WebPart/v3";
        internal const string ExportMetaDataElement = "metaData";
        internal const string ExportTypeElement = "type";
        internal const string ExportErrorMessageElement = "importErrorMessage";
        internal const string ExportDataElement = "data";
        internal const string ExportPropertiesElement = "properties";
        internal const string ExportPropertyElement = "property";
        internal const string ExportTypeNameAttribute = "name";
        internal const string ExportUserControlSrcAttribute = "src";
        internal const string ExportPropertyNameAttribute = "name";
        internal const string ExportGenericPartPropertiesElement = "genericWebPartProperties";
        internal const string ExportIPersonalizableElement = "ipersonalizable";
        internal const string ExportPropertyTypeAttribute = "type";
        internal const string ExportPropertyScopeAttribute = "scope";
        internal const string ExportPropertyNullAttribute = "null";

        private const string ExportTypeBool = "bool";
        private const string ExportTypeInt = "int";
        private const string ExportTypeChromeState = "chromestate";
        private const string ExportTypeChromeType = "chrometype";
        private const string ExportTypeColor = "color";
        private const string ExportTypeDateTime = "datetime";
        private const string ExportTypeDirection = "direction";
        private const string ExportTypeDouble = "double";
        private const string ExportTypeExportMode = "exportmode";
        private const string ExportTypeFontSize = "fontsize";
        private const string ExportTypeHelpMode = "helpmode";
        private const string ExportTypeObject = "object";
        private const string ExportTypeSingle = "single";
        private const string ExportTypeString = "string";
        private const string ExportTypeUnit = "unit";

        /// <devdoc>
        /// </devdoc>
        public WebPartManager() {
            _allowEventCancellation = true;
            _displayMode = BrowseDisplayMode;
            _webPartZones = new WebPartZoneCollection();
            _partAndChildControlIDs = new HybridDictionary(true /* caseInsensitive */);
            _zoneIDs = new HybridDictionary(true /* caseInsensitive */);
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public TransformerTypeCollection AvailableTransformers {
            get {
                if (_availableTransformers == null) {
                    _availableTransformers = CreateAvailableTransformers();
                }
                return _availableTransformers;
            }
        }

        [
        WebCategory("Behavior"),
        WebSysDefaultValue(SR.WebPartManager_DefaultCloseProviderWarning),
        WebSysDescription(SR.WebPartManager_CloseProviderWarning)
        ]
        public virtual string CloseProviderWarning {
            get {
                object o = ViewState["CloseProviderWarning"];
                return (o != null) ? (string)o : SR.GetString(SR.WebPartManager_DefaultCloseProviderWarning);
            }
            set {
                ViewState["CloseProviderWarning"] = value;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public WebPartConnectionCollection Connections {
            get {
                WebPartConnectionCollection connections = new WebPartConnectionCollection(this);
                if (_staticConnections != null) {
                    foreach (WebPartConnection connection in _staticConnections) {
                        if (!Internals.ConnectionDeleted(connection)) {
                            connections.Add(connection);
                        }
                    }
                }
                if (_dynamicConnections != null) {
                    foreach (WebPartConnection connection in _dynamicConnections) {
                        if (!Internals.ConnectionDeleted(connection)) {
                            connections.Add(connection);
                        }
                    }
                }
                connections.SetReadOnly(SR.WebPartManager_ConnectionsReadOnly);
                return connections;
            }
        }

        // Hide the Controls property from IntelliSense.  The developer should use the
        // WebParts property instead.
        [
        EditorBrowsable(EditorBrowsableState.Never),
        ]
        public override ControlCollection Controls {
            get {
                return base.Controls;
            }
        }

        [
        WebCategory("Behavior"),
        WebSysDefaultValue(SR.WebPartManager_DefaultDeleteWarning),
        WebSysDescription(SR.WebPartManager_DeleteWarning)
        ]
        public virtual string DeleteWarning {
            get {
                object o = ViewState["DeleteWarning"];
                return (o != null) ? (string)o : SR.GetString(SR.WebPartManager_DefaultDeleteWarning);
            }
            set {
                ViewState["DeleteWarning"] = value;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public virtual WebPartDisplayMode DisplayMode {
            get {
                return _displayMode;
            }
            set {
                if (value == null) {
                    throw new ArgumentNullException("value");
                }

                if (DisplayMode == value) {
                    return;
                }

                if (SupportedDisplayModes.Contains(value) == false) {
                    throw new ArgumentException(SR.GetString(SR.WebPartManager_InvalidDisplayMode), "value");
                }

                if (!value.IsEnabled(this)) {
                    throw new ArgumentException(SR.GetString(SR.WebPartManager_DisabledDisplayMode), "value");
                }

                WebPartDisplayModeCancelEventArgs dmce = new WebPartDisplayModeCancelEventArgs(value);
                OnDisplayModeChanging(dmce);

                if (_allowEventCancellation && dmce.Cancel) {
                    return;
                }

                // Custom display modes can take actions like this in the OnDisplayModeChanging method.
                // For example:
                // public override void OnDisplayModeChanging(WebPartDisplayModeCancelEventArgs e) {
                //     base.OnDisplayModeChanging(e);
                //     if (e.Cancel) return;
                //     if (DisplayMode == CustomDisplayMode) {
                //         // Take some actions and set e.Cancel=true if appropriate
                //     }
                // }

                // End web part connecting if necessary
                if ((DisplayMode == ConnectDisplayMode) && (SelectedWebPart != null)) {
                    EndWebPartConnecting();
                    if (SelectedWebPart != null) {
                        // WebPartConnectModeChanging event was cancelled
                        return;
                    }
                }

                // End web part editing if necessary
                if ((DisplayMode == EditDisplayMode) && (SelectedWebPart != null)) {
                    EndWebPartEditing();
                    if (SelectedWebPart != null) {
                        // WebPartEditModeChanging event was cancelled
                        return;
                    }
                }

                WebPartDisplayModeEventArgs dme = new WebPartDisplayModeEventArgs(DisplayMode);
                _displayMode = value;
                OnDisplayModeChanged(dme);
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public WebPartDisplayModeCollection DisplayModes {
            get {
                if (_displayModes == null) {
                    _displayModes = CreateDisplayModes();
                    _displayModes.SetReadOnly(SR.WebPartManager_DisplayModesReadOnly);
                }

                return _displayModes;
            }
        }

        protected internal WebPartConnectionCollection DynamicConnections {
            get {
                if (_dynamicConnections == null) {
                    _dynamicConnections = new WebPartConnectionCollection(this);
                }
                return _dynamicConnections;
            }
        }

        [
        DefaultValue(true),
        WebCategory("Behavior"),
        WebSysDescription(SR.WebPartManager_EnableClientScript)
        ]
        public virtual bool EnableClientScript {
            get {
                object o = ViewState["EnableClientScript"];
                return (o != null) ? (bool)o : true;
            }
            set {
                ViewState["EnableClientScript"] = value;
            }
        }

        // Theming must be enabled, so the WebPart child controls have theming enabled
        [
        Browsable(false),
        DefaultValue(true),
        EditorBrowsable(EditorBrowsableState.Never),
        ]
        public override bool EnableTheming {
            get {
                return true;
            }
            set {
                throw new NotSupportedException(SR.GetString(SR.WebPartManager_CantSetEnableTheming));
            }
        }

        [
        WebCategory("Behavior"),
        WebSysDefaultValue(SR.WebPartChrome_ConfirmExportSensitive),
        WebSysDescription(SR.WebPartManager_ExportSensitiveDataWarning)
        ]
        public virtual string ExportSensitiveDataWarning {
            get {
                object o = ViewState["ExportSensitiveDataWarning"];
                return (o != null) ? (string)o : SR.GetString(SR.WebPartChrome_ConfirmExportSensitive);
            }
            set {
                ViewState["ExportSensitiveDataWarning"] = value;
            }
        }

        [
        EditorBrowsable(EditorBrowsableState.Never),
        ]
        protected WebPartManagerInternals Internals {
            get {
                if (_internals == null) {
                    _internals = new WebPartManagerInternals(this);
                }
                return _internals;
            }
        }

        /// <devdoc>
        /// </devdoc>
        protected virtual bool IsCustomPersonalizationStateDirty {
            get {
                return _hasDataChanged;
            }
        }

        // PermissionSet that allows only Execution and AspNetHostingPermissionLevel.Medium.
        // AspNetHostingPermissionLevel.Medium is needed to call BuildManager.GetType().
        // Used for during Import for type deserialization.
        protected virtual PermissionSet MediumPermissionSet {
            get {
                if (_mediumPermissionSet == null) {
                    _mediumPermissionSet = new PermissionSet(PermissionState.None);
                    _mediumPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    _mediumPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));
                }
                return _mediumPermissionSet;
            }
        }

        // PermissionSet that allows only Execution and AspNetHostingPermissionLevel.Minimal.
        // Used for during Import for everything except type deserialization.
        protected virtual PermissionSet MinimalPermissionSet {
            get {
                if (_minimalPermissionSet == null) {
                    _minimalPermissionSet = new PermissionSet(PermissionState.None);
                    _minimalPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    _minimalPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));
                }
                return _minimalPermissionSet;
            }
        }

        /// <devdoc>
        /// </devdoc>
        [
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebCategory("Behavior"),
        WebSysDescription(SR.WebPartManager_Personalization)
        ]
        public WebPartPersonalization Personalization {
            get {
                if (_personalization == null) {
                    _personalization = CreatePersonalization();
                }

                return _personalization;
            }
        }

        internal bool RenderClientScript {
            get {
                return _renderClientScript;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public WebPart SelectedWebPart {
            get {
                return _selectedWebPart;
            }
        }

        [
        Browsable(false),
        DefaultValue(""),
        EditorBrowsable(EditorBrowsableState.Never),
        ]
        public override string SkinID {
            get {
                return String.Empty;
            }
            set {
                throw new NotSupportedException(SR.GetString(SR.NoThemingSupport, this.GetType().Name));
            }
        }

        [
        DefaultValue(null),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        MergableProperty(false),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebCategory("Behavior"),
        WebSysDescription(SR.WebPartManager_StaticConnections),
        ]
        public WebPartConnectionCollection StaticConnections {
            get {
                if (_staticConnections == null) {
                    _staticConnections = new WebPartConnectionCollection(this);
                }
                return _staticConnections;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public WebPartDisplayModeCollection SupportedDisplayModes {
            get {
                if (_supportedDisplayModes == null) {
                    _supportedDisplayModes = new WebPartDisplayModeCollection();

                    foreach (WebPartDisplayMode mode in DisplayModes) {
                        if (mode.AssociatedWithToolZone == false) {
                            _supportedDisplayModes.Add(mode);
                        }
                    }

                    _supportedDisplayModes.SetReadOnly(SR.WebPartManager_DisplayModesReadOnly);
                }
                return _supportedDisplayModes;
            }
        }

        // Only call PermitOnly() in legacy CAS mode.  In the v4 CAS model, calling PermitOnly() would prevent us from calling
        // Activator.CreateInstance() on types in App_Code (assuming it is non-APTCA). (Dev10 Bug 807117)
        private bool UsePermitOnly {
            get {
                if (!_usePermitOnly.HasValue) {
                    _usePermitOnly =  RuntimeConfig.GetAppConfig().Trust.LegacyCasModel;
                }
                return _usePermitOnly.Value;
            }
        }

        [
        Bindable(false),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        EditorBrowsable(EditorBrowsableState.Never),
        ]
        public override bool Visible {
            get {
                // Even though we are a non-visual control, this returns true, because we want our
                // child controls (the WebParts) to be Visible.
                return true;
            }
            set {
                throw new NotSupportedException(SR.GetString(SR.ControlNonVisual, this.GetType().Name));
            }
        }

        /// <devdoc>
        /// All the WebParts on the page.
        /// </devdoc>
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public WebPartCollection WebParts {
            get {
                // PERF: Consider changing WebPartCollection so it just wraps the ControlCollection,
                // instead of copying the controls to a new collection.
                if (HasControls()) {
                    return new WebPartCollection(Controls);
                }
                else {
                    return new WebPartCollection();
                }
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public WebPartZoneCollection Zones {
            get {
                return _webPartZones;
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_AuthorizeWebPart)
        ]
        public event WebPartAuthorizationEventHandler AuthorizeWebPart {
            add {
                Events.AddHandler(AuthorizeWebPartEvent, value);
            }
            remove {
                Events.RemoveHandler(AuthorizeWebPartEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_ConnectionsActivated)
        ]
        public event EventHandler ConnectionsActivated {
            add {
                Events.AddHandler(ConnectionsActivatedEvent, value);
            }
            remove {
                Events.RemoveHandler(ConnectionsActivatedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_ConnectionsActivating)
        ]
        public event EventHandler ConnectionsActivating {
            add {
                Events.AddHandler(ConnectionsActivatingEvent, value);
            }
            remove {
                Events.RemoveHandler(ConnectionsActivatingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_DisplayModeChanged)
        ]
        public event WebPartDisplayModeEventHandler DisplayModeChanged {
            add {
                Events.AddHandler(DisplayModeChangedEvent, value);
            }
            remove {
                Events.RemoveHandler(DisplayModeChangedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_DisplayModeChanging)
        ]
        public event WebPartDisplayModeCancelEventHandler DisplayModeChanging {
            add {
                Events.AddHandler(DisplayModeChangingEvent, value);
            }
            remove {
                Events.RemoveHandler(DisplayModeChangingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_SelectedWebPartChanged)
        ]
        public event WebPartEventHandler SelectedWebPartChanged {
            add {
                Events.AddHandler(SelectedWebPartChangedEvent, value);
            }
            remove {
                Events.RemoveHandler(SelectedWebPartChangedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_SelectedWebPartChanging)
        ]
        public event WebPartCancelEventHandler SelectedWebPartChanging {
            add {
                Events.AddHandler(SelectedWebPartChangingEvent, value);
            }
            remove {
                Events.RemoveHandler(SelectedWebPartChangingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartAdded)
        ]
        public event WebPartEventHandler WebPartAdded {
            add {
                Events.AddHandler(WebPartAddedEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartAddedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartAdding)
        ]
        public event WebPartAddingEventHandler WebPartAdding {
            add {
                Events.AddHandler(WebPartAddingEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartAddingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartClosed)
        ]
        public event WebPartEventHandler WebPartClosed {
            add {
                Events.AddHandler(WebPartClosedEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartClosedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartClosing)
        ]
        public event WebPartCancelEventHandler WebPartClosing {
            add {
                Events.AddHandler(WebPartClosingEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartClosingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartDeleted)
        ]
        public event WebPartEventHandler WebPartDeleted {
            add {
                Events.AddHandler(WebPartDeletedEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartDeletedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartDeleting)
        ]
        public event WebPartCancelEventHandler WebPartDeleting {
            add {
                Events.AddHandler(WebPartDeletingEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartDeletingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartMoved)
        ]
        public event WebPartEventHandler WebPartMoved {
            add {
                Events.AddHandler(WebPartMovedEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartMovedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartMoving)
        ]
        public event WebPartMovingEventHandler WebPartMoving {
            add {
                Events.AddHandler(WebPartMovingEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartMovingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartsConnected)
        ]
        public event WebPartConnectionsEventHandler WebPartsConnected {
            add {
                Events.AddHandler(WebPartsConnectedEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartsConnectedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartsConnecting)
        ]
        public event WebPartConnectionsCancelEventHandler WebPartsConnecting {
            add {
                Events.AddHandler(WebPartsConnectingEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartsConnectingEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartsDisconnected)
        ]
        public event WebPartConnectionsEventHandler WebPartsDisconnected {
            add {
                Events.AddHandler(WebPartsDisconnectedEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartsDisconnectedEvent, value);
            }
        }

        [
        WebCategory("Action"),
        WebSysDescription(SR.WebPartManager_WebPartsDisconnecting)
        ]
        public event WebPartConnectionsCancelEventHandler WebPartsDisconnecting {
            add {
                Events.AddHandler(WebPartsDisconnectingEvent, value);
            }
            remove {
                Events.RemoveHandler(WebPartsDisconnectingEvent, value);
            }
        }

        protected virtual void ActivateConnections() {
            try {
                // ActivateConnections() is called as a result of no user action, so the events
                // should not be cancellable. (VSWhidbey 516012)
                _allowEventCancellation = false;
                foreach (WebPartConnection connection in ConnectionsToActivate()) {
                    connection.Activate();
                }
            }
            finally {
                _allowEventCancellation = true;
            }
        }

        // Called by WebPartManagerInternals
        internal void AddWebPart(WebPart webPart) {
            ((WebPartManagerControlCollection)Controls).AddWebPart(webPart);
        }

        private WebPart AddDynamicWebPartToZone(WebPart webPart, WebPartZoneBase zone, int zoneIndex) {
            Debug.Assert(Personalization.IsModifiable);

            // Zone should not be set on a dynamic web part being added to the page for the first time
            Debug.Assert(webPart.Zone == null);

            // Only add WebPart if IsAuthorized(webPart) == true
            if (!IsAuthorized(webPart)) {
                return null;
            }

            WebPart newWebPart = CopyWebPart(webPart);
            Internals.SetIsStatic(newWebPart, false);
            Internals.SetIsShared(newWebPart, Personalization.Scope == PersonalizationScope.Shared);

            AddWebPartToZone(newWebPart, zone, zoneIndex);
            Internals.AddWebPart(newWebPart);

            // We set the personalized properties on the added WebPart AFTER it has been added to the
            // control tree, since we want to exactly recreate the process the WebPart will go through
            // when it is added from Personalization.
            Personalization.CopyPersonalizationState(webPart, newWebPart);

            // Raise event at very end of Add method
            OnWebPartAdded(new WebPartEventArgs(newWebPart));

            return newWebPart;
        }

        // Returns the WebPart that was actually added.  For an existing Closed WebPart, this is a reference
        // to the webPart parameter.  For a new DynamicWebPart, this will be a copy of the webPart parameter.
        public WebPart AddWebPart(WebPart webPart, WebPartZoneBase zone, int zoneIndex) {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }
            // Do not check that Controls.Contains(webPart), since this will be called on a WebPart
            // before it is added to the Controls collection.
            if (zone == null) {
                throw new ArgumentNullException("zone");
            }
            if (_webPartZones.Contains(zone) == false) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_MustRegister), "zone");
            }
            if (zoneIndex < 0) {
                throw new ArgumentOutOfRangeException("zoneIndex");
            }
            if (webPart.Zone != null && !webPart.IsClosed) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_AlreadyInZone), "webPart");
            }

            WebPartAddingEventArgs e = new WebPartAddingEventArgs(webPart, zone, zoneIndex);
            OnWebPartAdding(e);
            if (_allowEventCancellation && e.Cancel) {
                return null;
            }

            WebPart addedWebPart;

            // If a part is already in the controls collection, dynamic or static, just make it
            // not closed and add it to the specified zone
            if (Controls.Contains(webPart)) {
                addedWebPart = webPart;
                AddWebPartToZone(webPart, zone, zoneIndex);
                OnWebPartAdded(new WebPartEventArgs(addedWebPart));
            } else {
                addedWebPart = AddDynamicWebPartToZone(webPart, zone, zoneIndex);
                // OnWebPartAdded() is called by AddDynamicWebPartToZone
            }

#if DEBUG
            CheckPartZoneIndexes(zone);
#endif

            return addedWebPart;
        }

        /// <devdoc>
        /// Adds the part to the dictionary mapping zones to parts.
        /// </devdoc>
        private void AddWebPartToDictionary(WebPart webPart) {
            if (_partsForZone != null) {
                string zoneID = Internals.GetZoneID(webPart);
                if (!String.IsNullOrEmpty(zoneID)) {
                    SortedList partsForZone = (SortedList)(_partsForZone[zoneID]);
                    if (partsForZone == null) {
                        partsForZone = new SortedList(new WebPart.ZoneIndexComparer());
                        _partsForZone[zoneID] = partsForZone;
                    }
                    partsForZone.Add(webPart, null);
                }
            }
        }

        /// <devdoc>
        /// Adds a web part to a zone at the specified zoneIndex, and renumbers all the parts in the zone
        /// sequentially.
        /// </devdoc>
        private void AddWebPartToZone(WebPart webPart, WebPartZoneBase zone, int zoneIndex) {
            Debug.Assert(webPart.Zone == null || webPart.IsClosed);

            // All the parts for the zone
            IList allParts = GetAllWebPartsForZone(zone);

            // The parts for the zone that were actually rendered
            WebPartCollection renderedParts = GetWebPartsForZone(zone);

            // The zoneIndex parameter is the desired index in the renderedParts collection.
            // Calculate the destination index into the allParts collection. (VSWhidbey 77719)
            int allPartsDestinationIndex;
            if (zoneIndex < renderedParts.Count) {
                WebPart successor = renderedParts[zoneIndex];
                Debug.Assert(allParts.Contains(successor));
                allPartsDestinationIndex = allParts.IndexOf(successor);
            }
            else {
                allPartsDestinationIndex = allParts.Count;
            }

            // Renumber all parts in the zone, leaving room for the added part
            for (int i = 0; i < allPartsDestinationIndex; i++) {
                WebPart part = ((WebPart)allParts[i]);
                Internals.SetZoneIndex(part, i);
            }
            for (int i = allPartsDestinationIndex; i < allParts.Count; i++) {
                WebPart part = ((WebPart)allParts[i]);
                Internals.SetZoneIndex(part, i + 1);
            }

            // Set the part index and add to destination zone
            Internals.SetZoneIndex(webPart, allPartsDestinationIndex);
            Internals.SetZoneID(webPart, zone.ID);
            Internals.SetIsClosed(webPart, false);

            _hasDataChanged = true;

            AddWebPartToDictionary(webPart);
        }

        public virtual void BeginWebPartConnecting(WebPart webPart) {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

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

            if (webPart.IsClosed) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_CantBeginConnectingClosed), "webPart");
            }

            if (!Controls.Contains(webPart)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "webPart");
            }

            if (DisplayMode != ConnectDisplayMode) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartManager_MustBeInConnect));
            }

            if (webPart == SelectedWebPart) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_AlreadyInConnect), "webPart");
            }

            WebPartCancelEventArgs ce = new WebPartCancelEventArgs(webPart);
            OnSelectedWebPartChanging(ce);
            if (_allowEventCancellation && ce.Cancel) {
                return;
            }

            if (SelectedWebPart != null) {
                EndWebPartConnecting();
                if (SelectedWebPart != null) {
                    // The ConnectModeChange was cancelled
                    return;
                }
            }

            SetSelectedWebPart(webPart);

            Internals.CallOnConnectModeChanged(webPart);

            OnSelectedWebPartChanged(new WebPartEventArgs(webPart));
        }

        public virtual void BeginWebPartEditing(WebPart webPart) {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

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

            if (webPart.IsClosed) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_CantBeginEditingClosed), "webPart");
            }

            if (!Controls.Contains(webPart)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "webPart");
            }

            if (DisplayMode != EditDisplayMode) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartManager_MustBeInEdit));
            }

            if (webPart == SelectedWebPart) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_AlreadyInEdit), "webPart");
            }

            WebPartCancelEventArgs ce = new WebPartCancelEventArgs(webPart);
            OnSelectedWebPartChanging(ce);
            if (_allowEventCancellation && ce.Cancel) {
                return;
            }

            if (SelectedWebPart != null) {
                EndWebPartEditing();
                if (SelectedWebPart != null) {
                    // The EditModeChange was cancelled
                    return;
                }
            }

            SetSelectedWebPart(webPart);

            Internals.CallOnEditModeChanged(webPart);

            OnSelectedWebPartChanged(new WebPartEventArgs(webPart));
        }

#if DEBUG
        /// <devdoc>
        /// Checks that the web parts in a zone are numbered sequentially.  This invariant
        /// should hold at the exit of AddWebPart, CloseWebPart, DeleteWebPart, MoveWebPart, and RegisterZone.
        /// </devdoc>
        private void CheckPartZoneIndexes(WebPartZoneBase zone) {
            ICollection parts = GetAllWebPartsForZone(zone);
            int index = 0;
            foreach (WebPart part in parts) {
                if (part.ZoneIndex != index) {
                    System.Text.StringBuilder builder = new System.Text.StringBuilder();
                    builder.Append("Title\tZone\tZoneIndex");
                    foreach (WebPart part2 in Controls) {
                        string zoneTitle = (part2.Zone == null) ? "null" : part2.Zone.DisplayTitle;
                        builder.Append(part2.DisplayTitle + "\t" + zoneTitle + "\t" + part2.ZoneIndex);
                    }
                    Debug.Assert(false, builder.ToString());
                    return;
                }
                index++;
            }
        }
#endif // DEBUG

        protected virtual bool CheckRenderClientScript() {
            bool renderClientScript = false;

            if (EnableClientScript && Page != null) {
                HttpBrowserCapabilities browserCaps = Page.Request.Browser;

                // Win32 IE5.5+ and JScript 5.5+
                if (browserCaps.Win32 && (browserCaps.MSDomVersion.CompareTo(new Version(5, 5)) >= 0)) {
                    renderClientScript = true;
                }
            }

            return renderClientScript;
        }

        // When a Zone is deleted, any web parts in that zone should move to the page catalog.
        // VSWhidbey 77708
        private void CloseOrphanedParts() {
            // PERF: Use Controls instead of WebParts property, to avoid creating another collection
            if (HasControls()) {
                try {
                    // CloseOrphanedParts() is called as a result of no user action, so the events
                    // should not be cancellable. (VSWhidbey 516012)
                    _allowEventCancellation = false;
                    foreach (WebPart part in Controls) {
                        if (part.IsOrphaned) {
                            CloseWebPart(part);
                        }
                    }
                }
                finally {
                    _allowEventCancellation = true;
                }
            }
        }

        public bool CanConnectWebParts(WebPart provider, ProviderConnectionPoint providerConnectionPoint,
                                       WebPart consumer, ConsumerConnectionPoint consumerConnectionPoint) {
            return CanConnectWebParts(provider, providerConnectionPoint, consumer, consumerConnectionPoint, null);
        }

        public virtual bool CanConnectWebParts(WebPart provider, ProviderConnectionPoint providerConnectionPoint,
                                               WebPart consumer, ConsumerConnectionPoint consumerConnectionPoint,
                                               WebPartTransformer transformer) {
            return CanConnectWebPartsCore(provider, providerConnectionPoint, consumer, consumerConnectionPoint,
                                          transformer, false);
        }

        private bool CanConnectWebPartsCore(WebPart provider, ProviderConnectionPoint providerConnectionPoint,
                                            WebPart consumer, ConsumerConnectionPoint consumerConnectionPoint,
                                            WebPartTransformer transformer, bool throwOnError) {
            if (!Personalization.IsModifiable) {
                if (throwOnError) {
                    // Will throw appropriate exception
                    Personalization.EnsureEnabled(/* ensureModifiable */ true);
                }
                else {
                    return false;
                }
            }

            if (provider == null) {
                throw new ArgumentNullException("provider");
            }
            if (!Controls.Contains(provider)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "provider");
            }

            if (consumer == null) {
                throw new ArgumentNullException("consumer");
            }
            if (!Controls.Contains(consumer)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "consumer");
            }

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

            Control providerControl = provider.ToControl();
            Control consumerControl = consumer.ToControl();

            if (providerConnectionPoint.ControlType != providerControl.GetType()) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_InvalidConnectionPoint), "providerConnectionPoint");
            }
            if (consumerConnectionPoint.ControlType != consumerControl.GetType()) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_InvalidConnectionPoint), "consumerConnectionPoint");
            }

            if (provider == consumer) {
                if (throwOnError) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartManager_CantConnectToSelf));
                }
                else {
                    return false;
                }
            }

            if (provider.IsClosed) {
                if (throwOnError) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartManager_CantConnectClosed, provider.ID));
                }
                else {
                    return false;
                }
            }

            if (consumer.IsClosed) {
                if (throwOnError) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartManager_CantConnectClosed, consumer.ID));
                }
                else {
                    return false;
                }
            }

            if (!providerConnectionPoint.GetEnabled(providerControl)) {
                if (throwOnError) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_DisabledConnectionPoint, providerConnectionPoint.ID, provider.ID));
                }
                else {
                    return false;
                }
            }

            if (!consumerConnectionPoint.GetEnabled(consumerControl)) {
                if (throwOnError) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_DisabledConnectionPoint, consumerConnectionPoint.ID, consumer.ID));
                }
                else {
                    return false;
                }
            }

            // Check AllowsMultipleConnections on each ConnectionPoint
            if (!providerConnectionPoint.AllowsMultipleConnections) {
                foreach (WebPartConnection c in Connections) {
                    if (c.Provider == provider && c.ProviderConnectionPoint == providerConnectionPoint) {
                        if (throwOnError) {
                            throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_Duplicate, providerConnectionPoint.ID, provider.ID));
                        }
                        else {
                            return false;
                        }
                    }
                }
            }

            if (!consumerConnectionPoint.AllowsMultipleConnections) {
                foreach (WebPartConnection c in Connections) {
                    if (c.Consumer == consumer && c.ConsumerConnectionPoint == consumerConnectionPoint) {
                        if (throwOnError) {
                            throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_Duplicate, consumerConnectionPoint.ID, consumer.ID));
                        }
                        else {
                            return false;
                        }
                    }
                }
            }

            if (transformer == null) {
                if (providerConnectionPoint.InterfaceType != consumerConnectionPoint.InterfaceType) {
                    if (throwOnError) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_NoCommonInterface,
                            new string[] {providerConnectionPoint.DisplayName, provider.ID,
                                consumerConnectionPoint.DisplayName, consumer.ID}));
                    }
                    else {
                        return false;
                    }
                }

                ConnectionInterfaceCollection secondaryInterfaces = providerConnectionPoint.GetSecondaryInterfaces(providerControl);
                if (!consumerConnectionPoint.SupportsConnection(consumerControl, secondaryInterfaces)) {
                    if (throwOnError) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_IncompatibleSecondaryInterfaces, new string[] {
                                consumerConnectionPoint.DisplayName, consumer.ID,
                                providerConnectionPoint.DisplayName, provider.ID}));
                    }
                    else {
                        return false;
                    }
                }
            }
            else {
                Type transformerType = transformer.GetType();

                if (!AvailableTransformers.Contains(transformerType)) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_TransformerNotAvailable, transformerType.FullName));
                }

                // Check matching interfaces on connection points and transformer attribute.
                // Note that we require the connection interfaces to match exactly.  We do not match
                // a derived interface type.  This is because we want to simplify the interface matching
                // algorithm when transformers are involved.  If we allowed derived interfaces to match,
                // then we would to take into account the "closest" match if multiple transformers
                // have compatible interfaces.
                Type transformerConsumerType = WebPartTransformerAttribute.GetConsumerType(transformerType);
                Type transformerProviderType = WebPartTransformerAttribute.GetProviderType(transformerType);
                if (providerConnectionPoint.InterfaceType != transformerConsumerType) {
                    if (throwOnError) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_IncompatibleProviderTransformer,
                            providerConnectionPoint.DisplayName, provider.ID, transformerType.FullName));
                    }
                    else {
                        return false;
                    }
                }
                if (transformerProviderType != consumerConnectionPoint.InterfaceType) {
                    if (throwOnError) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_IncompatibleConsumerTransformer,
                            transformerType.FullName, consumerConnectionPoint.DisplayName, consumer.ID));
                    }
                    else {
                        return false;
                    }
                }

                // A transformer never provides any secondary interfaces
                if (!consumerConnectionPoint.SupportsConnection(consumerControl, ConnectionInterfaceCollection.Empty)) {
                    if (throwOnError) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_ConsumerRequiresSecondaryInterfaces,
                            consumerConnectionPoint.DisplayName, consumer.ID));
                    }
                    else {
                        return false;
                    }
                }

            }

            return true;
        }

        public void CloseWebPart(WebPart webPart) {
            CloseOrDeleteWebPart(webPart, /* delete */ false);
        }

        private void CloseOrDeleteWebPart(WebPart webPart, bool delete) {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }
            if (!Controls.Contains(webPart)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "webPart");
            }

            if (!delete && webPart.IsClosed) {
                // Throw an exception instead of just returning.  If the shared user and per user close
                // a WebPart at the same time, then the WebPartZoneBase should not call CloseWebPart
                // if the WebPart is now closed.
                throw new ArgumentException(SR.GetString(SR.WebPartManager_AlreadyClosed), "webPart");
            }

            if (delete) {
                if (webPart.IsStatic) {
                    // Can't delete static parts
                    throw new ArgumentException(SR.GetString(SR.WebPartManager_CantDeleteStatic), "webPart");
                }
                else if (webPart.IsShared && (Personalization.Scope == PersonalizationScope.User)) {
                    // Can't delete shared part in user scope
                    throw new ArgumentException(SR.GetString(SR.WebPartManager_CantDeleteSharedInUserScope), "webPart");
                }
            }

            WebPartCancelEventArgs ce = new WebPartCancelEventArgs(webPart);
            if (delete) {
                OnWebPartDeleting(ce);
            }
            else {
                OnWebPartClosing(ce);
            }
            if (_allowEventCancellation && ce.Cancel) {
                return;
            }

            if ((DisplayMode == ConnectDisplayMode) && (webPart == SelectedWebPart)) {
                EndWebPartConnecting();
                if (SelectedWebPart != null) {
                    // The ConnectModeChange was cancelled
                    return;
                }
            }

            // VSWhidbey 77768
            if ((DisplayMode == EditDisplayMode) && (webPart == SelectedWebPart)) {
                EndWebPartEditing();
                if (SelectedWebPart != null) {
                    // The EditModeChange was cancelled
                    return;
                }
            }

            if (delete) {
                Internals.CallOnDeleting(webPart);
            }
            else {
                Internals.CallOnClosing(webPart);
            }

#if DEBUG
            WebPartZoneBase zone = webPart.Zone;
#endif

            // If we are deleting a closed WebPart, it has already been removed from
            // its Zone, so there is no need to do it again.
            if (!webPart.IsClosed) {
                RemoveWebPartFromZone(webPart);
            }

            DisconnectWebPart(webPart);

            if (delete) {
                Internals.RemoveWebPart(webPart);

                // Raise the WebPartDeleted event after changing the WebPart properties
                // The WebPartDeleting event is raised before changing the WebPart properties
                OnWebPartDeleted(new WebPartEventArgs(webPart));
            }
            else {
                // Raise the WebPartClosed event after changing the WebPart properties
                // The WebPartClosing event is raised before changing the WebPart properties
                OnWebPartClosed(new WebPartEventArgs(webPart));
            }

#if DEBUG
            if (zone != null) {
                CheckPartZoneIndexes(zone);
            }
#endif
        }

        private WebPartConnection[] ConnectionsToActivate() {
            // PERF: We could implement this with a sorted list to simplify the code

            ArrayList connectionsToActivate = new ArrayList();

            // Contains the connection IDs we have already seen
            HybridDictionary connectionIDs = new HybridDictionary(true /* caseInsensitive */);

            WebPartConnection[] connections = new WebPartConnection[StaticConnections.Count + DynamicConnections.Count];
            StaticConnections.CopyTo(connections, 0);
            DynamicConnections.CopyTo(connections, StaticConnections.Count);
            foreach (WebPartConnection connection in connections) {
                ConnectionsToActivateHelper(connection, connectionIDs, connectionsToActivate);
            }

            // Check unshared connections for conflicts with shared connections
            // Maybe this should only be done in user scope
            WebPartConnection[] connectionsToActivateArray = (WebPartConnection[])connectionsToActivate.ToArray(typeof(WebPartConnection));
            foreach (WebPartConnection connection in connectionsToActivateArray) {
                if (connection.IsShared) {
                    continue;
                }

                ArrayList connectionsToDelete = new ArrayList();
                foreach (WebPartConnection otherConnection in connectionsToActivate) {
                    if (connection == otherConnection) {
                        continue;
                    }

                    if (otherConnection.IsShared && connection.ConflictsWith(otherConnection)) {
                        // Delete shared connection.
                        connectionsToDelete.Add(otherConnection);
                    }
                }

                foreach (WebPartConnection connectionToDelete in connectionsToDelete) {
                    DisconnectWebParts(connectionToDelete);
                    connectionsToActivate.Remove(connectionToDelete);
                }
            }

            // Check shared, nonstatic connections for conflicts with static connections
            connectionsToActivateArray = (WebPartConnection[])connectionsToActivate.ToArray(typeof(WebPartConnection));
            foreach (WebPartConnection connection in connectionsToActivateArray) {
                if (!connection.IsShared || connection.IsStatic) {
                    continue;
                }

                ArrayList connectionsToDelete = new ArrayList();
                foreach (WebPartConnection otherConnection in connectionsToActivate) {
                    if (connection == otherConnection) {
                        continue;
                    }

                    if (otherConnection.IsStatic && connection.ConflictsWith(otherConnection)) {
                        // Delete static connection.
                        connectionsToDelete.Add(otherConnection);
                    }
                }

                foreach (WebPartConnection connectionToDelete in connectionsToDelete) {
                    DisconnectWebParts(connectionToDelete);
                    connectionsToActivate.Remove(connectionToDelete);
                }
            }

            // Check all remaining connections for conflicts.  Any conflicts at this stage will
            // cause an error to be rendered in the consumer WebPart, and the conflicting connections
            // will not be activated.
            ArrayList finalConnectionsToActivate = new ArrayList();
            foreach (WebPartConnection connection in connectionsToActivate) {
                bool hasConflict = false;

                foreach (WebPartConnection otherConnection in connectionsToActivate) {
                    if (connection == otherConnection) {
                        continue;
                    }

                    if (connection.ConflictsWithConsumer(otherConnection)) {
                        connection.Consumer.SetConnectErrorMessage(SR.GetString(SR.WebPartConnection_Duplicate, connection.ConsumerConnectionPoint.DisplayName,
                                connection.Consumer.DisplayTitle));
                        hasConflict = true;
                    }

                    if (connection.ConflictsWithProvider(otherConnection)) {
                        connection.Consumer.SetConnectErrorMessage(SR.GetString(SR.WebPartConnection_Duplicate, connection.ProviderConnectionPoint.DisplayName,
                                connection.Provider.DisplayTitle));
                        hasConflict = true;
                    }
                }

                if (!hasConflict) {
                    finalConnectionsToActivate.Add(connection);
                }
            }

            // Don't allow the user to modify the StaticConnections collection after its connections have
            // been activated.  Use property instead of field to force creation of collection.
            StaticConnections.SetReadOnly(SR.WebPartManager_StaticConnectionsReadOnly);

            // The user can't directly change the DynamicConnections property since it is internal.
            // Make it read-only in case we have a bug and try to change it after activation.
            // We check the read-only status of this collection in ConnectWebParts() and DisconnectWebParts().
            DynamicConnections.SetReadOnly(SR.WebPartManager_DynamicConnectionsReadOnly);

            return (WebPartConnection[])finalConnectionsToActivate.ToArray(typeof(WebPartConnection));
        }

        // If we think we should activate the connection, adds it to the dictionary under the key
        // for its provider and consumer connection points.
        private void ConnectionsToActivateHelper(WebPartConnection connection, IDictionary connectionIDs,
                                                 ArrayList connectionsToActivate) {
            string connectionID = connection.ID;

            if (String.IsNullOrEmpty(connectionID)) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_NoID));
            }

            if (connectionIDs.Contains(connectionID)) {
                throw new InvalidOperationException(
                    SR.GetString(SR.WebPartManager_DuplicateConnectionID, connectionID));
            }
            connectionIDs.Add(connectionID, null);

            if (connection.Deleted) {
                return;
            }

            WebPart providerWebPart = connection.Provider;
            if (providerWebPart == null) {
                if (connection.IsStatic) {
                    // throw an exception, to alert the developer that his static connection is invalid
                    throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_NoProvider, connection.ProviderID));
                }
                else {
                    // Silently delete the connection, since this is a valid runtime scenario.
                    // A connected web part may have been deleted.
                    DisconnectWebParts(connection);
                    return;
                }
            }

            WebPart consumerWebPart = connection.Consumer;
            if (consumerWebPart == null) {
                if (connection.IsStatic) {
                    // throw an exception, to alert the developer that his static connection is invalid
                    throw new InvalidOperationException(SR.GetString(SR.WebPartConnection_NoConsumer, connection.ConsumerID));
                }
                else {
                    // Silently delete the connection, since this is a valid runtime scenario.
                    // A connected web part may have been deleted.
                    DisconnectWebParts(connection);
                    return;
                }
            }

            // Do not activate connections involving ProxyWebParts
            if (providerWebPart is ProxyWebPart || consumerWebPart is ProxyWebPart) {
                return;
            }

            Control providerControl = providerWebPart.ToControl();
            Control consumerControl = consumerWebPart.ToControl();

            // Cannot connect a WebPart to itself
            if (providerControl == consumerControl) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartManager_CantConnectToSelf));
            }

            ProviderConnectionPoint providerConnectionPoint = connection.ProviderConnectionPoint;
            if (providerConnectionPoint == null) {
                consumerWebPart.SetConnectErrorMessage(SR.GetString(SR.WebPartConnection_NoProviderConnectionPoint, connection.ProviderConnectionPointID,
                    providerWebPart.DisplayTitle));
                return;
            }
            // Don't need to check that providerConnectionPoint is enabled, since this will be checked
            // in WebPartConnection.Activate().

            ConsumerConnectionPoint consumerConnectionPoint = connection.ConsumerConnectionPoint;
            if (consumerConnectionPoint == null) {
                consumerWebPart.SetConnectErrorMessage(SR.GetString(SR.WebPartConnection_NoConsumerConnectionPoint, connection.ConsumerConnectionPointID,
                    consumerWebPart.DisplayTitle));
                return;
            }
            // Don't need to check that consumer ConnectionPoint is enabled, since this will be checked
            // in WebPartConnection.Activate().

            connectionsToActivate.Add(connection);
        }

        public WebPartConnection ConnectWebParts(WebPart provider, ProviderConnectionPoint providerConnectionPoint,
                                                 WebPart consumer, ConsumerConnectionPoint consumerConnectionPoint) {
            return ConnectWebParts(provider, providerConnectionPoint, consumer, consumerConnectionPoint, null);
        }

        public virtual WebPartConnection ConnectWebParts(WebPart provider, ProviderConnectionPoint providerConnectionPoint,
                                                         WebPart consumer, ConsumerConnectionPoint consumerConnectionPoint,
                                                         WebPartTransformer transformer) {
            CanConnectWebPartsCore(provider, providerConnectionPoint, consumer, consumerConnectionPoint,
                                   transformer, /*throwOnError*/ true);

            if (DynamicConnections.IsReadOnly) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartManager_ConnectTooLate));
            }

            WebPartConnectionsCancelEventArgs ce = new WebPartConnectionsCancelEventArgs(
                provider, providerConnectionPoint, consumer, consumerConnectionPoint);
            OnWebPartsConnecting(ce);
            if (_allowEventCancellation && ce.Cancel) {
                return null;
            }

            Control providerControl = provider.ToControl();
            Control consumerControl = consumer.ToControl();

            WebPartConnection connection = new WebPartConnection();
            connection.ID = CreateDynamicConnectionID();
            connection.ProviderID = providerControl.ID;
            connection.ConsumerID = consumerControl.ID;
            connection.ProviderConnectionPointID = providerConnectionPoint.ID;
            connection.ConsumerConnectionPointID = consumerConnectionPoint.ID;

            if (transformer != null) {
                Internals.SetTransformer(connection, transformer);
            }

            Internals.SetIsShared(connection, Personalization.Scope == PersonalizationScope.Shared);
            Internals.SetIsStatic(connection, false);

            DynamicConnections.Add(connection);
            _hasDataChanged = true;

            OnWebPartsConnected(new WebPartConnectionsEventArgs(provider, providerConnectionPoint,
                                                                consumer, consumerConnectionPoint, connection));

            return connection;
        }

        // Returns a copy of the WebPart, with all the properties reset to their default value.
        // If the WebPart is a GenericWebPart, returns a copy of the GenericWebPart and a copy of the
        // ChildControl inside the GenericWebPart.  The ID of the new WebPart and ChildControl should
        // be set to a value obtained from CreateDynamicWebPartID.
        // Virtual because a derived WebPartManager will deserialize a WebPart from XML in this method.
        protected virtual WebPart CopyWebPart(WebPart webPart) {
            WebPart newWebPart;

            GenericWebPart genericWebPart = webPart as GenericWebPart;
            if (genericWebPart != null) {
                Control childControl = genericWebPart.ChildControl;
                VerifyType(childControl);
                Type childControlType = childControl.GetType();
                Control newChildControl = (Control)Internals.CreateObjectFromType(childControlType);
                newChildControl.ID = CreateDynamicWebPartID(childControlType);

                newWebPart = CreateWebPart(newChildControl);
            }
            else {
                VerifyType(webPart);
                newWebPart = (WebPart)Internals.CreateObjectFromType(webPart.GetType());
            }

            newWebPart.ID = CreateDynamicWebPartID(webPart.GetType());

            return newWebPart;
        }

        protected virtual TransformerTypeCollection CreateAvailableTransformers() {
            TransformerTypeCollection availableTransformers = new TransformerTypeCollection();

            WebPartsSection configSection = RuntimeConfig.GetConfig().WebParts;

            IDictionary transformers = configSection.Transformers.GetTransformerEntries();

            foreach (Type type in transformers.Values) {
                availableTransformers.Add(type);
            }

            return availableTransformers;
        }

        // Returns an array of ICollection objects.  The first is the ConsumerConnectionPoints, the
        // second is the ProviderConnectionPoints.
        private static ICollection[] CreateConnectionPoints(Type type) {
            ArrayList consumerConnectionPoints = new ArrayList();
            ArrayList providerConnectionPoints = new ArrayList();

            MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (MethodInfo method in methods) {

                // Create consumer connection points
                object[] consumerAttributes = method.GetCustomAttributes(typeof(ConnectionConsumerAttribute), true);
                // ConnectionConsumerAttribute.AllowMultiple is false
                Debug.Assert(consumerAttributes.Length == 0 || consumerAttributes.Length == 1);
                if (consumerAttributes.Length == 1) {
                    // Consumer signature: method is public, return type is void, takes one parameter
                    ParameterInfo[] parameters = method.GetParameters();
                    Type parameterType = null;
                    if (parameters.Length == 1) {
                        parameterType = parameters[0].ParameterType;
                    }

                    if (method.IsPublic && method.ReturnType == typeof(void) && parameterType != null) {
                        ConnectionConsumerAttribute attribute = consumerAttributes[0] as ConnectionConsumerAttribute;
                        String displayName = attribute.DisplayName;
                        String id = attribute.ID;
                        Type connectionPointType = attribute.ConnectionPointType;
                        bool allowsMultipleConnections = attribute.AllowsMultipleConnections;
                        ConsumerConnectionPoint connectionPoint;
                        if (connectionPointType == null) {
                            connectionPoint = new ConsumerConnectionPoint(method, parameterType, type,
                                                                          displayName, id, allowsMultipleConnections);
                        }
                        else {
                            // The ConnectionPointType is validated in the attribute property getter
                            Object[] args = new Object[] { method, parameterType, type, displayName, id, allowsMultipleConnections };
                            connectionPoint = (ConsumerConnectionPoint)Activator.CreateInstance(connectionPointType, args);
                        }
                        consumerConnectionPoints.Add(connectionPoint);
                    }
                    else {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartManager_InvalidConsumerSignature, method.Name, type.FullName));
                    }
                }

                // Create provider connection points
                object[] providerAttributes = method.GetCustomAttributes(typeof(ConnectionProviderAttribute), true);
                // ConnectionProviderAttribute.AllowMultiple is false
                Debug.Assert(providerAttributes.Length == 0 || providerAttributes.Length == 1);
                if (providerAttributes.Length == 1) {
                    // Provider signature: method is public, return type is an object, and takes no parameters
                    Type returnType = method.ReturnType;
                    if (method.IsPublic && returnType != typeof(void) && method.GetParameters().Length == 0) {
                        ConnectionProviderAttribute attribute = providerAttributes[0] as ConnectionProviderAttribute;
                        String displayName = attribute.DisplayName;
                        String id = attribute.ID;
                        Type connectionPointType = attribute.ConnectionPointType;
                        bool allowsMultipleConnections = attribute.AllowsMultipleConnections;
                        ProviderConnectionPoint connectionPoint;
                        if (connectionPointType == null) {
                            connectionPoint = new ProviderConnectionPoint(method, returnType, type,
                                                                          displayName, id, allowsMultipleConnections);
                        }
                        else {
                            // The ConnectionPointType is validated in the attribute property getter
                            Object[] args = new Object[] { method, returnType, type, displayName, id, allowsMultipleConnections };
                            connectionPoint = (ProviderConnectionPoint)Activator.CreateInstance(connectionPointType, args);
                        }
                        providerConnectionPoints.Add(connectionPoint);
                    }
                    else {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartManager_InvalidProviderSignature, method.Name, type.FullName));
                    }
                }
            }

            return new ICollection[] { new ConsumerConnectionPointCollection(consumerConnectionPoints),
                new ProviderConnectionPointCollection(providerConnectionPoints) };
        }

        protected sealed override ControlCollection CreateControlCollection() {
            return new WebPartManagerControlCollection(this);
        }

        /// <devdoc>
        /// Can be overridden by derived types, to add additional display modes.  Display modes
        /// should be added in the order they are to appear in the page menu.
        /// </devdoc>
        protected virtual WebPartDisplayModeCollection CreateDisplayModes() {
            WebPartDisplayModeCollection displayModes = new WebPartDisplayModeCollection();

            displayModes.Add(BrowseDisplayMode);
            displayModes.Add(CatalogDisplayMode);
            displayModes.Add(DesignDisplayMode);
            displayModes.Add(EditDisplayMode);
            displayModes.Add(ConnectDisplayMode);

            return displayModes;
        }

        private string CreateDisplayTitle(string title, WebPart webPart, int count) {
            string displayTitle = title;

            if (webPart.Hidden) {
                displayTitle = SR.GetString(SR.WebPart_HiddenFormatString, displayTitle);
            }

            if (webPart is ErrorWebPart) {
                displayTitle = SR.GetString(SR.WebPart_ErrorFormatString, displayTitle);
            }

            if (count != 0) {
                if (count < displayTitleSuffix.Length) {
                    displayTitle += displayTitleSuffix[count];
                }
                else {
                    displayTitle += " [" + count.ToString(CultureInfo.CurrentCulture) + "]";
                }
            }

            return displayTitle;
        }

        private IDictionary CreateDisplayTitles() {
            Hashtable displayTitles = new Hashtable();

            Hashtable titles = new Hashtable();
            foreach (WebPart part in Controls) {
                string title = part.Title;
                if (String.IsNullOrEmpty(title)) {
                    title = SR.GetString(SR.Part_Untitled);
                }

                if (part is UnauthorizedWebPart) {
                    displayTitles[part] = title;
                    continue;
                }

                ArrayList parts = (ArrayList)titles[title];
                if (parts == null) {
                    parts = new ArrayList();
                    titles[title] = parts;
                    displayTitles[part] = CreateDisplayTitle(title, part, 0);
                }
                else {
                    int count = parts.Count;
                    if (count == 1) {
                        WebPart firstPart = (WebPart)parts[0];
                        displayTitles[firstPart] = CreateDisplayTitle(title, firstPart, 1);
                    }
                    displayTitles[part] = CreateDisplayTitle(title, part, count + 1);
                }

                parts.Add(part);
            }

            return displayTitles;
        }

        protected virtual string CreateDynamicConnectionID() {
            Debug.Assert(Personalization.IsModifiable);
            // 
            int guidHash = Math.Abs(Guid.NewGuid().GetHashCode());
            return DynamicConnectionIDPrefix + guidHash.ToString(CultureInfo.InvariantCulture);
        }

        protected virtual string CreateDynamicWebPartID(Type webPartType) {
            if (webPartType == null) {
                throw new ArgumentNullException("webPartType");
            }

            Debug.Assert(Personalization.IsModifiable);

            // 

            int guidHash = Math.Abs(Guid.NewGuid().GetHashCode());
            string id = DynamicWebPartIDPrefix + guidHash.ToString(CultureInfo.InvariantCulture);

            if (Page != null && Page.Trace.IsEnabled) {
                id += webPartType.Name;
            }

            return id;
        }

        protected virtual ErrorWebPart CreateErrorWebPart(string originalID, string originalTypeName,
                                                          string originalPath, string genericWebPartID,
                                                          string errorMessage) {
            ErrorWebPart errorWebPart = new ErrorWebPart(originalID, originalTypeName, originalPath, genericWebPartID);
            errorWebPart.ErrorMessage = errorMessage;
            return errorWebPart;
        }

        /// <devdoc>
        /// </devdoc>
        protected virtual WebPartPersonalization CreatePersonalization() {
            return new WebPartPersonalization(this);
        }

        /// <devdoc>
        /// Wraps the control in a GenericWebPart, and returns the GenericWebPart.  Virtual so it can be
        /// overridden to use a derived type of GenericWebPart instead.  Needs to be public so it can
        /// be called by the page developer.
        /// </devdoc>
        public virtual GenericWebPart CreateWebPart(Control control) {
            return CreateWebPartStatic(control);
        }

        // Called by other WebParts classes to create a GenericWebPart, if they do not have
        // a reference to a WebPartManager (i.e. at design time).  This method centralizes
        // the creation of GenericWebParts.
        internal static GenericWebPart CreateWebPartStatic(Control control) {
            GenericWebPart genericWebPart = new GenericWebPart(control);
            
            // The ChildControl should be added to the GenericWebPart.Controls collection when CreateWebPart()
            // is called, instead of waiting until the GenericWebPart.Controls collection is accessed.
            // This is necessary since the caller has a direct reference to the ChildControl, and may
            // perform operations on the ChildControl that assume the ChildControl is parented.
            // (VSWhidbey 498039)
            genericWebPart.CreateChildControls();

            return genericWebPart;
        }

        public void DeleteWebPart(WebPart webPart) {
            CloseOrDeleteWebPart(webPart, /* delete */ true);
        }

        // Disconnects all connections involving the Web Part
        protected virtual void DisconnectWebPart(WebPart webPart) {
            try {
                // We cannot allow any of the WebPartsDisconnecting events to be cancelled, since we may have already
                // disconnected some connections before we hit the one that needs to be cancelled. (VSWhidbey 516012)
                _allowEventCancellation = false;
                foreach (WebPartConnection connection in Connections) {
                    if (connection.Provider == webPart || connection.Consumer == webPart) {
                        DisconnectWebParts(connection);
                    }
                }
            }
            finally {
                _allowEventCancellation = true;
            }
        }

        public virtual void DisconnectWebParts(WebPartConnection connection) {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

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

            Debug.Assert(!(StaticConnections.Contains(connection) && DynamicConnections.Contains(connection)));

            WebPart provider = connection.Provider;
            ProviderConnectionPoint providerConnectionPoint = connection.ProviderConnectionPoint;
            WebPart consumer = connection.Consumer;
            ConsumerConnectionPoint consumerConnectionPoint = connection.ConsumerConnectionPoint;

            WebPartConnectionsCancelEventArgs ce = new WebPartConnectionsCancelEventArgs(
                provider, providerConnectionPoint, consumer, consumerConnectionPoint, connection);
            OnWebPartsDisconnecting(ce);
            if (_allowEventCancellation && ce.Cancel) {
                return;
            }

            WebPartConnectionsEventArgs eventArgs = new WebPartConnectionsEventArgs(
                provider, providerConnectionPoint, consumer, consumerConnectionPoint);

            if (StaticConnections.Contains(connection)) {
                if (StaticConnections.IsReadOnly) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartManager_DisconnectTooLate));
                }
                if (Internals.ConnectionDeleted(connection)) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartManager_AlreadyDisconnected));
                }
                Internals.DeleteConnection(connection);
                _hasDataChanged = true;
                OnWebPartsDisconnected(eventArgs);
            }
            else if (DynamicConnections.Contains(connection)) {
                if (DynamicConnections.IsReadOnly) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartManager_DisconnectTooLate));
                }

                if (ShouldRemoveConnection(connection)) {
                    // Unshared dynamic connection should never be disabled
                    Debug.Assert(!Internals.ConnectionDeleted(connection));
                    DynamicConnections.Remove(connection);
                }
                else {
                    if (Internals.ConnectionDeleted(connection)) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartManager_AlreadyDisconnected));
                    }
                    Internals.DeleteConnection(connection);
                }
                _hasDataChanged = true;
                OnWebPartsDisconnected(eventArgs);
            }
            else {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_UnknownConnection), "connection");
            }
        }

        public virtual void EndWebPartConnecting() {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

            WebPart selectedWebPart = SelectedWebPart;

            if (selectedWebPart == null) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartManager_NoSelectedWebPartConnect));
            }

            WebPartCancelEventArgs ce = new WebPartCancelEventArgs(selectedWebPart);
            OnSelectedWebPartChanging(ce);

            if (_allowEventCancellation && ce.Cancel) {
                return;
            }

            SetSelectedWebPart(null);

            Internals.CallOnConnectModeChanged(selectedWebPart);

            // The EventArg should always contain the new SelectedWebPart, so it should contain null
            // when we are ending connecting.
            OnSelectedWebPartChanged(new WebPartEventArgs(null));
        }

        public virtual void EndWebPartEditing() {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

            WebPart selectedWebPart = SelectedWebPart;

            if (selectedWebPart == null) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartManager_NoSelectedWebPartEdit));
            }

            WebPartCancelEventArgs ce = new WebPartCancelEventArgs(selectedWebPart);
            OnSelectedWebPartChanging(ce);

            if (_allowEventCancellation && ce.Cancel) {
                return;
            }

            SetSelectedWebPart(null);

            Internals.CallOnEditModeChanged(selectedWebPart);

            // The EventArg should always contain the new SelectedWebPart, so it should contain null
            // when we are ending editing.
            OnSelectedWebPartChanged(new WebPartEventArgs(null));
        }

        public virtual void ExportWebPart(WebPart webPart, XmlWriter writer) {
//            Personalization.EnsureEnabled(/* ensureModifiable */ false);

            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }
            if (!Controls.Contains(webPart)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "webPart");
            }

            if (writer == null) {
                throw new ArgumentNullException("writer");
            }
            if (webPart.ExportMode == WebPartExportMode.None) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_PartNotExportable), "webPart");
            }
            bool excludeSensitive = (webPart.ExportMode == WebPartExportMode.NonSensitiveData &&
                !(Personalization.Scope == PersonalizationScope.Shared));

            // Write the root elements
            writer.WriteStartElement(ExportRootElement);
            writer.WriteStartElement(ExportPartElement);
            writer.WriteAttributeString(ExportPartNamespaceAttribute, ExportPartNamespaceValue);
            // Write metadata
            writer.WriteStartElement(ExportMetaDataElement);
            writer.WriteStartElement(ExportTypeElement);
            Control control = webPart.ToControl();
            UserControl userControl = control as UserControl;
            if (userControl != null) {
                writer.WriteAttributeString(ExportUserControlSrcAttribute, userControl.AppRelativeVirtualPath);
            }
            else {
                writer.WriteAttributeString(ExportTypeNameAttribute, WebPartUtil.SerializeType(control.GetType()));
            }
            writer.WriteEndElement(); //type
            writer.WriteElementString(ExportErrorMessageElement, webPart.ImportErrorMessage);
            writer.WriteEndElement(); //metadata
            // Write the data
            writer.WriteStartElement(ExportDataElement);
            // We get the personalization data for the current page personalization mode
            IDictionary propBag = PersonalizableAttribute.GetPersonalizablePropertyValues(webPart, PersonalizationScope.Shared, excludeSensitive);

            writer.WriteStartElement(ExportPropertiesElement);

            // Special case GenericWebPart
            GenericWebPart genericWebPart = webPart as GenericWebPart;

            if (genericWebPart != null) {

                // Export IPersonalizable user control data first
                ExportIPersonalizable(writer, control, excludeSensitive);

                IDictionary controlData = PersonalizableAttribute.GetPersonalizablePropertyValues(control,
                                                                                                  PersonalizationScope.Shared,
                                                                                                  excludeSensitive);
                ExportToWriter(controlData, writer);
                writer.WriteEndElement(); //properties
                writer.WriteStartElement(ExportGenericPartPropertiesElement);
                // Export IPersonalizable part data first
                ExportIPersonalizable(writer, webPart, excludeSensitive);
                ExportToWriter(propBag, writer);
            }
            else {
                // Export IPersonalizable part data first
                ExportIPersonalizable(writer, webPart, excludeSensitive);
                ExportToWriter(propBag, writer);
            }
            writer.WriteEndElement(); //properties or genericWebPartProperties
            writer.WriteEndElement(); //data
            writer.WriteEndElement(); //webpart
            writer.WriteEndElement(); //webparts
        }

        private void ExportIPersonalizable(XmlWriter writer, Control control, bool excludeSensitive) {
            IPersonalizable personalizableControl = control as IPersonalizable;
            if (personalizableControl != null) {
                PersonalizationDictionary personalizableData = new PersonalizationDictionary();
                personalizableControl.Save(personalizableData);
                if (personalizableData.Count > 0) {
                    writer.WriteStartElement(ExportIPersonalizableElement);
                    ExportToWriter(personalizableData, writer, /* isIPersonalizable */ true, excludeSensitive);
                    writer.WriteEndElement(); // ipersonalizable
                }
            }
        }

        private static void ExportProperty(XmlWriter writer, string name, string value, Type type,
            PersonalizationScope scope, bool isIPersonalizable) {

            writer.WriteStartElement(ExportPropertyElement);
            writer.WriteAttributeString(ExportPropertyNameAttribute, name);
            writer.WriteAttributeString(ExportPropertyTypeAttribute, GetExportName(type));
            if (isIPersonalizable) {
                writer.WriteAttributeString(ExportPropertyScopeAttribute, scope.ToString());
            }
            if (value == null) {
                writer.WriteAttributeString(ExportPropertyNullAttribute, "true");
            }
            else {
                writer.WriteString(value);
            }
            writer.WriteEndElement(); //property
        }

        private void ExportToWriter(IDictionary propBag, XmlWriter writer) {
            ExportToWriter(propBag, writer, false, false);
        }

        private void ExportToWriter(IDictionary propBag,
                                    XmlWriter writer,
                                    bool isIPersonalizable,
                                    bool excludeSensitive) {
            // We only honor excludeSensitive if isIpersonalizable is true.
            Debug.Assert((!excludeSensitive) || isIPersonalizable);

            // Work on each property in the persomalization data
            foreach(DictionaryEntry entry in propBag) {
                string name = (string)entry.Key;
                if (name == AuthorizationFilterName || name == ImportErrorMessageName) {
                    continue;
                }

                PropertyInfo pi = null;
                object val = null;
                Pair data = entry.Value as Pair;
                PersonalizationScope scope = PersonalizationScope.User;
                // We expect a pair if not exporting types
                // (which happens only for non-IPersonalizable data)
                if (isIPersonalizable == false && data != null) {
                    pi = (PropertyInfo)data.First;
                    val = data.Second;
                }
                else if (isIPersonalizable) {
                    PersonalizationEntry personalizationEntry = entry.Value as PersonalizationEntry;
                    if (personalizationEntry != null &&
                        (Personalization.Scope == PersonalizationScope.Shared ||
                        personalizationEntry.Scope == PersonalizationScope.User)) {

                        val = personalizationEntry.Value;
                        scope = personalizationEntry.Scope;
                    }
                    if (excludeSensitive && personalizationEntry.IsSensitive) {
                        continue;
                    }
                }
                // we get the type from the PropertyInfo if we have it, or from the value if it's not null, or we use object.
                Type valType = ((pi != null) ? pi.PropertyType : ((val != null) ? val.GetType() : typeof(object)));

                string exportString;
                if (ShouldExportProperty(pi, valType, val, out exportString)) {
                    ExportProperty(writer, name, exportString, valType, scope, isIPersonalizable);
                }
            }
        }

        [
        EditorBrowsable(EditorBrowsableState.Never),
        ]
        public override void Focus() {
            throw new NotSupportedException(SR.GetString(SR.NoFocusSupport, this.GetType().Name));
        }

        /// <devdoc>
        /// Returns all the web parts in a zone, excluding closed web parts.
        /// Since this is only a private method, return an IList instead of a WebPartCollection
        /// for better performance.
        /// </devdoc>
        private IList GetAllWebPartsForZone(WebPartZoneBase zone) {
            if (_partsForZone == null) {
                _partsForZone = new HybridDictionary(true /* caseInsensitive */);
                foreach (WebPart part in Controls) {
                    if (!part.IsClosed) {
                        string zoneID = Internals.GetZoneID(part);
                        Debug.Assert(!String.IsNullOrEmpty(zoneID));
                        if (!String.IsNullOrEmpty(zoneID)) {
                            SortedList partsForZone = (SortedList)_partsForZone[zoneID];
                            if (partsForZone == null) {
                                partsForZone = new SortedList(new WebPart.ZoneIndexComparer());
                                _partsForZone[zoneID] = partsForZone;
                            }
                            partsForZone.Add(part, null);
                        }
                    }
                }
            }

            SortedList parts = (SortedList)_partsForZone[zone.ID];
            if (parts == null) {
                parts = new SortedList();
            }

            return parts.GetKeyList();
        }

        private static ICollection[] GetConnectionPoints(Type type) {
            if (ConnectionPointsCache == null) {
                // I don't think there is a race condition here.  Even if multiple threads enter this block
                // at the same time, the worst thing that can happen is that the ConnectionPointsCache gets
                // replaced by a new Hashtable(), and existing entries will need to be recomputed.
                // There is no way for the ConnectionPointsCache to become null.
                ConnectionPointsCache = Hashtable.Synchronized(new Hashtable());
            }

            // DevDiv Bugs 38677: Cache by culture and type as it may vary by culture within this app
            ConnectionPointKey connectionPointKey = new ConnectionPointKey(type, CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture);

            ICollection[] connectionPoints = (ICollection[])ConnectionPointsCache[connectionPointKey];
            if (connectionPoints == null) {
                connectionPoints = CreateConnectionPoints(type);
                ConnectionPointsCache[connectionPointKey] = connectionPoints;
            }

            return connectionPoints;
        }

        internal ConsumerConnectionPoint GetConsumerConnectionPoint(WebPart webPart, string connectionPointID) {
            ConsumerConnectionPointCollection points = GetConsumerConnectionPoints(webPart);
            if (points != null && points.Count > 0) {
                return points[connectionPointID];
            }
            else {
                return null;
            }
        }

        public virtual ConsumerConnectionPointCollection GetConsumerConnectionPoints(WebPart webPart) {
            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }
            // Do not check that Controls.Contains(webPart), since this may be called on a WebPart
            // outside of a Zone.  Also, this method shouldn't really care whether the WebPart is
            // inside the WebPartManager.

            return GetConsumerConnectionPoints(webPart.ToControl().GetType());
        }

        private static ConsumerConnectionPointCollection GetConsumerConnectionPoints(Type type) {
            ICollection[] connectionPoints = GetConnectionPoints(type);
            return (ConsumerConnectionPointCollection)connectionPoints[0];
        }

        public static WebPartManager GetCurrentWebPartManager(Page page) {
            if (page == null) {
                throw new ArgumentNullException("page");
            }

            return page.Items[typeof(WebPartManager)] as WebPartManager;
        }

        // Before PreRender, return String.Empty.
        // On first call to this function after PreRender, compute DisplayTitle for all WebParts
        // and save it in a dictionary.  WebPart.DisplayTitle is nonvirtual and calls this method every time.
        // A derived WebPartManager can override this method to compute and store DisplayTitle any way it
        // sees fit.  It could compute the values sooner than PreRender.
        protected internal virtual string GetDisplayTitle(WebPart webPart) {
            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }
            if (!Controls.Contains(webPart)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "webPart");
            }

            if (!_allowCreateDisplayTitles) {
                return String.Empty;
            }

            if (_displayTitles == null) {
                _displayTitles = CreateDisplayTitles();
            }

            string displayTitle = (string)_displayTitles[webPart];
            Debug.Assert(!String.IsNullOrEmpty(displayTitle));
            return displayTitle;
        }

        private static ICollection GetEnabledConnectionPoints(ICollection connectionPoints, WebPart webPart) {
            Control control = webPart.ToControl();
            ArrayList enabledPoints = new ArrayList();
            foreach (ConnectionPoint point in connectionPoints) {
                if (point.GetEnabled(control)) {
                    enabledPoints.Add(point);
                }
            }
            return enabledPoints;
        }

        internal ConsumerConnectionPointCollection GetEnabledConsumerConnectionPoints(WebPart webPart) {
            ICollection enabledPoints = GetEnabledConnectionPoints(GetConsumerConnectionPoints(webPart), webPart);
            return new ConsumerConnectionPointCollection(enabledPoints);
        }

        internal ProviderConnectionPointCollection GetEnabledProviderConnectionPoints(WebPart webPart) {
            ICollection enabledPoints = GetEnabledConnectionPoints(GetProviderConnectionPoints(webPart), webPart);
            return new ProviderConnectionPointCollection(enabledPoints);
        }

        public string GetExportUrl(WebPart webPart) {
            string personalizationScope =
                (Personalization.Scope == PersonalizationScope.Shared) ? "&scope=shared" : String.Empty;
            string queryString = Page.Request.QueryStringText;

            return Page.Request.FilePath + "?" + Page.WebPartExportID + "=true&webPart=" +
                HttpUtility.UrlEncode(webPart.ID) +
                (!String.IsNullOrEmpty(queryString) ?
                    "&query=" + HttpUtility.UrlEncode(queryString) :
                    String.Empty) +
                personalizationScope;
        }

        private static Type GetExportType(string name) {
            switch (name) {
                case ExportTypeString:
                    return typeof(string);
                case ExportTypeInt:
                    return typeof(int);
                case ExportTypeBool:
                    return typeof(bool);
                case ExportTypeDouble:
                    return typeof(double);
                case ExportTypeSingle:
                    return typeof(Single);
                case ExportTypeDateTime:
                    return typeof(DateTime);
                case ExportTypeColor:
                    return typeof(Color);
                case ExportTypeUnit:
                    return typeof(Unit);
                case ExportTypeFontSize:
                    return typeof(FontSize);
                case ExportTypeDirection:
                    return typeof(ContentDirection);
                case ExportTypeHelpMode:
                    return typeof(WebPartHelpMode);
                case ExportTypeChromeState:
                    return typeof(PartChromeState);
                case ExportTypeChromeType:
                    return typeof(PartChromeType);
                case ExportTypeExportMode:
                    return typeof(WebPartExportMode);
                case ExportTypeObject:
                    return typeof(object);
                default:
                    return WebPartUtil.DeserializeType(name, false);
            }
        }

        private static string GetExportName(Type type) {
            if (type == typeof(string)) {
                return ExportTypeString;
            }
            else if (type == typeof(int)) {
                return ExportTypeInt;
            }
            else if (type == typeof(bool)) {
                return ExportTypeBool;
            }
            else if (type == typeof(double)) {
                return ExportTypeDouble;
            }
            else if (type == typeof(Single)) {
                return ExportTypeSingle;
            }
            else if (type == typeof(DateTime)) {
                return ExportTypeDateTime;
            }
            else if (type == typeof(Color)) {
                return ExportTypeColor;
            }
            else if (type == typeof(Unit)) {
                return ExportTypeUnit;
            }
            else if (type == typeof(FontSize)) {
                return ExportTypeFontSize;
            }
            else if (type == typeof(ContentDirection)) {
                return ExportTypeDirection;
            }
            else if (type == typeof(WebPartHelpMode)) {
                return ExportTypeHelpMode;
            }
            else if (type == typeof(PartChromeState)) {
                return ExportTypeChromeState;
            }
            else if (type == typeof(PartChromeType)) {
                return ExportTypeChromeType;
            }
            else if (type == typeof(WebPartExportMode)) {
                return ExportTypeExportMode;
            }
            else if (type == typeof(object)) {
                return ExportTypeObject;
            }
            else {
                return type.AssemblyQualifiedName;
            }
        }

        /// <devdoc>
        /// Used by the page developer to get a reference to the WebPart that contains a control
        /// placed in a WebPartZone.  Returns null if the control is not inside a WebPart.
        /// </devdoc>
        public GenericWebPart GetGenericWebPart(Control control) {
             if (control == null) {
                 throw new ArgumentNullException("control");
             }

             // PERF: First check the parent of the control, before looping through all GenericWebParts
             Control parent = control.Parent;
             GenericWebPart genericParent = parent as GenericWebPart;
             if (genericParent != null && genericParent.ChildControl == control) {
                 return genericParent;
             }
             else {
                 foreach (WebPart part in Controls) {
                     GenericWebPart genericPart = part as GenericWebPart;
                     if (genericPart != null && genericPart.ChildControl == control) {
                         return genericPart;
                     }
                 }
             }

             return null;
        }

        internal ProviderConnectionPoint GetProviderConnectionPoint(WebPart webPart, string connectionPointID) {
            ProviderConnectionPointCollection points = GetProviderConnectionPoints(webPart);
            if (points != null && points.Count > 0) {
                return points[connectionPointID];
            }
            else {
                return null;
            }
        }

        public virtual ProviderConnectionPointCollection GetProviderConnectionPoints(WebPart webPart) {
            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }
            // Do not check that Controls.Contains(webPart), since this may be called on a WebPart
            // outside of a Zone.  Also, this method shouldn't really care whether the WebPart is
            // inside the WebPartManager.

            return GetProviderConnectionPoints(webPart.ToControl().GetType());
        }

        private static ProviderConnectionPointCollection GetProviderConnectionPoints(Type type) {
            ICollection[] connectionPoints = GetConnectionPoints(type);
            return (ProviderConnectionPointCollection)connectionPoints[1];
        }

        /// <devdoc>
        /// Returns the web parts that should currently be rendered by the zone.  It is important that
        /// this method filter out any web parts that will not be rendered by the zone, otherwise
        /// the AddWebPart method will not work correctly (VSWhidbey 77719)
        /// </devdoc>
        internal WebPartCollection GetWebPartsForZone(WebPartZoneBase zone) {
            if (zone == null) {
                throw new ArgumentNullException("zone");
            }
            if (_webPartZones.Contains(zone) == false) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_MustRegister), "zone");
            }

            IList allWebPartsForZone = GetAllWebPartsForZone(zone);
            WebPartCollection webParts = new WebPartCollection();

            if (allWebPartsForZone.Count > 0) {
                foreach (WebPart part in allWebPartsForZone) {
                    if (ShouldRenderWebPartInZone(part, zone)) {
                        webParts.Add(part);
                    }
                }
            }

            return webParts;
        }

        /// <devdoc>
        /// If the WebPart is a consumer on the given connection point, returns the corresponding connection.
        /// Else, returns null.
        /// </devdoc>
        internal WebPartConnection GetConnectionForConsumer(WebPart consumer, ConsumerConnectionPoint connectionPoint) {
            ConsumerConnectionPoint actualConnectionPoint = connectionPoint;
            // 
            if (connectionPoint == null) {
                actualConnectionPoint = GetConsumerConnectionPoint(consumer, null);
            }

            // PERF: Use the StaticConnections and DynamicConnections collections separately, instead
            // of using the Connections property which is created on every call.
            foreach (WebPartConnection connection in StaticConnections) {
                if (!Internals.ConnectionDeleted(connection) && connection.Consumer == consumer) {
                    ConsumerConnectionPoint c =
                        GetConsumerConnectionPoint(consumer, connection.ConsumerConnectionPointID);
                    if (c == actualConnectionPoint) {
                        return connection;
                    }
                }
            }

            foreach (WebPartConnection connection in DynamicConnections) {
                if (!Internals.ConnectionDeleted(connection) && connection.Consumer == consumer) {
                    ConsumerConnectionPoint c =
                        GetConsumerConnectionPoint(consumer, connection.ConsumerConnectionPointID);
                    if (c == actualConnectionPoint) {
                        return connection;
                    }
                }
            }

            return null;
        }

        /// <devdoc>
        /// If the WebPart is a provider on the given connection point, returns the corresponding connection.
        /// Else, returns null.
        /// </devdoc>
        internal WebPartConnection GetConnectionForProvider(WebPart provider, ProviderConnectionPoint connectionPoint) {
            ProviderConnectionPoint actualConnectionPoint = connectionPoint;
            if (connectionPoint == null) {
                actualConnectionPoint = GetProviderConnectionPoint(provider, null);
            }

            // PERF: Use the StaticConnections and DynamicConnections collections separately, instead
            // of using the Connections property which is created on every call.
            foreach (WebPartConnection connection in StaticConnections) {
                if (!Internals.ConnectionDeleted(connection) && connection.Provider == provider) {
                    ProviderConnectionPoint c =
                        GetProviderConnectionPoint(provider, connection.ProviderConnectionPointID);
                    if (c == actualConnectionPoint) {
                        return connection;
                    }
                }
            }

            foreach (WebPartConnection connection in DynamicConnections) {
                if (!Internals.ConnectionDeleted(connection) && connection.Provider == provider) {
                    ProviderConnectionPoint c =
                        GetProviderConnectionPoint(provider, connection.ProviderConnectionPointID);
                    if (c == actualConnectionPoint) {
                        return connection;
                    }
                }
            }

            return null;
        }

        private static void ImportReadTo(XmlReader reader, string elementToFind) {
            while (reader.Name != elementToFind) {
                if (!reader.Read()) {
                    throw new XmlException();
                }
            }
        }

        private static void ImportReadTo(XmlReader reader, string elementToFindA, string elementToFindB) {
            while (reader.Name != elementToFindA && reader.Name != elementToFindB) {
                if (!reader.Read()) {
                    throw new XmlException();
                }
            }
        }

        private static void ImportSkipTo(XmlReader reader, string elementToFind) {
            while (reader.Name != elementToFind) {
                reader.Skip();
                if (reader.EOF) {
                    throw new XmlException();
                }
            }
        }

        /// <devdoc>
        /// Never throws except for null arguments. Returns an error message in the out parameter instead.
        /// [Microsoft] I investigated whether this could be refactored to share common code with
        ///           LoadDynamicWebPart(), but it seems the methods are too different.
        /// </devdoc>
        public virtual WebPart ImportWebPart(XmlReader reader, out string errorMessage) {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

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

            bool permitOnly = false;

            if (UsePermitOnly) {
                MinimalPermissionSet.PermitOnly();
                permitOnly = true;
            }
            string importErrorMessage = string.Empty;
            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    // Get to the metadata
                    reader.MoveToContent();
                    reader.ReadStartElement(ExportRootElement);
                    ImportSkipTo(reader, ExportPartElement);
                    // Check the version on the webPart element
                    string version = reader.GetAttribute(ExportPartNamespaceAttribute);
                    if (String.IsNullOrEmpty(version)) {
                        errorMessage = SR.GetString(SR.WebPart_ImportErrorNoVersion);
                        return null;
                    }
                    if (!String.Equals(version, ExportPartNamespaceValue, StringComparison.OrdinalIgnoreCase)) {
                        errorMessage = SR.GetString(SR.WebPart_ImportErrorInvalidVersion);
                        return null;
                    }
                    ImportReadTo(reader, ExportMetaDataElement);
                    reader.ReadStartElement(ExportMetaDataElement);
                    // Get the type name
                    string partTypeName = null;
                    string userControlTypeName = null;
                    ImportSkipTo(reader, ExportTypeElement);
                    partTypeName = reader.GetAttribute(ExportTypeNameAttribute);
                    userControlTypeName = reader.GetAttribute(ExportUserControlSrcAttribute);
                    // Get the error message to display if unsuccessful to load the type
                    ImportSkipTo(reader, ExportErrorMessageElement);
                    importErrorMessage = reader.ReadElementString();
                    // Get a type object from the type name
                    Type partType;
                    WebPart part = null;
                    Control childControl = null;

                    try {
                        // If we are in shared scope, we are importing a shared WebPart
                        bool isShared = (Personalization.Scope == PersonalizationScope.Shared);

                        if (!String.IsNullOrEmpty(partTypeName)) {

                            if (UsePermitOnly) {
                                CodeAccessPermission.RevertPermitOnly();
                                permitOnly = false;
                                MediumPermissionSet.PermitOnly();
                                permitOnly = true;
                            }

                            partType = WebPartUtil.DeserializeType(partTypeName, true);

                            if (UsePermitOnly) {
                                CodeAccessPermission.RevertPermitOnly();
                                permitOnly = false;
                                MinimalPermissionSet.PermitOnly();
                                permitOnly = true;
                            }

                            // First check if the type is authorized
                            if (!IsAuthorized(partType, null, null, isShared)) {
                                errorMessage = SR.GetString(SR.WebPartManager_ForbiddenType);
                                return null;
                            }
                            // If the type is not a webpart, create a generic Web Part
                            if (!partType.IsSubclassOf(typeof(WebPart))) {
                                if (!partType.IsSubclassOf(typeof(Control))) {
                                    // We only allow for Controls (VSWhidbey 428511)
                                    errorMessage = SR.GetString(SR.WebPartManager_TypeMustDeriveFromControl);
                                    return null;
                                }
                                // Create an instance of the object
                                childControl = (Control)(Internals.CreateObjectFromType(partType));
                                childControl.ID = CreateDynamicWebPartID(partType);
                                part = CreateWebPart(childControl);
                            }
                            else {
                                // Create an instance of the object
                                part = (WebPart)(Internals.CreateObjectFromType(partType));
                            }
                        }
                        else {
                            // Instantiate a user control in a generic web part

                            // Check if the path is authorized
                            if (!IsAuthorized(typeof(UserControl), userControlTypeName, null, isShared)) {
                                errorMessage = SR.GetString(SR.WebPartManager_ForbiddenType);
                                return null;
                            }

                            if (UsePermitOnly) {
                                CodeAccessPermission.RevertPermitOnly();
                                permitOnly = false;
                            }
                            childControl = Page.LoadControl(userControlTypeName);
                            partType = childControl.GetType();
                            if (UsePermitOnly) {
                                MinimalPermissionSet.PermitOnly();
                                permitOnly = true;
                            }
                            childControl.ID = CreateDynamicWebPartID(partType);
                            part = CreateWebPart(childControl);
                        }
                    }
                    catch {
                        if (!String.IsNullOrEmpty(importErrorMessage)) {
                            errorMessage = importErrorMessage;
                        }
                        else {
                            errorMessage = SR.GetString(SR.WebPartManager_ErrorLoadingWebPartType);
                        }
                        return null;
                    }

                    // Set default error message for all subsequent errors
                    if (String.IsNullOrEmpty(importErrorMessage)) {
                        importErrorMessage = SR.GetString(SR.WebPart_DefaultImportErrorMessage);
                    }
                    // Get to the data
                    ImportSkipTo(reader, ExportDataElement);
                    reader.ReadStartElement(ExportDataElement);
                    ImportSkipTo(reader, ExportPropertiesElement);
                    if (!reader.IsEmptyElement) {
                        reader.ReadStartElement(ExportPropertiesElement);
                        // Special-case IPersonalizable controls
                        // ImportFromReader will set the right permission set when appropriate, reverting before we call
                        if (UsePermitOnly) {
                            CodeAccessPermission.RevertPermitOnly();
                            permitOnly = false;
                        }
                        ImportIPersonalizable(reader, (childControl != null ? childControl : part));
                        if (UsePermitOnly) {
                            MinimalPermissionSet.PermitOnly();
                            permitOnly = true;
                        }
                    }
                    // Set property values from XML description
                    IDictionary personalizableProperties;
                    if (childControl != null) {
                        if (!reader.IsEmptyElement) {
                            // Get the collection of personalizable properties for the child control
                            personalizableProperties = PersonalizableAttribute.GetPersonalizablePropertyEntries(partType);

                            // Copied from below.  We must also execute this code when parsing the ChildControl
                            // IPersonalizable and Personalizable properties.
                            while (reader.Name != ExportPropertyElement) {
                                reader.Skip();
                                if (reader.EOF) {
                                    errorMessage = null;
                                    return part;
                                }
                            }                            
                            
                            // ImportFromReader will set the right permission set when appropriate, reverting before we call
                            if (UsePermitOnly) {
                                CodeAccessPermission.RevertPermitOnly();
                                permitOnly = false;
                            }
                            ImportFromReader(personalizableProperties, childControl, reader);
                            if (UsePermitOnly) {
                                MinimalPermissionSet.PermitOnly();
                                permitOnly = true;
                            }
                        }
                        // And then for the generic WebPart
                        ImportSkipTo(reader, ExportGenericPartPropertiesElement);
                        reader.ReadStartElement(ExportGenericPartPropertiesElement);
                        // ImportFromReader will set the right permission set when appropriate, reverting before we call
                        if (UsePermitOnly) {
                            CodeAccessPermission.RevertPermitOnly();
                            permitOnly = false;
                        }
                        ImportIPersonalizable(reader, part);
                        if (UsePermitOnly) {
                            MinimalPermissionSet.PermitOnly();
                            permitOnly = true;
                        }
                        personalizableProperties = PersonalizableAttribute.GetPersonalizablePropertyEntries(part.GetType());
                    }
                    else {
                        // Get the collection of personalizable properties
                        personalizableProperties = PersonalizableAttribute.GetPersonalizablePropertyEntries(partType);
                    }

                    while (reader.Name != ExportPropertyElement) {
                        reader.Skip();
                        if (reader.EOF) {
                            errorMessage = null;
                            return part;
                        }
                    }

                    // ImportFromReader will set the right permission set when appropriate, reverting before we call
                    if (UsePermitOnly) {
                        CodeAccessPermission.RevertPermitOnly();
                        permitOnly = false;
                    }
                    ImportFromReader(personalizableProperties, part, reader);
                    if (UsePermitOnly) {
                        MinimalPermissionSet.PermitOnly();
                        permitOnly = true;
                    }
                    errorMessage = null;
                    // Return imported part
                    return part;
                }
                catch (XmlException) {
                    errorMessage = SR.GetString(SR.WebPartManager_ImportInvalidFormat);
                    return null;
                }
                catch (Exception e) {
                    if ((Context != null) && (Context.IsCustomErrorEnabled)) {
                        errorMessage = (importErrorMessage.Length != 0) ?
                            importErrorMessage :
                            SR.GetString(SR.WebPart_DefaultImportErrorMessage);
                    }
                    else {
                        errorMessage = e.Message;
                    }
                    return null;
                }
                finally {
                    if (permitOnly) {
                        // revert if you're not just exiting the stack frame anyway
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
            }
            catch {
                throw;
            }
        }

        private void ImportIPersonalizable(XmlReader reader, Control control) {
            if (control is IPersonalizable) {
                // The control may implement IPersonalizable, but the .WebPart file may not contain
                // an "ipersonalizable" element.  The WebPart may have returned no data from its
                // IPersonalizable.Save() method, or the WebPart may have been recently changed to
                // implement IPersonalizable.  This are valid scenarios, so we should not require
                // the XML to contain the "ipersonalizable" element. (VSWhidbey 499016)

                // Read to the next element that is either "property" or "ipersonalizable".
                ImportReadTo(reader, ExportIPersonalizableElement, ExportPropertyElement);

                // If the next element is "ipersonalizable", then we import the IPersonalizable data.
                // Else, we do nothing, and the current "property" element will be imported as a standard
                // personalizable property.
                if (reader.Name == ExportIPersonalizableElement) {
                    // Create a dictionary from the XML description
                    reader.ReadStartElement(ExportIPersonalizableElement);
                    ImportFromReader(null, control, reader);
                }
            }
        }

        private void ImportFromReader(IDictionary personalizableProperties,
                                      Control target,
                                      XmlReader reader) {

            Debug.Assert(target != null);

            ImportReadTo(reader, ExportPropertyElement);

            bool permitOnly = false;

            if (UsePermitOnly) {
                MinimalPermissionSet.PermitOnly();
                permitOnly = true;
            }

            try {
                try {
                    IDictionary properties;
                    if (personalizableProperties != null) {
                        properties = new HybridDictionary();
                    }
                    else {
                        properties = new PersonalizationDictionary();
                    }
                    // Set properties from the xml document
                    while (reader.Name == ExportPropertyElement) {
                        // Get the name of the property
                        string propertyName = reader.GetAttribute(ExportPropertyNameAttribute);
                        string typeName = reader.GetAttribute(ExportPropertyTypeAttribute);
                        string scope = reader.GetAttribute(ExportPropertyScopeAttribute);
                        bool isNull = String.Equals(
                            reader.GetAttribute(ExportPropertyNullAttribute),
                            "true",
                            StringComparison.OrdinalIgnoreCase);

                        // Do not import Zone information or AuthorizationFilter or custom data
                        if (propertyName == AuthorizationFilterName ||
                             propertyName == ZoneIDName ||
                             propertyName == ZoneIndexName) {

                            reader.ReadElementString();
                            if (!reader.Read()) {
                                throw new XmlException();
                            }
                        }
                        else {
                            string valString = reader.ReadElementString();
                            object val = null;
                            bool valueComputed = false;
                            PropertyInfo pi = null;
                            if (personalizableProperties != null) {
                                // Get the relevant personalizable property on the target (no need to check the property is personalizable)
                                PersonalizablePropertyEntry entry = (PersonalizablePropertyEntry)(personalizableProperties[propertyName]);
                                if (entry != null) {
                                    pi = entry.PropertyInfo;
                                    Debug.Assert(pi != null);
                                    // If the property is a url, validate protocol (VSWhidbey 290418)
                                    UrlPropertyAttribute urlAttr = Attribute.GetCustomAttribute(pi, typeof(UrlPropertyAttribute), true) as UrlPropertyAttribute;
                                    if (urlAttr != null && CrossSiteScriptingValidation.IsDangerousUrl(valString)) {
                                        throw new InvalidDataException(SR.GetString(SR.WebPart_BadUrl, valString));
                                    }
                                }
                            }

                            Type type = null;
                            if (!String.IsNullOrEmpty(typeName)) {
                                if (UsePermitOnly) {
                                    // Need medium trust to call BuildManager.GetType()
                                    CodeAccessPermission.RevertPermitOnly();
                                    permitOnly = false;
                                    MediumPermissionSet.PermitOnly();
                                    permitOnly = true;
                                }
                                type = GetExportType(typeName);

                                if (UsePermitOnly) {
                                    CodeAccessPermission.RevertPermitOnly();
                                    permitOnly = false;
                                    MinimalPermissionSet.PermitOnly();
                                    permitOnly = true;
                                }
                            }

                            if ((pi != null) && ((pi.PropertyType == type) || (type == null))) {
                                // Look at the target property
                                // See if the property itself has a type converter associated with it
                                TypeConverterAttribute attr = Attribute.GetCustomAttribute(pi, typeof(TypeConverterAttribute), true) as TypeConverterAttribute;
                                if (attr != null) {
                                    if (UsePermitOnly) {
                                        // Need medium trust to call BuildManager.GetType()
                                        CodeAccessPermission.RevertPermitOnly();
                                        permitOnly = false;
                                        MediumPermissionSet.PermitOnly();
                                        permitOnly = true;
                                    }

                                    Type converterType = WebPartUtil.DeserializeType(attr.ConverterTypeName, false);

                                    if (UsePermitOnly) {
                                        CodeAccessPermission.RevertPermitOnly();
                                        permitOnly = false;
                                        MinimalPermissionSet.PermitOnly();
                                        permitOnly = true;
                                    }

                                    // SECURITY: Check that the type is a subclass of TypeConverter before instantiating.
                                    if (converterType != null && converterType.IsSubclassOf(typeof(TypeConverter))) {
                                        TypeConverter converter = (TypeConverter)(Internals.CreateObjectFromType(converterType));
                                        if (Util.CanConvertToFrom(converter, typeof(string))) {
                                            if (!isNull) {
                                                val = converter.ConvertFromInvariantString(valString);
                                            }
                                            valueComputed = true;
                                        }
                                    }
                                }
                                // Then, look at the converters on the property type
                                if (!valueComputed) {
                                    // Use the type converter associated with the type itself
                                    TypeConverter converter = TypeDescriptor.GetConverter(pi.PropertyType);
                                    if (Util.CanConvertToFrom(converter, typeof(string))) {
                                        if (!isNull) {
                                            val = converter.ConvertFromInvariantString(valString);
                                        }
                                        valueComputed = true;
                                        // Not importing anything else for security reasons
                                    }
                                }
                            }
                            // finally, use the XML-specified type
                            if (!valueComputed && (type != null)) {
                                // Look at the XML-declared type
                                if (type == typeof(string)) {
                                    if (!isNull) {
                                        val = valString;
                                    }
                                    valueComputed = true;
                                }
                                else {
                                    TypeConverter typeConverter = TypeDescriptor.GetConverter(type);
                                    if (Util.CanConvertToFrom(typeConverter, typeof(string))) {
                                        if (!isNull) {
                                            val = typeConverter.ConvertFromInvariantString(valString);
                                        }
                                        valueComputed = true;
                                    }
                                }
                            }

                            // Always want to import a null IPersonalizable value, since we will never have a type
                            // converter for the value.  However, we should not import a null Personalizable value
                            // unless the PropertyInfo had a type converter, since the property may be a value type
                            // that cannot accept null as a value. (VSWhidbey 537895)
                            if (isNull && personalizableProperties == null) {
                                valueComputed = true;
                            }

                            // Now we should have a value (val)
                            if (valueComputed) {
                                if (personalizableProperties != null) {
                                    properties.Add(propertyName, val);
                                }
                                else {
                                    // Determine scope:
                                    PersonalizationScope personalizationScope =
                                        String.Equals(scope, PersonalizationScope.Shared.ToString(), StringComparison.OrdinalIgnoreCase) ?
                                        PersonalizationScope.Shared : PersonalizationScope.User;
                                    properties.Add(propertyName, new PersonalizationEntry(val, personalizationScope));
                                }
                            }
                            else {
                                throw new HttpException(SR.GetString(SR.WebPartManager_ImportInvalidData, propertyName));
                            }
                        }
                        while (reader.Name != ExportPropertyElement) {
                            if (reader.EOF ||
                                (reader.Name == ExportGenericPartPropertiesElement) ||
                                (reader.Name == ExportPropertiesElement) ||
                                ((reader.Name == ExportIPersonalizableElement) && (reader.NodeType == XmlNodeType.EndElement))) {
                                goto EndOfData;
                            }
                            reader.Skip();
                        }
                    }
                    EndOfData:
                    if (personalizableProperties != null) {
                        IDictionary unused = BlobPersonalizationState.SetPersonalizedProperties(target, properties);
                        if ((unused != null) && (unused.Count > 0)) {
                            IVersioningPersonalizable versioningTarget = target as IVersioningPersonalizable;
                            if (versioningTarget != null) {
                                versioningTarget.Load(unused);
                            }
                        }
                    }
                    else {
                        Debug.Assert(target is IPersonalizable);
                        ((IPersonalizable)target).Load((PersonalizationDictionary)properties);
                    }
                }
                finally {
                    if (permitOnly) {
                        // revert if you're not just exiting the stack frame anyway
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
            }
            catch {
                throw;
            }
        }

        public virtual bool IsAuthorized(Type type, string path, string authorizationFilter, bool isShared) {
            if (type == null) {
                throw new ArgumentNullException("type");
            }

            if (type == typeof(UserControl)) {
                if (String.IsNullOrEmpty(path)) {
                    throw new ArgumentException(SR.GetString(SR.WebPartManager_PathCannotBeEmpty));
                }
            }
            else {
                if (!String.IsNullOrEmpty(path)) {
                    throw new ArgumentException(SR.GetString(SR.WebPartManager_PathMustBeEmpty, path));
                }
            }

            WebPartAuthorizationEventArgs auth = new WebPartAuthorizationEventArgs(type, path, authorizationFilter, isShared);
            OnAuthorizeWebPart(auth);
            return auth.IsAuthorized;
        }

        public bool IsAuthorized(WebPart webPart) {
            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }

            // Do not check that Controls.Contains(webPart), since this will be called on a WebPart
            // before it is added to the Controls collection.

            // Calculate authorizationFilter from property value and personalization data
            string authorizationFilter = webPart.AuthorizationFilter;

            // webPart.ID will be null for imported WebParts.  Also, a user may want to call
            // this method on a WebPart before it has an ID.
            string webPartID = webPart.ID;
            if (!String.IsNullOrEmpty(webPartID) && Personalization.IsEnabled) {
                string personalizedAuthorizationFilter = Personalization.GetAuthorizationFilter(webPart.ID);
                if (personalizedAuthorizationFilter != null) {
                    authorizationFilter = personalizedAuthorizationFilter;
                }
            }

            GenericWebPart genericWebPart = webPart as GenericWebPart;
            if (genericWebPart != null) {
                Type childType = null;
                string childPath = null;

                Control childControl = genericWebPart.ChildControl;
                UserControl childUserControl = childControl as UserControl;
                if (childUserControl != null) {
                    childType = typeof(UserControl);
                    childPath = childUserControl.AppRelativeVirtualPath;
                }
                else {
                    childType = childControl.GetType();
                }

                // Only authorize the type/path of the child control
                // Don't need to authorize the GenericWebPart as well
                return IsAuthorized(childType, childPath, authorizationFilter, webPart.IsShared);
            }
            else {
                return IsAuthorized(webPart.GetType(), null, authorizationFilter, webPart.IsShared);
            }
        }

        internal bool IsConsumerConnected(WebPart consumer, ConsumerConnectionPoint connectionPoint) {
            return (GetConnectionForConsumer(consumer, connectionPoint) != null);
        }

        internal bool IsProviderConnected(WebPart provider, ProviderConnectionPoint connectionPoint) {
            return (GetConnectionForProvider(provider, connectionPoint) != null);
        }

        /// <devdoc>
        /// Loads the control state for those properties that should persist across postbacks
        /// even when EnableViewState=false.
        /// </devdoc>
        protected internal override void LoadControlState(object savedState) {
            if (savedState == null) {
                base.LoadControlState(null);
            }
            else {
                object[] myState = (object[])savedState;
                if (myState.Length != controlStateArrayLength) {
                    throw new ArgumentException(SR.GetString(SR.Invalid_ControlState));
                }

                base.LoadControlState(myState[baseIndex]);

                // 

                if (myState[selectedWebPartIndex] != null) {
                    // All dynamic parts must be loaded before this point, in case a dynamic part is the
                    // SelectedWebPart.
                    WebPart selectedWebPart = WebParts[(string)myState[selectedWebPartIndex]];
                    if (selectedWebPart == null || selectedWebPart.IsClosed) {
                        // The SelectedWebPart was either closed or deleted between requests.
                        // Raise the changed event, since the SelectedWebPart was not null on the previous request.
                        SetSelectedWebPart(null);
                        OnSelectedWebPartChanged(new WebPartEventArgs(null));
                    }
                    else {
                        SetSelectedWebPart(selectedWebPart);
                    }
                }
                if (myState[displayModeIndex] != null) {
                    string modeName = (string)myState[displayModeIndex];

                    WebPartDisplayMode restoredDisplayMode = SupportedDisplayModes[modeName];
                    if (!restoredDisplayMode.IsEnabled(this)) {
                        // Throw
                    }

                    if (restoredDisplayMode == null) {
                        _displayMode = BrowseDisplayMode;
                        OnDisplayModeChanged(new WebPartDisplayModeEventArgs(null));
                    }
                    else {
                        _displayMode = restoredDisplayMode;
                    }
                }
            }
        }

        protected virtual void LoadCustomPersonalizationState(PersonalizationDictionary state) {
            // The state must be loaded after the Static Connections and WebParts have been added
            // to the WebPartManager (after the WebPartZone's and ProxyWebPartManager's Init methods)
            _personalizationState = state;
        }

        private void LoadDynamicConnections(PersonalizationEntry entry) {
            if (entry != null) {
                object[] dynamicConnectionState = (object[])entry.Value;
                if (dynamicConnectionState != null) {
                    Debug.Assert(dynamicConnectionState.Length % 7 == 0);
                    for (int i = 0; i < dynamicConnectionState.Length; i += 7) {
                        string ID = (string)dynamicConnectionState[i];
                        string consumerID = (string)dynamicConnectionState[i + 1];
                        string consumerConnectionPointID = (string)dynamicConnectionState[i + 2];
                        string providerID = (string)dynamicConnectionState[i + 3];
                        string providerConnectionPointID = (string)dynamicConnectionState[i + 4];

                        // Add a new connection to the collection
                        WebPartConnection connection = new WebPartConnection();
                        connection.ID = ID;
                        connection.ConsumerID = consumerID;
                        connection.ConsumerConnectionPointID = consumerConnectionPointID;
                        connection.ProviderID = providerID;
                        connection.ProviderConnectionPointID = providerConnectionPointID;
                        Internals.SetIsShared(connection, (entry.Scope == PersonalizationScope.Shared));
                        Internals.SetIsStatic(connection, false);

                        Type type = dynamicConnectionState[i + 5] as Type;
                        if (type != null) {
                            // SECURITY: Only instantiate type if it is a subclass of WebPartTransformer
                            if (type.IsSubclassOf(typeof(WebPartTransformer))) {
                                object configuration = dynamicConnectionState[i + 6];
                                WebPartTransformer transformer = (WebPartTransformer)Internals.CreateObjectFromType(type);
                                Internals.LoadConfigurationState(transformer, configuration);
                                Internals.SetTransformer(connection, transformer);
                            }
                            else {
                                throw new InvalidOperationException(SR.GetString(SR.WebPartTransformerAttribute_NotTransformer, type.Name));
                            }
                        }

                        DynamicConnections.Add(connection);
                    }
                }
            }
        }

        private void LoadDynamicWebPart(string id, string typeName, string path, string genericWebPartID, bool isShared) {
            WebPart dynamicWebPart = null;
            Type type = WebPartUtil.DeserializeType(typeName, false);
            if (type == null) {
                string errorMessage;
                if (Context != null && Context.IsCustomErrorEnabled) {
                    errorMessage = SR.GetString(SR.WebPartManager_ErrorLoadingWebPartType);
                }
                else {
                    errorMessage = SR.GetString(SR.Invalid_type, typeName);
                }
                dynamicWebPart = CreateErrorWebPart(id, typeName, path, genericWebPartID, errorMessage);
            }
            else if (type.IsSubclassOf(typeof(WebPart))) {
                string authorizationFilter = Personalization.GetAuthorizationFilter(id);
                if (IsAuthorized(type, null, authorizationFilter, isShared)) {
                    try {
                        dynamicWebPart = (WebPart)Internals.CreateObjectFromType(type);
                        dynamicWebPart.ID = id;
                    }
                    catch {
                        // If custom errors are enabled, we do not want to render the type name to the browser.
                        // (VSWhidbey 381646)
                        string errorMessage;
                        if (Context != null && Context.IsCustomErrorEnabled) {
                            errorMessage = SR.GetString(SR.WebPartManager_CantCreateInstance);
                        }
                        else {
                            errorMessage = SR.GetString(SR.WebPartManager_CantCreateInstanceWithType, typeName);
                        }
                        dynamicWebPart = CreateErrorWebPart(id, typeName, path, genericWebPartID, errorMessage);
                    }
                }
                else {
                    dynamicWebPart = new UnauthorizedWebPart(id, typeName, path, genericWebPartID);
                }
            }
            else if (type.IsSubclassOf(typeof(Control))) {
                string authorizationFilter = Personalization.GetAuthorizationFilter(genericWebPartID);
                if (IsAuthorized(type, path, authorizationFilter, isShared)) {
                    Control childControl = null;
                    try {
                        if (!String.IsNullOrEmpty(path)) {
                            Debug.Assert(type == typeof(UserControl));
                            childControl = Page.LoadControl(path);
                        }
                        else {
                            childControl = (Control)Internals.CreateObjectFromType(type);
                        }
                        childControl.ID = id;

                        dynamicWebPart = CreateWebPart(childControl);
                        dynamicWebPart.ID = genericWebPartID;
                    }
                    catch {
                        string errorMessage;
                        if (childControl == null && String.IsNullOrEmpty(path)) {
                            if (Context != null && Context.IsCustomErrorEnabled) {
                                errorMessage = SR.GetString(SR.WebPartManager_CantCreateInstance);
                            }
                            else {
                                errorMessage = SR.GetString(SR.WebPartManager_CantCreateInstanceWithType, typeName);
                            }
                        }
                        else if (childControl == null) {
                            if (Context != null && Context.IsCustomErrorEnabled) {
                                errorMessage = SR.GetString(SR.WebPartManager_InvalidPath);
                            }
                            else {
                                errorMessage = SR.GetString(SR.WebPartManager_InvalidPathWithPath, path);
                            }
                        }
                        else {
                            errorMessage = SR.GetString(SR.WebPartManager_CantCreateGeneric);
                        }
                        dynamicWebPart = CreateErrorWebPart(id, typeName, path, genericWebPartID, errorMessage);
                    }
                }
                else {
                    dynamicWebPart = new UnauthorizedWebPart(id, typeName, path, genericWebPartID);
                }
            }
            else {
                // Type is not a subclass of Control.  For security, do not even instantiate
                // the type (VSWhidbey 428511).
                string errorMessage;
                if (Context != null && Context.IsCustomErrorEnabled) {
                    errorMessage = SR.GetString(SR.WebPartManager_TypeMustDeriveFromControl);
                }
                else {
                    errorMessage = SR.GetString(SR.WebPartManager_TypeMustDeriveFromControlWithType, typeName);
                }
                dynamicWebPart = CreateErrorWebPart(id, typeName, path, genericWebPartID, errorMessage);
            }

            Debug.Assert(dynamicWebPart != null);
            Internals.SetIsStatic(dynamicWebPart, false);
            Internals.SetIsShared(dynamicWebPart, isShared);
            Internals.AddWebPart(dynamicWebPart);
        }

        private void LoadDynamicWebParts(PersonalizationEntry entry) {
            if (entry != null) {
                object[] dynamicWebPartState = (object[])entry.Value;
                if (dynamicWebPartState != null) {
                    Debug.Assert(dynamicWebPartState.Length % 4 == 0);
                    bool isShared = (entry.Scope == PersonalizationScope.Shared);

                    // 
                    for (int i = 0; i < dynamicWebPartState.Length; i += 4) {
                        string id = (string)dynamicWebPartState[i];
                        string typeName = (string)dynamicWebPartState[i + 1];
                        string path = (string)dynamicWebPartState[i + 2];
                        string genericWebPartID = (string)dynamicWebPartState[i + 3];

                        LoadDynamicWebPart(id, typeName, path, genericWebPartID, isShared);
                    }
                }
            }
        }

        private void LoadDeletedConnectionState(PersonalizationEntry entry) {
            if (entry != null) {
                string[] deletedConnections = (string[])entry.Value;
                if (deletedConnections != null) {
                    for (int i=0; i < deletedConnections.Length; i++) {
                        string idToDelete = deletedConnections[i];
                        WebPartConnection connectionToDelete = null;

                        foreach (WebPartConnection connection in StaticConnections) {
                            if (String.Equals(connection.ID, idToDelete, StringComparison.OrdinalIgnoreCase)) {
                                connectionToDelete = connection;
                                break;
                            }
                        }
                        if (connectionToDelete == null) {
                            foreach (WebPartConnection connection in DynamicConnections) {
                                if (String.Equals(connection.ID, idToDelete, StringComparison.OrdinalIgnoreCase)) {
                                    connectionToDelete = connection;
                                    break;
                                }
                            }
                        }

                        if (connectionToDelete != null) {
                            // Only shared connections can be deleted
                            Debug.Assert(connectionToDelete.IsShared);

                            // In shared scope, only static connections should be deleted
                            // In user scope, static and dynamic connections can be deleted
                            Debug.Assert(connectionToDelete.IsStatic || entry.Scope == PersonalizationScope.User);

                            Internals.DeleteConnection(connectionToDelete);
                        }
                        else {
                            // Some of the personalization data is invalid, so we should mark ourselves
                            // as dirty so the data will be re-saved, and the invalid data will be removed.
                            _hasDataChanged = true;
                        }
                    }
                }
            }
        }

        /// <devdoc>
        /// Sets the ZoneID, ZoneIndex, and IsClosed properties on the WebParts.  The state
        /// was loaded from personalization.
        /// </devdoc>
        private void LoadWebPartState(PersonalizationEntry entry) {
            if (entry != null) {
                object[] webPartState = (object[])entry.Value;
                if (webPartState != null) {
                    Debug.Assert(webPartState.Length % 4 == 0);
                    for (int i=0; i < webPartState.Length; i += 4) {
                        string id = (string)webPartState[i];
                        string zoneID = (string)webPartState[i + 1];
                        int zoneIndex = (int)webPartState[i + 2];
                        bool isClosed = (bool)webPartState[i + 3];

                        WebPart part = (WebPart)FindControl(id);
                        if (part != null) {
                            Internals.SetZoneID(part, zoneID);
                            Internals.SetZoneIndex(part, zoneIndex);
                            // 

                            Internals.SetIsClosed(part, isClosed);
                        }
                        else {
                            // Some of the personalization data is invalid, so we should mark ourselves
                            // as dirty so the data will be re-saved, and the invalid data will be removed.
                            _hasDataChanged = true;
                        }
                    }
                }
            }
        }

        /// <devdoc>
        /// </devdoc>
        public virtual void MoveWebPart(WebPart webPart, WebPartZoneBase zone, int zoneIndex) {
            Personalization.EnsureEnabled(/* ensureModifiable */ true);

            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }
            if (!Controls.Contains(webPart)) {
                throw new ArgumentException(SR.GetString(SR.UnknownWebPart), "webPart");
            }
            if (zone == null) {
                throw new ArgumentNullException("zone");
            }
            if (_webPartZones.Contains(zone) == false) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_MustRegister), "zone");
            }
            if (zoneIndex < 0) {
                throw new ArgumentOutOfRangeException("zoneIndex");
            }
            if (webPart.Zone == null || webPart.IsClosed) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_MustBeInZone), "webPart");
            }

            // Return immediately if moving part to its current location
            if ((webPart.Zone == zone) && (webPart.ZoneIndex == zoneIndex)) {
                return;
            }

            WebPartMovingEventArgs e = new WebPartMovingEventArgs(webPart, zone, zoneIndex);
            OnWebPartMoving(e);
            if (_allowEventCancellation && e.Cancel) {
                return;
            }

            RemoveWebPartFromZone(webPart);
            AddWebPartToZone(webPart, zone, zoneIndex);

            // Raise event at very end of Move method
            OnWebPartMoved(new WebPartEventArgs(webPart));

#if DEBUG
            CheckPartZoneIndexes(webPart.Zone);
            CheckPartZoneIndexes(zone);
#endif
        }

        protected virtual void OnAuthorizeWebPart(WebPartAuthorizationEventArgs e) {
            WebPartAuthorizationEventHandler handler = (WebPartAuthorizationEventHandler)Events[AuthorizeWebPartEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnConnectionsActivated(EventArgs e) {
            EventHandler handler = (EventHandler)Events[ConnectionsActivatedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnConnectionsActivating(EventArgs e) {
            EventHandler handler = (EventHandler)Events[ConnectionsActivatingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnDisplayModeChanged(WebPartDisplayModeEventArgs e) {
            WebPartDisplayModeEventHandler handler = (WebPartDisplayModeEventHandler)Events[DisplayModeChangedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnDisplayModeChanging(WebPartDisplayModeCancelEventArgs e) {
            WebPartDisplayModeCancelEventHandler handler = (WebPartDisplayModeCancelEventHandler)Events[DisplayModeChangingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        /// <devdoc>
        /// </devdoc>
        protected internal override void OnInit(EventArgs e) {
            base.OnInit(e);

            if (!DesignMode) {
                Page page = Page;
                if (page != null) {
                    WebPartManager existingInstance = (WebPartManager)page.Items[typeof(WebPartManager)];

                    if (existingInstance != null) {
                        Debug.Assert(existingInstance != this);
                        throw new InvalidOperationException(SR.GetString(SR.WebPartManager_OnlyOneInstance));
                    }

                    page.Items[typeof(WebPartManager)] = this;

                    page.InitComplete += new EventHandler(this.OnPageInitComplete);
                    page.LoadComplete += new EventHandler(this.OnPageLoadComplete);
                    page.SaveStateComplete += new EventHandler(this.OnPageSaveStateComplete);
                    page.RegisterRequiresControlState(this);

                    Personalization.LoadInternal();
                }
            }
        }

        /// <devdoc>
        /// </devdoc>
        protected internal override void OnUnload(EventArgs e) {
            base.OnUnload(e);

            if (!DesignMode) {
                Page page = Page;

                Debug.Assert(page != null);
                if (page != null) {
                    page.Items.Remove(typeof(WebPartManager));
                }
            }
        }

        private void OnPageInitComplete(object sender, EventArgs e) {
            if (_personalizationState != null) {
                // These must be loaded after the Static Connections have been added to the WebPartManager
                // (after the ProxyWebPartManager's Init methods)
                LoadDynamicConnections(_personalizationState["DynamicConnectionsShared"]);
                LoadDynamicConnections(_personalizationState["DynamicConnectionsUser"]);
                LoadDeletedConnectionState(_personalizationState["DeletedConnectionsShared"]);
                LoadDeletedConnectionState(_personalizationState["DeletedConnectionsUser"]);

                // These must be loaded after the Static WebParts have been added to the WebPartManager
                // (after the WebPartZone's Init methods)
                LoadDynamicWebParts(_personalizationState["DynamicWebPartsShared"]);
                LoadDynamicWebParts(_personalizationState["DynamicWebPartsUser"]);
                LoadWebPartState(_personalizationState["WebPartStateShared"]);
                LoadWebPartState(_personalizationState["WebPartStateUser"]);
            }

            _pageInitComplete = true;
        }

        private void OnPageLoadComplete(object sender, EventArgs e) {
            // VSWhidbey 77708
            CloseOrphanedParts();

            _allowCreateDisplayTitles = true;

            // Raise events outside of ActivateConnections() method, since the method is virtual
            OnConnectionsActivating(EventArgs.Empty);
            // Activate connections in Page.LoadComplete instead of WebPartManager.PreRender.
            // Additional connection types can be activated here, so this improves our compatibility. (VSWhidbey 266995)
            ActivateConnections();
            OnConnectionsActivated(EventArgs.Empty);
        }

        private void OnPageSaveStateComplete(object sender, EventArgs e) {
            // NOTE: Ideally this would be done by overriding SaveViewState in
            //       WebPartManager and WebPart to be symmetric with Personalization
            //       loading which happens in TrackViewState.
            //       However SaveViewState is not called when view state is disabled. Also,
            //       we don't want to have everything register for the SaveStateComplete event,
            //       because that creates more management issues for the event handler list.
            //       We don't want to change how the Apply works either, because we'd have
            //       to set up listeners for the Init event on every webpart.
            Personalization.ExtractPersonalizationState();
            foreach (WebPart webPart in Controls) {
                Personalization.ExtractPersonalizationState(webPart);
            }

            Personalization.SaveInternal();
        }

        protected internal override void OnPreRender(EventArgs e) {
            base.OnPreRender(e);

            if (Page != null) {
                Page.ClientScript.RegisterStartupScript(
                    this,
                    typeof(WebPartManager),
                    ExportSensitiveDataWarningDeclaration,
                    "var __wpmExportWarning='" + Util.QuoteJScriptString(ExportSensitiveDataWarning) + "';",
                    true);

                Page.ClientScript.RegisterStartupScript(
                    this,
                    typeof(WebPartManager),
                    CloseProviderWarningDeclaration,
                    "var __wpmCloseProviderWarning='" + Util.QuoteJScriptString(CloseProviderWarning) + "';",
                    true);

                Page.ClientScript.RegisterStartupScript(
                    this,
                    typeof(WebPartManager),
                    DeleteWarningDeclaration,
                    "var __wpmDeleteWarning='" + Util.QuoteJScriptString(DeleteWarning) + "';",
                    true);

                _renderClientScript = CheckRenderClientScript();
                if (_renderClientScript) {
                    // 

                    Page.RegisterPostBackScript();

                    RegisterClientScript();
                }
            }
        }

        protected virtual void OnSelectedWebPartChanged(WebPartEventArgs e) {
            WebPartEventHandler handler = (WebPartEventHandler)Events[SelectedWebPartChangedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnSelectedWebPartChanging(WebPartCancelEventArgs e) {
            WebPartCancelEventHandler handler = (WebPartCancelEventHandler)Events[SelectedWebPartChangingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartAdded(WebPartEventArgs e) {
            WebPartEventHandler handler = (WebPartEventHandler)Events[WebPartAddedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartAdding(WebPartAddingEventArgs e) {
            WebPartAddingEventHandler handler = (WebPartAddingEventHandler)Events[WebPartAddingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartClosed(WebPartEventArgs e) {
            WebPartEventHandler handler = (WebPartEventHandler)Events[WebPartClosedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartClosing(WebPartCancelEventArgs e) {
            WebPartCancelEventHandler handler = (WebPartCancelEventHandler)Events[WebPartClosingEvent];
            if (handler != null) {
                handler(this, e);
            }

        }

        protected virtual void OnWebPartDeleted(WebPartEventArgs e) {
            WebPartEventHandler handler = (WebPartEventHandler)Events[WebPartDeletedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartDeleting(WebPartCancelEventArgs e) {
            WebPartCancelEventHandler handler = (WebPartCancelEventHandler)Events[WebPartDeletingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartMoved(WebPartEventArgs e) {
            WebPartEventHandler handler = (WebPartEventHandler)Events[WebPartMovedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartMoving(WebPartMovingEventArgs e) {
            WebPartMovingEventHandler handler = (WebPartMovingEventHandler)Events[WebPartMovingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartsConnected(WebPartConnectionsEventArgs e) {
            WebPartConnectionsEventHandler handler = (WebPartConnectionsEventHandler)Events[WebPartsConnectedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartsConnecting(WebPartConnectionsCancelEventArgs e) {
            WebPartConnectionsCancelEventHandler handler = (WebPartConnectionsCancelEventHandler)Events[WebPartsConnectingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartsDisconnected(WebPartConnectionsEventArgs e) {
            WebPartConnectionsEventHandler handler = (WebPartConnectionsEventHandler)Events[WebPartsDisconnectedEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnWebPartsDisconnecting(WebPartConnectionsCancelEventArgs e) {
            WebPartConnectionsCancelEventHandler handler = (WebPartConnectionsCancelEventHandler)Events[WebPartsDisconnectingEvent];
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void RegisterClientScript() {
            Page.ClientScript.RegisterClientScriptResource(this, typeof(WebPartManager), "WebParts.js");

            bool allowPageDesign = DisplayMode.AllowPageDesign;

            string dragOverlayElementReference = "null";
            if (allowPageDesign) {
                dragOverlayElementReference = "document.getElementById('" + ClientID + "___Drag')";
            }

            StringBuilder zoneCode = new StringBuilder(1024);
            foreach (WebPartZoneBase zone in _webPartZones) {
                string isVertical = (zone.LayoutOrientation == Orientation.Vertical) ? "true" : "false";

                string allowLayoutChange = "false";
                string dragHighlightColor = "black";
                if (allowPageDesign && zone.AllowLayoutChange) {
                    allowLayoutChange = "true";
                    dragHighlightColor = ColorTranslator.ToHtml(zone.DragHighlightColor);
                }

                zoneCode.AppendFormat(CultureInfo.InvariantCulture, ZoneScript, zone.ClientID, zone.UniqueID, isVertical,
                                      allowLayoutChange, dragHighlightColor);

                WebPartCollection webParts = GetWebPartsForZone(zone);
                foreach (WebPart webPart in webParts) {
                    string titleBarElementReference = "null";
                    string allowMove = "false";
                    if (allowPageDesign) {
                        titleBarElementReference = "document.getElementById('" + webPart.TitleBarID + "')";
                        if (webPart.AllowZoneChange) {
                            allowMove = "true";
                        }
                    }
                    zoneCode.AppendFormat(ZonePartScript, webPart.WholePartID, titleBarElementReference, allowMove);
                }

                zoneCode.Append(ZoneEndScript);
            }

            string startupScript = String.Format(CultureInfo.InvariantCulture,
                                                 StartupScript,
                                                 dragOverlayElementReference,
                                                 (Personalization.Scope == PersonalizationScope.Shared ? "true" : "false"),
                                                 zoneCode.ToString());
            Page.ClientScript.RegisterStartupScript(this, typeof(WebPartManager), String.Empty, startupScript, false);

            IScriptManager scriptManager = Page.ScriptManager;
            if ((scriptManager != null) && scriptManager.SupportsPartialRendering) {
                scriptManager.RegisterDispose(this, "WebPartManager_Dispose();");
            }
        }

        internal void RegisterZone(WebZone zone) {
            Debug.Assert(zone != null);

            if (_pageInitComplete) {
                throw new InvalidOperationException(SR.GetString(SR.WebPartManager_RegisterTooLate));
            }

            string zoneID = zone.ID;
            if (String.IsNullOrEmpty(zoneID)) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_NoZoneID), "zone");
            }
            if (_zoneIDs.Contains(zoneID)) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_DuplicateZoneID, zoneID));
            }
            _zoneIDs.Add(zoneID, zone);

            WebPartZoneBase webPartZone = zone as WebPartZoneBase;
            if (webPartZone != null) {
                if (_webPartZones.Contains(webPartZone)) {
                    throw new ArgumentException(SR.GetString(SR.WebPartManager_AlreadyRegistered), "zone");
                }

                _webPartZones.Add(webPartZone);

                WebPartCollection initialWebParts = webPartZone.GetInitialWebParts();
                ((WebPartManagerControlCollection)Controls).AddWebPartsFromZone(webPartZone, initialWebParts);
            }
            else {
                Debug.Assert(zone is ToolZone);
                ToolZone toolZone = (ToolZone)zone;

                WebPartDisplayModeCollection allDisplayModes = DisplayModes;
                WebPartDisplayModeCollection supportedDisplayModes = SupportedDisplayModes;
                foreach (WebPartDisplayMode displayMode in toolZone.AssociatedDisplayModes) {
                    if (allDisplayModes.Contains(displayMode) && !supportedDisplayModes.Contains(displayMode)) {
                        supportedDisplayModes.AddInternal(displayMode);
                    }
                }
            }
        }

        /// <devdoc>
        /// Deletes the part from the dictionary mapping zones to parts.
        /// </devdoc>
        private void RemoveWebPartFromDictionary(WebPart webPart) {
            if (_partsForZone != null) {
                string zoneID = Internals.GetZoneID(webPart);
                if (!String.IsNullOrEmpty(zoneID)) {
                    SortedList partsForZone = (SortedList)(_partsForZone[zoneID]);
                    if (partsForZone != null) {
                        partsForZone.Remove(webPart);
                    }
                }
            }
        }

        // Called by WebPartManagerInternals
        internal void RemoveWebPart(WebPart webPart) {
            ((WebPartManagerControlCollection)Controls).RemoveWebPart(webPart);
        }

        /// <devdoc>
        /// Removes a web part from its zone, and renumbers all the remaining parts sequentially.
        /// </devdoc>
        private void RemoveWebPartFromZone(WebPart webPart) {
            Debug.Assert(!webPart.IsClosed);

            WebPartZoneBase zone = webPart.Zone;
            Internals.SetIsClosed(webPart, true);
            _hasDataChanged = true;

            RemoveWebPartFromDictionary(webPart);

            // 

            if (zone != null) {
                IList parts = GetAllWebPartsForZone(zone);
                for (int i = 0; i < parts.Count; i++) {
                    WebPart part = ((WebPart)parts[i]);
                    Internals.SetZoneIndex(part, i);
                }
            }
        }

        protected internal override void Render(HtmlTextWriter writer) {
            if (DisplayMode.AllowPageDesign) {
                string dragOverlayElementHtml = String.Format(CultureInfo.InvariantCulture, DragOverlayElementHtmlTemplate, ClientID);
                writer.WriteLine(dragOverlayElementHtml);
            }
        }

        /// <devdoc>
        /// Saves the control state for those properties that should persist across postbacks
        /// even when EnableViewState=false.
        /// </devdoc>
        protected internal override object SaveControlState() {
            object[] myState = new object[controlStateArrayLength];

            myState[baseIndex] = base.SaveControlState();
            if (SelectedWebPart != null) {
                myState[selectedWebPartIndex] = SelectedWebPart.ID;
            }
            if (_displayMode != BrowseDisplayMode) {
                myState[displayModeIndex] = _displayMode.Name;
            }

            for (int i=0; i < controlStateArrayLength; i++) {
                if (myState[i] != null) {
                    return myState;
                }
            }

            // More performant to return null than an array of null values
            return null;
        }

        protected virtual void SaveCustomPersonalizationState(PersonalizationDictionary state) {
            PersonalizationScope scope = Personalization.Scope;

            int webPartsCount = Controls.Count;
            if (webPartsCount > 0) {
                object[] webPartState = new object[webPartsCount * 4];
                for (int i=0; i < webPartsCount; i++) {
                    WebPart webPart = (WebPart)Controls[i];
                    webPartState[4*i] = webPart.ID;
                    webPartState[4*i + 1] = Internals.GetZoneID(webPart);
                    webPartState[4*i + 2] = webPart.ZoneIndex;
                    webPartState[4*i + 3] = webPart.IsClosed;
                }
                if (scope == PersonalizationScope.Shared) {
                    state["WebPartStateShared"] =
                        new PersonalizationEntry(webPartState, PersonalizationScope.Shared);
                }
                else {
                    state["WebPartStateUser"] =
                        new PersonalizationEntry(webPartState, PersonalizationScope.User);
                }
            }

            // Select only the dynamic WebParts that should be saved for this mode
            ArrayList dynamicWebParts = new ArrayList();
            foreach (WebPart webPart in Controls) {
                if (!webPart.IsStatic &&
                    ((scope == PersonalizationScope.User && !webPart.IsShared) ||
                     (scope == PersonalizationScope.Shared && webPart.IsShared))) {
                    dynamicWebParts.Add(webPart);
                }
            }

            int dynamicWebPartsCount = dynamicWebParts.Count;
            if (dynamicWebPartsCount > 0) {
                // Use a 1-dimensional array for smallest storage space
                object[] dynamicWebPartState = new object[dynamicWebPartsCount * 4];
                for (int i = 0; i < dynamicWebPartsCount; i++) {
                    WebPart webPart = (WebPart)dynamicWebParts[i];

                    string id;
                    string typeName;
                    string path = null;
                    string genericWebPartID = null;
                    ProxyWebPart proxyWebPart = webPart as ProxyWebPart;
                    if (proxyWebPart != null) {
                        id = proxyWebPart.OriginalID;
                        typeName = proxyWebPart.OriginalTypeName;
                        path = proxyWebPart.OriginalPath;
                        genericWebPartID = proxyWebPart.GenericWebPartID;
                    }
                    else {
                        GenericWebPart genericWebPart = webPart as GenericWebPart;
                        if (genericWebPart != null) {
                            Control childControl = genericWebPart.ChildControl;
                            UserControl userControl = childControl as UserControl;

                            id = childControl.ID;
                            if (userControl != null) {
                                typeName = WebPartUtil.SerializeType(typeof(UserControl));
                                path = userControl.AppRelativeVirtualPath;
                            }
                            else {
                                typeName = WebPartUtil.SerializeType(childControl.GetType());
                            }
                            genericWebPartID = genericWebPart.ID;
                        }
                        else {
                            id = webPart.ID;
                            typeName = WebPartUtil.SerializeType(webPart.GetType());
                        }
                    }

                    dynamicWebPartState[4*i] = id;
                    dynamicWebPartState[4*i + 1] = typeName;
                    if (!String.IsNullOrEmpty(path)) {
                        dynamicWebPartState[4*i + 2] = path;
                    }
                    if (!String.IsNullOrEmpty(genericWebPartID)) {
                        dynamicWebPartState[4*i + 3] = genericWebPartID;
                    }
                }
                if (scope == PersonalizationScope.Shared) {
                    state["DynamicWebPartsShared"] =
                        new PersonalizationEntry(dynamicWebPartState, PersonalizationScope.Shared);
                }
                else {
                    state["DynamicWebPartsUser"] =
                        new PersonalizationEntry(dynamicWebPartState, PersonalizationScope.User);
                }
            }

            // Save deleted connections
            // 

            ArrayList deletedConnections = new ArrayList();
            // PERF: Use the StaticConnections and DynamicConnections collections separately, instead
            // of using the Connections property which is created on every call.
            foreach (WebPartConnection connection in StaticConnections) {
                if (Internals.ConnectionDeleted(connection)) {
                    deletedConnections.Add(connection);
                }
            }
            foreach (WebPartConnection connection in DynamicConnections) {
                if (Internals.ConnectionDeleted(connection)) {
                    deletedConnections.Add(connection);
                }
            }

            int deletedConnectionsCount = deletedConnections.Count;
            if (deletedConnections.Count > 0) {
                string[] deletedConnectionsState = new string[deletedConnectionsCount];
                for (int i=0; i < deletedConnectionsCount; i++) {
                    WebPartConnection deletedConnection = (WebPartConnection)deletedConnections[i];
                    // Only shared connections can be deleted
                    Debug.Assert(deletedConnection.IsShared);
                    // In shared scope, only static connections should be deleted
                    // In user scope, static and dynamic connections can be deleted
                    Debug.Assert(deletedConnection.IsStatic || scope == PersonalizationScope.User);
                    deletedConnectionsState[i] = deletedConnection.ID;
                }
                if (scope == PersonalizationScope.Shared) {
                    state["DeletedConnectionsShared"] =
                        new PersonalizationEntry(deletedConnectionsState, PersonalizationScope.Shared);
                }
                else {
                    state["DeletedConnectionsUser"] =
                        new PersonalizationEntry(deletedConnectionsState, PersonalizationScope.User);
                }
            }

            // Select only the dynamic Connections that should be saved for this mode
            ArrayList dynamicConnections = new ArrayList();
            foreach (WebPartConnection connection in DynamicConnections) {
                if (((scope == PersonalizationScope.User) && (!connection.IsShared)) ||
                    ((scope == PersonalizationScope.Shared) && (connection.IsShared))) {
                    dynamicConnections.Add(connection);
                }
            }

            int dynamicConnectionsCount = dynamicConnections.Count;
            if (dynamicConnectionsCount > 0) {
                // Use a 1-dimensional array for smallest storage space
                object[] dynamicConnectionState = new object[dynamicConnectionsCount * 7];
                for (int i = 0; i < dynamicConnectionsCount; i++) {
                    WebPartConnection connection = (WebPartConnection)dynamicConnections[i];
                    WebPartTransformer transformer = connection.Transformer;

                    // We should never be saving a deleted dynamic connection.  If the User has deleted a
                    // a shared connection, the connection will be saved in the Shared data, not here.
                    Debug.Assert(!Internals.ConnectionDeleted(connection));

                    dynamicConnectionState[7*i] = connection.ID;
                    dynamicConnectionState[7*i + 1] = connection.ConsumerID;
                    dynamicConnectionState[7*i + 2] = connection.ConsumerConnectionPointID;
                    dynamicConnectionState[7*i + 3] = connection.ProviderID;
                    dynamicConnectionState[7*i + 4] = connection.ProviderConnectionPointID;
                    if (transformer != null) {
                        dynamicConnectionState[7*i + 5] = transformer.GetType();
                        dynamicConnectionState[7*i + 6] = Internals.SaveConfigurationState(transformer);
                    }
                }

                if (scope == PersonalizationScope.Shared) {
                    state["DynamicConnectionsShared"] =
                        new PersonalizationEntry(dynamicConnectionState, PersonalizationScope.Shared);
                }
                else {
                    state["DynamicConnectionsUser"] =
                        new PersonalizationEntry(dynamicConnectionState, PersonalizationScope.User);
                }
            }
        }

        // Can be called by a derived WebPartManager to mark itself as dirty
        protected void SetPersonalizationDirty() {
            Personalization.SetDirty();
        }

        // Returns true if the WebPart should currently be rendered in the Zone.  Determines
        // which WebParts are returned by GetWebPartsForZone.
        private bool ShouldRenderWebPartInZone(WebPart part, WebPartZoneBase zone) {
            Debug.Assert(part.Zone == zone);

            // Never render UnauthorizedWebParts
            if (part is UnauthorizedWebPart) {
                return false;
            }

            return true;
        }

        protected void SetSelectedWebPart(WebPart webPart) {
            _selectedWebPart = webPart;
        }

        // PropertyInfo will be null for an IPersonalizable property, since there is no associated PropertyInfo
        private bool ShouldExportProperty(PropertyInfo propertyInfo, Type propertyValueType,
                                          object propertyValue, out string exportString) {
            string propertyValueAsString = propertyValue as string;
            if (propertyValueAsString != null) {
                exportString = propertyValueAsString;
                return true;
            }
            else {
                TypeConverter converter = null;

                if (propertyInfo != null) {
                    // See if the property itself has a type converter associated with it
                    TypeConverterAttribute attr =
                        Attribute.GetCustomAttribute(propertyInfo, typeof(TypeConverterAttribute), true) as TypeConverterAttribute;
                    if (attr != null) {
                        // Get the type using DeserializeType(), which calls BuildManager.GetType(),
                        // since we want this to work with a non-assembly qualified typename
                        // in the Code directory.
                        Type converterType = WebPartUtil.DeserializeType(attr.ConverterTypeName, false);
                        // SECURITY: Check that the type is a subclass of TypeConverter before instantiating.
                        if (converterType != null && converterType.IsSubclassOf(typeof(TypeConverter))) {
                            TypeConverter tempConverter = (TypeConverter)(Internals.CreateObjectFromType(converterType));
                            if (Util.CanConvertToFrom(tempConverter, typeof(string))) {
                                converter = tempConverter;
                            }
                        }
                    }
                }

                if (converter == null) {
                    // If there was no valid type converter on the property info, look on the type of the value
                    TypeConverter tempConverter = TypeDescriptor.GetConverter(propertyValueType);
                    if (Util.CanConvertToFrom(tempConverter, typeof(string))) {
                        converter = tempConverter;
                    }
                }

                // Only export property if we found a valid type converter (VSWhidbey 496495)
                if (converter != null) {
                    if (propertyValue != null) {
                        exportString = converter.ConvertToInvariantString(propertyValue);
                        return true;
                    }
                    else {
                        // Special-case null value
                        exportString = null;
                        return true;
                    }
                }
                else {
                    exportString = null;
                    if (propertyInfo == null && propertyValue == null) {
                        // Always want to export a null IPersonalizable value, since we will never have a type
                        // converter for the value.  However, we should not export a null Personalizable value
                        // unless the propertyInfo had a type converter, since we may not be able to import a
                        // null value, since the property may be a value type that cannot accept null as a value.
                        // (VSWhidbey 537895)
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
        }

        /// <devdoc>
        /// Returns true if the connection should be removed from the dynamic connection
        /// collection when deleted.
        /// </devdoc>
        private bool ShouldRemoveConnection(WebPartConnection connection) {
            Debug.Assert(Personalization.IsModifiable);

            if (connection.IsShared && (Personalization.Scope == PersonalizationScope.User)) {
                // Can't remove shared connection in user mode
                return false;
            }
            else {
                return true;
            }
        }

        /// <internalonly />
        protected override void TrackViewState() {
            Personalization.ApplyPersonalizationState();
            base.TrackViewState();
        }

        // Throw if the type cannot be loaded by BuildManager
        // For instance, we cannot load a type defined in the Page class
        private void VerifyType(Control control) {
            // Don't need to verify type of UserControls, since we load them using
            // their path instead of their type
            if (control is UserControl) {
                return;
            }

            Type type = control.GetType();
            string typeName = WebPartUtil.SerializeType(type);
            Type loadedType = WebPartUtil.DeserializeType(typeName, /* throwOnError */ false);
            if (loadedType != type) {
                throw new InvalidOperationException(
                    SR.GetString(SR.WebPartManager_CantAddControlType, typeName));
            }
        }

        #region Implementation of IPersonalizable
        /// <internalonly/>
        bool IPersonalizable.IsDirty {
            get {
                return IsCustomPersonalizationStateDirty;
            }
        }

        /// <internalonly/>
        void IPersonalizable.Load(PersonalizationDictionary state) {
            LoadCustomPersonalizationState(state);
        }

        /// <internalonly/>
        void IPersonalizable.Save(PersonalizationDictionary state) {
            SaveCustomPersonalizationState(state);
        }
        #endregion

        private sealed class WebPartManagerControlCollection : ControlCollection {

            private WebPartManager _manager;

            public WebPartManagerControlCollection(WebPartManager owner) : base(owner) {
                _manager = owner;
                SetCollectionReadOnly(SR.WebPartManager_CannotModify);
            }

            internal void AddWebPart(WebPart webPart) {
                string originalError = SetCollectionReadOnly(null);
                // Extra try-catch block to prevent elevation of privilege attack via exception filter
                try {
                    try {
                        AddWebPartHelper(webPart);
                    }
                    finally {
                        SetCollectionReadOnly(originalError);
                    }
                }
                catch {
                    throw;
                }
            }

            private void AddWebPartHelper(WebPart webPart) {
                string partID = webPart.ID;
                if (String.IsNullOrEmpty(partID)) {
                    throw new InvalidOperationException(SR.GetString(SR.WebPartManager_NoWebPartID));
                }
                if (_manager._partAndChildControlIDs.Contains(partID)) {
                   throw new InvalidOperationException(SR.GetString(SR.WebPartManager_DuplicateWebPartID, partID));
                }

                // Add to dictionary to prevent duplicate IDs, even if this part is not authorized.  Don't want page
                // developer to have 2 parts with the same ID, and not get the exception until they are both authorized.
                _manager._partAndChildControlIDs.Add(partID, null);

                // Check and add child control ID (VSWhidbey 339482)
                GenericWebPart genericWebPart = webPart as GenericWebPart;
                if (genericWebPart != null) {
                    string childControlID = genericWebPart.ChildControl.ID;

                    if (String.IsNullOrEmpty(childControlID)) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartManager_NoChildControlID));
                    }

                    if (_manager._partAndChildControlIDs.Contains(childControlID)) {
                        throw new InvalidOperationException(SR.GetString(SR.WebPartManager_DuplicateWebPartID, childControlID));
                    }

                    _manager._partAndChildControlIDs.Add(childControlID, null);
                }

                _manager.Internals.SetIsStandalone(webPart, false);
                webPart.SetWebPartManager(_manager);
                Add(webPart);

                // Invalidate the part dictionary if it has already been created
                _manager._partsForZone = null;
            }

            internal void AddWebPartsFromZone(WebPartZoneBase zone, WebPartCollection webParts) {
                if ((webParts != null) && (webParts.Count != 0)) {
                    string originalError = SetCollectionReadOnly(null);

                    // Extra try-catch block to prevent elevation of privilege attack via exception filter
                    try {
                        try {
                            string zoneID = zone.ID;
                            int index = 0;

                            foreach (WebPart webPart in webParts) {
                                // Need to set IsShared before calling IsAuthorized
                                _manager.Internals.SetIsShared(webPart, true);

                                WebPart webPartOrProxy = webPart;
                                if (!_manager.IsAuthorized(webPart)) {
                                    webPartOrProxy = new UnauthorizedWebPart(webPart);
                                }

                                _manager.Internals.SetIsStatic(webPartOrProxy, true);
                                _manager.Internals.SetIsShared(webPartOrProxy, true);
                                _manager.Internals.SetZoneID(webPartOrProxy, zoneID);
                                _manager.Internals.SetZoneIndex(webPartOrProxy, index);

                                AddWebPartHelper(webPartOrProxy);
                                index++;
                            }
                        }
                        finally {
                            SetCollectionReadOnly(originalError);
                        }
                    } catch {
                        throw;
                    }
                }
            }

            internal void RemoveWebPart(WebPart webPart) {
                string originalError = SetCollectionReadOnly(null);
                // Extra try-catch block to prevent elevation of privilege attack via exception filter
                try {
                    try {
                        _manager._partAndChildControlIDs.Remove(webPart.ID);

                        // Remove child control ID (VSWhidbey 339482)
                        GenericWebPart genericWebPart = webPart as GenericWebPart;
                        if (genericWebPart != null) {
                            _manager._partAndChildControlIDs.Remove(genericWebPart.ChildControl.ID);
                        }

                        Remove(webPart);
                        _manager._hasDataChanged = true;
                        webPart.SetWebPartManager(null);
                        _manager.Internals.SetIsStandalone(webPart, true);

                        // Invalidate the part dictionary if it has already been created
                        _manager._partsForZone = null;
                    }
                    finally {
                        SetCollectionReadOnly(originalError);
                    }
                }
                catch {
                    throw;
                }
            }
        }

        private sealed class BrowseWebPartDisplayMode : WebPartDisplayMode {

            public BrowseWebPartDisplayMode() : base("Browse") {
            }
        }

        private sealed class CatalogWebPartDisplayMode : WebPartDisplayMode {

            public CatalogWebPartDisplayMode() : base("Catalog") {
            }

            public override bool AllowPageDesign {
                get {
                    return true;
                }
            }

            public override bool AssociatedWithToolZone {
                get {
                    return true;
                }
            }

            public override bool RequiresPersonalization {
                get {
                    return true;
                }
            }

            public override bool ShowHiddenWebParts {
                get {
                    return true;
                }
            }
        }

        private sealed class ConnectionPointKey {
            // DevDiv Bugs 38677
            // used as the Cache key for Connection Points, using Type and Culture
            private Type _type;
            private CultureInfo _culture;
            private CultureInfo _uiCulture;

            public ConnectionPointKey(Type type, CultureInfo culture, CultureInfo uiCulture) {
                 Debug.Assert(type != null && culture != null && uiCulture != null);

                 _type = type;
                 _culture = culture;
                 _uiCulture = uiCulture;
            }

            public override bool Equals(object obj) {
                 if (obj == this) {
                      return true;
                 }

                 ConnectionPointKey other = obj as ConnectionPointKey;
                 return (other != null) &&
				    (other._type.Equals(_type)) &&
				    (other._culture.Equals(_culture)) &&
				    (other._uiCulture.Equals(_uiCulture));
            }

            [SuppressMessage("Microsoft.Usage", "CA2303:FlagTypeGetHashCode", Justification = "The types are Sytem.Web.UI.Control derived classes and not com interop types.")]
            public override int GetHashCode()
            {
                 int typeHashCode = _type.GetHashCode();
                 // This is the algorithm used in Whidbey to combine hashcodes.
                 // It adheres better than a simple XOR to the randomness requirement for hashcodes.
                 int hashCode = ((typeHashCode << 5) + typeHashCode) ^ _culture.GetHashCode();
                 return ((hashCode << 5) + hashCode) ^ _uiCulture.GetHashCode();
            }
        }

        private sealed class ConnectWebPartDisplayMode : WebPartDisplayMode {

            public ConnectWebPartDisplayMode() : base("Connect") {
            }

            public override bool AllowPageDesign {
                get {
                    return true;
                }
            }

            public override bool AssociatedWithToolZone {
                get {
                    return true;
                }
            }

            public override bool RequiresPersonalization {
                get {
                    return true;
                }
            }

            public override bool ShowHiddenWebParts {
                get {
                    return true;
                }
            }
        }

        private sealed class DesignWebPartDisplayMode : WebPartDisplayMode {

            public DesignWebPartDisplayMode() : base("Design") {
            }

            public override bool AllowPageDesign {
                get {
                    return true;
                }
            }

            public override bool RequiresPersonalization {
                get {
                    return true;
                }
            }

            public override bool ShowHiddenWebParts {
                get {
                    return true;
                }
            }
        }

        private sealed class EditWebPartDisplayMode : WebPartDisplayMode {

            public EditWebPartDisplayMode() : base("Edit") {
            }

            public override bool AllowPageDesign {
                get {
                    return true;
                }
            }

            public override bool AssociatedWithToolZone {
                get {
                    return true;
                }
            }

            public override bool RequiresPersonalization {
                get {
                    return true;
                }
            }

            public override bool ShowHiddenWebParts {
                get {
                    return true;
                }
            }
        }
    }
}