XmlReflectionImporter.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. map.IsNullable = nullable;
  206. relatedMaps.Add (map);
  207. return map;
  208. }
  209. XmlTypeMapping ImportClassMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  210. {
  211. TypeData typeData = TypeTranslator.GetTypeData (type);
  212. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  213. if (map != null) return map;
  214. if (!allowPrivateTypes)
  215. ReflectionHelper.CheckSerializableType (type, false);
  216. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  217. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  218. helper.RegisterSchemaType (map, map.XmlType, map.XmlTypeNamespace);
  219. // Import members
  220. ClassMap classMap = new ClassMap ();
  221. map.ObjectMap = classMap;
  222. // try
  223. // {
  224. ICollection members = GetReflectionMembers (type);
  225. foreach (XmlReflectionMember rmember in members)
  226. {
  227. if (rmember.XmlAttributes.XmlIgnore) continue;
  228. XmlTypeMapMember mem = CreateMapMember (rmember, map.XmlTypeNamespace);
  229. mem.CheckOptionalValueType (type);
  230. classMap.AddMember (mem);
  231. }
  232. // }
  233. // catch (Exception ex) {
  234. // throw helper.CreateError (map, ex.Message);
  235. // }
  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. ClassMap cbmap = bmap.ObjectMap as ClassMap;
  247. if (type.BaseType != typeof (object)) {
  248. map.BaseMap = bmap;
  249. if (!cbmap.HasSimpleContent)
  250. classMap.SetCanBeSimpleType (false);
  251. }
  252. // At this point, derived classes of this map must be already registered
  253. RegisterDerivedMap (bmap, map);
  254. if (cbmap.HasSimpleContent && classMap.ElementMembers != null && classMap.ElementMembers.Count != 1)
  255. throw new InvalidOperationException (String.Format (errSimple, map.TypeData.TypeName, map.BaseMap.TypeData.TypeName));
  256. }
  257. ImportIncludedTypes (type, defaultNamespace);
  258. if (classMap.XmlTextCollector != null && !classMap.HasSimpleContent)
  259. {
  260. XmlTypeMapMember mem = classMap.XmlTextCollector;
  261. if (mem.TypeData.Type != typeof(string) &&
  262. mem.TypeData.Type != typeof(string[]) &&
  263. mem.TypeData.Type != typeof(object[]) &&
  264. mem.TypeData.Type != typeof(XmlNode[]))
  265. throw new InvalidOperationException (String.Format (errSimple2, map.TypeData.TypeName, mem.Name, mem.TypeData.TypeName));
  266. }
  267. return map;
  268. }
  269. void RegisterDerivedMap (XmlTypeMapping map, XmlTypeMapping derivedMap)
  270. {
  271. map.DerivedTypes.Add (derivedMap);
  272. map.DerivedTypes.AddRange (derivedMap.DerivedTypes);
  273. if (map.BaseMap != null)
  274. RegisterDerivedMap (map.BaseMap, derivedMap);
  275. else {
  276. XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
  277. if (obmap != map)
  278. obmap.DerivedTypes.Add (derivedMap);
  279. }
  280. }
  281. string GetTypeNamespace (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
  282. {
  283. string typeNamespace = null;
  284. XmlAttributes atts = null;
  285. if (!typeData.IsListType)
  286. {
  287. if (attributeOverrides != null)
  288. atts = attributeOverrides[typeData.Type];
  289. }
  290. if (atts == null)
  291. atts = new XmlAttributes (typeData.Type);
  292. if (atts.XmlType != null)
  293. {
  294. if (atts.XmlType.Namespace != null && atts.XmlType.Namespace.Length != 0 && typeData.SchemaType != SchemaTypes.Enum)
  295. typeNamespace = atts.XmlType.Namespace;
  296. }
  297. if (typeNamespace != null && typeNamespace.Length != 0) return typeNamespace;
  298. if (atts.XmlRoot != null && root == null)
  299. root = atts.XmlRoot;
  300. if (root != null)
  301. {
  302. if (root.Namespace != null && root.Namespace.Length != 0)
  303. return root.Namespace;
  304. }
  305. if (defaultNamespace == null) return "";
  306. else return defaultNamespace;
  307. }
  308. XmlTypeMapping ImportListMapping (Type type, XmlRootAttribute root, string defaultNamespace, XmlAttributes atts, int nestingLevel)
  309. {
  310. TypeData typeData = TypeTranslator.GetTypeData (type);
  311. ListMap obmap = new ListMap ();
  312. if (!allowPrivateTypes)
  313. ReflectionHelper.CheckSerializableType (type, true);
  314. if (atts == null) atts = new XmlAttributes();
  315. Type itemType = typeData.ListItemType;
  316. // warning: byte[][] should not be considered multiarray
  317. bool isMultiArray = (type.IsArray && (TypeTranslator.GetTypeData(itemType).SchemaType == SchemaTypes.Array) && itemType.IsArray);
  318. XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
  319. foreach (XmlArrayItemAttribute att in atts.XmlArrayItems)
  320. {
  321. if (att.NestingLevel != nestingLevel) continue;
  322. Type elemType = (att.Type != null) ? att.Type : itemType;
  323. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData(elemType, att.DataType));
  324. elem.Namespace = att.Namespace != null ? att.Namespace : defaultNamespace;
  325. if (elem.Namespace == null) elem.Namespace = "";
  326. elem.Form = att.Form;
  327. elem.IsNullable = att.IsNullable && CanBeNull (elem.TypeData);
  328. elem.NestingLevel = att.NestingLevel;
  329. if (isMultiArray)
  330. elem.MappedType = ImportListMapping (elemType, null, elem.Namespace, atts, nestingLevel + 1);
  331. else if (elem.TypeData.IsComplexType)
  332. elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
  333. if (att.ElementName != null) elem.ElementName = att.ElementName;
  334. else if (elem.MappedType != null) elem.ElementName = elem.MappedType.ElementName;
  335. else elem.ElementName = TypeTranslator.GetTypeData(elemType).XmlType;
  336. list.Add (elem);
  337. }
  338. if (list.Count == 0)
  339. {
  340. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData (itemType));
  341. if (isMultiArray)
  342. elem.MappedType = ImportListMapping (itemType, null, defaultNamespace, atts, nestingLevel + 1);
  343. else if (elem.TypeData.IsComplexType)
  344. elem.MappedType = ImportTypeMapping (itemType, null, defaultNamespace);
  345. if (elem.MappedType != null) elem.ElementName = elem.MappedType.XmlType;
  346. else elem.ElementName = TypeTranslator.GetTypeData(itemType).XmlType ;
  347. elem.Namespace = (defaultNamespace != null) ? defaultNamespace : "";
  348. elem.IsNullable = CanBeNull (elem.TypeData);
  349. list.Add (elem);
  350. }
  351. obmap.ItemInfo = list;
  352. // If there can be different element names (types) in the array, then its name cannot
  353. // be "ArrayOfXXX" it must be something like ArrayOfChoiceNNN
  354. string baseName;
  355. if (list.Count > 1)
  356. baseName = "ArrayOfChoice" + (arrayChoiceCount++);
  357. else
  358. {
  359. XmlTypeMapElementInfo elem = ((XmlTypeMapElementInfo)list[0]);
  360. if (elem.MappedType != null) baseName = TypeTranslator.GetArrayName (elem.MappedType.XmlType);
  361. else baseName = TypeTranslator.GetArrayName (elem.ElementName);
  362. }
  363. // Avoid name colisions
  364. int nameCount = 1;
  365. string name = baseName;
  366. do {
  367. XmlTypeMapping foundMap = helper.GetRegisteredSchemaType (name, defaultNamespace);
  368. if (foundMap == null) nameCount = -1;
  369. else if (obmap.Equals (foundMap.ObjectMap) && typeData.Type == foundMap.TypeData.Type) return foundMap;
  370. else name = baseName + (nameCount++);
  371. }
  372. while (nameCount != -1);
  373. XmlTypeMapping map = CreateTypeMapping (typeData, root, name, defaultNamespace);
  374. map.ObjectMap = obmap;
  375. // Register any of the including types as a derived class of object
  376. XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
  377. XmlTypeMapping objectMapping = ImportTypeMapping (typeof(object));
  378. for (int i = 0; i < includes.Length; i++)
  379. {
  380. Type includedType = includes[i].Type;
  381. objectMapping.DerivedTypes.Add(ImportTypeMapping (includedType, null, defaultNamespace));
  382. }
  383. // Register this map as a derived class of object
  384. helper.RegisterSchemaType (map, name, defaultNamespace);
  385. ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
  386. return map;
  387. }
  388. XmlTypeMapping ImportXmlNodeMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  389. {
  390. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (TypeTranslator.GetTypeData (type), root, defaultNamespace));
  391. if (map != null) return map;
  392. // Registers the maps for XmlNode and XmlElement
  393. XmlTypeMapping nodeMap = CreateTypeMapping (TypeTranslator.GetTypeData (typeof(XmlNode)), root, null, defaultNamespace);
  394. helper.RegisterClrType (nodeMap, typeof(XmlNode), nodeMap.XmlTypeNamespace);
  395. XmlTypeMapping elemMap = CreateTypeMapping (TypeTranslator.GetTypeData (typeof(XmlElement)), root, null, defaultNamespace);
  396. helper.RegisterClrType (elemMap, typeof(XmlElement), elemMap.XmlTypeNamespace);
  397. XmlTypeMapping textMap = CreateTypeMapping (TypeTranslator.GetTypeData (typeof(XmlText)), root, null, defaultNamespace);
  398. helper.RegisterClrType (textMap, typeof(XmlText), textMap.XmlTypeNamespace);
  399. XmlTypeMapping docMap = CreateTypeMapping (TypeTranslator.GetTypeData (typeof(XmlDocument)), root, null, defaultNamespace);
  400. helper.RegisterClrType (docMap, typeof(XmlDocument), textMap.XmlTypeNamespace);
  401. XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
  402. obmap.DerivedTypes.Add (nodeMap);
  403. obmap.DerivedTypes.Add (elemMap);
  404. obmap.DerivedTypes.Add (textMap);
  405. obmap.DerivedTypes.Add (docMap);
  406. nodeMap.DerivedTypes.Add (elemMap);
  407. nodeMap.DerivedTypes.Add (textMap);
  408. nodeMap.DerivedTypes.Add (docMap);
  409. map = helper.GetRegisteredClrType (type, GetTypeNamespace (TypeTranslator.GetTypeData (type), root, defaultNamespace));
  410. if (map == null) throw new InvalidOperationException ("Objects of type '" + type + "' can't be serialized");
  411. return map;
  412. }
  413. XmlTypeMapping ImportPrimitiveMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  414. {
  415. TypeData typeData = TypeTranslator.GetTypeData (type);
  416. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  417. if (map != null) return map;
  418. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  419. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  420. return map;
  421. }
  422. XmlTypeMapping ImportEnumMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  423. {
  424. TypeData typeData = TypeTranslator.GetTypeData (type);
  425. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  426. if (map != null) return map;
  427. if (!allowPrivateTypes)
  428. ReflectionHelper.CheckSerializableType (type, false);
  429. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  430. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  431. string [] names = Enum.GetNames (type);
  432. ArrayList members = new ArrayList();
  433. foreach (string name in names)
  434. {
  435. MemberInfo[] mem = type.GetMember (name);
  436. string xmlName = null;
  437. object[] atts = mem[0].GetCustomAttributes (typeof(XmlIgnoreAttribute), false);
  438. if (atts.Length > 0) continue;
  439. atts = mem[0].GetCustomAttributes (typeof(XmlEnumAttribute), false);
  440. if (atts.Length > 0) xmlName = ((XmlEnumAttribute)atts[0]).Name;
  441. if (xmlName == null) xmlName = name;
  442. members.Add (new EnumMap.EnumMapMember (xmlName, name));
  443. }
  444. bool isFlags = type.GetCustomAttributes (typeof(FlagsAttribute),false).Length > 0;
  445. map.ObjectMap = new EnumMap ((EnumMap.EnumMapMember[])members.ToArray (typeof(EnumMap.EnumMapMember)), isFlags);
  446. ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
  447. return map;
  448. }
  449. XmlTypeMapping ImportXmlSerializableMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  450. {
  451. TypeData typeData = TypeTranslator.GetTypeData (type);
  452. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  453. if (map != null) return map;
  454. if (!allowPrivateTypes)
  455. ReflectionHelper.CheckSerializableType (type, false);
  456. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  457. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  458. return map;
  459. }
  460. void ImportIncludedTypes (Type type, string defaultNamespace)
  461. {
  462. XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
  463. for (int n=0; n<includes.Length; n++)
  464. {
  465. Type includedType = includes[n].Type;
  466. ImportTypeMapping (includedType, null, defaultNamespace);
  467. }
  468. }
  469. ICollection GetReflectionMembers (Type type)
  470. {
  471. // First we want to find the inheritance hierarchy in reverse order.
  472. Type currentType = type;
  473. ArrayList typeList = new ArrayList();
  474. typeList.Add(currentType);
  475. while (currentType != typeof(object))
  476. {
  477. currentType = currentType.BaseType; // Read the base type.
  478. typeList.Insert(0, currentType); // Insert at 0 to reverse the order.
  479. }
  480. // Read all Fields via reflection.
  481. ArrayList fieldList = new ArrayList();
  482. FieldInfo[] tfields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
  483. currentType = null;
  484. int currentIndex = 0;
  485. foreach (FieldInfo field in tfields)
  486. {
  487. // This statement ensures fields are ordered starting from the base type.
  488. if (currentType != field.DeclaringType)
  489. {
  490. currentType = field.DeclaringType;
  491. currentIndex=0;
  492. }
  493. fieldList.Insert(currentIndex++, field);
  494. }
  495. // Read all Properties via reflection.
  496. ArrayList propList = new ArrayList();
  497. PropertyInfo[] tprops = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
  498. currentType = null;
  499. currentIndex = 0;
  500. foreach (PropertyInfo prop in tprops)
  501. {
  502. // This statement ensures properties are ordered starting from the base type.
  503. if (currentType != prop.DeclaringType)
  504. {
  505. currentType = prop.DeclaringType;
  506. currentIndex = 0;
  507. }
  508. if (!prop.CanRead) continue;
  509. if (!prop.CanWrite && TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array) continue;
  510. if (prop.GetIndexParameters().Length > 0) continue;
  511. propList.Insert(currentIndex++, prop);
  512. }
  513. ArrayList members = new ArrayList();
  514. int fieldIndex=0;
  515. int propIndex=0;
  516. // We now step through the type hierarchy from the base (object) through
  517. // to the supplied class, as each step outputting all Fields, and then
  518. // all Properties. This is the exact same ordering as .NET 1.0/1.1.
  519. foreach (Type t in typeList)
  520. {
  521. // Add any fields matching the current DeclaringType.
  522. while (fieldIndex < fieldList.Count)
  523. {
  524. FieldInfo field = (FieldInfo)fieldList[fieldIndex];
  525. if (field.DeclaringType==t)
  526. {
  527. fieldIndex++;
  528. XmlAttributes atts = attributeOverrides[type, field.Name];
  529. if (atts == null) atts = new XmlAttributes (field);
  530. if (atts.XmlIgnore) continue;
  531. XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
  532. members.Add(member);
  533. }
  534. else break;
  535. }
  536. // Add any properties matching the current DeclaringType.
  537. while (propIndex < propList.Count)
  538. {
  539. PropertyInfo prop = (PropertyInfo)propList[propIndex];
  540. if (prop.DeclaringType==t)
  541. {
  542. propIndex++;
  543. XmlAttributes atts = attributeOverrides[type, prop.Name];
  544. if (atts == null) atts = new XmlAttributes (prop);
  545. if (atts.XmlIgnore) continue;
  546. XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
  547. members.Add(member);
  548. }
  549. else break;
  550. }
  551. }
  552. return members;
  553. }
  554. private XmlTypeMapMember CreateMapMember (XmlReflectionMember rmember, string defaultNamespace)
  555. {
  556. XmlTypeMapMember mapMember;
  557. XmlAttributes atts = rmember.XmlAttributes;
  558. TypeData typeData = TypeTranslator.GetTypeData (rmember.MemberType);
  559. if (atts.XmlAnyAttribute != null)
  560. {
  561. if ( (rmember.MemberType.FullName == "System.Xml.XmlAttribute[]") ||
  562. (rmember.MemberType.FullName == "System.Xml.XmlNode[]") )
  563. {
  564. mapMember = new XmlTypeMapMemberAnyAttribute();
  565. }
  566. else
  567. throw new InvalidOperationException ("XmlAnyAttributeAttribute can only be applied to members of type XmlAttribute[] or XmlNode[]");
  568. }
  569. else if (atts.XmlAnyElements != null && atts.XmlAnyElements.Count > 0)
  570. {
  571. if ( (rmember.MemberType.FullName == "System.Xml.XmlElement[]") ||
  572. (rmember.MemberType.FullName == "System.Xml.XmlNode[]") ||
  573. (rmember.MemberType.FullName == "System.Xml.XmlElement"))
  574. {
  575. XmlTypeMapMemberAnyElement member = new XmlTypeMapMemberAnyElement();
  576. member.ElementInfo = ImportAnyElementInfo (defaultNamespace, rmember, member, atts);
  577. mapMember = member;
  578. }
  579. else
  580. throw new InvalidOperationException ("XmlAnyElementAttribute can only be applied to members of type XmlElement, XmlElement[] or XmlNode[]");
  581. }
  582. else if (atts.Xmlns)
  583. {
  584. XmlTypeMapMemberNamespaces mapNamespaces = new XmlTypeMapMemberNamespaces ();
  585. mapMember = mapNamespaces;
  586. }
  587. else if (atts.XmlAttribute != null)
  588. {
  589. // An attribute
  590. if (atts.XmlElements != null && atts.XmlElements.Count > 0)
  591. throw new Exception ("XmlAttributeAttribute and XmlElementAttribute cannot be applied to the same member");
  592. XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute ();
  593. if (atts.XmlAttribute.AttributeName == null)
  594. mapAttribute.AttributeName = rmember.MemberName;
  595. else
  596. mapAttribute.AttributeName = atts.XmlAttribute.AttributeName;
  597. if (typeData.IsComplexType)
  598. mapAttribute.MappedType = ImportTypeMapping (typeData.Type, null, mapAttribute.Namespace);
  599. if (atts.XmlAttribute.Namespace != null && atts.XmlAttribute.Namespace != defaultNamespace)
  600. {
  601. if (atts.XmlAttribute.Form == XmlSchemaForm.Unqualified)
  602. throw new InvalidOperationException ("The Form property may not be 'Unqualified' when an explicit Namespace property is present");
  603. mapAttribute.Form = XmlSchemaForm.Qualified;
  604. mapAttribute.Namespace = atts.XmlAttribute.Namespace;
  605. }
  606. else
  607. {
  608. mapAttribute.Form = atts.XmlAttribute.Form;
  609. if (atts.XmlAttribute.Form == XmlSchemaForm.Qualified)
  610. mapAttribute.Namespace = defaultNamespace;
  611. else
  612. mapAttribute.Namespace = "";
  613. }
  614. typeData = TypeTranslator.GetTypeData(rmember.MemberType, atts.XmlAttribute.DataType);
  615. mapMember = mapAttribute;
  616. }
  617. else if (typeData.SchemaType == SchemaTypes.Array)
  618. {
  619. // If the member has a single XmlElementAttribute and the type is the type of the member,
  620. // then it is not a flat list
  621. if (atts.XmlElements.Count > 1 ||
  622. (atts.XmlElements.Count == 1 && atts.XmlElements[0].Type != typeData.Type) ||
  623. (atts.XmlText != null))
  624. {
  625. // A flat list
  626. // TODO: check that it does not have XmlArrayAttribute
  627. XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList ();
  628. member.ListMap = new ListMap ();
  629. member.ListMap.ItemInfo = ImportElementInfo (rmember.MemberName, defaultNamespace, typeData.ListItemType, member, atts);
  630. member.ElementInfo = member.ListMap.ItemInfo;
  631. mapMember = member;
  632. }
  633. else
  634. {
  635. // A list
  636. XmlTypeMapMemberList member = new XmlTypeMapMemberList ();
  637. // Creates an ElementInfo that identifies the array instance.
  638. member.ElementInfo = new XmlTypeMapElementInfoList();
  639. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, typeData);
  640. elem.ElementName = (atts.XmlArray != null && atts.XmlArray.ElementName != null) ? atts.XmlArray.ElementName : rmember.MemberName;
  641. elem.Namespace = (atts.XmlArray != null && atts.XmlArray.Namespace != null) ? atts.XmlArray.Namespace : defaultNamespace;
  642. elem.MappedType = ImportListMapping (rmember.MemberType, null, elem.Namespace, atts, 0);
  643. elem.IsNullable = (atts.XmlArray != null) ? atts.XmlArray.IsNullable : false;
  644. elem.Form = (atts.XmlArray != null) ? atts.XmlArray.Form : XmlSchemaForm.Qualified;
  645. member.ElementInfo.Add (elem);
  646. mapMember = member;
  647. }
  648. }
  649. else
  650. {
  651. // An element
  652. XmlTypeMapMemberElement member = new XmlTypeMapMemberElement ();
  653. member.ElementInfo = ImportElementInfo (rmember.MemberName, defaultNamespace, rmember.MemberType, member, atts);
  654. mapMember = member;
  655. }
  656. mapMember.DefaultValue = atts.XmlDefaultValue;
  657. mapMember.TypeData = typeData;
  658. mapMember.Name = rmember.MemberName;
  659. mapMember.IsReturnValue = rmember.IsReturnValue;
  660. return mapMember;
  661. }
  662. XmlTypeMapElementInfoList ImportElementInfo (string defaultName, string defaultNamespace, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts)
  663. {
  664. XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
  665. ImportTextElementInfo (list, defaultType, member, atts);
  666. if (atts.XmlElements.Count == 0 && list.Count == 0)
  667. {
  668. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType));
  669. elem.ElementName = defaultName;
  670. elem.Namespace = defaultNamespace;
  671. if (elem.TypeData.IsComplexType)
  672. elem.MappedType = ImportTypeMapping (defaultType, null, defaultNamespace);
  673. list.Add (elem);
  674. }
  675. bool multiType = (atts.XmlElements.Count > 1);
  676. foreach (XmlElementAttribute att in atts.XmlElements)
  677. {
  678. Type elemType = (att.Type != null) ? att.Type : defaultType;
  679. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(elemType, att.DataType));
  680. elem.ElementName = (att.ElementName != null) ? att.ElementName : defaultName;
  681. elem.Namespace = (att.Namespace != null) ? att.Namespace : defaultNamespace;
  682. elem.Form = att.Form;
  683. elem.IsNullable = att.IsNullable;
  684. if (elem.IsNullable && elem.TypeData.IsValueType)
  685. throw new InvalidOperationException ("IsNullable may not be 'true' for value type " + elem.TypeData.FullTypeName + " in member '" + defaultName + "'");
  686. if (elem.TypeData.IsComplexType)
  687. {
  688. 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.");
  689. elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
  690. }
  691. if (att.ElementName != null)
  692. elem.ElementName = att.ElementName;
  693. else if (multiType) {
  694. if (elem.MappedType != null) elem.ElementName = elem.MappedType.ElementName;
  695. else elem.ElementName = TypeTranslator.GetTypeData(elemType).XmlType;
  696. }
  697. else
  698. elem.ElementName = defaultName;
  699. list.Add (elem);
  700. }
  701. return list;
  702. }
  703. XmlTypeMapElementInfoList ImportAnyElementInfo (string defaultNamespace, XmlReflectionMember rmember, XmlTypeMapMemberElement member, XmlAttributes atts)
  704. {
  705. XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
  706. ImportTextElementInfo (list, rmember.MemberType, member, atts);
  707. foreach (XmlAnyElementAttribute att in atts.XmlAnyElements)
  708. {
  709. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(typeof(XmlElement)));
  710. if (att.Name != null && att.Name != string.Empty)
  711. {
  712. elem.ElementName = att.Name;
  713. elem.Namespace = (att.Namespace != null) ? att.Namespace : "";
  714. }
  715. else
  716. {
  717. elem.IsUnnamedAnyElement = true;
  718. elem.Namespace = defaultNamespace;
  719. if (att.Namespace != null)
  720. 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.");
  721. }
  722. list.Add (elem);
  723. }
  724. return list;
  725. }
  726. void ImportTextElementInfo (XmlTypeMapElementInfoList list, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts)
  727. {
  728. if (atts.XmlText != null)
  729. {
  730. member.IsXmlTextCollector = true;
  731. if (atts.XmlText.Type != null) defaultType = atts.XmlText.Type;
  732. if (defaultType == typeof(XmlNode)) defaultType = typeof(XmlText); // Nodes must be text nodes
  733. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType, atts.XmlText.DataType));
  734. if (elem.TypeData.SchemaType != SchemaTypes.Primitive &&
  735. elem.TypeData.SchemaType != SchemaTypes.Enum &&
  736. elem.TypeData.SchemaType != SchemaTypes.XmlNode &&
  737. !(elem.TypeData.SchemaType == SchemaTypes.Array && elem.TypeData.ListItemTypeData.SchemaType == SchemaTypes.XmlNode)
  738. )
  739. throw new InvalidOperationException ("XmlText cannot be used to encode complex types");
  740. elem.IsTextElement = true;
  741. elem.WrappedElement = false;
  742. list.Add (elem);
  743. }
  744. }
  745. bool CanBeNull (TypeData type)
  746. {
  747. return (type.SchemaType != SchemaTypes.Primitive || type.Type == typeof (string));
  748. }
  749. public void IncludeType (Type type)
  750. {
  751. if (type == null)
  752. throw new ArgumentNullException ("type");
  753. if (includedTypes == null) includedTypes = new ArrayList ();
  754. if (!includedTypes.Contains (type))
  755. includedTypes.Add (type);
  756. }
  757. public void IncludeTypes (ICustomAttributeProvider provider)
  758. {
  759. object[] ats = provider.GetCustomAttributes (typeof(XmlIncludeAttribute), true);
  760. foreach (XmlIncludeAttribute at in ats)
  761. IncludeType (at.Type);
  762. }
  763. #endregion // Methods
  764. }
  765. }