XmlSerializer.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. //
  2. // Mono Class Libraries
  3. // System.Xml.Serialization.XmlSerializer
  4. //
  5. // Authors:
  6. // John Donagher ([email protected])
  7. // Ajay kumar Dwivedi ([email protected])
  8. // Tim Coleman ([email protected])
  9. //
  10. // (C) 2002 John Donagher, Ajay kumar Dwivedi
  11. // Copyright (C) Tim Coleman, 2002
  12. //
  13. using System;
  14. using System.Collections;
  15. using System.IO;
  16. using System.Reflection;
  17. using System.Xml;
  18. using System.Xml.Schema;
  19. namespace System.Xml.Serialization {
  20. /// <summary>
  21. /// Summary description for XmlSerializer.
  22. /// </summary>
  23. public class XmlSerializer {
  24. #region Fields
  25. Type type;
  26. XmlAttributeOverrides overrides;
  27. Type[] extraTypes;
  28. XmlRootAttribute rootAttribute;
  29. string defaultNamespace;
  30. static Hashtable typeTable;
  31. bool useOrder;
  32. bool isNullable;
  33. #endregion // Fields
  34. #region Constructors
  35. protected XmlSerializer ()
  36. {
  37. }
  38. public XmlSerializer (Type type)
  39. : this (type, null, null, null, null)
  40. {
  41. }
  42. [MonoTODO]
  43. public XmlSerializer (XmlTypeMapping xmltypemapping)
  44. {
  45. }
  46. public XmlSerializer (Type type, string defaultNamespace)
  47. : this (type, null, null, null, defaultNamespace)
  48. {
  49. }
  50. public XmlSerializer (Type type, Type[] extraTypes)
  51. : this (type, null, extraTypes, null, null)
  52. {
  53. }
  54. public XmlSerializer (Type type, XmlAttributeOverrides overrides)
  55. : this (type, overrides, null, null, null)
  56. {
  57. }
  58. public XmlSerializer (Type type, XmlRootAttribute root)
  59. : this (type, null, null, root, null)
  60. {
  61. }
  62. internal XmlSerializer (Hashtable typeTable)
  63. {
  64. typeTable = typeTable;
  65. }
  66. public XmlSerializer (Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace)
  67. {
  68. if (type == null)
  69. throw new ArgumentNullException ("type", "XmlSerializer can't be constructed with a null type");
  70. this.type = type;
  71. this.overrides = overrides;
  72. this.extraTypes = (extraTypes == null ? new Type[0] : extraTypes);
  73. if (root != null)
  74. this.rootAttribute = root;
  75. else {
  76. object[] attributes = type.GetCustomAttributes (typeof (XmlRootAttribute), false);
  77. if (attributes.Length > 0)
  78. this.rootAttribute = (XmlRootAttribute) attributes[0];
  79. }
  80. this.defaultNamespace = defaultNamespace;
  81. if (typeTable == null)
  82. typeTable = new Hashtable ();
  83. FillTypeTable (type);
  84. }
  85. #endregion // Constructors
  86. #region Events
  87. [MonoTODO]
  88. public event XmlAttributeEventHandler UnknownAttribute;
  89. [MonoTODO]
  90. public event XmlElementEventHandler UnknownElement;
  91. [MonoTODO]
  92. public event XmlNodeEventHandler UnknownNode;
  93. [MonoTODO]
  94. public event UnreferencedObjectEventHandler UnreferencedObject;
  95. #endregion // Events
  96. #region Properties
  97. public bool UseOrder {
  98. get { return useOrder; }
  99. set { useOrder = value; }
  100. }
  101. #endregion // Properties
  102. #region Methods
  103. [MonoTODO]
  104. public virtual bool CanDeserialize (XmlReader xmlReader)
  105. {
  106. throw new NotImplementedException ();
  107. }
  108. [MonoTODO]
  109. protected virtual XmlSerializationReader CreateReader ()
  110. {
  111. throw new NotImplementedException ();
  112. }
  113. [MonoTODO]
  114. protected virtual XmlSerializationWriter CreateWriter ()
  115. {
  116. throw new NotImplementedException ();
  117. }
  118. [MonoTODO]
  119. public object Deserialize (Stream stream)
  120. {
  121. throw new NotImplementedException ();
  122. }
  123. [MonoTODO]
  124. public object Deserialize (TextReader textReader)
  125. {
  126. throw new NotImplementedException ();
  127. }
  128. [MonoTODO]
  129. public object Deserialize (XmlReader xmlReader)
  130. {
  131. throw new NotImplementedException ();
  132. }
  133. [MonoTODO]
  134. protected virtual object Deserialize (XmlSerializationReader reader)
  135. {
  136. throw new NotImplementedException ();
  137. }
  138. [MonoTODO]
  139. protected virtual void Serialize (object o, XmlSerializationWriter writer)
  140. {
  141. throw new NotImplementedException ();
  142. }
  143. public void Serialize (Stream stream, object o)
  144. {
  145. XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
  146. xmlWriter.Formatting = Formatting.Indented;
  147. Serialize (xmlWriter, o, null);
  148. }
  149. public void Serialize (TextWriter textWriter, object o)
  150. {
  151. XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
  152. xmlWriter.Formatting = Formatting.Indented;
  153. Serialize (xmlWriter, o, null);
  154. }
  155. public void Serialize (XmlWriter xmlWriter, object o)
  156. {
  157. Serialize (xmlWriter, o);
  158. }
  159. public void Serialize (Stream stream, object o, XmlSerializerNamespaces namespaces)
  160. {
  161. XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
  162. xmlWriter.Formatting = Formatting.Indented;
  163. Serialize (xmlWriter, o, namespaces);
  164. }
  165. public void Serialize (TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
  166. {
  167. XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
  168. xmlWriter.Formatting = Formatting.Indented;
  169. Serialize (xmlWriter, o, namespaces);
  170. }
  171. public void Serialize (XmlWriter writer, object o, XmlSerializerNamespaces namespaces)
  172. {
  173. Type objType = o.GetType ();
  174. string rootName = objType.Name;
  175. string rootNs = String.Empty;
  176. string rootPrefix = String.Empty;
  177. if (namespaces == null)
  178. namespaces = new XmlSerializerNamespaces ();
  179. if (namespaces.Count == 0) {
  180. namespaces.Add ("xsd", XmlSchema.Namespace);
  181. namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
  182. }
  183. XmlSerializerNamespaces nss = new XmlSerializerNamespaces ();
  184. XmlQualifiedName[] qnames;
  185. writer.WriteStartDocument ();
  186. object[] memberObj = (object[]) typeTable[objType];
  187. if (memberObj == null)
  188. throw new Exception ("Unknown Type " + objType + " encountered during Serialization");
  189. Hashtable memberTable = (Hashtable) memberObj[0];
  190. XmlAttributes xmlAttributes = (XmlAttributes) memberTable[""];
  191. //If we have been passed an XmlRoot, set it on the base class
  192. if (rootAttribute != null)
  193. xmlAttributes.XmlRoot = rootAttribute;
  194. if (xmlAttributes.XmlRoot != null) {
  195. isNullable = xmlAttributes.XmlRoot.IsNullable;
  196. if (xmlAttributes.XmlRoot.ElementName != null)
  197. rootName = xmlAttributes.XmlRoot.ElementName;
  198. rootNs = xmlAttributes.XmlRoot.Namespace;
  199. }
  200. if (namespaces.GetPrefix (rootNs) != null)
  201. rootPrefix = namespaces.GetPrefix (rootNs);
  202. //XMLNS attributes in the Root
  203. XmlAttributes XnsAttrs = (XmlAttributes) ((object[]) typeTable[objType])[1];
  204. if (XnsAttrs != null) {
  205. MemberInfo member = XnsAttrs.MemberInfo;
  206. FieldInfo fieldInfo = member as FieldInfo;
  207. PropertyInfo propertyInfo = member as PropertyInfo;
  208. XmlSerializerNamespaces xns;
  209. if (fieldInfo != null)
  210. xns = (XmlSerializerNamespaces) fieldInfo.GetValue (o);
  211. else
  212. xns = (XmlSerializerNamespaces) propertyInfo.GetValue (o, null);
  213. qnames = xns.ToArray ();
  214. foreach (XmlQualifiedName qname in qnames)
  215. nss.Add (qname.Name, qname.Namespace);
  216. }
  217. //XmlNs from the namespaces passed
  218. qnames = namespaces.ToArray ();
  219. foreach (XmlQualifiedName qname in qnames)
  220. if (writer.LookupPrefix (qname.Namespace) != qname.Name)
  221. nss.Add (qname.Name, qname.Namespace);
  222. writer.WriteStartElement (rootPrefix, rootName, rootNs);
  223. qnames = nss.ToArray();
  224. foreach (XmlQualifiedName qname in qnames)
  225. if (writer.LookupPrefix (qname.Namespace) != qname.Name)
  226. writer.WriteAttributeString ("xmlns", qname.Name, null, qname.Namespace);
  227. if (rootPrefix == String.Empty && rootNs != String.Empty && rootNs != null)
  228. writer.WriteAttributeString (String.Empty, "xmlns", null, rootNs);
  229. SerializeMembers (writer, o, true);//, namespaces);
  230. writer.WriteEndDocument ();
  231. }
  232. private void SerializeMembers (XmlWriter writer, object o, bool isRoot)
  233. {
  234. Type objType = o.GetType ();
  235. XmlAttributes nsAttributes = (XmlAttributes) ((object[]) typeTable [objType])[1];
  236. ArrayList attributes = (ArrayList) ((object[]) typeTable [objType])[2];
  237. ArrayList elements = (ArrayList) ((object[]) typeTable [objType])[3];
  238. if (!isRoot && nsAttributes != null) {
  239. MemberInfo member = nsAttributes.MemberInfo;
  240. FieldInfo fieldInfo = member as FieldInfo;
  241. PropertyInfo propertyInfo = member as PropertyInfo;
  242. XmlSerializerNamespaces xns;
  243. if (fieldInfo != null)
  244. xns = (XmlSerializerNamespaces) fieldInfo.GetValue (o);
  245. else
  246. xns = (XmlSerializerNamespaces) propertyInfo.GetValue (o, null);
  247. XmlQualifiedName[] qnames = xns.ToArray ();
  248. foreach (XmlQualifiedName qname in qnames)
  249. if (writer.LookupPrefix (qname.Namespace) != qname.Name)
  250. writer.WriteAttributeString ("xmlns", qname.Name, null, qname.Namespace);
  251. }
  252. //Serialize the Attributes.
  253. foreach (XmlAttributes xmlAttributes in attributes) {
  254. MemberInfo member = xmlAttributes.MemberInfo;
  255. FieldInfo fieldInfo = member as FieldInfo;
  256. PropertyInfo propertyInfo = member as PropertyInfo;
  257. Type attributeType;
  258. object attributeValue;
  259. string attributeValueString;
  260. string attributeName;
  261. string attributeNs;
  262. if (fieldInfo != null) {
  263. attributeType = fieldInfo.FieldType;
  264. attributeValue = fieldInfo.GetValue (o);
  265. }
  266. else {
  267. attributeType = propertyInfo.PropertyType;
  268. attributeValue = propertyInfo.GetValue (o, null);
  269. }
  270. attributeName = xmlAttributes.GetAttributeName (attributeType, member.Name);
  271. attributeNs = xmlAttributes.GetAttributeNamespace (attributeType);
  272. if (attributeValue is XmlQualifiedName) {
  273. XmlQualifiedName qname = (XmlQualifiedName) attributeValue;
  274. if (qname.IsEmpty)
  275. continue;
  276. writer.WriteStartAttribute (attributeName, attributeNs);
  277. writer.WriteQualifiedName (qname.Name, qname.Namespace);
  278. writer.WriteEndAttribute ();
  279. continue;
  280. }
  281. else if (attributeValue is XmlQualifiedName[]) {
  282. XmlQualifiedName[] qnames = (XmlQualifiedName[]) attributeValue;
  283. writer.WriteStartAttribute (attributeName, attributeNs);
  284. int count = 0;
  285. foreach (XmlQualifiedName qname in qnames) {
  286. if (qname.IsEmpty)
  287. continue;
  288. if (count++ > 0)
  289. writer.WriteWhitespace (" ");
  290. writer.WriteQualifiedName (qname.Name, qname.Namespace);
  291. }
  292. writer.WriteEndAttribute ();
  293. continue;
  294. }
  295. else if (attributeValue is XmlAttribute[]) {
  296. XmlAttribute[] xmlattrs = (XmlAttribute[]) attributeValue;
  297. foreach (XmlAttribute xmlattr in xmlattrs)
  298. xmlattr.WriteTo(writer);
  299. continue;
  300. }
  301. attributeValueString = GetXmlValue (attributeValue);
  302. if (attributeValueString != GetXmlValue (xmlAttributes.XmlDefaultValue))
  303. writer.WriteAttributeString (attributeName, attributeNs, attributeValueString);
  304. }
  305. // Serialize Elements
  306. foreach (XmlAttributes xmlElements in elements) {
  307. MemberInfo member = xmlElements.MemberInfo;
  308. FieldInfo fieldInfo = member as FieldInfo;
  309. PropertyInfo propertyInfo = member as PropertyInfo;
  310. Type elementType;
  311. object elementValue;
  312. string elementName;
  313. string elementNs;
  314. if (fieldInfo != null) {
  315. elementType = fieldInfo.FieldType;
  316. elementValue = fieldInfo.GetValue (o);
  317. }
  318. else {
  319. elementType = propertyInfo.PropertyType;
  320. elementValue = propertyInfo.GetValue (o, null);
  321. }
  322. elementName = xmlElements.GetElementName (elementType, member.Name);
  323. elementNs = xmlElements.GetElementNamespace (elementType);
  324. WriteElement (writer, xmlElements, elementName, elementNs, elementType, elementValue);
  325. }
  326. }
  327. [MonoTODO ("Remove FIXMEs")]
  328. private void WriteElement (XmlWriter writer, XmlAttributes attrs, string name, string ns, Type type, Object value)
  329. {
  330. if (IsInbuiltType (type)) {
  331. string xmlValue = GetXmlValue (value);
  332. if (xmlValue != String.Empty && xmlValue != null)
  333. writer.WriteElementString (name, ns, xmlValue);
  334. }
  335. else if (attrs.XmlText != null && value != null) {
  336. if (type == typeof (object[])) {
  337. // FIXME
  338. }
  339. else if (type == typeof (string[])) {
  340. // FIXME
  341. }
  342. else if (type == typeof (XmlNode)) {
  343. ((XmlNode) value).WriteTo (writer);
  344. }
  345. else if (type == typeof (XmlNode[])) {
  346. XmlNode[] nodes = (XmlNode[]) value;
  347. foreach (XmlNode node in nodes)
  348. node.WriteTo (writer);
  349. }
  350. }
  351. else if (type.IsArray && value != null) {
  352. writer.WriteStartElement (name, ns);
  353. SerializeArray (writer, value);
  354. writer.WriteEndElement ();
  355. }
  356. else if (value is ICollection) {
  357. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
  358. //Find a non indexer Count Property with return type of int
  359. PropertyInfo countInfo = type.GetProperty ("Count", flags, null, typeof (int), new Type[0], null);
  360. PropertyInfo itemInfo = type.GetProperty ("Item", flags, null, null, new Type[1] {typeof (int)}, null);
  361. int count = (int) countInfo.GetValue (value, null);
  362. if (count > 0)
  363. for (int i = 0; i < count; i++) {
  364. object itemValue = itemInfo.GetValue (value, new object[1] {i});
  365. if (itemValue != null) {
  366. string itemName = attrs.GetElementName (itemValue.GetType (), name);
  367. string itemNs = attrs.GetElementNamespace (itemValue.GetType ());
  368. writer.WriteStartElement (itemName, itemNs);
  369. SerializeMembers (writer, itemValue, false);
  370. writer.WriteEndElement ();
  371. }
  372. }
  373. }
  374. else if (value is IEnumerable) {
  375. // FIXME
  376. }
  377. else if (type.IsEnum) {
  378. // FIXME
  379. }
  380. else if (value != null) { //Complex Type?
  381. string itemName = attrs.GetElementName (value.GetType (), name);
  382. string itemNs = attrs.GetElementNamespace (value.GetType ());
  383. writer.WriteStartElement (itemName, itemNs);
  384. SerializeMembers (writer, value, false);
  385. writer.WriteEndElement ();
  386. }
  387. else {
  388. // FIXME
  389. }
  390. }
  391. [MonoTODO]
  392. private void SerializeArray (XmlWriter writer, object o)
  393. {
  394. throw new NotImplementedException ();
  395. }
  396. /// <summary>
  397. /// If the type is a string, valuetype or primitive type we do not populate the TypeTable.
  398. /// If the type is an array, we populate the TypeTable with Element type of the array.
  399. /// If the type implements ICollection, it is handled differently. We do not care for its members.
  400. /// If the type implements IEnumberable, we check that it implements Add(). Don't care for members.
  401. /// </summary>
  402. [MonoTODO ("Remove FIXMEs")]
  403. private void FillTypeTable (Type type)
  404. {
  405. if (typeTable.Contains (type))
  406. return;
  407. //For value types and strings we don't need the members.
  408. //FIXME: We will need the enum types probably.
  409. if (IsInbuiltType (type))
  410. return;
  411. //Array, ICollection and IEnumberable are treated differenty
  412. if (type.IsArray) {
  413. FillArrayType (type);
  414. return;
  415. }
  416. else if (type.IsEnum) {
  417. FillEnum (type);
  418. return;
  419. }
  420. else {
  421. //There must be a public constructor
  422. if (!HasDefaultConstructor (type))
  423. throw new Exception ("Can't Serialize Type " + type.Name + " since it does not have default Constructor");
  424. if (type.GetInterface ("ICollection") == typeof (System.Collections.ICollection)) {
  425. FillICollectionType (type);
  426. return;
  427. }
  428. if (type.GetInterface ("IEnumerable") == typeof (System.Collections.IEnumerable)) {
  429. //FillIEnumerableType(type);
  430. //return;
  431. }
  432. }
  433. //Add the Class to the hashtable.
  434. //Each value of the hashtable has two objects, one is the hashtable with key of membername (for deserialization)
  435. //Other is an Array of XmlSerializernames, Array of XmlAttributes & Array of XmlElements.
  436. Object[] memberObj = new Object[4];
  437. typeTable.Add (type,memberObj);
  438. Hashtable memberTable = new Hashtable ();
  439. memberObj[0] = memberTable;
  440. memberTable.Add ("", XmlAttributes.FromClass (type));
  441. memberObj[1] = null;
  442. ArrayList attributes = new ArrayList ();
  443. memberObj[2] = attributes;
  444. ArrayList elements = new ArrayList ();
  445. memberObj[3] = elements;
  446. //Get the graph of the members. Graph is nothing but the order
  447. //in which MS implementation serializes the members.
  448. MemberInfo[] minfo = GetGraph (type);
  449. foreach (MemberInfo member in minfo) {
  450. FieldInfo fieldInfo = (member as FieldInfo);
  451. PropertyInfo propertyInfo = (member as PropertyInfo);
  452. if (fieldInfo != null) {
  453. //If field is readOnly or const, do not serialize it.
  454. if (fieldInfo.IsLiteral || fieldInfo.IsInitOnly)
  455. continue;
  456. XmlAttributes xmlAttributes = XmlAttributes.FromField (member, fieldInfo);
  457. //If XmlAttributes have XmlIgnore, ignore this member
  458. if (xmlAttributes.XmlIgnore)
  459. continue;
  460. //If this member is a XmlNs type, set the XmlNs object.
  461. if (xmlAttributes.Xmlns) {
  462. memberObj[1] = xmlAttributes;
  463. continue;
  464. }
  465. //If the member is a attribute Type, Add to attribute list
  466. if (xmlAttributes.isAttribute)
  467. attributes.Add (xmlAttributes);
  468. else //Add to elements
  469. elements.Add (xmlAttributes);
  470. //Add in the Hashtable.
  471. memberTable.Add (member.Name, xmlAttributes);
  472. if (xmlAttributes.XmlAnyAttribute != null || xmlAttributes.XmlText != null)
  473. continue;
  474. if (xmlAttributes.XmlElements.Count > 0) {
  475. foreach (XmlElementAttribute elem in xmlAttributes.XmlElements) {
  476. if (elem.Type != null)
  477. FillTypeTable (elem.Type);
  478. else
  479. FillTypeTable (fieldInfo.FieldType);
  480. }
  481. continue;
  482. }
  483. if (!IsInbuiltType (fieldInfo.FieldType))
  484. FillTypeTable (fieldInfo.FieldType);
  485. }
  486. else if (propertyInfo != null) {
  487. //If property is readonly or writeonly, do not serialize it.
  488. //Exceptions are properties whose return type is array, ICollection or IEnumerable
  489. //Indexers are not serialized unless the class Implements ICollection.
  490. if (!(propertyInfo.PropertyType.IsArray || Implements (propertyInfo.PropertyType, typeof (ICollection)) ||
  491. (propertyInfo.PropertyType != typeof (string) && Implements (propertyInfo.PropertyType, typeof (IEnumerable))))) {
  492. if(!(propertyInfo.CanRead && propertyInfo.CanWrite) || propertyInfo.GetIndexParameters ().Length != 0)
  493. continue;
  494. }
  495. XmlAttributes xmlAttributes = XmlAttributes.FromProperty (member, propertyInfo);
  496. // If XmlAttributes have XmlIgnore, ignore this member
  497. if (xmlAttributes.XmlIgnore)
  498. continue;
  499. // If this member is a XmlNs type, set the XmlNs object.
  500. if (xmlAttributes.Xmlns) {
  501. memberObj[1] = xmlAttributes;
  502. continue;
  503. }
  504. // If the member is a attribute Type, Add to attribute list
  505. if (xmlAttributes.isAttribute)
  506. attributes.Add (xmlAttributes);
  507. else //Add to elements
  508. elements.Add (xmlAttributes);
  509. // OtherWise add in the Hashtable.
  510. memberTable.Add (member.Name, xmlAttributes);
  511. if (xmlAttributes.XmlAnyAttribute != null || xmlAttributes.XmlText != null)
  512. continue;
  513. if (xmlAttributes.XmlElements.Count > 0) {
  514. foreach (XmlElementAttribute elem in xmlAttributes.XmlElements) {
  515. if (elem.Type != null)
  516. FillTypeTable (elem.Type);
  517. else
  518. FillTypeTable (propertyInfo.PropertyType);
  519. }
  520. continue;
  521. }
  522. if (!IsInbuiltType (propertyInfo.PropertyType))
  523. FillTypeTable (propertyInfo.PropertyType);
  524. }
  525. }
  526. // Sort the attributes for the members according to their Order
  527. // This is an extension to MS's Implementation and will be useful
  528. // if our reflection does not return the same order of elements
  529. // as MS .NET impl
  530. if (useOrder)
  531. BubbleSort (elements, XmlAttributes.attrComparer);
  532. }
  533. private void FillArrayType (Type type)
  534. {
  535. if (type.GetArrayRank () != 1)
  536. throw new Exception ("MultiDimensional Arrays are not Supported");
  537. Type arrayType = type.GetElementType ();
  538. if (arrayType.IsArray)
  539. FillArrayType (arrayType);
  540. else if (!IsInbuiltType (arrayType))
  541. FillTypeTable (arrayType);
  542. }
  543. private void FillICollectionType (Type type)
  544. {
  545. //Must have an public Indexer that takes an integer and
  546. //a public Count Property which returns an int.
  547. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
  548. //Find a non indexer Count Property with return type of int
  549. PropertyInfo countProp = type.GetProperty ("Count", flags, null, typeof (int), new Type[0], null);
  550. if (countProp == null || !countProp.CanRead)
  551. throw new Exception ("Cannot Serialize " + type + " because it implements ICollectoion, but does not implement public Count property");
  552. //Find a indexer Item Property which takes an int
  553. PropertyInfo itemProp = type.GetProperty ("Item", flags, null, null, new Type[1] {typeof (int)}, null);
  554. if (itemProp == null || !itemProp.CanRead || !itemProp.CanWrite)
  555. throw new Exception ("Cannot Serialize " + type + " because it does not have a read/write indexer property that takes an int as argument");
  556. FillTypeTable (itemProp.PropertyType);
  557. }
  558. [MonoTODO]
  559. private void FillIEnumerableType (Type type)
  560. {
  561. //Must implement a public Add method that takes a single parameter.
  562. //The Add method's parameter must be of the same type as is returned from
  563. //the Current property on the value returned from GetEnumerator, or one of that type's bases.
  564. // We currently ignore enumerable types anyway, so this method was junked.
  565. // The code did not do what the documentation above says (if that is even possible!)
  566. return;
  567. }
  568. private void FillEnum (Type type)
  569. {
  570. Hashtable memberTable = new Hashtable ();
  571. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
  572. typeTable.Add (type, memberTable);
  573. string[] names = Enum.GetNames (type);
  574. foreach (string name in names) {
  575. MemberInfo[] members = type.GetMember (name);
  576. if (members.Length != 1)
  577. throw new Exception("Should never happen. Enum member not present or more than one. " + name);
  578. XmlAttributes xmlAttributes = new XmlAttributes (members[0]);
  579. if (xmlAttributes.XmlIgnore)
  580. continue;
  581. if (xmlAttributes.XmlEnum != null)
  582. memberTable.Add (members[0].Name, xmlAttributes.XmlEnum.Name);
  583. else
  584. memberTable.Add (members[0].Name, members[0].Name);
  585. }
  586. }
  587. private bool HasDefaultConstructor (Type type)
  588. {
  589. ConstructorInfo defaultConstructor = type.GetConstructor (new Type[0]);
  590. if (defaultConstructor == null || defaultConstructor.IsAbstract || defaultConstructor.IsStatic || !defaultConstructor.IsPublic)
  591. return false;
  592. return true;
  593. }
  594. private bool IsInbuiltType (Type type)
  595. {
  596. if (type.IsEnum)
  597. return false;
  598. if (type.IsValueType || type == typeof (string) || type.IsPrimitive)
  599. return true;
  600. return false;
  601. }
  602. private static MemberInfo[] GetGraph(Type type)
  603. {
  604. ArrayList typeGraph = new ArrayList ();
  605. GetGraph (type, typeGraph);
  606. return (MemberInfo[]) typeGraph.ToArray (typeof (MemberInfo));
  607. }
  608. private static void GetGraph (Type type, ArrayList typeGraph)
  609. {
  610. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
  611. if (type.BaseType == null)
  612. return;
  613. GetGraph (type.BaseType, typeGraph);
  614. typeGraph.AddRange (type.GetFields (flags));
  615. typeGraph.AddRange (type.GetProperties (flags));
  616. }
  617. private string GetXmlValue (object value)
  618. {
  619. if (value == null)
  620. return null;
  621. if (value is Enum) {
  622. Type type = value.GetType ();
  623. if (typeTable.ContainsKey (type)) {
  624. Hashtable memberTable = (Hashtable) (typeTable[type]);
  625. if (type.IsDefined (typeof (FlagsAttribute), false)) {
  626. //If value is exactly a single enum member
  627. if (memberTable.Contains (value.ToString ()))
  628. return (string) memberTable[value.ToString ()];
  629. string retval = "";
  630. int enumval = (int) value;
  631. string[] names = Enum.GetNames (type);
  632. foreach (string key in names) {
  633. if (!memberTable.ContainsKey (key))
  634. continue;
  635. //Otherwise multiple values.
  636. int val = (int) Enum.Parse (type, key);
  637. if (val != 0 && (enumval & val) == val)
  638. retval += " " + (string) memberTable[Enum.GetName (type, val)];
  639. }
  640. retval = retval.Trim ();
  641. if (retval.Length == 0)
  642. return null;
  643. return retval;
  644. }
  645. else if (memberTable.ContainsKey (value.ToString ()))
  646. return (string) memberTable[value.ToString()];
  647. else
  648. return null;
  649. }
  650. else
  651. throw new Exception ("Unknown Enumeration");
  652. }
  653. if (value is bool)
  654. return (bool) value ? "true" : "false";
  655. if (value is XmlQualifiedName) {
  656. if (((XmlQualifiedName) value).IsEmpty)
  657. return null;
  658. }
  659. return (value == null) ? null : value.ToString ();
  660. }
  661. [MonoTODO ("Remove FIXMEs")]
  662. private static void ProcessAttributes (XmlAttributes attrs, Hashtable memberTable)
  663. {
  664. if (attrs.XmlAnyAttribute != null) {
  665. // FIXME
  666. }
  667. foreach (XmlAnyElementAttribute anyelem in attrs.XmlAnyElements)
  668. memberTable.Add (new XmlQualifiedName (anyelem.Name, anyelem.Namespace), attrs);
  669. if (attrs.XmlArray != null) {
  670. // FIXME
  671. }
  672. foreach (XmlArrayItemAttribute item in attrs.XmlArrayItems)
  673. memberTable.Add (new XmlQualifiedName (item.ElementName, item.Namespace), attrs);
  674. if (attrs.XmlAttribute != null)
  675. memberTable.Add (new XmlQualifiedName (attrs.XmlAttribute.AttributeName,attrs.XmlAttribute.Namespace), attrs);
  676. if (attrs.XmlChoiceIdentifier != null) {
  677. // FIXME
  678. }
  679. foreach (XmlElementAttribute elem in attrs.XmlElements)
  680. memberTable.Add (new XmlQualifiedName (elem.ElementName, elem.Namespace), attrs);
  681. if (attrs.XmlEnum != null) {
  682. // FIXME
  683. }
  684. if (attrs.XmlType != null)
  685. memberTable.Add (new XmlQualifiedName (attrs.XmlType.TypeName, attrs.XmlType.Namespace), attrs);
  686. }
  687. private bool Implements (Type type, Type interfaceType)
  688. {
  689. return (type.GetInterface (interfaceType.Name) == interfaceType);
  690. }
  691. private static void BubbleSort (ArrayList array, IComparer comparer)
  692. {
  693. int len = array.Count;
  694. object obj1, obj2;
  695. for (int i=0; i < len; i++) {
  696. for (int j=0; j < len -i -1; j++) {
  697. obj1 = array[j];
  698. obj2 = array[j+1];
  699. if (comparer.Compare (obj2 , obj1 ) < 0) {
  700. array[j] = obj2;
  701. array[j+1] = obj1;
  702. }
  703. }
  704. }
  705. }
  706. #endregion // Methods
  707. }
  708. }