File: DataContract.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (2692 lines) | stat: -rw-r--r-- 119,003 bytes parent folder | download
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
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
    using System;
    using System.CodeDom;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime.CompilerServices;
#if !NO_CONFIGURATION
    using System.Runtime.Serialization.Configuration;
#endif
    using System.Runtime.Serialization.Diagnostics.Application;
    using System.Security;
    using System.Text;
    using System.Xml;
    using System.Xml.Schema;
    using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
    using System.Text.RegularExpressions;

#if USE_REFEMIT
    public abstract class DataContract
#else
    internal abstract class DataContract
#endif
    {
        [Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the type name. Statically cached and used from IL generated code.")]
        [SecurityCritical]
        XmlDictionaryString name;

        [Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the type name. Statically cached and used from IL generated code.")]
        [SecurityCritical]
        XmlDictionaryString ns;

        [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
            + " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
        [SecurityCritical]
        DataContractCriticalHelper helper;

        [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
            Safe = "Doesn't leak anything.")]
        [SecuritySafeCritical]
        protected DataContract(DataContractCriticalHelper helper)
        {
            this.helper = helper;
            this.name = helper.Name;
            this.ns = helper.Namespace;
        }

        internal static DataContract GetDataContract(Type type)
        {
            return GetDataContract(type.TypeHandle, type, SerializationMode.SharedContract);
        }

        internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
        {
            int id = GetId(typeHandle);
            return GetDataContract(id, typeHandle, mode);
        }

        internal static DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle, SerializationMode mode)
        {
            DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null);
            dataContract = dataContract.GetValidContract(mode);

            return dataContract;
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract .",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
        {
            return DataContractCriticalHelper.GetDataContractSkipValidation(id, typeHandle, type);
        }

        internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
        {
            DataContract dataContract = GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type);
            dataContract = dataContract.GetValidContract(mode);
            if (dataContract is ClassDataContract)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.ClassDataContractReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(dataContract.UnderlyingType))));
            }
            return dataContract;
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract .",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
        {
            return DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract .",
            Safe = "Read only access; doesn't modify any static information.")]
        [SecuritySafeCritical]
        internal static DataContract GetDataContractForInitialization(int id)
        {
            return DataContractCriticalHelper.GetDataContractForInitialization(id);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up id for DataContract .",
            Safe = "Read only access; doesn't modify any static information.")]
        [SecuritySafeCritical]
        internal static int GetIdForInitialization(ClassDataContract classContract)
        {
            return DataContractCriticalHelper.GetIdForInitialization(classContract);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up id assigned to a particular type.",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        internal static int GetId(RuntimeTypeHandle typeHandle)
        {
            return DataContractCriticalHelper.GetId(typeHandle);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract.",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        public static DataContract GetBuiltInDataContract(Type type)
        {
            return DataContractCriticalHelper.GetBuiltInDataContract(type);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract.",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        public static DataContract GetBuiltInDataContract(string name, string ns)
        {
            return DataContractCriticalHelper.GetBuiltInDataContract(name, ns);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract.",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        public static DataContract GetBuiltInDataContract(string typeName)
        {
            return DataContractCriticalHelper.GetBuiltInDataContract(typeName);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up string reference to use for a namespace string.",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        internal static string GetNamespace(string key)
        {
            return DataContractCriticalHelper.GetNamespace(key);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up XmlDictionaryString for a string.",
            Safe = "Read only access.")]
        [SecuritySafeCritical]
        internal static XmlDictionaryString GetClrTypeString(string key)
        {
            return DataContractCriticalHelper.GetClrTypeString(key);
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to remove invalid DataContract if it has been added to cache.",
            Safe = "Doesn't leak any information.")]
        [SecuritySafeCritical]
        internal static void ThrowInvalidDataContractException(string message, Type type)
        {
            DataContractCriticalHelper.ThrowInvalidDataContractException(message, type);
        }

#if USE_REFEMIT
        internal DataContractCriticalHelper Helper
#else
        protected DataContractCriticalHelper Helper
#endif
        {
            [Fx.Tag.SecurityNote(Critical = "holds instance of CriticalHelper which keeps state that is cached statically for serialization."
                + " Static fields are marked SecurityCritical or readonly to prevent"
                + " data from being modified or leaked to other components in appdomain.")]
            [SecurityCritical]
            get { return helper; }
        }

        internal Type UnderlyingType
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical UnderlyingType field.",
                Safe = "Get-only properties only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.UnderlyingType; }
        }

        internal Type OriginalUnderlyingType
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical OriginalUnderlyingType property.",
                Safe = "OrginalUnderlyingType only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.OriginalUnderlyingType; }
        }


        internal virtual bool IsBuiltInDataContract
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical isBuiltInDataContract property.",
                Safe = "isBuiltInDataContract only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.IsBuiltInDataContract; }
        }

        internal Type TypeForInitialization
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical typeForInitialization property.",
                Safe = "typeForInitialization only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.TypeForInitialization; }
        }

        public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
        {
            throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
        }

        public virtual object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
        {
            throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
        }

        internal bool IsValueType
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsValueType property.",
                Safe = "IsValueType only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.IsValueType; }
            [Fx.Tag.SecurityNote(Critical = "Sets the critical IsValueType property.")]
            [SecurityCritical]
            set { helper.IsValueType = value; }
        }

        internal bool IsReference
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsReference property.",
                Safe = "IsReference only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.IsReference; }

            [Fx.Tag.SecurityNote(Critical = "Sets the critical IsReference property.")]
            [SecurityCritical]
            set { helper.IsReference = value; }
        }

        internal XmlQualifiedName StableName
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical StableName property.",
                Safe = "StableName only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.StableName; }

            [Fx.Tag.SecurityNote(Critical = "Sets the critical StableName property.")]
            [SecurityCritical]
            set { helper.StableName = value; }
        }

        internal GenericInfo GenericInfo
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical GenericInfo property.",
                Safe = "GenericInfo only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.GenericInfo; }
            [Fx.Tag.SecurityNote(Critical = "Sets the critical GenericInfo property.",
                Safe = "Protected for write if contract has underlyingType .")]
            [SecurityCritical]
            set { helper.GenericInfo = value; }
        }

        internal virtual DataContractDictionary KnownDataContracts
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical KnownDataContracts property.",
                Safe = "KnownDataContracts only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.KnownDataContracts; }

            [Fx.Tag.SecurityNote(Critical = "Sets the critical KnownDataContracts property.")]
            [SecurityCritical]
            set { helper.KnownDataContracts = value; }
        }

        internal virtual bool IsISerializable
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsISerializable property.",
                Safe = "IsISerializable only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.IsISerializable; }

            [Fx.Tag.SecurityNote(Critical = "Sets the critical IsISerializable property.")]
            [SecurityCritical]
            set { helper.IsISerializable = value; }
        }

        internal XmlDictionaryString Name
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical Name property.",
                Safe = "Name only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return this.name; }
        }

        public virtual XmlDictionaryString Namespace
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical Namespace property.",
                Safe = "Namespace only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return this.ns; }
        }

        internal virtual bool HasRoot
        {
            get { return true; }
            set { }
        }

        internal virtual XmlDictionaryString TopLevelElementName
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical Name property.",
                Safe = "Name only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.TopLevelElementName; }

            [Fx.Tag.SecurityNote(Critical = "Sets the critical Name property.")]
            [SecurityCritical]
            set { helper.TopLevelElementName = value; }
        }

        internal virtual XmlDictionaryString TopLevelElementNamespace
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical Namespace property.",
                Safe = "Namespace only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.TopLevelElementNamespace; }

            [Fx.Tag.SecurityNote(Critical = "Sets the critical Namespace property.")]
            [SecurityCritical]
            set { helper.TopLevelElementNamespace = value; }
        }

        internal virtual bool CanContainReferences
        {
            get { return true; }
        }

        internal virtual bool IsPrimitive
        {
            get { return false; }
        }

        internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
        {
            if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive)
                writer.WriteStartElement(Globals.SerPrefix, name, ns);
            else
                writer.WriteStartElement(name, ns);
        }

        internal virtual DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary<DataContract, DataContract> boundContracts)
        {
            return this;
        }

        internal virtual DataContract GetValidContract(SerializationMode mode)
        {
            return this;
        }

        internal virtual DataContract GetValidContract()
        {
            return this;
        }

        internal virtual bool IsValidContract(SerializationMode mode)
        {
            return true;
        }

        internal MethodInfo ParseMethod
        {
            [Fx.Tag.SecurityNote(Critical = "Fetches the critical ParseMethod field.",
                Safe = "Get-only properties only needs to be protected for write.")]
            [SecuritySafeCritical]
            get { return helper.ParseMethod; }
        }

        [Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing types."
            + " Since the data is cached statically, we lock down access to it.")]
#if !NO_SECURITY_ATTRIBUTES
        [SecurityCritical(SecurityCriticalScope.Everything)]
#endif
#if USE_REFEMIT
        public class DataContractCriticalHelper
#else
        protected class DataContractCriticalHelper
