DataContractSerializer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. //
  2. // DataContractSerializer.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. #if NET_2_0
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Collections.ObjectModel;
  33. using System.IO;
  34. using System.Reflection;
  35. using System.Runtime.Serialization.Formatters.Binary;
  36. using System.Xml;
  37. using System.Xml.Schema;
  38. using QName = System.Xml.XmlQualifiedName;
  39. namespace System.Runtime.Serialization
  40. {
  41. public sealed class DataContractSerializer : XmlObjectSerializer
  42. {
  43. const string xmlns = "http://www.w3.org/2000/xmlns/";
  44. Type type;
  45. bool ignore_ext, preserve_refs;
  46. // This is only for compatible mode.
  47. StreamingContext context;
  48. ReadOnlyCollection<Type> returned_known_types;
  49. KnownTypeCollection known_types;
  50. IDataContractSurrogate surrogate;
  51. int max_items = 0x10000; // FIXME: could be from config.
  52. bool names_filled;
  53. XmlDictionaryString root_name, root_ns;
  54. public DataContractSerializer (Type type)
  55. : this (type, Type.EmptyTypes)
  56. {
  57. // nothing to do here.
  58. }
  59. public DataContractSerializer (Type type,
  60. IEnumerable<Type> knownTypes)
  61. {
  62. if (type == null)
  63. throw new ArgumentNullException ("type");
  64. this.type = type;
  65. known_types = new KnownTypeCollection ();
  66. PopulateTypes (knownTypes);
  67. known_types.TryRegister (type);
  68. QName qname = known_types.GetQName (type);
  69. FillDictionaryString (qname.Name, qname.Namespace);
  70. }
  71. public DataContractSerializer (Type type, string rootName,
  72. string rootNamespace)
  73. : this (type, rootName, rootNamespace, Type.EmptyTypes)
  74. {
  75. // nothing to do here.
  76. }
  77. public DataContractSerializer (Type type,
  78. XmlDictionaryString rootName,
  79. XmlDictionaryString rootNamespace)
  80. : this (type, rootName, rootNamespace, Type.EmptyTypes)
  81. {
  82. // nothing to do here.
  83. }
  84. public DataContractSerializer (Type type, string rootName,
  85. string rootNamespace, IEnumerable<Type> knownTypes)
  86. {
  87. if (type == null)
  88. throw new ArgumentNullException ("type");
  89. if (rootName == null)
  90. throw new ArgumentNullException ("rootName");
  91. if (rootNamespace == null)
  92. throw new ArgumentNullException ("rootNamespace");
  93. this.type = type;
  94. PopulateTypes (knownTypes);
  95. FillDictionaryString (rootName, rootNamespace);
  96. }
  97. public DataContractSerializer (Type type,
  98. XmlDictionaryString rootName,
  99. XmlDictionaryString rootNamespace,
  100. IEnumerable<Type> knownTypes)
  101. {
  102. if (type == null)
  103. throw new ArgumentNullException ("type");
  104. if (rootName == null)
  105. throw new ArgumentNullException ("rootName");
  106. if (rootNamespace == null)
  107. throw new ArgumentNullException ("rootNamespace");
  108. this.type = type;
  109. PopulateTypes (knownTypes);
  110. root_name = rootName;
  111. root_ns = rootNamespace;
  112. }
  113. public DataContractSerializer (Type type,
  114. IEnumerable<Type> knownTypes,
  115. int maxObjectsInGraph,
  116. bool ignoreExtensionDataObject,
  117. bool preserveObjectReferences,
  118. IDataContractSurrogate dataContractSurrogate)
  119. : this (type, knownTypes)
  120. {
  121. Initialize (maxObjectsInGraph,
  122. ignoreExtensionDataObject,
  123. preserveObjectReferences,
  124. dataContractSurrogate);
  125. }
  126. public DataContractSerializer (Type type,
  127. string rootName,
  128. string rootNamespace,
  129. IEnumerable<Type> knownTypes,
  130. int maxObjectsInGraph,
  131. bool ignoreExtensionDataObject,
  132. bool preserveObjectReferences,
  133. IDataContractSurrogate dataContractSurrogate)
  134. : this (type, rootName, rootNamespace, knownTypes)
  135. {
  136. Initialize (maxObjectsInGraph,
  137. ignoreExtensionDataObject,
  138. preserveObjectReferences,
  139. dataContractSurrogate);
  140. }
  141. public DataContractSerializer (Type type,
  142. XmlDictionaryString rootName,
  143. XmlDictionaryString rootNamespace,
  144. IEnumerable<Type> knownTypes,
  145. int maxObjectsInGraph,
  146. bool ignoreExtensionDataObject,
  147. bool preserveObjectReferences,
  148. IDataContractSurrogate dataContractSurrogate)
  149. : this (type, rootName, rootNamespace, knownTypes)
  150. {
  151. Initialize (maxObjectsInGraph,
  152. ignoreExtensionDataObject,
  153. preserveObjectReferences,
  154. dataContractSurrogate);
  155. }
  156. #if NET_4_0
  157. public DataContractSerializer (Type type,
  158. IEnumerable<Type> knownTypes,
  159. int maxObjectsInGraph,
  160. bool ignoreExtensionDataObject,
  161. bool preserveObjectReferences,
  162. IDataContractSurrogate dataContractSurrogate,
  163. DataContractResolver dataContractResolver)
  164. : this (type, knownTypes, maxObjectsInGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate)
  165. {
  166. DataContractResolver = dataContractResolver;
  167. }
  168. public DataContractSerializer (Type type,
  169. string rootName,
  170. string rootNamespace,
  171. IEnumerable<Type> knownTypes,
  172. int maxObjectsInGraph,
  173. bool ignoreExtensionDataObject,
  174. bool preserveObjectReferences,
  175. IDataContractSurrogate dataContractSurrogate,
  176. DataContractResolver dataContractResolver)
  177. : this (type, rootName, rootNamespace, knownTypes, maxObjectsInGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate)
  178. {
  179. DataContractResolver = dataContractResolver;
  180. }
  181. public DataContractSerializer (Type type,
  182. XmlDictionaryString rootName,
  183. XmlDictionaryString rootNamespace,
  184. IEnumerable<Type> knownTypes,
  185. int maxObjectsInGraph,
  186. bool ignoreExtensionDataObject,
  187. bool preserveObjectReferences,
  188. IDataContractSurrogate dataContractSurrogate,
  189. DataContractResolver dataContractResolver)
  190. : this (type, rootName, rootNamespace, knownTypes, maxObjectsInGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate)
  191. {
  192. DataContractResolver = dataContractResolver;
  193. }
  194. #endif
  195. void PopulateTypes (IEnumerable<Type> knownTypes)
  196. {
  197. if (known_types == null)
  198. known_types= new KnownTypeCollection ();
  199. if (knownTypes != null) {
  200. foreach (Type t in knownTypes)
  201. known_types.TryRegister (t);
  202. }
  203. Type elementType = type;
  204. if (type.HasElementType)
  205. elementType = type.GetElementType ();
  206. /* Get all KnownTypeAttribute-s, including inherited ones */
  207. object [] attrs = elementType.GetCustomAttributes (typeof (KnownTypeAttribute), true);
  208. for (int i = 0; i < attrs.Length; i ++) {
  209. KnownTypeAttribute kt = (KnownTypeAttribute) attrs [i];
  210. known_types.TryRegister (kt.Type);
  211. }
  212. }
  213. void FillDictionaryString (string name, string ns)
  214. {
  215. XmlDictionary d = new XmlDictionary ();
  216. root_name = d.Add (name);
  217. root_ns = d.Add (ns);
  218. names_filled = true;
  219. }
  220. void Initialize (
  221. int maxObjectsInGraph,
  222. bool ignoreExtensionDataObject,
  223. bool preserveObjectReferences,
  224. IDataContractSurrogate dataContractSurrogate)
  225. {
  226. if (maxObjectsInGraph < 0)
  227. throw new ArgumentOutOfRangeException ("maxObjectsInGraph must not be negative.");
  228. max_items = maxObjectsInGraph;
  229. ignore_ext = ignoreExtensionDataObject;
  230. preserve_refs = preserveObjectReferences;
  231. surrogate = dataContractSurrogate;
  232. PopulateTypes (Type.EmptyTypes);
  233. }
  234. #if NET_4_0
  235. public
  236. #else
  237. internal
  238. #endif
  239. DataContractResolver DataContractResolver { get; private set; }
  240. public bool IgnoreExtensionDataObject {
  241. get { return ignore_ext; }
  242. }
  243. public ReadOnlyCollection<Type> KnownTypes {
  244. get {
  245. if (returned_known_types == null)
  246. returned_known_types = new ReadOnlyCollection<Type> (known_types);
  247. return returned_known_types;
  248. }
  249. }
  250. public IDataContractSurrogate DataContractSurrogate {
  251. get { return surrogate; }
  252. }
  253. public int MaxItemsInObjectGraph {
  254. get { return max_items; }
  255. }
  256. public bool PreserveObjectReferences {
  257. get { return preserve_refs; }
  258. }
  259. public override bool IsStartObject (XmlDictionaryReader reader)
  260. {
  261. if (reader == null)
  262. throw new ArgumentNullException ("reader");
  263. reader.MoveToContent ();
  264. return reader.IsStartElement (root_name, root_ns);
  265. }
  266. // SP1
  267. public override bool IsStartObject (XmlReader reader)
  268. {
  269. return IsStartObject (XmlDictionaryReader.CreateDictionaryReader (reader));
  270. }
  271. // SP1
  272. public override object ReadObject (XmlReader reader)
  273. {
  274. return ReadObject (XmlDictionaryReader.CreateDictionaryReader (reader));
  275. }
  276. public override object ReadObject (XmlReader reader, bool verifyObjectName)
  277. {
  278. return ReadObject (XmlDictionaryReader.CreateDictionaryReader (reader), verifyObjectName);
  279. }
  280. public override object ReadObject (XmlDictionaryReader reader, bool verifyObjectName)
  281. {
  282. int startTypeCount = known_types.Count;
  283. known_types.Add (type);
  284. bool isEmpty = reader.IsEmptyElement;
  285. object ret = XmlFormatterDeserializer.Deserialize (reader, type,
  286. known_types, surrogate, DataContractResolver, root_name.Value, root_ns.Value, verifyObjectName);
  287. // remove temporarily-added known types for
  288. // rootType and object graph type.
  289. while (known_types.Count > startTypeCount)
  290. known_types.RemoveAt (startTypeCount);
  291. return ret;
  292. }
  293. #if NET_4_0
  294. public object ReadObject (XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver resolver)
  295. {
  296. var bak = DataContractResolver;
  297. try {
  298. DataContractResolver = resolver;
  299. return ReadObject (reader, verifyObjectName);
  300. } finally {
  301. DataContractResolver = bak;
  302. }
  303. }
  304. #endif
  305. private void ReadRootStartElement (XmlReader reader, Type type)
  306. {
  307. SerializationMap map =
  308. known_types.FindUserMap (type);
  309. QName name = map != null ? map.XmlName :
  310. KnownTypeCollection.GetPredefinedTypeName (type);
  311. reader.MoveToContent ();
  312. reader.ReadStartElement (name.Name, name.Namespace);
  313. // FIXME: could there be any attributes to handle here?
  314. reader.Read ();
  315. }
  316. // SP1
  317. public override void WriteObject (XmlWriter writer, object graph)
  318. {
  319. XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (writer);
  320. WriteObject (w, graph);
  321. }
  322. #if NET_4_0
  323. public void WriteObject (XmlDictionaryWriter writer, object graph, DataContractResolver resolver)
  324. {
  325. var bak = DataContractResolver;
  326. try {
  327. DataContractResolver = resolver;
  328. WriteObject (writer, graph);
  329. } finally {
  330. DataContractResolver = bak;
  331. }
  332. }
  333. #endif
  334. [MonoTODO ("support arrays; support Serializable; support SharedType; use DataContractSurrogate")]
  335. /*
  336. when writeContentOnly is true, then the input XmlWriter
  337. must be at element state. This is to write possible
  338. xsi:nil.
  339. rootType determines the top-level element QName (thus
  340. it is ignored when writeContentOnly is true).
  341. preserveObjectReferences indicates that whether the
  342. output should contain ms:Id or not.
  343. (http://schemas.microsoft.com/2003/10/Serialization/)
  344. */
  345. public override void WriteObjectContent (XmlDictionaryWriter writer, object graph)
  346. {
  347. if (graph == null)
  348. return;
  349. int startTypeCount = known_types.Count;
  350. XmlFormatterSerializer.Serialize (writer, graph,
  351. known_types,
  352. ignore_ext, max_items, root_ns.Value, preserve_refs);
  353. // remove temporarily-added known types for
  354. // rootType and object graph type.
  355. while (known_types.Count > startTypeCount)
  356. known_types.RemoveAt (startTypeCount);
  357. }
  358. public override void WriteObjectContent (XmlWriter writer, object graph)
  359. {
  360. XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (writer);
  361. WriteObjectContent (w, graph);
  362. }
  363. // SP1
  364. public override void WriteStartObject (
  365. XmlWriter writer, object graph)
  366. {
  367. WriteStartObject (XmlDictionaryWriter.CreateDictionaryWriter (writer), graph);
  368. }
  369. public override void WriteStartObject (
  370. XmlDictionaryWriter writer, object graph)
  371. {
  372. Type rootType = type;
  373. if (root_name.Value == "")
  374. throw new InvalidDataContractException ("Type '" + type.ToString () +
  375. "' cannot have a DataContract attribute Name set to null or empty string.");
  376. if (graph == null) {
  377. if (names_filled)
  378. writer.WriteStartElement (root_name.Value, root_ns.Value);
  379. else
  380. writer.WriteStartElement (root_name, root_ns);
  381. writer.WriteAttributeString ("i", "nil", XmlSchema.InstanceNamespace, "true");
  382. return;
  383. }
  384. QName instName = null;
  385. QName root_qname = known_types.GetQName (rootType);
  386. QName graph_qname = known_types.GetQName (graph.GetType ());
  387. known_types.Add (graph.GetType ());
  388. if (names_filled)
  389. writer.WriteStartElement (root_name.Value, root_ns.Value);
  390. else
  391. writer.WriteStartElement (root_name, root_ns);
  392. if (root_ns.Value != root_qname.Namespace)
  393. if (root_qname.Namespace != KnownTypeCollection.MSSimpleNamespace)
  394. writer.WriteXmlnsAttribute (null, root_qname.Namespace);
  395. if (root_qname == graph_qname) {
  396. if (root_qname.Namespace != KnownTypeCollection.MSSimpleNamespace &&
  397. !rootType.IsEnum)
  398. //FIXME: Hack, when should the "i:type" be written?
  399. //Not used in case of enums
  400. writer.WriteXmlnsAttribute ("i", XmlSchema.InstanceNamespace);
  401. return;
  402. }
  403. /* Different names */
  404. known_types.Add (rootType);
  405. instName = KnownTypeCollection.GetPredefinedTypeName (graph.GetType ());
  406. if (instName == QName.Empty)
  407. /* Not a primitive type */
  408. instName = graph_qname;
  409. else
  410. /* FIXME: Hack, .. see test WriteObject7 () */
  411. instName = new QName (instName.Name, XmlSchema.Namespace);
  412. // output xsi:type as rootType is not equivalent to the graph's type.
  413. writer.WriteStartAttribute ("i", "type", XmlSchema.InstanceNamespace);
  414. writer.WriteQualifiedName (instName.Name, instName.Namespace);
  415. writer.WriteEndAttribute ();
  416. }
  417. public override void WriteEndObject (XmlDictionaryWriter writer)
  418. {
  419. writer.WriteEndElement ();
  420. }
  421. // SP1
  422. public override void WriteEndObject (XmlWriter writer)
  423. {
  424. WriteEndObject (XmlDictionaryWriter.CreateDictionaryWriter (writer));
  425. }
  426. }
  427. }
  428. #endif