Merge pull request #93 from konrad-kruczynski/dispatcher_timer_fix
[mono.git] / mcs / class / System.XML / System.Xml.Serialization / XmlReflectionImporter.cs
1 // 
2 // System.Xml.Serialization.XmlReflectionImporter 
3 //
4 // Author:
5 //   Tim Coleman (tim@timcoleman.com)
6 //   Erik LeBel (eriklebel@yahoo.ca)
7 //   Lluis Sanchez Gual (lluis@ximian.com)
8 //
9 // Copyright (C) Tim Coleman, 2002
10 // (C) 2003 Erik LeBel
11 //
12
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System.Collections;
35 using System.Collections.Generic;
36 using System.Globalization;
37 using System.Reflection;
38 using System.Xml.Schema;
39
40 namespace System.Xml.Serialization {
41         public class XmlReflectionImporter {
42
43                 string initialDefaultNamespace;
44                 XmlAttributeOverrides attributeOverrides;
45                 ArrayList includedTypes;
46                 ReflectionHelper helper = new ReflectionHelper();
47                 int arrayChoiceCount = 1;
48                 ArrayList relatedMaps = new ArrayList ();
49                 bool allowPrivateTypes = false;
50
51                 static readonly string errSimple = "Cannot serialize object of type '{0}'. Base " +
52                         "type '{1}' has simpleContent and can be only extended by adding XmlAttribute " +
53                         "elements. Please consider changing XmlText member of the base class to string array";
54
55                 static readonly string errSimple2 = "Cannot serialize object of type '{0}'. " +
56                         "Consider changing type of XmlText member '{1}' from '{2}' to string or string array";
57
58                 #region Constructors
59
60                 public XmlReflectionImporter ()
61                         : this (null, null)
62                 {
63                 }
64
65                 public XmlReflectionImporter (string defaultNamespace)
66                         : this (null, defaultNamespace)
67                 {
68                 }
69
70                 public XmlReflectionImporter (XmlAttributeOverrides attributeOverrides)
71                         : this (attributeOverrides, null)
72                 {
73                 }
74
75                 public XmlReflectionImporter (XmlAttributeOverrides attributeOverrides, string defaultNamespace)
76                 {
77                         if (defaultNamespace == null)
78                                 this.initialDefaultNamespace = String.Empty;
79                         else
80                                 this.initialDefaultNamespace = defaultNamespace;
81
82                         if (attributeOverrides == null)
83                                 this.attributeOverrides = new XmlAttributeOverrides();
84                         else
85                                 this.attributeOverrides = attributeOverrides;
86                 }
87
88 /*              void Reset ()
89                 {
90                         helper = new ReflectionHelper();
91                         arrayChoiceCount = 1;
92                 }
93 */
94                 
95                 internal bool AllowPrivateTypes
96                 {
97                         get { return allowPrivateTypes; }
98                         set { allowPrivateTypes = value; }
99                 }
100
101                 #endregion // Constructors
102
103                 #region Methods
104
105                 public XmlMembersMapping ImportMembersMapping (string elementName,
106                         string ns,
107                         XmlReflectionMember [] members,
108                         bool hasWrapperElement)
109                 {
110                         return ImportMembersMapping (elementName, ns, members, hasWrapperElement, true);
111                 }
112
113 #if NET_2_0
114                 [MonoTODO]
115                 public
116 #endif
117                 XmlMembersMapping ImportMembersMapping (string elementName, 
118                         string ns, 
119                         XmlReflectionMember[] members, 
120                         bool hasWrapperElement, 
121                         bool writeAccessors)
122                 {
123                         return ImportMembersMapping (elementName, ns, members, hasWrapperElement, writeAccessors, true);
124                 }
125
126 #if NET_2_0
127                 [MonoTODO]
128                 public
129 #endif
130                 XmlMembersMapping ImportMembersMapping (string elementName, 
131                         string ns, 
132                         XmlReflectionMember[] members, 
133                         bool hasWrapperElement, 
134                         bool writeAccessors, 
135                         bool validate)
136                 {
137                         return ImportMembersMapping (elementName, ns, members, hasWrapperElement, writeAccessors, validate, XmlMappingAccess.Read | XmlMappingAccess.Write);
138                 }
139
140 #if NET_2_0
141                 [MonoTODO] // FIXME: handle writeAccessors, validate, and mapping access
142                 public
143 #endif
144                 XmlMembersMapping ImportMembersMapping (string elementName, 
145                         string ns, 
146                         XmlReflectionMember[] members, 
147                         bool hasWrapperElement, 
148                         bool writeAccessors, 
149                         bool validate,
150                         XmlMappingAccess access)
151                 {
152 //                      Reset ();       Disabled. See ChangeLog
153
154                         ArrayList mapping = new ArrayList ();
155                         for (int n=0; n<members.Length; n++)
156                         {
157                                 if (members[n].XmlAttributes.XmlIgnore) continue;
158                                 XmlTypeMapMember mapMem = CreateMapMember (null, members[n], ns);
159                                 mapMem.GlobalIndex = n;
160                                 mapMem.CheckOptionalValueType (members);
161                                 mapping.Add (new XmlMemberMapping (members[n].MemberName, ns, mapMem, false));
162                         }
163                         elementName = XmlConvert.EncodeLocalName (elementName);
164                         XmlMembersMapping mps = new XmlMembersMapping (elementName, ns, hasWrapperElement, false, (XmlMemberMapping[])mapping.ToArray (typeof(XmlMemberMapping)));
165                         mps.RelatedMaps = relatedMaps;
166                         mps.Format = SerializationFormat.Literal;
167                         Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
168 #if !NET_2_1
169                         mps.Source = new MembersSerializationSource (elementName, hasWrapperElement, members, false, true, ns, extraTypes);
170                         if (allowPrivateTypes) mps.Source.CanBeGenerated = false;
171 #endif
172                         return mps;
173                 }
174
175                 public XmlTypeMapping ImportTypeMapping (Type type)
176                 {
177                         return ImportTypeMapping (type, null, null);
178                 }
179
180                 public XmlTypeMapping ImportTypeMapping (Type type, string defaultNamespace)
181                 {
182                         return ImportTypeMapping (type, null, defaultNamespace);
183                 }
184
185                 public XmlTypeMapping ImportTypeMapping (Type type, XmlRootAttribute group)
186                 {
187                         return ImportTypeMapping (type, group, null);
188                 }
189
190                 public XmlTypeMapping ImportTypeMapping (Type type, XmlRootAttribute root, string defaultNamespace)
191                 {
192                         if (type == null)
193                                 throw new ArgumentNullException ("type");
194
195                         if (type == typeof (void))
196                                 throw new NotSupportedException ("The type " + type.FullName + " may not be serialized.");
197
198                         return ImportTypeMapping (TypeTranslator.GetTypeData (type), root, 
199                                 defaultNamespace);
200                 }
201
202                 internal XmlTypeMapping ImportTypeMapping (TypeData typeData, string defaultNamespace)
203                 {
204                         return ImportTypeMapping (typeData, (XmlRootAttribute) null, 
205                                 defaultNamespace);
206                 }
207
208                 private XmlTypeMapping ImportTypeMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
209                 {
210                         if (typeData == null)
211                                 throw new ArgumentNullException ("typeData");
212
213                         if (typeData.Type == null)
214                                 throw new ArgumentException ("Specified TypeData instance does not have Type set.");
215
216                         if (defaultNamespace == null) defaultNamespace = initialDefaultNamespace;
217                         if (defaultNamespace == null) defaultNamespace = string.Empty;
218
219                         try {
220                                 XmlTypeMapping map;
221
222                                 switch (typeData.SchemaType) {
223                                         case SchemaTypes.Class: map = ImportClassMapping (typeData, root, defaultNamespace); break;
224                                         case SchemaTypes.Array: map = ImportListMapping (typeData, root, defaultNamespace, null, 0); break;
225                                         case SchemaTypes.XmlNode: map = ImportXmlNodeMapping (typeData, root, defaultNamespace); break;
226                                         case SchemaTypes.Primitive: map = ImportPrimitiveMapping (typeData, root, defaultNamespace); break;
227                                         case SchemaTypes.Enum: map = ImportEnumMapping (typeData, root, defaultNamespace); break;
228                                         case SchemaTypes.XmlSerializable: map = ImportXmlSerializableMapping (typeData, root, defaultNamespace); break;
229                                         default: throw new NotSupportedException ("Type " + typeData.Type.FullName + " not supported for XML stialization");
230                                 }
231
232 #if NET_2_0
233                                 // bug #372780
234                                 map.SetKey (typeData.Type.ToString ());
235 #endif
236                                 map.RelatedMaps = relatedMaps;
237                                 map.Format = SerializationFormat.Literal;
238                                 Type[] extraTypes = includedTypes != null ? (Type[]) includedTypes.ToArray (typeof (Type)) : null;
239 #if !NET_2_1
240                                 map.Source = new XmlTypeSerializationSource (typeData.Type, root, attributeOverrides, defaultNamespace, extraTypes);
241                                 if (allowPrivateTypes) map.Source.CanBeGenerated = false;
242 #endif
243                                 return map;
244                         } catch (InvalidOperationException ex) {
245                                 throw new InvalidOperationException (string.Format (CultureInfo.InvariantCulture,
246                                         "There was an error reflecting type '{0}'.", typeData.Type.FullName), ex);
247                         }
248                 }
249
250                 XmlTypeMapping CreateTypeMapping (TypeData typeData, XmlRootAttribute root, string defaultXmlType, string defaultNamespace)
251                 {
252                         string rootNamespace = defaultNamespace;
253                         string typeNamespace = null;
254                         string elementName;
255                         bool includeInSchema = true;
256                         XmlAttributes atts = null;
257                         bool nullable = CanBeNull (typeData);
258
259                         if (defaultXmlType == null) defaultXmlType = typeData.XmlType;
260
261                         if (!typeData.IsListType)
262                         {
263                                 if (attributeOverrides != null) 
264                                         atts = attributeOverrides[typeData.Type];
265
266                                 if (atts != null && typeData.SchemaType == SchemaTypes.Primitive)
267                                         throw new InvalidOperationException ("XmlRoot and XmlType attributes may not be specified for the type " + typeData.FullTypeName);
268                         }
269
270                         if (atts == null) 
271                                 atts = new XmlAttributes (typeData.Type);
272
273                         if (atts.XmlRoot != null && root == null)
274                                 root = atts.XmlRoot;
275
276                         if (atts.XmlType != null)
277                         {
278                                 if (atts.XmlType.Namespace != null)
279                                         typeNamespace = atts.XmlType.Namespace;
280
281                                 if (atts.XmlType.TypeName != null && atts.XmlType.TypeName != string.Empty)
282                                         defaultXmlType = XmlConvert.EncodeLocalName (atts.XmlType.TypeName);
283                                         
284                                 includeInSchema = atts.XmlType.IncludeInSchema;
285                         }
286
287                         elementName = defaultXmlType;
288
289                         if (root != null)
290                         {
291                                 if (root.ElementName.Length != 0)
292                                         elementName = XmlConvert.EncodeLocalName(root.ElementName);
293                                 if (root.Namespace != null)
294                                         rootNamespace = root.Namespace;
295                                 nullable = root.IsNullable;
296                         }
297
298                         if (rootNamespace == null) rootNamespace = "";
299                         if (typeNamespace == null) typeNamespace = rootNamespace;
300                         
301                         XmlTypeMapping map;
302                         switch (typeData.SchemaType) {
303                                 case SchemaTypes.XmlSerializable:
304                                         map = new XmlSerializableMapping (root, elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
305                                         break;
306                                 case SchemaTypes.Primitive:
307                                         if (!typeData.IsXsdType)
308                                                 map = new XmlTypeMapping (elementName, rootNamespace, 
309                                                         typeData, defaultXmlType, XmlSerializer.WsdlTypesNamespace);
310                                         else
311                                                 map = new XmlTypeMapping (elementName, rootNamespace, 
312                                                         typeData, defaultXmlType, typeNamespace);
313                                         break;
314                                 default:
315                                         map = new XmlTypeMapping (elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
316                                         break;
317                         }
318
319                         map.IncludeInSchema = includeInSchema;
320                         map.IsNullable = nullable;
321                         relatedMaps.Add (map);
322                         
323                         return map;
324                 }
325
326                 XmlTypeMapping ImportClassMapping (Type type, XmlRootAttribute root, string defaultNamespace)
327                 {
328                         TypeData typeData = TypeTranslator.GetTypeData (type);
329                         return ImportClassMapping (typeData, root, defaultNamespace);
330                 }
331
332                 XmlTypeMapping ImportClassMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
333                 {
334                         Type type = typeData.Type;
335
336                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
337                         if (map != null) return map;
338
339                         if (!allowPrivateTypes)
340                                 ReflectionHelper.CheckSerializableType (type, false);
341                         
342                         map = CreateTypeMapping (typeData, root, null, defaultNamespace);
343                         helper.RegisterClrType (map, type, map.XmlTypeNamespace);
344                         helper.RegisterSchemaType (map, map.XmlType, map.XmlTypeNamespace);
345
346                         // Import members
347
348                         ClassMap classMap = new ClassMap ();
349                         map.ObjectMap = classMap;
350
351                         var members = GetReflectionMembers (type);
352                         bool? isOrderExplicit = null;
353                         foreach (XmlReflectionMember rmember in members)
354                         {
355                                 if (isOrderExplicit == null)
356                                         isOrderExplicit = rmember.XmlAttributes.Order >= 0;
357                                 else if (isOrderExplicit != (rmember.XmlAttributes.Order >= 0))
358                                         throw new InvalidOperationException ("Inconsistent XML sequence was detected. If there are XmlElement/XmlArray/XmlAnyElement attributes with explicit Order, then every other member must have an explicit order too.");
359                         }
360                         if (isOrderExplicit == true)
361                                 members.Sort ((m1, m2) => m1.XmlAttributes.Order - m2.XmlAttributes.Order);
362
363                         foreach (XmlReflectionMember rmember in members)
364                         {
365                                 string ns = map.XmlTypeNamespace;
366                                 if (rmember.XmlAttributes.XmlIgnore) continue;
367                                 if (rmember.DeclaringType != null && rmember.DeclaringType != type) {
368                                         XmlTypeMapping bmap = ImportClassMapping (rmember.DeclaringType, root, defaultNamespace);
369                                         ns = bmap.XmlTypeNamespace;
370                                 }
371
372                                 try {
373                                         XmlTypeMapMember mem = CreateMapMember (type, rmember, ns);
374                                         mem.CheckOptionalValueType (type);
375                                         classMap.AddMember (mem);
376                                 } catch (Exception ex) {
377                                         throw new InvalidOperationException (string.Format (
378                                                 CultureInfo.InvariantCulture, "There was an error" +
379                                                 " reflecting field '{0}'.", rmember.MemberName), ex);
380                                 }
381                         }
382
383                         // Import extra classes
384
385                         if (type == typeof (object) && includedTypes != null)
386                         {
387                                 foreach (Type intype in includedTypes)
388                                         map.DerivedTypes.Add (ImportTypeMapping (intype, defaultNamespace));
389                         }
390
391                         // Register inheritance relations
392
393                         if (type.BaseType != null)
394                         {
395                                 XmlTypeMapping bmap = ImportClassMapping (type.BaseType, root, defaultNamespace);
396                                 ClassMap cbmap = bmap.ObjectMap as ClassMap;
397                                 
398                                 if (type.BaseType != typeof (object)) {
399                                         map.BaseMap = bmap;
400                                         if (!cbmap.HasSimpleContent)
401                                                 classMap.SetCanBeSimpleType (false);
402                                 }
403                                 
404                                 // At this point, derived classes of this map must be already registered
405                                 
406                                 RegisterDerivedMap (bmap, map);
407                                 
408                                 if (cbmap.HasSimpleContent && classMap.ElementMembers != null && classMap.ElementMembers.Count != 1)
409                                         throw new InvalidOperationException (String.Format (errSimple, map.TypeData.TypeName, map.BaseMap.TypeData.TypeName));
410                         }
411                         
412                         ImportIncludedTypes (type, defaultNamespace);
413                         
414                         if (classMap.XmlTextCollector != null && !classMap.HasSimpleContent)
415                         {
416                                 XmlTypeMapMember mem = classMap.XmlTextCollector;
417                                 if (mem.TypeData.Type != typeof(string) && 
418                                    mem.TypeData.Type != typeof(string[]) && 
419 #if !MOONLIGHT
420                                    mem.TypeData.Type != typeof(XmlNode[]) && 
421 #endif
422                                    mem.TypeData.Type != typeof(object[]))
423                                    
424                                         throw new InvalidOperationException (String.Format (errSimple2, map.TypeData.TypeName, mem.Name, mem.TypeData.TypeName));
425                         }
426                         
427                         return map;
428                 }
429                 
430                 void RegisterDerivedMap (XmlTypeMapping map, XmlTypeMapping derivedMap)
431                 {
432                         map.DerivedTypes.Add (derivedMap);
433                         map.DerivedTypes.AddRange (derivedMap.DerivedTypes);
434                         
435                         if (map.BaseMap != null)
436                                 RegisterDerivedMap (map.BaseMap, derivedMap);
437                         else {
438                                 XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
439                                 if (obmap != map)
440                                         obmap.DerivedTypes.Add (derivedMap);
441                         }
442                 }
443
444                 string GetTypeNamespace (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
445                 {
446                         string typeNamespace = null;
447                         
448                         XmlAttributes atts = null;
449                         if (!typeData.IsListType)
450                         {
451                                 if (attributeOverrides != null)
452                                         atts = attributeOverrides[typeData.Type];
453                         }
454
455                         if (atts == null)
456                                 atts = new XmlAttributes (typeData.Type);
457
458                         if (atts.XmlType != null)
459                         {
460                                 if (atts.XmlType.Namespace != null && atts.XmlType.Namespace.Length != 0 && typeData.SchemaType != SchemaTypes.Enum)
461                                         typeNamespace = atts.XmlType.Namespace;
462                         }
463
464                         if (typeNamespace != null && typeNamespace.Length != 0) return typeNamespace;
465                         
466                         if (atts.XmlRoot != null && root == null)
467                                 root = atts.XmlRoot;
468
469                         if (root != null)
470                         {
471                                 if (root.Namespace != null && root.Namespace.Length != 0)
472                                         return root.Namespace;
473                         }
474
475                         if (defaultNamespace == null) return "";
476                         else return defaultNamespace;
477                 }
478
479                 XmlTypeMapping ImportListMapping (Type type, XmlRootAttribute root, string defaultNamespace, XmlAttributes atts, int nestingLevel)
480                 {
481                         TypeData typeData = TypeTranslator.GetTypeData (type);
482                         return ImportListMapping (typeData, root, defaultNamespace, atts, nestingLevel);
483                 }
484
485                 XmlTypeMapping ImportListMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace, XmlAttributes atts, int nestingLevel)
486                 {
487                         Type type = typeData.Type;
488                         ListMap obmap = new ListMap ();
489
490                         if (!allowPrivateTypes)
491                                 ReflectionHelper.CheckSerializableType (type, true);
492                         
493                         if (atts == null) atts = new XmlAttributes();
494                         Type itemType = typeData.ListItemType;
495
496                         // warning: byte[][] should not be considered multiarray
497                         bool isMultiArray = (type.IsArray && (TypeTranslator.GetTypeData(itemType).SchemaType == SchemaTypes.Array) && itemType.IsArray);
498
499                         XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
500
501                         foreach (XmlArrayItemAttribute att in atts.XmlArrayItems)
502                         {
503                                 if (att.Namespace != null && att.Form == XmlSchemaForm.Unqualified)
504                                         throw new InvalidOperationException ("XmlArrayItemAttribute.Form must not be Unqualified when it has an explicit Namespace value.");
505                                 if (att.NestingLevel != nestingLevel) continue;
506                                 Type elemType = (att.Type != null) ? att.Type : itemType;
507                                 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData(elemType, att.DataType));
508                                 elem.Namespace = att.Namespace != null ? att.Namespace : defaultNamespace;
509                                 if (elem.Namespace == null) elem.Namespace = "";
510                                 elem.Form = att.Form;
511                                 if (att.Form == XmlSchemaForm.Unqualified)
512                                         elem.Namespace = string.Empty;
513                                 elem.IsNullable = att.IsNullable && CanBeNull (elem.TypeData);
514                                 elem.NestingLevel = att.NestingLevel;
515
516                                 if (isMultiArray) {
517                                         elem.MappedType = ImportListMapping (elemType, null, elem.Namespace, atts, nestingLevel + 1);
518                                 } else if (elem.TypeData.IsComplexType) {
519                                         elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
520                                 }
521
522                                 if (att.ElementName.Length != 0) {
523                                         elem.ElementName = XmlConvert.EncodeLocalName (att.ElementName);
524                                 } else if (elem.MappedType != null) {
525                                         elem.ElementName = elem.MappedType.ElementName;
526                                 } else {
527                                         elem.ElementName = TypeTranslator.GetTypeData (elemType).XmlType;
528                                 }
529
530                                 list.Add (elem);
531                         }
532
533                         if (list.Count == 0)
534                         {
535                                 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData (itemType));
536                                 if (isMultiArray)
537                                         elem.MappedType = ImportListMapping (itemType, null, defaultNamespace, atts, nestingLevel + 1);
538                                 else if (elem.TypeData.IsComplexType)
539                                         elem.MappedType = ImportTypeMapping (itemType, null, defaultNamespace);
540
541                                 if (elem.MappedType != null) {
542                                         elem.ElementName = elem.MappedType.XmlType;
543                                 } else {
544                                         elem.ElementName = TypeTranslator.GetTypeData (itemType).XmlType;
545                                 }
546
547                                 elem.Namespace = (defaultNamespace != null) ? defaultNamespace : "";
548                                 elem.IsNullable = CanBeNull (elem.TypeData);
549                                 list.Add (elem);
550                         }
551
552                         obmap.ItemInfo = list;
553
554                         // If there can be different element names (types) in the array, then its name cannot
555                         // be "ArrayOfXXX" it must be something like ArrayOfChoiceNNN
556
557                         string baseName;
558                         if (list.Count > 1) {
559                                 baseName = "ArrayOfChoice" + (arrayChoiceCount++);
560                         } else {
561                                 XmlTypeMapElementInfo elem = ((XmlTypeMapElementInfo) list[0]);
562                                 if (elem.MappedType != null) {
563                                         baseName = TypeTranslator.GetArrayName (elem.MappedType.XmlType);
564                                 } else {
565                                         baseName = TypeTranslator.GetArrayName (elem.ElementName);
566                                 }
567                         }
568
569                         // Avoid name colisions
570
571                         int nameCount = 1;
572                         string name = baseName;
573
574                         do {
575                                 XmlTypeMapping foundMap = helper.GetRegisteredSchemaType (name, defaultNamespace);
576                                 if (foundMap == null) nameCount = -1;
577                                 else if (obmap.Equals (foundMap.ObjectMap) && typeData.Type == foundMap.TypeData.Type) return foundMap;
578                                 else name = baseName + (nameCount++);
579                         }
580                         while (nameCount != -1);
581
582                         XmlTypeMapping map = CreateTypeMapping (typeData, root, name, defaultNamespace);
583                         map.ObjectMap = obmap;
584                         
585                         // Register any of the including types as a derived class of object
586                         XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
587                         
588                         XmlTypeMapping objectMapping = ImportTypeMapping (typeof(object));
589                         for (int i = 0; i < includes.Length; i++)
590                         {
591                                 Type includedType = includes[i].Type;
592                                 objectMapping.DerivedTypes.Add(ImportTypeMapping (includedType, null, defaultNamespace));
593                         }
594                         
595                         // Register this map as a derived class of object
596
597                         helper.RegisterSchemaType (map, name, defaultNamespace);
598                         ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
599
600                         return map;
601                 }
602
603                 XmlTypeMapping ImportXmlNodeMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
604                 {
605                         Type type = typeData.Type;
606                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
607                         if (map != null) return map;
608
609                         map = CreateTypeMapping (typeData, root, null, defaultNamespace);
610                         helper.RegisterClrType (map, type, map.XmlTypeNamespace);
611                         
612                         if (type.BaseType != null)
613                         {
614                                 XmlTypeMapping bmap = ImportTypeMapping (type.BaseType, root, defaultNamespace);
615                                 if (type.BaseType != typeof (object))
616                                         map.BaseMap = bmap;
617                                 
618                                 RegisterDerivedMap (bmap, map);
619                         }
620
621                         return map;
622                 }
623
624                 XmlTypeMapping ImportPrimitiveMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
625                 {
626                         Type type = typeData.Type;
627                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
628                         if (map != null) return map;
629                         map = CreateTypeMapping (typeData, root, null, defaultNamespace);
630                         helper.RegisterClrType (map, type, map.XmlTypeNamespace);
631                         return map;
632                 }
633 #if MOONLIGHT
634                 // Enum.GetNames is not available in SL API
635                 public static System.Collections.Generic.IEnumerable<string> GetEnumNames (Type type)
636                 {
637                         System.Collections.Generic.List<string> names = new System.Collections.Generic.List<string> ();
638                         foreach (FieldInfo fi in type.GetFields (BindingFlags.Static | BindingFlags.Public))
639                                 names.Add (fi.Name);
640                         return names;
641                 }
642 #endif
643                 XmlTypeMapping ImportEnumMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
644                 {
645                         Type type = typeData.Type;
646                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
647                         if (map != null) return map;
648                         
649                         if (!allowPrivateTypes)
650                                 ReflectionHelper.CheckSerializableType (type, false);
651                                 
652                         map = CreateTypeMapping (typeData, root, null, defaultNamespace);
653                         map.IsNullable = false;
654                         helper.RegisterClrType (map, type, map.XmlTypeNamespace);
655
656                         ArrayList members = new ArrayList();
657 #if MOONLIGHT
658                         foreach (string name in GetEnumNames (type)) {
659 #else
660                         string [] names = Enum.GetNames (type);
661                         foreach (string name in names) {
662 #endif
663                                 FieldInfo field = type.GetField (name);
664                                 string xmlName = null;
665                                 if (field.IsDefined(typeof(XmlIgnoreAttribute), false))
666                                         continue;
667                                 object[] atts = field.GetCustomAttributes (typeof(XmlEnumAttribute), false);
668                                 if (atts.Length > 0) xmlName = ((XmlEnumAttribute)atts[0]).Name;
669                                 if (xmlName == null) xmlName = name;
670                                 long value = ((IConvertible) field.GetValue (null)).ToInt64 (CultureInfo.InvariantCulture);
671                                 members.Add (new EnumMap.EnumMapMember (xmlName, name, value));
672                         }
673
674                         bool isFlags = type.IsDefined (typeof (FlagsAttribute), false);
675                         map.ObjectMap = new EnumMap ((EnumMap.EnumMapMember[])members.ToArray (typeof(EnumMap.EnumMapMember)), isFlags);
676                         ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
677                         return map;
678                 }
679
680                 XmlTypeMapping ImportXmlSerializableMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
681                 {
682                         Type type = typeData.Type;
683                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
684                         if (map != null) return map;
685                         
686                         if (!allowPrivateTypes)
687                                 ReflectionHelper.CheckSerializableType (type, false);
688                                 
689                         map = CreateTypeMapping (typeData, root, null, defaultNamespace);
690                         helper.RegisterClrType (map, type, map.XmlTypeNamespace);
691                         return map;
692                 }
693
694                 void ImportIncludedTypes (Type type, string defaultNamespace)
695                 {
696                         XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
697                         for (int n=0; n<includes.Length; n++)
698                         {
699                                 Type includedType = includes[n].Type;
700                                 ImportTypeMapping (includedType, null, defaultNamespace);
701                         }
702                 }
703
704                 List<XmlReflectionMember> GetReflectionMembers (Type type)
705                 {
706                         // First we want to find the inheritance hierarchy in reverse order.
707                         Type currentType = type;
708                         ArrayList typeList = new ArrayList();
709                         typeList.Add(currentType);
710                         while (currentType != typeof(object))
711                         {
712                                 currentType = currentType.BaseType; // Read the base type.
713                                 typeList.Insert(0, currentType); // Insert at 0 to reverse the order.
714                         }
715
716                         // Read all Fields via reflection.
717                         ArrayList fieldList = new ArrayList();
718                         FieldInfo[] tfields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
719 #if TARGET_JVM
720                         // This statement ensures fields are ordered starting from the base type.
721                         for (int ti=0; ti<typeList.Count; ti++) {
722                                 for (int i=0; i<tfields.Length; i++) {
723                                         FieldInfo field = tfields[i];
724                                         if (field.DeclaringType == typeList[ti])
725                                                 fieldList.Add (field);
726                                 }
727                         }
728 #else
729                         currentType = null;
730                         int currentIndex = 0;
731                         foreach (FieldInfo field in tfields)
732                         {
733                                 // This statement ensures fields are ordered starting from the base type.
734                                 if (currentType != field.DeclaringType)
735                                 {
736                                         currentType = field.DeclaringType;
737                                         currentIndex=0;
738                                 }
739                                 fieldList.Insert(currentIndex++, field);
740                         }
741 #endif
742                         // Read all Properties via reflection.
743                         ArrayList propList = new ArrayList();
744                         PropertyInfo[] tprops = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
745 #if TARGET_JVM
746                         // This statement ensures properties are ordered starting from the base type.
747                         for (int ti=0; ti<typeList.Count; ti++) {
748                                 for (int i=0; i<tprops.Length; i++) {
749                                         PropertyInfo prop = tprops[i];
750                                         if (!prop.CanRead) continue;
751                                         if (prop.GetIndexParameters().Length > 0) continue;
752                                         if (prop.DeclaringType == typeList[ti])
753                                                 propList.Add (prop);
754                                 }
755                         }
756 #else
757                         currentType = null;
758                         currentIndex = 0;
759                         foreach (PropertyInfo prop in tprops)
760                         {
761                                 // This statement ensures properties are ordered starting from the base type.
762                                 if (currentType != prop.DeclaringType)
763                                 {
764                                         currentType = prop.DeclaringType;
765                                         currentIndex = 0;
766                                 }
767                                 if (!prop.CanRead) continue;
768                                 if (prop.GetIndexParameters().Length > 0) continue;
769                                 propList.Insert(currentIndex++, prop);
770                         }
771 #endif
772                         var members = new List<XmlReflectionMember>();
773                         int fieldIndex=0;
774                         int propIndex=0;
775                         // We now step through the type hierarchy from the base (object) through
776                         // to the supplied class, as each step outputting all Fields, and then
777                         // all Properties.  This is the exact same ordering as .NET 1.0/1.1.
778                         foreach (Type t in typeList)
779                         {
780                                 // Add any fields matching the current DeclaringType.
781                                 while (fieldIndex < fieldList.Count)
782                                 {
783                                         FieldInfo field = (FieldInfo)fieldList[fieldIndex];
784                                         if (field.DeclaringType==t)
785                                         {
786                                                 fieldIndex++;
787                                                 XmlAttributes atts = attributeOverrides[type, field.Name];
788                                                 if (atts == null) atts = new XmlAttributes (field);
789                                                 if (atts.XmlIgnore) continue;
790                                                 XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
791                                                 member.DeclaringType = field.DeclaringType;
792                                                 members.Add(member);
793                                         }
794                                         else break;
795                                 }
796
797                                 // Add any properties matching the current DeclaringType.
798                                 while (propIndex < propList.Count)
799                                 {
800                                         PropertyInfo prop = (PropertyInfo)propList[propIndex];
801                                         if (prop.DeclaringType==t)
802                                         {
803                                                 propIndex++;
804                                                 XmlAttributes atts = attributeOverrides[type, prop.Name];
805                                                 if (atts == null) atts = new XmlAttributes (prop);
806                                                 if (atts.XmlIgnore) continue;
807                                                 if (!prop.CanWrite) {
808                                                         if (prop.PropertyType.IsGenericType && TypeData.GetGenericListItemType (prop.PropertyType) == null) continue; // check this before calling GetTypeData() which raises error for missing Add(). See bug #704813.
809                                                         if (TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array || prop.PropertyType.IsArray) continue;
810                                                 }
811                                                 XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
812                                                 member.DeclaringType = prop.DeclaringType;
813                                                 members.Add(member);
814                                         }
815                                         else break;
816                                 }
817                         }
818                         
819                         return members;
820                 }
821                 
822                 private XmlTypeMapMember CreateMapMember (Type declaringType, XmlReflectionMember rmember, string defaultNamespace)
823                 {
824                         XmlTypeMapMember mapMember;
825                         XmlAttributes atts = rmember.XmlAttributes;
826                         TypeData typeData = TypeTranslator.GetTypeData (rmember.MemberType);
827
828                         if (atts.XmlArray != null) {
829                                 if (atts.XmlArray.Namespace != null && atts.XmlArray.Form == XmlSchemaForm.Unqualified)
830                                         throw new InvalidOperationException ("XmlArrayAttribute.Form must not be Unqualified when it has an explicit Namespace value.");
831                                 if (typeData.SchemaType != SchemaTypes.Array &&
832                                     !(typeData.SchemaType == SchemaTypes.Primitive && typeData.Type == typeof (byte [])))
833                                         throw new InvalidOperationException ("XmlArrayAttribute can be applied to members of array or collection type.");
834                         }
835
836 #if !MOONLIGHT
837                         if (atts.XmlAnyAttribute != null)
838                         {
839                                 if ( (rmember.MemberType.FullName == "System.Xml.XmlAttribute[]") ||
840                                          (rmember.MemberType.FullName == "System.Xml.XmlNode[]") )
841                                 {
842                                         mapMember = new XmlTypeMapMemberAnyAttribute();
843                                 }
844                                 else
845                                         throw new InvalidOperationException ("XmlAnyAttributeAttribute can only be applied to members of type XmlAttribute[] or XmlNode[]");
846                         }
847                         else
848 #endif
849                         if (atts.XmlAnyElements != null && atts.XmlAnyElements.Count > 0)
850                         {
851                                 // no XmlNode type check is done here (seealso: bug #553032).
852                                 XmlTypeMapMemberAnyElement member = new XmlTypeMapMemberAnyElement();
853                                 member.ElementInfo = ImportAnyElementInfo (defaultNamespace, rmember, member, atts);
854                                 mapMember = member;
855                         }
856                         else if (atts.Xmlns)
857                         {
858                                 XmlTypeMapMemberNamespaces mapNamespaces = new XmlTypeMapMemberNamespaces ();
859                                 mapMember = mapNamespaces;
860                         }
861                         else if (atts.XmlAttribute != null)
862                         {
863                                 // An attribute
864
865                                 if (atts.XmlElements != null && atts.XmlElements.Count > 0)
866                                         throw new Exception ("XmlAttributeAttribute and XmlElementAttribute cannot be applied to the same member");
867
868                                 XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute ();
869                                 if (atts.XmlAttribute.AttributeName.Length == 0) 
870                                         mapAttribute.AttributeName = rmember.MemberName;
871                                 else 
872                                         mapAttribute.AttributeName = atts.XmlAttribute.AttributeName;
873
874                                 mapAttribute.AttributeName = XmlConvert.EncodeLocalName (mapAttribute.AttributeName);
875
876                                 if (typeData.IsComplexType)
877                                         mapAttribute.MappedType = ImportTypeMapping (typeData.Type, null, defaultNamespace);
878
879                                 if (atts.XmlAttribute.Namespace != null && atts.XmlAttribute.Namespace != defaultNamespace)
880                                 {
881                                         if (atts.XmlAttribute.Form == XmlSchemaForm.Unqualified)
882                                                 throw new InvalidOperationException ("The Form property may not be 'Unqualified' when an explicit Namespace property is present");
883                                         mapAttribute.Form = XmlSchemaForm.Qualified;
884                                         mapAttribute.Namespace = atts.XmlAttribute.Namespace;
885                                 }
886                                 else
887                                 {
888                                         mapAttribute.Form = atts.XmlAttribute.Form;
889                                         if (atts.XmlAttribute.Form == XmlSchemaForm.Qualified)
890                                                 mapAttribute.Namespace = defaultNamespace;
891                                         else
892                                                 mapAttribute.Namespace = "";
893                                 }
894                                 
895                                 typeData = TypeTranslator.GetTypeData(rmember.MemberType, atts.XmlAttribute.DataType);
896                                 mapMember = mapAttribute;
897                         }
898                         else if (typeData.SchemaType == SchemaTypes.Array)
899                         {
900                                 // If the member has a single XmlElementAttribute and the type is the type of the member,
901                                 // then it is not a flat list
902                                 
903                                 if (atts.XmlElements.Count > 1 ||
904                                    (atts.XmlElements.Count == 1 && atts.XmlElements[0].Type != typeData.Type) ||
905                                    (atts.XmlText != null))
906                                 {
907                                         // A flat list
908
909                                         // check that it does not have XmlArrayAttribute
910                                         if (atts.XmlArray != null)
911                                                 throw new InvalidOperationException ("XmlArrayAttribute cannot be used with members which also attributed with XmlElementAttribute or XmlTextAttribute.");
912
913                                         XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList ();
914                                         member.ListMap = new ListMap ();
915                                         member.ListMap.ItemInfo = ImportElementInfo (declaringType, XmlConvert.EncodeLocalName (rmember.MemberName), defaultNamespace, typeData.ListItemType, member, atts);
916                                         member.ElementInfo = member.ListMap.ItemInfo;
917                                         member.ListMap.ChoiceMember = member.ChoiceMember;
918                                         mapMember = member;
919                                 }
920                                 else
921                                 {
922                                         // A list
923
924                                         XmlTypeMapMemberList member = new XmlTypeMapMemberList ();
925
926                                         // Creates an ElementInfo that identifies the array instance. 
927                                         member.ElementInfo = new XmlTypeMapElementInfoList();
928                                         XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, typeData);
929                                         elem.ElementName = XmlConvert.EncodeLocalName((atts.XmlArray != null && atts.XmlArray.ElementName.Length != 0) ? atts.XmlArray.ElementName : rmember.MemberName);
930                                         // note that it could be changed below (when Form is Unqualified)
931                                         elem.Namespace = (atts.XmlArray != null && atts.XmlArray.Namespace != null) ? atts.XmlArray.Namespace : defaultNamespace;
932                                         elem.MappedType = ImportListMapping (rmember.MemberType, null, elem.Namespace, atts, 0);
933                                         elem.IsNullable = (atts.XmlArray != null) ? atts.XmlArray.IsNullable : false;
934                                         elem.Form = (atts.XmlArray != null) ? atts.XmlArray.Form : XmlSchemaForm.Qualified;
935                                         elem.ExplicitOrder = (atts.XmlArray != null) ? atts.XmlArray.Order : -1;
936                                         // This is a bit tricky, but is done
937                                         // after filling descendant members, so
938                                         // that array items could be serialized
939                                         // with proper namespace.
940                                         if (atts.XmlArray != null && atts.XmlArray.Form == XmlSchemaForm.Unqualified)
941                                                 elem.Namespace = String.Empty;
942
943                                         member.ElementInfo.Add (elem);
944                                         mapMember = member;
945                                 }
946                         }
947                         else
948                         {
949                                 // An element
950
951                                 XmlTypeMapMemberElement member = new XmlTypeMapMemberElement ();
952                                 member.ElementInfo = ImportElementInfo (declaringType, XmlConvert.EncodeLocalName(rmember.MemberName), defaultNamespace, rmember.MemberType, member, atts);
953                                 mapMember = member;
954                         }
955
956                         mapMember.DefaultValue = GetDefaultValue (typeData, atts.XmlDefaultValue);
957                         mapMember.TypeData = typeData;
958                         mapMember.Name = rmember.MemberName;
959                         mapMember.IsReturnValue = rmember.IsReturnValue;
960                         return mapMember;
961                 }
962
963                 XmlTypeMapElementInfoList ImportElementInfo (Type cls, string defaultName, string defaultNamespace, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts)
964                 {
965                         EnumMap choiceEnumMap = null;
966                         Type choiceEnumType = null;
967                         
968                         XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
969                         ImportTextElementInfo (list, defaultType, member, atts, defaultNamespace);
970                         
971                         if (atts.XmlChoiceIdentifier != null) {
972                                 if (cls == null)
973                                         throw new InvalidOperationException ("XmlChoiceIdentifierAttribute not supported in this context.");
974                                         
975                                 member.ChoiceMember = atts.XmlChoiceIdentifier.MemberName;
976                                 MemberInfo[] mems = cls.GetMember (member.ChoiceMember, BindingFlags.Instance|BindingFlags.Public);
977                                 
978                                 if (mems.Length == 0)
979                                         throw new InvalidOperationException ("Choice member '" + member.ChoiceMember + "' not found in class '" + cls);
980                                         
981                                 if (mems[0] is PropertyInfo) {
982                                         PropertyInfo pi = (PropertyInfo)mems[0];
983                                         if (!pi.CanWrite || !pi.CanRead)
984                                                 throw new InvalidOperationException ("Choice property '" + member.ChoiceMember + "' must be read/write.");
985                                         choiceEnumType = pi.PropertyType;
986                                 }
987                                 else choiceEnumType = ((FieldInfo)mems[0]).FieldType;
988                                 
989                                 member.ChoiceTypeData = TypeTranslator.GetTypeData (choiceEnumType);
990                                 
991                                 if (choiceEnumType.IsArray)
992                                         choiceEnumType = choiceEnumType.GetElementType ();
993                                 
994                                 choiceEnumMap = ImportTypeMapping (choiceEnumType).ObjectMap as EnumMap;
995                                 if (choiceEnumMap == null)
996                                         throw new InvalidOperationException ("The member '" + mems[0].Name + "' is not a valid target for XmlChoiceIdentifierAttribute.");
997                         }
998                         
999                         if (atts.XmlElements.Count == 0 && list.Count == 0)
1000                         {
1001                                 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType));
1002                                 elem.ElementName = defaultName;
1003                                 elem.Namespace = defaultNamespace;
1004                                 if (elem.TypeData.IsComplexType)
1005                                         elem.MappedType = ImportTypeMapping (defaultType, null, defaultNamespace);
1006                                 list.Add (elem);
1007                         }
1008
1009                         bool multiType = (atts.XmlElements.Count > 1);
1010                         foreach (XmlElementAttribute att in atts.XmlElements)
1011                         {
1012                                 Type elemType = (att.Type != null) ? att.Type : defaultType;
1013                                 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(elemType, att.DataType));
1014                                 elem.Form = att.Form;
1015                                 if (elem.Form != XmlSchemaForm.Unqualified)
1016                                         elem.Namespace = (att.Namespace != null) ? att.Namespace : defaultNamespace;
1017                                 elem.IsNullable = att.IsNullable;
1018                                 elem.ExplicitOrder = att.Order;
1019
1020                                 if (elem.IsNullable && !elem.TypeData.IsNullable)
1021                                         throw new InvalidOperationException ("IsNullable may not be 'true' for value type " + elem.TypeData.FullTypeName + " in member '" + defaultName + "'");
1022                                         
1023                                 if (elem.TypeData.IsComplexType)
1024                                 {
1025                                         if (att.DataType.Length != 0) throw new InvalidOperationException (
1026                                                 string.Format(CultureInfo.InvariantCulture, "'{0}' is "
1027                                                         + "an invalid value for '{1}.{2}' of type '{3}'. "
1028                                                         + "The property may only be specified for primitive types.",
1029                                                         att.DataType, cls.FullName, defaultName, 
1030                                                         elem.TypeData.FullTypeName));
1031                                         elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
1032                                 }
1033
1034                                 if (att.ElementName.Length != 0)  {
1035                                         elem.ElementName = XmlConvert.EncodeLocalName(att.ElementName);
1036                                 } else if (multiType) {
1037                                         if (elem.MappedType != null) {
1038                                                 elem.ElementName = elem.MappedType.ElementName;
1039                                         } else {
1040                                                 elem.ElementName = TypeTranslator.GetTypeData (elemType).XmlType;
1041                                         }
1042                                 } else {
1043                                         elem.ElementName = defaultName;
1044                                 }
1045
1046                                 if (choiceEnumMap != null) {
1047                                         string cname = choiceEnumMap.GetEnumName (choiceEnumType.FullName, elem.ElementName);
1048                                         if (cname == null)
1049                                                 throw new InvalidOperationException (string.Format (
1050                                                         CultureInfo.InvariantCulture, "Type {0} is missing"
1051                                                         + " enumeration value '{1}' for element '{1} from"
1052                                                         + " namespace '{2}'.", choiceEnumType, elem.ElementName,
1053                                                         elem.Namespace));
1054                                         elem.ChoiceValue = Enum.Parse (choiceEnumType, cname, false);
1055                                 }
1056                                         
1057                                 list.Add (elem);
1058                         }
1059                         return list;
1060                 }
1061
1062                 XmlTypeMapElementInfoList ImportAnyElementInfo (string defaultNamespace, XmlReflectionMember rmember, XmlTypeMapMemberElement member, XmlAttributes atts)
1063                 {
1064                         XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
1065
1066                         ImportTextElementInfo (list, rmember.MemberType, member, atts, defaultNamespace);
1067
1068 #if !MOONLIGHT // no practical anyElement support
1069                         foreach (XmlAnyElementAttribute att in atts.XmlAnyElements)
1070                         {
1071                                 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(typeof(XmlElement)));
1072                                 if (att.Name.Length != 0) 
1073                                 {
1074                                         elem.ElementName = XmlConvert.EncodeLocalName(att.Name);
1075                                         elem.Namespace = (att.Namespace != null) ? att.Namespace : "";
1076                                 }
1077                                 else 
1078                                 {
1079                                         elem.IsUnnamedAnyElement = true;
1080                                         elem.Namespace = defaultNamespace;
1081                                         if (att.Namespace != null) 
1082                                                 throw new InvalidOperationException ("The element " + rmember.MemberName + " has been attributed with an XmlAnyElementAttribute and a namespace '" + att.Namespace + "', but no name. When a namespace is supplied, a name is also required. Supply a name or remove the namespace.");
1083                                 }
1084                                 elem.ExplicitOrder = att.Order;
1085                                 list.Add (elem);
1086                         }
1087 #endif
1088                         return list;
1089                 }
1090
1091                 void ImportTextElementInfo (XmlTypeMapElementInfoList list, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts, string defaultNamespace)
1092                 {
1093                         if (atts.XmlText != null)
1094                         {
1095                                 member.IsXmlTextCollector = true;
1096                                 if (atts.XmlText.Type != null) {
1097                                         TypeData td = TypeTranslator.GetTypeData (defaultType);
1098                                         if ((td.SchemaType == SchemaTypes.Primitive || td.SchemaType == SchemaTypes.Enum) && atts.XmlText.Type != defaultType) {
1099                                                 throw new InvalidOperationException ("The type for XmlText may not be specified for primitive types.");
1100                                         }
1101                                         defaultType = atts.XmlText.Type;
1102                                 }
1103 #if !MOONLIGHT
1104                                 if (defaultType == typeof(XmlNode)) defaultType = typeof(XmlText);      // Nodes must be text nodes
1105 #endif
1106
1107                                 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType, atts.XmlText.DataType));
1108
1109                                 if (elem.TypeData.SchemaType != SchemaTypes.Primitive &&
1110                                         elem.TypeData.SchemaType != SchemaTypes.Enum &&
1111                                     elem.TypeData.SchemaType != SchemaTypes.XmlNode &&
1112                                     !(elem.TypeData.SchemaType == SchemaTypes.Array && elem.TypeData.ListItemTypeData.SchemaType == SchemaTypes.XmlNode)
1113                                  )
1114                                         throw new InvalidOperationException ("XmlText cannot be used to encode complex types");
1115
1116                                 if (elem.TypeData.IsComplexType)
1117                                         elem.MappedType = ImportTypeMapping (defaultType, null, defaultNamespace);
1118                                 elem.IsTextElement = true;
1119                                 elem.WrappedElement = false;
1120                                 list.Add (elem);
1121                         }
1122                 }
1123                 
1124                 bool CanBeNull (TypeData type)
1125                 {
1126 #if !NET_2_0    // idiotic compatibility
1127                         if (type.Type == typeof (XmlQualifiedName))
1128                                 return false;
1129 #endif
1130                         return !type.Type.IsValueType || type.IsNullable;
1131                 }
1132                 
1133                 public void IncludeType (Type type)
1134                 {
1135                         if (type == null)
1136                                 throw new ArgumentNullException ("type");
1137
1138                         if (includedTypes == null) includedTypes = new ArrayList ();
1139                         if (!includedTypes.Contains (type))
1140                                 includedTypes.Add (type);
1141                         
1142                         if (relatedMaps.Count > 0) {
1143                                 foreach (XmlTypeMapping map in (ArrayList) relatedMaps.Clone ()) {
1144                                         if (map.TypeData.Type == typeof(object))
1145                                                 map.DerivedTypes.Add (ImportTypeMapping (type));
1146                                 }
1147                         }
1148                 }
1149
1150                 public void IncludeTypes (ICustomAttributeProvider provider)
1151                 { 
1152                         object[] ats = provider.GetCustomAttributes (typeof(XmlIncludeAttribute), true);
1153                         
1154                         foreach (XmlIncludeAttribute at in ats)
1155                                 IncludeType (at.Type);
1156                 }
1157
1158                 private object GetDefaultValue (TypeData typeData, object defaultValue)
1159                 {
1160                         if (defaultValue == DBNull.Value || typeData.SchemaType != SchemaTypes.Enum)
1161                                 return defaultValue;
1162
1163 #if MOONLIGHT
1164                         string namedValue = (defaultValue as Enum).ToString ("g");
1165                         string decimalValue = (defaultValue as Enum).ToString ("d");
1166 #else
1167                         // get string representation of enum value
1168                         string namedValue = Enum.Format (typeData.Type, defaultValue, "g");
1169                         // get decimal representation of enum value
1170                         string decimalValue = Enum.Format (typeData.Type, defaultValue, "d");
1171 #endif
1172                         // if decimal representation matches string representation, then
1173                         // the value is not defined in the enum type (as the "g" format
1174                         // will return the decimal equivalent of the value if the value
1175                         // is not equal to a combination of named enumerated constants
1176                         if (namedValue == decimalValue) {
1177                                 string msg = string.Format (CultureInfo.InvariantCulture,
1178                                         "Value '{0}' cannot be converted to {1}.", defaultValue,
1179                                         defaultValue.GetType ().FullName);
1180                                 throw new InvalidOperationException (msg);
1181                         }
1182
1183                         // XmlSerializer expects integral enum value
1184                         //return namedValue.Replace (',', ' ');
1185                         return defaultValue;
1186                 }
1187
1188                 #endregion // Methods
1189         }
1190 }