#endif
        {
            static Dictionary<TypeHandleRef, IntRef> typeToIDCache;
            static DataContract[] dataContractCache;
            static int dataContractID;
            static Dictionary<Type, DataContract> typeToBuiltInContract;
            static Dictionary<XmlQualifiedName, DataContract> nameToBuiltInContract;
            static Dictionary<string, DataContract> typeNameToBuiltInContract;
            static Dictionary<string, string> namespaces;
            static Dictionary<string, XmlDictionaryString> clrTypeStrings;
            static XmlDictionary clrTypeStringsDictionary;
            static TypeHandleRef typeHandleRef = new TypeHandleRef();

            static object cacheLock = new object();
            static object createDataContractLock = new object();
            static object initBuiltInContractsLock = new object();
            static object namespacesLock = new object();
            static object clrTypeStringsLock = new object();

            readonly Type underlyingType;
            Type originalUnderlyingType;
            bool isReference;
            bool isValueType;
            XmlQualifiedName stableName;
            GenericInfo genericInfo;
            XmlDictionaryString name;
            XmlDictionaryString ns;

            [Fx.Tag.SecurityNote(Critical = "In deserialization, we initialize an object instance passing this Type to GetUninitializedObject method.")]
            Type typeForInitialization;

            MethodInfo parseMethod;
            bool parseMethodSet;

            static DataContractCriticalHelper()
            {
                typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
                dataContractCache = new DataContract[32];
                dataContractID = 0;
            }

            internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
            {
                DataContract dataContract = dataContractCache[id];
                if (dataContract == null)
                {
                    dataContract = CreateDataContract(id, typeHandle, type);
                }
                else
                {
                    return dataContract.GetValidContract();
                }
                return dataContract;
            }

            internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
            {
                DataContract dataContract = dataContractCache[id];
                if (dataContract == null)
                {
                    dataContract = CreateGetOnlyCollectionDataContract(id, typeHandle, type);
                    dataContractCache[id] = dataContract;
                }
                return dataContract;
            }

            internal static DataContract GetDataContractForInitialization(int id)
            {
                DataContract dataContract = dataContractCache[id];
                if (dataContract == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.DataContractCacheOverflow)));
                }
                return dataContract;
            }

            internal static int GetIdForInitialization(ClassDataContract classContract)
            {
                int id = DataContract.GetId(classContract.TypeForInitialization.TypeHandle);
                if (id < dataContractCache.Length && ContractMatches(classContract, dataContractCache[id]))
                {
                    return id;
                }
                for (int i = 0; i < DataContractCriticalHelper.dataContractID; i++)
                {
                    if (ContractMatches(classContract, dataContractCache[i]))
                    {
                        return i;
                    }
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.DataContractCacheOverflow)));
            }

            static bool ContractMatches(DataContract contract, DataContract cachedContract)
            {
                return (cachedContract != null && cachedContract.UnderlyingType == contract.UnderlyingType);
            }

            internal static int GetId(RuntimeTypeHandle typeHandle)
            {
                lock (cacheLock)
                {
                    IntRef id;
                    typeHandle = GetDataContractAdapterTypeHandle(typeHandle);
                    typeHandleRef.Value = typeHandle;
                    if (!typeToIDCache.TryGetValue(typeHandleRef, out id))
                    {
                        id = GetNextId();
                        try
                        {
                            typeToIDCache.Add(new TypeHandleRef(typeHandle), id);
                        }
                        catch (Exception ex)
                        {
                            if (Fx.IsFatal(ex))
                            {
                                throw;
                            }
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
                        }
                    }
                    return id.Value;
                }
            }

            // Assumed that this method is called under a lock
            static IntRef GetNextId()
            {
                int value = dataContractID++;
                if (value >= dataContractCache.Length)
                {
                    int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue;
                    if (newSize <= value)
                    {
                        Fx.Assert("DataContract cache overflow");
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.DataContractCacheOverflow)));
                    }
                    Array.Resize<DataContract>(ref dataContractCache, newSize);
                }
                return new IntRef(value);
            }

            // check whether a corresponding update is required in ClassDataContract.IsNonAttributedTypeValidForSerialization
            static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type type)
            {
                lock (createDataContractLock)
                {
                    DataContract dataContract = dataContractCache[id];
                    if (dataContract == null)
                    {
                        if (type == null)
                            type = Type.GetTypeFromHandle(typeHandle);
                        type = UnwrapNullableType(type);
                        type = GetDataContractAdapterType(type);
                        dataContract = GetBuiltInDataContract(type);
                        if (dataContract == null)
                        {
                            if (type.IsArray)
                                dataContract = new CollectionDataContract(type);
                            else if (type.IsEnum)
                                dataContract = new EnumDataContract(type);
                            else if (type.IsGenericParameter)
                                dataContract = new GenericParameterDataContract(type);
                            else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
                                dataContract = new XmlDataContract(type);
                            else
                            {
                                //if (type.ContainsGenericParameters)
                                //    ThrowInvalidDataContractException(SR.GetString(SR.TypeMustNotBeOpenGeneric, type), type);
                                if (type.IsPointer)
                                    type = Globals.TypeOfReflectionPointer;

                                if (!CollectionDataContract.TryCreate(type, out dataContract))
                                {
                                    if (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, false) || ClassDataContract.IsNonAttributedTypeValidForSerialization(type))
                                    {
                                        dataContract = new ClassDataContract(type);
                                    }
                                    else
                                    {
                                        ThrowInvalidDataContractException(SR.GetString(SR.TypeNotSerializable, type), type);
                                    }
                                }
                            }
                        }
                    }
                    dataContractCache[id] = dataContract;
                    return dataContract;
                }
            }

            static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type)
            {
                DataContract dataContract = null;
                lock (createDataContractLock)
                {
                    dataContract = dataContractCache[id];
                    if (dataContract == null)
                    {
                        if (type == null)
                            type = Type.GetTypeFromHandle(typeHandle);
                        type = UnwrapNullableType(type);
                        type = GetDataContractAdapterType(type);
                        if (!CollectionDataContract.TryCreateGetOnlyCollectionDataContract(type, out dataContract))
                        {
                            ThrowInvalidDataContractException(SR.GetString(SR.TypeNotSerializable, type), type);
                        }
                    }
                }
                return dataContract;
            }

            // Any change to this method should be reflected in GetDataContractOriginalType
            internal static Type GetDataContractAdapterType(Type type)
            {
                // Replace the DataTimeOffset ISerializable type passed in with the internal DateTimeOffsetAdapter DataContract type.
                // DateTimeOffsetAdapter is used for serialization/deserialization purposes to bypass the ISerializable implementation
                // on DateTimeOffset; which does not work in partial trust and to ensure correct schema import/export scenarios.
                if (type == Globals.TypeOfDateTimeOffset)
                {
                    return Globals.TypeOfDateTimeOffsetAdapter;
                }
                return type;
            }

            // Maps adapted types back to the original type
            // Any change to this method should be reflected in GetDataContractAdapterType
            internal static Type GetDataContractOriginalType(Type type)
            {
                if (type == Globals.TypeOfDateTimeOffsetAdapter)
                {
                    return Globals.TypeOfDateTimeOffset;
                }
                return type;
            }

            static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHandle typeHandle)
            {
                if (Globals.TypeOfDateTimeOffset.TypeHandle.Equals(typeHandle))
                {
                    return Globals.TypeOfDateTimeOffsetAdapter.TypeHandle;
                }
                return typeHandle;
            }

            [SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "typeToBuiltInContract", Justification = "No need to support type equivalence here.")]
            public static DataContract GetBuiltInDataContract(Type type)
            {
                if (type.IsInterface && !CollectionDataContract.IsCollectionInterface(type))
                    type = Globals.TypeOfObject;

                lock (initBuiltInContractsLock)
                {
                    if (typeToBuiltInContract == null)
                        typeToBuiltInContract = new Dictionary<Type, DataContract>();

                    DataContract dataContract = null;
                    if (!typeToBuiltInContract.TryGetValue(type, out dataContract))
                    {
                        TryCreateBuiltInDataContract(type, out dataContract);
                        typeToBuiltInContract.Add(type, dataContract);
                    }
                    return dataContract;
                }
            }

            public static DataContract GetBuiltInDataContract(string name, string ns)
            {
                lock (initBuiltInContractsLock)
                {
                    if (nameToBuiltInContract == null)
                        nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract>();

                    DataContract dataContract = null;
                    XmlQualifiedName qname = new XmlQualifiedName(name, ns);
                    if (!nameToBuiltInContract.TryGetValue(qname, out dataContract))
                    {
                        if (TryCreateBuiltInDataContract(name, ns, out dataContract))
                        {
                            nameToBuiltInContract.Add(qname, dataContract);
                        }
                    }
                    return dataContract;
                }
            }

            public static DataContract GetBuiltInDataContract(string typeName)
            {
                if (!typeName.StartsWith("System.", StringComparison.Ordinal))
                    return null;

                lock (initBuiltInContractsLock)
                {
                    if (typeNameToBuiltInContract == null)
                        typeNameToBuiltInContract = new Dictionary<string, DataContract>();

                    DataContract dataContract = null;
                    if (!typeNameToBuiltInContract.TryGetValue(typeName, out dataContract))
                    {
                        Type type = null;
                        string name = typeName.Substring(7);
                        if (name == "Char")
                            type = typeof(Char);
                        else if (name == "Boolean")
                            type = typeof(Boolean);
                        else if (name == "SByte")
                            type = typeof(SByte);
                        else if (name == "Byte")
                            type = typeof(Byte);
                        else if (name == "Int16")
                            type = typeof(Int16);
                        else if (name == "UInt16")
                            type = typeof(UInt16);
                        else if (name == "Int32")
                            type = typeof(Int32);
                        else if (name == "UInt32")
                            type = typeof(UInt32);
                        else if (name == "Int64")
                            type = typeof(Int64);
                        else if (name == "UInt64")
                            type = typeof(UInt64);
                        else if (name == "Single")
                            type = typeof(Single);
                        else if (name == "Double")
                            type = typeof(Double);
                        else if (name == "Decimal")
                            type = typeof(Decimal);
                        else if (name == "DateTime")
                            type = typeof(DateTime);
                        else if (name == "String")
                            type = typeof(String);
                        else if (name == "Byte[]")
                            type = typeof(byte[]);
                        else if (name == "Object")
                            type = typeof(Object);
                        else if (name == "TimeSpan")
                            type = typeof(TimeSpan);
                        else if (name == "Guid")
                            type = typeof(Guid);
                        else if (name == "Uri")
                            type = typeof(Uri);
                        else if (name == "Xml.XmlQualifiedName")
                            type = typeof(XmlQualifiedName);
                        else if (name == "Enum")
                            type = typeof(Enum);
                        else if (name == "ValueType")
                            type = typeof(ValueType);
                        else if (name == "Array")
                            type = typeof(Array);
                        else if (name == "Xml.XmlElement")
                            type = typeof(XmlElement);
                        else if (name == "Xml.XmlNode[]")
                            type = typeof(XmlNode[]);

                        if (type != null)
                            TryCreateBuiltInDataContract(type, out dataContract);

                        typeNameToBuiltInContract.Add(typeName, dataContract);
                    }
                    return dataContract;
                }
            }

            static public bool TryCreateBuiltInDataContract(Type type, out DataContract dataContract)
            {
                if (type.IsEnum) // Type.GetTypeCode will report Enums as TypeCode.IntXX
                {
                    dataContract = null;
                    return false;
                }
                dataContract = null;
                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.Boolean:
                        dataContract = new BooleanDataContract();
                        break;
                    case TypeCode.Byte:
                        dataContract = new UnsignedByteDataContract();
                        break;
                    case TypeCode.Char:
                        dataContract = new CharDataContract();
                        break;
                    case TypeCode.DateTime:
                        dataContract = new DateTimeDataContract();
                        break;
                    case TypeCode.Decimal:
                        dataContract = new DecimalDataContract();
                        break;
                    case TypeCode.Double:
                        dataContract = new DoubleDataContract();
                        break;
                    case TypeCode.Int16:
                        dataContract = new ShortDataContract();
                        break;
                    case TypeCode.Int32:
                        dataContract = new IntDataContract();
                        break;
                    case TypeCode.Int64:
                        dataContract = new LongDataContract();
                        break;
                    case TypeCode.SByte:
                        dataContract = new SignedByteDataContract();
                        break;
                    case TypeCode.Single:
                        dataContract = new FloatDataContract();
                        break;
                    case TypeCode.String:
                        dataContract = new StringDataContract();
                        break;
                    case TypeCode.UInt16:
                        dataContract = new UnsignedShortDataContract();
                        break;
                    case TypeCode.UInt32:
                        dataContract = new UnsignedIntDataContract();
                        break;
                    case TypeCode.UInt64:
                        dataContract = new UnsignedLongDataContract();
                        break;
                    default:
                        if (type == typeof(byte[]))
                            dataContract = new ByteArrayDataContract();
                        else if (type == typeof(object))
                            dataContract = new ObjectDataContract();
                        else if (type == typeof(Uri))
                            dataContract = new UriDataContract();
                        else if (type == typeof(XmlQualifiedName))
                            dataContract = new QNameDataContract();
                        else if (type == typeof(TimeSpan))
                            dataContract = new TimeSpanDataContract();
                        else if (type == typeof(Guid))
                            dataContract = new GuidDataContract();
                        else if (type == typeof(Enum) || type == typeof(ValueType))
                        {
                            dataContract = new SpecialTypeDataContract(type, DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace);
                        }
                        else if (type == typeof(Array))
                            dataContract = new CollectionDataContract(type);
                        else if (type == typeof(XmlElement) || type == typeof(XmlNode[]))
                            dataContract = new XmlDataContract(type);
                        break;
                }
                return dataContract != null;
            }

            static public bool TryCreateBuiltInDataContract(string name, string ns, out DataContract dataContract)
            {
                dataContract = null;
                if (ns == DictionaryGlobals.SchemaNamespace.Value)
                {
                    if (DictionaryGlobals.BooleanLocalName.Value == name)
                        dataContract = new BooleanDataContract();
                    else if (DictionaryGlobals.SignedByteLocalName.Value == name)
                        dataContract = new SignedByteDataContract();
                    else if (DictionaryGlobals.UnsignedByteLocalName.Value == name)
                        dataContract = new UnsignedByteDataContract();
                    else if (DictionaryGlobals.ShortLocalName.Value == name)
                        dataContract = new ShortDataContract();
                    else if (DictionaryGlobals.UnsignedShortLocalName.Value == name)
                        dataContract = new UnsignedShortDataContract();
                    else if (DictionaryGlobals.IntLocalName.Value == name)
                        dataContract = new IntDataContract();
                    else if (DictionaryGlobals.UnsignedIntLocalName.Value == name)
                        dataContract = new UnsignedIntDataContract();
                    else if (DictionaryGlobals.LongLocalName.Value == name)
                        dataContract = new LongDataContract();
                    else if (DictionaryGlobals.integerLocalName.Value == name)
                        dataContract = new IntegerDataContract();
                    else if (DictionaryGlobals.positiveIntegerLocalName.Value == name)
                        dataContract = new PositiveIntegerDataContract();
                    else if (DictionaryGlobals.negativeIntegerLocalName.Value == name)
                        dataContract = new NegativeIntegerDataContract();
                    else if (DictionaryGlobals.nonPositiveIntegerLocalName.Value == name)
                        dataContract = new NonPositiveIntegerDataContract();
                    else if (DictionaryGlobals.nonNegativeIntegerLocalName.Value == name)
                        dataContract = new NonNegativeIntegerDataContract();
                    else if (DictionaryGlobals.UnsignedLongLocalName.Value == name)
                        dataContract = new UnsignedLongDataContract();
                    else if (DictionaryGlobals.FloatLocalName.Value == name)
                        dataContract = new FloatDataContract();
                    else if (DictionaryGlobals.DoubleLocalName.Value == name)
                        dataContract = new DoubleDataContract();
                    else if (DictionaryGlobals.DecimalLocalName.Value == name)
                        dataContract = new DecimalDataContract();
                    else if (DictionaryGlobals.DateTimeLocalName.Value == name)
                        dataContract = new DateTimeDataContract();
                    else if (DictionaryGlobals.StringLocalName.Value == name)
                        dataContract = new StringDataContract();
                    else if (DictionaryGlobals.timeLocalName.Value == name)
                        dataContract = new TimeDataContract();
                    else if (DictionaryGlobals.dateLocalName.Value == name)
                        dataContract = new DateDataContract();
                    else if (DictionaryGlobals.hexBinaryLocalName.Value == name)
                        dataContract = new HexBinaryDataContract();
                    else if (DictionaryGlobals.gYearMonthLocalName.Value == name)
                        dataContract = new GYearMonthDataContract();
                    else if (DictionaryGlobals.gYearLocalName.Value == name)
                        dataContract = new GYearDataContract();
                    else if (DictionaryGlobals.gMonthDayLocalName.Value == name)
                        dataContract = new GMonthDayDataContract();
                    else if (DictionaryGlobals.gDayLocalName.Value == name)
                        dataContract = new GDayDataContract();
                    else if (DictionaryGlobals.gMonthLocalName.Value == name)
                        dataContract = new GMonthDataContract();
                    else if (DictionaryGlobals.normalizedStringLocalName.Value == name)
                        dataContract = new NormalizedStringDataContract();
                    else if (DictionaryGlobals.tokenLocalName.Value == name)
                        dataContract = new TokenDataContract();
                    else if (DictionaryGlobals.languageLocalName.Value == name)
                        dataContract = new LanguageDataContract();
                    else if (DictionaryGlobals.NameLocalName.Value == name)
                        dataContract = new NameDataContract();
                    else if (DictionaryGlobals.NCNameLocalName.Value == name)
                        dataContract = new NCNameDataContract();
                    else if (DictionaryGlobals.XSDIDLocalName.Value == name)
                        dataContract = new IDDataContract();
                    else if (DictionaryGlobals.IDREFLocalName.Value == name)
                        dataContract = new IDREFDataContract();
                    else if (DictionaryGlobals.IDREFSLocalName.Value == name)
                        dataContract = new IDREFSDataContract();
                    else if (DictionaryGlobals.ENTITYLocalName.Value == name)
                        dataContract = new ENTITYDataContract();
                    else if (DictionaryGlobals.ENTITIESLocalName.Value == name)
                        dataContract = new ENTITIESDataContract();
                    else if (DictionaryGlobals.NMTOKENLocalName.Value == name)
                        dataContract = new NMTOKENDataContract();
                    else if (DictionaryGlobals.NMTOKENSLocalName.Value == name)
                        dataContract = new NMTOKENDataContract();
                    else if (DictionaryGlobals.ByteArrayLocalName.Value == name)
                        dataContract = new ByteArrayDataContract();
                    else if (DictionaryGlobals.ObjectLocalName.Value == name)
                        dataContract = new ObjectDataContract();
                    else if (DictionaryGlobals.TimeSpanLocalName.Value == name)
                        dataContract = new XsDurationDataContract();
                    else if (DictionaryGlobals.UriLocalName.Value == name)
                        dataContract = new UriDataContract();
                    else if (DictionaryGlobals.QNameLocalName.Value == name)
                        dataContract = new QNameDataContract();
                }
                else if (ns == DictionaryGlobals.SerializationNamespace.Value)
                {
                    if (DictionaryGlobals.TimeSpanLocalName.Value == name)
                        dataContract = new TimeSpanDataContract();
                    else if (DictionaryGlobals.GuidLocalName.Value == name)
                        dataContract = new GuidDataContract();
                    else if (DictionaryGlobals.CharLocalName.Value == name)
                        dataContract = new CharDataContract();
                    else if ("ArrayOfanyType" == name)
                        dataContract = new CollectionDataContract(typeof(Array));
                }
                else if (ns == DictionaryGlobals.AsmxTypesNamespace.Value)
                {
                    if (DictionaryGlobals.CharLocalName.Value == name)
                        dataContract = new AsmxCharDataContract();
                    else if (DictionaryGlobals.GuidLocalName.Value == name)
                        dataContract = new AsmxGuidDataContract();
                }
                else if (ns == Globals.DataContractXmlNamespace)
                {
                    if (name == "XmlElement")
                        dataContract = new XmlDataContract(typeof(XmlElement));
                    else if (name == "ArrayOfXmlNode")
                        dataContract = new XmlDataContract(typeof(XmlNode[]));
                }
                return dataContract != null;
            }

            internal static string GetNamespace(string key)
            {
                lock (namespacesLock)
                {
                    if (namespaces == null)
                        namespaces = new Dictionary<string, string>();
                    string value;
                    if (namespaces.TryGetValue(key, out value))
                        return value;
                    try
                    {
                        namespaces.Add(key, key);
                    }
                    catch (Exception ex)
                    {
                        if (Fx.IsFatal(ex))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
                    }
                    return key;
                }
            }

            internal static XmlDictionaryString GetClrTypeString(string key)
            {
                lock (clrTypeStringsLock)
                {
                    if (clrTypeStrings == null)
                    {
                        clrTypeStringsDictionary = new XmlDictionary();
                        clrTypeStrings = new Dictionary<string, XmlDictionaryString>();
                        try
                        {
                            clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName, clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName));
                        }
                        catch (Exception ex)
                        {
                            if (Fx.IsFatal(ex))
                            {
                                throw;
                            }
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
                        }
                    }
                    XmlDictionaryString value;
                    if (clrTypeStrings.TryGetValue(key, out value))
                        return value;
                    value = clrTypeStringsDictionary.Add(key);
                    try
                    {
                        clrTypeStrings.Add(key, value);
                    }
                    catch (Exception ex)
                    {
                        if (Fx.IsFatal(ex))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
                    }
                    return value;
                }
            }

            internal static void ThrowInvalidDataContractException(string message, Type type)
            {
                if (type != null)
                {
                    lock (cacheLock)
                    {
                        typeHandleRef.Value = GetDataContractAdapterTypeHandle(type.TypeHandle);
                        try
                        {
                            typeToIDCache.Remove(typeHandleRef);
                        }
                        catch (Exception ex)
                        {
                            if (Fx.IsFatal(ex))
                            {
                                throw;
                            }
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
                        }
                    }
                }

                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(message));
            }

            internal DataContractCriticalHelper()
            {
            }

            internal DataContractCriticalHelper(Type type)
            {
                underlyingType = type;
                SetTypeForInitialization(type);
                isValueType = type.IsValueType;
            }

            internal Type UnderlyingType
            {
                get { return underlyingType; }
            }

            internal Type OriginalUnderlyingType
            {
                get
                {
                    if (this.originalUnderlyingType == null)
                    {
                        this.originalUnderlyingType = GetDataContractOriginalType(this.underlyingType);
                    }
                    return this.originalUnderlyingType;
                }
            }

            internal virtual bool IsBuiltInDataContract
            {
                get
                {
                    return false;
                }
            }

            internal Type TypeForInitialization
            {
                get { return this.typeForInitialization; }
            }

            [Fx.Tag.SecurityNote(Critical = "Sets the critical typeForInitialization property.",
                Safe = "Validates input data, sets field correctly.")]
            [SecuritySafeCritical]
            void SetTypeForInitialization(Type classType)
            {
                if (classType.IsSerializable || classType.IsDefined(Globals.TypeOfDataContractAttribute, false))
                {
                    this.typeForInitialization = classType;
                }
            }

            internal bool IsReference
            {
                get { return isReference; }
                set
                {
                    isReference = value;
                }
            }

            internal bool IsValueType
            {
                get { return isValueType; }
                set { isValueType = value; }
            }

            internal XmlQualifiedName StableName
            {
                get { return stableName; }
                set { stableName = value; }
            }

            internal GenericInfo GenericInfo
            {
                get { return genericInfo; }
                set { genericInfo = value; }
            }

            internal virtual DataContractDictionary KnownDataContracts
            {
                get { return null; }
                set { /* do nothing */ }
            }

            internal virtual bool IsISerializable
            {
                get { return false; }
                set { ThrowInvalidDataContractException(SR.GetString(SR.RequiresClassDataContractToSetIsISerializable)); }
            }

            internal XmlDictionaryString Name
            {
                get { return name; }
                set { name = value; }
            }

            public XmlDictionaryString Namespace
            {
                get { return ns; }
                set { ns = value; }
            }

            internal virtual bool HasRoot
            {
                get { return true; }
                set { }
            }

            internal virtual XmlDictionaryString TopLevelElementName
            {
                get { return name; }
                set { name = value; }
            }

            internal virtual XmlDictionaryString TopLevelElementNamespace
            {
                get { return ns; }
                set { ns = value; }
            }

            internal virtual bool CanContainReferences
            {
                get { return true; }
            }

            internal virtual bool IsPrimitive
            {
                get { return false; }
            }

            internal MethodInfo ParseMethod
            {
                get 
                {
                    if (!parseMethodSet)
                    {
                        MethodInfo method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, null, new Type[] { Globals.TypeOfString }, null);

                        if (method != null && method.ReturnType == UnderlyingType)
                        {
                            parseMethod = method;
                        }

                        parseMethodSet = true;
                    }
                    return parseMethod; }
            }

            internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
            {
                if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive)
                    writer.WriteStartElement(Globals.SerPrefix, name, ns);
                else
                    writer.WriteStartElement(name, ns);
            }

            internal void SetDataContractName(XmlQualifiedName stableName)
            {
                XmlDictionary dictionary = new XmlDictionary(2);
                this.Name = dictionary.Add(stableName.Name);
                this.Namespace = dictionary.Add(stableName.Namespace);
                this.StableName = stableName;
            }

            internal void SetDataContractName(XmlDictionaryString name, XmlDictionaryString ns)
            {
                this.Name = name;
                this.Namespace = ns;
                this.StableName = CreateQualifiedName(name.Value, ns.Value);
            }

            internal void ThrowInvalidDataContractException(string message)
            {
                ThrowInvalidDataContractException(message, UnderlyingType);
            }
        }

        static internal bool IsTypeSerializable(Type type)
        {
            return IsTypeSerializable(type, new Dictionary<Type, object>());
        }

        static bool IsTypeSerializable(Type type, Dictionary<Type, object> previousCollectionTypes)
        {
            Type itemType;
            if (type.IsSerializable ||
                type.IsDefined(Globals.TypeOfDataContractAttribute, false) ||
                type.IsInterface ||
                type.IsPointer ||
                Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
            {
                return true;
            }
            if (CollectionDataContract.IsCollection(type, out itemType))
            {
                ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes);
                if (IsTypeSerializable(itemType, previousCollectionTypes))
                {
                    return true;
                }
            }
            return (DataContract.GetBuiltInDataContract(type) != null || ClassDataContract.IsNonAttributedTypeValidForSerialization(type));
        }

        [SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "previousCollectionTypes", Justification = "No need to support type equivalence here.")]
        static void ValidatePreviousCollectionTypes(Type collectionType, Type itemType, Dictionary<Type, object> previousCollectionTypes)
        {
            previousCollectionTypes.Add(collectionType, collectionType);
            while (itemType.IsArray)
            {
                itemType = itemType.GetElementType();
            }

            // Do a breadth first traversal of the generic type tree to 
            // produce the closure of all generic argument types and
            // check that none of these is in the previousCollectionTypes            
            
            List<Type> itemTypeClosure = new List<Type>();
            Queue<Type> itemTypeQueue = new Queue<Type>();

            itemTypeQueue.Enqueue(itemType);
            itemTypeClosure.Add(itemType);
                       
            while (itemTypeQueue.Count > 0)
            {
                itemType = itemTypeQueue.Dequeue();
                if (previousCollectionTypes.ContainsKey(itemType))
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.RecursiveCollectionType, DataContract.GetClrTypeFullName(itemType))));
                }
                if (itemType.IsGenericType)
                {
                    foreach (Type argType in itemType.GetGenericArguments())
                    {
                        if (!itemTypeClosure.Contains(argType))
                        {
                            itemTypeQueue.Enqueue(argType);
                            itemTypeClosure.Add(argType);
                        }
                    }
                }
            }
        }

        internal static Type UnwrapRedundantNullableType(Type type)
        {
            Type nullableType = type;
            while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
            {
                nullableType = type;
                type = type.GetGenericArguments()[0];
            }
            return nullableType;
        }

        internal static Type UnwrapNullableType(Type type)
        {
            while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
                type = type.GetGenericArguments()[0];
            return type;
        }

        static bool IsAlpha(char ch)
        {
            return (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z');
        }

        static bool IsDigit(char ch)
        {
            return (ch >= '0' && ch <= '9');
        }

        static bool IsAsciiLocalName(string localName)
        {
            if (localName.Length == 0)
                return false;
            if (!IsAlpha(localName[0]))
                return false;
            for (int i = 1; i < localName.Length; i++)
            {
                char ch = localName[i];
                if (!IsAlpha(ch) && !IsDigit(ch))
                    return false;
            }
            return true;
        }

        static internal string EncodeLocalName(string localName)
        {
            if (IsAsciiLocalName(localName))
                return localName;

            if (IsValidNCName(localName))
                return localName;

            return XmlConvert.EncodeLocalName(localName);
        }

        internal static bool IsValidNCName(string name)
        {
            try
            {
                XmlConvert.VerifyNCName(name);
                return true;
            }
            catch (XmlException)
            {
                return false;
            }
        }

        internal static XmlQualifiedName GetStableName(Type type)
        {
            bool hasDataContract;
            return GetStableName(type, out hasDataContract);
        }

        internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContract)
        {
            return GetStableName(type, new Dictionary<Type, object>(), out hasDataContract);
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Callers may need to depend on hasDataContract for a security decision."
            + " hasDataContract must be calculated correctly."
            + " GetStableName is factored into sub-methods so as to isolate the DataContractAttribute calculation and reduce SecurityCritical surface area.",
            Safe = "Does not let caller influence hasDataContract calculation; no harm in leaking value.")]
        static XmlQualifiedName GetStableName(Type type, Dictionary<Type, object> previousCollectionTypes, out bool hasDataContract)
        {
            type = UnwrapRedundantNullableType(type);
            XmlQualifiedName stableName;
            if (TryGetBuiltInXmlAndArrayTypeStableName(type, previousCollectionTypes, out stableName))
            {
                hasDataContract = false;
            }
            else
            {
                DataContractAttribute dataContractAttribute;
                if (TryGetDCAttribute(type, out dataContractAttribute))
                {
                    stableName = GetDCTypeStableName(type, dataContractAttribute);
                    hasDataContract = true;
                }
                else
                {
                    stableName = GetNonDCTypeStableName(type, previousCollectionTypes);
                    hasDataContract = false;
                }
            }

            return stableName;
        }

        static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute)
        {
            string name = null, ns = null;
            if (dataContractAttribute.IsNameSetExplicitly)
            {
                name = dataContractAttribute.Name;
                if (name == null || name.Length == 0)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidDataContractName, DataContract.GetClrTypeFullName(type))));
                if (type.IsGenericType && !type.IsGenericTypeDefinition)
                    name = ExpandGenericParameters(name, type);
                name = DataContract.EncodeLocalName(name);
            }
            else
                name = GetDefaultStableLocalName(type);

            if (dataContractAttribute.IsNamespaceSetExplicitly)
            {
                ns = dataContractAttribute.Namespace;
                if (ns == null)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidDataContractNamespace, DataContract.GetClrTypeFullName(type))));
                CheckExplicitDataContractNamespaceUri(ns, type);
            }
            else
                ns = GetDefaultDataContractNamespace(type);

            return CreateQualifiedName(name, ns);
        }

        static XmlQualifiedName GetNonDCTypeStableName(Type type, Dictionary<Type, object> previousCollectionTypes)
        {
            string name = null, ns = null;

            Type itemType;
            CollectionDataContractAttribute collectionContractAttribute;
            if (CollectionDataContract.IsCollection(type, out itemType))
            {
                ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes);
                return GetCollectionStableName(type, itemType, previousCollectionTypes, out collectionContractAttribute);
            }
            name = GetDefaultStableLocalName(type);

            // ensures that ContractNamespaceAttribute is honored when used with non-attributed types
            if (ClassDataContract.IsNonAttributedTypeValidForSerialization(type))
            {
                ns = GetDefaultDataContractNamespace(type);
            }
            else
            {
                ns = GetDefaultStableNamespace(type);
            }
            return CreateQualifiedName(name, ns);
        }

        static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, Dictionary<Type, object> previousCollectionTypes, out XmlQualifiedName stableName)
        {
            stableName = null;

            DataContract builtInContract = GetBuiltInDataContract(type);
            if (builtInContract != null)
            {
                stableName = builtInContract.StableName;
            }
            else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
            {
                bool hasRoot;
                XmlSchemaType xsdType;
                XmlQualifiedName xmlTypeStableName;
                SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out xsdType, out hasRoot);
                stableName = xmlTypeStableName;
            }
            else if (type.IsArray)
            {
                Type itemType = type.GetElementType();
                ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes);
                CollectionDataContractAttribute collectionContractAttribute;
                stableName = GetCollectionStableName(type, itemType, previousCollectionTypes, out collectionContractAttribute);
            }
            return stableName != null;
        }

        [Fx.Tag.SecurityNote(Critical = "Marked SecurityCritical because callers may need to base security decisions on the presence (or absence) of the DC attribute.",
            Safe = "Does not let caller influence calculation and the result is not a protected value.")]
        [SecuritySafeCritical]
        internal static bool TryGetDCAttribute(Type type, out DataContractAttribute dataContractAttribute)
        {
            dataContractAttribute = null;

            object[] dataContractAttributes = type.GetCustomAttributes(Globals.TypeOfDataContractAttribute, false);
            if (dataContractAttributes != null && dataContractAttributes.Length > 0)
            {
#if DEBUG
                if (dataContractAttributes.Length > 1)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TooManyDataContracts, DataContract.GetClrTypeFullName(type))));
