[bcl] Default XmlSerializer stream serialize to UTF8 Encoding (#18836)
[mono-project.git] / mcs / class / System.XML / Test / System.Xml.Serialization / XmlSerializerTests.cs
blobe87df12964ebbe4b45e60398986fcbf43bc75ef1
1 //
2 // System.Xml.XmlSerializerTests
3 //
4 // Author:
5 // Erik LeBel <eriklebel@yahoo.ca>
6 // Hagit Yidov <hagity@mainsoft.com>
7 //
8 // (C) 2003 Erik LeBel
9 // (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
12 // NOTES:
13 // Where possible, these tests avoid testing the order of
14 // an object's members serialization. Mono and .NET do not
15 // reflect members in the same order.
17 // Only serializations tests so far, no deserialization.
19 // FIXME
20 // test XmlArrayAttribute
21 // test XmlArrayItemAttribute
22 // test serialization of decimal type
23 // test serialization of Guid type
24 // test XmlNode serialization with and without modifying attributes.
25 // test deserialization
26 // FIXMEs found in this file
28 using System;
29 using System.Collections;
30 using System.Globalization;
31 using System.IO;
32 using System.Text;
33 using System.Xml;
34 using System.Data;
35 using System.Xml.Schema;
36 using System.Xml.Serialization;
37 using System.Reflection;
38 using System.Collections.Generic;
40 using NUnit.Framework;
42 using MonoTests.System.Xml.TestClasses;
44 namespace MonoTests.System.XmlSerialization
46 [TestFixture]
47 public class XmlSerializerTests
49 const string SoapEncodingNamespace = "http://schemas.xmlsoap.org/soap/encoding/";
50 const string WsdlTypesNamespace = "http://microsoft.com/wsdl/types/";
51 const string ANamespace = "some:urn";
52 const string AnotherNamespace = "another:urn";
54 StringWriter sw;
55 XmlTextWriter xtw;
56 XmlSerializer xs;
58 private void SetUpWriter ()
60 sw = new StringWriter ();
61 xtw = new XmlTextWriter (sw);
62 xtw.QuoteChar = '\'';
63 xtw.Formatting = Formatting.None;
66 private string WriterText
68 get
70 string val = sw.GetStringBuilder ().ToString ();
71 int offset = val.IndexOf ('>') + 1;
72 val = val.Substring (offset);
73 return Infoset (val);
77 private void Serialize (object o)
79 SetUpWriter ();
80 xs = new XmlSerializer (o.GetType ());
81 xs.Serialize (xtw, o);
84 private void Serialize (object o, Type type)
86 SetUpWriter ();
87 xs = new XmlSerializer (type);
88 xs.Serialize (xtw, o);
91 private void Serialize (object o, XmlSerializerNamespaces ns)
93 SetUpWriter ();
94 xs = new XmlSerializer (o.GetType ());
95 xs.Serialize (xtw, o, ns);
98 private void Serialize (object o, XmlAttributeOverrides ao)
100 SetUpWriter ();
101 xs = new XmlSerializer (o.GetType (), ao);
102 xs.Serialize (xtw, o);
105 private void Serialize (object o, XmlAttributeOverrides ao, string defaultNamespace)
107 SetUpWriter ();
108 xs = new XmlSerializer (o.GetType (), ao, Type.EmptyTypes,
109 (XmlRootAttribute) null, defaultNamespace);
110 xs.Serialize (xtw, o);
113 private void Serialize (object o, XmlRootAttribute root)
115 SetUpWriter ();
116 xs = new XmlSerializer (o.GetType (), root);
117 xs.Serialize (xtw, o);
120 private void Serialize (object o, XmlTypeMapping typeMapping)
122 SetUpWriter ();
123 xs = new XmlSerializer (typeMapping);
124 xs.Serialize (xtw, o);
127 private void SerializeEncoded (object o)
129 SerializeEncoded (o, o.GetType ());
132 private void SerializeEncoded (object o, SoapAttributeOverrides ao)
134 XmlTypeMapping mapping = CreateSoapMapping (o.GetType (), ao);
135 SetUpWriter ();
136 xs = new XmlSerializer (mapping);
137 xs.Serialize (xtw, o);
140 private void SerializeEncoded (object o, SoapAttributeOverrides ao, string defaultNamespace)
142 XmlTypeMapping mapping = CreateSoapMapping (o.GetType (), ao, defaultNamespace);
143 SetUpWriter ();
144 xs = new XmlSerializer (mapping);
145 xs.Serialize (xtw, o);
148 private void SerializeEncoded (object o, Type type)
150 XmlTypeMapping mapping = CreateSoapMapping (type);
151 SetUpWriter ();
152 xs = new XmlSerializer (mapping);
153 xs.Serialize (xtw, o);
156 private void SerializeEncoded (XmlTextWriter xtw, object o, Type type)
158 XmlTypeMapping mapping = CreateSoapMapping (type);
159 xs = new XmlSerializer (mapping);
160 xs.Serialize (xtw, o);
163 // test constructors
164 [Test]
165 [ExpectedException (typeof (ArgumentNullException))]
166 public void TestConstructor()
168 XmlSerializer ser = new XmlSerializer (null, "");
171 // test basic types ////////////////////////////////////////////////////////
172 [Test]
173 public void TestSerializeInt ()
175 Serialize (10);
176 Assert.AreEqual (Infoset ("<int>10</int>"), WriterText);
179 [Test]
180 public void TestSerializeBool ()
182 Serialize (true);
183 Assert.AreEqual (Infoset ("<boolean>true</boolean>"), WriterText);
185 Serialize (false);
186 Assert.AreEqual (Infoset ("<boolean>false</boolean>"), WriterText);
189 [Test]
190 public void TestSerializeString ()
192 Serialize ("hello");
193 Assert.AreEqual (Infoset ("<string>hello</string>"), WriterText);
196 [Test]
197 public void TestSerializeEmptyString ()
199 Serialize (String.Empty);
200 Assert.AreEqual (Infoset ("<string />"), WriterText);
203 [Test]
204 public void TestSerializeNullObject ()
206 Serialize (null, typeof (object));
207 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
208 "<anyType xmlns:xsd='{0}' xmlns:xsi='{1}' xsi:nil='true' />",
209 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
212 [Test]
213 [Ignore ("The generated XML is not exact but it is equivalent")]
214 public void TestSerializeNullString ()
216 Serialize (null, typeof (string));
217 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
218 "<string xmlns:xsd='{0}' xmlns:xsi='{1}' xsi:nil='true' />",
219 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
222 [Test]
223 public void TestSerializeIntArray ()
225 Serialize (new int[] { 1, 2, 3, 4 });
226 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
227 "<ArrayOfInt xmlns:xsd='{0}' xmlns:xsi='{1}'><int>1</int><int>2</int><int>3</int><int>4</int></ArrayOfInt>",
228 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
231 [Test]
232 public void TestSerializeEmptyArray ()
234 Serialize (new int[] { });
235 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
236 "<ArrayOfInt xmlns:xsd='{0}' xmlns:xsi='{1}' />",
237 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
240 [Test]
241 public void TestSerializeChar ()
243 Serialize ('A');
244 Assert.AreEqual (Infoset ("<char>65</char>"), WriterText);
246 Serialize ('\0');
247 Assert.AreEqual (Infoset ("<char>0</char>"), WriterText);
249 Serialize ('\n');
250 Assert.AreEqual (Infoset ("<char>10</char>"), WriterText);
252 Serialize ('\uFF01');
253 Assert.AreEqual (Infoset ("<char>65281</char>"), WriterText);
256 [Test]
257 public void TestSerializeFloat ()
259 Serialize (10.78);
260 Assert.AreEqual (Infoset ("<double>10.78</double>"), WriterText);
262 Serialize (-1e8);
263 Assert.AreEqual (Infoset ("<double>-100000000</double>"), WriterText);
265 // FIXME test INF and other boundary conditions that may exist with floats
268 [Test]
269 public void TestSerializeEnumeration_FromValue ()
271 Serialize ((int) SimpleEnumeration.SECOND, typeof (SimpleEnumeration));
272 Assert.AreEqual (
273 "<?xml version='1.0' encoding='utf-16'?>" +
274 "<SimpleEnumeration>SECOND</SimpleEnumeration>",
275 sw.ToString ());
278 [Test]
279 [Category ("MobileNotWorking")]
280 public void TestSerializeEnumeration_FromValue_Encoded ()
282 SerializeEncoded ((int) SimpleEnumeration.SECOND, typeof (SimpleEnumeration));
283 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
284 "<?xml version='1.0' encoding='utf-16'?>" +
285 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>SECOND</SimpleEnumeration>",
286 XmlSchema.InstanceNamespace), sw.ToString ());
289 [Test]
290 public void TestSerializeEnumeration ()
292 Serialize (SimpleEnumeration.FIRST);
293 Assert.AreEqual (Infoset ("<SimpleEnumeration>FIRST</SimpleEnumeration>"), WriterText, "#1");
295 Serialize (SimpleEnumeration.SECOND);
296 Assert.AreEqual (Infoset ("<SimpleEnumeration>SECOND</SimpleEnumeration>"), WriterText, "#2");
299 [Test]
300 public void TestSerializeEnumeration_Encoded ()
302 SerializeEncoded (SimpleEnumeration.FIRST);
303 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
304 "<?xml version='1.0' encoding='utf-16'?>" +
305 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>FIRST</SimpleEnumeration>",
306 XmlSchema.InstanceNamespace), sw.ToString (), "#B1");
308 SerializeEncoded (SimpleEnumeration.SECOND);
309 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
310 "<?xml version='1.0' encoding='utf-16'?>" +
311 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>SECOND</SimpleEnumeration>",
312 XmlSchema.InstanceNamespace), sw.ToString (), "#B2");
315 [Test]
316 public void TestSerializeEnumDefaultValue ()
318 Serialize (new EnumDefaultValue ());
319 Assert.AreEqual (Infoset ("<EnumDefaultValue />"), WriterText, "#1");
321 Serialize (new SimpleEnumeration ());
322 Assert.AreEqual (Infoset ("<SimpleEnumeration>FIRST</SimpleEnumeration>"), WriterText, "#2");
324 Serialize (3, typeof (EnumDefaultValue));
325 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#3");
327 Serialize (EnumDefaultValue.e3, typeof (EnumDefaultValue));
328 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#4");
330 Serialize (EnumDefaultValue.e1 | EnumDefaultValue.e2, typeof (EnumDefaultValue));
331 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#5");
333 Serialize (EnumDefaultValue.e1 | EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
334 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#6");
336 Serialize (EnumDefaultValue.e1 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
337 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#7");
339 Serialize (EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
340 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#8");
342 Serialize (3, typeof (FlagEnum));
343 Assert.AreEqual (Infoset ("<FlagEnum>one two</FlagEnum>"), WriterText, "#9");
345 Serialize (5, typeof (FlagEnum));
346 Assert.AreEqual (Infoset ("<FlagEnum>one four</FlagEnum>"), WriterText, "#10");
348 Serialize (FlagEnum.e4, typeof (FlagEnum));
349 Assert.AreEqual (Infoset ("<FlagEnum>four</FlagEnum>"), WriterText, "#11");
351 Serialize (FlagEnum.e1 | FlagEnum.e2, typeof (FlagEnum));
352 Assert.AreEqual (Infoset ("<FlagEnum>one two</FlagEnum>"), WriterText, "#12");
354 Serialize (FlagEnum.e1 | FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
355 Assert.AreEqual (Infoset ("<FlagEnum>one two four</FlagEnum>"), WriterText, "#13");
357 Serialize (FlagEnum.e1 | FlagEnum.e4, typeof (FlagEnum));
358 Assert.AreEqual (Infoset ("<FlagEnum>one four</FlagEnum>"), WriterText, "#14");
360 Serialize (FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
361 Assert.AreEqual (Infoset ("<FlagEnum>two four</FlagEnum>"), WriterText, "#15");
363 Serialize (3, typeof (EnumDefaultValueNF));
364 Assert.AreEqual (Infoset ("<EnumDefaultValueNF>e3</EnumDefaultValueNF>"), WriterText, "#16");
366 Serialize (EnumDefaultValueNF.e2, typeof (EnumDefaultValueNF));
367 Assert.AreEqual (Infoset ("<EnumDefaultValueNF>e2</EnumDefaultValueNF>"), WriterText, "#17");
369 Serialize (2, typeof (ZeroFlagEnum));
370 Assert.AreEqual (Infoset ("<ZeroFlagEnum>tns:t&lt;w&gt;o</ZeroFlagEnum>"), WriterText, "#18");
372 Serialize (new ZeroFlagEnum ()); // enum actually has a field with value 0
373 Assert.AreEqual (Infoset ("<ZeroFlagEnum>zero</ZeroFlagEnum>"), WriterText, "#19");
376 [Test]
377 [Category ("MobileNotWorking")]
378 public void TestSerializeEnumDefaultValue_Encoded ()
380 SerializeEncoded (new EnumDefaultValue ());
381 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
382 "<?xml version='1.0' encoding='utf-16'?>" +
383 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}' />",
384 XmlSchema.InstanceNamespace), sw.ToString (), "#1");
386 SerializeEncoded (new SimpleEnumeration ());
387 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
388 "<?xml version='1.0' encoding='utf-16'?>" +
389 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>FIRST</SimpleEnumeration>",
390 XmlSchema.InstanceNamespace), sw.ToString (), "#2");
392 SerializeEncoded (3, typeof (EnumDefaultValue));
393 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
394 "<?xml version='1.0' encoding='utf-16'?>" +
395 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
396 XmlSchema.InstanceNamespace), sw.ToString (), "#3");
398 SerializeEncoded (EnumDefaultValue.e3, typeof (EnumDefaultValue));
399 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
400 "<?xml version='1.0' encoding='utf-16'?>" +
401 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
402 XmlSchema.InstanceNamespace), sw.ToString (), "#4");
404 SerializeEncoded (EnumDefaultValue.e1 | EnumDefaultValue.e2, typeof (EnumDefaultValue));
405 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
406 "<?xml version='1.0' encoding='utf-16'?>" +
407 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
408 XmlSchema.InstanceNamespace), sw.ToString (), "#5");
410 SerializeEncoded (EnumDefaultValue.e1 | EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
411 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
412 "<?xml version='1.0' encoding='utf-16'?>" +
413 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
414 XmlSchema.InstanceNamespace), sw.ToString (), "#6");
416 SerializeEncoded (EnumDefaultValue.e1 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
417 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
418 "<?xml version='1.0' encoding='utf-16'?>" +
419 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
420 XmlSchema.InstanceNamespace), sw.ToString (), "#7");
422 SerializeEncoded (EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
423 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
424 "<?xml version='1.0' encoding='utf-16'?>" +
425 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
426 XmlSchema.InstanceNamespace), sw.ToString (), "#8");
428 SerializeEncoded (3, typeof (FlagEnum));
429 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
430 "<?xml version='1.0' encoding='utf-16'?>" +
431 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e2</FlagEnum>",
432 XmlSchema.InstanceNamespace), sw.ToString (), "#9");
434 SerializeEncoded (5, typeof (FlagEnum));
435 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
436 "<?xml version='1.0' encoding='utf-16'?>" +
437 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e4</FlagEnum>",
438 XmlSchema.InstanceNamespace), sw.ToString (), "#10");
440 SerializeEncoded (FlagEnum.e4, typeof (FlagEnum));
441 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
442 "<?xml version='1.0' encoding='utf-16'?>" +
443 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e4</FlagEnum>",
444 XmlSchema.InstanceNamespace), sw.ToString (), "#11");
446 SerializeEncoded (FlagEnum.e1 | FlagEnum.e2, typeof (FlagEnum));
447 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
448 "<?xml version='1.0' encoding='utf-16'?>" +
449 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e2</FlagEnum>",
450 XmlSchema.InstanceNamespace), sw.ToString (), "#12");
452 SerializeEncoded (FlagEnum.e1 | FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
453 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
454 "<?xml version='1.0' encoding='utf-16'?>" +
455 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e2 e4</FlagEnum>",
456 XmlSchema.InstanceNamespace), sw.ToString (), "#13");
458 SerializeEncoded (FlagEnum.e1 | FlagEnum.e4, typeof (FlagEnum));
459 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
460 "<?xml version='1.0' encoding='utf-16'?>" +
461 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e4</FlagEnum>",
462 XmlSchema.InstanceNamespace), sw.ToString (), "#14");
464 SerializeEncoded (FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
465 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
466 "<?xml version='1.0' encoding='utf-16'?>" +
467 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e2 e4</FlagEnum>",
468 XmlSchema.InstanceNamespace), sw.ToString (), "#15");
470 SerializeEncoded (3, typeof (EnumDefaultValueNF));
471 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
472 "<?xml version='1.0' encoding='utf-16'?>" +
473 "<EnumDefaultValueNF d1p1:type='EnumDefaultValueNF' xmlns:d1p1='{0}'>e3</EnumDefaultValueNF>",
474 XmlSchema.InstanceNamespace), sw.ToString (), "#16");
476 SerializeEncoded (EnumDefaultValueNF.e2, typeof (EnumDefaultValueNF));
477 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
478 "<?xml version='1.0' encoding='utf-16'?>" +
479 "<EnumDefaultValueNF d1p1:type='EnumDefaultValueNF' xmlns:d1p1='{0}'>e2</EnumDefaultValueNF>",
480 XmlSchema.InstanceNamespace), sw.ToString (), "#17");
482 SerializeEncoded (2, typeof (ZeroFlagEnum));
483 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
484 "<?xml version='1.0' encoding='utf-16'?>" +
485 "<ZeroFlagEnum d1p1:type='ZeroFlagEnum' xmlns:d1p1='{0}'>e2</ZeroFlagEnum>",
486 XmlSchema.InstanceNamespace), sw.ToString (), "#18");
488 SerializeEncoded (new ZeroFlagEnum ()); // enum actually has a field with value 0
489 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
490 "<?xml version='1.0' encoding='utf-16'?>" +
491 "<ZeroFlagEnum d1p1:type='ZeroFlagEnum' xmlns:d1p1='{0}'>e0</ZeroFlagEnum>",
492 XmlSchema.InstanceNamespace), sw.ToString (), "#19");
495 [Test]
496 public void TestSerializeEnumDefaultValue_InvalidValue1 ()
498 try {
499 Serialize ("b", typeof (EnumDefaultValue));
500 Assert.Fail ("#A1");
501 } catch (InvalidOperationException ex) {
502 Assert.IsNotNull (ex.InnerException, "#A2");
503 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#A3");
506 try {
507 Serialize ("e1", typeof (EnumDefaultValue));
508 Assert.Fail ("#B1");
509 } catch (InvalidOperationException ex) {
510 Assert.IsNotNull (ex.InnerException, "#B2");
511 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#B3");
514 try {
515 Serialize ("e1,e2", typeof (EnumDefaultValue));
516 Assert.Fail ("#C1");
517 } catch (InvalidOperationException ex) {
518 Assert.IsNotNull (ex.InnerException, "#C2");
519 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#C3");
522 try {
523 Serialize (string.Empty, typeof (EnumDefaultValue));
524 Assert.Fail ("#D1");
525 } catch (InvalidOperationException ex) {
526 Assert.IsNotNull (ex.InnerException, "#D2");
527 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#D3");
530 try {
531 Serialize ("1", typeof (EnumDefaultValue));
532 Assert.Fail ("#E1");
533 } catch (InvalidOperationException ex) {
534 Assert.IsNotNull (ex.InnerException, "#E2");
535 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#E3");
538 try {
539 Serialize ("0", typeof (EnumDefaultValue));
540 Assert.Fail ("#F1");
541 } catch (InvalidOperationException ex) {
542 Assert.IsNotNull (ex.InnerException, "#F2");
543 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#F3");
546 try {
547 Serialize (new SimpleClass (), typeof (EnumDefaultValue));
548 Assert.Fail ("#G1");
549 } catch (InvalidOperationException ex) {
550 Assert.IsNotNull (ex.InnerException, "#G2");
551 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#G3");
555 [Test]
556 public void TestSerializeEnumDefaultValue_InvalidValue2 ()
558 try {
559 Serialize (5, typeof (EnumDefaultValue));
560 Assert.Fail ("#1");
561 } catch (InvalidOperationException ex) {
562 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
563 Assert.IsNotNull (ex.InnerException, "#3");
564 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
565 Assert.IsNotNull (ex.InnerException.Message, "#5");
566 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'5'") != -1, "#6");
567 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (EnumDefaultValue).FullName) != -1, "#7");
571 [Test]
572 public void TestSerializeEnumDefaultValueNF_InvalidValue1 ()
574 try {
575 Serialize (new EnumDefaultValueNF ());
576 Assert.Fail ("#1");
577 } catch (InvalidOperationException ex) {
578 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
579 Assert.IsNotNull (ex.InnerException, "#3");
580 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
581 Assert.IsNotNull (ex.InnerException.Message, "#5");
582 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'0'") != -1, "#6");
583 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (EnumDefaultValueNF).FullName) != -1, "#7");
587 [Test]
588 public void TestSerializeEnumDefaultValueNF_InvalidValue2 ()
590 try {
591 Serialize (15, typeof (EnumDefaultValueNF));
592 Assert.Fail ("#1");
593 } catch (InvalidOperationException ex) {
594 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
595 Assert.IsNotNull (ex.InnerException, "#3");
596 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
597 Assert.IsNotNull (ex.InnerException.Message, "#5");
598 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'15'") != -1, "#6");
599 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (EnumDefaultValueNF).FullName) != -1, "#7");
603 [Test]
604 public void TestSerializeEnumDefaultValueNF_InvalidValue3 ()
606 try {
607 Serialize ("b", typeof (EnumDefaultValueNF));
608 Assert.Fail ("#A1");
609 } catch (InvalidOperationException ex) {
610 Assert.IsNotNull (ex.InnerException, "#A2");
611 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#A3");
614 try {
615 Serialize ("e2", typeof (EnumDefaultValueNF));
616 Assert.Fail ("#B1");
617 } catch (InvalidOperationException ex) {
618 Assert.IsNotNull (ex.InnerException, "#B2");
619 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#B3");
622 try {
623 Serialize (string.Empty, typeof (EnumDefaultValueNF));
624 Assert.Fail ("#C1");
625 } catch (InvalidOperationException ex) {
626 Assert.IsNotNull (ex.InnerException, "#C2");
627 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#C3");
630 try {
631 Serialize ("1", typeof (EnumDefaultValueNF));
632 Assert.Fail ("#D1");
633 } catch (InvalidOperationException ex) {
634 Assert.IsNotNull (ex.InnerException, "#D2");
635 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#D3");
638 try {
639 Serialize ("0", typeof (EnumDefaultValueNF));
640 Assert.Fail ("#E1");
641 } catch (InvalidOperationException ex) {
642 Assert.IsNotNull (ex.InnerException, "#E2");
643 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#E3");
647 [Test]
648 public void TestSerializeField ()
650 Field f = new Field ();
651 Serialize (f, typeof (Field));
652 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
653 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag1='' flag2='' flag3=''" +
654 " flag4='' modifiers='public' modifiers2='public' modifiers4='public' />",
655 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#A");
657 f.Flags1 = FlagEnum.e1;
658 f.Flags2 = FlagEnum.e1;
659 f.Flags3 = FlagEnum.e2;
660 f.Modifiers = MapModifiers.Protected;
661 f.Modifiers2 = MapModifiers.Public;
662 f.Modifiers3 = MapModifiers.Public;
663 f.Modifiers4 = MapModifiers.Protected;
664 f.Modifiers5 = MapModifiers.Public;
665 Serialize (f, typeof (Field));
666 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
667 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag3='two' flag4=''" +
668 " modifiers='protected' modifiers2='public' />",
669 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#B");
671 f.Flags1 = (FlagEnum) 1;
672 f.Flags1 = FlagEnum.e2;
673 f.Flags2 = FlagEnum.e2;
674 f.Flags3 = FlagEnum.e1 | FlagEnum.e2;
675 f.Modifiers = MapModifiers.Public;
676 f.Modifiers2 = MapModifiers.Protected;
677 f.Modifiers3 = MapModifiers.Protected;
678 f.Modifiers4 = MapModifiers.Public;
679 f.Modifiers5 = MapModifiers.Protected;
680 Serialize (f, typeof (Field));
681 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
682 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag1='two' flag2='two'" +
683 " flag4='' modifiers='public' modifiers2='protected'" +
684 " modifiers3='protected' modifiers4='public'" +
685 " modifiers5='protected' />",
686 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#C");
688 f.Flags1 = FlagEnum.e1 | FlagEnum.e2;
689 f.Flags2 = FlagEnum.e2;
690 f.Flags3 = FlagEnum.e4;
691 f.Flags4 = FlagEnum.e1 | FlagEnum.e2 | FlagEnum.e4;
692 f.Modifiers3 = MapModifiers.Public;
693 f.Modifiers4 = MapModifiers.Protected;
694 f.Modifiers5 = MapModifiers.Public;
695 f.Names = new string[] { "a", "b" };
696 Serialize (f, typeof (Field));
697 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
698 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag1='one two' flag2='two'" +
699 " flag3='four' flag4='one two four' modifiers='public'" +
700 " modifiers2='protected' names='a b' />",
701 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#D");
703 f.Flags2 = (FlagEnum) 444;
704 f.Flags3 = (FlagEnum) 555;
705 f.Modifiers = (MapModifiers) 666;
706 f.Modifiers2 = (MapModifiers) 777;
707 f.Modifiers3 = (MapModifiers) 0;
708 f.Modifiers4 = (MapModifiers) 888;
709 f.Modifiers5 = (MapModifiers) 999;
710 try {
711 Serialize (f, typeof (Field));
712 Assert.Fail ("#E1");
713 } catch (InvalidOperationException ex) {
714 // There was an error generating the XML document
715 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");
716 Assert.IsNotNull (ex.Message, "#E3");
717 Assert.IsNotNull (ex.InnerException, "#E4");
719 // Instance validation error: '444' is not a valid value for
720 // MonoTests.System.Xml.TestClasses.FlagEnum
721 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#E5");
722 Assert.IsNotNull (ex.InnerException.Message, "#E6");
723 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'444'") != -1, "#E7");
724 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (FlagEnum).FullName) != -1, "#E8");
725 Assert.IsNull (ex.InnerException.InnerException, "#E9");
729 [Test]
730 [Category ("NotWorking")] // MS bug
731 public void TestSerializeField_Encoded ()
733 Field_Encoded f = new Field_Encoded ();
734 SerializeEncoded (f, typeof (Field_Encoded));
735 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
736 "<?xml version='1.0' encoding='utf-16'?>" +
737 "<q1:field xmlns:xsd='{0}' xmlns:xsi='{1}' id='id1' flag1=''" +
738 " flag2='' flag3='' flag4='' modifiers='PuBlIc'" +
739 " modifiers2='PuBlIc' modifiers4='PuBlIc' xmlns:q1='some:urn' />",
740 XmlSchema.Namespace, XmlSchema.InstanceNamespace),
741 sw.GetStringBuilder ().ToString (), "#A");
743 f.Flags1 = FlagEnum_Encoded.e1;
744 f.Flags2 = FlagEnum_Encoded.e1;
745 f.Flags3 = FlagEnum_Encoded.e2;
746 f.Modifiers = MapModifiers.Protected;
747 f.Modifiers2 = MapModifiers.Public;
748 f.Modifiers3 = MapModifiers.Public;
749 f.Modifiers4 = MapModifiers.Protected;
750 f.Modifiers5 = MapModifiers.Public;
751 SerializeEncoded (f, typeof (Field_Encoded));
752 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
753 "<?xml version='1.0' encoding='utf-16'?>" +
754 "<q1:field xmlns:xsd='{0}' xmlns:xsi='{1}' id='id1' flag3='two'" +
755 " flag4='' modifiers='Protected' modifiers2='PuBlIc'" +
756 " xmlns:q1='some:urn' />",
757 XmlSchema.Namespace, XmlSchema.InstanceNamespace),
758 sw.GetStringBuilder ().ToString (), "#B");
760 f.Flags1 = FlagEnum_Encoded.e2;
761 f.Flags2 = FlagEnum_Encoded.e2;
762 f.Flags3 = FlagEnum_Encoded.e1 | FlagEnum_Encoded.e2;
763 f.Modifiers = MapModifiers.Public;
764 f.Modifiers2 = MapModifiers.Protected;
765 f.Modifiers3 = MapModifiers.Protected;
766 f.Modifiers4 = MapModifiers.Public;
767 f.Modifiers5 = MapModifiers.Protected;
768 SerializeEncoded (f, typeof (Field_Encoded));
769 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
770 "<?xml version='1.0' encoding='utf-16'?>" +
771 "<q1:field xmlns:xsd='{0}' xmlns:xsi='{1}' id='id1' flag1='two'" +
772 " flag2='two' flag4='' modifiers='PuBlIc' modifiers2='Protected'" +
773 " modifiers3='Protected' modifiers4='PuBlIc' modifiers5='Protected'" +
774 " xmlns:q1='some:urn' />",
775 XmlSchema.Namespace, XmlSchema.InstanceNamespace),
776 sw.GetStringBuilder ().ToString (), "#C");
778 f.Flags1 = (FlagEnum_Encoded) 1;
779 f.Flags2 = (FlagEnum_Encoded) 444;
780 f.Flags3 = (FlagEnum_Encoded) 555;
781 f.Modifiers = (MapModifiers) 666;
782 f.Modifiers2 = (MapModifiers) 777;
783 f.Modifiers3 = (MapModifiers) 0;
784 f.Modifiers4 = (MapModifiers) 888;
785 f.Modifiers5 = (MapModifiers) 999;
786 try {
787 SerializeEncoded (f, typeof (Field_Encoded));
788 Assert.Fail ("#D1");
789 } catch (InvalidOperationException ex) {
790 // There was an error generating the XML document
791 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");
792 Assert.IsNotNull (ex.Message, "#D3");
793 Assert.IsNotNull (ex.InnerException, "#D4");
795 // Instance validation error: '444' is not a valid value for
796 // MonoTests.System.Xml.TestClasses.FlagEnum_Encoded
797 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#D5");
798 Assert.IsNotNull (ex.InnerException.Message, "#D6");
799 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'444'") != -1, "#D7");
800 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (FlagEnum_Encoded).FullName) != -1, "#D8");
801 Assert.IsNull (ex.InnerException.InnerException, "#D9");
805 [Test]
806 public void TestSerializeGroup ()
808 Group myGroup = new Group ();
809 myGroup.GroupName = ".NET";
811 Byte[] hexByte = new Byte[] { 0x64, 0x32 };
812 myGroup.GroupNumber = hexByte;
814 DateTime myDate = new DateTime (2002, 5, 2);
815 myGroup.Today = myDate;
816 myGroup.PostitiveInt = "10000";
817 myGroup.IgnoreThis = true;
818 Car thisCar = (Car) myGroup.myCar ("1234566");
819 myGroup.MyVehicle = thisCar;
821 SetUpWriter ();
822 xtw.WriteStartDocument (true);
823 xtw.WriteStartElement ("Wrapper");
824 SerializeEncoded (xtw, myGroup, typeof (Group));
825 xtw.WriteEndElement ();
826 xtw.Close ();
828 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
829 "<Wrapper>" +
830 "<Group xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns:d2p1='http://www.cpandl.com' CreationDate='2002-05-02' d2p1:GroupName='.NET' GroupNumber='ZDI=' id='id1'>" +
831 "<PosInt xsi:type='xsd:nonNegativeInteger'>10000</PosInt>" +
832 "<Grouptype xsi:type='GroupType'>Small</Grouptype>" +
833 "<MyVehicle href='#id2' />" +
834 "</Group>" +
835 "<Car xmlns:d2p1='{1}' id='id2' d2p1:type='Car'>" +
836 "<licenseNumber xmlns:q1='{0}' d2p1:type='q1:string'>1234566</licenseNumber>" +
837 "<makeDate xmlns:q2='{0}' d2p1:type='q2:date'>0001-01-01</makeDate>" +
838 "</Car>" +
839 "</Wrapper>",
840 XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
841 WriterText, "#1");
843 myGroup.GroupName = null;
844 myGroup.Grouptype = GroupType.B;
845 myGroup.MyVehicle.licenseNumber = null;
846 myGroup.MyVehicle.weight = "450";
848 SetUpWriter ();
849 xtw.WriteStartDocument (true);
850 xtw.WriteStartElement ("Wrapper");
851 SerializeEncoded (xtw, myGroup, typeof (Group));
852 xtw.WriteEndElement ();
853 xtw.Close ();
855 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
856 "<Wrapper>" +
857 "<Group xmlns:xsd='{0}' xmlns:xsi='{1}' CreationDate='2002-05-02' GroupNumber='ZDI=' id='id1'>" +
858 "<PosInt xsi:type='xsd:nonNegativeInteger'>10000</PosInt>" +
859 "<Grouptype xsi:type='GroupType'>Large</Grouptype>" +
860 "<MyVehicle href='#id2' />" +
861 "</Group>" +
862 "<Car xmlns:d2p1='{1}' id='id2' d2p1:type='Car'>" +
863 "<makeDate xmlns:q1='{0}' d2p1:type='q1:date'>0001-01-01</makeDate>" +
864 "<weight xmlns:q2='{0}' d2p1:type='q2:string'>450</weight>" +
865 "</Car>" +
866 "</Wrapper>",
867 XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
868 WriterText, "#2");
871 [Test]
872 public void TestSerializeZeroFlagEnum_InvalidValue ()
874 try {
875 Serialize (4, typeof (ZeroFlagEnum)); // corresponding enum field is marked XmlIgnore
876 Assert.Fail ("#1");
877 } catch (InvalidOperationException ex) {
878 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
879 Assert.IsNotNull (ex.InnerException, "#3");
880 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
881 Assert.IsNotNull (ex.InnerException.Message, "#5");
882 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'4'") != -1, "#6");
883 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (ZeroFlagEnum).FullName) != -1, "#7");
887 [Test]
888 public void TestSerializeQualifiedName ()
890 Serialize (new XmlQualifiedName ("me", "home.urn"));
891 Assert.AreEqual (Infoset ("<QName xmlns:q1='home.urn'>q1:me</QName>"), WriterText);
894 [Test]
895 public void TestSerializeBytes ()
897 Serialize ((byte) 0xAB);
898 Assert.AreEqual (Infoset ("<unsignedByte>171</unsignedByte>"), WriterText);
900 Serialize ((byte) 15);
901 Assert.AreEqual (Infoset ("<unsignedByte>15</unsignedByte>"), WriterText);
904 [Test]
905 public void TestSerializeByteArrays ()
907 Serialize (new byte[] { });
908 Assert.AreEqual (Infoset ("<base64Binary />"), WriterText);
910 Serialize (new byte[] { 0xAB, 0xCD });
911 Assert.AreEqual (Infoset ("<base64Binary>q80=</base64Binary>"), WriterText);
914 [Test]
915 public void TestSerializeDateTime ()
917 DateTime d = new DateTime ();
918 Serialize (d);
920 TimeZone tz = TimeZone.CurrentTimeZone;
921 TimeSpan off = tz.GetUtcOffset (d);
922 string sp = string.Format ("{0}{1:00}:{2:00}", off.Ticks >= 0 ? "+" : "", off.Hours, off.Minutes);
923 Assert.AreEqual (Infoset ("<dateTime>0001-01-01T00:00:00</dateTime>"), WriterText);
927 FIXME
928 - decimal
929 - Guid
930 - XmlNode objects
932 [Test]
933 public void TestSerialize()
935 Serialize();
936 Assert.AreEqual (WriterText, "");
940 // test basic class serialization /////////////////////////////////////
941 [Test]
942 public void TestSerializeSimpleClass ()
944 SimpleClass simple = new SimpleClass ();
945 Serialize (simple);
946 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
948 simple.something = "hello";
950 Serialize (simple);
951 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>hello</something></SimpleClass>"), WriterText);
954 [Test]
955 public void TestSerializeStringCollection ()
957 StringCollection strings = new StringCollection ();
958 Serialize (strings);
959 Assert.AreEqual (Infoset ("<ArrayOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
961 strings.Add ("hello");
962 strings.Add ("goodbye");
963 Serialize (strings);
964 Assert.AreEqual (Infoset ("<ArrayOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><string>hello</string><string>goodbye</string></ArrayOfString>"), WriterText);
967 [Test]
968 public void TestSerializeOptionalValueTypeContainer ()
970 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
971 XmlAttributes attr;
972 OptionalValueTypeContainer optionalValue = new OptionalValueTypeContainer ();
974 Serialize (optionalValue);
975 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
976 "<?xml version='1.0' encoding='utf-16'?>" +
977 "<optionalValue xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns='{2}' />",
978 XmlSchema.Namespace, XmlSchema.InstanceNamespace, AnotherNamespace),
979 sw.ToString (), "#1");
981 attr = new XmlAttributes ();
983 // remove the DefaultValue attribute on the Flags member
984 overrides.Add (typeof (OptionalValueTypeContainer), "Flags", attr);
985 // remove the DefaultValue attribute on the Attributes member
986 overrides.Add (typeof (OptionalValueTypeContainer), "Attributes", attr);
988 Serialize (optionalValue, overrides);
989 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
990 "<?xml version='1.0' encoding='utf-16'?>" +
991 "<optionalValue xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns='{2}'>" +
992 "<Attributes xmlns='{3}'>one four</Attributes>" +
993 "</optionalValue>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
994 AnotherNamespace, ANamespace), sw.ToString (), "#2");
996 optionalValue.FlagsSpecified = true;
997 Serialize (optionalValue, overrides);
998 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
999 "<?xml version='1.0' encoding='utf-16'?>" +
1000 "<optionalValue xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns='{2}'>" +
1001 "<Attributes xmlns='{3}'>one four</Attributes>" +
1002 "<Flags xmlns='{3}'>one</Flags>" +
1003 "</optionalValue>",
1004 XmlSchema.Namespace, XmlSchema.InstanceNamespace, AnotherNamespace,
1005 ANamespace), sw.ToString (), "#3");
1008 [Test]
1009 public void TestRoundTripSerializeOptionalValueTypeContainer ()
1011 var source = new OptionalValueTypeContainer ();
1012 source.IsEmpty = true;
1013 source.IsEmptySpecified = true;
1014 var ser = new XmlSerializer (typeof (OptionalValueTypeContainer));
1015 string xml;
1016 using (var t = new StringWriter ()) {
1017 ser.Serialize (t, source);
1018 xml = t.ToString();
1020 using (var s = new StringReader (xml)) {
1021 var obj = (OptionalValueTypeContainer) ser.Deserialize(s);
1022 Assert.AreEqual (source.IsEmpty, obj.IsEmpty, "#1");
1023 Assert.AreEqual (source.IsEmptySpecified, obj.IsEmptySpecified, "#2");
1027 [Test]
1028 public void TestSerializePlainContainer ()
1030 StringCollectionContainer container = new StringCollectionContainer ();
1031 Serialize (container);
1032 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Messages /></StringCollectionContainer>"), WriterText);
1034 container.Messages.Add ("hello");
1035 container.Messages.Add ("goodbye");
1036 Serialize (container);
1037 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Messages><string>hello</string><string>goodbye</string></Messages></StringCollectionContainer>"), WriterText);
1040 [Test]
1041 public void TestSerializeArrayContainer ()
1043 ArrayContainer container = new ArrayContainer ();
1044 Serialize (container);
1045 Assert.AreEqual (Infoset ("<ArrayContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1047 container.items = new object[] { 10, 20 };
1048 Serialize (container);
1049 Assert.AreEqual (Infoset ("<ArrayContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ><items><anyType xsi:type='xsd:int'>10</anyType><anyType xsi:type='xsd:int'>20</anyType></items></ArrayContainer>"), WriterText);
1051 container.items = new object[] { 10, "hello" };
1052 Serialize (container);
1053 Assert.AreEqual (Infoset ("<ArrayContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ><items><anyType xsi:type='xsd:int'>10</anyType><anyType xsi:type='xsd:string'>hello</anyType></items></ArrayContainer>"), WriterText);
1056 [Test]
1057 public void TestSerializeClassArrayContainer ()
1059 ClassArrayContainer container = new ClassArrayContainer ();
1060 Serialize (container);
1061 Assert.AreEqual (Infoset ("<ClassArrayContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1063 SimpleClass simple1 = new SimpleClass ();
1064 simple1.something = "hello";
1065 SimpleClass simple2 = new SimpleClass ();
1066 simple2.something = "hello";
1067 container.items = new SimpleClass[2];
1068 container.items[0] = simple1;
1069 container.items[1] = simple2;
1070 Serialize (container);
1071 Assert.AreEqual (Infoset ("<ClassArrayContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ><items><SimpleClass><something>hello</something></SimpleClass><SimpleClass><something>hello</something></SimpleClass></items></ClassArrayContainer>"), WriterText);
1074 // test basic attributes ///////////////////////////////////////////////
1075 [Test]
1076 public void TestSerializeSimpleClassWithXmlAttributes ()
1078 SimpleClassWithXmlAttributes simple = new SimpleClassWithXmlAttributes ();
1079 Serialize (simple);
1080 Assert.AreEqual (Infoset ("<simple xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1082 simple.something = "hello";
1083 Serialize (simple);
1084 Assert.AreEqual (Infoset ("<simple xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' member='hello' />"), WriterText);
1087 // test overrides ///////////////////////////////////////////////////////
1088 [Test]
1089 public void TestSerializeSimpleClassWithOverrides ()
1091 // Also tests XmlIgnore
1092 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1094 XmlAttributes attr = new XmlAttributes ();
1095 attr.XmlIgnore = true;
1096 overrides.Add (typeof (SimpleClassWithXmlAttributes), "something", attr);
1098 SimpleClassWithXmlAttributes simple = new SimpleClassWithXmlAttributes ();
1099 simple.something = "hello";
1100 Serialize (simple, overrides);
1101 Assert.AreEqual (Infoset ("<simple xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1104 [Test]
1105 public void TestSerializeSchema ()
1107 XmlSchema schema = new XmlSchema ();
1108 schema.Items.Add (new XmlSchemaAttribute ());
1109 schema.Items.Add (new XmlSchemaAttributeGroup ());
1110 schema.Items.Add (new XmlSchemaComplexType ());
1111 schema.Items.Add (new XmlSchemaNotation ());
1112 schema.Items.Add (new XmlSchemaSimpleType ());
1113 schema.Items.Add (new XmlSchemaGroup ());
1114 schema.Items.Add (new XmlSchemaElement ());
1116 StringWriter sw = new StringWriter ();
1117 XmlTextWriter xtw = new XmlTextWriter (sw);
1118 xtw.QuoteChar = '\'';
1119 xtw.Formatting = Formatting.Indented;
1120 XmlSerializer xs = new XmlSerializer (schema.GetType ());
1121 xs.Serialize (xtw, schema);
1123 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
1124 "<?xml version='1.0' encoding='utf-16'?>{0}" +
1125 "<xsd:schema xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>{0}" +
1126 " <xsd:attribute />{0}" +
1127 " <xsd:attributeGroup />{0}" +
1128 " <xsd:complexType />{0}" +
1129 " <xsd:notation />{0}" +
1130 " <xsd:simpleType />{0}" +
1131 " <xsd:group />{0}" +
1132 " <xsd:element />{0}" +
1133 "</xsd:schema>", Environment.NewLine), sw.ToString ());
1136 // test xmlText //////////////////////////////////////////////////////////
1137 [Test]
1138 public void TestSerializeXmlTextAttribute ()
1140 SimpleClass simple = new SimpleClass ();
1141 simple.something = "hello";
1143 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1144 XmlAttributes attr = new XmlAttributes ();
1145 overrides.Add (typeof (SimpleClass), "something", attr);
1147 attr.XmlText = new XmlTextAttribute ();
1148 Serialize (simple, overrides);
1149 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>hello</SimpleClass>"), WriterText, "#1");
1151 attr.XmlText = new XmlTextAttribute (typeof (string));
1152 Serialize (simple, overrides);
1153 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>hello</SimpleClass>"), WriterText, "#2");
1155 try {
1156 attr.XmlText = new XmlTextAttribute (typeof (byte[]));
1157 Serialize (simple, overrides);
1158 Assert.Fail ("#A1: XmlText.Type does not match the type it serializes: this should have failed");
1159 } catch (InvalidOperationException ex) {
1160 // there was an error reflecting type 'MonoTests.System.Xml.TestClasses.SimpleClass'
1161 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
1162 Assert.IsNotNull (ex.Message, "#A3");
1163 Assert.IsTrue (ex.Message.IndexOf (typeof (SimpleClass).FullName) != -1, "#A4");
1164 Assert.IsNotNull (ex.InnerException, "#A5");
1166 // there was an error reflecting field 'something'.
1167 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#A6");
1168 Assert.IsNotNull (ex.InnerException.Message, "#A7");
1169 Assert.IsTrue (ex.InnerException.Message.IndexOf ("something") != -1, "#A8");
1170 Assert.IsNotNull (ex.InnerException.InnerException, "#A9");
1172 // the type for XmlText may not be specified for primitive types.
1173 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.InnerException.GetType (), "#A10");
1174 Assert.IsNotNull (ex.InnerException.InnerException.Message, "#A11");
1175 Assert.IsNull (ex.InnerException.InnerException.InnerException, "#A12");
1178 try {
1179 attr.XmlText = new XmlTextAttribute ();
1180 attr.XmlText.DataType = "sometype";
1181 Serialize (simple, overrides);
1182 Assert.Fail ("#B1: XmlText.DataType does not match the type it serializes: this should have failed");
1183 } catch (InvalidOperationException ex) {
1184 // There was an error reflecting type 'MonoTests.System.Xml.TestClasses.SimpleClass'.
1185 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
1186 Assert.IsNotNull (ex.Message, "#B3");
1187 Assert.IsTrue (ex.Message.IndexOf (typeof (SimpleClass).FullName) != -1, "#B4");
1188 Assert.IsNotNull (ex.InnerException, "#B5");
1190 // There was an error reflecting field 'something'.
1191 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#B6");
1192 Assert.IsNotNull (ex.InnerException.Message, "#B7");
1193 Assert.IsTrue (ex.InnerException.Message.IndexOf ("something") != -1, "#B8");
1194 Assert.IsNotNull (ex.InnerException.InnerException, "#B9");
1196 //FIXME
1198 // There was an error reflecting type 'System.String'.
1199 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.InnerException.GetType (), "#B10");
1200 Assert.IsNotNull (ex.InnerException.InnerException.Message, "#B11");
1201 Assert.IsTrue (ex.InnerException.InnerException.Message.IndexOf (typeof (string).FullName) != -1, "#B12");
1202 Assert.IsNotNull (ex.InnerException.InnerException.InnerException, "#B13");
1204 // Value 'sometype' cannot be used for the XmlElementAttribute.DataType property.
1205 // The datatype 'http://www.w3.org/2001/XMLSchema:sometype' is missing.
1206 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.InnerException.InnerException.GetType (), "#B14");
1207 Assert.IsNotNull (ex.InnerException.InnerException.InnerException.Message, "#B15");
1208 Assert.IsTrue (ex.InnerException.InnerException.InnerException.Message.IndexOf ("http://www.w3.org/2001/XMLSchema:sometype") != -1, "#B16");
1209 Assert.IsNull (ex.InnerException.InnerException.InnerException.InnerException, "#B17");
1214 // test xmlRoot //////////////////////////////////////////////////////////
1215 [Test]
1216 public void TestSerializeXmlRootAttribute ()
1218 // constructor override & element name
1219 XmlRootAttribute root = new XmlRootAttribute ();
1220 root.ElementName = "renamed";
1222 SimpleClassWithXmlAttributes simpleWithAttributes = new SimpleClassWithXmlAttributes ();
1223 Serialize (simpleWithAttributes, root);
1224 Assert.AreEqual (Infoset ("<renamed xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1226 SimpleClass simple = null;
1227 root.IsNullable = false;
1228 try {
1229 Serialize (simple, root);
1230 Assert.Fail ("Cannot serialize null object if XmlRoot's IsNullable == false");
1231 } catch (NullReferenceException) {
1234 root.IsNullable = true;
1235 try {
1236 Serialize (simple, root);
1237 Assert.Fail ("Cannot serialize null object if XmlRoot's IsNullable == true");
1238 } catch (NullReferenceException) {
1241 simple = new SimpleClass ();
1242 root.ElementName = null;
1243 root.Namespace = "some.urn";
1244 Serialize (simple, root);
1245 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='some.urn' />"), WriterText);
1248 [Test]
1249 public void TestSerializeXmlRootAttributeOnMember ()
1251 // nested root
1252 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1253 XmlAttributes childAttr = new XmlAttributes ();
1254 childAttr.XmlRoot = new XmlRootAttribute ("simple");
1255 overrides.Add (typeof (SimpleClass), childAttr);
1257 XmlAttributes attr = new XmlAttributes ();
1258 attr.XmlRoot = new XmlRootAttribute ("simple");
1259 overrides.Add (typeof (ClassArrayContainer), attr);
1261 ClassArrayContainer container = new ClassArrayContainer ();
1262 container.items = new SimpleClass[1];
1263 container.items[0] = new SimpleClass ();
1264 Serialize (container, overrides);
1265 Assert.AreEqual (Infoset ("<simple xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ><items><SimpleClass /></items></simple>"), WriterText);
1267 // FIXME test data type
1270 // test XmlAttribute /////////////////////////////////////////////////////
1271 [Test]
1272 public void TestSerializeXmlAttributeAttribute ()
1274 // null
1275 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1276 XmlAttributes attr = new XmlAttributes ();
1277 attr.XmlAttribute = new XmlAttributeAttribute ();
1278 overrides.Add (typeof (SimpleClass), "something", attr);
1280 SimpleClass simple = new SimpleClass (); ;
1281 Serialize (simple, overrides);
1282 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#1");
1284 // regular
1285 simple.something = "hello";
1286 Serialize (simple, overrides);
1287 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' something='hello' />"), WriterText, "#2");
1289 // AttributeName
1290 attr.XmlAttribute.AttributeName = "somethingelse";
1291 Serialize (simple, overrides);
1292 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' somethingelse='hello' />"), WriterText, "#3");
1294 // Type
1295 // FIXME this should work, shouldnt it?
1296 // attr.XmlAttribute.Type = typeof(string);
1297 // Serialize(simple, overrides);
1298 // Assert(WriterText.EndsWith(" something='hello' />"));
1300 // Namespace
1301 attr.XmlAttribute.Namespace = "some:urn";
1302 Serialize (simple, overrides);
1303 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' d1p1:somethingelse='hello' xmlns:d1p1='some:urn' />"), WriterText, "#4");
1305 // FIXME DataType
1306 // FIXME XmlSchemaForm Form
1308 // FIXME write XmlQualifiedName as attribute
1311 // test XmlElement ///////////////////////////////////////////////////////
1312 [Test]
1313 public void TestSerializeXmlElementAttribute ()
1315 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1316 XmlAttributes attr = new XmlAttributes ();
1317 XmlElementAttribute element = new XmlElementAttribute ();
1318 attr.XmlElements.Add (element);
1319 overrides.Add (typeof (SimpleClass), "something", attr);
1321 // null
1322 SimpleClass simple = new SimpleClass (); ;
1323 Serialize (simple, overrides);
1324 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#1");
1326 // not null
1327 simple.something = "hello";
1328 Serialize (simple, overrides);
1329 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>hello</something></SimpleClass>"), WriterText, "#2");
1331 //ElementName
1332 element.ElementName = "saying";
1333 Serialize (simple, overrides);
1334 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><saying>hello</saying></SimpleClass>"), WriterText, "#3");
1336 //IsNullable
1337 element.IsNullable = false;
1338 simple.something = null;
1339 Serialize (simple, overrides);
1340 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#4");
1342 element.IsNullable = true;
1343 simple.something = null;
1344 Serialize (simple, overrides);
1345 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><saying xsi:nil='true' /></SimpleClass>"), WriterText, "#5");
1347 //Namespace
1348 element.ElementName = null;
1349 element.IsNullable = false;
1350 element.Namespace = "some:urn";
1351 simple.something = "hello";
1352 Serialize (simple, overrides);
1353 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something xmlns='some:urn'>hello</something></SimpleClass>"), WriterText, "#6");
1355 //FIXME DataType
1356 //FIXME Form
1357 //FIXME Type
1360 // test XmlElementAttribute with arrays and collections //////////////////
1361 [Test]
1362 public void TestSerializeCollectionWithXmlElementAttribute ()
1364 // the rule is:
1365 // if no type is specified or the specified type
1366 // matches the contents of the collection,
1367 // serialize each element in an element named after the member.
1368 // if the type does not match, or matches the collection itself,
1369 // create a base wrapping element for the member, and then
1370 // wrap each collection item in its own wrapping element based on type.
1372 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1373 XmlAttributes attr = new XmlAttributes ();
1374 XmlElementAttribute element = new XmlElementAttribute ();
1375 attr.XmlElements.Add (element);
1376 overrides.Add (typeof (StringCollectionContainer), "Messages", attr);
1378 // empty collection & no type info in XmlElementAttribute
1379 StringCollectionContainer container = new StringCollectionContainer ();
1380 Serialize (container, overrides);
1381 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#1");
1383 // non-empty collection & no type info in XmlElementAttribute
1384 container.Messages.Add ("hello");
1385 Serialize (container, overrides);
1386 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Messages>hello</Messages></StringCollectionContainer>"), WriterText, "#2");
1388 // non-empty collection & only type info in XmlElementAttribute
1389 element.Type = typeof (StringCollection);
1390 Serialize (container, overrides);
1391 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Messages><string>hello</string></Messages></StringCollectionContainer>"), WriterText, "#3");
1393 // non-empty collection & only type info in XmlElementAttribute
1394 element.Type = typeof (string);
1395 Serialize (container, overrides);
1396 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Messages>hello</Messages></StringCollectionContainer>"), WriterText, "#4");
1398 // two elements
1399 container.Messages.Add ("goodbye");
1400 element.Type = null;
1401 Serialize (container, overrides);
1402 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Messages>hello</Messages><Messages>goodbye</Messages></StringCollectionContainer>"), WriterText, "#5");
1405 // test DefaultValue /////////////////////////////////////////////////////
1406 [Test]
1407 public void TestSerializeDefaultValueAttribute ()
1409 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1411 XmlAttributes attr = new XmlAttributes ();
1412 string defaultValueInstance = "nothing";
1413 attr.XmlDefaultValue = defaultValueInstance;
1414 overrides.Add (typeof (SimpleClass), "something", attr);
1416 // use the default
1417 SimpleClass simple = new SimpleClass ();
1418 Serialize (simple, overrides);
1419 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#A1");
1421 // same value as default
1422 simple.something = defaultValueInstance;
1423 Serialize (simple, overrides);
1424 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#A2");
1426 // some other value
1427 simple.something = "hello";
1428 Serialize (simple, overrides);
1429 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>hello</something></SimpleClass>"), WriterText, "#A3");
1431 overrides = new XmlAttributeOverrides ();
1432 attr = new XmlAttributes ();
1433 attr.XmlAttribute = new XmlAttributeAttribute ();
1434 attr.XmlDefaultValue = defaultValueInstance;
1435 overrides.Add (typeof (SimpleClass), "something", attr);
1437 // use the default
1438 simple = new SimpleClass ();
1439 Serialize (simple, overrides);
1440 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#B1");
1442 // same value as default
1443 simple.something = defaultValueInstance;
1444 Serialize (simple, overrides);
1445 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#B2");
1447 // some other value
1448 simple.something = "hello";
1449 Serialize (simple, overrides);
1450 Assert.AreEqual (Infoset ("<SimpleClass something='hello' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#B3");
1452 overrides = new XmlAttributeOverrides ();
1453 attr = new XmlAttributes ();
1454 attr.XmlAttribute = new XmlAttributeAttribute ("flagenc");
1455 overrides.Add (typeof (TestDefault), "flagencoded", attr);
1457 // use the default
1458 TestDefault testDefault = new TestDefault ();
1459 Serialize (testDefault);
1460 Assert.AreEqual (Infoset ("<testDefault xmlns='urn:myNS' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#C1");
1462 // use the default with overrides
1463 Serialize (testDefault, overrides);
1464 Assert.AreEqual (Infoset ("<testDefault flagenc='e1 e4' xmlns='urn:myNS' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#C2");
1466 overrides = new XmlAttributeOverrides ();
1467 attr = new XmlAttributes ();
1468 attr.XmlAttribute = new XmlAttributeAttribute ("flagenc");
1469 attr.XmlDefaultValue = (FlagEnum_Encoded.e1 | FlagEnum_Encoded.e4); // add default again
1470 overrides.Add (typeof (TestDefault), "flagencoded", attr);
1472 // use the default with overrides
1473 Serialize (testDefault, overrides);
1474 Assert.AreEqual (Infoset ("<testDefault xmlns='urn:myNS' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#C3");
1476 // use the default with overrides and default namspace
1477 Serialize (testDefault, overrides, AnotherNamespace);
1478 Assert.AreEqual (Infoset ("<testDefault xmlns='urn:myNS' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#C4");
1480 // non-default values
1481 testDefault.strDefault = "Some Text";
1482 testDefault.boolT = false;
1483 testDefault.boolF = true;
1484 testDefault.decimalval = 20m;
1485 testDefault.flag = FlagEnum.e2;
1486 testDefault.flagencoded = FlagEnum_Encoded.e2 | FlagEnum_Encoded.e1;
1487 Serialize (testDefault);
1488 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1489 "<testDefault xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1490 " <strDefault>Some Text</strDefault>" +
1491 " <boolT>false</boolT>" +
1492 " <boolF>true</boolF>" +
1493 " <decimalval>20</decimalval>" +
1494 " <flag>two</flag>" +
1495 " <flagencoded>e1 e2</flagencoded>" +
1496 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1497 WriterText, "#C5");
1499 Serialize (testDefault, overrides);
1500 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1501 "<testDefault flagenc='e1 e2' xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1502 " <strDefault>Some Text</strDefault>" +
1503 " <boolT>false</boolT>" +
1504 " <boolF>true</boolF>" +
1505 " <decimalval>20</decimalval>" +
1506 " <flag>two</flag>" +
1507 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1508 WriterText, "#C6");
1510 Serialize (testDefault, overrides, AnotherNamespace);
1511 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1512 "<testDefault flagenc='e1 e2' xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1513 " <strDefault>Some Text</strDefault>" +
1514 " <boolT>false</boolT>" +
1515 " <boolF>true</boolF>" +
1516 " <decimalval>20</decimalval>" +
1517 " <flag>two</flag>" +
1518 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1519 WriterText, "#C7");
1521 attr = new XmlAttributes ();
1522 XmlTypeAttribute xmlType = new XmlTypeAttribute ("flagenum");
1523 xmlType.Namespace = "yetanother:urn";
1524 attr.XmlType = xmlType;
1525 overrides.Add (typeof (FlagEnum_Encoded), attr);
1527 Serialize (testDefault, overrides, AnotherNamespace);
1528 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1529 "<testDefault flagenc='e1 e2' xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1530 " <strDefault>Some Text</strDefault>" +
1531 " <boolT>false</boolT>" +
1532 " <boolF>true</boolF>" +
1533 " <decimalval>20</decimalval>" +
1534 " <flag>two</flag>" +
1535 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1536 WriterText, "#C8");
1538 attr = new XmlAttributes ();
1539 attr.XmlType = new XmlTypeAttribute ("testDefault");
1540 overrides.Add (typeof (TestDefault), attr);
1542 Serialize (testDefault, overrides, AnotherNamespace);
1543 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1544 "<testDefault flagenc='e1 e2' xmlns='{2}' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1545 " <strDefault>Some Text</strDefault>" +
1546 " <boolT>false</boolT>" +
1547 " <boolF>true</boolF>" +
1548 " <decimalval>20</decimalval>" +
1549 " <flag>two</flag>" +
1550 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1551 AnotherNamespace)), WriterText, "#C9");
1554 [Test]
1555 public void TestSerializeDefaultValueAttribute_Encoded ()
1557 SoapAttributeOverrides overrides = new SoapAttributeOverrides ();
1558 SoapAttributes attr = new SoapAttributes ();
1559 attr.SoapAttribute = new SoapAttributeAttribute ();
1560 string defaultValueInstance = "nothing";
1561 attr.SoapDefaultValue = defaultValueInstance;
1562 overrides.Add (typeof (SimpleClass), "something", attr);
1564 // use the default
1565 SimpleClass simple = new SimpleClass ();
1566 SerializeEncoded (simple, overrides);
1567 Assert.AreEqual (Infoset ("<SimpleClass id='id1' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#A1");
1569 // same value as default
1570 simple.something = defaultValueInstance;
1571 SerializeEncoded (simple, overrides);
1572 Assert.AreEqual (Infoset ("<SimpleClass id='id1' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#A2");
1574 // some other value
1575 simple.something = "hello";
1576 SerializeEncoded (simple, overrides);
1577 Assert.AreEqual (Infoset ("<SimpleClass id='id1' something='hello' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#A3");
1579 attr.SoapAttribute = null;
1580 attr.SoapElement = new SoapElementAttribute ();
1582 // use the default
1583 simple = new SimpleClass ();
1584 SerializeEncoded (simple, overrides);
1585 Assert.AreEqual (Infoset ("<SimpleClass id='id1' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#B1");
1587 // same value as default
1588 simple.something = defaultValueInstance;
1589 SerializeEncoded (simple, overrides);
1590 Assert.AreEqual (Infoset ("<SimpleClass id='id1' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something xsi:type='xsd:string'>nothing</something></SimpleClass>"), WriterText, "#B2");
1592 // some other value
1593 simple.something = "hello";
1594 SerializeEncoded (simple, overrides);
1595 Assert.AreEqual (Infoset ("<SimpleClass id='id1' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something xsi:type='xsd:string'>hello</something></SimpleClass>"), WriterText, "#B3");
1597 overrides = new SoapAttributeOverrides ();
1598 attr = new SoapAttributes ();
1599 attr.SoapElement = new SoapElementAttribute ("flagenc");
1600 overrides.Add (typeof (TestDefault), "flagencoded", attr);
1602 // use the default (from MS KB325691)
1603 TestDefault testDefault = new TestDefault ();
1604 SerializeEncoded (testDefault);
1605 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1606 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1607 " <strDefault xsi:type='xsd:string'>Default Value</strDefault>" +
1608 " <boolT xsi:type='xsd:boolean'>true</boolT>" +
1609 " <boolF xsi:type='xsd:boolean'>false</boolF>" +
1610 " <decimalval xsi:type='xsd:decimal'>10</decimalval>" +
1611 " <flag xsi:type='FlagEnum'>e1 e4</flag>" +
1612 " <flagencoded xsi:type='flagenum'>one four</flagencoded>" +
1613 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1614 WriterText, "#C1");
1616 SerializeEncoded (testDefault, overrides);
1617 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1618 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1619 " <strDefault xsi:type='xsd:string'>Default Value</strDefault>" +
1620 " <boolT xsi:type='xsd:boolean'>true</boolT>" +
1621 " <boolF xsi:type='xsd:boolean'>false</boolF>" +
1622 " <decimalval xsi:type='xsd:decimal'>10</decimalval>" +
1623 " <flag xsi:type='FlagEnum'>e1 e4</flag>" +
1624 " <flagenc xsi:type='flagenum'>one four</flagenc>" +
1625 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1626 WriterText, "#C2");
1628 SerializeEncoded (testDefault, overrides, AnotherNamespace);
1629 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1630 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1631 " <strDefault xsi:type='xsd:string'>Default Value</strDefault>" +
1632 " <boolT xsi:type='xsd:boolean'>true</boolT>" +
1633 " <boolF xsi:type='xsd:boolean'>false</boolF>" +
1634 " <decimalval xsi:type='xsd:decimal'>10</decimalval>" +
1635 " <flag xmlns:q2='{2}' xsi:type='q2:FlagEnum'>e1 e4</flag>" +
1636 " <flagenc xmlns:q3='{2}' xsi:type='q3:flagenum'>one four</flagenc>" +
1637 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1638 AnotherNamespace)), WriterText, "#C3");
1640 // non-default values
1641 testDefault.strDefault = "Some Text";
1642 testDefault.boolT = false;
1643 testDefault.boolF = true;
1644 testDefault.decimalval = 20m;
1645 testDefault.flag = FlagEnum.e2;
1646 testDefault.flagencoded = FlagEnum_Encoded.e2 | FlagEnum_Encoded.e1;
1647 SerializeEncoded (testDefault);
1648 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1649 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1650 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1651 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1652 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1653 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1654 " <flag xsi:type='FlagEnum'>e2</flag>" +
1655 " <flagencoded xsi:type='flagenum'>one two</flagencoded>" +
1656 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1657 WriterText, "#C4");
1659 SerializeEncoded (testDefault, overrides);
1660 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1661 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1662 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1663 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1664 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1665 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1666 " <flag xsi:type='FlagEnum'>e2</flag>" +
1667 " <flagenc xsi:type='flagenum'>one two</flagenc>" +
1668 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1669 WriterText, "#C5");
1671 attr = new SoapAttributes ();
1672 attr.SoapType = new SoapTypeAttribute ("flagenum", "yetanother:urn");
1673 overrides.Add (typeof (FlagEnum_Encoded), attr);
1675 SerializeEncoded (testDefault, overrides, AnotherNamespace);
1676 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1677 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1678 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1679 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1680 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1681 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1682 " <flag xmlns:q2='{2}' xsi:type='q2:FlagEnum'>e2</flag>" +
1683 " <flagenc xmlns:q3='yetanother:urn' xsi:type='q3:flagenum'>one two</flagenc>" +
1684 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1685 AnotherNamespace)), WriterText, "#C6");
1687 attr = new SoapAttributes ();
1688 attr.SoapType = new SoapTypeAttribute ("testDefault");
1689 overrides.Add (typeof (TestDefault), attr);
1691 SerializeEncoded (testDefault, overrides, AnotherNamespace);
1692 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1693 "<q1:testDefault id='id1' xmlns:q1='{2}' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1694 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1695 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1696 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1697 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1698 " <flag xsi:type='q1:FlagEnum'>e2</flag>" +
1699 " <flagenc xmlns:q2='yetanother:urn' xsi:type='q2:flagenum'>one two</flagenc>" +
1700 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1701 AnotherNamespace)), WriterText, "#C7");
1704 // test XmlEnum //////////////////////////////////////////////////////////
1705 [Test]
1706 public void TestSerializeXmlEnumAttribute ()
1708 Serialize (XmlSchemaForm.Qualified);
1709 Assert.AreEqual (Infoset ("<XmlSchemaForm>qualified</XmlSchemaForm>"), WriterText, "#1");
1711 Serialize (XmlSchemaForm.Unqualified);
1712 Assert.AreEqual (Infoset ("<XmlSchemaForm>unqualified</XmlSchemaForm>"), WriterText, "#2");
1715 [Test]
1716 public void TestSerializeXmlEnumAttribute_IgnoredValue ()
1718 // technically XmlSchemaForm.None has an XmlIgnore attribute,
1719 // but it is not being serialized as a member.
1721 try {
1722 Serialize (XmlSchemaForm.None);
1723 Assert.Fail ("#1");
1724 } catch (InvalidOperationException ex) {
1725 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
1726 Assert.IsNotNull (ex.InnerException, "#3");
1727 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
1728 Assert.IsNotNull (ex.InnerException.Message, "#5");
1729 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'0'") != -1, "#6");
1730 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (XmlSchemaForm).FullName) != -1, "#7");
1734 [Test]
1735 public void TestSerializeXmlNodeArray ()
1737 XmlDocument doc = new XmlDocument ();
1738 Serialize (new XmlNode[] { doc.CreateAttribute ("at"), doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (object));
1739 Assert.AreEqual (Infoset ("<anyType at=\"\"><elem1/><elem2/></anyType>"), WriterText);
1742 [Test]
1743 public void TestSerializeXmlNodeArray2 ()
1745 XmlDocument doc = new XmlDocument ();
1746 Serialize (new XmlNode[] { doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (XmlNode []));
1747 Assert.AreEqual (Infoset (String.Format ("<ArrayOfXmlNode xmlns:xsd='{0}' xmlns:xsi='{1}'><XmlNode><elem1/></XmlNode><XmlNode><elem2/></XmlNode></ArrayOfXmlNode>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
1750 [Test]
1751 [ExpectedException (typeof (InvalidOperationException))]
1752 [Category ("MobileNotWorking")]
1753 public void TestSerializeXmlNodeArrayIncludesAttribute ()
1755 XmlDocument doc = new XmlDocument ();
1756 Serialize (new XmlNode[] { doc.CreateAttribute ("at"), doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (XmlNode []));
1759 [Test]
1760 public void TestSerializeXmlElementArray ()
1762 XmlDocument doc = new XmlDocument ();
1763 Serialize (new XmlElement[] { doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (object));
1764 Assert.AreEqual (Infoset ("<anyType><elem1/><elem2/></anyType>"), WriterText);
1767 [Test]
1768 [ExpectedException (typeof (InvalidOperationException))] // List<XmlNode> is not supported
1769 public void TestSerializeGenericListOfNode ()
1771 XmlDocument doc = new XmlDocument ();
1772 Serialize (new List<XmlNode> (new XmlNode [] { doc.CreateAttribute ("at"), doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }), typeof (object));
1773 Assert.AreEqual (Infoset ("<anyType at=\"\"><elem1/><elem2/></anyType>"), WriterText);
1776 [Test]
1777 [ExpectedException (typeof (InvalidOperationException))] // List<XmlElement> is not supported
1778 public void TestSerializeGenericListOfElement ()
1780 XmlDocument doc = new XmlDocument ();
1781 Serialize (new List<XmlElement> (new XmlElement [] { doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }), typeof (object));
1782 Assert.AreEqual (Infoset ("<anyType><elem1/><elem2/></anyType>"), WriterText);
1784 [Test]
1785 public void TestSerializeXmlDocument ()
1787 XmlDocument doc = new XmlDocument ();
1788 doc.LoadXml (@"<?xml version=""1.0"" encoding=""utf-8"" ?><root/>");
1789 Serialize (doc, typeof (XmlDocument));
1790 Assert.AreEqual ("<?xml version='1.0' encoding='utf-16'?><root />",
1791 sw.GetStringBuilder ().ToString ());
1794 [Test]
1795 public void TestSerializeXmlElement ()
1797 XmlDocument doc = new XmlDocument ();
1798 Serialize (doc.CreateElement ("elem"), typeof (XmlElement));
1799 Assert.AreEqual (Infoset ("<elem/>"), WriterText);
1802 [Test]
1803 public void TestSerializeXmlElementSubclass ()
1805 XmlDocument doc = new XmlDocument ();
1806 Serialize (new MyElem (doc), typeof (XmlElement));
1807 Assert.AreEqual (Infoset ("<myelem aa=\"1\"/>"), WriterText, "#1");
1809 Serialize (new MyElem (doc), typeof (MyElem));
1810 Assert.AreEqual (Infoset ("<myelem aa=\"1\"/>"), WriterText, "#2");
1813 [Test]
1814 public void TestSerializeXmlCDataSection ()
1816 XmlDocument doc = new XmlDocument ();
1817 CDataContainer c = new CDataContainer ();
1818 c.cdata = doc.CreateCDataSection ("data section contents");
1819 Serialize (c);
1820 Assert.AreEqual (Infoset ("<CDataContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><cdata><![CDATA[data section contents]]></cdata></CDataContainer>"), WriterText);
1823 [Test]
1824 public void TestSerializeXmlNode ()
1826 XmlDocument doc = new XmlDocument ();
1827 NodeContainer c = new NodeContainer ();
1828 c.node = doc.CreateTextNode ("text");
1829 Serialize (c);
1830 Assert.AreEqual (Infoset ("<NodeContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><node>text</node></NodeContainer>"), WriterText);
1833 [Test]
1834 public void TestSerializeChoice ()
1836 Choices ch = new Choices ();
1837 ch.MyChoice = "choice text";
1838 ch.ItemType = ItemChoiceType.ChoiceZero;
1839 Serialize (ch);
1840 Assert.AreEqual (Infoset ("<Choices xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><ChoiceZero>choice text</ChoiceZero></Choices>"), WriterText, "#1");
1841 ch.ItemType = ItemChoiceType.StrangeOne;
1842 Serialize (ch);
1843 Assert.AreEqual (Infoset ("<Choices xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><ChoiceOne>choice text</ChoiceOne></Choices>"), WriterText, "#2");
1844 ch.ItemType = ItemChoiceType.ChoiceTwo;
1845 Serialize (ch);
1846 Assert.AreEqual (Infoset ("<Choices xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><ChoiceTwo>choice text</ChoiceTwo></Choices>"), WriterText, "#3");
1849 [Test]
1850 public void TestSerializeNamesWithSpaces ()
1852 TestSpace ts = new TestSpace ();
1853 ts.elem = 4;
1854 ts.attr = 5;
1855 Serialize (ts);
1856 Assert.AreEqual (Infoset ("<Type_x0020_with_x0020_space xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' Attribute_x0020_with_x0020_space='5'><Element_x0020_with_x0020_space>4</Element_x0020_with_x0020_space></Type_x0020_with_x0020_space>"), WriterText);
1859 [Test]
1860 public void TestSerializeReadOnlyProps ()
1862 ReadOnlyProperties ts = new ReadOnlyProperties ();
1863 Serialize (ts);
1864 Assert.AreEqual (Infoset ("<ReadOnlyProperties xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1867 [Test]
1868 public void TestSerializeReadOnlyListProp ()
1870 ReadOnlyListProperty ts = new ReadOnlyListProperty ();
1871 Serialize (ts);
1872 Assert.AreEqual (Infoset ("<ReadOnlyListProperty xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><StrList><string>listString1</string><string>listString2</string></StrList></ReadOnlyListProperty>"), WriterText);
1876 [Test]
1877 public void TestSerializeIList ()
1879 clsPerson k = new clsPerson ();
1880 k.EmailAccounts = new ArrayList ();
1881 k.EmailAccounts.Add ("a");
1882 k.EmailAccounts.Add ("b");
1883 Serialize (k);
1884 Assert.AreEqual (Infoset ("<clsPerson xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><EmailAccounts><anyType xsi:type=\"xsd:string\">a</anyType><anyType xsi:type=\"xsd:string\">b</anyType></EmailAccounts></clsPerson>"), WriterText);
1887 [Test]
1888 public void TestSerializeArrayEnc ()
1890 SoapReflectionImporter imp = new SoapReflectionImporter ();
1891 XmlTypeMapping map = imp.ImportTypeMapping (typeof (ArrayClass));
1892 XmlSerializer ser = new XmlSerializer (map);
1893 StringWriter sw = new StringWriter ();
1894 XmlTextWriter tw = new XmlTextWriter (sw);
1895 tw.WriteStartElement ("aa");
1896 ser.Serialize (tw, new ArrayClass ());
1897 tw.WriteEndElement ();
1900 [Test] // bug #76049
1901 public void TestIncludeType ()
1903 XmlReflectionImporter imp = new XmlReflectionImporter ();
1904 XmlTypeMapping map = imp.ImportTypeMapping (typeof (object));
1905 imp.IncludeType (typeof (TestSpace));
1906 XmlSerializer ser = new XmlSerializer (map);
1907 ser.Serialize (new StringWriter (), new TestSpace ());
1910 [Test]
1911 public void TestSerializeChoiceArray ()
1913 CompositeValueType v = new CompositeValueType ();
1914 v.Init ();
1915 Serialize (v);
1916 Assert.AreEqual (Infoset ("<?xml version=\"1.0\" encoding=\"utf-16\"?><CompositeValueType xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><In>1</In><Es>2</Es></CompositeValueType>"), WriterText);
1919 [Test]
1920 public void TestArrayAttributeWithDataType ()
1922 Serialize (new ArrayAttributeWithType ());
1923 string res = "<ArrayAttributeWithType xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
1924 res += "at='a b' bin1='AQI= AQI=' bin2='AQI=' />";
1925 Assert.AreEqual (Infoset (res), WriterText);
1928 [Test]
1929 public void TestSubclassElementType ()
1931 SubclassTestContainer c = new SubclassTestContainer ();
1932 c.data = new SubclassTestSub ();
1933 Serialize (c);
1935 string res = "<SubclassTestContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>";
1936 res += "<a xsi:type=\"SubclassTestSub\"/></SubclassTestContainer>";
1937 Assert.AreEqual (Infoset (res), WriterText);
1940 [Test] // Covers #36829
1941 public void TestSubclassElementList ()
1943 var o = new SubclassTestList () { Items = new List<object> () { new SubclassTestSub () } };
1944 Serialize (o);
1946 string res = "<SubclassTestList xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>";
1947 res += "<b xsi:type=\"SubclassTestSub\"/></SubclassTestList>";
1948 Assert.AreEqual (Infoset (res), WriterText);
1951 [Test]
1952 [ExpectedException (typeof (InvalidOperationException))]
1953 public void TestArrayAttributeWithWrongDataType ()
1955 Serialize (new ArrayAttributeWithWrongType ());
1958 [Test]
1959 [Category ("NotWorking")]
1960 public void TestSerializePrimitiveTypesContainer ()
1962 Serialize (new PrimitiveTypesContainer ());
1963 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
1964 "<?xml version='1.0' encoding='utf-16'?>" +
1965 "<PrimitiveTypesContainer xmlns:xsi='{1}' xmlns:xsd='{0}' xmlns='some:urn'>" +
1966 "<Number>2004</Number>" +
1967 "<Name>some name</Name>" +
1968 "<Index>56</Index>" +
1969 "<Password>8w8=</Password>" +
1970 "<PathSeparatorCharacter>47</PathSeparatorCharacter>" +
1971 "</PrimitiveTypesContainer>", XmlSchema.Namespace,
1972 XmlSchema.InstanceNamespace), sw.ToString (), "#1");
1974 SerializeEncoded (new PrimitiveTypesContainer ());
1975 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
1976 "<?xml version='1.0' encoding='utf-16'?>" +
1977 "<q1:PrimitiveTypesContainer xmlns:xsi='{1}' xmlns:xsd='{0}' id='id1' xmlns:q1='{2}'>" +
1978 "<Number xsi:type='xsd:int'>2004</Number>" +
1979 "<Name xsi:type='xsd:string'>some name</Name>" +
1980 "<Index xsi:type='xsd:unsignedByte'>56</Index>" +
1981 "<Password xsi:type='xsd:base64Binary'>8w8=</Password>" +
1982 "<PathSeparatorCharacter xmlns:q2='{3}' xsi:type='q2:char'>47</PathSeparatorCharacter>" +
1983 "</q1:PrimitiveTypesContainer>", XmlSchema.Namespace,
1984 XmlSchema.InstanceNamespace, AnotherNamespace, WsdlTypesNamespace),
1985 sw.ToString (), "#2");
1988 [Test]
1989 public void TestSchemaForm ()
1991 TestSchemaForm1 t1 = new TestSchemaForm1 ();
1992 t1.p1 = new PrintTypeResponse ();
1993 t1.p1.Init ();
1994 t1.p2 = new PrintTypeResponse ();
1995 t1.p2.Init ();
1997 TestSchemaForm2 t2 = new TestSchemaForm2 ();
1998 t2.p1 = new PrintTypeResponse ();
1999 t2.p1.Init ();
2000 t2.p2 = new PrintTypeResponse ();
2001 t2.p2.Init ();
2003 Serialize (t1);
2004 string res = "";
2005 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
2006 res += "<TestSchemaForm1 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
2007 res += " <p1>";
2008 res += " <result>";
2009 res += " <data>data1</data>";
2010 res += " </result>";
2011 res += " <intern xmlns=\"urn:responseTypes\">";
2012 res += " <result xmlns=\"\">";
2013 res += " <data>data2</data>";
2014 res += " </result>";
2015 res += " </intern>";
2016 res += " </p1>";
2017 res += " <p2 xmlns=\"urn:oo\">";
2018 res += " <result xmlns=\"\">";
2019 res += " <data>data1</data>";
2020 res += " </result>";
2021 res += " <intern xmlns=\"urn:responseTypes\">";
2022 res += " <result xmlns=\"\">";
2023 res += " <data>data2</data>";
2024 res += " </result>";
2025 res += " </intern>";
2026 res += " </p2>";
2027 res += "</TestSchemaForm1>";
2028 Assert.AreEqual (Infoset (res), WriterText);
2030 Serialize (t2);
2031 res = "";
2032 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
2033 res += "<TestSchemaForm2 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
2034 res += " <p1 xmlns=\"urn:testForm\">";
2035 res += " <result xmlns=\"\">";
2036 res += " <data>data1</data>";
2037 res += " </result>";
2038 res += " <intern xmlns=\"urn:responseTypes\">";
2039 res += " <result xmlns=\"\">";
2040 res += " <data>data2</data>";
2041 res += " </result>";
2042 res += " </intern>";
2043 res += " </p1>";
2044 res += " <p2 xmlns=\"urn:oo\">";
2045 res += " <result xmlns=\"\">";
2046 res += " <data>data1</data>";
2047 res += " </result>";
2048 res += " <intern xmlns=\"urn:responseTypes\">";
2049 res += " <result xmlns=\"\">";
2050 res += " <data>data2</data>";
2051 res += " </result>";
2052 res += " </intern>";
2053 res += " </p2>";
2054 res += "</TestSchemaForm2>";
2055 Assert.AreEqual (Infoset (res), WriterText);
2057 XmlReflectionImporter imp = new XmlReflectionImporter ();
2058 XmlTypeMapping map = imp.ImportTypeMapping (typeof (TestSchemaForm1), "urn:extra");
2059 Serialize (t1, map);
2060 res = "";
2061 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
2062 res += "<TestSchemaForm1 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:extra\">";
2063 res += " <p1>";
2064 res += " <result xmlns=\"\">";
2065 res += " <data>data1</data>";
2066 res += " </result>";
2067 res += " <intern xmlns=\"urn:responseTypes\">";
2068 res += " <result xmlns=\"\">";
2069 res += " <data>data2</data>";
2070 res += " </result>";
2071 res += " </intern>";
2072 res += " </p1>";
2073 res += " <p2 xmlns=\"urn:oo\">";
2074 res += " <result xmlns=\"\">";
2075 res += " <data>data1</data>";
2076 res += " </result>";
2077 res += " <intern xmlns=\"urn:responseTypes\">";
2078 res += " <result xmlns=\"\">";
2079 res += " <data>data2</data>";
2080 res += " </result>";
2081 res += " </intern>";
2082 res += " </p2>";
2083 res += "</TestSchemaForm1>";
2084 Assert.AreEqual (Infoset (res), WriterText);
2086 imp = new XmlReflectionImporter ();
2087 map = imp.ImportTypeMapping (typeof (TestSchemaForm2), "urn:extra");
2088 Serialize (t2, map);
2089 res = "";
2090 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
2091 res += "<TestSchemaForm2 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:extra\">";
2092 res += " <p1 xmlns=\"urn:testForm\">";
2093 res += " <result xmlns=\"\">";
2094 res += " <data>data1</data>";
2095 res += " </result>";
2096 res += " <intern xmlns=\"urn:responseTypes\">";
2097 res += " <result xmlns=\"\">";
2098 res += " <data>data2</data>";
2099 res += " </result>";
2100 res += " </intern>";
2101 res += " </p1>";
2102 res += " <p2 xmlns=\"urn:oo\">";
2103 res += " <result xmlns=\"\">";
2104 res += " <data>data1</data>";
2105 res += " </result>";
2106 res += " <intern xmlns=\"urn:responseTypes\">";
2107 res += " <result xmlns=\"\">";
2108 res += " <data>data2</data>";
2109 res += " </result>";
2110 res += " </intern>";
2111 res += " </p2>";
2112 res += "</TestSchemaForm2>";
2113 Assert.AreEqual (Infoset (res), WriterText);
2116 [Test] // bug #78536
2117 public void CDataTextNodes ()
2119 XmlSerializer ser = new XmlSerializer (typeof (CDataTextNodesType));
2120 ser.UnknownNode += new XmlNodeEventHandler (CDataTextNodes_BadNode);
2121 string xml = @"<CDataTextNodesType>
2122 <foo><![CDATA[
2123 (?<filename>^([A-Z]:)?[^\(]+)\((?<line>\d+),(?<column>\d+)\):
2124 \s((?<warning>warning)|(?<error>error))\s[^:]+:(?<message>.+$)|
2125 (?<error>(fatal\s)?error)[^:]+:(?<message>.+$)
2126 ]]></foo>
2127 </CDataTextNodesType>";
2128 ser.Deserialize (new XmlTextReader (xml, XmlNodeType.Document, null));
2131 #if !MOBILE
2132 [Test]
2133 public void GenerateSerializerGenerics ()
2135 XmlReflectionImporter imp = new XmlReflectionImporter ();
2136 Type type = typeof (List<int>);
2137 XmlSerializer.GenerateSerializer (
2138 new Type [] {type},
2139 new XmlTypeMapping [] {imp.ImportTypeMapping (type)});
2141 #endif
2143 [Test]
2144 public void Nullable ()
2146 XmlSerializer ser = new XmlSerializer (typeof (int?));
2147 int? nullableType = 5;
2148 sw = new StringWriter ();
2149 xtw = new XmlTextWriter (sw);
2150 ser.Serialize (xtw, nullableType);
2151 xtw.Close ();
2152 string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?><int>5</int>";
2153 Assert.AreEqual (Infoset (expected), WriterText);
2154 int? i = (int?) ser.Deserialize (new StringReader (sw.ToString ()));
2155 Assert.AreEqual (5, i);
2158 [Test]
2159 public void NullableEnums ()
2161 WithNulls w = new WithNulls ();
2162 XmlSerializer ser = new XmlSerializer (typeof(WithNulls));
2163 StringWriter tw = new StringWriter ();
2164 ser.Serialize (tw, w);
2166 string expected = "<?xml version='1.0' encoding='utf-16'?>" +
2167 "<WithNulls xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
2168 "<nint xsi:nil='true' />" +
2169 "<nenum xsi:nil='true' />" +
2170 "<ndate xsi:nil='true' />" +
2171 "</WithNulls>";
2173 Assert.AreEqual (Infoset (expected), Infoset (tw.ToString ()));
2175 StringReader sr = new StringReader (tw.ToString ());
2176 w = (WithNulls) ser.Deserialize (sr);
2178 Assert.IsFalse (w.nint.HasValue);
2179 Assert.IsFalse (w.nenum.HasValue);
2180 Assert.IsFalse (w.ndate.HasValue);
2182 DateTime t = new DateTime (2008,4,1);
2183 w.nint = 4;
2184 w.ndate = t;
2185 w.nenum = TestEnumWithNulls.bb;
2187 tw = new StringWriter ();
2188 ser.Serialize (tw, w);
2190 expected = "<?xml version='1.0' encoding='utf-16'?>" +
2191 "<WithNulls xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
2192 "<nint>4</nint>" +
2193 "<nenum>bb</nenum>" +
2194 "<ndate>2008-04-01T00:00:00</ndate>" +
2195 "</WithNulls>";
2197 Assert.AreEqual (Infoset (expected), Infoset (tw.ToString ()));
2199 sr = new StringReader (tw.ToString ());
2200 w = (WithNulls) ser.Deserialize (sr);
2202 Assert.IsTrue (w.nint.HasValue);
2203 Assert.IsTrue (w.nenum.HasValue);
2204 Assert.IsTrue (w.ndate.HasValue);
2205 Assert.AreEqual (4, w.nint.Value);
2206 Assert.AreEqual (TestEnumWithNulls.bb, w.nenum.Value);
2207 Assert.AreEqual (t, w.ndate.Value);
2210 [Test]
2211 public void SerializeBase64Binary()
2213 XmlSerializer ser = new XmlSerializer (typeof (Base64Binary));
2214 sw = new StringWriter ();
2215 XmlTextWriter xtw = new XmlTextWriter (sw);
2216 ser.Serialize (xtw, new Base64Binary ());
2217 xtw.Close ();
2218 string expected = @"<?xml version=""1.0"" encoding=""utf-16""?><Base64Binary xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" Data=""AQID"" />";
2219 Assert.AreEqual (Infoset (expected), WriterText);
2220 Base64Binary h = (Base64Binary) ser.Deserialize (new StringReader (sw.ToString ()));
2221 Assert.AreEqual (new byte [] {1, 2, 3}, h.Data);
2224 [Test] // bug #79989, #79990
2225 public void SerializeHexBinary ()
2227 XmlSerializer ser = new XmlSerializer (typeof (HexBinary));
2228 sw = new StringWriter ();
2229 XmlTextWriter xtw = new XmlTextWriter (sw);
2230 ser.Serialize (xtw, new HexBinary ());
2231 xtw.Close ();
2232 string expected = @"<?xml version=""1.0"" encoding=""utf-16""?><HexBinary xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" Data=""010203"" />";
2233 Assert.AreEqual (Infoset (expected), WriterText);
2234 HexBinary h = (HexBinary) ser.Deserialize (new StringReader (sw.ToString ()));
2235 Assert.AreEqual (new byte[] { 1, 2, 3 }, h.Data);
2238 [Test]
2239 [ExpectedException (typeof (InvalidOperationException))]
2240 public void XmlArrayAttributeOnInt ()
2242 new XmlSerializer (typeof (XmlArrayOnInt));
2245 [Test]
2246 [Category ("MobileNotWorking")]
2247 public void XmlArrayAttributeUnqualifiedWithNamespace ()
2249 new XmlSerializer (typeof (XmlArrayUnqualifiedWithNamespace));
2252 [Test]
2253 [Category ("MobileNotWorking")]
2254 public void XmlArrayItemAttributeUnqualifiedWithNamespace ()
2256 new XmlSerializer (typeof (XmlArrayItemUnqualifiedWithNamespace));
2259 [Test] // bug #78042
2260 public void XmlArrayAttributeOnArray ()
2262 XmlSerializer ser = new XmlSerializer (typeof (XmlArrayOnArray));
2263 sw = new StringWriter ();
2264 XmlTextWriter xtw = new XmlTextWriter (sw);
2265 ser.Serialize (xtw, new XmlArrayOnArray ());
2266 xtw.Close ();
2267 string expected = @"<?xml version=""1.0"" encoding=""utf-16""?><XmlArrayOnArray xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""urn:foo""><Sane xmlns=""""><string xmlns=""urn:foo"">foo</string><string xmlns=""urn:foo"">bar</string></Sane><Mids xmlns=""""><ArrayItemInXmlArray xmlns=""urn:foo""><Whee xmlns=""""><string xmlns=""urn:gyabo"">foo</string><string xmlns=""urn:gyabo"">bar</string></Whee></ArrayItemInXmlArray></Mids></XmlArrayOnArray>";
2268 Assert.AreEqual (Infoset (expected), WriterText);
2271 [Test]
2272 public void XmlArrayAttributeOnCollection ()
2274 XmlSerializer ser = new XmlSerializer (typeof (XmlArrayOnArrayList));
2275 XmlArrayOnArrayList inst = new XmlArrayOnArrayList ();
2276 inst.Sane.Add ("abc");
2277 inst.Sane.Add (1);
2278 sw = new StringWriter ();
2279 XmlTextWriter xtw = new XmlTextWriter (sw);
2280 ser.Serialize (xtw, inst);
2281 xtw.Close ();
2282 string expected = @"<?xml version=""1.0"" encoding=""utf-16""?><XmlArrayOnArrayList xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""urn:foo""><Sane xmlns=""""><anyType xsi:type=""xsd:string"" xmlns=""urn:foo"">abc</anyType><anyType xsi:type=""xsd:int"" xmlns=""urn:foo"">1</anyType></Sane></XmlArrayOnArrayList>";
2283 Assert.AreEqual (Infoset (expected), WriterText);
2286 [Test] // bug #338705
2287 public void SerializeTimeSpan ()
2289 // TimeSpan itself is not for duration. Hence it is just regarded as one of custom types.
2290 XmlSerializer ser = new XmlSerializer (typeof (TimeSpan));
2291 ser.Serialize (TextWriter.Null, TimeSpan.Zero);
2294 [Test]
2295 public void SerializeDurationToString ()
2297 XmlSerializer ser = new XmlSerializer (typeof (TimeSpanContainer1));
2298 ser.Serialize (TextWriter.Null, new TimeSpanContainer1 ());
2301 [Test]
2302 [ExpectedException (typeof (InvalidOperationException))]
2303 public void SerializeDurationToTimeSpan ()
2305 XmlSerializer ser = new XmlSerializer (typeof (TimeSpanContainer2));
2306 ser.Serialize (TextWriter.Null, new TimeSpanContainer2 ());
2309 [Test]
2310 [ExpectedException (typeof (InvalidOperationException))]
2311 public void SerializeInvalidDataType ()
2313 XmlSerializer ser = new XmlSerializer (typeof (InvalidTypeContainer));
2314 ser.Serialize (TextWriter.Null, new InvalidTypeContainer ());
2317 [Test]
2318 public void SerializeErrorneousIXmlSerializable ()
2320 Serialize (new ErrorneousGetSchema ());
2321 Assert.AreEqual ("<:ErrorneousGetSchema></>", Infoset (sw.ToString ()));
2324 [Test]
2325 public void DateTimeRoundtrip ()
2327 // bug #337729
2328 XmlSerializer ser = new XmlSerializer (typeof (DateTime));
2329 StringWriter sw = new StringWriter ();
2330 ser.Serialize (sw, DateTime.UtcNow);
2331 DateTime d = (DateTime) ser.Deserialize (new StringReader (sw.ToString ()));
2332 Assert.AreEqual (DateTimeKind.Utc, d.Kind);
2335 [Test]
2336 public void SupportIXmlSerializableImplicitlyConvertible ()
2338 XmlAttributes attrs = new XmlAttributes ();
2339 XmlElementAttribute attr = new XmlElementAttribute ();
2340 attr.ElementName = "XmlSerializable";
2341 attr.Type = typeof (XmlSerializableImplicitConvertible.XmlSerializable);
2342 attrs.XmlElements.Add (attr);
2343 XmlAttributeOverrides attrOverrides = new
2344 XmlAttributeOverrides ();
2345 attrOverrides.Add (typeof (XmlSerializableImplicitConvertible), "B", attrs);
2347 XmlSerializableImplicitConvertible x = new XmlSerializableImplicitConvertible ();
2348 new XmlSerializer (typeof (XmlSerializableImplicitConvertible), attrOverrides).Serialize (TextWriter.Null, x);
2351 [Test] // bug #566370
2352 public void SerializeEnumWithCSharpKeyword ()
2354 var ser = new XmlSerializer (typeof (DoxCompoundKind));
2355 for (int i = 0; i < 100; i++) // test serialization code generator
2356 ser.Serialize (Console.Out, DoxCompoundKind.@class);
2359 public enum DoxCompoundKind
2361 [XmlEnum("class")]
2362 @class,
2363 [XmlEnum("struct")]
2364 @struct,
2365 union,
2366 [XmlEnum("interface")]
2367 @interface,
2368 protocol,
2369 category,
2370 exception,
2371 file,
2372 [XmlEnum("namespace")]
2373 @namespace,
2374 group,
2375 page,
2376 example,
2380 #region GenericsSeralizationTests
2382 [Test]
2383 public void TestSerializeGenSimpleClassString ()
2385 GenSimpleClass<string> simple = new GenSimpleClass<string> ();
2386 Serialize (simple);
2387 Assert.AreEqual (Infoset ("<GenSimpleClassOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
2389 simple.something = "hello";
2391 Serialize (simple);
2392 Assert.AreEqual (Infoset ("<GenSimpleClassOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>hello</something></GenSimpleClassOfString>"), WriterText);
2395 [Test]
2396 public void TestSerializeGenSimpleClassBool ()
2398 GenSimpleClass<bool> simple = new GenSimpleClass<bool> ();
2399 Serialize (simple);
2400 Assert.AreEqual (Infoset ("<GenSimpleClassOfBoolean xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>false</something></GenSimpleClassOfBoolean>"), WriterText);
2402 simple.something = true;
2404 Serialize (simple);
2405 Assert.AreEqual (Infoset ("<GenSimpleClassOfBoolean xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>true</something></GenSimpleClassOfBoolean>"), WriterText);
2408 [Test]
2409 public void TestSerializeGenSimpleStructInt ()
2411 GenSimpleStruct<int> simple = new GenSimpleStruct<int> (0);
2412 Serialize (simple);
2413 Assert.AreEqual (Infoset ("<GenSimpleStructOfInt32 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>0</something></GenSimpleStructOfInt32>"), WriterText);
2415 simple.something = 123;
2417 Serialize (simple);
2418 Assert.AreEqual (Infoset ("<GenSimpleStructOfInt32 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something>123</something></GenSimpleStructOfInt32>"), WriterText);
2421 [Test]
2422 public void TestSerializeGenListClassString ()
2424 GenListClass<string> genlist = new GenListClass<string> ();
2425 Serialize (genlist);
2426 Assert.AreEqual (Infoset ("<GenListClassOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist></somelist></GenListClassOfString>"), WriterText);
2428 genlist.somelist.Add ("Value1");
2429 genlist.somelist.Add ("Value2");
2431 Serialize (genlist);
2432 Assert.AreEqual (Infoset ("<GenListClassOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist><string>Value1</string><string>Value2</string></somelist></GenListClassOfString>"), WriterText);
2435 [Test]
2436 public void TestSerializeGenListClassFloat ()
2438 GenListClass<float> genlist = new GenListClass<float> ();
2439 Serialize (genlist);
2440 Assert.AreEqual (Infoset ("<GenListClassOfSingle xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist></somelist></GenListClassOfSingle>"), WriterText);
2442 genlist.somelist.Add (1);
2443 genlist.somelist.Add (2.2F);
2445 Serialize (genlist);
2446 Assert.AreEqual (Infoset ("<GenListClassOfSingle xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist><float>1</float><float>2.2</float></somelist></GenListClassOfSingle>"), WriterText);
2449 [Test]
2450 public void TestSerializeGenListClassList ()
2452 GenListClass<GenListClass<int>> genlist = new GenListClass<GenListClass<int>> ();
2453 Serialize (genlist);
2454 Assert.AreEqual (Infoset ("<GenListClassOfGenListClassOfInt32 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist></somelist></GenListClassOfGenListClassOfInt32>"), WriterText);
2456 GenListClass<int> inlist1 = new GenListClass<int> ();
2457 inlist1.somelist.Add (1);
2458 inlist1.somelist.Add (2);
2459 GenListClass<int> inlist2 = new GenListClass<int> ();
2460 inlist2.somelist.Add (10);
2461 inlist2.somelist.Add (20);
2462 genlist.somelist.Add (inlist1);
2463 genlist.somelist.Add (inlist2);
2465 Serialize (genlist);
2466 Assert.AreEqual (Infoset ("<GenListClassOfGenListClassOfInt32 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist><GenListClassOfInt32><somelist><int>1</int><int>2</int></somelist></GenListClassOfInt32><GenListClassOfInt32><somelist><int>10</int><int>20</int></somelist></GenListClassOfInt32></somelist></GenListClassOfGenListClassOfInt32>"), WriterText);
2469 [Test]
2470 public void TestSerializeGenListClassArray ()
2472 GenListClass<GenArrayClass<char>> genlist = new GenListClass<GenArrayClass<char>> ();
2473 Serialize (genlist);
2474 Assert.AreEqual (Infoset ("<GenListClassOfGenArrayClassOfChar xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist></somelist></GenListClassOfGenArrayClassOfChar>"), WriterText);
2476 GenArrayClass<char> genarr1 = new GenArrayClass<char> ();
2477 genarr1.arr[0] = 'a';
2478 genarr1.arr[1] = 'b';
2479 genlist.somelist.Add (genarr1);
2480 GenArrayClass<char> genarr2 = new GenArrayClass<char> ();
2481 genarr2.arr[0] = 'd';
2482 genarr2.arr[1] = 'e';
2483 genarr2.arr[2] = 'f';
2484 genlist.somelist.Add (genarr2);
2486 Serialize (genlist);
2487 Assert.AreEqual (Infoset ("<GenListClassOfGenArrayClassOfChar xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist><GenArrayClassOfChar><arr><char>97</char><char>98</char><char>0</char></arr></GenArrayClassOfChar><GenArrayClassOfChar><arr><char>100</char><char>101</char><char>102</char></arr></GenArrayClassOfChar></somelist></GenListClassOfGenArrayClassOfChar>"), WriterText);
2490 [Test]
2491 public void TestSerializeGenTwoClassCharDouble ()
2493 GenTwoClass<char, double> gentwo = new GenTwoClass<char, double> ();
2494 Serialize (gentwo);
2495 Assert.AreEqual (Infoset ("<GenTwoClassOfCharDouble xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something1>0</something1><something2>0</something2></GenTwoClassOfCharDouble>"), WriterText);
2497 gentwo.something1 = 'a';
2498 gentwo.something2 = 2.2;
2500 Serialize (gentwo);
2501 Assert.AreEqual (Infoset ("<GenTwoClassOfCharDouble xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something1>97</something1><something2>2.2</something2></GenTwoClassOfCharDouble>"), WriterText);
2504 [Test]
2505 public void TestSerializeGenDerivedClassDecimalShort ()
2507 GenDerivedClass<decimal, short> derived = new GenDerivedClass<decimal, short> ();
2508 Serialize (derived);
2509 Assert.AreEqual (Infoset ("<GenDerivedClassOfDecimalInt16 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something2>0</something2><another1>0</another1><another2>0</another2></GenDerivedClassOfDecimalInt16>"), WriterText);
2511 derived.something1 = "Value1";
2512 derived.something2 = 1;
2513 derived.another1 = 1.1M;
2514 derived.another2 = -22;
2516 Serialize (derived);
2517 Assert.AreEqual (Infoset ("<GenDerivedClassOfDecimalInt16 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something1>Value1</something1><something2>1</something2><another1>1.1</another1><another2>-22</another2></GenDerivedClassOfDecimalInt16>"), WriterText);
2520 [Test]
2521 public void TestSerializeGenDerivedSecondClassByteUlong ()
2523 GenDerived2Class<byte, ulong> derived2 = new GenDerived2Class<byte, ulong> ();
2524 Serialize (derived2);
2525 Assert.AreEqual (Infoset ("<GenDerived2ClassOfByteUInt64 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something1>0</something1><something2>0</something2><another1>0</another1><another2>0</another2></GenDerived2ClassOfByteUInt64>"), WriterText);
2527 derived2.something1 = 1;
2528 derived2.something2 = 222;
2529 derived2.another1 = 111;
2530 derived2.another2 = 222222;
2532 Serialize (derived2);
2533 Assert.AreEqual (Infoset ("<GenDerived2ClassOfByteUInt64 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><something1>1</something1><something2>222</something2><another1>111</another1><another2>222222</another2></GenDerived2ClassOfByteUInt64>"), WriterText);
2536 [Test]
2537 public void TestSerializeGenNestedClass ()
2539 GenNestedClass<string, int>.InnerClass<bool> nested =
2540 new GenNestedClass<string, int>.InnerClass<bool> ();
2541 Serialize (nested);
2542 Assert.AreEqual (Infoset ("<InnerClassOfStringInt32Boolean xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><inner>0</inner><something>false</something></InnerClassOfStringInt32Boolean>"), WriterText);
2544 nested.inner = 5;
2545 nested.something = true;
2547 Serialize (nested);
2548 Assert.AreEqual (Infoset ("<InnerClassOfStringInt32Boolean xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><inner>5</inner><something>true</something></InnerClassOfStringInt32Boolean>"), WriterText);
2551 [Test]
2552 public void TestSerializeGenListClassListNested ()
2554 GenListClass<GenListClass<GenNestedClass<int, int>.InnerClass<string>>> genlist =
2555 new GenListClass<GenListClass<GenNestedClass<int, int>.InnerClass<string>>> ();
2556 Serialize (genlist);
2557 Assert.AreEqual (Infoset ("<GenListClassOfGenListClassOfInnerClassOfInt32Int32String xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist></somelist></GenListClassOfGenListClassOfInnerClassOfInt32Int32String>"), WriterText);
2559 GenListClass<GenNestedClass<int, int>.InnerClass<string>> inlist1 =
2560 new GenListClass<GenNestedClass<int, int>.InnerClass<string>> ();
2561 GenNestedClass<int, int>.InnerClass<string> inval1 = new GenNestedClass<int, int>.InnerClass<string> ();
2562 inval1.inner = 1;
2563 inval1.something = "ONE";
2564 inlist1.somelist.Add (inval1);
2565 GenNestedClass<int, int>.InnerClass<string> inval2 = new GenNestedClass<int, int>.InnerClass<string> ();
2566 inval2.inner = 2;
2567 inval2.something = "TWO";
2568 inlist1.somelist.Add (inval2);
2569 GenListClass<GenNestedClass<int, int>.InnerClass<string>> inlist2 =
2570 new GenListClass<GenNestedClass<int, int>.InnerClass<string>> ();
2571 GenNestedClass<int, int>.InnerClass<string> inval3 = new GenNestedClass<int, int>.InnerClass<string> ();
2572 inval3.inner = 30;
2573 inval3.something = "THIRTY";
2574 inlist2.somelist.Add (inval3);
2575 genlist.somelist.Add (inlist1);
2576 genlist.somelist.Add (inlist2);
2578 Serialize (genlist);
2579 Assert.AreEqual (Infoset ("<GenListClassOfGenListClassOfInnerClassOfInt32Int32String xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><somelist><GenListClassOfInnerClassOfInt32Int32String><somelist><InnerClassOfInt32Int32String><inner>1</inner><something>ONE</something></InnerClassOfInt32Int32String><InnerClassOfInt32Int32String><inner>2</inner><something>TWO</something></InnerClassOfInt32Int32String></somelist></GenListClassOfInnerClassOfInt32Int32String><GenListClassOfInnerClassOfInt32Int32String><somelist><InnerClassOfInt32Int32String><inner>30</inner><something>THIRTY</something></InnerClassOfInt32Int32String></somelist></GenListClassOfInnerClassOfInt32Int32String></somelist></GenListClassOfGenListClassOfInnerClassOfInt32Int32String>"), WriterText);
2582 public enum Myenum { one, two, three, four, five, six };
2583 [Test]
2584 public void TestSerializeGenArrayClassEnum ()
2586 GenArrayClass<Myenum> genarr = new GenArrayClass<Myenum> ();
2587 Serialize (genarr);
2588 Assert.AreEqual (Infoset ("<GenArrayClassOfMyenum xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><arr><Myenum>one</Myenum><Myenum>one</Myenum><Myenum>one</Myenum></arr></GenArrayClassOfMyenum>"), WriterText);
2590 genarr.arr[0] = Myenum.one;
2591 genarr.arr[1] = Myenum.three;
2592 genarr.arr[2] = Myenum.five;
2594 Serialize (genarr);
2595 Assert.AreEqual (Infoset ("<GenArrayClassOfMyenum xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><arr><Myenum>one</Myenum><Myenum>three</Myenum><Myenum>five</Myenum></arr></GenArrayClassOfMyenum>"), WriterText);
2598 [Test]
2599 public void TestSerializeGenArrayStruct ()
2601 GenArrayClass<GenSimpleStruct<uint>> genarr = new GenArrayClass<GenSimpleStruct<uint>> ();
2602 Serialize (genarr);
2603 Assert.AreEqual ("<:GenArrayClassOfGenSimpleStructOfUInt32 http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:arr><:GenSimpleStructOfUInt32><:something>0</></><:GenSimpleStructOfUInt32><:something>0</></><:GenSimpleStructOfUInt32><:something>0</></></></>", WriterText);
2605 GenSimpleStruct<uint> genstruct = new GenSimpleStruct<uint> ();
2606 genstruct.something = 111;
2607 genarr.arr[0] = genstruct;
2608 genstruct.something = 222;
2609 genarr.arr[1] = genstruct;
2610 genstruct.something = 333;
2611 genarr.arr[2] = genstruct;
2613 Serialize (genarr);
2614 Assert.AreEqual ("<:GenArrayClassOfGenSimpleStructOfUInt32 http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:arr><:GenSimpleStructOfUInt32><:something>111</></><:GenSimpleStructOfUInt32><:something>222</></><:GenSimpleStructOfUInt32><:something>333</></></></>", WriterText);
2617 [Test]
2618 public void TestSerializeGenArrayList ()
2620 GenArrayClass<GenListClass<string>> genarr = new GenArrayClass<GenListClass<string>> ();
2621 Serialize (genarr);
2622 Assert.AreEqual ("<:GenArrayClassOfGenListClassOfString http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:arr><:GenListClassOfString http://www.w3.org/2001/XMLSchema-instance:nil='true'></><:GenListClassOfString http://www.w3.org/2001/XMLSchema-instance:nil='true'></><:GenListClassOfString http://www.w3.org/2001/XMLSchema-instance:nil='true'></></></>", WriterText);
2624 GenListClass<string> genlist1 = new GenListClass<string> ();
2625 genlist1.somelist.Add ("list1-val1");
2626 genlist1.somelist.Add ("list1-val2");
2627 genarr.arr[0] = genlist1;
2628 GenListClass<string> genlist2 = new GenListClass<string> ();
2629 genlist2.somelist.Add ("list2-val1");
2630 genlist2.somelist.Add ("list2-val2");
2631 genlist2.somelist.Add ("list2-val3");
2632 genlist2.somelist.Add ("list2-val4");
2633 genarr.arr[1] = genlist2;
2634 GenListClass<string> genlist3 = new GenListClass<string> ();
2635 genlist3.somelist.Add ("list3val");
2636 genarr.arr[2] = genlist3;
2638 Serialize (genarr);
2639 Assert.AreEqual ("<:GenArrayClassOfGenListClassOfString http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:arr><:GenListClassOfString><:somelist><:string>list1-val1</><:string>list1-val2</></></><:GenListClassOfString><:somelist><:string>list2-val1</><:string>list2-val2</><:string>list2-val3</><:string>list2-val4</></></><:GenListClassOfString><:somelist><:string>list3val</></></></></>", WriterText);
2642 [Test]
2643 public void TestSerializeGenComplexStruct ()
2645 GenComplexStruct<int, string> complex = new GenComplexStruct<int, string> (0);
2646 Serialize (complex);
2647 Assert.AreEqual ("<:GenComplexStructOfInt32String http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:something>0</><:simpleclass><:something>0</></><:simplestruct><:something>0</></><:listclass><:somelist></></><:arrayclass><:arr><:int>0</><:int>0</><:int>0</></></><:twoclass><:something1>0</></><:derivedclass><:something2>0</><:another1>0</></><:derived2><:something1>0</><:another1>0</></><:nestedouter><:outer>0</></><:nestedinner><:something>0</></></>", WriterText);
2649 complex.something = 123;
2650 complex.simpleclass.something = 456;
2651 complex.simplestruct.something = 789;
2652 GenListClass<int> genlist = new GenListClass<int> ();
2653 genlist.somelist.Add (100);
2654 genlist.somelist.Add (200);
2655 complex.listclass = genlist;
2656 GenArrayClass<int> genarr = new GenArrayClass<int> ();
2657 genarr.arr[0] = 11;
2658 genarr.arr[1] = 22;
2659 genarr.arr[2] = 33;
2660 complex.arrayclass = genarr;
2661 complex.twoclass.something1 = 10;
2662 complex.twoclass.something2 = "Ten";
2663 complex.derivedclass.another1 = 1;
2664 complex.derivedclass.another2 = "one";
2665 complex.derivedclass.something1 = "two";
2666 complex.derivedclass.something2 = 2;
2667 complex.derived2.another1 = 3;
2668 complex.derived2.another2 = "three";
2669 complex.derived2.something1 = 4;
2670 complex.derived2.something2 = "four";
2671 complex.nestedouter.outer = 5;
2672 complex.nestedinner.inner = "six";
2673 complex.nestedinner.something = 6;
2675 Serialize (complex);
2676 Assert.AreEqual ("<:GenComplexStructOfInt32String http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:something>123</><:simpleclass><:something>456</></><:simplestruct><:something>789</></><:listclass><:somelist><:int>100</><:int>200</></></><:arrayclass><:arr><:int>11</><:int>22</><:int>33</></></><:twoclass><:something1>10</><:something2>Ten</></><:derivedclass><:something1>two</><:something2>2</><:another1>1</><:another2>one</></><:derived2><:something1>4</><:something2>four</><:another1>3</><:another2>three</></><:nestedouter><:outer>5</></><:nestedinner><:inner>six</><:something>6</></></>", WriterText);
2679 [Test]
2680 public void TestSerializeStreamPreserveUTFChars () {
2681 string foo = "BÄR";
2682 XmlSerializer serializer = new XmlSerializer (typeof (string));
2684 MemoryStream stream = new MemoryStream ();
2686 serializer.Serialize (stream, foo);
2687 stream.Position = 0;
2688 foo = (string) serializer.Deserialize (stream);
2689 Assert.AreEqual("BÄR", foo);
2692 [Test] // bug #80759
2693 public void HasNullableField ()
2695 Bug80759 foo = new Bug80759 ();
2696 foo.Test = "BAR";
2697 foo.NullableInt = 10;
2699 XmlSerializer serializer = new XmlSerializer (typeof (Bug80759));
2701 MemoryStream stream = new MemoryStream ();
2703 serializer.Serialize (stream, foo);
2704 stream.Position = 0;
2705 foo = (Bug80759) serializer.Deserialize (stream);
2708 [Test] // bug #80759, with fieldSpecified.
2709 [ExpectedException (typeof (InvalidOperationException))]
2710 [Category ("NotWorking")]
2711 public void HasFieldSpecifiedButIrrelevant ()
2713 Bug80759_2 foo = new Bug80759_2 ();
2714 foo.Test = "BAR";
2715 foo.NullableInt = 10;
2717 XmlSerializer serializer = new XmlSerializer (typeof (Bug80759_2));
2719 MemoryStream stream = new MemoryStream ();
2721 serializer.Serialize (stream, foo);
2722 stream.Position = 0;
2723 foo = (Bug80759_2) serializer.Deserialize (stream);
2726 [Test]
2727 public void HasNullableField2 ()
2729 Bug80759 foo = new Bug80759 ();
2730 foo.Test = "BAR";
2731 foo.NullableInt = 10;
2733 XmlSerializer serializer = new XmlSerializer (typeof (Bug80759));
2735 MemoryStream stream = new MemoryStream ();
2737 serializer.Serialize (stream, foo);
2738 stream.Position = 0;
2739 foo = (Bug80759) serializer.Deserialize (stream);
2741 Assert.AreEqual ("BAR", foo.Test, "#1");
2742 Assert.AreEqual (10, foo.NullableInt, "#2");
2744 foo.NullableInt = null;
2745 stream = new MemoryStream ();
2746 serializer.Serialize (stream, foo);
2747 stream.Position = 0;
2748 foo = (Bug80759) serializer.Deserialize (stream);
2750 Assert.AreEqual ("BAR", foo.Test, "#3");
2751 Assert.IsNull (foo.NullableInt, "#4");
2754 [Test]
2755 public void SupportPrivateCtorOnly ()
2757 XmlSerializer xs =
2758 new XmlSerializer (typeof (PrivateCtorOnly));
2759 StringWriter sw = new StringWriter ();
2760 xs.Serialize (sw, PrivateCtorOnly.Instance);
2761 xs.Deserialize (new StringReader (sw.ToString ()));
2764 [Test]
2765 public void XmlSchemaProviderQNameBecomesRootName ()
2767 xs = new XmlSerializer (typeof (XmlSchemaProviderQNameBecomesRootNameType));
2768 Serialize (new XmlSchemaProviderQNameBecomesRootNameType ());
2769 Assert.AreEqual (Infoset ("<foo />"), WriterText);
2770 xs.Deserialize (new StringReader ("<foo/>"));
2773 [Test]
2774 public void XmlSchemaProviderQNameBecomesRootName2 ()
2776 string xml = "<XmlSchemaProviderQNameBecomesRootNameType2 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Foo><foo /></Foo></XmlSchemaProviderQNameBecomesRootNameType2>";
2777 xs = new XmlSerializer (typeof (XmlSchemaProviderQNameBecomesRootNameType2));
2778 Serialize (new XmlSchemaProviderQNameBecomesRootNameType2 ());
2779 Assert.AreEqual (Infoset (xml), WriterText);
2780 xs.Deserialize (new StringReader (xml));
2783 [Test]
2784 public void XmlAnyElementForObjects () // bug #553032
2786 new XmlSerializer (typeof (XmlAnyElementForObjectsType));
2789 [Test]
2790 [ExpectedException (typeof (InvalidOperationException))]
2791 public void XmlAnyElementForObjects2 () // bug #553032-2
2793 new XmlSerializer (typeof (XmlAnyElementForObjectsType)).Serialize (TextWriter.Null, new XmlAnyElementForObjectsType ());
2797 public class Bug2893 {
2798 public Bug2893 ()
2800 Contents = new XmlDataDocument();
2803 [XmlAnyElement("Contents")]
2804 public XmlNode Contents;
2807 // Bug Xamarin #2893
2808 [Test]
2809 public void XmlAnyElementForXmlNode ()
2811 var obj = new Bug2893 ();
2812 XmlSerializer mySerializer = new XmlSerializer(typeof(Bug2893));
2813 XmlWriterSettings settings = new XmlWriterSettings();
2815 var xsn = new XmlSerializerNamespaces();
2816 xsn.Add(string.Empty, string.Empty);
2818 byte[] buffer = new byte[2048];
2819 var ms = new MemoryStream(buffer);
2820 using (var xw = XmlWriter.Create(ms, settings))
2822 mySerializer.Serialize(xw, obj, xsn);
2823 xw.Flush();
2826 mySerializer.Serialize(ms, obj);
2829 [Test]
2830 public void XmlRootOverridesSchemaProviderQName ()
2832 var obj = new XmlRootOverridesSchemaProviderQNameType ();
2834 XmlSerializer xs = new XmlSerializer (obj.GetType ());
2836 var sw = new StringWriter ();
2837 using (XmlWriter xw = XmlWriter.Create (sw))
2838 xs.Serialize (xw, obj);
2839 Assert.IsTrue (sw.ToString ().IndexOf ("foo") > 0, "#1");
2842 public class AnotherArrayListType
2844 [XmlAttribute]
2845 public string one = "aaa";
2846 [XmlAttribute]
2847 public string another = "bbb";
2850 public class DerivedArrayListType : AnotherArrayListType
2855 public class ClassWithArrayList
2857 [XmlElement (Type = typeof(int), ElementName = "int_elem")]
2858 [XmlElement (Type = typeof(string), ElementName = "string_elem")]
2859 [XmlElement (Type = typeof(AnotherArrayListType), ElementName = "another_elem")]
2860 [XmlElement (Type = typeof(DerivedArrayListType), ElementName = "derived_elem")]
2861 public ArrayList list;
2864 public class ClassWithArray
2866 [XmlElement (Type = typeof(int), ElementName = "int_elem")]
2867 [XmlElement (Type = typeof(string), ElementName = "string_elem")]
2868 [XmlElement (Type = typeof(AnotherArrayListType), ElementName = "another_elem")]
2869 [XmlElement (Type = typeof(DerivedArrayListType), ElementName = "derived_elem")]
2870 public object[] list;
2874 [Test]
2875 public void MultipleXmlElementAttributesOnArrayList()
2877 var test = new ClassWithArrayList();
2879 test.list = new ArrayList();
2880 test.list.Add(3);
2881 test.list.Add("apepe");
2882 test.list.Add(new AnotherArrayListType());
2883 test.list.Add(new DerivedArrayListType());
2885 Serialize(test);
2886 var expected_text = "<:ClassWithArrayList http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:int_elem>3</><:string_elem>apepe</><:another_elem :another='bbb' :one='aaa'></><:derived_elem :another='bbb' :one='aaa'></></>";
2888 Assert.AreEqual(WriterText, expected_text, WriterText);
2891 [Test]
2892 public void MultipleXmlElementAttributesOnArray()
2894 var test = new ClassWithArray();
2896 test.list = new object[] { 3, "apepe", new AnotherArrayListType(), new DerivedArrayListType() };
2898 Serialize(test);
2899 var expected_text = "<:ClassWithArray http://www.w3.org/2000/xmlns/:xsd='http://www.w3.org/2001/XMLSchema' http://www.w3.org/2000/xmlns/:xsi='http://www.w3.org/2001/XMLSchema-instance'><:int_elem>3</><:string_elem>apepe</><:another_elem :another='bbb' :one='aaa'></><:derived_elem :another='bbb' :one='aaa'></></>";
2901 Assert.AreEqual(WriterText, expected_text, WriterText);
2905 #endregion //GenericsSeralizationTests
2906 #region XmlInclude on abstract class tests (Bug #18558)
2907 [Test]
2908 public void TestSerializeIntermediateType ()
2910 string expectedXml = "<ContainerTypeForTest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><XmlIntermediateType intermediate=\"false\"/></ContainerTypeForTest>";
2911 var obj = new ContainerTypeForTest();
2912 obj.MemberToUseInclude = new IntermediateTypeForTest ();
2913 Serialize (obj);
2914 Assert.AreEqual (Infoset (expectedXml), WriterText, "Serialized Output : " + WriterText);
2917 [Test]
2918 public void TestSerializeSecondType ()
2920 string expectedXml = "<ContainerTypeForTest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><XmlSecondType intermediate=\"false\"/></ContainerTypeForTest>";
2921 var obj = new ContainerTypeForTest();
2922 obj.MemberToUseInclude = new SecondDerivedTypeForTest ();
2923 Serialize (obj);
2924 Assert.AreEqual (Infoset (expectedXml), WriterText, "Serialized Output : " + WriterText);
2926 #endregion
2927 public class XmlArrayOnInt
2929 [XmlArray]
2930 public int Bogus;
2933 public class XmlArrayUnqualifiedWithNamespace
2935 [XmlArray (Namespace = "", Form = XmlSchemaForm.Unqualified)]
2936 public ArrayList Sane = new ArrayList ();
2939 public class XmlArrayItemUnqualifiedWithNamespace
2941 [XmlArrayItem ("foo", Namespace = "", Form = XmlSchemaForm.Unqualified)]
2942 public ArrayList Sane = new ArrayList ();
2945 [XmlRoot (Namespace = "urn:foo")]
2946 public class XmlArrayOnArrayList
2948 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2949 public ArrayList Sane = new ArrayList ();
2952 [XmlRoot (Namespace = "urn:foo")]
2953 public class XmlArrayOnArray
2955 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2956 public string[] Sane = new string[] { "foo", "bar" };
2958 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2959 public ArrayItemInXmlArray[] Mids =
2960 new ArrayItemInXmlArray[] { new ArrayItemInXmlArray () };
2963 [XmlType (Namespace = "urn:gyabo")]
2964 public class ArrayItemInXmlArray
2966 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2967 public string[] Whee = new string[] { "foo", "bar" };
2970 [XmlRoot ("Base64Binary")]
2971 public class Base64Binary
2973 [XmlAttribute (DataType = "base64Binary")]
2974 public byte [] Data = new byte [] {1, 2, 3};
2977 [XmlRoot ("HexBinary")]
2978 public class HexBinary
2980 [XmlAttribute (DataType = "hexBinary")]
2981 public byte[] Data = new byte[] { 1, 2, 3 };
2984 [XmlRoot ("PrivateCtorOnly")]
2985 public class PrivateCtorOnly
2987 public static PrivateCtorOnly Instance = new PrivateCtorOnly ();
2988 private PrivateCtorOnly ()
2993 public class CDataTextNodesType
2995 public CDataTextNodesInternal foo;
2998 public class CDataTextNodesInternal
3000 [XmlText]
3001 public string Value;
3004 public class InvalidTypeContainer
3006 [XmlElement (DataType = "invalid")]
3007 public string InvalidTypeItem = "aaa";
3010 public class TimeSpanContainer1
3012 [XmlElement (DataType = "duration")]
3013 public string StringDuration = "aaa";
3016 public class TimeSpanContainer2
3018 [XmlElement (DataType = "duration")]
3019 public TimeSpan StringDuration = TimeSpan.FromSeconds (1);
3022 public class Bug80759
3024 public string Test;
3025 public int? NullableInt;
3028 public class Bug80759_2
3030 public string Test;
3031 public int? NullableInt;
3033 [XmlIgnore]
3034 public bool NullableIntSpecified {
3035 get { return NullableInt.HasValue; }
3039 [XmlSchemaProvider ("GetXsdType")]
3040 public class XmlSchemaProviderQNameBecomesRootNameType : IXmlSerializable
3042 public XmlSchema GetSchema ()
3044 return null;
3047 public void ReadXml (XmlReader reader)
3049 reader.Skip ();
3052 public void WriteXml (XmlWriter writer)
3056 public static XmlQualifiedName GetXsdType (XmlSchemaSet xss)
3058 if (xss.Count == 0) {
3059 XmlSchema xs = new XmlSchema ();
3060 XmlSchemaComplexType ct = new XmlSchemaComplexType ();
3061 ct.Name = "foo";
3062 xs.Items.Add (ct);
3063 xss.Add (xs);
3065 return new XmlQualifiedName ("foo");
3069 public class XmlSchemaProviderQNameBecomesRootNameType2
3071 [XmlArrayItem (typeof (XmlSchemaProviderQNameBecomesRootNameType))]
3072 public object [] Foo = new object [] {new XmlSchemaProviderQNameBecomesRootNameType ()};
3075 public class XmlAnyElementForObjectsType
3077 [XmlAnyElement]
3078 public object [] arr = new object [] {3,4,5};
3081 [XmlRoot ("foo")]
3082 [XmlSchemaProvider ("GetSchema")]
3083 public class XmlRootOverridesSchemaProviderQNameType : IXmlSerializable
3085 public static XmlQualifiedName GetSchema (XmlSchemaSet xss)
3087 var xs = new XmlSchema ();
3088 var xse = new XmlSchemaComplexType () { Name = "bar" };
3089 xs.Items.Add (xse);
3090 xss.Add (xs);
3091 return new XmlQualifiedName ("bar");
3094 XmlSchema IXmlSerializable.GetSchema ()
3096 return null;
3099 void IXmlSerializable.ReadXml (XmlReader reader)
3102 void IXmlSerializable.WriteXml (XmlWriter writer)
3108 void CDataTextNodes_BadNode (object s, XmlNodeEventArgs e)
3110 Assert.Fail ();
3113 // Helper methods
3115 public static string Infoset (string sx)
3117 XmlDocument doc = new XmlDocument ();
3118 doc.LoadXml (sx);
3119 StringBuilder sb = new StringBuilder ();
3120 GetInfoset (doc.DocumentElement, sb);
3121 return sb.ToString ();
3124 public static string Infoset (XmlNode nod)
3126 StringBuilder sb = new StringBuilder ();
3127 GetInfoset (nod, sb);
3128 return sb.ToString ();
3131 static void GetInfoset (XmlNode nod, StringBuilder sb)
3133 switch (nod.NodeType) {
3134 case XmlNodeType.Attribute:
3135 if (nod.LocalName == "xmlns" && nod.NamespaceURI == "http://www.w3.org/2000/xmlns/") return;
3136 sb.Append (" " + nod.NamespaceURI + ":" + nod.LocalName + "='" + nod.Value + "'");
3137 break;
3139 case XmlNodeType.Element:
3140 XmlElement elem = (XmlElement) nod;
3141 sb.Append ("<" + elem.NamespaceURI + ":" + elem.LocalName);
3143 ArrayList ats = new ArrayList ();
3144 foreach (XmlAttribute at in elem.Attributes)
3145 ats.Add (at.LocalName + " " + at.NamespaceURI);
3147 ats.Sort ();
3149 foreach (string name in ats) {
3150 string[] nn = name.Split (' ');
3151 GetInfoset (elem.Attributes[nn[0], nn[1]], sb);
3154 sb.Append (">");
3155 foreach (XmlNode cn in elem.ChildNodes)
3156 GetInfoset (cn, sb);
3157 sb.Append ("</>");
3158 break;
3160 default:
3161 sb.Append (nod.OuterXml);
3162 break;
3166 static XmlTypeMapping CreateSoapMapping (Type type)
3168 SoapReflectionImporter importer = new SoapReflectionImporter ();
3169 return importer.ImportTypeMapping (type);
3172 static XmlTypeMapping CreateSoapMapping (Type type, SoapAttributeOverrides ao)
3174 SoapReflectionImporter importer = new SoapReflectionImporter (ao);
3175 return importer.ImportTypeMapping (type);
3178 static XmlTypeMapping CreateSoapMapping (Type type, SoapAttributeOverrides ao, string defaultNamespace)
3180 SoapReflectionImporter importer = new SoapReflectionImporter (ao, defaultNamespace);
3181 return importer.ImportTypeMapping (type);
3184 [XmlSchemaProvider (null, IsAny = true)]
3185 public class AnySchemaProviderClass : IXmlSerializable {
3187 public string Text;
3189 void IXmlSerializable.WriteXml (XmlWriter writer)
3191 writer.WriteElementString ("text", Text);
3194 void IXmlSerializable.ReadXml (XmlReader reader)
3196 Text = reader.ReadElementString ("text");
3199 XmlSchema IXmlSerializable.GetSchema ()
3201 return null;
3205 [Test]
3206 public void SerializeAnySchemaProvider ()
3208 string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
3209 Environment.NewLine + "<text>test</text>";
3211 var ser = new XmlSerializer (typeof (AnySchemaProviderClass));
3213 var obj = new AnySchemaProviderClass {
3214 Text = "test",
3217 using (var t = new StringWriter ()) {
3218 ser.Serialize (t, obj);
3219 Assert.AreEqual (expected, t.ToString ());
3223 [Test]
3224 public void DeserializeAnySchemaProvider ()
3226 string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
3227 Environment.NewLine + "<text>test</text>";
3229 var ser = new XmlSerializer (typeof (AnySchemaProviderClass));
3231 using (var t = new StringReader (expected)) {
3232 var obj = (AnySchemaProviderClass) ser.Deserialize (t);
3233 Assert.AreEqual ("test", obj.Text);
3237 public class SubNoParameterlessConstructor : NoParameterlessConstructor
3239 public SubNoParameterlessConstructor ()
3240 : base ("")
3245 public class NoParameterlessConstructor
3247 [XmlElement ("Text")]
3248 public string Text;
3250 public NoParameterlessConstructor (string parameter)
3255 [Test]
3256 public void BaseClassWithoutParameterlessConstructor ()
3258 var ser = new XmlSerializer (typeof (SubNoParameterlessConstructor));
3260 var obj = new SubNoParameterlessConstructor {
3261 Text = "test",
3264 using (var w = new StringWriter ()) {
3265 ser.Serialize (w, obj);
3266 using (var r = new StringReader ( w.ToString ())) {
3267 var desObj = (SubNoParameterlessConstructor) ser.Deserialize (r);
3268 Assert.AreEqual (obj.Text, desObj.Text);
3273 public class ClassWithXmlAnyElement
3275 [XmlAnyElement ("Contents")]
3276 public XmlNode Contents;
3279 [Test] // bug #3211
3280 public void TestClassWithXmlAnyElement ()
3282 var d = new XmlDocument ();
3283 var e = d.CreateElement ("Contents");
3284 e.AppendChild (d.CreateElement ("SomeElement"));
3286 var c = new ClassWithXmlAnyElement {
3287 Contents = e,
3290 var ser = new XmlSerializer (typeof (ClassWithXmlAnyElement));
3291 using (var sw = new StringWriter ())
3292 ser.Serialize (sw, c);
3295 [Test]
3296 public void ClassWithImplicitlyConvertibleElement ()
3298 var ser = new XmlSerializer (typeof (ObjectWithElementRequiringImplicitCast));
3300 var obj = new ObjectWithElementRequiringImplicitCast ("test");
3302 using (var w = new StringWriter ()) {
3303 ser.Serialize (w, obj);
3304 using (var r = new StringReader ( w.ToString ())) {
3305 var desObj = (ObjectWithElementRequiringImplicitCast) ser.Deserialize (r);
3306 Assert.AreEqual (obj.Object.Text, desObj.Object.Text);
3311 public class ClassWithOptionalMethods
3313 private readonly bool shouldSerializeX;
3314 private readonly bool xSpecified;
3316 [XmlAttribute]
3317 public int X { get; set; }
3319 public bool ShouldSerializeX () { return shouldSerializeX; }
3321 public bool XSpecified
3323 get { return xSpecified; }
3326 public ClassWithOptionalMethods ()
3330 public ClassWithOptionalMethods (int x, bool shouldSerializeX, bool xSpecified)
3332 this.X = x;
3333 this.shouldSerializeX = shouldSerializeX;
3334 this.xSpecified = xSpecified;
3338 [Test]
3339 public void OptionalMethods ()
3341 var ser = new XmlSerializer (typeof (ClassWithOptionalMethods));
3343 var expectedValueWithoutX = Infoset ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
3344 "<ClassWithOptionalMethods xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" />");
3346 var expectedValueWithX = Infoset ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
3347 "<ClassWithOptionalMethods xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" X=\"11\" />");
3349 using (var t = new StringWriter ()) {
3350 var obj = new ClassWithOptionalMethods (11, false, false);
3351 ser.Serialize (t, obj);
3352 Assert.AreEqual (expectedValueWithoutX, Infoset (t.ToString ()));
3355 using (var t = new StringWriter ()) {
3356 var obj = new ClassWithOptionalMethods (11, true, false);
3357 ser.Serialize (t, obj);
3358 Assert.AreEqual (expectedValueWithoutX, Infoset (t.ToString ()));
3361 using (var t = new StringWriter ()) {
3362 var obj = new ClassWithOptionalMethods (11, false, true);
3363 ser.Serialize (t, obj);
3364 Assert.AreEqual (expectedValueWithoutX, Infoset (t.ToString ()));
3367 using (var t = new StringWriter ()) {
3368 var obj = new ClassWithOptionalMethods (11, true, true);
3369 ser.Serialize (t, obj);
3370 Assert.AreEqual (expectedValueWithX, Infoset (t.ToString ()));
3374 public class ClassWithShouldSerializeGeneric
3376 [XmlAttribute]
3377 public int X { get; set; }
3379 public bool ShouldSerializeX<T> () { return false; }
3382 [Test]
3383 [Category("NotWorking")]
3384 public void ShouldSerializeGeneric ()
3386 var ser = new XmlSerializer (typeof (ClassWithShouldSerializeGeneric));
3388 var expectedValueWithX = Infoset ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
3389 "<ClassWithShouldSerializeGeneric xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" X=\"11\" />");
3391 using (var t = new StringWriter ()) {
3392 var obj = new ClassWithShouldSerializeGeneric { X = 11 };
3393 ser.Serialize (t, obj);
3394 Assert.AreEqual (expectedValueWithX, Infoset (t.ToString ()));
3398 [Test]
3399 public void NullableArrayItems ()
3401 var ser = new XmlSerializer (typeof (ObjectWithNullableArrayItems));
3403 var obj = new ObjectWithNullableArrayItems ();
3404 obj.Elements = new List <SimpleClass> ();
3405 obj.Elements.Add (new SimpleClass { something = "Hello" });
3406 obj.Elements.Add (null);
3407 obj.Elements.Add (new SimpleClass { something = "World" });
3409 using (var w = new StringWriter ()) {
3410 ser.Serialize (w, obj);
3411 using (var r = new StringReader ( w.ToString ())) {
3412 var desObj = (ObjectWithNullableArrayItems) ser.Deserialize (r);
3413 Assert.IsNull (desObj.Elements [1]);
3418 [Test]
3419 public void NonNullableArrayItems ()
3421 var ser = new XmlSerializer (typeof (ObjectWithNonNullableArrayItems));
3423 var obj = new ObjectWithNonNullableArrayItems ();
3424 obj.Elements = new List <SimpleClass> ();
3425 obj.Elements.Add (new SimpleClass { something = "Hello" });
3426 obj.Elements.Add (null);
3427 obj.Elements.Add (new SimpleClass { something = "World" });
3429 using (var w = new StringWriter ()) {
3430 ser.Serialize (w, obj);
3431 using (var r = new StringReader ( w.ToString ())) {
3432 var desObj = (ObjectWithNonNullableArrayItems) ser.Deserialize (r);
3433 Assert.IsNotNull (desObj.Elements [1]);
3438 [Test]
3439 public void NotSpecifiedNullableArrayItems ()
3441 var ser = new XmlSerializer (typeof (ObjectWithNotSpecifiedNullableArrayItems));
3443 var obj = new ObjectWithNotSpecifiedNullableArrayItems ();
3444 obj.Elements = new List <SimpleClass> ();
3445 obj.Elements.Add (new SimpleClass { something = "Hello" });
3446 obj.Elements.Add (null);
3447 obj.Elements.Add (new SimpleClass { something = "World" });
3449 using (var w = new StringWriter ()) {
3450 ser.Serialize (w, obj);
3451 using (var r = new StringReader ( w.ToString ())) {
3452 var desObj = (ObjectWithNotSpecifiedNullableArrayItems) ser.Deserialize (r);
3453 Assert.IsNull (desObj.Elements [1]);
3458 private static void TestClassWithDefaultTextNotNullAux (string value, string expected)
3460 var obj = new ClassWithDefaultTextNotNull (value);
3461 var ser = new XmlSerializer (typeof (ClassWithDefaultTextNotNull));
3463 using (var mstream = new MemoryStream ())
3464 using (var writer = new XmlTextWriter (mstream, Encoding.ASCII)) {
3465 ser.Serialize (writer, obj);
3467 mstream.Seek (0, SeekOrigin.Begin);
3468 using (var reader = new XmlTextReader (mstream)) {
3469 var result = (ClassWithDefaultTextNotNull) ser.Deserialize (reader);
3470 Assert.AreEqual (expected, result.Value);
3475 [Test]
3476 public void TestClassWithDefaultTextNotNull ()
3478 TestClassWithDefaultTextNotNullAux ("my_text", "my_text");
3479 TestClassWithDefaultTextNotNullAux ("", ClassWithDefaultTextNotNull.DefaultValue);
3480 TestClassWithDefaultTextNotNullAux (null, ClassWithDefaultTextNotNull.DefaultValue);
3484 // Test generated serialization code.
3485 public class XmlSerializerGeneratorTests : XmlSerializerTests {
3487 private FieldInfo backgroundGeneration;
3488 private FieldInfo generationThreshold;
3489 private FieldInfo generatorFallback;
3491 private bool backgroundGenerationOld;
3492 private int generationThresholdOld;
3493 private bool generatorFallbackOld;
3495 [SetUp]
3496 public void SetUp ()
3498 // Make sure XmlSerializer static constructor is called
3499 XmlSerializer.FromTypes (new Type [] {});
3501 const BindingFlags binding = BindingFlags.Static | BindingFlags.NonPublic;
3502 backgroundGeneration = typeof (XmlSerializer).GetField ("backgroundGeneration", binding);
3503 generationThreshold = typeof (XmlSerializer).GetField ("generationThreshold", binding);
3504 generatorFallback = typeof (XmlSerializer).GetField ("generatorFallback", binding);
3506 if (backgroundGeneration == null)
3507 Assert.Ignore ("Unable to access field backgroundGeneration");
3508 if (generationThreshold == null)
3509 Assert.Ignore ("Unable to access field generationThreshold");
3510 if (generatorFallback == null)
3511 Assert.Ignore ("Unable to access field generatorFallback");
3513 backgroundGenerationOld = (bool) backgroundGeneration.GetValue (null);
3514 generationThresholdOld = (int) generationThreshold.GetValue (null);
3515 generatorFallbackOld = (bool) generatorFallback.GetValue (null);
3517 backgroundGeneration.SetValue (null, false);
3518 generationThreshold.SetValue (null, 0);
3519 generatorFallback.SetValue (null, false);
3522 [TearDown]
3523 public void TearDown ()
3525 if (backgroundGeneration == null || generationThreshold == null || generatorFallback == null)
3526 return;
3528 backgroundGeneration.SetValue (null, backgroundGenerationOld);
3529 generationThreshold.SetValue (null, generationThresholdOld);
3530 generatorFallback.SetValue (null, generatorFallbackOld);
3534 #region XmlInclude on abstract class test classes
3536 [XmlType]
3537 public class ContainerTypeForTest
3539 [XmlElement ("XmlSecondType", typeof (SecondDerivedTypeForTest))]
3540 [XmlElement ("XmlIntermediateType", typeof (IntermediateTypeForTest))]
3541 [XmlElement ("XmlFirstType", typeof (FirstDerivedTypeForTest))]
3542 public AbstractTypeForTest MemberToUseInclude { get; set; }
3545 [XmlInclude (typeof (SecondDerivedTypeForTest))]
3546 [XmlInclude (typeof (IntermediateTypeForTest))]
3547 [XmlInclude (typeof (FirstDerivedTypeForTest))]
3548 public abstract class AbstractTypeForTest
3552 public class IntermediateTypeForTest : AbstractTypeForTest
3554 [XmlAttribute (AttributeName = "intermediate")]
3555 public bool IntermediateMember { get; set; }
3558 public class FirstDerivedTypeForTest : AbstractTypeForTest
3560 public string FirstMember { get; set; }
3563 public class SecondDerivedTypeForTest : IntermediateTypeForTest
3565 public string SecondMember { get; set; }
3567 #endregion