XmlSerializer.cs 29 KB

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