#endif
                dataContractAttribute = (DataContractAttribute)dataContractAttributes[0];
            }

            return dataContractAttribute != null;
        }

        internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute collectionContractAttribute)
        {
            return GetCollectionStableName(type, itemType, new Dictionary<Type, object>(), out collectionContractAttribute);
        }

        static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, Dictionary<Type, object> previousCollectionTypes, out CollectionDataContractAttribute collectionContractAttribute)
        {
            string name, ns;
            object[] collectionContractAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, false);
            if (collectionContractAttributes != null && collectionContractAttributes.Length > 0)
            {
#if DEBUG
                if (collectionContractAttributes.Length > 1)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TooManyCollectionContracts, DataContract.GetClrTypeFullName(type))));
#endif
                collectionContractAttribute = (CollectionDataContractAttribute)collectionContractAttributes[0];
                if (collectionContractAttribute.IsNameSetExplicitly)
                {
                    name = collectionContractAttribute.Name;
                    if (name == null || name.Length == 0)
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractName, DataContract.GetClrTypeFullName(type))));
                    if (type.IsGenericType && !type.IsGenericTypeDefinition)
                        name = ExpandGenericParameters(name, type);
                    name = DataContract.EncodeLocalName(name);
                }
                else
                    name = GetDefaultStableLocalName(type);

                if (collectionContractAttribute.IsNamespaceSetExplicitly)
                {
                    ns = collectionContractAttribute.Namespace;
                    if (ns == null)
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractNamespace, DataContract.GetClrTypeFullName(type))));
                    CheckExplicitDataContractNamespaceUri(ns, type);
                }
                else
                    ns = GetDefaultDataContractNamespace(type);
            }
            else
            {
                collectionContractAttribute = null;
                string arrayOfPrefix = Globals.ArrayPrefix + GetArrayPrefix(ref itemType);
                bool hasDataContract;
                XmlQualifiedName elementStableName = GetStableName(itemType, previousCollectionTypes, out hasDataContract);
                name = arrayOfPrefix + elementStableName.Name;
                ns = GetCollectionNamespace(elementStableName.Namespace);
            }
            return CreateQualifiedName(name, ns);
        }

        private static string GetArrayPrefix(ref Type itemType)
        {
            string arrayOfPrefix = string.Empty;
            while (itemType.IsArray)
            {
                if (DataContract.GetBuiltInDataContract(itemType) != null)
                    break;
                arrayOfPrefix += Globals.ArrayPrefix;
                itemType = itemType.GetElementType();
            }
            return arrayOfPrefix;
        }

        internal XmlQualifiedName GetArrayTypeName(bool isNullable)
        {
            XmlQualifiedName itemName;
            if (this.IsValueType && isNullable)
            {
                GenericInfo genericInfo = new GenericInfo(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable.FullName);
                genericInfo.Add(new GenericInfo(this.StableName, null));
                genericInfo.AddToLevel(0, 1);
                itemName = genericInfo.GetExpandedStableName();
            }
            else
                itemName = this.StableName;
            string ns = GetCollectionNamespace(itemName.Namespace);
            string name = Globals.ArrayPrefix + itemName.Name;
            return new XmlQualifiedName(name, ns);
        }

        internal static string GetCollectionNamespace(string elementNs)
        {
            return IsBuiltInNamespace(elementNs) ? Globals.CollectionsNamespace : elementNs;
        }

        internal static XmlQualifiedName GetDefaultStableName(Type type)
        {
            return CreateQualifiedName(GetDefaultStableLocalName(type), GetDefaultStableNamespace(type));
        }

        static string GetDefaultStableLocalName(Type type)
        {
            if (type.IsGenericParameter)
                return "{" + type.GenericParameterPosition + "}";
            string typeName;
            string arrayPrefix = null;
            if (type.IsArray)
                arrayPrefix = GetArrayPrefix(ref type);
            if (type.DeclaringType == null)
                typeName = type.Name;
            else
            {
                int nsLen = (type.Namespace == null) ? 0 : type.Namespace.Length;
                if (nsLen > 0)
                    nsLen++; //include the . following namespace
                typeName = DataContract.GetClrTypeFullName(type).Substring(nsLen).Replace('+', '.');
            }
            if (arrayPrefix != null)
                typeName = arrayPrefix + typeName;
            if (type.IsGenericType)
            {
                StringBuilder localName = new StringBuilder();
                StringBuilder namespaces = new StringBuilder();
                bool parametersFromBuiltInNamespaces = true;
                int iParam = typeName.IndexOf('[');
                if (iParam >= 0)
                    typeName = typeName.Substring(0, iParam);
                IList<int> nestedParamCounts = GetDataContractNameForGenericName(typeName, localName);
                bool isTypeOpenGeneric = type.IsGenericTypeDefinition;
                Type[] genParams = type.GetGenericArguments();
                for (int i = 0; i < genParams.Length; i++)
                {
                    Type genParam = genParams[i];
                    if (isTypeOpenGeneric)
                        localName.Append("{").Append(i).Append("}");
                    else
                    {
                        XmlQualifiedName qname = DataContract.GetStableName(genParam);
                        localName.Append(qname.Name);
                        namespaces.Append(" ").Append(qname.Namespace);
                        if (parametersFromBuiltInNamespaces)
                            parametersFromBuiltInNamespaces = IsBuiltInNamespace(qname.Namespace);
                    }
                }
                if (isTypeOpenGeneric)
                    localName.Append("{#}");
                else if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces)
                {
                    foreach (int count in nestedParamCounts)
                        namespaces.Insert(0, count).Insert(0, " ");
                    localName.Append(GetNamespacesDigest(namespaces.ToString()));
                }
                typeName = localName.ToString();
            }
            return DataContract.EncodeLocalName(typeName);
        }

        static string GetDefaultDataContractNamespace(Type type)
        {
            string clrNs = type.Namespace;
            if (clrNs == null)
                clrNs = String.Empty;
            string ns = GetGlobalDataContractNamespace(clrNs, type.Module);
            if (ns == null)
                ns = GetGlobalDataContractNamespace(clrNs, type.Assembly);

            if (ns == null)
                ns = GetDefaultStableNamespace(type);
            else
                CheckExplicitDataContractNamespaceUri(ns, type);
            return ns;
        }

        internal static IList<int> GetDataContractNameForGenericName(string typeName, StringBuilder localName)
        {
            List<int> nestedParamCounts = new List<int>();
            for (int startIndex = 0, endIndex;;)
            {
                endIndex = typeName.IndexOf('`', startIndex);
                if (endIndex < 0)
                {
                    if (localName != null)
                        localName.Append(typeName.Substring(startIndex));
                    nestedParamCounts.Add(0);
                    break;
                }
                if (localName != null)
                    localName.Append(typeName.Substring(startIndex, endIndex - startIndex));
                while ((startIndex = typeName.IndexOf('.', startIndex + 1, endIndex - startIndex - 1)) >= 0)
                    nestedParamCounts.Add(0);
                startIndex = typeName.IndexOf('.', endIndex);
                if (startIndex < 0)
                {
                    nestedParamCounts.Add(Int32.Parse(typeName.Substring(endIndex + 1), CultureInfo.InvariantCulture));
                    break;
                }
                else
                    nestedParamCounts.Add(Int32.Parse(typeName.Substring(endIndex + 1, startIndex - endIndex - 1), CultureInfo.InvariantCulture));
            }
            if (localName != null)
                localName.Append("Of");
            return nestedParamCounts;
        }

        internal static bool IsBuiltInNamespace(string ns)
        {
            return (ns == Globals.SchemaNamespace || ns == Globals.SerializationNamespace);
        }

        internal static string GetDefaultStableNamespace(Type type)
        {
            if (type.IsGenericParameter)
                return "{ns}";
            return GetDefaultStableNamespace(type.Namespace);
        }

        internal static XmlQualifiedName CreateQualifiedName(string localName, string ns)
        {
            return new XmlQualifiedName(localName, GetNamespace(ns));
        }

        internal static string GetDefaultStableNamespace(string clrNs)
        {
            if (clrNs == null) clrNs = String.Empty;
            return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri;
        }

        static void CheckExplicitDataContractNamespaceUri(string dataContractNs, Type type)
        {
            if (dataContractNs.Length > 0)
            {
                string trimmedNs = dataContractNs.Trim();
                // Code similar to XmlConvert.ToUri (string.Empty is a valid uri but not "   ")
                if (trimmedNs.Length == 0 || trimmedNs.IndexOf("##", StringComparison.Ordinal) != -1)
                    ThrowInvalidDataContractException(SR.GetString(SR.DataContractNamespaceIsNotValid, dataContractNs), type);
                dataContractNs = trimmedNs;
            }
            Uri uri;
            if (Uri.TryCreate(dataContractNs, UriKind.RelativeOrAbsolute, out uri))
            {
                if (uri.ToString() == Globals.SerializationNamespace)
                    ThrowInvalidDataContractException(SR.GetString(SR.DataContractNamespaceReserved, Globals.SerializationNamespace), type);
            }
            else
                ThrowInvalidDataContractException(SR.GetString(SR.DataContractNamespaceIsNotValid, dataContractNs), type);
        }

        internal static string GetClrTypeFullName(Type type)
        {
            return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? String.Format(CultureInfo.InvariantCulture, "{0}.{1}", type.Namespace, type.Name) : type.FullName;
        }

        internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom)
        {
            hasTypeForwardedFrom = false;
            object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false);
            if (typeAttributes != null && typeAttributes.Length > 0)
            {
                TypeForwardedFromAttribute typeForwardedFromAttribute = (TypeForwardedFromAttribute)typeAttributes[0];
                hasTypeForwardedFrom = true;
                return typeForwardedFromAttribute.AssemblyFullName;
            }
            else
            {
                return type.Assembly.FullName;
            }
        }

        internal static string GetClrTypeFullNameUsingTypeForwardedFromAttribute(Type type)
        {
            if (type.IsArray)
            {
                return GetClrTypeFullNameForArray(type);
            }
            else
            {
                return GetClrTypeFullNameForNonArrayTypes(type);
            }
        }

        static string GetClrTypeFullNameForArray(Type type)
        {
            return String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}",
                GetClrTypeFullNameUsingTypeForwardedFromAttribute(type.GetElementType()), Globals.OpenBracket, Globals.CloseBracket);
        }

        static string GetClrTypeFullNameForNonArrayTypes(Type type)
        {
            if (!type.IsGenericType)
            {
                return DataContract.GetClrTypeFullName(type);
            }

            Type[] genericArguments = type.GetGenericArguments();
            StringBuilder builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append(Globals.OpenBracket);

            foreach (Type genericArgument in genericArguments)
            {
                bool hasTypeForwardedFrom;
                builder.Append(Globals.OpenBracket).Append(GetClrTypeFullNameUsingTypeForwardedFromAttribute(genericArgument)).Append(Globals.Comma);
                builder.Append(Globals.Space).Append(GetClrAssemblyName(genericArgument, out hasTypeForwardedFrom));
                builder.Append(Globals.CloseBracket).Append(Globals.Comma);
            }

            //remove the last comma and close typename for generic with a close bracket
            return builder.Remove(builder.Length - 1, 1).Append(Globals.CloseBracket).ToString();
        }

        internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns)
        {
            int nsEnd = fullTypeName.LastIndexOf('.');
            if (nsEnd < 0)
            {
                ns = String.Empty;
                localName = fullTypeName.Replace('+', '.');
            }
            else
            {
                ns = fullTypeName.Substring(0, nsEnd);
                localName = fullTypeName.Substring(nsEnd + 1).Replace('+', '.');
            }
            int iParam = localName.IndexOf('[');
            if (iParam >= 0)
                localName = localName.Substring(0, iParam);
        }

        internal static void GetDefaultStableName(string fullTypeName, out string localName, out string ns)
        {
            CodeTypeReference typeReference = new CodeTypeReference(fullTypeName);
            GetDefaultStableName(typeReference, out localName, out ns);
        }

        static void GetDefaultStableName(CodeTypeReference typeReference, out string localName, out string ns)
        {
            string fullTypeName = typeReference.BaseType;
            DataContract dataContract = GetBuiltInDataContract(fullTypeName);
            if (dataContract != null)
            {
                localName = dataContract.StableName.Name;
                ns = dataContract.StableName.Namespace;
                return;
            }
            GetClrNameAndNamespace(fullTypeName, out localName, out ns);
            if (typeReference.TypeArguments.Count > 0)
            {
                StringBuilder localNameBuilder = new StringBuilder();
                StringBuilder argNamespacesBuilder = new StringBuilder();
                bool parametersFromBuiltInNamespaces = true;
                IList<int> nestedParamCounts = GetDataContractNameForGenericName(localName, localNameBuilder);
                foreach (CodeTypeReference typeArg in typeReference.TypeArguments)
                {
                    string typeArgName, typeArgNs;
                    GetDefaultStableName(typeArg, out typeArgName, out typeArgNs);
                    localNameBuilder.Append(typeArgName);
                    argNamespacesBuilder.Append(" ").Append(typeArgNs);
                    if (parametersFromBuiltInNamespaces)
                        parametersFromBuiltInNamespaces = IsBuiltInNamespace(typeArgNs);
                }
                if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces)
                {
                    foreach (int count in nestedParamCounts)
                        argNamespacesBuilder.Insert(0, count).Insert(0, " ");
                    localNameBuilder.Append(GetNamespacesDigest(argNamespacesBuilder.ToString()));
                }
                localName = localNameBuilder.ToString();
            }
            localName = DataContract.EncodeLocalName(localName);
            ns = GetDefaultStableNamespace(ns);
        }

        internal static string GetDataContractNamespaceFromUri(string uriString)
        {
            return uriString.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal) ? uriString.Substring(Globals.DataContractXsdBaseNamespace.Length) : uriString;
        }

        static string GetGlobalDataContractNamespace(string clrNs, ICustomAttributeProvider customAttribuetProvider)
        {
            object[] nsAttributes = customAttribuetProvider.GetCustomAttributes(typeof(ContractNamespaceAttribute), false);
            string dataContractNs = null;
            for (int i = 0; i < nsAttributes.Length; i++)
            {
                ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i];
                string clrNsInAttribute = nsAttribute.ClrNamespace;
                if (clrNsInAttribute == null)
                    clrNsInAttribute = String.Empty;
                if (clrNsInAttribute == clrNs)
                {
                    if (nsAttribute.ContractNamespace == null)
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidGlobalDataContractNamespace, clrNs)));
                    if (dataContractNs != null)
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.DataContractNamespaceAlreadySet, dataContractNs, nsAttribute.ContractNamespace, clrNs)));
                    dataContractNs = nsAttribute.ContractNamespace;
                }
            }
            return dataContractNs;
        }

        private static string GetNamespacesDigest(string namespaces)
        {
            byte[] namespaceBytes = Encoding.UTF8.GetBytes(namespaces);
            byte[] digestBytes = HashHelper.ComputeHash(namespaceBytes);
            char[] digestChars = new char[24];
            const int digestLen = 6;
            int digestCharsLen = Convert.ToBase64CharArray(digestBytes, 0, digestLen, digestChars, 0);
            StringBuilder digest = new StringBuilder();
            for (int i = 0; i < digestCharsLen; i++)
            {
                char ch = digestChars[i];
                switch (ch)
                {
                    case '=':
                        break;
                    case '/':
                        digest.Append("_S");
                        break;
                    case '+':
                        digest.Append("_P");
                        break;
                    default:
                        digest.Append(ch);
                        break;
                }
            }
            return digest.ToString();
        }

        private static string ExpandGenericParameters(string format, Type type)
        {
            GenericNameProvider genericNameProviderForType = new GenericNameProvider(type);
            return ExpandGenericParameters(format, genericNameProviderForType);
        }

        internal static string ExpandGenericParameters(string format, IGenericNameProvider genericNameProvider)
        {
            string digest = null;
            StringBuilder typeName = new StringBuilder();
            IList<int> nestedParameterCounts = genericNameProvider.GetNestedParameterCounts();
            for (int i = 0; i < format.Length; i++)
            {
                char ch = format[i];
                if (ch == '{')
                {
                    i++;
                    int start = i;
                    for (; i < format.Length; i++)
                        if (format[i] == '}')
                            break;
                    if (i == format.Length)
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericNameBraceMismatch, format, genericNameProvider.GetGenericTypeName())));
                    if (format[start] == '#' && i == (start + 1))
                    {
                        if (nestedParameterCounts.Count > 1 || !genericNameProvider.ParametersFromBuiltInNamespaces)
                        {
                            if (digest == null)
                            {
                                StringBuilder namespaces = new StringBuilder(genericNameProvider.GetNamespaces());
                                foreach (int count in nestedParameterCounts)
                                    namespaces.Insert(0, count).Insert(0, " ");
                                digest = GetNamespacesDigest(namespaces.ToString());
                            }
                            typeName.Append(digest);
                        }
                    }
                    else
                    {
                        int paramIndex;
                        if (!Int32.TryParse(format.Substring(start, i - start), out paramIndex) || paramIndex < 0 || paramIndex >= genericNameProvider.GetParameterCount())
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericParameterNotValid, format.Substring(start, i - start), genericNameProvider.GetGenericTypeName(), genericNameProvider.GetParameterCount() - 1)));
                        typeName.Append(genericNameProvider.GetParameterName(paramIndex));
                    }
                }
                else
                    typeName.Append(ch);
            }
            return typeName.ToString();
        }

        static internal bool IsTypeNullable(Type type)
        {
            return !type.IsValueType ||
                    (type.IsGenericType &&
                    type.GetGenericTypeDefinition() == Globals.TypeOfNullable);
        }

        public static void ThrowTypeNotSerializable(Type type)
        {
            ThrowInvalidDataContractException(SR.GetString(SR.TypeNotSerializable, type), type);
        }

