XmlReflectionImporter.cs 33 KB

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