PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/NServiceBus.Core.Tests/Serializers/XML/SerializerTests.cs

http://github.com/NServiceBus/NServiceBus
C# | 1538 lines | 1271 code | 266 blank | 1 comment | 15 complexity | f85e560df17849dce4384cfc187c0316 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. #pragma warning disable DE0006
  2. namespace NServiceBus.Serializers.XML.Test
  3. {
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net.Mail;
  12. using System.Runtime.Serialization;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Xml;
  16. using System.Xml.Linq;
  17. using A;
  18. using AlternateNamespace;
  19. using B;
  20. using MessageInterfaces;
  21. using MessageInterfaces.MessageMapper.Reflection;
  22. using NUnit.Framework;
  23. using Serialization;
  24. [TestFixture]
  25. public class SerializerTests
  26. {
  27. [Test]
  28. public void SerializeInvalidCharacters()
  29. {
  30. IMessageMapper mapper = new MessageMapper();
  31. var serializer = SerializerFactory.Create<MessageWithInvalidCharacter>();
  32. var msg = mapper.CreateInstance<MessageWithInvalidCharacter>();
  33. var sb = new StringBuilder();
  34. sb.Append("Hello");
  35. sb.Append((char)0x1C);
  36. sb.Append("John");
  37. msg.Special = sb.ToString();
  38. using (var stream = new MemoryStream())
  39. {
  40. serializer.Serialize(msg, stream);
  41. stream.Position = 0;
  42. var msgArray = serializer.Deserialize(stream);
  43. var m = (MessageWithInvalidCharacter)msgArray[0];
  44. Assert.AreEqual(sb.ToString(), m.Special);
  45. }
  46. }
  47. [Test] //note: This is not a desired behavior, but this test documents this limitation
  48. public void Limitation_Does_not_handle_types_implementing_ISerializable()
  49. {
  50. var message = new MessageImplementingISerializable("test");
  51. var serializer = SerializerFactory.Create<MessageImplementingISerializable>();
  52. using (var stream = new MemoryStream())
  53. {
  54. serializer.Serialize(message, stream);
  55. stream.Position = 0;
  56. var result = (MessageImplementingISerializable)serializer.Deserialize(stream)[0];
  57. Assert.Null(result.ReadOnlyProperty);
  58. }
  59. }
  60. [Test]
  61. public void Should_handle_struct_message()
  62. {
  63. var message = new StructMessage
  64. {
  65. SomeProperty = "property",
  66. SomeField = "field"
  67. };
  68. var serializer = SerializerFactory.Create<StructMessage>();
  69. using (var stream = new MemoryStream())
  70. {
  71. serializer.Serialize(message, stream);
  72. stream.Position = 0;
  73. var result = (StructMessage)serializer.Deserialize(stream)[0];
  74. Assert.AreEqual(message.SomeField, result.SomeField);
  75. Assert.AreEqual(message.SomeProperty, result.SomeProperty);
  76. }
  77. }
  78. [Test] //note: This is not a desired behavior, but this test documents this limitation
  79. public void Limitation_Does_not_handle_message_with_struct_property()
  80. {
  81. var message = new MessageWithStructProperty();
  82. var serializer = SerializerFactory.Create<MessageWithStructProperty>();
  83. using (var stream = new MemoryStream())
  84. {
  85. serializer.Serialize(message, stream);
  86. stream.Position = 0;
  87. var ex = Assert.Throws<Exception>(() => serializer.Deserialize(stream));
  88. StringAssert.StartsWith("Type not supported by the serializer", ex.Message);
  89. }
  90. }
  91. [Test] //note: This is not a desired behavior, but this test documents this limitation
  92. public void Limitation_Does_not_handle_concrete_message_with_invalid_interface_property()
  93. {
  94. var message = new MessageWithInvalidInterfaceProperty
  95. {
  96. InterfaceProperty = new InvalidInterfacePropertyImplementation
  97. {
  98. SomeProperty = "test"
  99. }
  100. };
  101. var serializer = SerializerFactory.Create<MessageWithInvalidInterfaceProperty>();
  102. using (var stream = new MemoryStream())
  103. {
  104. serializer.Serialize(message, stream);
  105. stream.Position = 0;
  106. Assert.Throws<Exception>(() => serializer.Deserialize(stream));
  107. }
  108. }
  109. [Test]
  110. public void Should_handle_concrete_message_with_interface_property()
  111. {
  112. var message = new MessageWithInterfaceProperty
  113. {
  114. InterfaceProperty = new InterfacePropertyImplementation
  115. {
  116. SomeProperty = "test"
  117. }
  118. };
  119. var serializer = SerializerFactory.Create<MessageWithInterfaceProperty>();
  120. using (var stream = new MemoryStream())
  121. {
  122. serializer.Serialize(message, stream);
  123. stream.Position = 0;
  124. var result = (MessageWithInterfaceProperty)serializer.Deserialize(stream)[0];
  125. Assert.AreEqual(message.InterfaceProperty.SomeProperty, result.InterfaceProperty.SomeProperty);
  126. }
  127. }
  128. [Test]
  129. public void Should_handle_interface_message_with_interface_property()
  130. {
  131. IMessageWithInterfaceProperty message = new InterfaceMessageWithInterfacePropertyImplementation
  132. {
  133. InterfaceProperty = new InterfacePropertyImplementation
  134. {
  135. SomeProperty = "test"
  136. }
  137. };
  138. var serializer = SerializerFactory.Create<IMessageWithInterfaceProperty>();
  139. using (var stream = new MemoryStream())
  140. {
  141. serializer.Serialize(message, stream);
  142. stream.Position = 0;
  143. var result = (IMessageWithInterfaceProperty)serializer.Deserialize(stream, new[]
  144. {
  145. typeof(IMessageWithInterfaceProperty)
  146. })[0];
  147. Assert.AreEqual(message.InterfaceProperty.SomeProperty, result.InterfaceProperty.SomeProperty);
  148. }
  149. }
  150. [Test, Ignore("ArrayList is not supported")]
  151. public void Should_deserialize_arrayList()
  152. {
  153. var expected = new ArrayList
  154. {
  155. "Value1",
  156. "Value2",
  157. "Value3"
  158. };
  159. var result = ExecuteSerializer.ForMessage<MessageWithArrayList>(m3 => m3.ArrayList = expected);
  160. CollectionAssert.AreEqual(expected, result.ArrayList);
  161. }
  162. [Test, Ignore("Hashtable is not supported")]
  163. public void Should_deserialize_hashtable()
  164. {
  165. var expected = new Hashtable
  166. {
  167. {"Key1", "Value1"},
  168. {"Key2", "Value2"},
  169. {"Key3", "Value3"}
  170. };
  171. var result = ExecuteSerializer.ForMessage<MessageWithHashtable>(m3 => m3.Hashtable = expected);
  172. CollectionAssert.AreEqual(expected, result.Hashtable);
  173. }
  174. [Test]
  175. public void Should_deserialize_multiple_messages_from_different_namespaces()
  176. {
  177. var xml = @"<?xml version=""1.0"" ?>
  178. <Messages
  179. xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
  180. xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
  181. xmlns=""http://tempuri.net/NServiceBus.Serializers.XML.Test.A""
  182. xmlns:q1=""http://tempuri.net/NServiceBus.Serializers.XML.Test.B"">
  183. <Command1>
  184. <Id>1eb17e5d-8573-49af-a5cb-76b4a602bb79</Id>
  185. </Command1>
  186. <q1:Command2>
  187. <Id>ad3b5a84-6cf1-4376-aa2d-058b1120c12f</Id>
  188. </q1:Command2>
  189. </Messages>
  190. ";
  191. using (var stream = new MemoryStream())
  192. {
  193. var writer = new StreamWriter(stream);
  194. writer.Write(xml);
  195. writer.Flush();
  196. stream.Position = 0;
  197. var msgArray = SerializerFactory.Create(typeof(Command1), typeof(Command2)).Deserialize(stream);
  198. Assert.AreEqual(typeof(Command1), msgArray[0].GetType());
  199. Assert.AreEqual(typeof(Command2), msgArray[1].GetType());
  200. }
  201. }
  202. [Test]
  203. public void Should_infer_message_type_from_root_node_if_type_is_known()
  204. {
  205. using (var stream = new MemoryStream())
  206. {
  207. var writer = new StreamWriter(stream);
  208. writer.WriteLine("<NServiceBus.Serializers.XML.Test.MessageWithDouble><Double>23.4</Double></NServiceBus.Serializers.XML.Test.MessageWithDouble>");
  209. writer.Flush();
  210. stream.Position = 0;
  211. var msgArray = SerializerFactory.Create(typeof(MessageWithDouble)).Deserialize(stream);
  212. Assert.AreEqual(typeof(MessageWithDouble), msgArray[0].GetType());
  213. }
  214. }
  215. [Test]
  216. public void Deserialize_private_message_with_two_unrelated_interface_without_wrapping()
  217. {
  218. var serializer = SerializerFactory.Create(typeof(CompositeMessage), typeof(IMyEventA), typeof(IMyEventB));
  219. var deserializer = SerializerFactory.Create(typeof(IMyEventA), typeof(IMyEventB));
  220. using (var stream = new MemoryStream())
  221. {
  222. var msg = new CompositeMessage
  223. {
  224. IntValue = 42,
  225. StringValue = "Answer"
  226. };
  227. serializer.Serialize(msg, stream);
  228. stream.Position = 0;
  229. var result = deserializer.Deserialize(stream, new[]
  230. {
  231. typeof(IMyEventA),
  232. typeof(IMyEventB)
  233. });
  234. var a = (IMyEventA)result[0];
  235. var b = (IMyEventB)result[1];
  236. Assert.AreEqual(42, b.IntValue);
  237. Assert.AreEqual("Answer", a.StringValue);
  238. }
  239. }
  240. [Test]
  241. public void Should_be_able_to_serialize_single_message_without_wrapping_element()
  242. {
  243. Serializer.ForMessage<EmptyMessage>(new EmptyMessage())
  244. .AssertResultingXml(d => d.DocumentElement.Name == "EmptyMessage", "Root should be message typename");
  245. }
  246. [Test]
  247. public void Should_be_able_to_serialize_single_message_without_wrapping_xml_raw_data()
  248. {
  249. const string XmlElement = "<SomeClass xmlns=\"http://nservicebus.com\"><SomeProperty value=\"Bar\" /></SomeClass>";
  250. const string XmlDocument = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + XmlElement;
  251. var messageWithXDocument = new MessageWithXDocument
  252. {
  253. Document = XDocument.Load(new StringReader(XmlDocument))
  254. };
  255. var messageWithXElement = new MessageWithXElement
  256. {
  257. Document = XElement.Load(new StringReader(XmlElement))
  258. };
  259. Serializer.ForMessage<MessageWithXDocument>(messageWithXDocument, s => { s.SkipWrappingRawXml = true; })
  260. .AssertResultingXml(d => d.DocumentElement.ChildNodes[0].FirstChild.Name != "Document", "Property name should not be available");
  261. Serializer.ForMessage<MessageWithXElement>(messageWithXElement, s => { s.SkipWrappingRawXml = true; })
  262. .AssertResultingXml(d => d.DocumentElement.ChildNodes[0].FirstChild.Name != "Document", "Property name should not be available");
  263. }
  264. [Test]
  265. public void Should_deserialize_messages_where_xml_raw_data_root_element_matches_property_name()
  266. {
  267. const string XmlElement = "<Document xmlns=\"http://nservicebus.com\"><SomeProperty value=\"Bar\" /></Document>";
  268. const string XmlDocument = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + XmlElement;
  269. var messageWithXDocument = new MessageWithXDocument
  270. {
  271. Document = XDocument.Load(new StringReader(XmlDocument))
  272. };
  273. var messageWithXElement = new MessageWithXElement
  274. {
  275. Document = XElement.Load(new StringReader(XmlElement))
  276. };
  277. var serializer = SerializerFactory.Create<MessageWithXDocument>();
  278. serializer.SkipWrappingRawXml = true;
  279. using (var stream = new MemoryStream())
  280. {
  281. serializer.Serialize(messageWithXDocument, stream);
  282. stream.Position = 0;
  283. serializer = SerializerFactory.Create(typeof(MessageWithXDocument));
  284. serializer.SkipWrappingRawXml = true;
  285. var msg = serializer.Deserialize(stream).Cast<MessageWithXDocument>().Single();
  286. Assert.NotNull(msg.Document);
  287. Assert.AreEqual("Document", msg.Document.Root.Name.LocalName);
  288. }
  289. serializer = SerializerFactory.Create<MessageWithXElement>();
  290. serializer.SkipWrappingRawXml = true;
  291. using (var stream = new MemoryStream())
  292. {
  293. serializer.Serialize(messageWithXElement, stream);
  294. stream.Position = 0;
  295. serializer = SerializerFactory.Create(typeof(MessageWithXElement));
  296. serializer.SkipWrappingRawXml = true;
  297. var msg = serializer.Deserialize(stream).Cast<MessageWithXElement>().Single();
  298. Assert.NotNull(msg.Document);
  299. Assert.AreEqual("Document", msg.Document.Name.LocalName);
  300. }
  301. }
  302. [Test]
  303. public void Should_be_able_to_serialize_single_message_with_default_namespaces_and_then_deserialize()
  304. {
  305. var serializer = SerializerFactory.Create<MessageWithDouble>();
  306. var msg = new MessageWithDouble();
  307. using (var stream = new MemoryStream())
  308. {
  309. serializer.Serialize(msg, stream);
  310. stream.Position = 0;
  311. var msgArray = SerializerFactory.Create(typeof(MessageWithDouble)).Deserialize(stream);
  312. Assert.AreEqual(typeof(MessageWithDouble), msgArray[0].GetType());
  313. }
  314. }
  315. [Test]
  316. public void Should_be_able_to_serialize_single_message_with_default_namespaces()
  317. {
  318. var serializer = SerializerFactory.Create<EmptyMessage>();
  319. var msg = new EmptyMessage();
  320. var expected = @"<EmptyMessage xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://tempuri.net/NServiceBus.Serializers.XML.Test""></EmptyMessage>";
  321. AssertSerializedEquals(serializer, msg, expected);
  322. }
  323. [Test]
  324. public void Should_be_able_to_serialize_single_message_with_specified_namespaces()
  325. {
  326. var serializer = SerializerFactory.Create<EmptyMessage>();
  327. serializer.Namespace = "http://super.com";
  328. var msg = new EmptyMessage();
  329. var expected = @"<EmptyMessage xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://super.com/NServiceBus.Serializers.XML.Test""></EmptyMessage>";
  330. AssertSerializedEquals(serializer, msg, expected);
  331. }
  332. [Test]
  333. public void Should_be_able_to_serialize_single_message_with_specified_namespace_with_trailing_forward_slashes()
  334. {
  335. var serializer = SerializerFactory.Create<EmptyMessage>();
  336. serializer.Namespace = "http://super.com///";
  337. var msg = new EmptyMessage();
  338. var expected = @"<EmptyMessage xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://super.com/NServiceBus.Serializers.XML.Test""></EmptyMessage>";
  339. AssertSerializedEquals(serializer, msg, expected);
  340. }
  341. static void AssertSerializedEquals(IMessageSerializer serializer, IMessage msg, string expected)
  342. {
  343. using (var stream = new MemoryStream())
  344. {
  345. serializer.Serialize(msg, stream);
  346. stream.Position = 0;
  347. string result;
  348. using (var reader = new StreamReader(stream))
  349. {
  350. result = XDocument.Load(reader).ToString();
  351. }
  352. Assert.AreEqual(expected, result);
  353. }
  354. }
  355. [Test]
  356. public void Should_deserialize_a_single_message_with_typeName_passed_in_externally()
  357. {
  358. using (var stream = new MemoryStream())
  359. {
  360. var writer = new StreamWriter(stream);
  361. writer.WriteLine("<WhatEver><Double>23.4</Double></WhatEver>");
  362. writer.Flush();
  363. stream.Position = 0;
  364. var msgArray = SerializerFactory.Create(typeof(MessageWithDouble)).Deserialize(stream, new[]
  365. {
  366. typeof(MessageWithDouble)
  367. });
  368. Assert.AreEqual(typeof(MessageWithDouble), msgArray[0].GetType());
  369. }
  370. }
  371. [Test]
  372. public void Should_deserialize_a_single_message_with_typeName_passed_in_externally_even_when_not_initialized_with_type()
  373. {
  374. using (var stream = new MemoryStream())
  375. {
  376. var writer = new StreamWriter(stream);
  377. writer.WriteLine("<WhatEver><Double>23.4</Double></WhatEver>");
  378. writer.Flush();
  379. stream.Position = 0;
  380. var msgArray = SerializerFactory.Create()
  381. .Deserialize(stream, new[]
  382. {
  383. typeof(MessageWithDouble)
  384. });
  385. Assert.AreEqual(23.4, ((MessageWithDouble)msgArray[0]).Double);
  386. }
  387. }
  388. [Test]
  389. public void Should_deserialize_a_batched_messages_with_typeName_passed_in_externally()
  390. {
  391. using (var stream = new MemoryStream())
  392. {
  393. var writer = new StreamWriter(stream);
  394. writer.WriteLine("<Messages><WhatEver><Double>23.4</Double></WhatEver><TheEmptyMessage></TheEmptyMessage></Messages>");
  395. writer.Flush();
  396. stream.Position = 0;
  397. var msgArray = SerializerFactory.Create(typeof(MessageWithDouble), typeof(EmptyMessage))
  398. .Deserialize(stream, new[]
  399. {
  400. typeof(MessageWithDouble),
  401. typeof(EmptyMessage)
  402. });
  403. Assert.AreEqual(23.4, ((MessageWithDouble)msgArray[0]).Double);
  404. Assert.AreEqual(typeof(EmptyMessage), msgArray[1].GetType());
  405. }
  406. }
  407. [Test]
  408. public void Should_deserialize_a_batched_messages_with_typeName_passed_in_externally_even_when_not_initialized_with_type()
  409. {
  410. using (var stream = new MemoryStream())
  411. {
  412. var writer = new StreamWriter(stream);
  413. writer.WriteLine("<Messages><WhatEver><Double>23.4</Double></WhatEver><TheEmptyMessage></TheEmptyMessage></Messages>");
  414. writer.Flush();
  415. stream.Position = 0;
  416. var msgArray = SerializerFactory.Create()
  417. .Deserialize(stream, new[]
  418. {
  419. typeof(MessageWithDouble),
  420. typeof(EmptyMessage)
  421. });
  422. Assert.AreEqual(23.4, ((MessageWithDouble)msgArray[0]).Double);
  423. Assert.AreEqual(typeof(EmptyMessage), msgArray[1].GetType());
  424. }
  425. }
  426. [Test]
  427. public void TestMultipleInterfacesDuplicatedProperty()
  428. {
  429. var mapper = new MessageMapper();
  430. var serializer = SerializerFactory.Create<IThird>(mapper);
  431. var msgBeforeSerialization = mapper.CreateInstance<IThird>(x => x.FirstName = "Danny");
  432. var count = 0;
  433. using (var stream = new MemoryStream())
  434. {
  435. serializer.Serialize(msgBeforeSerialization, stream);
  436. stream.Position = 0;
  437. var reader = XmlReader.Create(stream);
  438. while (reader.Read())
  439. if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "FirstName"))
  440. count++;
  441. }
  442. Assert.AreEqual(count, 1);
  443. }
  444. [Test]
  445. public void Generic_properties_should_be_supported()
  446. {
  447. var result = ExecuteSerializer.ForMessage<MessageWithGenericProperty>(m =>
  448. {
  449. m.GenericProperty =
  450. new GenericProperty<string>("test")
  451. {
  452. WhatEver = "a property"
  453. };
  454. });
  455. Assert.AreEqual("a property", result.GenericProperty.WhatEver);
  456. }
  457. [Test]
  458. public void Culture()
  459. {
  460. var serializer = SerializerFactory.Create<MessageWithDouble>();
  461. var val = 65.36;
  462. var msg = new MessageWithDouble
  463. {
  464. Double = val
  465. };
  466. Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
  467. var stream = new MemoryStream();
  468. serializer.Serialize(msg, stream);
  469. Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
  470. stream.Position = 0;
  471. var msgArray = serializer.Deserialize(stream);
  472. var m = (MessageWithDouble)msgArray[0];
  473. Assert.AreEqual(val, m.Double);
  474. stream.Dispose();
  475. }
  476. [Test]
  477. public void Comparison()
  478. {
  479. TestInterfaces();
  480. TestDataContractSerializer();
  481. }
  482. [Test]
  483. public void TestInterfaces()
  484. {
  485. var mapper = new MessageMapper();
  486. var serializer = SerializerFactory.Create<ISecondSerializableMessage>(mapper);
  487. var o = mapper.CreateInstance<ISecondSerializableMessage>();
  488. o.Id = Guid.NewGuid();
  489. o.Age = 10;
  490. o.Address = Guid.NewGuid().ToString();
  491. o.Int = 7;
  492. o.Name = "udi";
  493. o.Uri = new Uri("http://www.UdiDahan.com/");
  494. o.Risk = new Risk
  495. {
  496. Percent = 0.15D,
  497. Annum = true,
  498. Accuracy = 0.314M
  499. };
  500. o.Some = SomeEnum.B;
  501. o.Start = DateTime.Now;
  502. o.Duration = TimeSpan.Parse("-01:15:27.123");
  503. o.Offset = DateTimeOffset.Now;
  504. o.Lookup = new MyDictionary();
  505. o.Lookup["1"] = "1";
  506. o.Foos = new Dictionary<string, List<Foo>>();
  507. o.Foos["foo1"] = new List<Foo>(new[]
  508. {
  509. new Foo
  510. {
  511. Name = "1",
  512. Title = "1"
  513. },
  514. new Foo
  515. {
  516. Name = "2",
  517. Title = "2"
  518. }
  519. });
  520. o.Data = new byte[]
  521. {
  522. 1,
  523. 2,
  524. 3,
  525. 4,
  526. 5,
  527. 4,
  528. 3,
  529. 2,
  530. 1
  531. };
  532. o.SomeStrings = new List<string>
  533. {
  534. "a",
  535. "b",
  536. "c"
  537. };
  538. o.ArrayFoos = new[]
  539. {
  540. new Foo
  541. {
  542. Name = "FooArray1",
  543. Title = "Mr."
  544. },
  545. new Foo
  546. {
  547. Name = "FooAray2",
  548. Title = "Mrs"
  549. }
  550. };
  551. o.Bars = new[]
  552. {
  553. new Bar
  554. {
  555. Name = "Bar1",
  556. Length = 1
  557. },
  558. new Bar
  559. {
  560. Name = "BAr2",
  561. Length = 5
  562. }
  563. };
  564. o.NaturalNumbers = new HashSet<int>(new[]
  565. {
  566. 0,
  567. 1,
  568. 2,
  569. 3,
  570. 4,
  571. 5,
  572. 6,
  573. 7,
  574. 8,
  575. 9
  576. });
  577. o.Developers = new HashSet<string>(new[]
  578. {
  579. "Udi Dahan",
  580. "Andreas Ohlund",
  581. "Matt Burton",
  582. "Jonathan Oliver et al"
  583. });
  584. o.Parent = mapper.CreateInstance<IFirstSerializableMessage>();
  585. o.Parent.Name = "udi";
  586. o.Parent.Age = 10;
  587. o.Parent.Address = Guid.NewGuid().ToString();
  588. o.Parent.Int = 7;
  589. o.Parent.Name = "-1";
  590. o.Parent.Risk = new Risk
  591. {
  592. Percent = 0.15D,
  593. Annum = true,
  594. Accuracy = 0.314M
  595. };
  596. o.Names = new List<IFirstSerializableMessage>();
  597. for (var i = 0; i < number; i++)
  598. {
  599. var firstMessage = mapper.CreateInstance<IFirstSerializableMessage>();
  600. o.Names.Add(firstMessage);
  601. firstMessage.Age = 10;
  602. firstMessage.Address = Guid.NewGuid().ToString();
  603. firstMessage.Int = 7;
  604. firstMessage.Name = i.ToString();
  605. firstMessage.Risk = new Risk
  606. {
  607. Percent = 0.15D,
  608. Annum = true,
  609. Accuracy = 0.314M
  610. };
  611. }
  612. o.MoreNames = o.Names.ToArray();
  613. Time(o, serializer);
  614. }
  615. [Test]
  616. public void TestDataContractSerializer()
  617. {
  618. var o = CreateSecondSerializableMessage();
  619. var messages = new IMessage[]
  620. {
  621. o
  622. };
  623. var dataContractSerializer = new DataContractSerializer(typeof(ArrayList), new[]
  624. {
  625. typeof(SecondSerializableMessage),
  626. typeof(SomeEnum),
  627. typeof(FirstSerializableMessage),
  628. typeof(Risk),
  629. typeof(List<FirstSerializableMessage>)
  630. });
  631. var sw = new Stopwatch();
  632. sw.Start();
  633. var xmlWriterSettings = new XmlWriterSettings
  634. {
  635. OmitXmlDeclaration = false
  636. };
  637. var xmlReaderSettings = new XmlReaderSettings
  638. {
  639. IgnoreProcessingInstructions = true,
  640. ValidationType = ValidationType.None,
  641. IgnoreWhitespace = true,
  642. CheckCharacters = false,
  643. ConformanceLevel = ConformanceLevel.Auto
  644. };
  645. for (var i = 0; i < numberOfIterations; i++)
  646. using (var stream = new MemoryStream())
  647. DataContractSerialize(xmlWriterSettings, dataContractSerializer, messages, stream);
  648. sw.Stop();
  649. Debug.WriteLine("serialization " + sw.Elapsed);
  650. sw.Reset();
  651. File.Delete("a.xml");
  652. using (var fs = File.Open("a.xml", FileMode.OpenOrCreate))
  653. DataContractSerialize(xmlWriterSettings, dataContractSerializer, messages, fs);
  654. var s = new MemoryStream();
  655. DataContractSerialize(xmlWriterSettings, dataContractSerializer, messages, s);
  656. var buffer = s.GetBuffer();
  657. s.Dispose();
  658. sw.Start();
  659. for (var i = 0; i < numberOfIterations; i++)
  660. using (var reader = XmlReader.Create(new MemoryStream(buffer), xmlReaderSettings))
  661. dataContractSerializer.ReadObject(reader);
  662. sw.Stop();
  663. Debug.WriteLine("deserializing: " + sw.Elapsed);
  664. }
  665. [Test]
  666. public void SerializeLists()
  667. {
  668. IMessageMapper mapper = new MessageMapper();
  669. var serializer = SerializerFactory.Create<MessageWithList>();
  670. var msg = mapper.CreateInstance<MessageWithList>();
  671. msg.Items = new List<MessageWithListItem>
  672. {
  673. new MessageWithListItem
  674. {
  675. Data = "Hello"
  676. }
  677. };
  678. using (var stream = new MemoryStream())
  679. {
  680. serializer.Serialize(msg, stream);
  681. stream.Position = 0;
  682. var msgArray = serializer.Deserialize(stream);
  683. var m = (MessageWithList)msgArray[0];
  684. Assert.AreEqual("Hello", m.Items.First().Data);
  685. }
  686. }
  687. [Test]
  688. public void SerializeClosedGenericListsInAlternateNamespace()
  689. {
  690. IMessageMapper mapper = new MessageMapper();
  691. var serializer = SerializerFactory.Create<MessageWithClosedListInAlternateNamespace>();
  692. var msg = mapper.CreateInstance<MessageWithClosedListInAlternateNamespace>();
  693. msg.Items = new AlternateItemList
  694. {
  695. new MessageWithListItemAlternate
  696. {
  697. Data = "Hello"
  698. }
  699. };
  700. using (var stream = new MemoryStream())
  701. {
  702. serializer.Serialize(msg, stream);
  703. stream.Position = 0;
  704. var msgArray = serializer.Deserialize(stream);
  705. var m = (MessageWithClosedListInAlternateNamespace)msgArray[0];
  706. Assert.AreEqual("Hello", m.Items.First().Data);
  707. }
  708. }
  709. [Test]
  710. public void SerializeClosedGenericListsInAlternateNamespaceMultipleIEnumerableImplementations()
  711. {
  712. IMessageMapper mapper = new MessageMapper();
  713. var serializer = SerializerFactory.Create<MessageWithClosedListInAlternateNamespaceMultipleIEnumerableImplementations>();
  714. var msg = mapper.CreateInstance<MessageWithClosedListInAlternateNamespaceMultipleIEnumerableImplementations>();
  715. msg.Items = new AlternateItemListMultipleIEnumerableImplementations
  716. {
  717. new MessageWithListItemAlternate
  718. {
  719. Data = "Hello"
  720. }
  721. };
  722. using (var stream = new MemoryStream())
  723. {
  724. serializer.Serialize(msg, stream);
  725. stream.Position = 0;
  726. var msgArray = serializer.Deserialize(stream);
  727. var m = (MessageWithClosedListInAlternateNamespaceMultipleIEnumerableImplementations)msgArray[0];
  728. Assert.AreEqual("Hello", m.Items.First<MessageWithListItemAlternate>().Data);
  729. }
  730. }
  731. [Test]
  732. public void SerializeClosedGenericListsInAlternateNamespaceMultipleIListImplementations()
  733. {
  734. IMessageMapper mapper = new MessageMapper();
  735. var serializer = SerializerFactory.Create<MessageWithClosedListInAlternateNamespaceMultipleIListImplementations>();
  736. var msg = mapper.CreateInstance<MessageWithClosedListInAlternateNamespaceMultipleIListImplementations>();
  737. msg.Items = new AlternateItemListMultipleIListImplementations
  738. {
  739. new MessageWithListItemAlternate
  740. {
  741. Data = "Hello"
  742. }
  743. };
  744. using (var stream = new MemoryStream())
  745. {
  746. serializer.Serialize(msg, stream);
  747. stream.Position = 0;
  748. var msgArray = serializer.Deserialize(stream);
  749. var m = (MessageWithClosedListInAlternateNamespaceMultipleIListImplementations)msgArray[0];
  750. Assert.AreEqual("Hello", m.Items.First<MessageWithListItemAlternate>().Data);
  751. }
  752. }
  753. [Test]
  754. public void SerializeClosedGenericListsInSameNamespace()
  755. {
  756. IMessageMapper mapper = new MessageMapper();
  757. var serializer = SerializerFactory.Create<MessageWithClosedList>();
  758. var msg = mapper.CreateInstance<MessageWithClosedList>();
  759. msg.Items = new ItemList
  760. {
  761. new MessageWithListItem
  762. {
  763. Data = "Hello"
  764. }
  765. };
  766. using (var stream = new MemoryStream())
  767. {
  768. serializer.Serialize(msg, stream);
  769. stream.Position = 0;
  770. var msgArray = serializer.Deserialize(stream);
  771. var m = (MessageWithClosedList)msgArray[0];
  772. Assert.AreEqual("Hello", m.Items.First().Data);
  773. }
  774. }
  775. [Test]
  776. public void SerializeEmptyLists()
  777. {
  778. IMessageMapper mapper = new MessageMapper();
  779. var serializer = SerializerFactory.Create<MessageWithList>();
  780. var msg = mapper.CreateInstance<MessageWithList>();
  781. msg.Items = new List<MessageWithListItem>();
  782. using (var stream = new MemoryStream())
  783. {
  784. serializer.Serialize(msg, stream);
  785. stream.Position = 0;
  786. var msgArray = serializer.Deserialize(stream);
  787. var m = (MessageWithList)msgArray[0];
  788. Assert.IsEmpty(m.Items);
  789. }
  790. }
  791. void DataContractSerialize(XmlWriterSettings xmlWriterSettings, DataContractSerializer dataContractSerializer, IMessage[] messages, Stream stream)
  792. {
  793. var o = new ArrayList(messages);
  794. using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
  795. {
  796. dataContractSerializer.WriteStartObject(xmlWriter, o);
  797. dataContractSerializer.WriteObjectContent(xmlWriter, o);
  798. dataContractSerializer.WriteEndObject(xmlWriter);
  799. }
  800. }
  801. SecondSerializableMessage CreateSecondSerializableMessage()
  802. {
  803. var secondMessage = new SecondSerializableMessage
  804. {
  805. Id = Guid.NewGuid(),
  806. Age = 10,
  807. Address = Guid.NewGuid().ToString(),
  808. Int = 7,
  809. Name = "udi",
  810. Risk = new Risk
  811. {
  812. Percent = 0.15D,
  813. Annum = true,
  814. Accuracy = 0.314M
  815. },
  816. Some = SomeEnum.B,
  817. Start = DateTime.Now,
  818. Duration = TimeSpan.Parse("-01:15:27.123"),
  819. Offset = DateTimeOffset.Now,
  820. Parent = new FirstSerializableMessage
  821. {
  822. Age = 10,
  823. Address = Guid.NewGuid().ToString(),
  824. Int = 7,
  825. Name = "-1",
  826. Risk = new Risk
  827. {
  828. Percent = 0.15D,
  829. Annum = true,
  830. Accuracy = 0.314M
  831. }
  832. },
  833. Names = new List<FirstSerializableMessage>()
  834. };
  835. for (var i = 0; i < number; i++)
  836. {
  837. var firstMessage = new FirstSerializableMessage();
  838. secondMessage.Names.Add(firstMessage);
  839. firstMessage.Age = 10;
  840. firstMessage.Address = Guid.NewGuid().ToString();
  841. firstMessage.Int = 7;
  842. firstMessage.Name = i.ToString();
  843. firstMessage.Risk = new Risk
  844. {
  845. Percent = 0.15D,
  846. Annum = true,
  847. Accuracy = 0.314M
  848. };
  849. }
  850. secondMessage.MoreNames = secondMessage.Names.ToArray();
  851. return secondMessage;
  852. }
  853. void Time(object message, IMessageSerializer serializer)
  854. {
  855. var watch = new Stopwatch();
  856. watch.Start();
  857. for (var i = 0; i < numberOfIterations; i++)
  858. using (var stream = new MemoryStream())
  859. serializer.Serialize(message, stream);
  860. watch.Stop();
  861. Debug.WriteLine("Serializing: " + watch.Elapsed);
  862. watch.Reset();
  863. byte[] buffer;
  864. using (var s = new MemoryStream())
  865. {
  866. serializer.Serialize(message, s);
  867. buffer = s.ToArray();
  868. }
  869. watch.Start();
  870. for (var i = 0; i < numberOfIterations; i++)
  871. {
  872. using (var forDeserializing = new MemoryStream(buffer))
  873. {
  874. serializer.Deserialize(forDeserializing);
  875. }
  876. }
  877. watch.Stop();
  878. Debug.WriteLine("Deserializing: " + watch.Elapsed);
  879. }
  880. [Test]
  881. public void NestedObjectWithNullPropertiesShouldBeSerialized()
  882. {
  883. var result = ExecuteSerializer.ForMessage<MessageWithNestedObject>(m => { m.NestedObject = new MessageWithNullProperty(); });
  884. Assert.IsNotNull(result.NestedObject);
  885. }
  886. [Test]
  887. public void Messages_with_generic_properties_closing_nullables_should_be_supported()
  888. {
  889. var theTime = DateTime.Now;
  890. var result = ExecuteSerializer.ForMessage<MessageWithGenericPropClosingNullable>(
  891. m =>
  892. {
  893. m.GenericNullable = new GenericPropertyWithNullable<DateTime?>
  894. {
  895. TheType = theTime
  896. };
  897. m.Whatever = "fdsfsdfsd";
  898. });
  899. Assert.IsNotNull(result.GenericNullable.TheType == theTime);
  900. }
  901. [Test]
  902. public void When_Using_A_Dictionary_With_An_object_As_Key_should_throw()
  903. {
  904. Assert.Throws<NotSupportedException>(() => SerializerFactory.Create<MessageWithDictionaryWithAnObjectAsKey>());
  905. }
  906. [Test]
  907. public void When_Using_A_Dictionary_With_An_Object_As_Value_should_throw()
  908. {
  909. Assert.Throws<NotSupportedException>(() => SerializerFactory.Create<MessageWithDictionaryWithAnObjectAsValue>());
  910. }
  911. [Test, Ignore("We're not supporting this type")]
  912. public void System_classes_with_non_default_constructors_should_be_supported()
  913. {
  914. var message = new MailMessage("from@gmail.com", "to@hotmail.com")
  915. {
  916. Subject = "Testing the NSB email support",
  917. Body = "Hello"
  918. };
  919. var result = ExecuteSerializer.ForMessage<MessageWithSystemClassAsProperty>(
  920. m => { m.MailMessage = message; });
  921. Assert.IsNotNull(result.MailMessage);
  922. Assert.AreEqual("from@gmail.com", result.MailMessage.From.Address);
  923. Assert.AreEqual(message.To.First(), result.MailMessage.To.First());
  924. Assert.AreEqual(message.BodyEncoding.CodePage, result.MailMessage.BodyEncoding.CodePage);
  925. Assert.AreEqual(message.BodyEncoding.EncoderFallback.MaxCharCount, result.MailMessage.BodyEncoding.EncoderFallback.MaxCharCount);
  926. }
  927. [Test, Ignore("We're currently not supporting polymorphic properties")]
  928. public void Messages_with_polymorphic_properties_should_be_supported()
  929. {
  930. var message = new PolyMessage
  931. {
  932. BaseType = new ChildOfBase
  933. {
  934. BaseTypeProp = "base",
  935. ChildProp = "Child"
  936. }
  937. };
  938. var result = ExecuteSerializer.ForMessage<PolyMessage>(message);
  939. Assert.AreEqual(message.BaseType.BaseTypeProp, result.BaseType.BaseTypeProp);
  940. Assert.AreEqual(((ChildOfBase)message.BaseType).ChildProp, ((ChildOfBase)result.BaseType).ChildProp);
  941. }
  942. [Test]
  943. public void When_Using_Property_WithXContainerAssignable_should_preserve_xml()
  944. {
  945. const string XmlElement = "<SomeClass xmlns=\"http://nservicebus.com\"><SomeProperty value=\"Bar\" ></SomeProperty></SomeClass>";
  946. const string XmlDocument = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + XmlElement;
  947. var messageWithXDocument = new MessageWithXDocument
  948. {
  949. Document = XDocument.Load(new StringReader(XmlDocument))
  950. };
  951. var messageWithXElement = new MessageWithXElement
  952. {
  953. Document = XElement.Load(new StringReader(XmlElement))
  954. };
  955. var resultXDocument = ExecuteSerializer.ForMessage<MessageWithXDocument>(messageWithXDocument);
  956. var resultXElement = ExecuteSerializer.ForMessage<MessageWithXElement>(messageWithXElement);
  957. Assert.AreEqual(messageWithXDocument.Document.ToString(), resultXDocument.Document.ToString());
  958. Assert.AreEqual(messageWithXElement.Document.ToString(), resultXElement.Document.ToString());
  959. }
  960. [Test]
  961. public void Should_be_able_to_deserialize_many_messages_of_same_type()
  962. {
  963. var xml = @"<?xml version=""1.0"" ?>
  964. <Messages xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://tempuri.net/NServiceBus.Serializers.XML.Test"">
  965. <EmptyMessage>
  966. </EmptyMessage>
  967. <EmptyMessage>
  968. </EmptyMessage>
  969. <EmptyMessage>
  970. </EmptyMessage>
  971. </Messages>
  972. ";
  973. using (var stream = new MemoryStream())
  974. {
  975. var streamWriter = new StreamWriter(stream);
  976. streamWriter.Write(xml);
  977. streamWriter.Flush();
  978. stream.Position = 0;
  979. var serializer = SerializerFactory.Create<EmptyMessage>();
  980. var msgArray = serializer.Deserialize(stream, new[]
  981. {
  982. typeof(EmptyMessage)
  983. });
  984. Assert.AreEqual(3, msgArray.Length);
  985. }
  986. }
  987. [Test]
  988. public void Object_property_with_primitive_or_struct_value_should_serialize_correctly()
  989. {
  990. // this fixes issue #2796
  991. var serializer = SerializerFactory.Create<SerializedPair>();
  992. var message = new SerializedPair
  993. {
  994. Key = "AddressId",
  995. Value = new Guid("{ebdeeb33-baa7-4100-b1aa-eb4d6816fd3d}")
  996. };
  997. object[] messageDeserialized;
  998. using (var stream = new MemoryStream())
  999. {
  1000. serializer.Serialize(message, stream);
  1001. stream.Position = 0;
  1002. messageDeserialized = serializer.Deserialize(stream, new[]
  1003. {
  1004. message.GetType()
  1005. });
  1006. }
  1007. Assert.AreEqual(message.Key, ((SerializedPair)messageDeserialized[0]).Key);
  1008. Assert.AreEqual(message.Value, ((SerializedPair)messageDeserialized[0]).Value);
  1009. }
  1010. int number = 1;
  1011. int numberOfIterations = 100;
  1012. }
  1013. public class SerializedPair
  1014. {
  1015. public string Key { get; set; }
  1016. public object Value { get; set; }
  1017. }
  1018. public class EmptyMessage : IMessage
  1019. {
  1020. }
  1021. public struct StructMessage : IMessage
  1022. {
  1023. public string SomeProperty { get; set; }
  1024. public string SomeField;
  1025. }
  1026. public class MessageWithStructProperty : IMessage
  1027. {
  1028. public SomeStruct StructProperty { get; set; }
  1029. public struct SomeStruct
  1030. {
  1031. }
  1032. }
  1033. public class PolyMessage : IMessage
  1034. {
  1035. public BaseType BaseType { get; set; }
  1036. }
  1037. public class ChildOfBase : BaseType
  1038. {
  1039. public BaseType BaseType { get; set; }
  1040. public string ChildProp { get; set; }
  1041. }
  1042. public class BaseType
  1043. {
  1044. public string BaseTypeProp { get; set; }
  1045. }
  1046. public class MessageWithGenericPropClosingNullable
  1047. {
  1048. public GenericPropertyWithNullable<DateTime?> GenericNullable { get; set; }
  1049. public string Whatever { get; set; }
  1050. }
  1051. public class MessageWithNullProperty
  1052. {
  1053. public string WillBeNull { get; set; }
  1054. }
  1055. public class MessageWithDouble
  1056. {
  1057. public double Double { get; set; }
  1058. }
  1059. public class MessageWithGenericProperty
  1060. {
  1061. public GenericProperty<string> GenericProperty { get; set; }
  1062. public GenericProperty<string> GenericPropertyThatIsNull { get; set; }
  1063. }
  1064. public class MessageWithNestedObject
  1065. {
  1066. public MessageWithNullProperty NestedObject { get; set; }
  1067. }
  1068. public class MessageWithSystemClassAsProperty
  1069. {
  1070. public MailMessage MailMessage { get; set; }
  1071. }
  1072. public class GenericPropertyWithNullable<T>
  1073. {
  1074. public T TheType { get; set; }
  1075. }
  1076. public class GenericProperty<T>
  1077. {
  1078. public GenericProperty(T value)
  1079. {
  1080. ReadOnlyBlob = value;
  1081. }
  1082. public T ReadOnlyBlob { get; }
  1083. public string WhatEver { get; set; }
  1084. }
  1085. public class MessageWithDictionaryWithAnObjectAsKey
  1086. {
  1087. public Dictionary<object, string> Content { get; set; }
  1088. }
  1089. public class MessageWithDictionaryWithAnObjectAsValue
  1090. {
  1091. public Dictionary<string, object> Content { get; set; }
  1092. }
  1093. public class MessageWithListItem
  1094. {
  1095. public string Data { get; set; }
  1096. }
  1097. public class MessageWithInvalidCharacter : IMessage
  1098. {
  1099. public string Special { get; set; }
  1100. }
  1101. public class MessageWithList : IMessage
  1102. {
  1103. public List<MessageWithListItem> Items { get; set; }
  1104. }
  1105. public class MessageWithHashtable : IMessage
  1106. {
  1107. public Hashtable Hashtable { get; set; }
  1108. }
  1109. public class MessageWithArrayList : IMessage
  1110. {
  1111. public ArrayList ArrayList { get; set; }
  1112. }
  1113. public class MessageWithClosedListInAlternateNamespace : IMessage
  1114. {
  1115. public AlternateItemList Items { get; set; }
  1116. }
  1117. public class MessageWithClosedListInAlternateNamespaceMultipleIEnumerableImplementations : IMessage
  1118. {
  1119. public AlternateItemListMultipleIEnumerableImplementations Items { get; set; }
  1120. }
  1121. public class MessageWithClosedListInAlternateNamespaceMultipleIListImplementations : IMessage
  1122. {
  1123. public AlternateItemListMultipleIListImplementations Items { get; set; }
  1124. }
  1125. public class MessageWithClosedList : IMessage
  1126. {
  1127. public ItemList Items { get; set; }
  1128. }
  1129. public class MessageWithXDocument : IMessage
  1130. {
  1131. public XDocument Document { get; set; }
  1132. }
  1133. public class MessageWithXElement : IMessage
  1134. {
  1135. public XElement Document { get; set; }
  1136. }
  1137. public class ItemList : List<MessageWithListItem>
  1138. {
  1139. }
  1140. public class CompositeMessage : IMyEventA, IMyEventB
  1141. {
  1142. public string StringValue { get; set; }
  1143. public int IntValue { get; set; }
  1144. }
  1145. public interface IMyEventA
  1146. {
  1147. string StringValue { get; set; }
  1148. }
  1149. public class MyEventA_impl : IMyEventA
  1150. {
  1151. public string StringValue { get; set; }
  1152. }
  1153. public interface IMyEventB
  1154. {
  1155. int IntValue { get; set; }
  1156. }
  1157. public class MyEventB_impl : IMyEventB
  1158. {
  1159. public int IntValue { get; set; }
  1160. }
  1161. }
  1162. namespace NServiceBus.Serializers.XML.Test.AlternateNamespace
  1163. {
  1164. using System.Collections.Generic;
  1165. using System.Linq;
  1166. using System.Runtime.Serialization;
  1167. public class AlternateItemList : List<MessageWithListItemAlternate>
  1168. {
  1169. }
  1170. public class MessageWithListItemAlternate
  1171. {
  1172. public string Data { get; set; }
  1173. }
  1174. public class AlternateItemListMultipleIEnumerableImplementations : List<MessageWithListItemAlternate>, IEnumerable<string>
  1175. {
  1176. public new IEnumerator<string> GetEnumerator()
  1177. {
  1178. return ToArray().Select(item => item.Data).GetEnumerator();
  1179. }
  1180. }
  1181. public class AlternateItemListMultipleIListImplementations : List<MessageWithListItemAlternate>, IList<string>
  1182. {
  1183. IEnumerator<string> IEnumerable<string>.GetEnumerator()
  1184. {
  1185. return stringList.GetEnumerator();
  1186. }
  1187. void ICollection<string>.Add(string item)
  1188. {
  1189. stringList.Add(item);
  1190. }
  1191. bool ICollection<string>.Contains(string item)
  1192. {
  1193. return stringList.Contains(item);
  1194. }
  1195. void ICollection<string>.CopyTo(string[] arra

Large files files are truncated, but you can click here to view the full file