#if !NO_CONFIGURATION
        [Fx.Tag.SecurityNote(Critical = "configSection value is fetched under an elevation; need to protected access to it.")]
        [SecurityCritical]
        static DataContractSerializerSection configSection;
        static DataContractSerializerSection ConfigSection
        {
            [Fx.Tag.SecurityNote(Critical = "Calls Security Critical method DataContractSerializerSection.UnsafeGetSection and stores result in"
                + " SecurityCritical field configSection.")]
            [SecurityCritical]
            get
            {
                if (configSection == null)
                    configSection = DataContractSerializerSection.UnsafeGetSection();
                return configSection;
            }
        }
#endif

        internal static DataContractDictionary ImportKnownTypeAttributes(Type type)
        {
            DataContractDictionary knownDataContracts = null;
            Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>();
            ImportKnownTypeAttributes(type, typesChecked, ref knownDataContracts);
            return knownDataContracts;
        }

        [SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "typesChecked", Justification = "No need to support type equivalence here.")]
        static void ImportKnownTypeAttributes(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary knownDataContracts)
        {
            if (TD.ImportKnownTypesStartIsEnabled())
            {
                TD.ImportKnownTypesStart();
            }

            while (type != null && DataContract.IsTypeSerializable(type))
            {
                if (typesChecked.ContainsKey(type))
                    return;

                typesChecked.Add(type, type);
                object[] knownTypeAttributes = type.GetCustomAttributes(Globals.TypeOfKnownTypeAttribute, false);
                if (knownTypeAttributes != null)
                {
                    KnownTypeAttribute kt;
                    bool useMethod = false, useType = false;
                    for (int i = 0; i < knownTypeAttributes.Length; ++i)
                    {
                        kt = (KnownTypeAttribute)knownTypeAttributes[i];
                        if (kt.Type != null)
                        {
                            if (useMethod)
                            {
                                DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type);
                            }

                            CheckAndAdd(kt.Type, typesChecked, ref knownDataContracts);
                            useType = true;
                        }
                        else
                        {
                            if (useMethod || useType)
                            {
                                DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type);
                            }

                            string methodName = kt.MethodName;
                            if (methodName == null)
                            {
                                DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeNoData, DataContract.GetClrTypeFullName(type)), type);
                            }

                            if (methodName.Length == 0)
                                DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeEmptyString, DataContract.GetClrTypeFullName(type)), type);

                            MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
                            if (method == null)
                                DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeUnknownMethod, methodName, DataContract.GetClrTypeFullName(type)), type);

                            if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType))
                                DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeReturnType, DataContract.GetClrTypeFullName(type), methodName), type);

                            object types = method.Invoke(null, Globals.EmptyObjectArray);
                            if (types == null)
                            {
                                DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeMethodNull, DataContract.GetClrTypeFullName(type)), type);
                            }

                            foreach (Type ty in (IEnumerable<Type>)types)
                            {
                                if (ty == null)
                                    DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeValidMethodTypes, DataContract.GetClrTypeFullName(type)), type);

                                CheckAndAdd(ty, typesChecked, ref knownDataContracts);
                            }

                            useMethod = true;
                        }
                    }
                }

                LoadKnownTypesFromConfig(type, typesChecked, ref knownDataContracts);

                type = type.BaseType;
            }

            if (TD.ImportKnownTypesStopIsEnabled())
            {
                TD.ImportKnownTypesStop();
            }
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical property ConfigSection.",
            Safe = "Completely processes ConfigSection and only makes available the processed result."
            + " The ConfigSection instance is not leaked.")]
        [SecuritySafeCritical]
        static void LoadKnownTypesFromConfig(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary knownDataContracts)
        {
#if !NO_CONFIGURATION
            // Pull known types from config
            if (ConfigSection != null)
            {
                DeclaredTypeElementCollection elements = ConfigSection.DeclaredTypes;

                Type rootType = type;
                Type[] genArgs = null;

                CheckRootTypeInConfigIsGeneric(type, ref rootType, ref genArgs);

                DeclaredTypeElement elem = elements[rootType.AssemblyQualifiedName];
                if (elem != null)
                {
                    if (IsElemTypeNullOrNotEqualToRootType(elem.Type, rootType))
                    {
                        elem = null;
                    }
                }

                if (elem == null)
                {
                    for (int i = 0; i < elements.Count; ++i)
                    {
                        if (IsCollectionElementTypeEqualToRootType(elements[i].Type, rootType))
                        {
                            elem = elements[i];
                            break;
                        }
                    }
                }

                if (elem != null)
                {
                    for (int i = 0; i < elem.KnownTypes.Count; ++i)
                    {
                        Type knownType = elem.KnownTypes[i].GetType(elem.Type, genArgs);
                        if (knownType != null)
                        {
                            CheckAndAdd(knownType, typesChecked, ref knownDataContracts);
                        }
                    }
                }
            }
#endif
        }

        private static void CheckRootTypeInConfigIsGeneric(Type type, ref Type rootType, ref Type[] genArgs)
        {
            if (rootType.IsGenericType)
            {
                if (!rootType.ContainsGenericParameters)
                {
                    genArgs = rootType.GetGenericArguments();
                    rootType = rootType.GetGenericTypeDefinition();
                }
                else
                {
                    DataContract.ThrowInvalidDataContractException(SR.GetString(SR.TypeMustBeConcrete, type), type);
                }
            }
        }

        private static bool IsElemTypeNullOrNotEqualToRootType(string elemTypeName, Type rootType)
        {
            Type t = Type.GetType(elemTypeName, false);
            if (t == null || !rootType.Equals(t))
            {
                return true;
            }
            return false;
        }

        private static bool IsCollectionElementTypeEqualToRootType(string collectionElementTypeName, Type rootType)
        {
            if (collectionElementTypeName.StartsWith(DataContract.GetClrTypeFullName(rootType), StringComparison.Ordinal))
            {
                Type t = Type.GetType(collectionElementTypeName, false);
                if (t != null)
                {
                    if (t.IsGenericType && !IsOpenGenericType(t))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.KnownTypeConfigClosedGenericDeclared, collectionElementTypeName)));
                    }
                    else if (rootType.Equals(t))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        [Fx.Tag.SecurityNote(Critical = "Fetches the critical dataContractAdapterType.",
            Safe = "The critical dataContractAdapterType is only used for local comparison and is not leaked beyond this method.")]
        [SecurityCritical, SecurityTreatAsSafe]
        internal static void CheckAndAdd(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary nameToDataContractTable)
        {
            type = DataContract.UnwrapNullableType(type);
            DataContract dataContract = DataContract.GetDataContract(type);
            DataContract alreadyExistingContract;
            if (nameToDataContractTable == null)
            {
                nameToDataContractTable = new DataContractDictionary();
            }
            else if (nameToDataContractTable.TryGetValue(dataContract.StableName, out alreadyExistingContract))
            {
                if (alreadyExistingContract.UnderlyingType != DataContractCriticalHelper.GetDataContractAdapterType(type))
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DupContractInKnownTypes, type, alreadyExistingContract.UnderlyingType, dataContract.StableName.Namespace, dataContract.StableName.Name)));
                return;
            }
            nameToDataContractTable.Add(dataContract.StableName, dataContract);
            ImportKnownTypeAttributes(type, typesChecked, ref nameToDataContractTable);
        }

        static bool IsOpenGenericType(Type t)
        {
            Type[] args = t.GetGenericArguments();
            for (int i = 0; i < args.Length; ++i)
                if (!args[i].IsGenericParameter)
                    return false;

            return true;
        }

        public sealed override bool Equals(object other)
        {
            if ((object)this == other)
                return true;
            return Equals(other, new Dictionary<DataContractPairKey, object>());
        }

        internal virtual bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts)
        {
            DataContract dataContract = other as DataContract;
            if (dataContract != null)
            {
                return (StableName.Name == dataContract.StableName.Name && StableName.Namespace == dataContract.StableName.Namespace && IsReference == dataContract.IsReference);
            }
            return false;
        }

        internal bool IsEqualOrChecked(object other, Dictionary<DataContractPairKey, object> checkedContracts)
        {
            if ((object)this == other)
                return true;

            if (checkedContracts != null)
            {
                DataContractPairKey contractPairKey = new DataContractPairKey(this, other);
                if (checkedContracts.ContainsKey(contractPairKey))
                    return true;
                checkedContracts.Add(contractPairKey, null);
            }
            return false;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        internal void ThrowInvalidDataContractException(string message)
        {
            ThrowInvalidDataContractException(message, UnderlyingType);
        }
#if NO_DYNAMIC_CODEGEN
        static internal bool IsTypeVisible(Type t)
        {
            return true;
        }
#else
        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks type visibility to calculate if access to it requires MemberAccessPermission."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        static internal bool IsTypeVisible(Type t)
        {
            // Generic parameters are always considered visible.
            if (t.IsGenericParameter)
            {
                return true;
            }

            // The normal Type.IsVisible check requires all nested types to be IsNestedPublic.
            // This does not comply with our convention where they can also have InternalsVisibleTo
            // with our assembly.   The following method performs a recursive walk back the declaring
            // type hierarchy to perform this enhanced IsVisible check.
            if (!IsTypeAndDeclaringTypeVisible(t))
            {
                return false;
            }

            // All generic argument types must also be visible.
            // Nested types perform this test recursively for all their declaring types.
            foreach (Type genericType in t.GetGenericArguments())
            {
                if (!IsTypeVisible(genericType))
                {
                    return false;
                }
            }

            return true;
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks type visibility to calculate if access to it requires MemberAccessPermission."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        static internal bool IsTypeAndDeclaringTypeVisible(Type t)
        {
            // Arrays, etc. must consider the underlying element type because the
            // non-element type does not reflect the same type nesting.  For example,
            // MyClass[] would not show as a nested type, even when MyClass is nested.
            if (t.HasElementType)
            {
                return IsTypeVisible(t.GetElementType());
            }

            // Nested types are not visible unless their declaring type is visible.
            // Additionally, they must be either IsNestedPublic or in an assembly with InternalsVisibleTo this current assembly.
            // Non-nested types must be public or have this same InternalsVisibleTo relation.
            return t.IsNested
                    ? (t.IsNestedPublic || IsTypeVisibleInSerializationModule(t)) && IsTypeVisible(t.DeclaringType)
                    : t.IsPublic || IsTypeVisibleInSerializationModule(t);
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks constructor visibility to calculate if access to it requires MemberAccessPermission."
            + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        static internal bool ConstructorRequiresMemberAccess(ConstructorInfo ctor)
        {
            return ctor != null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor);
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks method visibility to calculate if access to it requires MemberAccessPermission."
            + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        static internal bool MethodRequiresMemberAccess(MethodInfo method)
        {
            return method != null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method);
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks field visibility to calculate if access to it requires MemberAccessPermission."
            + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        static internal bool FieldRequiresMemberAccess(FieldInfo field)
        {
            return field != null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field);
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks type visibility to calculate if access to it requires MemberAccessPermission."
            + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        static bool IsTypeVisibleInSerializationModule(Type type)
        {
            return (type.Module.Equals(typeof(CodeGenerator).Module) || IsAssemblyFriendOfSerialization(type.Assembly)) && !type.IsNestedPrivate;
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks member visibility to calculate if access to it requires MemberAccessPermission."
            + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        static bool IsMemberVisibleInSerializationModule(MemberInfo member)
        {
            if (!IsTypeVisibleInSerializationModule(member.DeclaringType))
                return false;

            if (member is MethodInfo)
            {
                MethodInfo method = (MethodInfo)member;
                return (method.IsAssembly || method.IsFamilyOrAssembly);
            }
            else if (member is FieldInfo)
            {
                FieldInfo field = (FieldInfo)member;
                return (field.IsAssembly || field.IsFamilyOrAssembly) && IsTypeVisible(field.FieldType);
            }
            else if (member is ConstructorInfo)
            {
                ConstructorInfo constructor = (ConstructorInfo)member;
                return (constructor.IsAssembly || constructor.IsFamilyOrAssembly);
            }

            return false;
        }

        [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks member visibility to calculate if access to it requires MemberAccessPermission."
            + " Since this information is used to determine whether to give the generated code access"
            + " permissions to private members, any changes to the logic should be reviewed.")]
        internal static bool IsAssemblyFriendOfSerialization(Assembly assembly)
        {
            InternalsVisibleToAttribute[] internalsVisibleAttributes = (InternalsVisibleToAttribute[])assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), false);
            foreach (InternalsVisibleToAttribute internalsVisibleAttribute in internalsVisibleAttributes)
            {
                string internalsVisibleAttributeAssemblyName = internalsVisibleAttribute.AssemblyName;

                if (Regex.IsMatch(internalsVisibleAttributeAssemblyName, Globals.SimpleSRSInternalsVisiblePattern) ||
                    Regex.IsMatch(internalsVisibleAttributeAssemblyName, Globals.FullSRSInternalsVisiblePattern))
                {
                    return true;
                }
            }
            return false;
        }
#endif
    }

    interface IGenericNameProvider
    {
        int GetParameterCount();
        IList<int> GetNestedParameterCounts();
        string GetParameterName(int paramIndex);
        string GetNamespaces();
        string GetGenericTypeName();
        bool ParametersFromBuiltInNamespaces { get; }
    }

    class GenericNameProvider : IGenericNameProvider
    {
        string genericTypeName;
        object[] genericParams; //Type or DataContract
        IList<int> nestedParamCounts;
        internal GenericNameProvider(Type type)
            : this(DataContract.GetClrTypeFullName(type.GetGenericTypeDefinition()), type.GetGenericArguments())
        {
        }

        internal GenericNameProvider(string genericTypeName, object[] genericParams)
        {
            this.genericTypeName = genericTypeName;
            this.genericParams = new object[genericParams.Length];
            genericParams.CopyTo(this.genericParams, 0);

            string name, ns;
            DataContract.GetClrNameAndNamespace(genericTypeName, out name, out ns);
            this.nestedParamCounts = DataContract.GetDataContractNameForGenericName(name, null);
        }

        public int GetParameterCount()
        {
            return genericParams.Length;
        }

        public IList<int> GetNestedParameterCounts()
        {
            return nestedParamCounts;
        }

        public string GetParameterName(int paramIndex)
        {
            return GetStableName(paramIndex).Name;
        }

        public string GetNamespaces()
        {
            StringBuilder namespaces = new StringBuilder();
            for (int j = 0; j < GetParameterCount(); j++)
                namespaces.Append(" ").Append(GetStableName(j).Namespace);
            return namespaces.ToString();
        }

        public string GetGenericTypeName()
        {
            return genericTypeName;
        }

        public bool ParametersFromBuiltInNamespaces
        {
            get
            {
                bool parametersFromBuiltInNamespaces = true;
                for (int j = 0; j < GetParameterCount(); j++)
                {
                    if (parametersFromBuiltInNamespaces)
                        parametersFromBuiltInNamespaces = DataContract.IsBuiltInNamespace(GetStableName(j).Namespace);
                    else
                        break;
                }
                return parametersFromBuiltInNamespaces;
            }
        }

        XmlQualifiedName GetStableName(int i)
        {
            object o = genericParams[i];
            XmlQualifiedName qname = o as XmlQualifiedName;
            if (qname == null)
            {
                Type paramType = o as Type;
                if (paramType != null)
                    genericParams[i] = qname = DataContract.GetStableName(paramType);
                else
                    genericParams[i] = qname = ((DataContract)o).StableName;
            }
            return qname;
        }
    }

    class GenericInfo : IGenericNameProvider
    {
        string genericTypeName;
        XmlQualifiedName stableName;
        List<GenericInfo> paramGenericInfos;
        List<int> nestedParamCounts;

        internal GenericInfo(XmlQualifiedName stableName, string genericTypeName)
        {
            this.stableName = stableName;
            this.genericTypeName = genericTypeName;
            this.nestedParamCounts = new List<int>();
            this.nestedParamCounts.Add(0);
        }

        internal void Add(GenericInfo actualParamInfo)
        {
            if (paramGenericInfos == null)
                paramGenericInfos = new List<GenericInfo>();
            paramGenericInfos.Add(actualParamInfo);
        }

        internal void AddToLevel(int level, int count)
        {
            if (level >= nestedParamCounts.Count)
            {
                do
                {
                    nestedParamCounts.Add((level == nestedParamCounts.Count) ? count : 0);
                } while (level >= nestedParamCounts.Count);
            }
            else
                nestedParamCounts[level] = nestedParamCounts[level] + count;
        }

        internal XmlQualifiedName GetExpandedStableName()
        {
            if (paramGenericInfos == null)
                return stableName;
            return new XmlQualifiedName(DataContract.EncodeLocalName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(stableName.Name), this)), stableName.Namespace);
        }

        internal string GetStableNamespace()
        {
            return stableName.Namespace;
        }

        internal XmlQualifiedName StableName
        {
            get { return stableName; }
        }

        internal IList<GenericInfo> Parameters
        {
            get { return paramGenericInfos; }
        }

        public int GetParameterCount()
        {
            return paramGenericInfos.Count;
        }

        public IList<int> GetNestedParameterCounts()
        {
            return nestedParamCounts;
        }

        public string GetParameterName(int paramIndex)
        {
            return paramGenericInfos[paramIndex].GetExpandedStableName().Name;
        }

        public string GetNamespaces()
        {
            StringBuilder namespaces = new StringBuilder();
            for (int j = 0; j < paramGenericInfos.Count; j++)
                namespaces.Append(" ").Append(paramGenericInfos[j].GetStableNamespace());
            return namespaces.ToString();
        }

        public string GetGenericTypeName()
        {
            return genericTypeName;
        }

        public bool ParametersFromBuiltInNamespaces
        {
            get
            {
                bool parametersFromBuiltInNamespaces = true;
                for (int j = 0; j < paramGenericInfos.Count; j++)
                {
                    if (parametersFromBuiltInNamespaces)
                        parametersFromBuiltInNamespaces = DataContract.IsBuiltInNamespace(paramGenericInfos[j].GetStableNamespace());
                    else
                        break;
                }
                return parametersFromBuiltInNamespaces;
            }
        }

    }

    internal class DataContractPairKey
    {
        object object1;
        object object2;

        public DataContractPairKey(object object1, object object2)
        {
            this.object1 = object1;
            this.object2 = object2;
        }

        public override bool Equals(object other)
        {
            DataContractPairKey otherKey = other as DataContractPairKey;
            if (otherKey == null)
                return false;
            return ((otherKey.object1 == object1 && otherKey.object2 == object2) || (otherKey.object1 == object2 && otherKey.object2 == object1));
        }

        public override int GetHashCode()
        {
            return object1.GetHashCode() ^ object2.GetHashCode();
        }
    }

    class TypeHandleRefEqualityComparer : IEqualityComparer<TypeHandleRef>
    {
        public bool Equals(TypeHandleRef x, TypeHandleRef y)
        {
            return x.Value.Equals(y.Value);
        }

        public int GetHashCode(TypeHandleRef obj)
        {
            return obj.Value.GetHashCode();
        }
    }

    class TypeHandleRef
    {
        RuntimeTypeHandle value;

        public TypeHandleRef()
        {
        }

        public TypeHandleRef(RuntimeTypeHandle value)
        {
            this.value = value;
        }

        public RuntimeTypeHandle Value
        {
            get
            {
                return this.value;
            }
            set
            {
                this.value = value;
            }
        }
    }

    class IntRef
    {
        int value;

        public IntRef(int value)
        {
            this.value = value;
        }

        public int Value
        {
            get
            {
                return this.value;
            }
        }
    }
}