File: XmlSchemaImporter.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1878 lines) | stat: -rw-r--r-- 97,017 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
//------------------------------------------------------------------------------
// <copyright file="XmlSchemaImporter.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------

namespace System.Xml.Serialization  {

    using System;
    using System.Xml.Schema;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Reflection;
    using System.Xml.Serialization.Configuration;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.Collections.Specialized;
    using System.Globalization;
    using System.Security.Permissions;
    using System.Xml.Serialization.Advanced;

#if DEBUG
    using System.Diagnostics;
#endif

    /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter"]/*' />
    ///<internalonly/>
    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    public class XmlSchemaImporter : SchemaImporter {

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.XmlSchemaImporter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSchemaImporter(XmlSchemas schemas) : base(schemas, CodeGenerationOptions.GenerateProperties, null, new ImportContext()) {}

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.XmlSchemaImporter1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, null, new ImportContext(typeIdentifiers, false)) {}

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.XmlSchemaImporter2"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers, CodeGenerationOptions options) : base(schemas, options, null, new ImportContext(typeIdentifiers, false)) {}

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.XmlSchemaImporter3"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) : base(schemas, options, null, context){}

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.XmlSchemaImporter4"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, ImportContext context) : base(schemas, options, codeProvider, context){
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportDerivedTypeMapping"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType) {
            return ImportDerivedTypeMapping(name, baseType, false);
        }

        internal bool GenerateOrder {
            get { return (Options & CodeGenerationOptions.GenerateOrder) != 0; }
        }

        internal TypeMapping GetDefaultMapping(TypeFlags flags) {
            PrimitiveMapping mapping = new PrimitiveMapping();
            mapping.TypeDesc = Scope.GetTypeDesc("string", XmlSchema.Namespace, flags);
            mapping.TypeName = mapping.TypeDesc.DataType.Name;
            mapping.Namespace = XmlSchema.Namespace;
            return mapping;
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportDerivedTypeMapping1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType, bool baseTypeCanBeIndirect) {
            ElementAccessor element = ImportElement(name, typeof(TypeMapping), baseType);

            if (element.Mapping is StructMapping) {
                MakeDerived((StructMapping)element.Mapping, baseType, baseTypeCanBeIndirect);
            }
            else if (baseType != null) {
                if (element.Mapping is ArrayMapping) {
                    // in the case of the ArrayMapping we can use the top-level StructMapping, because it does not have base base type
                    element.Mapping = ((ArrayMapping)element.Mapping).TopLevelMapping;
                    MakeDerived((StructMapping)element.Mapping, baseType, baseTypeCanBeIndirect);
                }
                else {
                    // Element '{0}' from namespace '{1}' is not a complex type and cannot be used as a {2}.
                    throw new InvalidOperationException(Res.GetString(Res.XmlBadBaseElement, name.Name, name.Namespace, baseType.FullName));
                }
            }
            return new XmlTypeMapping(Scope, element);
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportSchemaType"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName) {
            return ImportSchemaType(typeName, null, false);
        }
                                          

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportSchemaType1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType) {
            return ImportSchemaType(typeName, baseType, false);
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportSchemaType2"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType, bool baseTypeCanBeIndirect) {
            TypeMapping typeMapping = ImportType(typeName, typeof(TypeMapping), baseType, TypeFlags.CanBeElementValue, true);
            typeMapping.ReferencedByElement = false;

            ElementAccessor accessor = new ElementAccessor();
            accessor.IsTopLevelInSchema = true; // false
            accessor.Name = typeName.Name;
            accessor.Namespace = typeName.Namespace;
            accessor.Mapping = typeMapping;

            if (typeMapping is SpecialMapping && ((SpecialMapping)typeMapping).NamedAny)
                accessor.Any = true;
            accessor.IsNullable = typeMapping.TypeDesc.IsNullable;
            accessor.Form = XmlSchemaForm.Qualified;

            if (accessor.Mapping is StructMapping) {
                MakeDerived((StructMapping)accessor.Mapping, baseType, baseTypeCanBeIndirect);
            }
            else if (baseType != null) {
                if (accessor.Mapping is ArrayMapping) {
                    // in the case of the ArrayMapping we can use the top-level StructMapping, because it does not have base base type
                    accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping;
                    MakeDerived((StructMapping)accessor.Mapping, baseType, baseTypeCanBeIndirect);
                }
                else {
                    // Type '{0}' from namespace '{1}' is not a complex type and cannot be used as a {2}.
                    throw new InvalidOperationException(Res.GetString(Res.XmlBadBaseType, typeName.Name, typeName.Namespace, baseType.FullName));
                }
            }
            return new XmlTypeMapping(Scope, accessor);
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportTypeMapping"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlTypeMapping ImportTypeMapping(XmlQualifiedName name) {
            return ImportDerivedTypeMapping(name, null);
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportMembersMapping"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlMembersMapping ImportMembersMapping(XmlQualifiedName name) {
            return new XmlMembersMapping(Scope, ImportElement(name, typeof(MembersMapping), null), XmlMappingAccess.Read | XmlMappingAccess.Write);
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportAnyType"]/*' />
        public XmlMembersMapping ImportAnyType(XmlQualifiedName typeName, string elementName) {
            TypeMapping typeMapping = ImportType(typeName, typeof(MembersMapping), null, TypeFlags.CanBeElementValue, true);
            MembersMapping mapping = typeMapping as MembersMapping;

            if (mapping == null) {
                XmlSchemaComplexType type = new XmlSchemaComplexType();
                XmlSchemaSequence seq = new XmlSchemaSequence();
                type.Particle = seq;
                XmlSchemaElement element = new XmlSchemaElement();
                element.Name = elementName;
                element.SchemaTypeName = typeName;
                seq.Items.Add(element);
                mapping = ImportMembersType(type, typeName.Namespace, elementName);
            }

            if (mapping.Members.Length != 1 || !mapping.Members[0].Accessor.Any)
                return null;
            mapping.Members[0].Name = elementName;
            ElementAccessor accessor = new ElementAccessor();
            accessor.Name = elementName;
            accessor.Namespace = typeName.Namespace;
            accessor.Mapping = mapping;
            accessor.Any = true;

            XmlSchemaObject xso = Schemas.SchemaSet.GlobalTypes[typeName];
            if (xso != null) {
                XmlSchema schema = xso.Parent as XmlSchema;
                if (schema != null) {
                    accessor.Form = schema.ElementFormDefault == XmlSchemaForm.None ? XmlSchemaForm.Unqualified : schema.ElementFormDefault;
                }
            }
            XmlMembersMapping members = new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write);
            return members;
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportMembersMapping1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names) {
            return ImportMembersMapping(names, null, false);
        }

        /// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportMembersMapping2"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type baseType, bool baseTypeCanBeIndirect) {
            CodeIdentifiers memberScope = new CodeIdentifiers();
            memberScope.UseCamelCasing = true;
            MemberMapping[] members = new MemberMapping[names.Length];
            for (int i = 0; i < names.Length; i++) {
                XmlQualifiedName name = names[i];
                ElementAccessor accessor =  ImportElement(name, typeof(TypeMapping), baseType);
                if (baseType != null && accessor.Mapping is StructMapping)
                    MakeDerived((StructMapping)accessor.Mapping, baseType, baseTypeCanBeIndirect);

                MemberMapping member = new MemberMapping();
                member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name));
                member.Name = memberScope.AddUnique(member.Name, member);
                member.TypeDesc = accessor.Mapping.TypeDesc;
                member.Elements = new ElementAccessor[] { accessor };
                members[i] = member;
            }
            MembersMapping mapping = new MembersMapping();
            mapping.HasWrapperElement = false;
            mapping.TypeDesc = Scope.GetTypeDesc(typeof(object[]));
            mapping.Members = members;
            ElementAccessor element = new ElementAccessor();
            element.Mapping = mapping;
            return new XmlMembersMapping(Scope, element, XmlMappingAccess.Read | XmlMappingAccess.Write);
        }

        public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members) {
            XmlSchemaComplexType type = new XmlSchemaComplexType();
            XmlSchemaSequence seq = new XmlSchemaSequence();
            type.Particle = seq;
            foreach (SoapSchemaMember member in members) {
                XmlSchemaElement element = new XmlSchemaElement();
                element.Name = member.MemberName;
                element.SchemaTypeName = member.MemberType;
                seq.Items.Add(element);
            }
            MembersMapping mapping = ImportMembersType(type, null, name);

            ElementAccessor accessor = new ElementAccessor();
            accessor.Name = Accessor.EscapeName(name);
            accessor.Namespace = ns;
            accessor.Mapping = mapping;
            accessor.IsNullable = false;
            accessor.Form = XmlSchemaForm.Qualified;
            return new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write);
        }

        ElementAccessor ImportElement(XmlQualifiedName name, Type desiredMappingType, Type baseType) {
            XmlSchemaElement element = FindElement(name);
            ElementAccessor accessor = (ElementAccessor)ImportedElements[element];
            if (accessor != null) return accessor;
            accessor = ImportElement(element, string.Empty, desiredMappingType, baseType, name.Namespace, true);
            ElementAccessor existing = (ElementAccessor)ImportedElements[element];
            if (existing != null) {
                return existing;
            }
            ImportedElements.Add(element, accessor);
            return accessor;
        }

        ElementAccessor ImportElement(XmlSchemaElement element, string identifier, Type desiredMappingType, Type baseType, string ns, bool topLevelElement) {
            if (!element.RefName.IsEmpty) {
                // we cannot re-use the accessor for the element refs
                ElementAccessor topAccessor = ImportElement(element.RefName, desiredMappingType, baseType);
                if (element.IsMultipleOccurrence && topAccessor.Mapping is ArrayMapping) {
                    ElementAccessor refAccessor = topAccessor.Clone();
                    refAccessor.IsTopLevelInSchema = false;
                    refAccessor.Mapping.ReferencedByElement = true;
                    return refAccessor;
                }
                return topAccessor;
            }

            if (element.Name.Length == 0) {
                XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
                throw new InvalidOperationException(Res.GetString(Res.XmlElementHasNoName, parentType.Name, parentType.Namespace));
            }
            string unescapedName = Accessor.UnescapeName(element.Name);
            if (identifier.Length == 0)
                identifier = CodeIdentifier.MakeValid(unescapedName);
            else
                identifier += CodeIdentifier.MakePascal(unescapedName);
            TypeMapping mapping = ImportElementType(element, identifier, desiredMappingType, baseType, ns);
            ElementAccessor accessor = new ElementAccessor();
            accessor.IsTopLevelInSchema = element.Parent is XmlSchema;
            accessor.Name = element.Name;
            accessor.Namespace = ns;
            accessor.Mapping = mapping;
            accessor.IsOptional = element.MinOccurs == 0m;

            if (element.DefaultValue != null) {
                accessor.Default = element.DefaultValue;
            }
            else if (element.FixedValue != null) {
                accessor.Default = element.FixedValue;
                accessor.IsFixed = true;
            }

            if (mapping is SpecialMapping && ((SpecialMapping)mapping).NamedAny)
                accessor.Any = true;
            accessor.IsNullable = element.IsNillable;
            if (topLevelElement) {
                accessor.Form = XmlSchemaForm.Qualified;
            }
            else {
                accessor.Form = ElementForm(ns, element);
            }
            return accessor;
        }

        TypeMapping ImportElementType(XmlSchemaElement element, string identifier, Type desiredMappingType, Type baseType, string ns) {
            TypeMapping mapping;
            if (!element.SchemaTypeName.IsEmpty) {
                mapping = ImportType(element.SchemaTypeName, desiredMappingType, baseType, TypeFlags.CanBeElementValue, false);
                if (!mapping.ReferencedByElement) {
                    object type = FindType(element.SchemaTypeName, TypeFlags.CanBeElementValue);
                    XmlSchemaObject parent = element;
                    while (parent.Parent != null && type != parent) {
                        parent = parent.Parent;
                    }
                    mapping.ReferencedByElement = (type != parent);
                }
            }
            else if (element.SchemaType != null) {
                if (element.SchemaType is XmlSchemaComplexType)
                    mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, identifier, desiredMappingType, baseType, TypeFlags.CanBeElementValue);
                else
                    mapping = ImportDataType((XmlSchemaSimpleType)element.SchemaType, ns, identifier, baseType, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue, false);
                mapping.ReferencedByElement = true;
            }
            else if (!element.SubstitutionGroup.IsEmpty)
                mapping = ImportElementType(FindElement(element.SubstitutionGroup), identifier, desiredMappingType, baseType, ns);
            else {
                if (desiredMappingType == typeof(MembersMapping)) {
                    mapping = ImportMembersType(new XmlSchemaType(), ns, identifier);
                }
                else {
                    mapping = ImportRootMapping();
                }
            }
            if (!(desiredMappingType.IsAssignableFrom(mapping.GetType())))
                throw new InvalidOperationException(Res.GetString(Res.XmlElementImportedTwice, element.Name, ns, mapping.GetType().Name, desiredMappingType.Name));

            // let the extensions to run
            if (!mapping.TypeDesc.IsMappedType) {
                RunSchemaExtensions(mapping, element.SchemaTypeName, element.SchemaType, element, TypeFlags.CanBeElementValue);
            }
            return mapping;
        }

        void RunSchemaExtensions(TypeMapping mapping, XmlQualifiedName qname, XmlSchemaType type, XmlSchemaObject context, TypeFlags flags) {
            string typeName = null;
            SchemaImporterExtension typeOwner = null;
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace mainNamespace = new CodeNamespace();
            compileUnit.Namespaces.Add(mainNamespace);

            if (!qname.IsEmpty) {
                typeName = FindExtendedType(qname.Name, qname.Namespace, context, compileUnit, mainNamespace, out typeOwner);
            }
            else if (type != null) {
                typeName = FindExtendedType(type, context, compileUnit, mainNamespace, out typeOwner);
            }
            else if (context is XmlSchemaAny) {
                typeName = FindExtendedAnyElement((XmlSchemaAny)context, ((flags & TypeFlags.CanBeTextValue) != 0), compileUnit, mainNamespace, out typeOwner);
            }

            if (typeName != null && typeName.Length > 0) {
                // check if the type name is valid 
                typeName = typeName.Replace('+', '.');
                try {
                    CodeGenerator.ValidateIdentifiers(new CodeTypeReference(typeName));
                }
                catch (ArgumentException) {
                    if (qname.IsEmpty) {
                        throw new InvalidOperationException(Res.GetString(Res.XmlImporterExtensionBadLocalTypeName, typeOwner.GetType().FullName, typeName));
                    }
                    else {
                        throw new InvalidOperationException(Res.GetString(Res.XmlImporterExtensionBadTypeName, typeOwner.GetType().FullName, qname.Name, qname.Namespace, typeName)); 
                    }
                }
                // 


                foreach (CodeNamespace ns in compileUnit.Namespaces) {
                    CodeGenerator.ValidateIdentifiers(ns);
                }
                // 

                mapping.TypeDesc = mapping.TypeDesc.CreateMappedTypeDesc(new MappedTypeDesc(typeName, qname.Name, qname.Namespace, type, context, typeOwner, mainNamespace, compileUnit.ReferencedAssemblies));

                if (mapping is ArrayMapping) {
                    TypeMapping top = ((ArrayMapping)mapping).TopLevelMapping;
                    top.TypeName =  mapping.TypeName;
                    top.TypeDesc = mapping.TypeDesc;
                }
                else {
                    mapping.TypeName = qname.IsEmpty ? null : typeName;
                }
            }
        }
        string GenerateUniqueTypeName(string desiredName, string ns) {
            int i = 1;

            string typeName = desiredName;
            while (true) {
                XmlQualifiedName qname = new XmlQualifiedName(typeName, ns);

                object type = Schemas.Find(qname, typeof(XmlSchemaType));
                if (type == null) {
                    break;
                }
                typeName = desiredName + i.ToString(CultureInfo.InvariantCulture);
                i++;
            }
            typeName = CodeIdentifier.MakeValid(typeName);
            return TypeIdentifiers.AddUnique(typeName, typeName);
        }

        [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
        internal override void ImportDerivedTypes(XmlQualifiedName baseName) {
            foreach (XmlSchema schema in Schemas) {
                if (Schemas.IsReference(schema)) continue;
                if (XmlSchemas.IsDataSet(schema)) continue;
                XmlSchemas.Preprocess(schema);
                foreach (object item in schema.SchemaTypes.Values) {
                    if (item is XmlSchemaType) {
                        XmlSchemaType type = (XmlSchemaType)item;
                        if (type.DerivedFrom == baseName && TypesInUse[type.Name, schema.TargetNamespace] == null) {
                            ImportType(type.QualifiedName, typeof(TypeMapping), null, TypeFlags.CanBeElementValue, false);
                        }
                    }
                }
            }
        }

        TypeMapping ImportType(XmlQualifiedName name, Type desiredMappingType, Type baseType, TypeFlags flags, bool addref) {
            if (name.Name == Soap.UrType && name.Namespace == XmlSchema.Namespace)
                return ImportRootMapping();
            object type = FindType(name, flags);

            TypeMapping mapping = (TypeMapping)ImportedMappings[type];
            if (mapping != null && desiredMappingType.IsAssignableFrom(mapping.GetType()))
                return mapping;

            if (addref)
                AddReference(name, TypesInUse, Res.XmlCircularTypeReference);
            if (type is XmlSchemaComplexType) {
                mapping = ImportType((XmlSchemaComplexType)type, name.Namespace, name.Name, desiredMappingType, baseType, flags);
            }
            else if (type is XmlSchemaSimpleType)
                mapping = ImportDataType((XmlSchemaSimpleType)type, name.Namespace, name.Name, baseType, flags, false);
            else
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));

            if (addref && name.Namespace != XmlSchema.Namespace)
                RemoveReference(name, TypesInUse);

            return mapping;
        }

        TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string identifier, Type desiredMappingType, Type baseType, TypeFlags flags) {
            if (type.Redefined != null) {
                // we do not support redefine in the current version
                throw new NotSupportedException(Res.GetString(Res.XmlUnsupportedRedefine, type.Name, typeNs));
            }   
            if (desiredMappingType == typeof(TypeMapping)) {
                TypeMapping mapping = null;

                if (baseType == null) {
                    if ((mapping = ImportArrayMapping(type, identifier, typeNs, false)) == null) {
                        mapping = ImportAnyMapping(type, identifier, typeNs, false);
                    }
                }
                if (mapping == null) {
                    mapping = ImportStructType(type, typeNs, identifier, baseType, false);

                    if (mapping != null && type.Name != null && type.Name.Length != 0)
                        ImportDerivedTypes(new XmlQualifiedName(identifier, typeNs));
                }
                return mapping;
            }
            else if (desiredMappingType == typeof(MembersMapping))
                return ImportMembersType(type, typeNs, identifier);
            else
                throw new ArgumentException(Res.GetString(Res.XmlInternalError), "desiredMappingType");
        }

        MembersMapping ImportMembersType(XmlSchemaType type, string typeNs, string identifier) {
            if (!type.DerivedFrom.IsEmpty) throw new InvalidOperationException(Res.GetString(Res.XmlMembersDeriveError));
            CodeIdentifiers memberScope = new CodeIdentifiers();
            memberScope.UseCamelCasing = true;
            bool needExplicitOrder = false;
            MemberMapping[] members = ImportTypeMembers(type, typeNs, identifier, memberScope, new CodeIdentifiers(), new NameTable(), ref needExplicitOrder, false, false);
            MembersMapping mappings = new MembersMapping();
            mappings.HasWrapperElement = true;
            mappings.TypeDesc = Scope.GetTypeDesc(typeof(object[]));
            mappings.Members = members;
            return mappings;
        }

        StructMapping ImportStructType(XmlSchemaType type, string typeNs, string identifier, Type baseType, bool arrayLike) {
            TypeDesc baseTypeDesc = null;
            TypeMapping baseMapping = null;

            bool isRootType = false;
            if (!type.DerivedFrom.IsEmpty) {
                baseMapping = ImportType(type.DerivedFrom, typeof(TypeMapping), null, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue, false);

                if (baseMapping is StructMapping)
                    baseTypeDesc = ((StructMapping)baseMapping).TypeDesc;
                else if (baseMapping is ArrayMapping) {
                    baseMapping = ((ArrayMapping)baseMapping).TopLevelMapping;
                    if (baseMapping != null) {
                        baseMapping.ReferencedByTopLevelElement = false;
                        baseMapping.ReferencedByElement = true;
                        baseTypeDesc = baseMapping.TypeDesc;
                    }
                }
                else
                    baseMapping = null;
            }
            if (baseTypeDesc == null && baseType != null)
                baseTypeDesc = Scope.GetTypeDesc(baseType);
            if (baseMapping == null) 
            {
                baseMapping = GetRootMapping();
                isRootType = true;
            }
            Mapping previousMapping = (Mapping)ImportedMappings[type];
            if (previousMapping != null) {
                if (previousMapping is StructMapping) {
                    return (StructMapping)previousMapping;
                }
                else if (arrayLike && previousMapping is ArrayMapping){
                    ArrayMapping arrayMapping = (ArrayMapping)previousMapping;
                    if (arrayMapping.TopLevelMapping != null) {
                        return arrayMapping.TopLevelMapping;
                    }
                }
                else {
                    throw new InvalidOperationException(Res.GetString(Res.XmlTypeUsedTwice, type.QualifiedName.Name, type.QualifiedName.Namespace));
                }
            }
            StructMapping structMapping = new StructMapping();
            structMapping.IsReference = Schemas.IsReference(type);
            TypeFlags flags = TypeFlags.Reference;
            if (type is XmlSchemaComplexType) {
                if (((XmlSchemaComplexType)type).IsAbstract) 
                    flags |= TypeFlags.Abstract;
            }

            identifier = Accessor.UnescapeName(identifier);
            string typeName = type.Name == null || type.Name.Length == 0 ? GenerateUniqueTypeName(identifier, typeNs) : GenerateUniqueTypeName(identifier);
            structMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Struct, baseTypeDesc, flags);
            structMapping.Namespace = typeNs;
            structMapping.TypeName = type.Name == null || type.Name.Length == 0 ? null : identifier;
            structMapping.BaseMapping = (StructMapping)baseMapping;
            if (!arrayLike)
                ImportedMappings.Add(type, structMapping);
            CodeIdentifiers members = new CodeIdentifiers();
            CodeIdentifiers membersScope = structMapping.BaseMapping.Scope.Clone();
            members.AddReserved(typeName);
            membersScope.AddReserved(typeName);
            AddReservedIdentifiersForDataBinding(members);
            if (isRootType)
                AddReservedIdentifiersForDataBinding(membersScope);
            bool needExplicitOrder = false;
            structMapping.Members = ImportTypeMembers(type, typeNs, identifier, members, membersScope, structMapping, ref needExplicitOrder, true, true);

            if (!IsAllGroup(type)) {
                if (needExplicitOrder && !GenerateOrder) {
                    structMapping.SetSequence();
                }
                else if (GenerateOrder) {
                    structMapping.IsSequence = true;
                }
            }

            for (int i = 0; i < structMapping.Members.Length; i++) {
                StructMapping declaringMapping;
                MemberMapping baseMember = ((StructMapping)baseMapping).FindDeclaringMapping(structMapping.Members[i], out declaringMapping, structMapping.TypeName);
                if (baseMember != null && baseMember.TypeDesc != structMapping.Members[i].TypeDesc)
                    throw new InvalidOperationException(Res.GetString(Res.XmlIllegalOverride, type.Name, baseMember.Name, baseMember.TypeDesc.FullName, structMapping.Members[i].TypeDesc.FullName, declaringMapping.TypeDesc.FullName));
            }
            structMapping.Scope = membersScope;
            Scope.AddTypeMapping(structMapping);
            return structMapping;
        }

        bool IsAllGroup(XmlSchemaType type) {
            TypeItems items = GetTypeItems(type);
            return (items.Particle != null) && (items.Particle is XmlSchemaAll);
        }

        StructMapping ImportStructDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, Type baseType) {
            identifier = Accessor.UnescapeName(identifier);
            string typeName = GenerateUniqueTypeName(identifier);
            StructMapping structMapping = new StructMapping();
            structMapping.IsReference = Schemas.IsReference(dataType);
            TypeFlags flags = TypeFlags.Reference;
            TypeDesc baseTypeDesc = Scope.GetTypeDesc(baseType);
            structMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Struct, baseTypeDesc, flags);
            structMapping.Namespace = typeNs;
            structMapping.TypeName = identifier;
            CodeIdentifiers members = new CodeIdentifiers();
            members.AddReserved(typeName);
            AddReservedIdentifiersForDataBinding(members);
            ImportTextMember(members, new CodeIdentifiers(), null);
            structMapping.Members = (MemberMapping[])members.ToArray(typeof(MemberMapping));
            structMapping.Scope = members;
            Scope.AddTypeMapping(structMapping);
            return structMapping;
        }

        class TypeItems {
            internal XmlSchemaObjectCollection Attributes = new XmlSchemaObjectCollection();
            internal XmlSchemaAnyAttribute AnyAttribute;
            internal XmlSchemaGroupBase Particle;
            internal XmlQualifiedName baseSimpleType;
            internal bool IsUnbounded;
        }

        MemberMapping[] ImportTypeMembers(XmlSchemaType type, string typeNs, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, ref bool needExplicitOrder, bool order, bool allowUnboundedElements) {
            TypeItems items = GetTypeItems(type);
            bool mixed = IsMixed(type);

            if (mixed) {
                // check if we can transfer the attribute to the base class
                XmlSchemaType t = type;
                while (!t.DerivedFrom.IsEmpty) {
                    t = FindType(t.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue);
                    if (IsMixed(t)) {
                        // keep the mixed attribute on the base class
                        mixed = false;
                        break;
                    }
                }
            }

            if (items.Particle != null) {
                ImportGroup(items.Particle, identifier, members, membersScope, elementsScope, typeNs, mixed, ref needExplicitOrder, order, items.IsUnbounded, allowUnboundedElements);
            }
            for (int i = 0; i < items.Attributes.Count; i++) {
                object item = items.Attributes[i];
                if (item is XmlSchemaAttribute) {
                    ImportAttributeMember((XmlSchemaAttribute)item, identifier, members, membersScope, typeNs);
                }
                else if (item is XmlSchemaAttributeGroupRef) {
                    XmlQualifiedName groupName = ((XmlSchemaAttributeGroupRef)item).RefName;
                    ImportAttributeGroupMembers(FindAttributeGroup(groupName), identifier, members, membersScope, groupName.Namespace);
                }
            }
            if (items.AnyAttribute != null) {
                ImportAnyAttributeMember(items.AnyAttribute, members, membersScope);
            }
            
            if (items.baseSimpleType != null || (items.Particle == null && mixed)) {
                ImportTextMember(members, membersScope, mixed ? null : items.baseSimpleType);
            }

            ImportXmlnsDeclarationsMember(type, members, membersScope);
            MemberMapping[] typeMembers = (MemberMapping[])members.ToArray(typeof(MemberMapping));
            return typeMembers;
        }

        internal static bool IsMixed(XmlSchemaType type) {
            if (!(type is XmlSchemaComplexType))
                return false;

            XmlSchemaComplexType ct = (XmlSchemaComplexType)type;
            bool mixed = ct.IsMixed;

            // check the mixed attribute on the complexContent
            if (!mixed) {
                if (ct.ContentModel != null && ct.ContentModel is XmlSchemaComplexContent) {
                    mixed = ((XmlSchemaComplexContent)ct.ContentModel).IsMixed;
                }
            }
            return mixed;
        }

        TypeItems GetTypeItems(XmlSchemaType type) {
            TypeItems items = new TypeItems();
            if (type is XmlSchemaComplexType) {
                XmlSchemaParticle particle = null;
                XmlSchemaComplexType ct = (XmlSchemaComplexType)type;
                if (ct.ContentModel != null) {
                    XmlSchemaContent content = ct.ContentModel.Content;
                    if (content is XmlSchemaComplexContentExtension) {
                        XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content;
                        items.Attributes = extension.Attributes;
                        items.AnyAttribute = extension.AnyAttribute;
                        particle = extension.Particle;
                    }
                    else if (content is XmlSchemaSimpleContentExtension) {
                        XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content;
                        items.Attributes = extension.Attributes;
                        items.AnyAttribute = extension.AnyAttribute;
                        items.baseSimpleType = extension.BaseTypeName;
                    }
                }
                else {
                    items.Attributes = ct.Attributes;
                    items.AnyAttribute = ct.AnyAttribute;
                    particle = ct.Particle;
                }
                if (particle is XmlSchemaGroupRef) {
                    XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle;
                    items.Particle = FindGroup(refGroup.RefName).Particle;
                    items.IsUnbounded = particle.IsMultipleOccurrence;
                }
                else if (particle is XmlSchemaGroupBase) {
                    items.Particle = (XmlSchemaGroupBase)particle;
                    items.IsUnbounded = particle.IsMultipleOccurrence;
                }
            }
            return items;
        }

        void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool groupRepeats, bool allowUnboundedElements) {
            if (group is XmlSchemaChoice)
                ImportChoiceGroup((XmlSchemaChoice)group, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates);
            else
                ImportGroupMembers(group, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref mixed, ref needExplicitOrder, allowDuplicates, allowUnboundedElements);

            if (mixed) {
                ImportTextMember(members, membersScope, null);
            }
        }

        MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool groupRepeats, ref bool needExplicitOrder, bool allowDuplicates) {
            NameTable choiceElements = new NameTable();
            if (GatherGroupChoices(group, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates))
                groupRepeats = true;
            MemberMapping member = new MemberMapping();
            member.Elements = (ElementAccessor[])choiceElements.ToArray(typeof(ElementAccessor));
            Array.Sort(member.Elements, new ElementComparer());

            AddScopeElements(elementsScope, member.Elements, ref needExplicitOrder, allowDuplicates);
            bool duplicateTypes = false;
            bool nullableMismatch = false;
            Hashtable uniqueTypeDescs = new Hashtable(member.Elements.Length);

            for (int i = 0; i < member.Elements.Length; i++) {
                ElementAccessor element = member.Elements[i];
                string tdFullName = element.Mapping.TypeDesc.FullName;
                object val = uniqueTypeDescs[tdFullName];
                if (val != null) {
                    duplicateTypes = true;
                    ElementAccessor existingElement = (ElementAccessor)val;
                    if (!nullableMismatch && existingElement.IsNullable != element.IsNullable)
                        nullableMismatch = true;
                }
                else {
                    uniqueTypeDescs.Add(tdFullName, element);
                }

                ArrayMapping arrayMapping = element.Mapping as ArrayMapping;
                if (arrayMapping != null) {
                    if (IsNeedXmlSerializationAttributes(arrayMapping)) {
                        // we cannot use ArrayMapping in choice if additional custom 
                        // serialization attributes are needed to serialize it
                        element.Mapping = arrayMapping.TopLevelMapping;
                        element.Mapping.ReferencedByTopLevelElement = false;
                        element.Mapping.ReferencedByElement = true;
                    }
                }
            }
            if (nullableMismatch)
                member.TypeDesc = Scope.GetTypeDesc(typeof(object));
            else
            {
                TypeDesc[] typeDescs = new TypeDesc[uniqueTypeDescs.Count];
                IEnumerator enumerator = uniqueTypeDescs.Values.GetEnumerator();
                for (int i = 0; i < typeDescs.Length; i++)
                {
                    if (!enumerator.MoveNext())
                        break;
                    typeDescs[i] = ((ElementAccessor)enumerator.Current).Mapping.TypeDesc;
                }
                member.TypeDesc = TypeDesc.FindCommonBaseTypeDesc(typeDescs);
                if (member.TypeDesc == null) member.TypeDesc = Scope.GetTypeDesc(typeof(object));
            }

            if (groupRepeats)
                member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc();

            if (membersScope != null) {
                member.Name = membersScope.AddUnique(groupRepeats ? "Items" : "Item", member);
                if (members != null) {
                    members.Add(member.Name, member);
                }
            }

            if (duplicateTypes) {
                member.ChoiceIdentifier = new ChoiceIdentifierAccessor();
                member.ChoiceIdentifier.MemberName = member.Name + "ElementName";
                // we need to create the EnumMapping to store all of the element names
                member.ChoiceIdentifier.Mapping = ImportEnumeratedChoice(member.Elements, ns, member.Name + "ChoiceType");
                member.ChoiceIdentifier.MemberIds = new string[member.Elements.Length];
                ConstantMapping[] constants = ((EnumMapping)member.ChoiceIdentifier.Mapping).Constants;
                for (int i = 0; i < member.Elements.Length; i++) {
                    member.ChoiceIdentifier.MemberIds[i] = constants[i].Name;
                }
                MemberMapping choiceIdentifier = new MemberMapping();
                choiceIdentifier.Ignore = true;
                choiceIdentifier.Name = member.ChoiceIdentifier.MemberName;
                if (groupRepeats) {
                    choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc.CreateArrayTypeDesc();
                }
                else {
                    choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc;
                }

                // create element accessor for the choiceIdentifier

                ElementAccessor choiceAccessor = new ElementAccessor();
                choiceAccessor.Name = choiceIdentifier.Name;
                choiceAccessor.Namespace = ns;
                choiceAccessor.Mapping =  member.ChoiceIdentifier.Mapping;
                choiceIdentifier.Elements  = new ElementAccessor[] {choiceAccessor};

                if (membersScope != null) {
                    choiceAccessor.Name = choiceIdentifier.Name = member.ChoiceIdentifier.MemberName = membersScope.AddUnique(member.ChoiceIdentifier.MemberName, choiceIdentifier);
                    if (members != null) {
                        members.Add(choiceAccessor.Name, choiceIdentifier);
                    }
                }
            }
            return member;
        }

        bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) {
            if (arrayMapping.Elements.Length != 1)
                return true;

            ElementAccessor item = arrayMapping.Elements[0];
            TypeMapping itemMapping = item.Mapping;

            if (item.Name != itemMapping.DefaultElementName)
                return true;

            if (item.Form != XmlSchemaForm.None && item.Form != XmlSchemaExporter.elementFormDefault)
                return true;

            if (item.Mapping.TypeDesc != null)
            {
                if (item.IsNullable != item.Mapping.TypeDesc.IsNullable)
                    return true;

                if (item.Mapping.TypeDesc.IsAmbiguousDataType)
                    return true;
            }
            return false;
        }

        bool GatherGroupChoices(XmlSchemaGroup group, NameTable choiceElements, string identifier, string ns, ref bool needExplicitOrder, bool allowDuplicates) {
            return GatherGroupChoices(group.Particle, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates);
        }

        bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElements, string identifier, string ns, ref bool needExplicitOrder, bool allowDuplicates) {
            if (particle is XmlSchemaGroupRef) {
                XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle;
                if (!refGroup.RefName.IsEmpty) {
                    AddReference(refGroup.RefName, GroupsInUse, Res.XmlCircularGroupReference);
                    if (GatherGroupChoices(FindGroup(refGroup.RefName), choiceElements, identifier, refGroup.RefName.Namespace, ref needExplicitOrder, allowDuplicates)) {
                        RemoveReference(refGroup.RefName, GroupsInUse);
                        return true;
                    }
                    RemoveReference(refGroup.RefName, GroupsInUse);
                }
            }
            else if (particle is XmlSchemaGroupBase) {
                XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;
                bool groupRepeats = group.IsMultipleOccurrence;
                XmlSchemaAny any = null;
                bool duplicateElements = false;
                for (int i = 0; i < group.Items.Count; i++) {
                    object item = group.Items[i];
                    if (item is XmlSchemaGroupBase || item is XmlSchemaGroupRef) {
                        if (GatherGroupChoices((XmlSchemaParticle)item, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates))
                            groupRepeats = true;
                    }
                    else if (item is XmlSchemaAny) {
                        if (GenerateOrder) {
                            AddScopeElements(choiceElements, ImportAny((XmlSchemaAny)item, true, ns), ref duplicateElements, allowDuplicates);
                        }
                        else {
                            any = (XmlSchemaAny)item;
                        }
                    }
                    else if (item is XmlSchemaElement) {
                        XmlSchemaElement element = (XmlSchemaElement)item;
                        XmlSchemaElement headElement = GetTopLevelElement(element);
                        if (headElement != null) {
                            XmlSchemaElement[] elements = GetEquivalentElements(headElement);
                            for (int j = 0; j < elements.Length; j++) {
                                if (elements[j].IsMultipleOccurrence) groupRepeats = true;
                                AddScopeElement(choiceElements, ImportElement(elements[j], identifier, typeof(TypeMapping), null, elements[j].QualifiedName.Namespace, true), ref duplicateElements, allowDuplicates);
                            }
                        }
                        if (element.IsMultipleOccurrence) groupRepeats = true;
                        AddScopeElement(choiceElements, ImportElement(element, identifier, typeof(TypeMapping), null, element.QualifiedName.Namespace, false), ref duplicateElements, allowDuplicates);
                    }
                }
                if (any != null) {
                    AddScopeElements(choiceElements, ImportAny(any, true, ns), ref duplicateElements, allowDuplicates);
                }
                if (!groupRepeats && !(group is XmlSchemaChoice) && group.Items.Count > 1) {
                    groupRepeats = true;
                }
                return groupRepeats;
            }
            return false;
        }

        void AddScopeElement(INameScope scope, ElementAccessor element, ref bool duplicateElements, bool allowDuplicates) {
            if (scope == null)
                return; 

            ElementAccessor scopeElement = (ElementAccessor)scope[element.Name, element.Namespace];
            if (scopeElement != null) {
                if (!allowDuplicates) {
                    throw new InvalidOperationException(Res.GetString(Res.XmlDuplicateElementInScope, element.Name, element.Namespace));
                }
                if (scopeElement.Mapping.TypeDesc != element.Mapping.TypeDesc) {
                    throw new InvalidOperationException(Res.GetString(Res.XmlDuplicateElementInScope1, element.Name, element.Namespace));
                }
                duplicateElements = true;
            }
            else {
                scope[element.Name, element.Namespace] = element;
            }
        }

        void AddScopeElements(INameScope scope, ElementAccessor[] elements, ref bool duplicateElements, bool allowDuplicates) {
            for (int i = 0; i < elements.Length; i++) {
                AddScopeElement(scope, elements[i], ref duplicateElements, allowDuplicates);
            }
        }

        void ImportGroupMembers(XmlSchemaParticle particle, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool groupRepeats, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) {

            if (particle is XmlSchemaGroupRef) {
                XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle;
                if (!refGroup.RefName.IsEmpty) {
                    AddReference(refGroup.RefName, GroupsInUse, Res.XmlCircularGroupReference);
                    ImportGroupMembers(FindGroup(refGroup.RefName).Particle, identifier, members, membersScope, elementsScope, refGroup.RefName.Namespace, groupRepeats | refGroup.IsMultipleOccurrence, ref mixed, ref needExplicitOrder, allowDuplicates, allowUnboundedElements);
                    RemoveReference(refGroup.RefName, GroupsInUse);
                }
            }
            else if (particle is XmlSchemaGroupBase) {
                XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;

                if (group.IsMultipleOccurrence)
                    groupRepeats = true;

                if (GenerateOrder && groupRepeats && group.Items.Count > 1) {
                    ImportChoiceGroup(group, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates);
                }
                else {
                    for (int i = 0; i < group.Items.Count; i++) {
                        object item = group.Items[i];
                        if (item is XmlSchemaChoice)
                            ImportChoiceGroup((XmlSchemaGroupBase)item, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates);
                        else if (item is XmlSchemaElement)
                            ImportElementMember((XmlSchemaElement)item, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates, allowUnboundedElements);
                        else if (item is XmlSchemaAny) {
                            ImportAnyMember((XmlSchemaAny)item, identifier, members, membersScope, elementsScope, ns, ref mixed, ref needExplicitOrder, allowDuplicates);
                        }
                        else if (item is XmlSchemaParticle) {
                            ImportGroupMembers((XmlSchemaParticle)item, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref mixed, ref needExplicitOrder, allowDuplicates, true);
                        }
                    }
                }
            }
        }

        XmlSchemaElement GetTopLevelElement(XmlSchemaElement element) {
            if (!element.RefName.IsEmpty)
                return FindElement(element.RefName);
            return null;
        }

        XmlSchemaElement[] GetEquivalentElements(XmlSchemaElement element) {
            ArrayList equivalentElements = new ArrayList();

            foreach (XmlSchema schema in Schemas.SchemaSet.Schemas()) {
                for (int j = 0; j < schema.Items.Count; j++) {
                    object item = schema.Items[j];
                    if (item is XmlSchemaElement) {
                        XmlSchemaElement equivalentElement = (XmlSchemaElement)item;
                        if (!equivalentElement.IsAbstract &&
                            equivalentElement.SubstitutionGroup.Namespace == schema.TargetNamespace &&
                            equivalentElement.SubstitutionGroup.Name == element.Name) {
                            equivalentElements.Add(equivalentElement);
                        }
                    }
                }
            }

            return (XmlSchemaElement[])equivalentElements.ToArray(typeof(XmlSchemaElement));
        }

        bool ImportSubstitutionGroupMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates) {
            XmlSchemaElement[] elements = GetEquivalentElements(element);
            if (elements.Length == 0)
                return false;
            XmlSchemaChoice choice = new XmlSchemaChoice();
            for (int i = 0; i < elements.Length; i++)
                choice.Items.Add(elements[i]);
            if (!element.IsAbstract)
                choice.Items.Add(element);
            if (identifier.Length == 0)
                identifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(element.Name));
            else
                identifier += CodeIdentifier.MakePascal(Accessor.UnescapeName(element.Name));
            ImportChoiceGroup(choice, identifier, members, membersScope, null, ns, repeats, ref needExplicitOrder, allowDuplicates);

            return true;
        }

        void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersScope, XmlQualifiedName simpleContentType) {
            TypeMapping mapping;
            bool isMixed = false;

            if (simpleContentType != null) {
                // allow to use all primitive types
                mapping = ImportType(simpleContentType, typeof(TypeMapping), null, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue, false);
                if (!(mapping is PrimitiveMapping || mapping.TypeDesc.CanBeTextValue)) {
                    return;
                }
            }
            else {
                // this is a case of the mixed content type, just generate string typeDesc
                isMixed = true;
                mapping = GetDefaultMapping(TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue);
            }

            TextAccessor accessor = new TextAccessor();
            accessor.Mapping = mapping;

            MemberMapping member = new MemberMapping();
            member.Elements = new ElementAccessor[0];
            member.Text = accessor;
            if (isMixed) {
                // just generate code for the standard mixed case (string[] text)
                member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc();
                member.Name = members.MakeRightCase("Text");
            }
            else {
                // import mapping for the simpleContent
                PrimitiveMapping pm = (PrimitiveMapping)accessor.Mapping;
                if (pm.IsList) {
                    member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc();
                    member.Name = members.MakeRightCase("Text");
                }
                else {
                    member.TypeDesc = accessor.Mapping.TypeDesc;
                    member.Name = members.MakeRightCase("Value");
                }
            }
            member.Name = membersScope.AddUnique(member.Name, member);
            members.Add(member.Name, member);
        }

        MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates) {
            ElementAccessor[] accessors = ImportAny(any, !mixed, ns);
            AddScopeElements(elementsScope, accessors, ref needExplicitOrder, allowDuplicates);
            MemberMapping member = new MemberMapping();
            member.Elements = accessors;
            member.Name = membersScope.MakeRightCase("Any");
            member.Name = membersScope.AddUnique(member.Name, member);
            members.Add(member.Name, member);
            member.TypeDesc = ((TypeMapping)accessors[0].Mapping).TypeDesc;

            bool repeats = any.IsMultipleOccurrence;

            if (mixed) {
                SpecialMapping textMapping = new SpecialMapping();
                textMapping.TypeDesc = Scope.GetTypeDesc(typeof(XmlNode));
                textMapping.TypeName = textMapping.TypeDesc.Name;
                member.TypeDesc = textMapping.TypeDesc;
                TextAccessor text = new TextAccessor();
                text.Mapping = textMapping;
                member.Text = text;
                repeats = true;
                mixed = false;
            }

            if (repeats) {
                member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc();
            }
            return member;
        }
        ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string targetNamespace) {
            SpecialMapping mapping = new SpecialMapping();

            mapping.TypeDesc = Scope.GetTypeDesc(makeElement ? typeof(XmlElement) : typeof(XmlNode));
            mapping.TypeName = mapping.TypeDesc.Name;

           
            TypeFlags flags = TypeFlags.CanBeElementValue;
            if (makeElement)
                flags |= TypeFlags.CanBeTextValue;

            // let the extensions to run
            RunSchemaExtensions(mapping, XmlQualifiedName.Empty, null, any, flags);

            if (GenerateOrder && any.Namespace != null) {
                NamespaceList list = new NamespaceList(any.Namespace, targetNamespace);

                if (list.Type == NamespaceList.ListType.Set) {
                    ICollection namespaces = list.Enumerate;
                    ElementAccessor[] accessors = new ElementAccessor[namespaces.Count == 0 ? 1 : namespaces.Count];
                    int count = 0;
                    foreach(string ns in list.Enumerate) {
                        ElementAccessor accessor = new ElementAccessor();
                        accessor.Mapping = mapping;
                        accessor.Any = true;
                        accessor.Namespace = ns;
                        accessors[count++] = accessor;
                    }
                    if (count > 0) {
                        return accessors;
                    }
                }
            }

            ElementAccessor anyAccessor = new ElementAccessor();
            anyAccessor.Mapping = mapping;
            anyAccessor.Any = true;
            return new ElementAccessor[] {anyAccessor};
        }

        ElementAccessor ImportArray(XmlSchemaElement element, string identifier, string ns, bool repeats) {
            if (repeats) return null;
            if (element.SchemaType == null) return null;
            if (element.IsMultipleOccurrence) return null;
            XmlSchemaType type = element.SchemaType;
            ArrayMapping arrayMapping = ImportArrayMapping(type, identifier, ns, repeats);
            if (arrayMapping == null) return null;
            ElementAccessor arrayAccessor = new ElementAccessor();
            arrayAccessor.Name = element.Name;
            arrayAccessor.Namespace = ns;
            arrayAccessor.Mapping = arrayMapping;
            if (arrayMapping.TypeDesc.IsNullable)
                arrayAccessor.IsNullable = element.IsNillable;
            arrayAccessor.Form = ElementForm(ns, element);
            return arrayAccessor;
        }

        ArrayMapping ImportArrayMapping(XmlSchemaType type, string identifier, string ns, bool repeats) {
            if (!(type is XmlSchemaComplexType)) return null;
            if (!type.DerivedFrom.IsEmpty) return null;
            if (IsMixed(type)) return null;

            Mapping previousMapping = (Mapping)ImportedMappings[type];
            if (previousMapping != null) {
                if (previousMapping is ArrayMapping)
                    return (ArrayMapping)previousMapping;
                else
                    return null;
            }

            TypeItems items = GetTypeItems(type);

            if (items.Attributes != null && items.Attributes.Count > 0) return null;
            if (items.AnyAttribute != null) return null;
            if (items.Particle == null) return null;

            XmlSchemaGroupBase item = items.Particle;
            ArrayMapping arrayMapping = new ArrayMapping();

            arrayMapping.TypeName = identifier;
            arrayMapping.Namespace = ns;

            if (item is XmlSchemaChoice) {
                XmlSchemaChoice choice = (XmlSchemaChoice)item;
                if (!choice.IsMultipleOccurrence)
                    return null;
                bool needExplicitOrder = false;
                MemberMapping choiceMember = ImportChoiceGroup(choice, identifier, null, null, null, ns, true, ref needExplicitOrder, false);
                if (choiceMember.ChoiceIdentifier != null) return null;
                arrayMapping.TypeDesc = choiceMember.TypeDesc;
                arrayMapping.Elements = choiceMember.Elements;
                arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(arrayMapping.TypeDesc.Name) : type.Name;
            }
            else if (item is XmlSchemaAll || item is XmlSchemaSequence) {
                if (item.Items.Count != 1 || !(item.Items[0] is XmlSchemaElement)) return null;
                XmlSchemaElement itemElement = (XmlSchemaElement)item.Items[0];
                if (!itemElement.IsMultipleOccurrence) return null;
                if (IsCyclicReferencedType(itemElement, new List<string>(1){identifier}))
                {
                    return null;
                }
               
                ElementAccessor itemAccessor = ImportElement(itemElement, identifier, typeof(TypeMapping), null, ns, false);
                if (itemAccessor.Any)
                    return null;
                arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
                arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping).TypeDesc.CreateArrayTypeDesc();
                arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeDesc.Name) : type.Name;
            }            
            else {
                return null;
            }

            ImportedMappings[type] = arrayMapping;
            Scope.AddTypeMapping(arrayMapping);
            // for the array-like mappings we need to create a struct mapping for the case when it referenced by the top-level element
            arrayMapping.TopLevelMapping = ImportStructType(type, ns, identifier, null, true);
            arrayMapping.TopLevelMapping.ReferencedByTopLevelElement = true;
            if (type.Name != null && type.Name.Length != 0)
                ImportDerivedTypes(new XmlQualifiedName(identifier, ns));

            return arrayMapping;
        }
        
        bool IsCyclicReferencedType(XmlSchemaElement element, List<string> identifiers)
        {
            if (!element.RefName.IsEmpty)
            {
                XmlSchemaElement refElement = FindElement(element.RefName);
                string refElementIdentifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(refElement.Name));
                foreach (string identifier in identifiers)
                {
                    if (refElementIdentifier == identifier)
                    {
                        return true;
                    }
                }
                identifiers.Add(refElementIdentifier);

                XmlSchemaType refType = refElement.SchemaType;
                if (refType is XmlSchemaComplexType)
                {                    
                    TypeItems items = GetTypeItems(refType);
                    if ((items.Particle is XmlSchemaSequence || items.Particle is XmlSchemaAll) && items.Particle.Items.Count == 1 && items.Particle.Items[0] is XmlSchemaElement)
                    {
                        XmlSchemaElement innerRefElement = (XmlSchemaElement)items.Particle.Items[0];
                        if (innerRefElement.IsMultipleOccurrence)
                        {
                            return IsCyclicReferencedType(innerRefElement, identifiers);
                        }
                    }
                }
            }
            return false;
        }
        
        SpecialMapping ImportAnyMapping(XmlSchemaType type, string identifier, string ns, bool repeats) {
            if (type == null) return null;
            if (!type.DerivedFrom.IsEmpty) return null;

            bool mixed = IsMixed(type);
            TypeItems items = GetTypeItems(type);
            if (items.Particle == null) return null;
            if (!(items.Particle is XmlSchemaAll || items.Particle is XmlSchemaSequence)) return null;
            if (items.Attributes != null && items.Attributes.Count > 0) return null;
            XmlSchemaGroupBase group = (XmlSchemaGroupBase) items.Particle;

            if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaAny)) return null;
            XmlSchemaAny any = (XmlSchemaAny)group.Items[0];

            SpecialMapping mapping = new SpecialMapping();
            // check for special named any case
            if (items.AnyAttribute != null && any.IsMultipleOccurrence && mixed) {
                mapping.NamedAny = true;
                mapping.TypeDesc = Scope.GetTypeDesc(typeof(XmlElement));
            }
            else if (items.AnyAttribute != null || any.IsMultipleOccurrence) {
                // these only work for named any case -- otherwise import as struct
                return null;
            }
            else {
                mapping.TypeDesc = Scope.GetTypeDesc(mixed ? typeof(XmlNode) : typeof(XmlElement));
            }

            TypeFlags flags = TypeFlags.CanBeElementValue;
            if (items.AnyAttribute != null || mixed)
                flags |= TypeFlags.CanBeTextValue;

            // let the extensions to run
            RunSchemaExtensions(mapping, XmlQualifiedName.Empty, null, any, flags);
            
            mapping.TypeName = mapping.TypeDesc.Name;
            if (repeats)
                mapping.TypeDesc = mapping.TypeDesc.CreateArrayTypeDesc();

            return mapping;
        }

        void ImportElementMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) {
            repeats = repeats | element.IsMultipleOccurrence;
            XmlSchemaElement headElement = GetTopLevelElement(element);
            if (headElement != null && ImportSubstitutionGroupMember(headElement, identifier, members, membersScope, ns, repeats, ref needExplicitOrder, allowDuplicates)) {
                return;
            }
            ElementAccessor accessor;
            if ((accessor = ImportArray(element, identifier, ns, repeats)) == null) {
                accessor = ImportElement(element, identifier, typeof(TypeMapping), null, ns, false);
            }

            MemberMapping member = new MemberMapping();
            string name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name));
            member.Name = membersScope.AddUnique(name, member);

            if (member.Name.EndsWith("Specified", StringComparison.Ordinal)) {
                name = member.Name;
                member.Name = membersScope.AddUnique(member.Name, member);
                membersScope.Remove(name);
            }
            members.Add(member.Name, member);
            // we do not support lists for elements
            if (accessor.Mapping.IsList) {
                accessor.Mapping = GetDefaultMapping(TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue);
                member.TypeDesc = accessor.Mapping.TypeDesc;
            }
            else {
                member.TypeDesc = accessor.Mapping.TypeDesc;
            }

            AddScopeElement(elementsScope, accessor, ref needExplicitOrder, allowDuplicates);
            member.Elements = new ElementAccessor[] { accessor };

            if (element.IsMultipleOccurrence || repeats) {
                if (!allowUnboundedElements && accessor.Mapping is ArrayMapping) {
                    accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping;
                    accessor.Mapping.ReferencedByTopLevelElement = false;
                    accessor.Mapping.ReferencedByElement = true;
                }
                member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc();
            }

            if (element.MinOccurs == 0 && member.TypeDesc.IsValueType && !element.HasDefault && !member.TypeDesc.HasIsEmpty) {
                member.CheckSpecified = SpecifiedAccessor.ReadWrite;
            }
        }

        void ImportAttributeMember(XmlSchemaAttribute attribute, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string ns) {
            AttributeAccessor accessor = ImportAttribute(attribute, identifier, ns, attribute);
            if (accessor == null) return;
            MemberMapping member = new MemberMapping();
            member.Elements = new ElementAccessor[0];
            member.Attribute = accessor;
            member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name));
            member.Name = membersScope.AddUnique(member.Name, member);
            if (member.Name.EndsWith("Specified", StringComparison.Ordinal)) {
                string name = member.Name;
                member.Name = membersScope.AddUnique(member.Name, member);
                membersScope.Remove(name);
            }
            members.Add(member.Name, member);
            member.TypeDesc = accessor.IsList ? accessor.Mapping.TypeDesc.CreateArrayTypeDesc() : accessor.Mapping.TypeDesc;

            if ((attribute.Use == XmlSchemaUse.Optional || attribute.Use == XmlSchemaUse.None) && member.TypeDesc.IsValueType && !attribute.HasDefault && !member.TypeDesc.HasIsEmpty) {
                member.CheckSpecified = SpecifiedAccessor.ReadWrite;
            }
        }

        void ImportAnyAttributeMember(XmlSchemaAnyAttribute any, CodeIdentifiers members, CodeIdentifiers membersScope) {
            SpecialMapping mapping = new SpecialMapping();
            mapping.TypeDesc = Scope.GetTypeDesc(typeof(XmlAttribute));
            mapping.TypeName = mapping.TypeDesc.Name;

            AttributeAccessor accessor = new AttributeAccessor();
            accessor.Any = true;
            accessor.Mapping = mapping;

            MemberMapping member = new MemberMapping();
            member.Elements = new ElementAccessor[0];
            member.Attribute = accessor;
            member.Name = membersScope.MakeRightCase("AnyAttr");
            member.Name = membersScope.AddUnique(member.Name, member);
            members.Add(member.Name, member);
            member.TypeDesc = ((TypeMapping)accessor.Mapping).TypeDesc;
            member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc();
        }

        bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberName) {
            xmlnsMemberName = null;
            if (type.Annotation == null)
                return false;
            if (type.Annotation.Items == null || type.Annotation.Items.Count == 0)
                return false;

            foreach(XmlSchemaObject o in type.Annotation.Items) {
                if (o is XmlSchemaAppInfo) {
                    XmlNode[] nodes = ((XmlSchemaAppInfo)o).Markup;
                    if (nodes != null && nodes.Length > 0) {
                        foreach(XmlNode node in nodes) {
                            if (node is XmlElement) {
                                XmlElement e = (XmlElement)node;
                                if (e.Name == "keepNamespaceDeclarations") {
                                    if (e.LastNode is XmlText) {
                                        xmlnsMemberName = (((XmlText)e.LastNode).Value).Trim(null);
                                    }
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            return false; 
        }

        void ImportXmlnsDeclarationsMember(XmlSchemaType type, CodeIdentifiers members, CodeIdentifiers membersScope) {
            string xmlnsMemberName;
            if (!KeepXmlnsDeclarations(type, out xmlnsMemberName))
                return;
            TypeDesc xmlnsTypeDesc = Scope.GetTypeDesc(typeof(XmlSerializerNamespaces));
            StructMapping xmlnsMapping = new StructMapping();

            xmlnsMapping.TypeDesc = xmlnsTypeDesc;
            xmlnsMapping.TypeName = xmlnsMapping.TypeDesc.Name;
            xmlnsMapping.Members = new MemberMapping[0];
            xmlnsMapping.IncludeInSchema = false;
            xmlnsMapping.ReferencedByTopLevelElement = true;
         
            ElementAccessor xmlns = new ElementAccessor();
            xmlns.Mapping = xmlnsMapping;
            
            MemberMapping member = new MemberMapping();
            member.Elements = new ElementAccessor[] {xmlns};
            member.Name = CodeIdentifier.MakeValid(xmlnsMemberName == null ? "Namespaces" : xmlnsMemberName);
            member.Name = membersScope.AddUnique(member.Name, member);
            members.Add(member.Name, member);
            member.TypeDesc = xmlnsTypeDesc;
            member.Xmlns = new XmlnsAccessor();
            member.Ignore = true;
        }

        void ImportAttributeGroupMembers(XmlSchemaAttributeGroup group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string ns) {
            for (int i = 0; i < group.Attributes.Count; i++) {
                object item = group.Attributes[i];
                if (item is XmlSchemaAttributeGroup)
                    ImportAttributeGroupMembers((XmlSchemaAttributeGroup)item, identifier, members, membersScope, ns);
                else if (item is XmlSchemaAttribute)
                    ImportAttributeMember((XmlSchemaAttribute)item, identifier, members, membersScope, ns);
            }
            if (group.AnyAttribute != null)
                ImportAnyAttributeMember(group.AnyAttribute, members, membersScope);
        }

        AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string identifier) {
            PrimitiveMapping mapping = new PrimitiveMapping();
            mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
            mapping.TypeName = mapping.TypeDesc.DataType.Name;
            AttributeAccessor accessor = new AttributeAccessor();
            accessor.Name = name.Name;
            accessor.Namespace = XmlReservedNs.NsXml;
            accessor.CheckSpecial();
            accessor.Mapping = mapping;
            return accessor;
        }

        AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string identifier, string ns, XmlSchemaAttribute defaultValueProvider) {
            if (attribute.Use == XmlSchemaUse.Prohibited) return null;
            if (!attribute.RefName.IsEmpty) {
                if (attribute.RefName.Namespace == XmlReservedNs.NsXml)
                    return ImportSpecialAttribute(attribute.RefName, identifier);
                else
                    return ImportAttribute(FindAttribute(attribute.RefName), identifier, attribute.RefName.Namespace, defaultValueProvider);
            }
            TypeMapping mapping;
            if (attribute.Name.Length == 0) throw new InvalidOperationException(Res.GetString(Res.XmlAttributeHasNoName));
            if (identifier.Length == 0)
                identifier = CodeIdentifier.MakeValid(attribute.Name);
            else
                identifier += CodeIdentifier.MakePascal(attribute.Name);
            if (!attribute.SchemaTypeName.IsEmpty)
                mapping = (TypeMapping)ImportType(attribute.SchemaTypeName, typeof(TypeMapping), null, TypeFlags.CanBeAttributeValue, false);
            else if (attribute.SchemaType != null)
                mapping = ImportDataType((XmlSchemaSimpleType)attribute.SchemaType, ns, identifier, null, TypeFlags.CanBeAttributeValue, false);
            else {
                mapping = GetDefaultMapping(TypeFlags.CanBeAttributeValue);
            }

            // let the extensions to run
            if (mapping != null && !mapping.TypeDesc.IsMappedType) {
                RunSchemaExtensions(mapping, attribute.SchemaTypeName, attribute.SchemaType, attribute, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue);
            }
            AttributeAccessor accessor = new AttributeAccessor();
            accessor.Name = attribute.Name;
            accessor.Namespace = ns;
            accessor.Form = AttributeForm(ns, attribute);
            accessor.CheckSpecial();
            accessor.Mapping = mapping;
            accessor.IsList = mapping.IsList;
            accessor.IsOptional = attribute.Use != XmlSchemaUse.Required;

            if (defaultValueProvider.DefaultValue != null) {
                accessor.Default = defaultValueProvider.DefaultValue;
            }
            else if (defaultValueProvider.FixedValue != null) {
                accessor.Default = defaultValueProvider.FixedValue;
                accessor.IsFixed = true;
            }
            else if (attribute != defaultValueProvider) {
                if (attribute.DefaultValue != null) {
                    accessor.Default = attribute.DefaultValue;
                }
                else if (attribute.FixedValue != null) {
                    accessor.Default = attribute.FixedValue;
                    accessor.IsFixed = true;
                }
            }
            return accessor;
        }

        TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, Type baseType, TypeFlags flags, bool isList) {
            if (baseType != null)
                return ImportStructDataType(dataType, typeNs, identifier, baseType);

            TypeMapping mapping = ImportNonXsdPrimitiveDataType(dataType, typeNs, flags);
            if (mapping != null)
                return mapping;

            if (dataType.Content is XmlSchemaSimpleTypeRestriction) {
                XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;
                foreach (object o in restriction.Facets) {
                    if (o is XmlSchemaEnumerationFacet) {
                        return ImportEnumeratedDataType(dataType, typeNs, identifier, flags, isList);
                    }
                }
                if (restriction.BaseType != null) {
                    return ImportDataType(restriction.BaseType, typeNs, identifier, null, flags, false);
                }
                else {
                    AddReference(restriction.BaseTypeName, TypesInUse, Res.XmlCircularTypeReference);
                    mapping = ImportDataType(FindDataType(restriction.BaseTypeName, flags), restriction.BaseTypeName.Namespace, identifier, null, flags, false);
                    if (restriction.BaseTypeName.Namespace != XmlSchema.Namespace)
                        RemoveReference(restriction.BaseTypeName, TypesInUse);
                    return mapping;
                }
            }
            else if (dataType.Content is XmlSchemaSimpleTypeList || dataType.Content is XmlSchemaSimpleTypeUnion) {
                if (dataType.Content is XmlSchemaSimpleTypeList) {
                    // check if we have enumeration list
                    XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)dataType.Content;
                    if (list.ItemType != null) {
                        mapping = ImportDataType(list.ItemType, typeNs, identifier, null, flags, true);
                        if (mapping != null) {
                            mapping.TypeName = dataType.Name;
                            return mapping;
                        }
                    }
                    else if (list.ItemTypeName != null && !list.ItemTypeName.IsEmpty) {
                        mapping = ImportType(list.ItemTypeName, typeof(TypeMapping), null, TypeFlags.CanBeAttributeValue, true);
                        if (mapping != null && mapping is PrimitiveMapping) {
                            ((PrimitiveMapping)mapping).IsList = true;
                            return mapping;
                        }
                    }
                }
                return GetDefaultMapping(flags);
            }
            return ImportPrimitiveDataType(dataType, flags);
        }

        TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, TypeFlags flags, bool isList) {
            TypeMapping mapping = (TypeMapping)ImportedMappings[dataType];
            if (mapping != null)
                return mapping;

            XmlSchemaType sourceType = dataType;
            while (!sourceType.DerivedFrom.IsEmpty) {
                sourceType = FindType(sourceType.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue);
            }
            if (sourceType is XmlSchemaComplexType) return null;
            TypeDesc sourceTypeDesc = Scope.GetTypeDesc((XmlSchemaSimpleType)sourceType);
            if (sourceTypeDesc != null && sourceTypeDesc.FullName != typeof(string).FullName)
                return ImportPrimitiveDataType(dataType, flags);
            identifier = Accessor.UnescapeName(identifier);
            string typeName = GenerateUniqueTypeName(identifier);
            EnumMapping enumMapping = new EnumMapping();
            enumMapping.IsReference = Schemas.IsReference(dataType);
            enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            if (dataType.Name != null && dataType.Name.Length > 0)
                enumMapping.TypeName = identifier;
            enumMapping.Namespace = typeNs;
            enumMapping.IsFlags = isList;

            CodeIdentifiers constants = new CodeIdentifiers();
            XmlSchemaSimpleTypeContent content = dataType.Content;

            if (content is XmlSchemaSimpleTypeRestriction) {
                XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content;
                for (int i = 0; i < restriction.Facets.Count; i++) {
                    object facet = restriction.Facets[i];
                    if (!(facet is XmlSchemaEnumerationFacet)) continue;
                    XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
                    // validate the enumeration value
                    if (sourceTypeDesc != null && sourceTypeDesc.HasCustomFormatter) {
                        XmlCustomFormatter.ToDefaultValue(enumeration.Value, sourceTypeDesc.FormatterName);
                    }
                    ConstantMapping constant = new ConstantMapping();
                    string constantName = CodeIdentifier.MakeValid(enumeration.Value);
                    constant.Name = constants.AddUnique(constantName, constant);
                    constant.XmlName = enumeration.Value;
                    constant.Value = i;
                }
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            if (isList && enumMapping.Constants.Length > 63) {
                // if we have 64+ flag constants we cannot map the type to long enum, we will use string mapping instead.
                mapping = GetDefaultMapping(TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue);
                ImportedMappings.Add(dataType, mapping);
                return mapping;
            }
            ImportedMappings.Add(dataType, enumMapping);
            Scope.AddTypeMapping(enumMapping);
            return enumMapping;
        }

        internal class ElementComparer : IComparer {
            public int Compare(object o1, object o2) {
                ElementAccessor e1 = (ElementAccessor)o1;
                ElementAccessor e2 = (ElementAccessor)o2;
                return String.Compare(e1.ToString(string.Empty), e2.ToString(string.Empty), StringComparison.Ordinal);
            }
        }

        EnumMapping ImportEnumeratedChoice(ElementAccessor[] choice, string typeNs, string typeName) {
            typeName = GenerateUniqueTypeName(Accessor.UnescapeName(typeName), typeNs);
            EnumMapping enumMapping = new EnumMapping();
            enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            enumMapping.TypeName = typeName;
            enumMapping.Namespace = typeNs;
            enumMapping.IsFlags = false;
            enumMapping.IncludeInSchema = false;

            if (GenerateOrder) {
                Array.Sort(choice, new ElementComparer());
            }
            CodeIdentifiers constants = new CodeIdentifiers();
            for (int i = 0; i < choice.Length; i++) {
                ElementAccessor element = choice[i];
                ConstantMapping constant = new ConstantMapping();
                string constantName = CodeIdentifier.MakeValid(element.Name);
                constant.Name = constants.AddUnique(constantName, constant);
                constant.XmlName = element.ToString(typeNs);
                constant.Value = i;
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            Scope.AddTypeMapping(enumMapping);
            return enumMapping;
        }

        PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType, TypeFlags flags) {
            TypeDesc sourceTypeDesc = GetDataTypeSource(dataType, flags);
            PrimitiveMapping mapping = new PrimitiveMapping();
            mapping.TypeDesc = sourceTypeDesc;
            mapping.TypeName = sourceTypeDesc.DataType.Name;
            mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace;
            return mapping;
        }

        PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string ns, TypeFlags flags) {
            PrimitiveMapping mapping = null;
            TypeDesc typeDesc = null;
            if (dataType.Name != null && dataType.Name.Length != 0) {
                typeDesc = Scope.GetTypeDesc(dataType.Name, ns, flags);
                if (typeDesc != null) {
                    mapping = new PrimitiveMapping();
                    mapping.TypeDesc = typeDesc;
                    mapping.TypeName = typeDesc.DataType.Name;
                    mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : ns;
                }
            }
            return mapping;
        }

        XmlSchemaGroup FindGroup(XmlQualifiedName name) {
            XmlSchemaGroup group = (XmlSchemaGroup)Schemas.Find(name, typeof(XmlSchemaGroup));
            if (group == null)
                throw new InvalidOperationException(Res.GetString(Res.XmlMissingGroup, name.Name));

            return group;
        }

        XmlSchemaAttributeGroup FindAttributeGroup(XmlQualifiedName name) {
            XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)Schemas.Find(name, typeof(XmlSchemaAttributeGroup));
            if (group == null)
                throw new InvalidOperationException(Res.GetString(Res.XmlMissingAttributeGroup, name.Name));

            return group;
        }

        internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) {
            XmlSchemaSimpleTypeContent content = dataType.Content;
            if (content is XmlSchemaSimpleTypeRestriction) {
                return ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName;
            }
            else if (content is XmlSchemaSimpleTypeList) {
                XmlSchemaSimpleTypeList list  = (XmlSchemaSimpleTypeList)content;
                if (list.ItemTypeName != null && !list.ItemTypeName.IsEmpty)
                    return list.ItemTypeName;
                if (list.ItemType != null) {
                    return BaseTypeName(list.ItemType);
                }
            }
            return new XmlQualifiedName("string", XmlSchema.Namespace);
        }

        TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags) {
            TypeDesc typeDesc = null;
            if (dataType.Name != null && dataType.Name.Length != 0) {
                typeDesc = Scope.GetTypeDesc(dataType);
                if (typeDesc != null) return typeDesc;
            }
            XmlQualifiedName qname = BaseTypeName(dataType);
            AddReference(qname, TypesInUse, Res.XmlCircularTypeReference);
            typeDesc = GetDataTypeSource(FindDataType(qname, flags), flags);
            if (qname.Namespace != XmlSchema.Namespace)
                RemoveReference(qname, TypesInUse);

            return typeDesc;
        }

        XmlSchemaSimpleType FindDataType(XmlQualifiedName name, TypeFlags flags) {
            if (name == null || name.IsEmpty) {
                return (XmlSchemaSimpleType)Scope.GetTypeDesc(typeof(string)).DataType;
            }
            TypeDesc typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace, flags);
            if (typeDesc != null && typeDesc.DataType is XmlSchemaSimpleType)
                return (XmlSchemaSimpleType)typeDesc.DataType;
            XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)Schemas.Find(name, typeof(XmlSchemaSimpleType));
            if (dataType != null) {
                return dataType;
            }
            if (name.Namespace == XmlSchema.Namespace)
                return (XmlSchemaSimpleType)Scope.GetTypeDesc("string", XmlSchema.Namespace, flags).DataType;
            else {
                if (name.Name == Soap.Array && name.Namespace == Soap.Encoding) {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInvalidEncoding, name.ToString()));
                }
                else {
                    throw new InvalidOperationException(Res.GetString(Res.XmlMissingDataType, name.ToString()));
                }
            }
        }

        XmlSchemaType FindType(XmlQualifiedName name, TypeFlags flags) {
            if (name == null || name.IsEmpty) {
                return Scope.GetTypeDesc(typeof(string)).DataType;
            }
            object type = Schemas.Find(name, typeof(XmlSchemaComplexType));
            if (type != null) {
                return (XmlSchemaComplexType)type;
            }
            return FindDataType(name, flags);
        }

        XmlSchemaElement FindElement(XmlQualifiedName name) {
            XmlSchemaElement element = (XmlSchemaElement)Schemas.Find(name, typeof(XmlSchemaElement));
            if (element == null) 
                throw new InvalidOperationException(Res.GetString(Res.XmlMissingElement, name.ToString()));
            return element;
        }

        XmlSchemaAttribute FindAttribute(XmlQualifiedName name) {
            XmlSchemaAttribute attribute = (XmlSchemaAttribute)Schemas.Find(name, typeof(XmlSchemaAttribute));
            if (attribute == null) 
                throw new InvalidOperationException(Res.GetString(Res.XmlMissingAttribute, name.Name));

            return attribute;
        }

        XmlSchemaForm ElementForm(string ns, XmlSchemaElement element) {
            if (element.Form == XmlSchemaForm.None) {
                XmlSchemaObject parent = element;
                while (parent.Parent != null) {
                    parent = parent.Parent;
                }
                XmlSchema schema = parent as XmlSchema;

                if (schema != null) {
                    if (ns == null || ns.Length == 0) {
                        return schema.ElementFormDefault == XmlSchemaForm.None ? XmlSchemaForm.Unqualified : schema.ElementFormDefault;
                    }
                    else {
                        XmlSchemas.Preprocess(schema);
                        return element.QualifiedName.Namespace == null || element.QualifiedName.Namespace.Length == 0 ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified;
                    }
                }
                return XmlSchemaForm.Qualified;
            }
            return element.Form;
        }

        internal string FindExtendedAnyElement(XmlSchemaAny any, bool mixed, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, out SchemaImporterExtension extension) {
            extension = null;
            foreach (SchemaImporterExtension ex in Extensions) {
                string typeName = ex.ImportAnyElement(any, mixed, Schemas, this, compileUnit, mainNamespace, Options, CodeProvider);
                if (typeName != null && typeName.Length > 0) {
                    extension = ex;
                    return typeName; 
                }
            }
            return null;
        }

        internal string FindExtendedType(string name, string ns, XmlSchemaObject context, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, out SchemaImporterExtension extension ) {
            extension = null;
            foreach (SchemaImporterExtension ex in Extensions) {
                string typeName = ex.ImportSchemaType(name, ns, context, Schemas, this, compileUnit, mainNamespace, Options, CodeProvider);
                if (typeName != null && typeName.Length > 0) {
                    extension = ex;
                    return typeName; 
                }
            }
            return null;
        }

        internal string FindExtendedType(XmlSchemaType type, XmlSchemaObject context, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, out SchemaImporterExtension extension) {
            extension = null;
            foreach (SchemaImporterExtension ex in Extensions) {
                string typeName = ex.ImportSchemaType(type, context, Schemas, this, compileUnit, mainNamespace, Options, CodeProvider);
                if (typeName != null && typeName.Length > 0) {
                    extension = ex;
                    return typeName; 
                }
            }
            return null;
        }

        XmlSchemaForm AttributeForm(string ns, XmlSchemaAttribute attribute) {
            if (attribute.Form == XmlSchemaForm.None) {
                XmlSchemaObject parent = attribute;
                while (parent.Parent != null) {
                    parent = parent.Parent;
                }
                XmlSchema schema = parent as XmlSchema;
                if (schema != null) {
                    if (ns == null || ns.Length == 0) {
                        return schema.AttributeFormDefault == XmlSchemaForm.None ? XmlSchemaForm.Unqualified : schema.AttributeFormDefault;
                    }
                    else {
                        XmlSchemas.Preprocess(schema);
                        return attribute.QualifiedName.Namespace == null || attribute.QualifiedName.Namespace.Length == 0 ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified;
                    }
                }
                return XmlSchemaForm.Unqualified;
            }
            return attribute.Form;
        }
    }
}