XmlReflectionImporter.cs 42 KB

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