XmlReflectionImporter.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. map = CreateTypeMapping (TypeTranslator.GetTypeData (type), root, null, defaultNamespace);
  398. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  399. if (type.BaseType != null)
  400. {
  401. XmlTypeMapping bmap = ImportTypeMapping (type.BaseType, root, defaultNamespace);
  402. if (type.BaseType != typeof (object))
  403. map.BaseMap = bmap;
  404. RegisterDerivedMap (bmap, map);
  405. }
  406. return map;
  407. }
  408. XmlTypeMapping ImportPrimitiveMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  409. {
  410. TypeData typeData = TypeTranslator.GetTypeData (type);
  411. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  412. if (map != null) return map;
  413. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  414. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  415. return map;
  416. }
  417. XmlTypeMapping ImportEnumMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  418. {
  419. TypeData typeData = TypeTranslator.GetTypeData (type);
  420. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  421. if (map != null) return map;
  422. if (!allowPrivateTypes)
  423. ReflectionHelper.CheckSerializableType (type, false);
  424. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  425. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  426. string [] names = Enum.GetNames (type);
  427. ArrayList members = new ArrayList();
  428. foreach (string name in names)
  429. {
  430. MemberInfo[] mem = type.GetMember (name);
  431. string xmlName = null;
  432. object[] atts = mem[0].GetCustomAttributes (typeof(XmlIgnoreAttribute), false);
  433. if (atts.Length > 0) continue;
  434. atts = mem[0].GetCustomAttributes (typeof(XmlEnumAttribute), false);
  435. if (atts.Length > 0) xmlName = ((XmlEnumAttribute)atts[0]).Name;
  436. if (xmlName == null) xmlName = name;
  437. members.Add (new EnumMap.EnumMapMember (xmlName, name));
  438. }
  439. bool isFlags = type.GetCustomAttributes (typeof(FlagsAttribute),false).Length > 0;
  440. map.ObjectMap = new EnumMap ((EnumMap.EnumMapMember[])members.ToArray (typeof(EnumMap.EnumMapMember)), isFlags);
  441. ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
  442. return map;
  443. }
  444. XmlTypeMapping ImportXmlSerializableMapping (Type type, XmlRootAttribute root, string defaultNamespace)
  445. {
  446. TypeData typeData = TypeTranslator.GetTypeData (type);
  447. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
  448. if (map != null) return map;
  449. if (!allowPrivateTypes)
  450. ReflectionHelper.CheckSerializableType (type, false);
  451. map = CreateTypeMapping (typeData, root, null, defaultNamespace);
  452. helper.RegisterClrType (map, type, map.XmlTypeNamespace);
  453. return map;
  454. }
  455. void ImportIncludedTypes (Type type, string defaultNamespace)
  456. {
  457. XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
  458. for (int n=0; n<includes.Length; n++)
  459. {
  460. Type includedType = includes[n].Type;
  461. ImportTypeMapping (includedType, null, defaultNamespace);
  462. }
  463. }
  464. ICollection GetReflectionMembers (Type type)
  465. {
  466. // First we want to find the inheritance hierarchy in reverse order.
  467. Type currentType = type;
  468. ArrayList typeList = new ArrayList();
  469. typeList.Add(currentType);
  470. while (currentType != typeof(object))
  471. {
  472. currentType = currentType.BaseType; // Read the base type.
  473. typeList.Insert(0, currentType); // Insert at 0 to reverse the order.
  474. }
  475. // Read all Fields via reflection.
  476. ArrayList fieldList = new ArrayList();
  477. FieldInfo[] tfields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
  478. currentType = null;
  479. int currentIndex = 0;
  480. foreach (FieldInfo field in tfields)
  481. {
  482. // This statement ensures fields are ordered starting from the base type.
  483. if (currentType != field.DeclaringType)
  484. {
  485. currentType = field.DeclaringType;
  486. currentIndex=0;
  487. }
  488. fieldList.Insert(currentIndex++, field);
  489. }
  490. // Read all Properties via reflection.
  491. ArrayList propList = new ArrayList();
  492. PropertyInfo[] tprops = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
  493. currentType = null;
  494. currentIndex = 0;
  495. foreach (PropertyInfo prop in tprops)
  496. {
  497. // This statement ensures properties are ordered starting from the base type.
  498. if (currentType != prop.DeclaringType)
  499. {
  500. currentType = prop.DeclaringType;
  501. currentIndex = 0;
  502. }
  503. if (!prop.CanRead) continue;
  504. if (prop.GetIndexParameters().Length > 0) continue;
  505. propList.Insert(currentIndex++, prop);
  506. }
  507. ArrayList members = new ArrayList();
  508. int fieldIndex=0;
  509. int propIndex=0;
  510. // We now step through the type hierarchy from the base (object) through
  511. // to the supplied class, as each step outputting all Fields, and then
  512. // all Properties. This is the exact same ordering as .NET 1.0/1.1.
  513. foreach (Type t in typeList)
  514. {
  515. // Add any fields matching the current DeclaringType.
  516. while (fieldIndex < fieldList.Count)
  517. {
  518. FieldInfo field = (FieldInfo)fieldList[fieldIndex];
  519. if (field.DeclaringType==t)
  520. {
  521. fieldIndex++;
  522. XmlAttributes atts = attributeOverrides[type, field.Name];
  523. if (atts == null) atts = new XmlAttributes (field);
  524. if (atts.XmlIgnore) continue;
  525. XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
  526. member.DeclaringType = field.DeclaringType;
  527. members.Add(member);
  528. }
  529. else break;
  530. }
  531. // Add any properties matching the current DeclaringType.
  532. while (propIndex < propList.Count)
  533. {
  534. PropertyInfo prop = (PropertyInfo)propList[propIndex];
  535. if (prop.DeclaringType==t)
  536. {
  537. propIndex++;
  538. XmlAttributes atts = attributeOverrides[type, prop.Name];
  539. if (atts == null) atts = new XmlAttributes (prop);
  540. if (atts.XmlIgnore) continue;
  541. if (!prop.CanWrite && TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array) continue;
  542. XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
  543. member.DeclaringType = prop.DeclaringType;
  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. }