2 // System.Xml.XmlSerializerTests
5 // Erik LeBel <eriklebel@yahoo.ca>
6 // Hagit Yidov <hagity@mainsoft.com>
9 // (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
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.
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
29 using System.Collections;
30 using System.Globalization;
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
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";
58 private void SetUpWriter ()
60 sw = new StringWriter ();
61 xtw = new XmlTextWriter (sw);
63 xtw.Formatting = Formatting.None;
66 private string WriterText
70 string val = sw.GetStringBuilder ().ToString ();
71 int offset = val.IndexOf ('>') + 1;
72 val = val.Substring (offset);
77 private void Serialize (object o)
80 xs = new XmlSerializer (o.GetType ());
81 xs.Serialize (xtw, o);
84 private void Serialize (object o, Type type)
87 xs = new XmlSerializer (type);
88 xs.Serialize (xtw, o);
91 private void Serialize (object o, XmlSerializerNamespaces ns)
94 xs = new XmlSerializer (o.GetType ());
95 xs.Serialize (xtw, o, ns);
98 private void Serialize (object o, XmlAttributeOverrides ao)
101 xs = new XmlSerializer (o.GetType (), ao);
102 xs.Serialize (xtw, o);
105 private void Serialize (object o, XmlAttributeOverrides ao, string defaultNamespace)
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)
116 xs = new XmlSerializer (o.GetType (), root);
117 xs.Serialize (xtw, o);
120 private void Serialize (object o, XmlTypeMapping typeMapping)
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);
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);
144 xs = new XmlSerializer (mapping);
145 xs.Serialize (xtw, o);
148 private void SerializeEncoded (object o, Type type)
150 XmlTypeMapping mapping = CreateSoapMapping (type);
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);
164 #if USE_VERSION_1_1 // It doesn't pass on MS.NET 1.1.
166 public void TestConstructor()
168 XmlSerializer ser = new XmlSerializer (null, "");
173 // test basic types ////////////////////////////////////////////////////////
175 public void TestSerializeInt ()
178 Assert.AreEqual (Infoset ("<int>10</int>"), WriterText);
182 public void TestSerializeBool ()
185 Assert.AreEqual (Infoset ("<boolean>true</boolean>"), WriterText);
188 Assert.AreEqual (Infoset ("<boolean>false</boolean>"), WriterText);
192 public void TestSerializeString ()
195 Assert.AreEqual (Infoset ("<string>hello</string>"), WriterText);
199 public void TestSerializeEmptyString ()
201 Serialize (String.Empty);
202 Assert.AreEqual (Infoset ("<string />"), WriterText);
206 public void TestSerializeNullObject ()
208 Serialize (null, typeof (object));
209 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
210 "<anyType xmlns:xsd='{0}' xmlns:xsi='{1}' xsi:nil='true' />",
211 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
215 [Ignore ("The generated XML is not exact but it is equivalent")]
216 public void TestSerializeNullString ()
218 Serialize (null, typeof (string));
219 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
220 "<string xmlns:xsd='{0}' xmlns:xsi='{1}' xsi:nil='true' />",
221 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
225 public void TestSerializeIntArray ()
227 Serialize (new int[] { 1, 2, 3, 4 });
228 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
229 "<ArrayOfInt xmlns:xsd='{0}' xmlns:xsi='{1}'><int>1</int><int>2</int><int>3</int><int>4</int></ArrayOfInt>",
230 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
234 public void TestSerializeEmptyArray ()
236 Serialize (new int[] { });
237 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
238 "<ArrayOfInt xmlns:xsd='{0}' xmlns:xsi='{1}' />",
239 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
243 public void TestSerializeChar ()
246 Assert.AreEqual (Infoset ("<char>65</char>"), WriterText);
249 Assert.AreEqual (Infoset ("<char>0</char>"), WriterText);
252 Assert.AreEqual (Infoset ("<char>10</char>"), WriterText);
254 Serialize ('\uFF01');
255 Assert.AreEqual (Infoset ("<char>65281</char>"), WriterText);
259 public void TestSerializeFloat ()
262 Assert.AreEqual (Infoset ("<double>10.78</double>"), WriterText);
265 Assert.AreEqual (Infoset ("<double>-100000000</double>"), WriterText);
267 // FIXME test INF and other boundary conditions that may exist with floats
271 public void TestSerializeEnumeration_FromValue ()
273 Serialize ((int) SimpleEnumeration.SECOND, typeof (SimpleEnumeration));
275 "<?xml version='1.0' encoding='utf-16'?>" +
276 "<SimpleEnumeration>SECOND</SimpleEnumeration>",
281 [Category ("NotWorking")]
282 public void TestSerializeEnumeration_FromValue_Encoded ()
284 SerializeEncoded ((int) SimpleEnumeration.SECOND, typeof (SimpleEnumeration));
285 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
286 "<?xml version='1.0' encoding='utf-16'?>" +
287 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>SECOND</SimpleEnumeration>",
288 XmlSchema.InstanceNamespace), sw.ToString ());
292 public void TestSerializeEnumeration ()
294 Serialize (SimpleEnumeration.FIRST);
295 Assert.AreEqual (Infoset ("<SimpleEnumeration>FIRST</SimpleEnumeration>"), WriterText, "#1");
297 Serialize (SimpleEnumeration.SECOND);
298 Assert.AreEqual (Infoset ("<SimpleEnumeration>SECOND</SimpleEnumeration>"), WriterText, "#2");
302 public void TestSerializeEnumeration_Encoded ()
304 SerializeEncoded (SimpleEnumeration.FIRST);
305 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
306 "<?xml version='1.0' encoding='utf-16'?>" +
307 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>FIRST</SimpleEnumeration>",
308 XmlSchema.InstanceNamespace), sw.ToString (), "#B1");
310 SerializeEncoded (SimpleEnumeration.SECOND);
311 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
312 "<?xml version='1.0' encoding='utf-16'?>" +
313 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>SECOND</SimpleEnumeration>",
314 XmlSchema.InstanceNamespace), sw.ToString (), "#B2");
318 public void TestSerializeEnumDefaultValue ()
320 Serialize (new EnumDefaultValue ());
321 Assert.AreEqual (Infoset ("<EnumDefaultValue />"), WriterText, "#1");
323 Serialize (new SimpleEnumeration ());
324 Assert.AreEqual (Infoset ("<SimpleEnumeration>FIRST</SimpleEnumeration>"), WriterText, "#2");
326 Serialize (3, typeof (EnumDefaultValue));
327 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#3");
329 Serialize (EnumDefaultValue.e3, typeof (EnumDefaultValue));
330 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#4");
332 Serialize (EnumDefaultValue.e1 | EnumDefaultValue.e2, typeof (EnumDefaultValue));
333 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#5");
335 Serialize (EnumDefaultValue.e1 | EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
336 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#6");
338 Serialize (EnumDefaultValue.e1 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
339 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#7");
341 Serialize (EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
342 Assert.AreEqual (Infoset ("<EnumDefaultValue>e3</EnumDefaultValue>"), WriterText, "#8");
344 Serialize (3, typeof (FlagEnum));
345 Assert.AreEqual (Infoset ("<FlagEnum>one two</FlagEnum>"), WriterText, "#9");
347 Serialize (5, typeof (FlagEnum));
348 Assert.AreEqual (Infoset ("<FlagEnum>one four</FlagEnum>"), WriterText, "#10");
350 Serialize (FlagEnum.e4, typeof (FlagEnum));
351 Assert.AreEqual (Infoset ("<FlagEnum>four</FlagEnum>"), WriterText, "#11");
353 Serialize (FlagEnum.e1 | FlagEnum.e2, typeof (FlagEnum));
354 Assert.AreEqual (Infoset ("<FlagEnum>one two</FlagEnum>"), WriterText, "#12");
356 Serialize (FlagEnum.e1 | FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
357 Assert.AreEqual (Infoset ("<FlagEnum>one two four</FlagEnum>"), WriterText, "#13");
359 Serialize (FlagEnum.e1 | FlagEnum.e4, typeof (FlagEnum));
360 Assert.AreEqual (Infoset ("<FlagEnum>one four</FlagEnum>"), WriterText, "#14");
362 Serialize (FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
363 Assert.AreEqual (Infoset ("<FlagEnum>two four</FlagEnum>"), WriterText, "#15");
365 Serialize (3, typeof (EnumDefaultValueNF));
366 Assert.AreEqual (Infoset ("<EnumDefaultValueNF>e3</EnumDefaultValueNF>"), WriterText, "#16");
368 Serialize (EnumDefaultValueNF.e2, typeof (EnumDefaultValueNF));
369 Assert.AreEqual (Infoset ("<EnumDefaultValueNF>e2</EnumDefaultValueNF>"), WriterText, "#17");
371 Serialize (2, typeof (ZeroFlagEnum));
372 Assert.AreEqual (Infoset ("<ZeroFlagEnum>tns:t<w>o</ZeroFlagEnum>"), WriterText, "#18");
374 Serialize (new ZeroFlagEnum ()); // enum actually has a field with value 0
375 Assert.AreEqual (Infoset ("<ZeroFlagEnum>zero</ZeroFlagEnum>"), WriterText, "#19");
379 [Category ("NotWorking")]
380 public void TestSerializeEnumDefaultValue_Encoded ()
382 SerializeEncoded (new EnumDefaultValue ());
383 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
384 "<?xml version='1.0' encoding='utf-16'?>" +
385 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}' />",
386 XmlSchema.InstanceNamespace), sw.ToString (), "#1");
388 SerializeEncoded (new SimpleEnumeration ());
389 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
390 "<?xml version='1.0' encoding='utf-16'?>" +
391 "<SimpleEnumeration d1p1:type='SimpleEnumeration' xmlns:d1p1='{0}'>FIRST</SimpleEnumeration>",
392 XmlSchema.InstanceNamespace), sw.ToString (), "#2");
394 SerializeEncoded (3, typeof (EnumDefaultValue));
395 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
396 "<?xml version='1.0' encoding='utf-16'?>" +
397 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
398 XmlSchema.InstanceNamespace), sw.ToString (), "#3");
400 SerializeEncoded (EnumDefaultValue.e3, typeof (EnumDefaultValue));
401 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
402 "<?xml version='1.0' encoding='utf-16'?>" +
403 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
404 XmlSchema.InstanceNamespace), sw.ToString (), "#4");
406 SerializeEncoded (EnumDefaultValue.e1 | EnumDefaultValue.e2, typeof (EnumDefaultValue));
407 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
408 "<?xml version='1.0' encoding='utf-16'?>" +
409 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
410 XmlSchema.InstanceNamespace), sw.ToString (), "#5");
412 SerializeEncoded (EnumDefaultValue.e1 | EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
413 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
414 "<?xml version='1.0' encoding='utf-16'?>" +
415 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
416 XmlSchema.InstanceNamespace), sw.ToString (), "#6");
418 SerializeEncoded (EnumDefaultValue.e1 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
419 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
420 "<?xml version='1.0' encoding='utf-16'?>" +
421 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
422 XmlSchema.InstanceNamespace), sw.ToString (), "#7");
424 SerializeEncoded (EnumDefaultValue.e2 | EnumDefaultValue.e3, typeof (EnumDefaultValue));
425 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
426 "<?xml version='1.0' encoding='utf-16'?>" +
427 "<EnumDefaultValue d1p1:type='EnumDefaultValue' xmlns:d1p1='{0}'>e3</EnumDefaultValue>",
428 XmlSchema.InstanceNamespace), sw.ToString (), "#8");
430 SerializeEncoded (3, typeof (FlagEnum));
431 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
432 "<?xml version='1.0' encoding='utf-16'?>" +
433 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e2</FlagEnum>",
434 XmlSchema.InstanceNamespace), sw.ToString (), "#9");
436 SerializeEncoded (5, typeof (FlagEnum));
437 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
438 "<?xml version='1.0' encoding='utf-16'?>" +
439 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e4</FlagEnum>",
440 XmlSchema.InstanceNamespace), sw.ToString (), "#10");
442 SerializeEncoded (FlagEnum.e4, typeof (FlagEnum));
443 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
444 "<?xml version='1.0' encoding='utf-16'?>" +
445 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e4</FlagEnum>",
446 XmlSchema.InstanceNamespace), sw.ToString (), "#11");
448 SerializeEncoded (FlagEnum.e1 | FlagEnum.e2, typeof (FlagEnum));
449 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
450 "<?xml version='1.0' encoding='utf-16'?>" +
451 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e2</FlagEnum>",
452 XmlSchema.InstanceNamespace), sw.ToString (), "#12");
454 SerializeEncoded (FlagEnum.e1 | FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
455 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
456 "<?xml version='1.0' encoding='utf-16'?>" +
457 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e2 e4</FlagEnum>",
458 XmlSchema.InstanceNamespace), sw.ToString (), "#13");
460 SerializeEncoded (FlagEnum.e1 | FlagEnum.e4, typeof (FlagEnum));
461 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
462 "<?xml version='1.0' encoding='utf-16'?>" +
463 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e1 e4</FlagEnum>",
464 XmlSchema.InstanceNamespace), sw.ToString (), "#14");
466 SerializeEncoded (FlagEnum.e2 | FlagEnum.e4, typeof (FlagEnum));
467 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
468 "<?xml version='1.0' encoding='utf-16'?>" +
469 "<FlagEnum d1p1:type='FlagEnum' xmlns:d1p1='{0}'>e2 e4</FlagEnum>",
470 XmlSchema.InstanceNamespace), sw.ToString (), "#15");
472 SerializeEncoded (3, typeof (EnumDefaultValueNF));
473 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
474 "<?xml version='1.0' encoding='utf-16'?>" +
475 "<EnumDefaultValueNF d1p1:type='EnumDefaultValueNF' xmlns:d1p1='{0}'>e3</EnumDefaultValueNF>",
476 XmlSchema.InstanceNamespace), sw.ToString (), "#16");
478 SerializeEncoded (EnumDefaultValueNF.e2, typeof (EnumDefaultValueNF));
479 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
480 "<?xml version='1.0' encoding='utf-16'?>" +
481 "<EnumDefaultValueNF d1p1:type='EnumDefaultValueNF' xmlns:d1p1='{0}'>e2</EnumDefaultValueNF>",
482 XmlSchema.InstanceNamespace), sw.ToString (), "#17");
484 SerializeEncoded (2, typeof (ZeroFlagEnum));
485 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
486 "<?xml version='1.0' encoding='utf-16'?>" +
487 "<ZeroFlagEnum d1p1:type='ZeroFlagEnum' xmlns:d1p1='{0}'>e2</ZeroFlagEnum>",
488 XmlSchema.InstanceNamespace), sw.ToString (), "#18");
490 SerializeEncoded (new ZeroFlagEnum ()); // enum actually has a field with value 0
491 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
492 "<?xml version='1.0' encoding='utf-16'?>" +
493 "<ZeroFlagEnum d1p1:type='ZeroFlagEnum' xmlns:d1p1='{0}'>e0</ZeroFlagEnum>",
494 XmlSchema.InstanceNamespace), sw.ToString (), "#19");
498 public void TestSerializeEnumDefaultValue_InvalidValue1 ()
501 Serialize ("b", typeof (EnumDefaultValue));
503 } catch (InvalidOperationException ex) {
504 Assert.IsNotNull (ex.InnerException, "#A2");
505 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#A3");
509 Serialize ("e1", typeof (EnumDefaultValue));
511 } catch (InvalidOperationException ex) {
512 Assert.IsNotNull (ex.InnerException, "#B2");
513 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#B3");
517 Serialize ("e1,e2", typeof (EnumDefaultValue));
519 } catch (InvalidOperationException ex) {
520 Assert.IsNotNull (ex.InnerException, "#C2");
521 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#C3");
525 Serialize (string.Empty, typeof (EnumDefaultValue));
527 } catch (InvalidOperationException ex) {
528 Assert.IsNotNull (ex.InnerException, "#D2");
529 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#D3");
533 Serialize ("1", typeof (EnumDefaultValue));
535 } catch (InvalidOperationException ex) {
536 Assert.IsNotNull (ex.InnerException, "#E2");
537 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#E3");
541 Serialize ("0", typeof (EnumDefaultValue));
543 } catch (InvalidOperationException ex) {
544 Assert.IsNotNull (ex.InnerException, "#F2");
545 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#F3");
549 Serialize (new SimpleClass (), typeof (EnumDefaultValue));
551 } catch (InvalidOperationException ex) {
552 Assert.IsNotNull (ex.InnerException, "#G2");
553 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#G3");
558 public void TestSerializeEnumDefaultValue_InvalidValue2 ()
561 Serialize (5, typeof (EnumDefaultValue));
563 } catch (InvalidOperationException ex) {
564 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
565 Assert.IsNotNull (ex.InnerException, "#3");
566 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
567 Assert.IsNotNull (ex.InnerException.Message, "#5");
568 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'5'") != -1, "#6");
569 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (EnumDefaultValue).FullName) != -1, "#7");
574 public void TestSerializeEnumDefaultValueNF_InvalidValue1 ()
577 Serialize (new EnumDefaultValueNF ());
579 } catch (InvalidOperationException ex) {
580 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
581 Assert.IsNotNull (ex.InnerException, "#3");
582 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
583 Assert.IsNotNull (ex.InnerException.Message, "#5");
584 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'0'") != -1, "#6");
585 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (EnumDefaultValueNF).FullName) != -1, "#7");
590 public void TestSerializeEnumDefaultValueNF_InvalidValue2 ()
593 Serialize (15, typeof (EnumDefaultValueNF));
595 } catch (InvalidOperationException ex) {
596 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
597 Assert.IsNotNull (ex.InnerException, "#3");
598 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
599 Assert.IsNotNull (ex.InnerException.Message, "#5");
600 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'15'") != -1, "#6");
601 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (EnumDefaultValueNF).FullName) != -1, "#7");
606 public void TestSerializeEnumDefaultValueNF_InvalidValue3 ()
609 Serialize ("b", typeof (EnumDefaultValueNF));
611 } catch (InvalidOperationException ex) {
612 Assert.IsNotNull (ex.InnerException, "#A2");
613 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#A3");
617 Serialize ("e2", typeof (EnumDefaultValueNF));
619 } catch (InvalidOperationException ex) {
620 Assert.IsNotNull (ex.InnerException, "#B2");
621 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#B3");
625 Serialize (string.Empty, typeof (EnumDefaultValueNF));
627 } catch (InvalidOperationException ex) {
628 Assert.IsNotNull (ex.InnerException, "#C2");
629 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#C3");
633 Serialize ("1", typeof (EnumDefaultValueNF));
635 } catch (InvalidOperationException ex) {
636 Assert.IsNotNull (ex.InnerException, "#D2");
637 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#D3");
641 Serialize ("0", typeof (EnumDefaultValueNF));
643 } catch (InvalidOperationException ex) {
644 Assert.IsNotNull (ex.InnerException, "#E2");
645 Assert.AreEqual (typeof (InvalidCastException), ex.InnerException.GetType (), "#E3");
650 public void TestSerializeField ()
652 Field f = new Field ();
653 Serialize (f, typeof (Field));
654 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
655 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag1='' flag2='' flag3=''" +
656 " flag4='' modifiers='public' modifiers2='public' modifiers4='public' />",
657 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#A");
659 f.Flags1 = FlagEnum.e1;
660 f.Flags2 = FlagEnum.e1;
661 f.Flags3 = FlagEnum.e2;
662 f.Modifiers = MapModifiers.Protected;
663 f.Modifiers2 = MapModifiers.Public;
664 f.Modifiers3 = MapModifiers.Public;
665 f.Modifiers4 = MapModifiers.Protected;
666 f.Modifiers5 = MapModifiers.Public;
667 Serialize (f, typeof (Field));
668 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
669 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag3='two' flag4=''" +
670 " modifiers='protected' modifiers2='public' />",
671 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#B");
673 f.Flags1 = (FlagEnum) 1;
674 f.Flags1 = FlagEnum.e2;
675 f.Flags2 = FlagEnum.e2;
676 f.Flags3 = FlagEnum.e1 | FlagEnum.e2;
677 f.Modifiers = MapModifiers.Public;
678 f.Modifiers2 = MapModifiers.Protected;
679 f.Modifiers3 = MapModifiers.Protected;
680 f.Modifiers4 = MapModifiers.Public;
681 f.Modifiers5 = MapModifiers.Protected;
682 Serialize (f, typeof (Field));
683 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
684 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag1='two' flag2='two'" +
685 " flag4='' modifiers='public' modifiers2='protected'" +
686 " modifiers3='protected' modifiers4='public'" +
687 " modifiers5='protected' />",
688 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#C");
690 f.Flags1 = FlagEnum.e1 | FlagEnum.e2;
691 f.Flags2 = FlagEnum.e2;
692 f.Flags3 = FlagEnum.e4;
693 f.Flags4 = FlagEnum.e1 | FlagEnum.e2 | FlagEnum.e4;
694 f.Modifiers3 = MapModifiers.Public;
695 f.Modifiers4 = MapModifiers.Protected;
696 f.Modifiers5 = MapModifiers.Public;
697 f.Names = new string[] { "a", "b" };
698 Serialize (f, typeof (Field));
699 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
700 "<field xmlns:xsd='{0}' xmlns:xsi='{1}' flag1='one two' flag2='two'" +
701 " flag3='four' flag4='one two four' modifiers='public'" +
702 " modifiers2='protected' names='a b' />",
703 XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText, "#D");
705 f.Flags2 = (FlagEnum) 444;
706 f.Flags3 = (FlagEnum) 555;
707 f.Modifiers = (MapModifiers) 666;
708 f.Modifiers2 = (MapModifiers) 777;
709 f.Modifiers3 = (MapModifiers) 0;
710 f.Modifiers4 = (MapModifiers) 888;
711 f.Modifiers5 = (MapModifiers) 999;
713 Serialize (f, typeof (Field));
715 } catch (InvalidOperationException ex) {
716 // There was an error generating the XML document
717 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");
718 Assert.IsNotNull (ex.Message, "#E3");
719 Assert.IsNotNull (ex.InnerException, "#E4");
721 // Instance validation error: '444' is not a valid value for
722 // MonoTests.System.Xml.TestClasses.FlagEnum
723 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#E5");
724 Assert.IsNotNull (ex.InnerException.Message, "#E6");
725 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'444'") != -1, "#E7");
726 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (FlagEnum).FullName) != -1, "#E8");
727 Assert.IsNull (ex.InnerException.InnerException, "#E9");
732 [Category ("NotDotNet")] // MS bug
733 public void TestSerializeField_Encoded ()
735 Field_Encoded f = new Field_Encoded ();
736 SerializeEncoded (f, typeof (Field_Encoded));
737 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
738 "<?xml version='1.0' encoding='utf-16'?>" +
739 "<q1:field xmlns:xsd='{0}' xmlns:xsi='{1}' id='id1' flag1=''" +
740 " flag2='' flag3='' flag4='' modifiers='PuBlIc'" +
741 " modifiers2='PuBlIc' modifiers4='PuBlIc' xmlns:q1='some:urn' />",
742 XmlSchema.Namespace, XmlSchema.InstanceNamespace),
743 sw.GetStringBuilder ().ToString (), "#A");
745 f.Flags1 = FlagEnum_Encoded.e1;
746 f.Flags2 = FlagEnum_Encoded.e1;
747 f.Flags3 = FlagEnum_Encoded.e2;
748 f.Modifiers = MapModifiers.Protected;
749 f.Modifiers2 = MapModifiers.Public;
750 f.Modifiers3 = MapModifiers.Public;
751 f.Modifiers4 = MapModifiers.Protected;
752 f.Modifiers5 = MapModifiers.Public;
753 SerializeEncoded (f, typeof (Field_Encoded));
754 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
755 "<?xml version='1.0' encoding='utf-16'?>" +
756 "<q1:field xmlns:xsd='{0}' xmlns:xsi='{1}' id='id1' flag3='two'" +
757 " flag4='' modifiers='Protected' modifiers2='PuBlIc'" +
758 " xmlns:q1='some:urn' />",
759 XmlSchema.Namespace, XmlSchema.InstanceNamespace),
760 sw.GetStringBuilder ().ToString (), "#B");
762 f.Flags1 = FlagEnum_Encoded.e2;
763 f.Flags2 = FlagEnum_Encoded.e2;
764 f.Flags3 = FlagEnum_Encoded.e1 | FlagEnum_Encoded.e2;
765 f.Modifiers = MapModifiers.Public;
766 f.Modifiers2 = MapModifiers.Protected;
767 f.Modifiers3 = MapModifiers.Protected;
768 f.Modifiers4 = MapModifiers.Public;
769 f.Modifiers5 = MapModifiers.Protected;
770 SerializeEncoded (f, typeof (Field_Encoded));
771 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
772 "<?xml version='1.0' encoding='utf-16'?>" +
773 "<q1:field xmlns:xsd='{0}' xmlns:xsi='{1}' id='id1' flag1='two'" +
774 " flag2='two' flag4='' modifiers='PuBlIc' modifiers2='Protected'" +
775 " modifiers3='Protected' modifiers4='PuBlIc' modifiers5='Protected'" +
776 " xmlns:q1='some:urn' />",
777 XmlSchema.Namespace, XmlSchema.InstanceNamespace),
778 sw.GetStringBuilder ().ToString (), "#C");
780 f.Flags1 = (FlagEnum_Encoded) 1;
781 f.Flags2 = (FlagEnum_Encoded) 444;
782 f.Flags3 = (FlagEnum_Encoded) 555;
783 f.Modifiers = (MapModifiers) 666;
784 f.Modifiers2 = (MapModifiers) 777;
785 f.Modifiers3 = (MapModifiers) 0;
786 f.Modifiers4 = (MapModifiers) 888;
787 f.Modifiers5 = (MapModifiers) 999;
789 SerializeEncoded (f, typeof (Field_Encoded));
791 } catch (InvalidOperationException ex) {
792 // There was an error generating the XML document
793 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");
794 Assert.IsNotNull (ex.Message, "#D3");
795 Assert.IsNotNull (ex.InnerException, "#D4");
797 // Instance validation error: '444' is not a valid value for
798 // MonoTests.System.Xml.TestClasses.FlagEnum_Encoded
799 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#D5");
800 Assert.IsNotNull (ex.InnerException.Message, "#D6");
801 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'444'") != -1, "#D7");
802 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (FlagEnum_Encoded).FullName) != -1, "#D8");
803 Assert.IsNull (ex.InnerException.InnerException, "#D9");
808 public void TestSerializeGroup ()
810 Group myGroup = new Group ();
811 myGroup.GroupName = ".NET";
813 Byte[] hexByte = new Byte[] { 0x64, 0x32 };
814 myGroup.GroupNumber = hexByte;
816 DateTime myDate = new DateTime (2002, 5, 2);
817 myGroup.Today = myDate;
818 myGroup.PostitiveInt = "10000";
819 myGroup.IgnoreThis = true;
820 Car thisCar = (Car) myGroup.myCar ("1234566");
821 myGroup.MyVehicle = thisCar;
824 xtw.WriteStartDocument (true);
825 xtw.WriteStartElement ("Wrapper");
826 SerializeEncoded (xtw, myGroup, typeof (Group));
827 xtw.WriteEndElement ();
830 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
832 "<Group xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns:d2p1='http://www.cpandl.com' CreationDate='2002-05-02' d2p1:GroupName='.NET' GroupNumber='ZDI=' id='id1'>" +
833 "<PosInt xsi:type='xsd:nonNegativeInteger'>10000</PosInt>" +
834 "<Grouptype xsi:type='GroupType'>Small</Grouptype>" +
835 "<MyVehicle href='#id2' />" +
837 "<Car xmlns:d2p1='{1}' id='id2' d2p1:type='Car'>" +
838 "<licenseNumber xmlns:q1='{0}' d2p1:type='q1:string'>1234566</licenseNumber>" +
839 "<makeDate xmlns:q2='{0}' d2p1:type='q2:date'>0001-01-01</makeDate>" +
842 XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
845 myGroup.GroupName = null;
846 myGroup.Grouptype = GroupType.B;
847 myGroup.MyVehicle.licenseNumber = null;
848 myGroup.MyVehicle.weight = "450";
851 xtw.WriteStartDocument (true);
852 xtw.WriteStartElement ("Wrapper");
853 SerializeEncoded (xtw, myGroup, typeof (Group));
854 xtw.WriteEndElement ();
857 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
859 "<Group xmlns:xsd='{0}' xmlns:xsi='{1}' CreationDate='2002-05-02' GroupNumber='ZDI=' id='id1'>" +
860 "<PosInt xsi:type='xsd:nonNegativeInteger'>10000</PosInt>" +
861 "<Grouptype xsi:type='GroupType'>Large</Grouptype>" +
862 "<MyVehicle href='#id2' />" +
864 "<Car xmlns:d2p1='{1}' id='id2' d2p1:type='Car'>" +
865 "<makeDate xmlns:q1='{0}' d2p1:type='q1:date'>0001-01-01</makeDate>" +
866 "<weight xmlns:q2='{0}' d2p1:type='q2:string'>450</weight>" +
869 XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
874 public void TestSerializeZeroFlagEnum_InvalidValue ()
877 Serialize (4, typeof (ZeroFlagEnum)); // corresponding enum field is marked XmlIgnore
879 } catch (InvalidOperationException ex) {
880 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
881 Assert.IsNotNull (ex.InnerException, "#3");
882 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
883 Assert.IsNotNull (ex.InnerException.Message, "#5");
884 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'4'") != -1, "#6");
885 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (ZeroFlagEnum).FullName) != -1, "#7");
890 public void TestSerializeQualifiedName ()
892 Serialize (new XmlQualifiedName ("me", "home.urn"));
893 Assert.AreEqual (Infoset ("<QName xmlns:q1='home.urn'>q1:me</QName>"), WriterText);
897 public void TestSerializeBytes ()
899 Serialize ((byte) 0xAB);
900 Assert.AreEqual (Infoset ("<unsignedByte>171</unsignedByte>"), WriterText);
902 Serialize ((byte) 15);
903 Assert.AreEqual (Infoset ("<unsignedByte>15</unsignedByte>"), WriterText);
907 public void TestSerializeByteArrays ()
909 Serialize (new byte[] { });
910 Assert.AreEqual (Infoset ("<base64Binary />"), WriterText);
912 Serialize (new byte[] { 0xAB, 0xCD });
913 Assert.AreEqual (Infoset ("<base64Binary>q80=</base64Binary>"), WriterText);
917 public void TestSerializeDateTime ()
919 DateTime d = new DateTime ();
922 TimeZone tz = TimeZone.CurrentTimeZone;
923 TimeSpan off = tz.GetUtcOffset (d);
924 string sp = string.Format ("{0}{1:00}:{2:00}", off.Ticks >= 0 ? "+" : "", off.Hours, off.Minutes);
925 Assert.AreEqual (Infoset ("<dateTime>0001-01-01T00:00:00</dateTime>"), WriterText);
935 public void TestSerialize()
938 Assert.AreEqual (WriterText, "");
942 // test basic class serialization /////////////////////////////////////
944 public void TestSerializeSimpleClass ()
946 SimpleClass simple = new SimpleClass ();
948 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
950 simple.something = "hello";
953 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);
957 public void TestSerializeStringCollection ()
959 StringCollection strings = new StringCollection ();
961 Assert.AreEqual (Infoset ("<ArrayOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
963 strings.Add ("hello");
964 strings.Add ("goodbye");
966 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);
970 public void TestSerializeOptionalValueTypeContainer ()
972 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
974 OptionalValueTypeContainer optionalValue = new OptionalValueTypeContainer ();
976 Serialize (optionalValue);
977 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
978 "<?xml version='1.0' encoding='utf-16'?>" +
979 "<optionalValue xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns='{2}' />",
980 XmlSchema.Namespace, XmlSchema.InstanceNamespace, AnotherNamespace),
981 sw.ToString (), "#1");
983 attr = new XmlAttributes ();
985 // remove the DefaultValue attribute on the Flags member
986 overrides.Add (typeof (OptionalValueTypeContainer), "Flags", attr);
987 // remove the DefaultValue attribute on the Attributes member
988 overrides.Add (typeof (OptionalValueTypeContainer), "Attributes", attr);
990 Serialize (optionalValue, overrides);
991 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
992 "<?xml version='1.0' encoding='utf-16'?>" +
993 "<optionalValue xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns='{2}'>" +
994 "<Attributes xmlns='{3}'>one four</Attributes>" +
995 "</optionalValue>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
996 AnotherNamespace, ANamespace), sw.ToString (), "#2");
998 optionalValue.FlagsSpecified = true;
999 Serialize (optionalValue, overrides);
1000 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
1001 "<?xml version='1.0' encoding='utf-16'?>" +
1002 "<optionalValue xmlns:xsd='{0}' xmlns:xsi='{1}' xmlns='{2}'>" +
1003 "<Attributes xmlns='{3}'>one four</Attributes>" +
1004 "<Flags xmlns='{3}'>one</Flags>" +
1006 XmlSchema.Namespace, XmlSchema.InstanceNamespace, AnotherNamespace,
1007 ANamespace), sw.ToString (), "#3");
1011 public void TestRoundTripSerializeOptionalValueTypeContainer ()
1013 var source = new OptionalValueTypeContainer ();
1014 source.IsEmpty = true;
1015 source.IsEmptySpecified = true;
1016 var ser = new XmlSerializer (typeof (OptionalValueTypeContainer));
1018 using (var t = new StringWriter ()) {
1019 ser.Serialize (t, source);
1022 using (var s = new StringReader (xml)) {
1023 var obj = (OptionalValueTypeContainer) ser.Deserialize(s);
1024 Assert.AreEqual (source.IsEmpty, obj.IsEmpty, "#1");
1025 Assert.AreEqual (source.IsEmptySpecified, obj.IsEmptySpecified, "#2");
1030 public void TestSerializePlainContainer ()
1032 StringCollectionContainer container = new StringCollectionContainer ();
1033 Serialize (container);
1034 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Messages /></StringCollectionContainer>"), WriterText);
1036 container.Messages.Add ("hello");
1037 container.Messages.Add ("goodbye");
1038 Serialize (container);
1039 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);
1043 public void TestSerializeArrayContainer ()
1045 ArrayContainer container = new ArrayContainer ();
1046 Serialize (container);
1047 Assert.AreEqual (Infoset ("<ArrayContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1049 container.items = new object[] { 10, 20 };
1050 Serialize (container);
1051 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);
1053 container.items = new object[] { 10, "hello" };
1054 Serialize (container);
1055 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);
1059 public void TestSerializeClassArrayContainer ()
1061 ClassArrayContainer container = new ClassArrayContainer ();
1062 Serialize (container);
1063 Assert.AreEqual (Infoset ("<ClassArrayContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1065 SimpleClass simple1 = new SimpleClass ();
1066 simple1.something = "hello";
1067 SimpleClass simple2 = new SimpleClass ();
1068 simple2.something = "hello";
1069 container.items = new SimpleClass[2];
1070 container.items[0] = simple1;
1071 container.items[1] = simple2;
1072 Serialize (container);
1073 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);
1076 // test basic attributes ///////////////////////////////////////////////
1078 public void TestSerializeSimpleClassWithXmlAttributes ()
1080 SimpleClassWithXmlAttributes simple = new SimpleClassWithXmlAttributes ();
1082 Assert.AreEqual (Infoset ("<simple xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1084 simple.something = "hello";
1086 Assert.AreEqual (Infoset ("<simple xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' member='hello' />"), WriterText);
1089 // test overrides ///////////////////////////////////////////////////////
1091 public void TestSerializeSimpleClassWithOverrides ()
1093 // Also tests XmlIgnore
1094 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1096 XmlAttributes attr = new XmlAttributes ();
1097 attr.XmlIgnore = true;
1098 overrides.Add (typeof (SimpleClassWithXmlAttributes), "something", attr);
1100 SimpleClassWithXmlAttributes simple = new SimpleClassWithXmlAttributes ();
1101 simple.something = "hello";
1102 Serialize (simple, overrides);
1103 Assert.AreEqual (Infoset ("<simple xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1107 public void TestSerializeSchema ()
1109 XmlSchema schema = new XmlSchema ();
1110 schema.Items.Add (new XmlSchemaAttribute ());
1111 schema.Items.Add (new XmlSchemaAttributeGroup ());
1112 schema.Items.Add (new XmlSchemaComplexType ());
1113 schema.Items.Add (new XmlSchemaNotation ());
1114 schema.Items.Add (new XmlSchemaSimpleType ());
1115 schema.Items.Add (new XmlSchemaGroup ());
1116 schema.Items.Add (new XmlSchemaElement ());
1118 StringWriter sw = new StringWriter ();
1119 XmlTextWriter xtw = new XmlTextWriter (sw);
1120 xtw.QuoteChar = '\'';
1121 xtw.Formatting = Formatting.Indented;
1122 XmlSerializer xs = new XmlSerializer (schema.GetType ());
1123 xs.Serialize (xtw, schema);
1125 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
1126 "<?xml version='1.0' encoding='utf-16'?>{0}" +
1127 "<xsd:schema xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>{0}" +
1128 " <xsd:attribute />{0}" +
1129 " <xsd:attributeGroup />{0}" +
1130 " <xsd:complexType />{0}" +
1131 " <xsd:notation />{0}" +
1132 " <xsd:simpleType />{0}" +
1133 " <xsd:group />{0}" +
1134 " <xsd:element />{0}" +
1135 "</xsd:schema>", Environment.NewLine), sw.ToString ());
1138 // test xmlText //////////////////////////////////////////////////////////
1140 public void TestSerializeXmlTextAttribute ()
1142 SimpleClass simple = new SimpleClass ();
1143 simple.something = "hello";
1145 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1146 XmlAttributes attr = new XmlAttributes ();
1147 overrides.Add (typeof (SimpleClass), "something", attr);
1149 attr.XmlText = new XmlTextAttribute ();
1150 Serialize (simple, overrides);
1151 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");
1153 attr.XmlText = new XmlTextAttribute (typeof (string));
1154 Serialize (simple, overrides);
1155 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");
1158 attr.XmlText = new XmlTextAttribute (typeof (byte[]));
1159 Serialize (simple, overrides);
1160 Assert.Fail ("#A1: XmlText.Type does not match the type it serializes: this should have failed");
1161 } catch (InvalidOperationException ex) {
1162 // there was an error reflecting type 'MonoTests.System.Xml.TestClasses.SimpleClass'
1163 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
1164 Assert.IsNotNull (ex.Message, "#A3");
1165 Assert.IsTrue (ex.Message.IndexOf (typeof (SimpleClass).FullName) != -1, "#A4");
1166 Assert.IsNotNull (ex.InnerException, "#A5");
1168 // there was an error reflecting field 'something'.
1169 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#A6");
1170 Assert.IsNotNull (ex.InnerException.Message, "#A7");
1171 Assert.IsTrue (ex.InnerException.Message.IndexOf ("something") != -1, "#A8");
1172 Assert.IsNotNull (ex.InnerException.InnerException, "#A9");
1174 // the type for XmlText may not be specified for primitive types.
1175 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.InnerException.GetType (), "#A10");
1176 Assert.IsNotNull (ex.InnerException.InnerException.Message, "#A11");
1177 Assert.IsNull (ex.InnerException.InnerException.InnerException, "#A12");
1181 attr.XmlText = new XmlTextAttribute ();
1182 attr.XmlText.DataType = "sometype";
1183 Serialize (simple, overrides);
1184 Assert.Fail ("#B1: XmlText.DataType does not match the type it serializes: this should have failed");
1185 } catch (InvalidOperationException ex) {
1186 // There was an error reflecting type 'MonoTests.System.Xml.TestClasses.SimpleClass'.
1187 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
1188 Assert.IsNotNull (ex.Message, "#B3");
1189 Assert.IsTrue (ex.Message.IndexOf (typeof (SimpleClass).FullName) != -1, "#B4");
1190 Assert.IsNotNull (ex.InnerException, "#B5");
1192 // There was an error reflecting field 'something'.
1193 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#B6");
1194 Assert.IsNotNull (ex.InnerException.Message, "#B7");
1195 Assert.IsTrue (ex.InnerException.Message.IndexOf ("something") != -1, "#B8");
1196 Assert.IsNotNull (ex.InnerException.InnerException, "#B9");
1200 // There was an error reflecting type 'System.String'.
1201 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.InnerException.GetType (), "#B10");
1202 Assert.IsNotNull (ex.InnerException.InnerException.Message, "#B11");
1203 Assert.IsTrue (ex.InnerException.InnerException.Message.IndexOf (typeof (string).FullName) != -1, "#B12");
1204 Assert.IsNotNull (ex.InnerException.InnerException.InnerException, "#B13");
1206 // Value 'sometype' cannot be used for the XmlElementAttribute.DataType property.
1207 // The datatype 'http://www.w3.org/2001/XMLSchema:sometype' is missing.
1208 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.InnerException.InnerException.GetType (), "#B14");
1209 Assert.IsNotNull (ex.InnerException.InnerException.InnerException.Message, "#B15");
1210 Assert.IsTrue (ex.InnerException.InnerException.InnerException.Message.IndexOf ("http://www.w3.org/2001/XMLSchema:sometype") != -1, "#B16");
1211 Assert.IsNull (ex.InnerException.InnerException.InnerException.InnerException, "#B17");
1216 // test xmlRoot //////////////////////////////////////////////////////////
1218 public void TestSerializeXmlRootAttribute ()
1220 // constructor override & element name
1221 XmlRootAttribute root = new XmlRootAttribute ();
1222 root.ElementName = "renamed";
1224 SimpleClassWithXmlAttributes simpleWithAttributes = new SimpleClassWithXmlAttributes ();
1225 Serialize (simpleWithAttributes, root);
1226 Assert.AreEqual (Infoset ("<renamed xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1228 SimpleClass simple = null;
1229 root.IsNullable = false;
1231 Serialize (simple, root);
1232 Assert.Fail ("Cannot serialize null object if XmlRoot's IsNullable == false");
1233 } catch (NullReferenceException) {
1236 root.IsNullable = true;
1238 Serialize (simple, root);
1239 Assert.Fail ("Cannot serialize null object if XmlRoot's IsNullable == true");
1240 } catch (NullReferenceException) {
1243 simple = new SimpleClass ();
1244 root.ElementName = null;
1245 root.Namespace = "some.urn";
1246 Serialize (simple, root);
1247 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);
1251 public void TestSerializeXmlRootAttributeOnMember ()
1254 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1255 XmlAttributes childAttr = new XmlAttributes ();
1256 childAttr.XmlRoot = new XmlRootAttribute ("simple");
1257 overrides.Add (typeof (SimpleClass), childAttr);
1259 XmlAttributes attr = new XmlAttributes ();
1260 attr.XmlRoot = new XmlRootAttribute ("simple");
1261 overrides.Add (typeof (ClassArrayContainer), attr);
1263 ClassArrayContainer container = new ClassArrayContainer ();
1264 container.items = new SimpleClass[1];
1265 container.items[0] = new SimpleClass ();
1266 Serialize (container, overrides);
1267 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);
1269 // FIXME test data type
1272 // test XmlAttribute /////////////////////////////////////////////////////
1274 public void TestSerializeXmlAttributeAttribute ()
1277 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1278 XmlAttributes attr = new XmlAttributes ();
1279 attr.XmlAttribute = new XmlAttributeAttribute ();
1280 overrides.Add (typeof (SimpleClass), "something", attr);
1282 SimpleClass simple = new SimpleClass (); ;
1283 Serialize (simple, overrides);
1284 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#1");
1287 simple.something = "hello";
1288 Serialize (simple, overrides);
1289 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");
1292 attr.XmlAttribute.AttributeName = "somethingelse";
1293 Serialize (simple, overrides);
1294 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");
1297 // FIXME this should work, shouldnt it?
1298 // attr.XmlAttribute.Type = typeof(string);
1299 // Serialize(simple, overrides);
1300 // Assert(WriterText.EndsWith(" something='hello' />"));
1303 attr.XmlAttribute.Namespace = "some:urn";
1304 Serialize (simple, overrides);
1305 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");
1308 // FIXME XmlSchemaForm Form
1310 // FIXME write XmlQualifiedName as attribute
1313 // test XmlElement ///////////////////////////////////////////////////////
1315 public void TestSerializeXmlElementAttribute ()
1317 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1318 XmlAttributes attr = new XmlAttributes ();
1319 XmlElementAttribute element = new XmlElementAttribute ();
1320 attr.XmlElements.Add (element);
1321 overrides.Add (typeof (SimpleClass), "something", attr);
1324 SimpleClass simple = new SimpleClass (); ;
1325 Serialize (simple, overrides);
1326 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#1");
1329 simple.something = "hello";
1330 Serialize (simple, overrides);
1331 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");
1334 element.ElementName = "saying";
1335 Serialize (simple, overrides);
1336 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");
1339 element.IsNullable = false;
1340 simple.something = null;
1341 Serialize (simple, overrides);
1342 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#4");
1344 element.IsNullable = true;
1345 simple.something = null;
1346 Serialize (simple, overrides);
1347 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");
1350 element.ElementName = null;
1351 element.IsNullable = false;
1352 element.Namespace = "some:urn";
1353 simple.something = "hello";
1354 Serialize (simple, overrides);
1355 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");
1362 // test XmlElementAttribute with arrays and collections //////////////////
1364 public void TestSerializeCollectionWithXmlElementAttribute ()
1367 // if no type is specified or the specified type
1368 // matches the contents of the collection,
1369 // serialize each element in an element named after the member.
1370 // if the type does not match, or matches the collection itself,
1371 // create a base wrapping element for the member, and then
1372 // wrap each collection item in its own wrapping element based on type.
1374 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1375 XmlAttributes attr = new XmlAttributes ();
1376 XmlElementAttribute element = new XmlElementAttribute ();
1377 attr.XmlElements.Add (element);
1378 overrides.Add (typeof (StringCollectionContainer), "Messages", attr);
1380 // empty collection & no type info in XmlElementAttribute
1381 StringCollectionContainer container = new StringCollectionContainer ();
1382 Serialize (container, overrides);
1383 Assert.AreEqual (Infoset ("<StringCollectionContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#1");
1385 // non-empty collection & no type info in XmlElementAttribute
1386 container.Messages.Add ("hello");
1387 Serialize (container, overrides);
1388 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");
1390 // non-empty collection & only type info in XmlElementAttribute
1391 element.Type = typeof (StringCollection);
1392 Serialize (container, overrides);
1393 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");
1395 // non-empty collection & only type info in XmlElementAttribute
1396 element.Type = typeof (string);
1397 Serialize (container, overrides);
1398 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");
1401 container.Messages.Add ("goodbye");
1402 element.Type = null;
1403 Serialize (container, overrides);
1404 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");
1407 // test DefaultValue /////////////////////////////////////////////////////
1409 public void TestSerializeDefaultValueAttribute ()
1411 XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
1413 XmlAttributes attr = new XmlAttributes ();
1414 string defaultValueInstance = "nothing";
1415 attr.XmlDefaultValue = defaultValueInstance;
1416 overrides.Add (typeof (SimpleClass), "something", attr);
1419 SimpleClass simple = new SimpleClass ();
1420 Serialize (simple, overrides);
1421 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#A1");
1423 // same value as default
1424 simple.something = defaultValueInstance;
1425 Serialize (simple, overrides);
1426 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#A2");
1429 simple.something = "hello";
1430 Serialize (simple, overrides);
1431 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");
1433 overrides = new XmlAttributeOverrides ();
1434 attr = new XmlAttributes ();
1435 attr.XmlAttribute = new XmlAttributeAttribute ();
1436 attr.XmlDefaultValue = defaultValueInstance;
1437 overrides.Add (typeof (SimpleClass), "something", attr);
1440 simple = new SimpleClass ();
1441 Serialize (simple, overrides);
1442 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#B1");
1444 // same value as default
1445 simple.something = defaultValueInstance;
1446 Serialize (simple, overrides);
1447 Assert.AreEqual (Infoset ("<SimpleClass xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText, "#B2");
1450 simple.something = "hello";
1451 Serialize (simple, overrides);
1452 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");
1454 overrides = new XmlAttributeOverrides ();
1455 attr = new XmlAttributes ();
1456 attr.XmlAttribute = new XmlAttributeAttribute ("flagenc");
1457 overrides.Add (typeof (TestDefault), "flagencoded", attr);
1460 TestDefault testDefault = new TestDefault ();
1461 Serialize (testDefault);
1462 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");
1464 // use the default with overrides
1465 Serialize (testDefault, overrides);
1466 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");
1468 overrides = new XmlAttributeOverrides ();
1469 attr = new XmlAttributes ();
1470 attr.XmlAttribute = new XmlAttributeAttribute ("flagenc");
1471 attr.XmlDefaultValue = (FlagEnum_Encoded.e1 | FlagEnum_Encoded.e4); // add default again
1472 overrides.Add (typeof (TestDefault), "flagencoded", attr);
1474 // use the default with overrides
1475 Serialize (testDefault, overrides);
1476 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");
1478 // use the default with overrides and default namspace
1479 Serialize (testDefault, overrides, AnotherNamespace);
1480 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");
1482 // non-default values
1483 testDefault.strDefault = "Some Text";
1484 testDefault.boolT = false;
1485 testDefault.boolF = true;
1486 testDefault.decimalval = 20m;
1487 testDefault.flag = FlagEnum.e2;
1488 testDefault.flagencoded = FlagEnum_Encoded.e2 | FlagEnum_Encoded.e1;
1489 Serialize (testDefault);
1490 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1491 "<testDefault xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1492 " <strDefault>Some Text</strDefault>" +
1493 " <boolT>false</boolT>" +
1494 " <boolF>true</boolF>" +
1495 " <decimalval>20</decimalval>" +
1496 " <flag>two</flag>" +
1497 " <flagencoded>e1 e2</flagencoded>" +
1498 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1501 Serialize (testDefault, overrides);
1502 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1503 "<testDefault flagenc='e1 e2' xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1504 " <strDefault>Some Text</strDefault>" +
1505 " <boolT>false</boolT>" +
1506 " <boolF>true</boolF>" +
1507 " <decimalval>20</decimalval>" +
1508 " <flag>two</flag>" +
1509 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1512 Serialize (testDefault, overrides, AnotherNamespace);
1513 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1514 "<testDefault flagenc='e1 e2' xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1515 " <strDefault>Some Text</strDefault>" +
1516 " <boolT>false</boolT>" +
1517 " <boolF>true</boolF>" +
1518 " <decimalval>20</decimalval>" +
1519 " <flag>two</flag>" +
1520 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1523 attr = new XmlAttributes ();
1524 XmlTypeAttribute xmlType = new XmlTypeAttribute ("flagenum");
1525 xmlType.Namespace = "yetanother:urn";
1526 attr.XmlType = xmlType;
1527 overrides.Add (typeof (FlagEnum_Encoded), attr);
1529 Serialize (testDefault, overrides, AnotherNamespace);
1530 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1531 "<testDefault flagenc='e1 e2' xmlns='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1532 " <strDefault>Some Text</strDefault>" +
1533 " <boolT>false</boolT>" +
1534 " <boolF>true</boolF>" +
1535 " <decimalval>20</decimalval>" +
1536 " <flag>two</flag>" +
1537 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1540 attr = new XmlAttributes ();
1541 attr.XmlType = new XmlTypeAttribute ("testDefault");
1542 overrides.Add (typeof (TestDefault), attr);
1544 Serialize (testDefault, overrides, AnotherNamespace);
1545 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1546 "<testDefault flagenc='e1 e2' xmlns='{2}' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1547 " <strDefault>Some Text</strDefault>" +
1548 " <boolT>false</boolT>" +
1549 " <boolF>true</boolF>" +
1550 " <decimalval>20</decimalval>" +
1551 " <flag>two</flag>" +
1552 "</testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1553 AnotherNamespace)), WriterText, "#C9");
1557 [Category ("NotWorking")] // SerializationCodeGenerator outputs wrong xsi:type for flagencoded in #C1
1558 public void TestSerializeDefaultValueAttribute_Encoded ()
1560 SoapAttributeOverrides overrides = new SoapAttributeOverrides ();
1561 SoapAttributes attr = new SoapAttributes ();
1562 attr.SoapAttribute = new SoapAttributeAttribute ();
1563 string defaultValueInstance = "nothing";
1564 attr.SoapDefaultValue = defaultValueInstance;
1565 overrides.Add (typeof (SimpleClass), "something", attr);
1568 SimpleClass simple = new SimpleClass ();
1569 SerializeEncoded (simple, overrides);
1570 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");
1572 // same value as default
1573 simple.something = defaultValueInstance;
1574 SerializeEncoded (simple, overrides);
1575 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");
1578 simple.something = "hello";
1579 SerializeEncoded (simple, overrides);
1580 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");
1582 attr.SoapAttribute = null;
1583 attr.SoapElement = new SoapElementAttribute ();
1586 simple = new SimpleClass ();
1587 SerializeEncoded (simple, overrides);
1588 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");
1590 // same value as default
1591 simple.something = defaultValueInstance;
1592 SerializeEncoded (simple, overrides);
1593 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");
1596 simple.something = "hello";
1597 SerializeEncoded (simple, overrides);
1598 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");
1600 overrides = new SoapAttributeOverrides ();
1601 attr = new SoapAttributes ();
1602 attr.SoapElement = new SoapElementAttribute ("flagenc");
1603 overrides.Add (typeof (TestDefault), "flagencoded", attr);
1605 // use the default (from MS KB325691)
1606 TestDefault testDefault = new TestDefault ();
1607 SerializeEncoded (testDefault);
1608 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1609 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1610 " <strDefault xsi:type='xsd:string'>Default Value</strDefault>" +
1611 " <boolT xsi:type='xsd:boolean'>true</boolT>" +
1612 " <boolF xsi:type='xsd:boolean'>false</boolF>" +
1613 " <decimalval xsi:type='xsd:decimal'>10</decimalval>" +
1614 " <flag xsi:type='FlagEnum'>e1 e4</flag>" +
1615 " <flagencoded xsi:type='flagenum'>one four</flagencoded>" +
1616 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1619 SerializeEncoded (testDefault, overrides);
1620 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1621 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1622 " <strDefault xsi:type='xsd:string'>Default Value</strDefault>" +
1623 " <boolT xsi:type='xsd:boolean'>true</boolT>" +
1624 " <boolF xsi:type='xsd:boolean'>false</boolF>" +
1625 " <decimalval xsi:type='xsd:decimal'>10</decimalval>" +
1626 " <flag xsi:type='FlagEnum'>e1 e4</flag>" +
1627 " <flagenc xsi:type='flagenum'>one four</flagenc>" +
1628 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1631 SerializeEncoded (testDefault, overrides, AnotherNamespace);
1632 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1633 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1634 " <strDefault xsi:type='xsd:string'>Default Value</strDefault>" +
1635 " <boolT xsi:type='xsd:boolean'>true</boolT>" +
1636 " <boolF xsi:type='xsd:boolean'>false</boolF>" +
1637 " <decimalval xsi:type='xsd:decimal'>10</decimalval>" +
1638 " <flag xmlns:q2='{2}' xsi:type='q2:FlagEnum'>e1 e4</flag>" +
1639 " <flagenc xmlns:q3='{2}' xsi:type='q3:flagenum'>one four</flagenc>" +
1640 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1641 AnotherNamespace)), WriterText, "#C3");
1643 // non-default values
1644 testDefault.strDefault = "Some Text";
1645 testDefault.boolT = false;
1646 testDefault.boolF = true;
1647 testDefault.decimalval = 20m;
1648 testDefault.flag = FlagEnum.e2;
1649 testDefault.flagencoded = FlagEnum_Encoded.e2 | FlagEnum_Encoded.e1;
1650 SerializeEncoded (testDefault);
1651 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1652 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1653 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1654 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1655 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1656 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1657 " <flag xsi:type='FlagEnum'>e2</flag>" +
1658 " <flagencoded xsi:type='flagenum'>one two</flagencoded>" +
1659 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1662 SerializeEncoded (testDefault, overrides);
1663 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1664 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1665 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1666 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1667 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1668 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1669 " <flag xsi:type='FlagEnum'>e2</flag>" +
1670 " <flagenc xsi:type='flagenum'>one two</flagenc>" +
1671 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)),
1674 attr = new SoapAttributes ();
1675 attr.SoapType = new SoapTypeAttribute ("flagenum", "yetanother:urn");
1676 overrides.Add (typeof (FlagEnum_Encoded), attr);
1678 SerializeEncoded (testDefault, overrides, AnotherNamespace);
1679 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1680 "<q1:testDefault id='id1' xmlns:q1='urn:myNS' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1681 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1682 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1683 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1684 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1685 " <flag xmlns:q2='{2}' xsi:type='q2:FlagEnum'>e2</flag>" +
1686 " <flagenc xmlns:q3='yetanother:urn' xsi:type='q3:flagenum'>one two</flagenc>" +
1687 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1688 AnotherNamespace)), WriterText, "#C6");
1690 attr = new SoapAttributes ();
1691 attr.SoapType = new SoapTypeAttribute ("testDefault");
1692 overrides.Add (typeof (TestDefault), attr);
1694 SerializeEncoded (testDefault, overrides, AnotherNamespace);
1695 Assert.AreEqual (Infoset (string.Format (CultureInfo.InvariantCulture,
1696 "<q1:testDefault id='id1' xmlns:q1='{2}' xmlns:xsd='{0}' xmlns:xsi='{1}'>" +
1697 " <strDefault xsi:type='xsd:string'>Some Text</strDefault>" +
1698 " <boolT xsi:type='xsd:boolean'>false</boolT>" +
1699 " <boolF xsi:type='xsd:boolean'>true</boolF>" +
1700 " <decimalval xsi:type='xsd:decimal'>20</decimalval>" +
1701 " <flag xsi:type='q1:FlagEnum'>e2</flag>" +
1702 " <flagenc xmlns:q2='yetanother:urn' xsi:type='q2:flagenum'>one two</flagenc>" +
1703 "</q1:testDefault>", XmlSchema.Namespace, XmlSchema.InstanceNamespace,
1704 AnotherNamespace)), WriterText, "#C7");
1707 // test XmlEnum //////////////////////////////////////////////////////////
1709 public void TestSerializeXmlEnumAttribute ()
1711 Serialize (XmlSchemaForm.Qualified);
1712 Assert.AreEqual (Infoset ("<XmlSchemaForm>qualified</XmlSchemaForm>"), WriterText, "#1");
1714 Serialize (XmlSchemaForm.Unqualified);
1715 Assert.AreEqual (Infoset ("<XmlSchemaForm>unqualified</XmlSchemaForm>"), WriterText, "#2");
1719 public void TestSerializeXmlEnumAttribute_IgnoredValue ()
1721 // technically XmlSchemaForm.None has an XmlIgnore attribute,
1722 // but it is not being serialized as a member.
1725 Serialize (XmlSchemaForm.None);
1727 } catch (InvalidOperationException ex) {
1728 Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
1729 Assert.IsNotNull (ex.InnerException, "#3");
1730 Assert.AreEqual (typeof (InvalidOperationException), ex.InnerException.GetType (), "#4");
1731 Assert.IsNotNull (ex.InnerException.Message, "#5");
1732 Assert.IsTrue (ex.InnerException.Message.IndexOf ("'0'") != -1, "#6");
1733 Assert.IsTrue (ex.InnerException.Message.IndexOf (typeof (XmlSchemaForm).FullName) != -1, "#7");
1738 public void TestSerializeXmlNodeArray ()
1740 XmlDocument doc = new XmlDocument ();
1741 Serialize (new XmlNode[] { doc.CreateAttribute ("at"), doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (object));
1742 Assert.AreEqual (Infoset ("<anyType at=\"\"><elem1/><elem2/></anyType>"), WriterText);
1746 public void TestSerializeXmlNodeArray2 ()
1748 XmlDocument doc = new XmlDocument ();
1749 Serialize (new XmlNode[] { doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (XmlNode []));
1750 Assert.AreEqual (Infoset (String.Format ("<ArrayOfXmlNode xmlns:xsd='{0}' xmlns:xsi='{1}'><XmlNode><elem1/></XmlNode><XmlNode><elem2/></XmlNode></ArrayOfXmlNode>", XmlSchema.Namespace, XmlSchema.InstanceNamespace)), WriterText);
1754 [ExpectedException (typeof (InvalidOperationException))]
1755 [Category ("NotWorking")]
1756 public void TestSerializeXmlNodeArrayIncludesAttribute ()
1758 XmlDocument doc = new XmlDocument ();
1759 Serialize (new XmlNode[] { doc.CreateAttribute ("at"), doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (XmlNode []));
1763 public void TestSerializeXmlElementArray ()
1765 XmlDocument doc = new XmlDocument ();
1766 Serialize (new XmlElement[] { doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }, typeof (object));
1767 Assert.AreEqual (Infoset ("<anyType><elem1/><elem2/></anyType>"), WriterText);
1771 [ExpectedException (typeof (InvalidOperationException))] // List<XmlNode> is not supported
1772 public void TestSerializeGenericListOfNode ()
1774 XmlDocument doc = new XmlDocument ();
1775 Serialize (new List<XmlNode> (new XmlNode [] { doc.CreateAttribute ("at"), doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }), typeof (object));
1776 Assert.AreEqual (Infoset ("<anyType at=\"\"><elem1/><elem2/></anyType>"), WriterText);
1780 [ExpectedException (typeof (InvalidOperationException))] // List<XmlElement> is not supported
1781 public void TestSerializeGenericListOfElement ()
1783 XmlDocument doc = new XmlDocument ();
1784 Serialize (new List<XmlElement> (new XmlElement [] { doc.CreateElement ("elem1"), doc.CreateElement ("elem2") }), typeof (object));
1785 Assert.AreEqual (Infoset ("<anyType><elem1/><elem2/></anyType>"), WriterText);
1788 public void TestSerializeXmlDocument ()
1790 XmlDocument doc = new XmlDocument ();
1791 doc.LoadXml (@"<?xml version=""1.0"" encoding=""utf-8"" ?><root/>");
1792 Serialize (doc, typeof (XmlDocument));
1793 Assert.AreEqual ("<?xml version='1.0' encoding='utf-16'?><root />",
1794 sw.GetStringBuilder ().ToString ());
1798 public void TestSerializeXmlElement ()
1800 XmlDocument doc = new XmlDocument ();
1801 Serialize (doc.CreateElement ("elem"), typeof (XmlElement));
1802 Assert.AreEqual (Infoset ("<elem/>"), WriterText);
1806 public void TestSerializeXmlElementSubclass ()
1808 XmlDocument doc = new XmlDocument ();
1809 Serialize (new MyElem (doc), typeof (XmlElement));
1810 Assert.AreEqual (Infoset ("<myelem aa=\"1\"/>"), WriterText, "#1");
1812 Serialize (new MyElem (doc), typeof (MyElem));
1813 Assert.AreEqual (Infoset ("<myelem aa=\"1\"/>"), WriterText, "#2");
1817 public void TestSerializeXmlCDataSection ()
1819 XmlDocument doc = new XmlDocument ();
1820 CDataContainer c = new CDataContainer ();
1821 c.cdata = doc.CreateCDataSection ("data section contents");
1823 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);
1827 public void TestSerializeXmlNode ()
1829 XmlDocument doc = new XmlDocument ();
1830 NodeContainer c = new NodeContainer ();
1831 c.node = doc.CreateTextNode ("text");
1833 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);
1837 public void TestSerializeChoice ()
1839 Choices ch = new Choices ();
1840 ch.MyChoice = "choice text";
1841 ch.ItemType = ItemChoiceType.ChoiceZero;
1843 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");
1844 ch.ItemType = ItemChoiceType.StrangeOne;
1846 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");
1847 ch.ItemType = ItemChoiceType.ChoiceTwo;
1849 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");
1853 public void TestSerializeNamesWithSpaces ()
1855 TestSpace ts = new TestSpace ();
1859 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);
1863 public void TestSerializeReadOnlyProps ()
1865 ReadOnlyProperties ts = new ReadOnlyProperties ();
1867 Assert.AreEqual (Infoset ("<ReadOnlyProperties xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
1871 public void TestSerializeReadOnlyListProp ()
1873 ReadOnlyListProperty ts = new ReadOnlyListProperty ();
1875 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);
1880 public void TestSerializeIList ()
1882 clsPerson k = new clsPerson ();
1883 k.EmailAccounts = new ArrayList ();
1884 k.EmailAccounts.Add ("a");
1885 k.EmailAccounts.Add ("b");
1887 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);
1891 public void TestSerializeArrayEnc ()
1893 SoapReflectionImporter imp = new SoapReflectionImporter ();
1894 XmlTypeMapping map = imp.ImportTypeMapping (typeof (ArrayClass));
1895 XmlSerializer ser = new XmlSerializer (map);
1896 StringWriter sw = new StringWriter ();
1897 XmlTextWriter tw = new XmlTextWriter (sw);
1898 tw.WriteStartElement ("aa");
1899 ser.Serialize (tw, new ArrayClass ());
1900 tw.WriteEndElement ();
1903 [Test] // bug #76049
1904 public void TestIncludeType ()
1906 XmlReflectionImporter imp = new XmlReflectionImporter ();
1907 XmlTypeMapping map = imp.ImportTypeMapping (typeof (object));
1908 imp.IncludeType (typeof (TestSpace));
1909 XmlSerializer ser = new XmlSerializer (map);
1910 ser.Serialize (new StringWriter (), new TestSpace ());
1914 public void TestSerializeChoiceArray ()
1916 CompositeValueType v = new CompositeValueType ();
1919 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);
1923 public void TestArrayAttributeWithDataType ()
1925 Serialize (new ArrayAttributeWithType ());
1926 string res = "<ArrayAttributeWithType xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
1927 res += "at='a b' bin1='AQI= AQI=' bin2='AQI=' />";
1928 Assert.AreEqual (Infoset (res), WriterText);
1932 public void TestSubclassElementType ()
1934 SubclassTestContainer c = new SubclassTestContainer ();
1935 c.data = new SubclassTestSub ();
1938 string res = "<SubclassTestContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>";
1939 res += "<a xsi:type=\"SubclassTestSub\"/></SubclassTestContainer>";
1940 Assert.AreEqual (Infoset (res), WriterText);
1944 [ExpectedException (typeof (InvalidOperationException))]
1945 public void TestArrayAttributeWithWrongDataType ()
1947 Serialize (new ArrayAttributeWithWrongType ());
1951 [Category ("NotWorking")]
1952 public void TestSerializePrimitiveTypesContainer ()
1954 Serialize (new PrimitiveTypesContainer ());
1955 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
1956 "<?xml version='1.0' encoding='utf-16'?>" +
1957 "<PrimitiveTypesContainer xmlns:xsi='{1}' xmlns:xsd='{0}' xmlns='some:urn'>" +
1958 "<Number>2004</Number>" +
1959 "<Name>some name</Name>" +
1960 "<Index>56</Index>" +
1961 "<Password>8w8=</Password>" +
1962 "<PathSeparatorCharacter>47</PathSeparatorCharacter>" +
1963 "</PrimitiveTypesContainer>", XmlSchema.Namespace,
1964 XmlSchema.InstanceNamespace), sw.ToString (), "#1");
1966 SerializeEncoded (new PrimitiveTypesContainer ());
1967 Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
1968 "<?xml version='1.0' encoding='utf-16'?>" +
1969 "<q1:PrimitiveTypesContainer xmlns:xsi='{1}' xmlns:xsd='{0}' id='id1' xmlns:q1='{2}'>" +
1970 "<Number xsi:type='xsd:int'>2004</Number>" +
1971 "<Name xsi:type='xsd:string'>some name</Name>" +
1972 "<Index xsi:type='xsd:unsignedByte'>56</Index>" +
1973 "<Password xsi:type='xsd:base64Binary'>8w8=</Password>" +
1974 "<PathSeparatorCharacter xmlns:q2='{3}' xsi:type='q2:char'>47</PathSeparatorCharacter>" +
1975 "</q1:PrimitiveTypesContainer>", XmlSchema.Namespace,
1976 XmlSchema.InstanceNamespace, AnotherNamespace, WsdlTypesNamespace),
1977 sw.ToString (), "#2");
1981 public void TestSchemaForm ()
1983 TestSchemaForm1 t1 = new TestSchemaForm1 ();
1984 t1.p1 = new PrintTypeResponse ();
1986 t1.p2 = new PrintTypeResponse ();
1989 TestSchemaForm2 t2 = new TestSchemaForm2 ();
1990 t2.p1 = new PrintTypeResponse ();
1992 t2.p2 = new PrintTypeResponse ();
1997 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
1998 res += "<TestSchemaForm1 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
2001 res += " <data>data1</data>";
2002 res += " </result>";
2003 res += " <intern xmlns=\"urn:responseTypes\">";
2004 res += " <result xmlns=\"\">";
2005 res += " <data>data2</data>";
2006 res += " </result>";
2007 res += " </intern>";
2009 res += " <p2 xmlns=\"urn:oo\">";
2010 res += " <result xmlns=\"\">";
2011 res += " <data>data1</data>";
2012 res += " </result>";
2013 res += " <intern xmlns=\"urn:responseTypes\">";
2014 res += " <result xmlns=\"\">";
2015 res += " <data>data2</data>";
2016 res += " </result>";
2017 res += " </intern>";
2019 res += "</TestSchemaForm1>";
2020 Assert.AreEqual (Infoset (res), WriterText);
2024 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
2025 res += "<TestSchemaForm2 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
2026 res += " <p1 xmlns=\"urn:testForm\">";
2027 res += " <result xmlns=\"\">";
2028 res += " <data>data1</data>";
2029 res += " </result>";
2030 res += " <intern xmlns=\"urn:responseTypes\">";
2031 res += " <result xmlns=\"\">";
2032 res += " <data>data2</data>";
2033 res += " </result>";
2034 res += " </intern>";
2036 res += " <p2 xmlns=\"urn:oo\">";
2037 res += " <result xmlns=\"\">";
2038 res += " <data>data1</data>";
2039 res += " </result>";
2040 res += " <intern xmlns=\"urn:responseTypes\">";
2041 res += " <result xmlns=\"\">";
2042 res += " <data>data2</data>";
2043 res += " </result>";
2044 res += " </intern>";
2046 res += "</TestSchemaForm2>";
2047 Assert.AreEqual (Infoset (res), WriterText);
2049 XmlReflectionImporter imp = new XmlReflectionImporter ();
2050 XmlTypeMapping map = imp.ImportTypeMapping (typeof (TestSchemaForm1), "urn:extra");
2051 Serialize (t1, map);
2053 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
2054 res += "<TestSchemaForm1 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:extra\">";
2056 res += " <result xmlns=\"\">";
2057 res += " <data>data1</data>";
2058 res += " </result>";
2059 res += " <intern xmlns=\"urn:responseTypes\">";
2060 res += " <result xmlns=\"\">";
2061 res += " <data>data2</data>";
2062 res += " </result>";
2063 res += " </intern>";
2065 res += " <p2 xmlns=\"urn:oo\">";
2066 res += " <result xmlns=\"\">";
2067 res += " <data>data1</data>";
2068 res += " </result>";
2069 res += " <intern xmlns=\"urn:responseTypes\">";
2070 res += " <result xmlns=\"\">";
2071 res += " <data>data2</data>";
2072 res += " </result>";
2073 res += " </intern>";
2075 res += "</TestSchemaForm1>";
2076 Assert.AreEqual (Infoset (res), WriterText);
2078 imp = new XmlReflectionImporter ();
2079 map = imp.ImportTypeMapping (typeof (TestSchemaForm2), "urn:extra");
2080 Serialize (t2, map);
2082 res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
2083 res += "<TestSchemaForm2 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:extra\">";
2084 res += " <p1 xmlns=\"urn:testForm\">";
2085 res += " <result xmlns=\"\">";
2086 res += " <data>data1</data>";
2087 res += " </result>";
2088 res += " <intern xmlns=\"urn:responseTypes\">";
2089 res += " <result xmlns=\"\">";
2090 res += " <data>data2</data>";
2091 res += " </result>";
2092 res += " </intern>";
2094 res += " <p2 xmlns=\"urn:oo\">";
2095 res += " <result xmlns=\"\">";
2096 res += " <data>data1</data>";
2097 res += " </result>";
2098 res += " <intern xmlns=\"urn:responseTypes\">";
2099 res += " <result xmlns=\"\">";
2100 res += " <data>data2</data>";
2101 res += " </result>";
2102 res += " </intern>";
2104 res += "</TestSchemaForm2>";
2105 Assert.AreEqual (Infoset (res), WriterText);
2108 [Test] // bug #78536
2109 public void CDataTextNodes ()
2111 XmlSerializer ser = new XmlSerializer (typeof (CDataTextNodesType));
2112 ser.UnknownNode += new XmlNodeEventHandler (CDataTextNodes_BadNode);
2113 string xml = @"<CDataTextNodesType>
2115 (?<filename>^([A-Z]:)?[^\(]+)\((?<line>\d+),(?<column>\d+)\):
2116 \s((?<warning>warning)|(?<error>error))\s[^:]+:(?<message>.+$)|
2117 (?<error>(fatal\s)?error)[^:]+:(?<message>.+$)
2119 </CDataTextNodesType>";
2120 ser.Deserialize (new XmlTextReader (xml, XmlNodeType.Document, null));
2125 public void GenerateSerializerGenerics ()
2127 XmlReflectionImporter imp = new XmlReflectionImporter ();
2128 Type type = typeof (List<int>);
2129 XmlSerializer.GenerateSerializer (
2131 new XmlTypeMapping [] {imp.ImportTypeMapping (type)});
2136 public void Nullable ()
2138 XmlSerializer ser = new XmlSerializer (typeof (int?));
2139 int? nullableType = 5;
2140 sw = new StringWriter ();
2141 xtw = new XmlTextWriter (sw);
2142 ser.Serialize (xtw, nullableType);
2144 string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?><int>5</int>";
2145 Assert.AreEqual (Infoset (expected), WriterText);
2146 int? i = (int?) ser.Deserialize (new StringReader (sw.ToString ()));
2147 Assert.AreEqual (5, i);
2151 public void NullableEnums ()
2153 WithNulls w = new WithNulls ();
2154 XmlSerializer ser = new XmlSerializer (typeof(WithNulls));
2155 StringWriter tw = new StringWriter ();
2156 ser.Serialize (tw, w);
2158 string expected = "<?xml version='1.0' encoding='utf-16'?>" +
2159 "<WithNulls xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
2160 "<nint xsi:nil='true' />" +
2161 "<nenum xsi:nil='true' />" +
2162 "<ndate xsi:nil='true' />" +
2165 Assert.AreEqual (Infoset (expected), Infoset (tw.ToString ()));
2167 StringReader sr = new StringReader (tw.ToString ());
2168 w = (WithNulls) ser.Deserialize (sr);
2170 Assert.IsFalse (w.nint.HasValue);
2171 Assert.IsFalse (w.nenum.HasValue);
2172 Assert.IsFalse (w.ndate.HasValue);
2174 DateTime t = new DateTime (2008,4,1);
2177 w.nenum = TestEnumWithNulls.bb;
2179 tw = new StringWriter ();
2180 ser.Serialize (tw, w);
2182 expected = "<?xml version='1.0' encoding='utf-16'?>" +
2183 "<WithNulls xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
2185 "<nenum>bb</nenum>" +
2186 "<ndate>2008-04-01T00:00:00</ndate>" +
2189 Assert.AreEqual (Infoset (expected), Infoset (tw.ToString ()));
2191 sr = new StringReader (tw.ToString ());
2192 w = (WithNulls) ser.Deserialize (sr);
2194 Assert.IsTrue (w.nint.HasValue);
2195 Assert.IsTrue (w.nenum.HasValue);
2196 Assert.IsTrue (w.ndate.HasValue);
2197 Assert.AreEqual (4, w.nint.Value);
2198 Assert.AreEqual (TestEnumWithNulls.bb, w.nenum.Value);
2199 Assert.AreEqual (t, w.ndate.Value);
2203 public void SerializeBase64Binary()
2205 XmlSerializer ser = new XmlSerializer (typeof (Base64Binary));
2206 sw = new StringWriter ();
2207 XmlTextWriter xtw = new XmlTextWriter (sw);
2208 ser.Serialize (xtw, new Base64Binary ());
2210 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"" />";
2211 Assert.AreEqual (Infoset (expected), WriterText);
2212 Base64Binary h = (Base64Binary) ser.Deserialize (new StringReader (sw.ToString ()));
2213 Assert.AreEqual (new byte [] {1, 2, 3}, h.Data);
2216 [Test] // bug #79989, #79990
2217 public void SerializeHexBinary ()
2219 XmlSerializer ser = new XmlSerializer (typeof (HexBinary));
2220 sw = new StringWriter ();
2221 XmlTextWriter xtw = new XmlTextWriter (sw);
2222 ser.Serialize (xtw, new HexBinary ());
2224 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"" />";
2225 Assert.AreEqual (Infoset (expected), WriterText);
2226 HexBinary h = (HexBinary) ser.Deserialize (new StringReader (sw.ToString ()));
2227 Assert.AreEqual (new byte[] { 1, 2, 3 }, h.Data);
2231 [ExpectedException (typeof (InvalidOperationException))]
2232 public void XmlArrayAttributeOnInt ()
2234 new XmlSerializer (typeof (XmlArrayOnInt));
2238 [ExpectedException (typeof (InvalidOperationException))]
2239 public void XmlArrayAttributeUnqualifiedWithNamespace ()
2241 new XmlSerializer (typeof (XmlArrayUnqualifiedWithNamespace));
2245 [ExpectedException (typeof (InvalidOperationException))]
2246 public void XmlArrayItemAttributeUnqualifiedWithNamespace ()
2248 new XmlSerializer (typeof (XmlArrayItemUnqualifiedWithNamespace));
2251 [Test] // bug #78042
2252 public void XmlArrayAttributeOnArray ()
2254 XmlSerializer ser = new XmlSerializer (typeof (XmlArrayOnArray));
2255 sw = new StringWriter ();
2256 XmlTextWriter xtw = new XmlTextWriter (sw);
2257 ser.Serialize (xtw, new XmlArrayOnArray ());
2259 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>";
2260 Assert.AreEqual (Infoset (expected), WriterText);
2264 public void XmlArrayAttributeOnCollection ()
2266 XmlSerializer ser = new XmlSerializer (typeof (XmlArrayOnArrayList));
2267 XmlArrayOnArrayList inst = new XmlArrayOnArrayList ();
2268 inst.Sane.Add ("abc");
2270 sw = new StringWriter ();
2271 XmlTextWriter xtw = new XmlTextWriter (sw);
2272 ser.Serialize (xtw, inst);
2274 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>";
2275 Assert.AreEqual (Infoset (expected), WriterText);
2278 [Test] // bug #338705
2279 public void SerializeTimeSpan ()
2281 // TimeSpan itself is not for duration. Hence it is just regarded as one of custom types.
2282 XmlSerializer ser = new XmlSerializer (typeof (TimeSpan));
2283 ser.Serialize (TextWriter.Null, TimeSpan.Zero);
2287 public void SerializeDurationToString ()
2289 XmlSerializer ser = new XmlSerializer (typeof (TimeSpanContainer1));
2290 ser.Serialize (TextWriter.Null, new TimeSpanContainer1 ());
2294 [ExpectedException (typeof (InvalidOperationException))]
2295 public void SerializeDurationToTimeSpan ()
2297 XmlSerializer ser = new XmlSerializer (typeof (TimeSpanContainer2));
2298 ser.Serialize (TextWriter.Null, new TimeSpanContainer2 ());
2302 [ExpectedException (typeof (InvalidOperationException))]
2303 public void SerializeInvalidDataType ()
2305 XmlSerializer ser = new XmlSerializer (typeof (InvalidTypeContainer));
2306 ser.Serialize (TextWriter.Null, new InvalidTypeContainer ());
2310 public void SerializeErrorneousIXmlSerializable ()
2312 Serialize (new ErrorneousGetSchema ());
2313 Assert.AreEqual ("<:ErrorneousGetSchema></>", Infoset (sw.ToString ()));
2316 public void DateTimeRoundtrip ()
2319 XmlSerializer ser = new XmlSerializer (typeof (DateTime));
2320 StringWriter sw = new StringWriter ();
2321 ser.Serialize (sw, DateTime.UtcNow);
2322 DateTime d = (DateTime) ser.Deserialize (new StringReader (sw.ToString ()));
2323 Assert.AreEqual (DateTimeKind.Utc, d.Kind);
2327 public void SupportIXmlSerializableImplicitlyConvertible ()
2329 XmlAttributes attrs = new XmlAttributes ();
2330 XmlElementAttribute attr = new XmlElementAttribute ();
2331 attr.ElementName = "XmlSerializable";
2332 attr.Type = typeof (XmlSerializableImplicitConvertible.XmlSerializable);
2333 attrs.XmlElements.Add (attr);
2334 XmlAttributeOverrides attrOverrides = new
2335 XmlAttributeOverrides ();
2336 attrOverrides.Add (typeof (XmlSerializableImplicitConvertible), "B", attrs);
2338 XmlSerializableImplicitConvertible x = new XmlSerializableImplicitConvertible ();
2339 new XmlSerializer (typeof (XmlSerializableImplicitConvertible), attrOverrides).Serialize (TextWriter.Null, x);
2342 [Test] // bug #566370
2343 public void SerializeEnumWithCSharpKeyword ()
2345 var ser = new XmlSerializer (typeof (DoxCompoundKind));
2346 for (int i = 0; i < 100; i++) // test serialization code generator
2347 ser.Serialize (Console.Out, DoxCompoundKind.@class);
2350 public enum DoxCompoundKind
2357 [XmlEnum("interface")]
2363 [XmlEnum("namespace")]
2371 #region GenericsSeralizationTests
2374 public void TestSerializeGenSimpleClassString ()
2376 GenSimpleClass<string> simple = new GenSimpleClass<string> ();
2378 Assert.AreEqual (Infoset ("<GenSimpleClassOfString xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />"), WriterText);
2380 simple.something = "hello";
2383 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);
2387 public void TestSerializeGenSimpleClassBool ()
2389 GenSimpleClass<bool> simple = new GenSimpleClass<bool> ();
2391 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);
2393 simple.something = true;
2396 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);
2400 public void TestSerializeGenSimpleStructInt ()
2402 GenSimpleStruct<int> simple = new GenSimpleStruct<int> (0);
2404 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);
2406 simple.something = 123;
2409 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);
2413 public void TestSerializeGenListClassString ()
2415 GenListClass<string> genlist = new GenListClass<string> ();
2416 Serialize (genlist);
2417 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);
2419 genlist.somelist.Add ("Value1");
2420 genlist.somelist.Add ("Value2");
2422 Serialize (genlist);
2423 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);
2427 public void TestSerializeGenListClassFloat ()
2429 GenListClass<float> genlist = new GenListClass<float> ();
2430 Serialize (genlist);
2431 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);
2433 genlist.somelist.Add (1);
2434 genlist.somelist.Add (2.2F);
2436 Serialize (genlist);
2437 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);
2441 public void TestSerializeGenListClassList ()
2443 GenListClass<GenListClass<int>> genlist = new GenListClass<GenListClass<int>> ();
2444 Serialize (genlist);
2445 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);
2447 GenListClass<int> inlist1 = new GenListClass<int> ();
2448 inlist1.somelist.Add (1);
2449 inlist1.somelist.Add (2);
2450 GenListClass<int> inlist2 = new GenListClass<int> ();
2451 inlist2.somelist.Add (10);
2452 inlist2.somelist.Add (20);
2453 genlist.somelist.Add (inlist1);
2454 genlist.somelist.Add (inlist2);
2456 Serialize (genlist);
2457 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);
2461 public void TestSerializeGenListClassArray ()
2463 GenListClass<GenArrayClass<char>> genlist = new GenListClass<GenArrayClass<char>> ();
2464 Serialize (genlist);
2465 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);
2467 GenArrayClass<char> genarr1 = new GenArrayClass<char> ();
2468 genarr1.arr[0] = 'a';
2469 genarr1.arr[1] = 'b';
2470 genlist.somelist.Add (genarr1);
2471 GenArrayClass<char> genarr2 = new GenArrayClass<char> ();
2472 genarr2.arr[0] = 'd';
2473 genarr2.arr[1] = 'e';
2474 genarr2.arr[2] = 'f';
2475 genlist.somelist.Add (genarr2);
2477 Serialize (genlist);
2478 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);
2482 public void TestSerializeGenTwoClassCharDouble ()
2484 GenTwoClass<char, double> gentwo = new GenTwoClass<char, double> ();
2486 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);
2488 gentwo.something1 = 'a';
2489 gentwo.something2 = 2.2;
2492 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);
2496 public void TestSerializeGenDerivedClassDecimalShort ()
2498 GenDerivedClass<decimal, short> derived = new GenDerivedClass<decimal, short> ();
2499 Serialize (derived);
2500 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);
2502 derived.something1 = "Value1";
2503 derived.something2 = 1;
2504 derived.another1 = 1.1M;
2505 derived.another2 = -22;
2507 Serialize (derived);
2508 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);
2512 public void TestSerializeGenDerivedSecondClassByteUlong ()
2514 GenDerived2Class<byte, ulong> derived2 = new GenDerived2Class<byte, ulong> ();
2515 Serialize (derived2);
2516 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);
2518 derived2.something1 = 1;
2519 derived2.something2 = 222;
2520 derived2.another1 = 111;
2521 derived2.another2 = 222222;
2523 Serialize (derived2);
2524 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);
2528 public void TestSerializeGenNestedClass ()
2530 GenNestedClass<string, int>.InnerClass<bool> nested =
2531 new GenNestedClass<string, int>.InnerClass<bool> ();
2533 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);
2536 nested.something = true;
2539 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);
2543 public void TestSerializeGenListClassListNested ()
2545 GenListClass<GenListClass<GenNestedClass<int, int>.InnerClass<string>>> genlist =
2546 new GenListClass<GenListClass<GenNestedClass<int, int>.InnerClass<string>>> ();
2547 Serialize (genlist);
2548 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);
2550 GenListClass<GenNestedClass<int, int>.InnerClass<string>> inlist1 =
2551 new GenListClass<GenNestedClass<int, int>.InnerClass<string>> ();
2552 GenNestedClass<int, int>.InnerClass<string> inval1 = new GenNestedClass<int, int>.InnerClass<string> ();
2554 inval1.something = "ONE";
2555 inlist1.somelist.Add (inval1);
2556 GenNestedClass<int, int>.InnerClass<string> inval2 = new GenNestedClass<int, int>.InnerClass<string> ();
2558 inval2.something = "TWO";
2559 inlist1.somelist.Add (inval2);
2560 GenListClass<GenNestedClass<int, int>.InnerClass<string>> inlist2 =
2561 new GenListClass<GenNestedClass<int, int>.InnerClass<string>> ();
2562 GenNestedClass<int, int>.InnerClass<string> inval3 = new GenNestedClass<int, int>.InnerClass<string> ();
2564 inval3.something = "THIRTY";
2565 inlist2.somelist.Add (inval3);
2566 genlist.somelist.Add (inlist1);
2567 genlist.somelist.Add (inlist2);
2569 Serialize (genlist);
2570 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);
2573 public enum Myenum { one, two, three, four, five, six };
2575 public void TestSerializeGenArrayClassEnum ()
2577 GenArrayClass<Myenum> genarr = new GenArrayClass<Myenum> ();
2579 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);
2581 genarr.arr[0] = Myenum.one;
2582 genarr.arr[1] = Myenum.three;
2583 genarr.arr[2] = Myenum.five;
2586 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);
2590 public void TestSerializeGenArrayStruct ()
2592 GenArrayClass<GenSimpleStruct<uint>> genarr = new GenArrayClass<GenSimpleStruct<uint>> ();
2594 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);
2596 GenSimpleStruct<uint> genstruct = new GenSimpleStruct<uint> ();
2597 genstruct.something = 111;
2598 genarr.arr[0] = genstruct;
2599 genstruct.something = 222;
2600 genarr.arr[1] = genstruct;
2601 genstruct.something = 333;
2602 genarr.arr[2] = genstruct;
2605 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);
2609 public void TestSerializeGenArrayList ()
2611 GenArrayClass<GenListClass<string>> genarr = new GenArrayClass<GenListClass<string>> ();
2613 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);
2615 GenListClass<string> genlist1 = new GenListClass<string> ();
2616 genlist1.somelist.Add ("list1-val1");
2617 genlist1.somelist.Add ("list1-val2");
2618 genarr.arr[0] = genlist1;
2619 GenListClass<string> genlist2 = new GenListClass<string> ();
2620 genlist2.somelist.Add ("list2-val1");
2621 genlist2.somelist.Add ("list2-val2");
2622 genlist2.somelist.Add ("list2-val3");
2623 genlist2.somelist.Add ("list2-val4");
2624 genarr.arr[1] = genlist2;
2625 GenListClass<string> genlist3 = new GenListClass<string> ();
2626 genlist3.somelist.Add ("list3val");
2627 genarr.arr[2] = genlist3;
2630 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);
2634 public void TestSerializeGenComplexStruct ()
2636 GenComplexStruct<int, string> complex = new GenComplexStruct<int, string> (0);
2637 Serialize (complex);
2638 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);
2640 complex.something = 123;
2641 complex.simpleclass.something = 456;
2642 complex.simplestruct.something = 789;
2643 GenListClass<int> genlist = new GenListClass<int> ();
2644 genlist.somelist.Add (100);
2645 genlist.somelist.Add (200);
2646 complex.listclass = genlist;
2647 GenArrayClass<int> genarr = new GenArrayClass<int> ();
2651 complex.arrayclass = genarr;
2652 complex.twoclass.something1 = 10;
2653 complex.twoclass.something2 = "Ten";
2654 complex.derivedclass.another1 = 1;
2655 complex.derivedclass.another2 = "one";
2656 complex.derivedclass.something1 = "two";
2657 complex.derivedclass.something2 = 2;
2658 complex.derived2.another1 = 3;
2659 complex.derived2.another2 = "three";
2660 complex.derived2.something1 = 4;
2661 complex.derived2.something2 = "four";
2662 complex.nestedouter.outer = 5;
2663 complex.nestedinner.inner = "six";
2664 complex.nestedinner.something = 6;
2666 Serialize (complex);
2667 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);
2670 [Test] // bug #80759
2671 public void HasNullableField ()
2673 Bug80759 foo = new Bug80759 ();
2675 foo.NullableInt = 10;
2677 XmlSerializer serializer = new XmlSerializer (typeof (Bug80759));
2679 MemoryStream stream = new MemoryStream ();
2681 serializer.Serialize (stream, foo);
2682 stream.Position = 0;
2683 foo = (Bug80759) serializer.Deserialize (stream);
2686 [Test] // bug #80759, with fieldSpecified.
2687 [ExpectedException (typeof (InvalidOperationException))]
2688 [Category ("NotWorking")]
2689 public void HasFieldSpecifiedButIrrelevant ()
2691 Bug80759_2 foo = new Bug80759_2 ();
2693 foo.NullableInt = 10;
2695 XmlSerializer serializer = new XmlSerializer (typeof (Bug80759_2));
2697 MemoryStream stream = new MemoryStream ();
2699 serializer.Serialize (stream, foo);
2700 stream.Position = 0;
2701 foo = (Bug80759_2) serializer.Deserialize (stream);
2705 public void HasNullableField2 ()
2707 Bug80759 foo = new Bug80759 ();
2709 foo.NullableInt = 10;
2711 XmlSerializer serializer = new XmlSerializer (typeof (Bug80759));
2713 MemoryStream stream = new MemoryStream ();
2715 serializer.Serialize (stream, foo);
2716 stream.Position = 0;
2717 foo = (Bug80759) serializer.Deserialize (stream);
2719 Assert.AreEqual ("BAR", foo.Test, "#1");
2720 Assert.AreEqual (10, foo.NullableInt, "#2");
2722 foo.NullableInt = null;
2723 stream = new MemoryStream ();
2724 serializer.Serialize (stream, foo);
2725 stream.Position = 0;
2726 foo = (Bug80759) serializer.Deserialize (stream);
2728 Assert.AreEqual ("BAR", foo.Test, "#3");
2729 Assert.IsNull (foo.NullableInt, "#4");
2733 public void SupportPrivateCtorOnly ()
2736 new XmlSerializer (typeof (PrivateCtorOnly));
2737 StringWriter sw = new StringWriter ();
2738 xs.Serialize (sw, PrivateCtorOnly.Instance);
2739 xs.Deserialize (new StringReader (sw.ToString ()));
2743 public void XmlSchemaProviderQNameBecomesRootName ()
2745 xs = new XmlSerializer (typeof (XmlSchemaProviderQNameBecomesRootNameType));
2746 Serialize (new XmlSchemaProviderQNameBecomesRootNameType ());
2747 Assert.AreEqual (Infoset ("<foo />"), WriterText);
2748 xs.Deserialize (new StringReader ("<foo/>"));
2752 public void XmlSchemaProviderQNameBecomesRootName2 ()
2754 string xml = "<XmlSchemaProviderQNameBecomesRootNameType2 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Foo><foo /></Foo></XmlSchemaProviderQNameBecomesRootNameType2>";
2755 xs = new XmlSerializer (typeof (XmlSchemaProviderQNameBecomesRootNameType2));
2756 Serialize (new XmlSchemaProviderQNameBecomesRootNameType2 ());
2757 Assert.AreEqual (Infoset (xml), WriterText);
2758 xs.Deserialize (new StringReader (xml));
2762 public void XmlAnyElementForObjects () // bug #553032
2764 new XmlSerializer (typeof (XmlAnyElementForObjectsType));
2768 [ExpectedException (typeof (InvalidOperationException))]
2769 public void XmlAnyElementForObjects2 () // bug #553032-2
2771 new XmlSerializer (typeof (XmlAnyElementForObjectsType)).Serialize (TextWriter.Null, new XmlAnyElementForObjectsType ());
2775 public class Bug2893 {
2778 Contents = new XmlDataDocument();
2781 [XmlAnyElement("Contents")]
2782 public XmlNode Contents;
2785 // Bug Xamarin #2893
2787 public void XmlAnyElementForXmlNode ()
2789 var obj = new Bug2893 ();
2790 XmlSerializer mySerializer = new XmlSerializer(typeof(Bug2893));
2791 XmlWriterSettings settings = new XmlWriterSettings();
2793 var xsn = new XmlSerializerNamespaces();
2794 xsn.Add(string.Empty, string.Empty);
2796 byte[] buffer = new byte[2048];
2797 var ms = new MemoryStream(buffer);
2798 using (var xw = XmlWriter.Create(ms, settings))
2800 mySerializer.Serialize(xw, obj, xsn);
2804 mySerializer.Serialize(ms, obj);
2808 public void XmlRootOverridesSchemaProviderQName ()
2810 var obj = new XmlRootOverridesSchemaProviderQNameType ();
2812 XmlSerializer xs = new XmlSerializer (obj.GetType ());
2814 var sw = new StringWriter ();
2815 using (XmlWriter xw = XmlWriter.Create (sw))
2816 xs.Serialize (xw, obj);
2817 Assert.IsTrue (sw.ToString ().IndexOf ("foo") > 0, "#1");
2820 public class AnotherArrayListType
2823 public string one = "aaa";
2825 public string another = "bbb";
2828 public class DerivedArrayListType : AnotherArrayListType
2833 public class ClassWithArrayList
2835 [XmlElement (Type = typeof(int), ElementName = "int_elem")]
2836 [XmlElement (Type = typeof(string), ElementName = "string_elem")]
2837 [XmlElement (Type = typeof(AnotherArrayListType), ElementName = "another_elem")]
2838 [XmlElement (Type = typeof(DerivedArrayListType), ElementName = "derived_elem")]
2839 public ArrayList list;
2842 public class ClassWithArray
2844 [XmlElement (Type = typeof(int), ElementName = "int_elem")]
2845 [XmlElement (Type = typeof(string), ElementName = "string_elem")]
2846 [XmlElement (Type = typeof(AnotherArrayListType), ElementName = "another_elem")]
2847 [XmlElement (Type = typeof(DerivedArrayListType), ElementName = "derived_elem")]
2848 public object[] list;
2853 public void MultipleXmlElementAttributesOnArrayList()
2855 var test = new ClassWithArrayList();
2857 test.list = new ArrayList();
2859 test.list.Add("apepe");
2860 test.list.Add(new AnotherArrayListType());
2861 test.list.Add(new DerivedArrayListType());
2864 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'></></>";
2866 Assert.AreEqual(WriterText, expected_text, WriterText);
2870 public void MultipleXmlElementAttributesOnArray()
2872 var test = new ClassWithArray();
2874 test.list = new object[] { 3, "apepe", new AnotherArrayListType(), new DerivedArrayListType() };
2877 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'></></>";
2879 Assert.AreEqual(WriterText, expected_text, WriterText);
2883 #endregion //GenericsSeralizationTests
2884 #region XmlInclude on abstract class tests (Bug #18558)
2886 public void TestSerializeIntermediateType ()
2888 string expectedXml = "<ContainerTypeForTest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><XmlIntermediateType intermediate=\"false\"/></ContainerTypeForTest>";
2889 var obj = new ContainerTypeForTest();
2890 obj.MemberToUseInclude = new IntermediateTypeForTest ();
2892 Assert.AreEqual (Infoset (expectedXml), WriterText, "Serialized Output : " + WriterText);
2896 public void TestSerializeSecondType ()
2898 string expectedXml = "<ContainerTypeForTest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><XmlSecondType intermediate=\"false\"/></ContainerTypeForTest>";
2899 var obj = new ContainerTypeForTest();
2900 obj.MemberToUseInclude = new SecondDerivedTypeForTest ();
2902 Assert.AreEqual (Infoset (expectedXml), WriterText, "Serialized Output : " + WriterText);
2905 public class XmlArrayOnInt
2911 public class XmlArrayUnqualifiedWithNamespace
2913 [XmlArray (Namespace = "", Form = XmlSchemaForm.Unqualified)]
2914 public ArrayList Sane = new ArrayList ();
2917 public class XmlArrayItemUnqualifiedWithNamespace
2919 [XmlArrayItem ("foo", Namespace = "", Form = XmlSchemaForm.Unqualified)]
2920 public ArrayList Sane = new ArrayList ();
2923 [XmlRoot (Namespace = "urn:foo")]
2924 public class XmlArrayOnArrayList
2926 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2927 public ArrayList Sane = new ArrayList ();
2930 [XmlRoot (Namespace = "urn:foo")]
2931 public class XmlArrayOnArray
2933 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2934 public string[] Sane = new string[] { "foo", "bar" };
2936 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2937 public ArrayItemInXmlArray[] Mids =
2938 new ArrayItemInXmlArray[] { new ArrayItemInXmlArray () };
2941 [XmlType (Namespace = "urn:gyabo")]
2942 public class ArrayItemInXmlArray
2944 [XmlArray (Form = XmlSchemaForm.Unqualified)]
2945 public string[] Whee = new string[] { "foo", "bar" };
2948 [XmlRoot ("Base64Binary")]
2949 public class Base64Binary
2951 [XmlAttribute (DataType = "base64Binary")]
2952 public byte [] Data = new byte [] {1, 2, 3};
2955 [XmlRoot ("HexBinary")]
2956 public class HexBinary
2958 [XmlAttribute (DataType = "hexBinary")]
2959 public byte[] Data = new byte[] { 1, 2, 3 };
2962 [XmlRoot ("PrivateCtorOnly")]
2963 public class PrivateCtorOnly
2965 public static PrivateCtorOnly Instance = new PrivateCtorOnly ();
2966 private PrivateCtorOnly ()
2971 public class CDataTextNodesType
2973 public CDataTextNodesInternal foo;
2976 public class CDataTextNodesInternal
2979 public string Value;
2982 public class InvalidTypeContainer
2984 [XmlElement (DataType = "invalid")]
2985 public string InvalidTypeItem = "aaa";
2988 public class TimeSpanContainer1
2990 [XmlElement (DataType = "duration")]
2991 public string StringDuration = "aaa";
2994 public class TimeSpanContainer2
2996 [XmlElement (DataType = "duration")]
2997 public TimeSpan StringDuration = TimeSpan.FromSeconds (1);
3000 public class Bug80759
3003 public int? NullableInt;
3006 public class Bug80759_2
3009 public int? NullableInt;
3012 public bool NullableIntSpecified {
3013 get { return NullableInt.HasValue; }
3017 [XmlSchemaProvider ("GetXsdType")]
3018 public class XmlSchemaProviderQNameBecomesRootNameType : IXmlSerializable
3020 public XmlSchema GetSchema ()
3025 public void ReadXml (XmlReader reader)
3030 public void WriteXml (XmlWriter writer)
3034 public static XmlQualifiedName GetXsdType (XmlSchemaSet xss)
3036 if (xss.Count == 0) {
3037 XmlSchema xs = new XmlSchema ();
3038 XmlSchemaComplexType ct = new XmlSchemaComplexType ();
3043 return new XmlQualifiedName ("foo");
3047 public class XmlSchemaProviderQNameBecomesRootNameType2
3049 [XmlArrayItem (typeof (XmlSchemaProviderQNameBecomesRootNameType))]
3050 public object [] Foo = new object [] {new XmlSchemaProviderQNameBecomesRootNameType ()};
3053 public class XmlAnyElementForObjectsType
3056 public object [] arr = new object [] {3,4,5};
3060 [XmlSchemaProvider ("GetSchema")]
3061 public class XmlRootOverridesSchemaProviderQNameType : IXmlSerializable
3063 public static XmlQualifiedName GetSchema (XmlSchemaSet xss)
3065 var xs = new XmlSchema ();
3066 var xse = new XmlSchemaComplexType () { Name = "bar" };
3069 return new XmlQualifiedName ("bar");
3072 XmlSchema IXmlSerializable.GetSchema ()
3077 void IXmlSerializable.ReadXml (XmlReader reader)
3080 void IXmlSerializable.WriteXml (XmlWriter writer)
3086 void CDataTextNodes_BadNode (object s, XmlNodeEventArgs e)
3093 public static string Infoset (string sx)
3095 XmlDocument doc = new XmlDocument ();
3097 StringBuilder sb = new StringBuilder ();
3098 GetInfoset (doc.DocumentElement, sb);
3099 return sb.ToString ();
3102 public static string Infoset (XmlNode nod)
3104 StringBuilder sb = new StringBuilder ();
3105 GetInfoset (nod, sb);
3106 return sb.ToString ();
3109 static void GetInfoset (XmlNode nod, StringBuilder sb)
3111 switch (nod.NodeType) {
3112 case XmlNodeType.Attribute:
3113 if (nod.LocalName == "xmlns" && nod.NamespaceURI == "http://www.w3.org/2000/xmlns/") return;
3114 sb.Append (" " + nod.NamespaceURI + ":" + nod.LocalName + "='" + nod.Value + "'");
3117 case XmlNodeType.Element:
3118 XmlElement elem = (XmlElement) nod;
3119 sb.Append ("<" + elem.NamespaceURI + ":" + elem.LocalName);
3121 ArrayList ats = new ArrayList ();
3122 foreach (XmlAttribute at in elem.Attributes)
3123 ats.Add (at.LocalName + " " + at.NamespaceURI);
3127 foreach (string name in ats) {
3128 string[] nn = name.Split (' ');
3129 GetInfoset (elem.Attributes[nn[0], nn[1]], sb);
3133 foreach (XmlNode cn in elem.ChildNodes)
3134 GetInfoset (cn, sb);
3139 sb.Append (nod.OuterXml);
3144 static XmlTypeMapping CreateSoapMapping (Type type)
3146 SoapReflectionImporter importer = new SoapReflectionImporter ();
3147 return importer.ImportTypeMapping (type);
3150 static XmlTypeMapping CreateSoapMapping (Type type, SoapAttributeOverrides ao)
3152 SoapReflectionImporter importer = new SoapReflectionImporter (ao);
3153 return importer.ImportTypeMapping (type);
3156 static XmlTypeMapping CreateSoapMapping (Type type, SoapAttributeOverrides ao, string defaultNamespace)
3158 SoapReflectionImporter importer = new SoapReflectionImporter (ao, defaultNamespace);
3159 return importer.ImportTypeMapping (type);
3162 [XmlSchemaProvider (null, IsAny = true)]
3163 public class AnySchemaProviderClass : IXmlSerializable {
3167 void IXmlSerializable.WriteXml (XmlWriter writer)
3169 writer.WriteElementString ("text", Text);
3172 void IXmlSerializable.ReadXml (XmlReader reader)
3174 Text = reader.ReadElementString ("text");
3177 XmlSchema IXmlSerializable.GetSchema ()
3184 public void SerializeAnySchemaProvider ()
3186 string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
3187 Environment.NewLine + "<text>test</text>";
3189 var ser = new XmlSerializer (typeof (AnySchemaProviderClass));
3191 var obj = new AnySchemaProviderClass {
3195 using (var t = new StringWriter ()) {
3196 ser.Serialize (t, obj);
3197 Assert.AreEqual (expected, t.ToString ());
3202 public void DeserializeAnySchemaProvider ()
3204 string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
3205 Environment.NewLine + "<text>test</text>";
3207 var ser = new XmlSerializer (typeof (AnySchemaProviderClass));
3209 using (var t = new StringReader (expected)) {
3210 var obj = (AnySchemaProviderClass) ser.Deserialize (t);
3211 Assert.AreEqual ("test", obj.Text);
3215 public class SubNoParameterlessConstructor : NoParameterlessConstructor
3217 public SubNoParameterlessConstructor ()
3223 public class NoParameterlessConstructor
3225 [XmlElement ("Text")]
3228 public NoParameterlessConstructor (string parameter)
3234 public void BaseClassWithoutParameterlessConstructor ()
3236 var ser = new XmlSerializer (typeof (SubNoParameterlessConstructor));
3238 var obj = new SubNoParameterlessConstructor {
3242 using (var w = new StringWriter ()) {
3243 ser.Serialize (w, obj);
3244 using (var r = new StringReader ( w.ToString ())) {
3245 var desObj = (SubNoParameterlessConstructor) ser.Deserialize (r);
3246 Assert.AreEqual (obj.Text, desObj.Text);
3251 public class ClassWithXmlAnyElement
3253 [XmlAnyElement ("Contents")]
3254 public XmlNode Contents;
3258 public void TestClassWithXmlAnyElement ()
3260 var d = new XmlDocument ();
3261 var e = d.CreateElement ("Contents");
3262 e.AppendChild (d.CreateElement ("SomeElement"));
3264 var c = new ClassWithXmlAnyElement {
3268 var ser = new XmlSerializer (typeof (ClassWithXmlAnyElement));
3269 using (var sw = new StringWriter ())
3270 ser.Serialize (sw, c);
3274 public void ClassWithImplicitlyConvertibleElement ()
3276 var ser = new XmlSerializer (typeof (ObjectWithElementRequiringImplicitCast));
3278 var obj = new ObjectWithElementRequiringImplicitCast ("test");
3280 using (var w = new StringWriter ()) {
3281 ser.Serialize (w, obj);
3282 using (var r = new StringReader ( w.ToString ())) {
3283 var desObj = (ObjectWithElementRequiringImplicitCast) ser.Deserialize (r);
3284 Assert.AreEqual (obj.Object.Text, desObj.Object.Text);
3289 public class ClassWithOptionalMethods
3291 private readonly bool shouldSerializeX;
3292 private readonly bool xSpecified;
3295 public int X { get; set; }
3297 public bool ShouldSerializeX () { return shouldSerializeX; }
3299 public bool XSpecified
3301 get { return xSpecified; }
3304 public ClassWithOptionalMethods ()
3308 public ClassWithOptionalMethods (int x, bool shouldSerializeX, bool xSpecified)
3311 this.shouldSerializeX = shouldSerializeX;
3312 this.xSpecified = xSpecified;
3317 public void OptionalMethods ()
3319 var ser = new XmlSerializer (typeof (ClassWithOptionalMethods));
3321 var expectedValueWithoutX = Infoset ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
3322 "<ClassWithOptionalMethods xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" />");
3324 var expectedValueWithX = Infoset ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
3325 "<ClassWithOptionalMethods xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" X=\"11\" />");
3327 using (var t = new StringWriter ()) {
3328 var obj = new ClassWithOptionalMethods (11, false, false);
3329 ser.Serialize (t, obj);
3330 Assert.AreEqual (expectedValueWithoutX, Infoset (t.ToString ()));
3333 using (var t = new StringWriter ()) {
3334 var obj = new ClassWithOptionalMethods (11, true, false);
3335 ser.Serialize (t, obj);
3336 Assert.AreEqual (expectedValueWithoutX, Infoset (t.ToString ()));
3339 using (var t = new StringWriter ()) {
3340 var obj = new ClassWithOptionalMethods (11, false, true);
3341 ser.Serialize (t, obj);
3342 Assert.AreEqual (expectedValueWithoutX, Infoset (t.ToString ()));
3345 using (var t = new StringWriter ()) {
3346 var obj = new ClassWithOptionalMethods (11, true, true);
3347 ser.Serialize (t, obj);
3348 Assert.AreEqual (expectedValueWithX, Infoset (t.ToString ()));
3352 public class ClassWithShouldSerializeGeneric
3355 public int X { get; set; }
3357 public bool ShouldSerializeX<T> () { return false; }
3361 [Category("NotDotNet")]
3362 public void ShouldSerializeGeneric ()
3364 var ser = new XmlSerializer (typeof (ClassWithShouldSerializeGeneric));
3366 var expectedValueWithX = Infoset ("<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
3367 "<ClassWithShouldSerializeGeneric xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" X=\"11\" />");
3369 using (var t = new StringWriter ()) {
3370 var obj = new ClassWithShouldSerializeGeneric { X = 11 };
3371 ser.Serialize (t, obj);
3372 Assert.AreEqual (expectedValueWithX, Infoset (t.ToString ()));
3377 public void NullableArrayItems ()
3379 var ser = new XmlSerializer (typeof (ObjectWithNullableArrayItems));
3381 var obj = new ObjectWithNullableArrayItems ();
3382 obj.Elements = new List <SimpleClass> ();
3383 obj.Elements.Add (new SimpleClass { something = "Hello" });
3384 obj.Elements.Add (null);
3385 obj.Elements.Add (new SimpleClass { something = "World" });
3387 using (var w = new StringWriter ()) {
3388 ser.Serialize (w, obj);
3389 using (var r = new StringReader ( w.ToString ())) {
3390 var desObj = (ObjectWithNullableArrayItems) ser.Deserialize (r);
3391 Assert.IsNull (desObj.Elements [1]);
3397 public void NonNullableArrayItems ()
3399 var ser = new XmlSerializer (typeof (ObjectWithNonNullableArrayItems));
3401 var obj = new ObjectWithNonNullableArrayItems ();
3402 obj.Elements = new List <SimpleClass> ();
3403 obj.Elements.Add (new SimpleClass { something = "Hello" });
3404 obj.Elements.Add (null);
3405 obj.Elements.Add (new SimpleClass { something = "World" });
3407 using (var w = new StringWriter ()) {
3408 ser.Serialize (w, obj);
3409 using (var r = new StringReader ( w.ToString ())) {
3410 var desObj = (ObjectWithNonNullableArrayItems) ser.Deserialize (r);
3411 Assert.IsNotNull (desObj.Elements [1]);
3417 public void NotSpecifiedNullableArrayItems ()
3419 var ser = new XmlSerializer (typeof (ObjectWithNotSpecifiedNullableArrayItems));
3421 var obj = new ObjectWithNotSpecifiedNullableArrayItems ();
3422 obj.Elements = new List <SimpleClass> ();
3423 obj.Elements.Add (new SimpleClass { something = "Hello" });
3424 obj.Elements.Add (null);
3425 obj.Elements.Add (new SimpleClass { something = "World" });
3427 using (var w = new StringWriter ()) {
3428 ser.Serialize (w, obj);
3429 using (var r = new StringReader ( w.ToString ())) {
3430 var desObj = (ObjectWithNotSpecifiedNullableArrayItems) ser.Deserialize (r);
3431 Assert.IsNull (desObj.Elements [1]);
3436 private static void TestClassWithDefaultTextNotNullAux (string value, string expected)
3438 var obj = new ClassWithDefaultTextNotNull (value);
3439 var ser = new XmlSerializer (typeof (ClassWithDefaultTextNotNull));
3441 using (var mstream = new MemoryStream ())
3442 using (var writer = new XmlTextWriter (mstream, Encoding.ASCII)) {
3443 ser.Serialize (writer, obj);
3445 mstream.Seek (0, SeekOrigin.Begin);
3446 using (var reader = new XmlTextReader (mstream)) {
3447 var result = (ClassWithDefaultTextNotNull) ser.Deserialize (reader);
3448 Assert.AreEqual (expected, result.Value);
3454 public void TestClassWithDefaultTextNotNull ()
3456 TestClassWithDefaultTextNotNullAux ("my_text", "my_text");
3457 TestClassWithDefaultTextNotNullAux ("", ClassWithDefaultTextNotNull.DefaultValue);
3458 TestClassWithDefaultTextNotNullAux (null, ClassWithDefaultTextNotNull.DefaultValue);
3462 // Test generated serialization code.
3463 public class XmlSerializerGeneratorTests : XmlSerializerTests {
3465 private FieldInfo backgroundGeneration;
3466 private FieldInfo generationThreshold;
3467 private FieldInfo generatorFallback;
3469 private bool backgroundGenerationOld;
3470 private int generationThresholdOld;
3471 private bool generatorFallbackOld;
3474 public void SetUp ()
3476 // Make sure XmlSerializer static constructor is called
3477 XmlSerializer.FromTypes (new Type [] {});
3479 const BindingFlags binding = BindingFlags.Static | BindingFlags.NonPublic;
3480 backgroundGeneration = typeof (XmlSerializer).GetField ("backgroundGeneration", binding);
3481 generationThreshold = typeof (XmlSerializer).GetField ("generationThreshold", binding);
3482 generatorFallback = typeof (XmlSerializer).GetField ("generatorFallback", binding);
3484 if (backgroundGeneration == null)
3485 Assert.Ignore ("Unable to access field backgroundGeneration");
3486 if (generationThreshold == null)
3487 Assert.Ignore ("Unable to access field generationThreshold");
3488 if (generatorFallback == null)
3489 Assert.Ignore ("Unable to access field generatorFallback");
3491 backgroundGenerationOld = (bool) backgroundGeneration.GetValue (null);
3492 generationThresholdOld = (int) generationThreshold.GetValue (null);
3493 generatorFallbackOld = (bool) generatorFallback.GetValue (null);
3495 backgroundGeneration.SetValue (null, false);
3496 generationThreshold.SetValue (null, 0);
3497 generatorFallback.SetValue (null, false);
3501 public void TearDown ()
3503 if (backgroundGeneration == null || generationThreshold == null || generatorFallback == null)
3506 backgroundGeneration.SetValue (null, backgroundGenerationOld);
3507 generationThreshold.SetValue (null, generationThresholdOld);
3508 generatorFallback.SetValue (null, generatorFallbackOld);
3512 #region XmlInclude on abstract class test classes
3515 public class ContainerTypeForTest
3517 [XmlElement ("XmlSecondType", typeof (SecondDerivedTypeForTest))]
3518 [XmlElement ("XmlIntermediateType", typeof (IntermediateTypeForTest))]
3519 [XmlElement ("XmlFirstType", typeof (FirstDerivedTypeForTest))]
3520 public AbstractTypeForTest MemberToUseInclude { get; set; }
3523 [XmlInclude (typeof (SecondDerivedTypeForTest))]
3524 [XmlInclude (typeof (IntermediateTypeForTest))]
3525 [XmlInclude (typeof (FirstDerivedTypeForTest))]
3526 public abstract class AbstractTypeForTest
3530 public class IntermediateTypeForTest : AbstractTypeForTest
3532 [XmlAttribute (AttributeName = "intermediate")]
3533 public bool IntermediateMember { get; set; }
3536 public class FirstDerivedTypeForTest : AbstractTypeForTest
3538 public string FirstMember { get; set; }
3541 public class SecondDerivedTypeForTest : IntermediateTypeForTest
3543 public string SecondMember { get; set; }