XmlReflectionImporter.cs 34 KB

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