XmlReflectionImporter.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. // Reset (); Disabled. See ChangeLog
  93. XmlMemberMapping[] mapping = new XmlMemberMapping[members.Length];
  94. for (int n=0; n<members.Length; n++)
  95. {
  96. XmlTypeMapMember mapMem = CreateMapMember (null, members[n], ns);
  97. mapping[n] = new XmlMemberMapping (members[n].MemberName, ns, mapMem, false);
  98. }
  99. elementName = XmlConvert.EncodeLocalName (elementName);
  100. XmlMembersMapping mps = new XmlMembersMapping (elementName, ns, hasWrapperElement, false, mapping);
  101. mps.RelatedMaps = relatedMaps;
  102. mps.Format = SerializationFormat.Literal;
  103. Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
  104. mps.Source = new MembersSerializationSource (elementName, hasWrapperElement, members, false, true, ns, extraTypes);
  105. if (allowPrivateTypes) mps.Source.CanBeGenerated = false;
  106. return mps;
  107. }
  108. #if NET_2_0
  109. [MonoTODO]
  110. public XmlMembersMapping ImportMembersMapping (string elementName,
  111. string ns,
  112. XmlReflectionMember[] members,
  113. bool hasWrapperElement,
  114. bool rpc)
  115. {
  116. throw new NotImplementedException ();
  117. }
  118. [MonoTODO]
  119. public XmlMembersMapping ImportMembersMapping (string elementName,
  120. string ns,
  121. XmlReflectionMember[] members,
  122. bool hasWrapperElement,
  123. bool rpc,
  124. bool openModel)
  125. {
  126. throw new NotImplementedException ();
  127. }
  128. #endif
  129. public XmlTypeMapping ImportTypeMapping (Type type)
  130. {
  131. return ImportTypeMapping (type, null, null);
  132. }
  133. public XmlTypeMapping ImportTypeMapping (Type type, string defaultNamespace)
  134. {
  135. return ImportTypeMapping (type, null, defaultNamespace);
  136. }
  137. public XmlTypeMapping ImportTypeMapping (Type type, XmlRootAttribute group)
  138. {
  139. return ImportTypeMapping (type, group, null);
  140. }
  141. public XmlTypeMapping ImportTypeMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  142. {
  143. if (type == null)
  144. throw new ArgumentNullException ("type");
  145. if (type == typeof (void))
  146. throw new InvalidOperationException ("Type " + type.Name + " may not be serialized.");
  147. if (defaultNamespace == null) defaultNamespace = initialDefaultNamespace;
  148. if (defaultNamespace == null) defaultNamespace = string.Empty;
  149. XmlTypeMapping map;
  150. switch (TypeTranslator.GetTypeData(type).SchemaType)
  151. {
  152. case SchemaTypes.Class: map = ImportClassMapping (type, root, defaultNamespace); break;
  153. case SchemaTypes.Array: map = ImportListMapping (type, root, defaultNamespace, null, 0); break;
  154. case SchemaTypes.XmlNode: map = ImportXmlNodeMapping (type, root, defaultNamespace); break;
  155. case SchemaTypes.Primitive: map = ImportPrimitiveMapping (type, root, defaultNamespace); break;
  156. case SchemaTypes.Enum: map = ImportEnumMapping (type, root, defaultNamespace); break;
  157. case SchemaTypes.XmlSerializable: map = ImportXmlSerializableMapping (type, root, defaultNamespace); break;
  158. default: throw new NotSupportedException ("Type " + type.FullName + " not supported for XML stialization");
  159. }
  160. map.RelatedMaps = relatedMaps;
  161. map.Format = SerializationFormat.Literal;
  162. Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
  163. map.Source = new XmlTypeSerializationSource (type, root, attributeOverrides, defaultNamespace, extraTypes);
  164. if (allowPrivateTypes) map.Source.CanBeGenerated = false;
  165. return map;
  166. }
  167. XmlTypeMapping CreateTypeMapping (TypeData typeData, XmlRootAttribute root, string defaultXmlType, string defaultNamespace)
  168. {
  169. string rootNamespace = defaultNamespace;
  170. string typeNamespace = null;
  171. string elementName;
  172. bool includeInSchema = true;
  173. XmlAttributes atts = null;
  174. bool nullable = true;
  175. if (defaultXmlType == null) defaultXmlType = typeData.XmlType;
  176. if (!typeData.IsListType)
  177. {
  178. if (attributeOverrides != null)
  179. atts = attributeOverrides[typeData.Type];
  180. if (atts != null && typeData.SchemaType == SchemaTypes.Primitive)
  181. throw new InvalidOperationException ("XmlRoot and XmlType attributes may not be specified for the type " + typeData.FullTypeName);
  182. }
  183. if (atts == null)
  184. atts = new XmlAttributes (typeData.Type);
  185. if (atts.XmlRoot != null && root == null)
  186. root = atts.XmlRoot;
  187. if (atts.XmlType != null)
  188. {
  189. if (atts.XmlType.Namespace != null && typeData.SchemaType != SchemaTypes.Enum)
  190. typeNamespace = atts.XmlType.Namespace;
  191. if (atts.XmlType.TypeName != null && atts.XmlType.TypeName != string.Empty)
  192. defaultXmlType = XmlConvert.EncodeLocalName (atts.XmlType.TypeName);
  193. includeInSchema = atts.XmlType.IncludeInSchema;
  194. }
  195. elementName = defaultXmlType;
  196. if (root != null)
  197. {
  198. if (root.ElementName.Length != 0)
  199. elementName = XmlConvert.EncodeLocalName(root.ElementName);
  200. if (root.Namespace != null)
  201. rootNamespace = root.Namespace;
  202. nullable = root.IsNullable;
  203. }
  204. if (rootNamespace == null) rootNamespace = "";
  205. if (typeNamespace == null) typeNamespace = rootNamespace;
  206. XmlTypeMapping map;
  207. if (typeData.SchemaType == SchemaTypes.XmlSerializable)
  208. map = new XmlSerializableMapping (elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
  209. else
  210. map = new XmlTypeMapping (elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
  211. map.IncludeInSchema = includeInSchema;
  212. map.IsNullable = nullable;
  213. relatedMaps.Add (map);
  214. return map;
  215. }
  216. XmlTypeMapping ImportClassMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  217. {
  218. TypeData typeData = TypeTranslator.GetTypeData (type);
  219. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  220. if (map != null) return map;
  221. if (!allowPrivateTypes)
  222. ReflectionHelper.CheckSerializableType (type, false);
  223. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  224. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  225. helper.RegisterSchemaType (map, map.XmlType, map.XmlTypeNamespace);
  226. // Import members
  227. ClassMap classMap = new ClassMap ();
  228. map.ObjectMap = classMap;
  229. // try
  230. // {
  231. ICollection members = GetReflectionMembers (type);
  232. foreach (XmlReflectionMember rmember in members)
  233. {
  234. string ns = map.XmlTypeNamespace;
  235. if (rmember.XmlAttributes.XmlIgnore) continue;
  236. if (rmember.DeclaringType != null && rmember.DeclaringType != type) {
  237. XmlTypeMapping bmap = ImportClassMapping (rmember.DeclaringType, root, defaultNamespace);
  238. ns = bmap.XmlTypeNamespace;
  239. }
  240. XmlTypeMapMember mem = CreateMapMember (type, rmember, ns);
  241. mem.CheckOptionalValueType (type);
  242. classMap.AddMember (mem);
  243. }
  244. // }
  245. // catch (Exception ex) {
  246. // throw helper.CreateError (map, ex.Message);
  247. // }
  248. // Import extra classes
  249. if (type == typeof (object) && includedTypes != null)
  250. {
  251. foreach (Type intype in includedTypes)
  252. map.DerivedTypes.Add (ImportTypeMapping (intype, defaultNamespace));
  253. }
  254. // Register inheritance relations
  255. if (type.BaseType != null)
  256. {
  257. XmlTypeMapping bmap = ImportClassMapping (type.BaseType, root, defaultNamespace);
  258. ClassMap cbmap = bmap.ObjectMap as ClassMap;
  259. if (type.BaseType != typeof (object)) {
  260. map.BaseMap = bmap;
  261. if (!cbmap.HasSimpleContent)
  262. classMap.SetCanBeSimpleType (false);
  263. }
  264. // At this point, derived classes of this map must be already registered
  265. RegisterDerivedMap (bmap, map);
  266. if (cbmap.HasSimpleContent && classMap.ElementMembers != null && classMap.ElementMembers.Count != 1)
  267. throw new InvalidOperationException (String.Format (errSimple, map.TypeData.TypeName, map.BaseMap.TypeData.TypeName));
  268. }
  269. ImportIncludedTypes (type, defaultNamespace);
  270. if (classMap.XmlTextCollector != null && !classMap.HasSimpleContent)
  271. {
  272. XmlTypeMapMember mem = classMap.XmlTextCollector;
  273. if (mem.TypeData.Type != typeof(string) &&
  274. mem.TypeData.Type != typeof(string[]) &&
  275. mem.TypeData.Type != typeof(object[]) &&
  276. mem.TypeData.Type != typeof(XmlNode[]))
  277. throw new InvalidOperationException (String.Format (errSimple2, map.TypeData.TypeName, mem.Name, mem.TypeData.TypeName));
  278. }
  279. return map;
  280. }
  281. void RegisterDerivedMap (XmlTypeMapping map, XmlTypeMapping derivedMap)
  282. {
  283. map.DerivedTypes.Add (derivedMap);
  284. map.DerivedTypes.AddRange (derivedMap.DerivedTypes);
  285. if (map.BaseMap != null)
  286. RegisterDerivedMap (map.BaseMap, derivedMap);
  287. else {
  288. XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
  289. if (obmap != map)
  290. obmap.DerivedTypes.Add (derivedMap);
  291. }
  292. }
  293. string GetTypeNamespace (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
  294. {
  295. string typeNamespace = null;
  296. XmlAttributes atts = null;
  297. if (!typeData.IsListType)
  298. {
  299. if (attributeOverrides != null)
  300. atts = attributeOverrides[typeData.Type];
  301. }
  302. if (atts == null)
  303. atts = new XmlAttributes (typeData.Type);
  304. if (atts.XmlType != null)
  305. {
  306. if (atts.XmlType.Namespace != null && atts.XmlType.Namespace.Length != 0 && typeData.SchemaType != SchemaTypes.Enum)
  307. typeNamespace = atts.XmlType.Namespace;
  308. }
  309. if (typeNamespace != null && typeNamespace.Length != 0) return typeNamespace;
  310. if (atts.XmlRoot != null && root == null)
  311. root = atts.XmlRoot;
  312. if (root != null)
  313. {
  314. if (root.Namespace != null && root.Namespace.Length != 0)
  315. return root.Namespace;
  316. }
  317. if (defaultNamespace == null) return "";
  318. else return defaultNamespace;
  319. }
  320. XmlTypeMapping ImportListMapping (Type type, XmlRootAttribute root, string defaultNamespace, XmlAttributes atts, int nestingLevel)
  321. {
  322. TypeData typeData = TypeTranslator.GetTypeData (type);
  323. ListMap obmap = new ListMap ();
  324. if (!allowPrivateTypes)
  325. ReflectionHelper.CheckSerializableType (type, true);
  326. if (atts == null) atts = new XmlAttributes();
  327. Type itemType = typeData.ListItemType;
  328. // warning: byte[][] should not be considered multiarray
  329. bool isMultiArray = (type.IsArray && (TypeTranslator.GetTypeData(itemType).SchemaType == SchemaTypes.Array) && itemType.IsArray);
  330. XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
  331. foreach (XmlArrayItemAttribute att in atts.XmlArrayItems)
  332. {
  333. if (att.NestingLevel != nestingLevel) continue;
  334. Type elemType = (att.Type != null) ? att.Type : itemType;
  335. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData(elemType, att.DataType));
  336. elem.Namespace = att.Namespace != null ? att.Namespace : defaultNamespace;
  337. if (elem.Namespace == null) elem.Namespace = "";
  338. elem.Form = att.Form;
  339. elem.IsNullable = att.IsNullable && CanBeNull (elem.TypeData);
  340. elem.NestingLevel = att.NestingLevel;
  341. if (isMultiArray) {
  342. elem.MappedType = ImportListMapping (elemType, null, elem.Namespace, atts, nestingLevel + 1);
  343. } else if (elem.TypeData.IsComplexType) {
  344. elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
  345. }
  346. if (att.ElementName.Length != 0) {
  347. elem.ElementName = XmlConvert.EncodeLocalName (att.ElementName);
  348. } else if (elem.MappedType != null) {
  349. elem.ElementName = elem.MappedType.ElementName;
  350. } else {
  351. elem.ElementName = TypeTranslator.GetTypeData (elemType).XmlType;
  352. }
  353. list.Add (elem);
  354. }
  355. if (list.Count == 0)
  356. {
  357. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData (itemType));
  358. if (isMultiArray)
  359. elem.MappedType = ImportListMapping (itemType, null, defaultNamespace, atts, nestingLevel + 1);
  360. else if (elem.TypeData.IsComplexType)
  361. elem.MappedType = ImportTypeMapping (itemType, null, defaultNamespace);
  362. if (elem.MappedType != null) {
  363. elem.ElementName = elem.MappedType.XmlType;
  364. } else {
  365. elem.ElementName = TypeTranslator.GetTypeData (itemType).XmlType;
  366. }
  367. elem.Namespace = (defaultNamespace != null) ? defaultNamespace : "";
  368. elem.IsNullable = CanBeNull (elem.TypeData);
  369. list.Add (elem);
  370. }
  371. obmap.ItemInfo = list;
  372. // If there can be different element names (types) in the array, then its name cannot
  373. // be "ArrayOfXXX" it must be something like ArrayOfChoiceNNN
  374. string baseName;
  375. if (list.Count > 1) {
  376. baseName = "ArrayOfChoice" + (arrayChoiceCount++);
  377. } else {
  378. XmlTypeMapElementInfo elem = ((XmlTypeMapElementInfo) list[0]);
  379. if (elem.MappedType != null) {
  380. baseName = TypeTranslator.GetArrayName (elem.MappedType.XmlType);
  381. } else {
  382. baseName = TypeTranslator.GetArrayName (elem.ElementName);
  383. }
  384. }
  385. // Avoid name colisions
  386. int nameCount = 1;
  387. string name = baseName;
  388. do {
  389. XmlTypeMapping foundMap = helper.GetRegisteredSchemaType (name, defaultNamespace);
  390. if (foundMap == null) nameCount = -1;
  391. else if (obmap.Equals (foundMap.ObjectMap) && typeData.Type == foundMap.TypeData.Type) return foundMap;
  392. else name = baseName + (nameCount++);
  393. }
  394. while (nameCount != -1);
  395. XmlTypeMapping map = CreateTypeMapping (typeData, root, name, defaultNamespace);
  396. map.ObjectMap = obmap;
  397. // Register any of the including types as a derived class of object
  398. XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
  399. XmlTypeMapping objectMapping = ImportTypeMapping (typeof(object));
  400. for (int i = 0; i < includes.Length; i++)
  401. {
  402. Type includedType = includes[i].Type;
  403. objectMapping.DerivedTypes.Add(ImportTypeMapping (includedType, null, defaultNamespace));
  404. }
  405. // Register this map as a derived class of object
  406. helper.RegisterSchemaType (map, name, defaultNamespace);
  407. ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
  408. return map;
  409. }
  410. XmlTypeMapping ImportXmlNodeMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  411. {
  412. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (TypeTranslator.GetTypeData (type), root, defaultNamespace));
  413. if (map != null) return map;
  414. map = CreateTypeMapping (TypeTranslator.GetTypeData (type), root, null, defaultNamespace);
  415. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  416. if (type.BaseType != null)
  417. {
  418. XmlTypeMapping bmap = ImportTypeMapping (type.BaseType, root, defaultNamespace);
  419. if (type.BaseType != typeof (object))
  420. map.BaseMap = bmap;
  421. RegisterDerivedMap (bmap, map);
  422. }
  423. return map;
  424. }
  425. XmlTypeMapping ImportPrimitiveMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  426. {
  427. TypeData typeData = TypeTranslator.GetTypeData (type);
  428. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  429. if (map != null) return map;
  430. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  431. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  432. return map;
  433. }
  434. XmlTypeMapping ImportEnumMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  435. {
  436. TypeData typeData = TypeTranslator.GetTypeData (type);
  437. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  438. if (map != null) return map;
  439. if (!allowPrivateTypes)
  440. ReflectionHelper.CheckSerializableType (type, false);
  441. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  442. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  443. string [] names = Enum.GetNames (type);
  444. ArrayList members = new ArrayList();
  445. foreach (string name in names)
  446. {
  447. MemberInfo[] mem = type.GetMember (name);
  448. string xmlName = null;
  449. object[] atts = mem[0].GetCustomAttributes (typeof(XmlIgnoreAttribute), false);
  450. if (atts.Length > 0) continue;
  451. atts = mem[0].GetCustomAttributes (typeof(XmlEnumAttribute), false);
  452. if (atts.Length > 0) xmlName = ((XmlEnumAttribute)atts[0]).Name;
  453. if (xmlName == null) xmlName = name;
  454. members.Add (new EnumMap.EnumMapMember (XmlConvert.EncodeLocalName (xmlName), name));
  455. }
  456. bool isFlags = type.GetCustomAttributes (typeof(FlagsAttribute),false).Length > 0;
  457. map.ObjectMap = new EnumMap ((EnumMap.EnumMapMember[])members.ToArray (typeof(EnumMap.EnumMapMember)), isFlags);
  458. ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
  459. return map;
  460. }
  461. XmlTypeMapping ImportXmlSerializableMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  462. {
  463. TypeData typeData = TypeTranslator.GetTypeData (type);
  464. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  465. if (map != null) return map;
  466. if (!allowPrivateTypes)
  467. ReflectionHelper.CheckSerializableType (type, false);
  468. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  469. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  470. return map;
  471. }
  472. void ImportIncludedTypes (Type type, string defaultNamespace)
  473. {
  474. XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
  475. for (int n=0; n<includes.Length; n++)
  476. {
  477. Type includedType = includes[n].Type;
  478. ImportTypeMapping (includedType, null, defaultNamespace);
  479. }
  480. }
  481. ICollection GetReflectionMembers (Type type)
  482. {
  483. // First we want to find the inheritance hierarchy in reverse order.
  484. Type currentType = type;
  485. ArrayList typeList = new ArrayList();
  486. typeList.Add(currentType);
  487. while (currentType != typeof(object))
  488. {
  489. currentType = currentType.BaseType; // Read the base type.
  490. typeList.Insert(0, currentType); // Insert at 0 to reverse the order.
  491. }
  492. // Read all Fields via reflection.
  493. ArrayList fieldList = new ArrayList();
  494. FieldInfo[] tfields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
  495. #if TARGET_JVM
  496. // This statement ensures fields are ordered starting from the base type.
  497. for (int ti=0; ti<typeList.Count; ti++) {
  498. for (int i=0; i<tfields.Length; i++) {
  499. FieldInfo field = tfields[i];
  500. if (field.DeclaringType == typeList[ti])
  501. fieldList.Add (field);
  502. }
  503. }
  504. #else
  505. currentType = null;
  506. int currentIndex = 0;
  507. foreach (FieldInfo field in tfields)
  508. {
  509. // This statement ensures fields are ordered starting from the base type.
  510. if (currentType != field.DeclaringType)
  511. {
  512. currentType = field.DeclaringType;
  513. currentIndex=0;
  514. }
  515. fieldList.Insert(currentIndex++, field);
  516. }
  517. #endif
  518. // Read all Properties via reflection.
  519. ArrayList propList = new ArrayList();
  520. PropertyInfo[] tprops = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
  521. #if TARGET_JVM
  522. // This statement ensures properties are ordered starting from the base type.
  523. for (int ti=0; ti<typeList.Count; ti++) {
  524. for (int i=0; i<tprops.Length; i++) {
  525. PropertyInfo prop = tprops[i];
  526. if (!prop.CanRead) continue;
  527. if (prop.GetIndexParameters().Length > 0) continue;
  528. if (prop.DeclaringType == typeList[ti])
  529. propList.Add (prop);
  530. }
  531. }
  532. #else
  533. currentType = null;
  534. currentIndex = 0;
  535. foreach (PropertyInfo prop in tprops)
  536. {
  537. // This statement ensures properties are ordered starting from the base type.
  538. if (currentType != prop.DeclaringType)
  539. {
  540. currentType = prop.DeclaringType;
  541. currentIndex = 0;
  542. }
  543. if (!prop.CanRead) continue;
  544. if (prop.GetIndexParameters().Length > 0) continue;
  545. propList.Insert(currentIndex++, prop);
  546. }
  547. #endif
  548. ArrayList members = new ArrayList();
  549. int fieldIndex=0;
  550. int propIndex=0;
  551. // We now step through the type hierarchy from the base (object) through
  552. // to the supplied class, as each step outputting all Fields, and then
  553. // all Properties. This is the exact same ordering as .NET 1.0/1.1.
  554. foreach (Type t in typeList)
  555. {
  556. // Add any fields matching the current DeclaringType.
  557. while (fieldIndex < fieldList.Count)
  558. {
  559. FieldInfo field = (FieldInfo)fieldList[fieldIndex];
  560. if (field.DeclaringType==t)
  561. {
  562. fieldIndex++;
  563. XmlAttributes atts = attributeOverrides[type, field.Name];
  564. if (atts == null) atts = new XmlAttributes (field);
  565. if (atts.XmlIgnore) continue;
  566. XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
  567. member.DeclaringType = field.DeclaringType;
  568. members.Add(member);
  569. }
  570. else break;
  571. }
  572. // Add any properties matching the current DeclaringType.
  573. while (propIndex < propList.Count)
  574. {
  575. PropertyInfo prop = (PropertyInfo)propList[propIndex];
  576. if (prop.DeclaringType==t)
  577. {
  578. propIndex++;
  579. XmlAttributes atts = attributeOverrides[type, prop.Name];
  580. if (atts == null) atts = new XmlAttributes (prop);
  581. if (atts.XmlIgnore) continue;
  582. if (!prop.CanWrite && (TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array || prop.PropertyType.IsArray)) continue;
  583. XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
  584. member.DeclaringType = prop.DeclaringType;
  585. members.Add(member);
  586. }
  587. else break;
  588. }
  589. }
  590. return members;
  591. }
  592. private XmlTypeMapMember CreateMapMember (Type declaringType, XmlReflectionMember rmember, string defaultNamespace)
  593. {
  594. XmlTypeMapMember mapMember;
  595. XmlAttributes atts = rmember.XmlAttributes;
  596. TypeData typeData = TypeTranslator.GetTypeData (rmember.MemberType);
  597. if (atts.XmlAnyAttribute != null)
  598. {
  599. if ( (rmember.MemberType.FullName == "System.Xml.XmlAttribute[]") ||
  600. (rmember.MemberType.FullName == "System.Xml.XmlNode[]") )
  601. {
  602. mapMember = new XmlTypeMapMemberAnyAttribute();
  603. }
  604. else
  605. throw new InvalidOperationException ("XmlAnyAttributeAttribute can only be applied to members of type XmlAttribute[] or XmlNode[]");
  606. }
  607. else if (atts.XmlAnyElements != null && atts.XmlAnyElements.Count > 0)
  608. {
  609. if ( (rmember.MemberType.FullName == "System.Xml.XmlElement[]") ||
  610. (rmember.MemberType.FullName == "System.Xml.XmlNode[]") ||
  611. (rmember.MemberType.FullName == "System.Xml.XmlElement"))
  612. {
  613. XmlTypeMapMemberAnyElement member = new XmlTypeMapMemberAnyElement();
  614. member.ElementInfo = ImportAnyElementInfo (defaultNamespace, rmember, member, atts);
  615. mapMember = member;
  616. }
  617. else
  618. throw new InvalidOperationException ("XmlAnyElementAttribute can only be applied to members of type XmlElement, XmlElement[] or XmlNode[]");
  619. }
  620. else if (atts.Xmlns)
  621. {
  622. XmlTypeMapMemberNamespaces mapNamespaces = new XmlTypeMapMemberNamespaces ();
  623. mapMember = mapNamespaces;
  624. }
  625. else if (atts.XmlAttribute != null)
  626. {
  627. // An attribute
  628. if (atts.XmlElements != null && atts.XmlElements.Count > 0)
  629. throw new Exception ("XmlAttributeAttribute and XmlElementAttribute cannot be applied to the same member");
  630. XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute ();
  631. if (atts.XmlAttribute.AttributeName.Length == 0)
  632. mapAttribute.AttributeName = rmember.MemberName;
  633. else
  634. mapAttribute.AttributeName = atts.XmlAttribute.AttributeName;
  635. mapAttribute.AttributeName = XmlConvert.EncodeLocalName (mapAttribute.AttributeName);
  636. if (typeData.IsComplexType)
  637. mapAttribute.MappedType = ImportTypeMapping (typeData.Type, null, mapAttribute.Namespace);
  638. if (atts.XmlAttribute.Namespace != null && atts.XmlAttribute.Namespace != defaultNamespace)
  639. {
  640. if (atts.XmlAttribute.Form == XmlSchemaForm.Unqualified)
  641. throw new InvalidOperationException ("The Form property may not be 'Unqualified' when an explicit Namespace property is present");
  642. mapAttribute.Form = XmlSchemaForm.Qualified;
  643. mapAttribute.Namespace = atts.XmlAttribute.Namespace;
  644. }
  645. else
  646. {
  647. mapAttribute.Form = atts.XmlAttribute.Form;
  648. if (atts.XmlAttribute.Form == XmlSchemaForm.Qualified)
  649. mapAttribute.Namespace = defaultNamespace;
  650. else
  651. mapAttribute.Namespace = "";
  652. }
  653. typeData = TypeTranslator.GetTypeData(rmember.MemberType, atts.XmlAttribute.DataType);
  654. mapMember = mapAttribute;
  655. }
  656. else if (typeData.SchemaType == SchemaTypes.Array)
  657. {
  658. // If the member has a single XmlElementAttribute and the type is the type of the member,
  659. // then it is not a flat list
  660. if (atts.XmlElements.Count > 1 ||
  661. (atts.XmlElements.Count == 1 && atts.XmlElements[0].Type != typeData.Type) ||
  662. (atts.XmlText != null))
  663. {
  664. // A flat list
  665. // TODO: check that it does not have XmlArrayAttribute
  666. XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList ();
  667. member.ListMap = new ListMap ();
  668. member.ListMap.ItemInfo = ImportElementInfo (declaringType, XmlConvert.EncodeLocalName (rmember.MemberName), defaultNamespace, typeData.ListItemType, member, atts);
  669. member.ElementInfo = member.ListMap.ItemInfo;
  670. member.ListMap.ChoiceMember = member.ChoiceMember;
  671. mapMember = member;
  672. }
  673. else
  674. {
  675. // A list
  676. XmlTypeMapMemberList member = new XmlTypeMapMemberList ();
  677. // Creates an ElementInfo that identifies the array instance.
  678. member.ElementInfo = new XmlTypeMapElementInfoList();
  679. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, typeData);
  680. elem.ElementName = XmlConvert.EncodeLocalName((atts.XmlArray != null && atts.XmlArray.ElementName.Length != 0) ? atts.XmlArray.ElementName : rmember.MemberName);
  681. elem.Namespace = (atts.XmlArray != null && atts.XmlArray.Namespace != null) ? atts.XmlArray.Namespace : defaultNamespace;
  682. elem.MappedType = ImportListMapping (rmember.MemberType, null, elem.Namespace, atts, 0);
  683. elem.IsNullable = (atts.XmlArray != null) ? atts.XmlArray.IsNullable : false;
  684. elem.Form = (atts.XmlArray != null) ? atts.XmlArray.Form : XmlSchemaForm.Qualified;
  685. member.ElementInfo.Add (elem);
  686. mapMember = member;
  687. }
  688. }
  689. else
  690. {
  691. // An element
  692. XmlTypeMapMemberElement member = new XmlTypeMapMemberElement ();
  693. member.ElementInfo = ImportElementInfo (declaringType, XmlConvert.EncodeLocalName(rmember.MemberName), defaultNamespace, rmember.MemberType, member, atts);
  694. mapMember = member;
  695. }
  696. mapMember.DefaultValue = atts.XmlDefaultValue;
  697. mapMember.TypeData = typeData;
  698. mapMember.Name = rmember.MemberName;
  699. mapMember.IsReturnValue = rmember.IsReturnValue;
  700. return mapMember;
  701. }
  702. XmlTypeMapElementInfoList ImportElementInfo (Type cls, string defaultName, string defaultNamespace, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts)
  703. {
  704. EnumMap choiceEnumMap = null;
  705. Type choiceEnumType = null;
  706. XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
  707. ImportTextElementInfo (list, defaultType, member, atts);
  708. if (atts.XmlChoiceIdentifier != null) {
  709. if (cls == null)
  710. throw new InvalidOperationException ("XmlChoiceIdentifierAttribute not supported in this context.");
  711. member.ChoiceMember = atts.XmlChoiceIdentifier.MemberName;
  712. MemberInfo[] mems = cls.GetMember (member.ChoiceMember, BindingFlags.Instance|BindingFlags.Public);
  713. if (mems.Length == 0)
  714. throw new InvalidOperationException ("Choice member '" + member.ChoiceMember + "' not found in class '" + cls);
  715. if (mems[0] is PropertyInfo) {
  716. PropertyInfo pi = (PropertyInfo)mems[0];
  717. if (!pi.CanWrite || !pi.CanRead)
  718. throw new InvalidOperationException ("Choice property '" + member.ChoiceMember + "' must be read/write.");
  719. choiceEnumType = pi.PropertyType;
  720. }
  721. else choiceEnumType = ((FieldInfo)mems[0]).FieldType;
  722. member.ChoiceTypeData = TypeTranslator.GetTypeData (choiceEnumType);
  723. if (choiceEnumType.IsArray)
  724. choiceEnumType = choiceEnumType.GetElementType ();
  725. choiceEnumMap = ImportTypeMapping (choiceEnumType).ObjectMap as EnumMap;
  726. if (choiceEnumMap == null)
  727. throw new InvalidOperationException ("The member '" + mems[0].Name + "' is not a valid target for XmlChoiceIdentifierAttribute.");
  728. }
  729. if (atts.XmlElements.Count == 0 && list.Count == 0)
  730. {
  731. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType));
  732. elem.ElementName = defaultName;
  733. elem.Namespace = defaultNamespace;
  734. if (elem.TypeData.IsComplexType)
  735. elem.MappedType = ImportTypeMapping (defaultType, null, defaultNamespace);
  736. list.Add (elem);
  737. }
  738. bool multiType = (atts.XmlElements.Count > 1);
  739. foreach (XmlElementAttribute att in atts.XmlElements)
  740. {
  741. Type elemType = (att.Type != null) ? att.Type : defaultType;
  742. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(elemType, att.DataType));
  743. elem.Namespace = (att.Namespace != null) ? att.Namespace : defaultNamespace;
  744. elem.Form = att.Form;
  745. elem.IsNullable = att.IsNullable;
  746. if (elem.IsNullable && elem.TypeData.IsValueType)
  747. throw new InvalidOperationException ("IsNullable may not be 'true' for value type " + elem.TypeData.FullTypeName + " in member '" + defaultName + "'");
  748. if (elem.TypeData.IsComplexType)
  749. {
  750. if (att.DataType.Length != 0) throw new InvalidOperationException (
  751. string.Format(CultureInfo.InvariantCulture, "'{0}' is "
  752. + "an invalid value for '{1}.{2}' of type '{3}'. "
  753. + "The property may only be specified for primitive types.",
  754. att.DataType, cls.FullName, defaultName,
  755. elem.TypeData.FullTypeName));
  756. elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
  757. }
  758. if (att.ElementName.Length != 0) {
  759. elem.ElementName = XmlConvert.EncodeLocalName(att.ElementName);
  760. } else if (multiType) {
  761. if (elem.MappedType != null) {
  762. elem.ElementName = elem.MappedType.ElementName;
  763. } else {
  764. elem.ElementName = TypeTranslator.GetTypeData (elemType).XmlType;
  765. }
  766. } else {
  767. elem.ElementName = defaultName;
  768. }
  769. if (choiceEnumMap != null) {
  770. string cname = choiceEnumMap.GetEnumName (elem.ElementName);
  771. if (cname == null) throw new InvalidOperationException ("The '" + choiceEnumType + "' enumeration does not have a value for the element '" + elem.ElementName + "'");
  772. elem.ChoiceValue = Enum.Parse (choiceEnumType, cname);
  773. }
  774. list.Add (elem);
  775. }
  776. return list;
  777. }
  778. XmlTypeMapElementInfoList ImportAnyElementInfo (string defaultNamespace, XmlReflectionMember rmember, XmlTypeMapMemberElement member, XmlAttributes atts)
  779. {
  780. XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
  781. ImportTextElementInfo (list, rmember.MemberType, member, atts);
  782. foreach (XmlAnyElementAttribute att in atts.XmlAnyElements)
  783. {
  784. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(typeof(XmlElement)));
  785. if (att.Name.Length != 0)
  786. {
  787. elem.ElementName = XmlConvert.EncodeLocalName(att.Name);
  788. elem.Namespace = (att.Namespace != null) ? att.Namespace : "";
  789. }
  790. else
  791. {
  792. elem.IsUnnamedAnyElement = true;
  793. elem.Namespace = defaultNamespace;
  794. if (att.Namespace != null)
  795. 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.");
  796. }
  797. list.Add (elem);
  798. }
  799. return list;
  800. }
  801. void ImportTextElementInfo (XmlTypeMapElementInfoList list, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts)
  802. {
  803. if (atts.XmlText != null)
  804. {
  805. member.IsXmlTextCollector = true;
  806. if (atts.XmlText.Type != null) defaultType = atts.XmlText.Type;
  807. if (defaultType == typeof(XmlNode)) defaultType = typeof(XmlText); // Nodes must be text nodes
  808. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType, atts.XmlText.DataType));
  809. if (elem.TypeData.SchemaType != SchemaTypes.Primitive &&
  810. elem.TypeData.SchemaType != SchemaTypes.Enum &&
  811. elem.TypeData.SchemaType != SchemaTypes.XmlNode &&
  812. !(elem.TypeData.SchemaType == SchemaTypes.Array && elem.TypeData.ListItemTypeData.SchemaType == SchemaTypes.XmlNode)
  813. )
  814. throw new InvalidOperationException ("XmlText cannot be used to encode complex types");
  815. elem.IsTextElement = true;
  816. elem.WrappedElement = false;
  817. list.Add (elem);
  818. }
  819. }
  820. bool CanBeNull (TypeData type)
  821. {
  822. return (type.SchemaType != SchemaTypes.Primitive || type.Type == typeof (string));
  823. }
  824. public void IncludeType (Type type)
  825. {
  826. if (type == null)
  827. throw new ArgumentNullException ("type");
  828. if (includedTypes == null) includedTypes = new ArrayList ();
  829. if (!includedTypes.Contains (type))
  830. includedTypes.Add (type);
  831. if (relatedMaps.Count > 0) {
  832. foreach (XmlTypeMapping map in (ArrayList) relatedMaps.Clone ()) {
  833. if (map.TypeData.Type == typeof(object))
  834. map.DerivedTypes.Add (ImportTypeMapping (type));
  835. }
  836. }
  837. }
  838. public void IncludeTypes (ICustomAttributeProvider provider)
  839. {
  840. object[] ats = provider.GetCustomAttributes (typeof(XmlIncludeAttribute), true);
  841. foreach (XmlIncludeAttribute at in ats)
  842. IncludeType (at.Type);
  843. }
  844. #endregion // Methods
  845. }
  846. }