PageRenderTime 48ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/Code/Platform/Channels/Text/SerializableDictionary.cs

http://github.com/waseems/inbox2_desktop
C# | 108 lines | 84 code | 24 blank | 0 comment | 3 complexity | 56532fa63c4b4944a8240e6ec3722221 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.Serialization;
  7. using System.Text;
  8. using System.Xml;
  9. using System.Xml.Schema;
  10. using System.Xml.Serialization;
  11. namespace Inbox2.Platform.Channels.Text
  12. {
  13. [Serializable]
  14. public class SerializableDictionary : Dictionary<string, object>, IXmlSerializable
  15. {
  16. public SerializableDictionary()
  17. {
  18. }
  19. protected SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info, context)
  20. {
  21. }
  22. public XmlSchema GetSchema()
  23. {
  24. return null;
  25. }
  26. public void ReadXml(XmlReader reader)
  27. {
  28. reader.Read();
  29. reader.ReadStartElement("dictionary");
  30. while (reader.NodeType != XmlNodeType.EndElement)
  31. {
  32. reader.ReadStartElement("item");
  33. string key = reader.ReadElementString("key");
  34. string value = reader.ReadElementString("value");
  35. object instance = null;
  36. using (MemoryStream ms = new MemoryStream())
  37. using (StreamWriter sw = new StreamWriter(ms))
  38. {
  39. sw.Write(value);
  40. sw.Flush();
  41. ms.Seek(0, SeekOrigin.Begin);
  42. NetDataContractSerializer ser = new NetDataContractSerializer();
  43. instance = ser.Deserialize(ms);
  44. }
  45. Debug.Assert(instance != null, "Deserialization of item failed");
  46. reader.ReadEndElement();
  47. reader.MoveToContent();
  48. Add(key, instance);
  49. }
  50. reader.ReadEndElement();
  51. }
  52. public void WriteXml(XmlWriter writer)
  53. {
  54. writer.WriteStartElement("dictionary");
  55. foreach (string key in Keys)
  56. {
  57. object value = this[key];
  58. writer.WriteStartElement("item");
  59. writer.WriteElementString("key", key);
  60. using (MemoryStream ms = new MemoryStream())
  61. using (StreamReader sr = new StreamReader(ms))
  62. {
  63. NetDataContractSerializer ser = new NetDataContractSerializer();
  64. ser.Serialize(ms, value);
  65. ms.Seek(0, SeekOrigin.Begin);
  66. writer.WriteElementString("value", sr.ReadToEnd());
  67. }
  68. writer.WriteEndElement();
  69. }
  70. writer.WriteEndElement();
  71. }
  72. public override string ToString()
  73. {
  74. using (MemoryStream ms = new MemoryStream())
  75. {
  76. XmlTextWriter w = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
  77. WriteXml(w);
  78. ms.Seek(0, SeekOrigin.Begin);
  79. using (StreamReader sr = new StreamReader(ms))
  80. return sr.ReadToEnd();
  81. }
  82. }
  83. }
  84. }