XmlReflectionImporter.cs 31 KB

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