// // XmlObjectSerializerTest.cs // // Author: // Atsushi Enomoto // Ankit Jain // // Copyright (C) 2005 Novell, Inc. http://www.novell.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // This test code contains tests for both DataContractSerializer and // NetDataContractSerializer. The code could be mostly common. // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Net; using System.Runtime.Serialization; using System.Text; using System.Xml; using NUnit.Framework; using System.Xml.Serialization; using System.Xml.Schema; namespace MonoTests.System.Runtime.Serialization { [TestFixture] public class DataContractSerializerTest { static readonly XmlWriterSettings settings; static DataContractSerializerTest () { settings = new XmlWriterSettings (); settings.OmitXmlDeclaration = true; } [DataContract] class Sample1 { [DataMember] public string Member1; } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ConstructorTypeNull () { new DataContractSerializer (null); } [Test] public void ConstructorKnownTypesNull () { // null knownTypes is allowed. new DataContractSerializer (typeof (Sample1), null); new DataContractSerializer (typeof (Sample1), "Foo", String.Empty, null); new DataContractSerializer (typeof (Sample1), new XmlDictionary ().Add ("Foo"), XmlDictionaryString.Empty, null); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ConstructorNameNull () { new DataContractSerializer (typeof (Sample1), null, String.Empty); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ConstructorNamespaceNull () { new DataContractSerializer (typeof (Sample1), "foo", null); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void ConstructorNegativeMaxObjects () { new DataContractSerializer (typeof (Sample1), null, -1, false, false, null); } [Test] public void ConstructorMisc () { new DataContractSerializer (typeof (GlobalSample1)); } [Test] public void WriteObjectContent () { StringWriter sw = new StringWriter (); using (XmlWriter xw = XmlWriter.Create (sw, settings)) { DataContractSerializer ser = new DataContractSerializer (typeof (string)); xw.WriteStartElement ("my-element"); ser.WriteObjectContent (xw, "TEST STRING"); xw.WriteEndElement (); } Assert.AreEqual ("TEST STRING", sw.ToString ()); } [Test] public void WriteObjectToStream () { DataContractSerializer ser = new DataContractSerializer (typeof (int)); MemoryStream sw = new MemoryStream (); ser.WriteObject (sw, 1); string expected = "1"; byte[] buf = sw.ToArray (); Assert.AreEqual (expected, Encoding.UTF8.GetString (buf, 0, buf.Length)); } [Test] public void ReadObjectFromStream () { DataContractSerializer ser = new DataContractSerializer (typeof (int)); string expected = "1"; byte[] buf = Encoding.UTF8.GetBytes (expected); MemoryStream sw = new MemoryStream (buf); object res = ser.ReadObject (sw); Assert.AreEqual (1, res); } // int [Test] public void SerializeInt () { DataContractSerializer ser = new DataContractSerializer (typeof (int)); SerializeInt (ser, "1"); } [Test] [Category ("NotWorking")] public void NetSerializeInt () { NetDataContractSerializer ser = new NetDataContractSerializer (); // z:Assembly="0" ??? SerializeInt (ser, String.Format ("1", typeof (int).Assembly.FullName)); } void SerializeInt (XmlObjectSerializer ser, string expected) { StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, 1); } Assert.AreEqual (expected, sw.ToString ()); } // pass typeof(DCEmpty), serialize int [Test] public void SerializeIntForDCEmpty () { DataContractSerializer ser = new DataContractSerializer (typeof (DCEmpty)); // tricky! SerializeIntForDCEmpty (ser, "1"); } void SerializeIntForDCEmpty (XmlObjectSerializer ser, string expected) { StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, 1); } XmlComparer.AssertAreEqual (expected, sw.ToString ()); } // DCEmpty [Test] public void SerializeEmptyClass () { DataContractSerializer ser = new DataContractSerializer (typeof (DCEmpty)); SerializeEmptyClass (ser, ""); } [Test] [Category ("NotWorking")] public void NetSerializeEmptyClass () { NetDataContractSerializer ser = new NetDataContractSerializer (); SerializeEmptyClass (ser, String.Format ("", this.GetType ().Assembly.FullName)); } void SerializeEmptyClass (XmlObjectSerializer ser, string expected) { StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCEmpty ()); } Assert.AreEqual (expected, sw.ToString ()); } // DCEmpty [Test] public void SerializeEmptyNoNSClass () { var ser = new DataContractSerializer (typeof (DCEmptyNoNS)); SerializeEmptyNoNSClass (ser, ""); } void SerializeEmptyNoNSClass (XmlObjectSerializer ser, string expected) { var sw = new StringWriter (); using (var w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCEmptyNoNS ()); } Assert.AreEqual (expected, sw.ToString ()); } // string (primitive) [Test] public void SerializePrimitiveString () { XmlObjectSerializer ser = new DataContractSerializer (typeof (string)); SerializePrimitiveString (ser, "TEST"); } [Test] [Category ("NotWorking")] public void NetSerializePrimitiveString () { XmlObjectSerializer ser = new NetDataContractSerializer (); SerializePrimitiveString (ser, "TEST"); } void SerializePrimitiveString (XmlObjectSerializer ser, string expected) { StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, "TEST"); } Assert.AreEqual (expected, sw.ToString ()); } // QName (primitive but ...) [Test] [Ignore ("These tests would not make any sense right now since it's populated prefix is not testable.")] public void SerializePrimitiveQName () { XmlObjectSerializer ser = new DataContractSerializer (typeof (XmlQualifiedName)); SerializePrimitiveQName (ser, "d7:foo"); } [Test] [Ignore ("These tests would not make any sense right now since it's populated prefix is not testable.")] public void NetSerializePrimitiveQName () { XmlObjectSerializer ser = new NetDataContractSerializer (); SerializePrimitiveQName (ser, "d7:foo"); } void SerializePrimitiveQName (XmlObjectSerializer ser, string expected) { StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new XmlQualifiedName ("foo", "urn:foo")); } Assert.AreEqual (expected, sw.ToString ()); } // DCSimple1 [Test] public void SerializeSimpleClass1 () { DataContractSerializer ser = new DataContractSerializer (typeof (DCSimple1)); SerializeSimpleClass1 (ser, "TEST"); } [Test] [ExpectedException (typeof (SerializationException))] [Category ("NotWorking")] // behavior changed in 3.5/SP1 public void SerializeSimpleXml () { DataContractSerializer ser = new DataContractSerializer (typeof (SimpleXml)); SerializeSimpleClass1 (ser, @"TEST"); } [Test] [Category ("NotWorking")] public void NetSerializeSimpleClass1 () { NetDataContractSerializer ser = new NetDataContractSerializer (); SerializeSimpleClass1 (ser, String.Format ("TEST", this.GetType ().Assembly.FullName)); } void SerializeSimpleClass1 (XmlObjectSerializer ser, string expected) { StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCSimple1 ()); } Console.WriteLine(sw.ToString()); Assert.AreEqual (expected, sw.ToString ()); } // NonDC (behavior changed in 3.5/SP1; not it's not rejected) [Test] public void SerializeNonDC () { DataContractSerializer ser = new DataContractSerializer (typeof (NonDC)); var sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new NonDC ()); } Assert.AreEqual ("whee!".Replace ('\'', '"'), sw.ToString ()); } // DCHasNonDC [Test] public void SerializeDCHasNonDC () { DataContractSerializer ser = new DataContractSerializer (typeof (DCHasNonDC)); var sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCHasNonDC ()); } Assert.AreEqual ("whee!".Replace ('\'', '"'), sw.ToString ()); } // DCHasSerializable [Test] // DCHasSerializable itself is DataContract and has a field // whose type is not contract but serializable. public void SerializeSimpleSerializable1 () { DataContractSerializer ser = new DataContractSerializer (typeof (DCHasSerializable)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCHasSerializable ()); } Assert.AreEqual ("doh!", sw.ToString ()); } [Test] public void SerializeDCWithName () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithName)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCWithName ()); } Assert.AreEqual ("value", sw.ToString ()); } [Test] public void SerializeDCWithEmptyName1 () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithEmptyName)); StringWriter sw = new StringWriter (); DCWithEmptyName dc = new DCWithEmptyName (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { try { ser.WriteObject (w, dc); } catch (InvalidDataContractException) { return; } } Assert.Fail ("Expected InvalidDataContractException"); } [Test] [Category ("NotWorking")] public void SerializeDCWithEmptyName2 () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithName)); StringWriter sw = new StringWriter (); /* DataContractAttribute.Name == "", not valid */ DCWithEmptyName dc = new DCWithEmptyName (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { try { ser.WriteObject (w, dc); } catch (InvalidDataContractException) { return; } } Assert.Fail ("Expected InvalidDataContractException"); } [Test] [Category ("NotWorking")] public void SerializeDCWithNullName () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithNullName)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { try { /* DataContractAttribute.Name == "", not valid */ ser.WriteObject (w, new DCWithNullName ()); } catch (InvalidDataContractException) { return; } } Assert.Fail ("Expected InvalidDataContractException"); } [Test] public void SerializeDCWithEmptyNamespace1 () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithEmptyNamespace)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCWithEmptyNamespace ()); } } // Wrapper.DCWrapped [Test] public void SerializeWrappedClass () { DataContractSerializer ser = new DataContractSerializer (typeof (Wrapper.DCWrapped)); SerializeWrappedClass (ser, ""); } [Test] [Category ("NotWorking")] public void NetSerializeWrappedClass () { NetDataContractSerializer ser = new NetDataContractSerializer (); SerializeWrappedClass (ser, String.Format ("", this.GetType ().Assembly.FullName)); } void SerializeWrappedClass (XmlObjectSerializer ser, string expected) { StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new Wrapper.DCWrapped ()); } Assert.AreEqual (expected, sw.ToString ()); } [Test] /* old code // CollectionContainer : Items must have a setter. [ExpectedException (typeof (InvalidDataContractException))] [Category ("NotWorking")] */ public void SerializeReadOnlyCollectionMember () { DataContractSerializer ser = new DataContractSerializer (typeof (CollectionContainer)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, null); } Assert.AreEqual ("".Replace ('\'', '"'), sw.ToString (), "#1"); sw = new StringWriter (); var c = new CollectionContainer (); c.Items.Add ("foo"); c.Items.Add ("bar"); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, c); } Assert.AreEqual ("foobar".Replace ('\'', '"'), sw.ToString (), "#2"); } // DataCollectionContainer : Items must have a setter. [Test] //[ExpectedException (typeof (InvalidDataContractException))] public void SerializeReadOnlyDataCollectionMember () { DataContractSerializer ser = new DataContractSerializer (typeof (DataCollectionContainer)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, null); } Assert.AreEqual ("".Replace ('\'', '"'), sw.ToString (), "#1"); sw = new StringWriter (); var c = new DataCollectionContainer (); c.Items.Add ("foo"); c.Items.Add ("bar"); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, c); } // LAMESPEC: this is bogus behavior. .NET serializes // System.String as "string" without overriding its // element namespace, but then it must be regarded as // in parent's namespace. What if there already is an // element definition for "string" with the same // namespace? Assert.AreEqual ("foobar".Replace ('\'', '"'), sw.ToString (), "#2"); } [Test] public void SerializeGuid () { DataContractSerializer ser = new DataContractSerializer (typeof (Guid)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, Guid.Empty); } Assert.AreEqual ( "00000000-0000-0000-0000-000000000000", sw.ToString ()); } [Test] public void SerializeEnum () { DataContractSerializer ser = new DataContractSerializer (typeof (Colors)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new Colors ()); } Assert.AreEqual ( @"Red", sw.ToString ()); } [Test] public void SerializeEnum2 () { DataContractSerializer ser = new DataContractSerializer (typeof (Colors)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, 0); } XmlComparer.AssertAreEqual ( @"0", sw.ToString ()); } [Test] public void SerializeEnumWithDC () { DataContractSerializer ser = new DataContractSerializer (typeof (ColorsWithDC)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new ColorsWithDC ()); } Assert.AreEqual ( @"<_ColorsWithDC xmlns=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">_Red", sw.ToString ()); } [Test] public void SerializeEnumWithNoDC () { DataContractSerializer ser = new DataContractSerializer (typeof (ColorsEnumMemberNoDC)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new ColorsEnumMemberNoDC ()); } Assert.AreEqual ( @"Red", sw.ToString ()); } [Test] public void SerializeEnumWithDC2 () { DataContractSerializer ser = new DataContractSerializer (typeof (ColorsWithDC)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, 3); } XmlComparer.AssertAreEqual ( @"<_ColorsWithDC xmlns:d1p1=""http://www.w3.org/2001/XMLSchema"" i:type=""d1p1:int"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">3", sw.ToString ()); } [Test] [ExpectedException (typeof (SerializationException))] public void SerializeEnumWithDCInvalid () { DataContractSerializer ser = new DataContractSerializer (typeof (ColorsWithDC)); StringWriter sw = new StringWriter (); ColorsWithDC cdc = ColorsWithDC.Blue; using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, cdc); } } [Test] public void SerializeDCWithEnum () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithEnum)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new DCWithEnum ()); } Assert.AreEqual ( @"<_colors>Red", sw.ToString ()); } [Test] public void SerializeDCWithTwoEnums () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithTwoEnums)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { DCWithTwoEnums e = new DCWithTwoEnums (); e.colors = Colors.Blue; e.colors2 = Colors.Green; ser.WriteObject (w, e); } Assert.AreEqual ( @"BlueGreen", sw.ToString ()); } [Test] public void SerializeNestingDC2 () { DataContractSerializer ser = new DataContractSerializer (typeof (NestingDC2)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { NestingDC2 e = new NestingDC2 (); e.Field = new NestedDC2 ("Something"); ser.WriteObject (w, e); } Assert.AreEqual ( @"Something", sw.ToString ()); } [Test] public void SerializeNestingDC () { DataContractSerializer ser = new DataContractSerializer (typeof (NestingDC)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { NestingDC e = new NestingDC (); e.Field1 = new NestedDC ("test1"); e.Field2 = new NestedDC ("test2"); ser.WriteObject (w, e); } Assert.AreEqual ( @"test1test2", sw.ToString ()); sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { NestingDC e = new NestingDC (); ser.WriteObject (w, e); } Assert.AreEqual ( @"", sw.ToString ()); } [Test] public void SerializeDerivedDC () { DataContractSerializer ser = new DataContractSerializer (typeof (DerivedDC)); StringWriter sw = new StringWriter (); using (XmlWriter w = XmlWriter.Create (sw, settings)) { DerivedDC e = new DerivedDC (); ser.WriteObject (w, e); } Assert.AreEqual ( @"00", sw.ToString ()); } [Test] public void SerializerDCArray () { DataContractSerializer ser = new DataContractSerializer (typeof (DCWithEnum [])); StringWriter sw = new StringWriter (); DCWithEnum [] arr = new DCWithEnum [2]; arr [0] = new DCWithEnum (); arr [0].colors = Colors.Red; arr [1] = new DCWithEnum (); arr [1].colors = Colors.Green; using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, arr); } XmlComparer.AssertAreEqual ( @"<_colors>Red<_colors>Green", sw.ToString ()); } [Test] public void SerializerDCArray2 () { List known = new List (); known.Add (typeof (DCWithEnum)); known.Add (typeof (DCSimple1)); DataContractSerializer ser = new DataContractSerializer (typeof (object []), known); StringWriter sw = new StringWriter (); object [] arr = new object [2]; arr [0] = new DCWithEnum (); ((DCWithEnum)arr [0]).colors = Colors.Red; arr [1] = new DCSimple1 (); ((DCSimple1) arr [1]).Foo = "hello"; using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, arr); } XmlComparer.AssertAreEqual ( @"Redhello", sw.ToString ()); } [Test] public void SerializerDCArray3 () { DataContractSerializer ser = new DataContractSerializer (typeof (int [])); StringWriter sw = new StringWriter (); int [] arr = new int [2]; arr [0] = 1; arr [1] = 2; using (XmlWriter w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, arr); } XmlComparer.AssertAreEqual ( @"12", sw.ToString ()); } [Test] public void SerializeNonDCArray () { DataContractSerializer ser = new DataContractSerializer (typeof (SerializeNonDCArrayType)); StringWriter sw = new StringWriter (); using (XmlWriter xw = XmlWriter.Create (sw, settings)) { ser.WriteObject (xw, new SerializeNonDCArrayType ()); } Assert.AreEqual (@"", sw.ToString ()); } [Test] public void SerializeNonDCArrayItems () { DataContractSerializer ser = new DataContractSerializer (typeof (SerializeNonDCArrayType)); StringWriter sw = new StringWriter (); using (XmlWriter xw = XmlWriter.Create (sw, settings)) { SerializeNonDCArrayType obj = new SerializeNonDCArrayType (); obj.IPAddresses = new NonDCItem [] {new NonDCItem () { Data = new int [] {1, 2, 3, 4} } }; ser.WriteObject (xw, obj); } XmlDocument doc = new XmlDocument (); doc.LoadXml (sw.ToString ()); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); nsmgr.AddNamespace ("s", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"); nsmgr.AddNamespace ("n", "http://schemas.datacontract.org/2004/07/System.Net"); nsmgr.AddNamespace ("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"); Assert.AreEqual (1, doc.SelectNodes ("/s:SerializeNonDCArrayType/s:IPAddresses/s:NonDCItem", nsmgr).Count, "#1"); XmlElement el = doc.SelectSingleNode ("/s:SerializeNonDCArrayType/s:IPAddresses/s:NonDCItem/s:Data", nsmgr) as XmlElement; Assert.IsNotNull (el, "#3"); Assert.AreEqual (4, el.SelectNodes ("a:int", nsmgr).Count, "#4"); } [Test] public void DeserializeEnum () { Colors c = Deserialize ( @"Red"); Assert.AreEqual (Colors.Red, c, "#de2"); } [Test] public void DeserializeEnum2 () { Colors c = Deserialize ( @"1", typeof (int)); Assert.AreEqual (Colors.Green, c, "#de4"); } [Test] [ExpectedException (typeof (SerializationException))] public void DeserializeEnumInvalid1 () { Deserialize ( @""); } [Test] [ExpectedException (typeof (SerializationException))] public void DeserializeEnumInvalid2 () { Deserialize ( @""); } [Test] [ExpectedException (typeof (SerializationException))] public void DeserializeEnumInvalid3 () { //"red" instead of "Red" Deserialize ( @"red"); } [Test] public void DeserializeEnumFlags () { Deserialize ( @""); } [Test] public void DeserializeEnumWithDC () { ColorsWithDC cdc = Deserialize ( @"<_ColorsWithDC xmlns=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">_Red"); Assert.AreEqual (ColorsWithDC.Red, cdc, "#de6"); } [Test] [ExpectedException (typeof (SerializationException))] public void DeserializeEnumWithDCInvalid () { Deserialize ( @"<_ColorsWithDC xmlns=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">NonExistant"); } [Test] public void DeserializeDCWithEnum () { DCWithEnum dc = Deserialize ( @"<_colors>Red"); Assert.AreEqual (Colors.Red, dc.colors, "#de8"); } [Test] public void DeserializeNestingDC () { NestingDC dc = Deserialize ( @"test1test2"); Assert.IsNotNull (dc.Field1, "#N1: Field1 should not be null."); Assert.IsNotNull (dc.Field2, "#N2: Field2 should not be null."); Assert.AreEqual ("test1", dc.Field1.Name, "#1"); Assert.AreEqual ("test2", dc.Field2.Name, "#2"); } [Test] public void DeserializeNestingDC2 () { NestingDC2 dc = Deserialize ( @"Something"); Assert.IsNotNull (dc.Field, "#N1: Field should not be null."); Assert.AreEqual ("Something", dc.Field.Name, "#N2"); } [Test] public void DeserializeDerivedDC () { DerivedDC dc = Deserialize ( @"12"); Assert.AreEqual (1, dc.baseVal, "#N1"); Assert.AreEqual (2, dc.derivedVal, "#N2"); } [Test] public void DeserializeTwice () { string xml = @"<_ColorsWithDC xmlns=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">_Red <_ColorsWithDC xmlns=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">_Red"; DataContractSerializer ser = new DataContractSerializer (typeof (ColorsWithDC)); XmlReader xr = XmlReader.Create (new StringReader (xml), new XmlReaderSettings ()); xr.ReadStartElement (); object o = ser.ReadObject (xr); Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5"); ColorsWithDC cdc = (ColorsWithDC) o; Assert.AreEqual (ColorsWithDC.Red, o, "#de6"); o = ser.ReadObject (xr); Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5"); cdc = (ColorsWithDC) o; Assert.AreEqual (ColorsWithDC.Red, o, "#de6"); Assert.AreEqual (XmlNodeType.EndElement, xr.NodeType, "#de6"); Assert.AreEqual ("any", xr.LocalName, "#de6"); xr.ReadEndElement (); } [Test] public void DeserializeEmptyNestingDC () { NestingDC dc = Deserialize ( @""); Assert.IsNotNull (dc, "#A0: The object should not be null."); Assert.IsNull (dc.Field1, "#A1: Field1 should be null."); Assert.IsNull (dc.Field2, "#A2: Field2 should be null."); dc = Deserialize ( @""); Assert.IsNotNull (dc, "#B0: The object should not be null."); Assert.IsNull (dc.Field1, "#B1: Field1 should be null."); Assert.IsNull (dc.Field2, "#B2: Field2 should be null."); dc = Deserialize ( @""); Assert.IsNotNull (dc, "#B0: The object should not be null."); Assert.IsNull (dc.Field1, "#B1: Field1 should be null."); Assert.IsNull (dc.Field2, "#B2: Field2 should be null."); } [Test] [ExpectedException (typeof (SerializationException))] public void DeserializeEmptyDCWithTwoEnums () { Deserialize ( @""); } [Test] [Category ("NotWorking")] public void DeserializeDCWithNullableEnum () { DCWithNullableEnum dc = Deserialize ( @""); Assert.IsNull (dc.colors, "#B1: Field should be null."); } [Test] public void DeserializeDCWithTwoEnums () { DCWithTwoEnums dc = Deserialize ( @"BlueGreen"); Assert.AreEqual (Colors.Blue, dc.colors, "#0"); Assert.AreEqual (Colors.Green, dc.colors2, "#1"); } [Test] public void DeserializerDCArray () { DCWithEnum [] dcArray = Deserialize ( @"<_colors>Red<_colors>Green"); Assert.AreEqual (2, dcArray.Length, "#N1"); Assert.AreEqual (Colors.Red, dcArray [0].colors, "#N2"); Assert.AreEqual (Colors.Green, dcArray [1].colors, "#N3"); } [Test] public void DeserializerDCArray2 () { string xml = @"Redhello"; List known = new List (); known.Add (typeof (DCWithEnum)); known.Add (typeof (DCSimple1)); DataContractSerializer ser = new DataContractSerializer (typeof (object []), known); XmlReader xr = XmlReader.Create (new StringReader (xml)); object [] dc = (object []) ser.ReadObject (xr); Assert.AreEqual (2, dc.Length, "#N1"); Assert.AreEqual (typeof (DCWithEnum), dc [0].GetType (), "#N2"); DCWithEnum dc0 = (DCWithEnum) dc [0]; Assert.AreEqual (Colors.Red, dc0.colors, "#N3"); Assert.AreEqual (typeof (DCSimple1), dc [1].GetType (), "#N4"); DCSimple1 dc1 = (DCSimple1) dc [1]; Assert.AreEqual ("hello", dc1.Foo, "#N4"); } [Test] public void DeserializerDCArray3 () { int [] intArray = Deserialize ( @"12"); Assert.AreEqual (2, intArray.Length, "#N0"); Assert.AreEqual (1, intArray [0], "#N1"); Assert.AreEqual (2, intArray [1], "#N2"); } [Test] public void ReadObjectNoVerifyObjectName () { string xml = @"bar1bar2bar"; VerifyObjectNameTestData res = (VerifyObjectNameTestData)new DataContractSerializer (typeof (VerifyObjectNameTestData)) .ReadObject (XmlReader.Create (new StringReader (xml)), false); Assert.AreEqual ("bar", res.GetMember()); } [Test] public void ReadObjectVerifyObjectName () { string xml = @"bar"; VerifyObjectNameTestData res = (VerifyObjectNameTestData)new DataContractSerializer (typeof (VerifyObjectNameTestData)) .ReadObject (XmlReader.Create (new StringReader (xml))); Assert.AreEqual ("bar", res.GetMember()); } [Test] [ExpectedException (typeof (SerializationException))] public void ReadObjectWrongNamespace () { string xml = @"bar"; new DataContractSerializer (typeof (VerifyObjectNameTestData)) .ReadObject (XmlReader.Create (new StringReader (xml))); } [Test] public void ReferenceSerialization () { var dc = new DataContractSerializer (typeof (ReferenceWrapper)); var t = new ReferenceType (); StringWriter sw = new StringWriter (); using (var xw = XmlWriter.Create (sw)) { xw.WriteStartElement ("z", "root", "http://schemas.microsoft.com/2003/10/Serialization/"); dc.WriteObject (xw, new ReferenceWrapper () {T = t, T2 = t}); xw.WriteEndElement (); } string xml = @"x"; Assert.AreEqual (xml.Replace ('\'', '"'), sw.ToString (), "#1"); ReferenceWrapper w; using (XmlReader r = XmlReader.Create (new StringReader (xml))) { r.ReadStartElement (); w = (ReferenceWrapper) dc.ReadObject (r); r.ReadEndElement (); } Assert.AreEqual (w.T, w.T2, "#2"); } [Test] public void GenericSerialization () { var sw = new StringWriter (); var ser = new DataContractSerializer (typeof (Foo)); using (var xw = XmlWriter.Create (sw)) ser.WriteObject (xw, new Foo () {Field = "f" }); var s = sw.ToString (); var ret = (Foo) ser.ReadObject (XmlReader.Create (new StringReader (s))); Assert.AreEqual ("f", ret.Field); } [Test] public void GenericCollectionSerialization () { var l = new MyList (); l.Add ("foo"); l.Add ("bar"); var ds = new DataContractSerializer (typeof (MyList)); var sw = new StringWriter (); using (var xw = XmlWriter.Create (sw)) ds.WriteObject (xw, l); l = (MyList) ds.ReadObject (XmlReader.Create (new StringReader (sw.ToString ()))); Assert.AreEqual (2, l.Count); } [Test] public void GenericListOfKeyValuePairSerialization () { string xml = @"foobar".Replace ('\'', '"'); var ds = new DataContractSerializer (typeof (List>)); var d = new List> (); d.Add (new KeyValuePair ("foo", "bar")); var sw = new StringWriter (); using (var xw = XmlWriter.Create (sw)) ds.WriteObject (xw, d); Assert.AreEqual (xml, sw.ToString (), "#1"); d = (List>) ds.ReadObject (XmlReader.Create (new StringReader (xml))); Assert.AreEqual (1, d.Count, "#2"); Assert.AreEqual ("bar", d [0].Value, "#3"); } [Test] public void GenericListOfDictionaryEntrySerialization () { string xml = @"<_key xmlns:d3p1='http://www.w3.org/2001/XMLSchema' i:type='d3p1:string'>foo<_value xmlns:d3p1='http://www.w3.org/2001/XMLSchema' i:type='d3p1:string'>bar".Replace ('\'', '"'); var ds = new DataContractSerializer (typeof (List)); var d = new List (); d.Add (new DictionaryEntry ("foo", "bar")); var sw = new StringWriter (); using (var xw = XmlWriter.Create (sw)) ds.WriteObject (xw, d); Assert.AreEqual (xml, sw.ToString (), "#1"); Assert.IsTrue (sw.ToString ().IndexOf ("i:type") >= 0); d = (List) ds.ReadObject (XmlReader.Create (new StringReader (xml))); Assert.AreEqual (1, d.Count, "#2"); Assert.AreEqual ("bar", d [0].Value, "#3"); } [Test] public void GenericDictionarySerialization () { string xml = @"foobar".Replace ('\'', '"'); var ds = new DataContractSerializer (typeof (Dictionary)); var d = new Dictionary (); d ["foo"] = "bar"; var sw = new StringWriter (); using (var xw = XmlWriter.Create (sw)) ds.WriteObject (xw, d); Assert.AreEqual (xml, sw.ToString (), "#1"); d = (Dictionary) ds.ReadObject (XmlReader.Create (new StringReader (xml))); Assert.AreEqual (1, d.Count, "#2"); Assert.AreEqual ("bar", d ["foo"], "#3"); } [Test] public void HashtableSerialization () { string xml = @"foobar".Replace ('\'', '"'); var ds = new DataContractSerializer (typeof (Hashtable)); var d = new Hashtable (); d ["foo"] = "bar"; var sw = new StringWriter (); using (var xw = XmlWriter.Create (sw)) ds.WriteObject (xw, d); Assert.AreEqual (xml, sw.ToString (), "#1"); d = (Hashtable) ds.ReadObject (XmlReader.Create (new StringReader (xml))); Assert.AreEqual (1, d.Count, "#2"); Assert.AreEqual ("bar", d ["foo"], "#3"); } [Test] public void CollectionContarctDictionarySerialization () { string xml = @"foobar".Replace ('\'', '"'); var ds = new DataContractSerializer (typeof (MyDictionary)); var d = new MyDictionary (); d ["foo"] = "bar"; var sw = new StringWriter (); using (var xw = XmlWriter.Create (sw)) ds.WriteObject (xw, d); Assert.AreEqual (xml, sw.ToString (), "#1"); d = (MyDictionary) ds.ReadObject (XmlReader.Create (new StringReader (xml))); Assert.AreEqual (1, d.Count, "#2"); Assert.AreEqual ("bar", d ["foo"], "#3"); } [Test] public void SerializeInterfaceCollection () { var ser = new DataContractSerializer (typeof (InterfaceCollectionType)); var sw = new StringWriter (); var obj = new InterfaceCollectionType (); using (var xw = XmlWriter.Create (sw)) ser.WriteObject (xw, obj); using (var xr = XmlReader.Create (new StringReader (sw.ToString ()))) { obj = (InterfaceCollectionType) ser.ReadObject (xr); Assert.IsNull (obj.Array, "#1"); } sw = new StringWriter (); obj.Array = new List (); obj.Array.Add (5); using (var xw = XmlWriter.Create (sw)) ser.WriteObject (xw, obj); using (var xr = XmlReader.Create (new StringReader (sw.ToString ()))) { obj = (InterfaceCollectionType) ser.ReadObject (xr); Assert.AreEqual (5, obj.Array [0], "#2"); } } [Test] public void EmptyChildren () { string xml = @" http://vmsservices.example.com:8080/VideoService.svc?crid=45541/part=1/guid=ae968b5d-e4a5-41fe-9b23-ed631b27cd21/ "; var reader = XmlReader.Create (new StringReader (xml)); DummyPlaylist playlist = (DummyPlaylist) new DataContractSerializer (typeof (DummyPlaylist)).ReadObject (reader); Assert.AreEqual (1, playlist.entries.Count, "#1"); Assert.IsTrue (playlist.entries [0] is DummyEntry, "#2"); Assert.IsNotNull (playlist.entries [0].Href, "#3"); } [Test] public void BaseKnownTypeAttributes () { // bug #524088 string xml = @" "; using (XmlReader reader = XmlReader.Create (new StringReader (xml))) { DummyPlaylist playlist = new DataContractSerializer(typeof(DummyPlaylist)).ReadObject(reader) as DummyPlaylist; Assert.IsNotNull (playlist); } } [Test] public void Bug524083 () { string xml = @" "; using (XmlReader reader = XmlReader.Create (new StringReader (xml))) new DataContractSerializer(typeof (AsxEntryInfo)).ReadObject (reader); } [Test] public void Bug539563 () { new DataContractSerializer (typeof (NestedContractType)); } [Test] public void Bug560155 () { var g = Guid.NewGuid (); Person p1 = new Person ("UserName", g); Assert.AreEqual ("name=UserName,id=" + g, p1.ToString (), "#1"); MemoryStream memStream = new MemoryStream (); DataContractSerializer ser = new DataContractSerializer (typeof (Person)); ser.WriteObject (memStream, p1); memStream.Seek (0, SeekOrigin.Begin); Person p2 = (Person) ser.ReadObject (memStream); Assert.AreEqual ("name=UserName,id=" + g, p2.ToString (), "#1"); } private T Deserialize (string xml) { return Deserialize (xml, typeof (T)); } private T Deserialize (string xml, Type runtimeType) { DataContractSerializer ser = new DataContractSerializer (typeof (T)); XmlReader xr = XmlReader.Create (new StringReader (xml), new XmlReaderSettings ()); object o = ser.ReadObject (xr); Assert.AreEqual (runtimeType, o.GetType (), "#DS0"); return (T)o; } public Dictionary GenericDictionary (Dictionary settings) { using (MemoryStream ms = new MemoryStream ()) { DataContractSerializer save = new DataContractSerializer (settings.GetType ()); save.WriteObject (ms, settings); ms.Position = 0; DataContractSerializer load = new DataContractSerializer (typeof (Dictionary)); return (Dictionary) load.ReadObject (ms); } } [Test] public void GenericDictionaryEmpty () { Dictionary in_settings = new Dictionary (); Dictionary out_settings = GenericDictionary (in_settings); out_settings.Clear (); } [Test] public void GenericDictionaryOneElement () { Dictionary in_settings = new Dictionary (); in_settings.Add ("one", "ONE"); Dictionary out_settings = GenericDictionary (in_settings); Assert.AreEqual ("ONE", out_settings ["one"], "out"); out_settings.Clear (); } [Test] public void IgnoreDataMember () { var ser = new DataContractSerializer (typeof (MemberIgnored)); var sw = new StringWriter (); using (var w = XmlWriter.Create (sw, settings)) { ser.WriteObject (w, new MemberIgnored ()); } Assert.AreEqual (@"bar", sw.ToString (), "#1"); } [Test] public void DeserializeEmptyArray () { var ds = new DataContractSerializer (typeof (string [])); var sw = new StringWriter (); var xw = XmlWriter.Create (sw); ds.WriteObject (xw, new string [] {}); xw.Close (); Console.WriteLine (sw.ToString ()); var sr = new StringReader (sw.ToString ()); var xr = XmlReader.Create (sr); var ret = ds.ReadObject (xr); Assert.AreEqual (typeof (string []), ret.GetType (), "#1"); } } [DataContract] public class MemberIgnored { [DataMember] MemberIgnoredBody body = new MemberIgnoredBody (); } public class MemberIgnoredBody { [IgnoreDataMember] public string Foo = "foo"; public string Bar = "bar"; } public enum Colors { Red, Green, Blue } [Flags] public enum Colors2 { Red, Green, Blue } [DataContract (Name = "_ColorsWithDC")] public enum ColorsWithDC { [EnumMember (Value = "_Red")] Red, [EnumMember] Green, Blue } public enum ColorsEnumMemberNoDC { [EnumMember (Value = "_Red")] Red, [EnumMember] Green, Blue } [DataContract] public class DCWithEnum { [DataMember (Name = "_colors")] public Colors colors; } [DataContract] public class DCWithTwoEnums { [DataMember] public Colors colors; [DataMember] public Colors colors2; } [DataContract] public class DCWithNullableEnum { [DataMember] public Colors? colors; } [DataContract (Namespace = "Base")] public class BaseDC { [DataMember] public int baseVal; } [DataContract (Namespace = "Derived")] public class DerivedDC : BaseDC { [DataMember] public int derivedVal; } [DataContract] public class NestedDC { public NestedDC (string name) { this.Name = name; } [DataMember] public string Name; } [DataContract] public class NestingDC { [DataMember] public NestedDC Field1; [DataMember] public NestedDC Field2; } [DataContract (Namespace = "test1")] public class NestedDC2 { public NestedDC2 (string name) { this.Name = name; } [DataMember] public string Name; } [DataContract (Namespace = "test2")] public class NestingDC2 { [DataMember] public NestedDC2 Field; } [DataContract] public class DCEmpty { // serializer doesn't touch it. public string Foo = "TEST"; } [DataContract (Namespace = "")] public class DCEmptyNoNS { } [DataContract] public class DCSimple1 { [DataMember] public string Foo = "TEST"; } [DataContract] public class DCHasNonDC { [DataMember] public NonDC Hoge= new NonDC (); } public class NonDC { public string Whee = "whee!"; } [DataContract] public class DCHasSerializable { [DataMember] public SimpleSer1 Ser = new SimpleSer1 (); } [DataContract (Name = "Foo")] public class DCWithName { [DataMember (Name = "FooMember")] public string DMWithName = "value"; } [DataContract (Name = "")] public class DCWithEmptyName { } [DataContract (Name = null)] public class DCWithNullName { } [DataContract (Namespace = "")] public class DCWithEmptyNamespace { } [Serializable] public class SimpleSer1 { public string Doh = "doh!"; [NonSerialized] public string Bah = "bah!"; } public class Wrapper { [DataContract] public class DCWrapped { } } [DataContract] public class CollectionContainer { Collection items = new Collection (); [DataMember] public Collection Items { get { return items; } } } [CollectionDataContract] public class DataCollection : Collection { } [DataContract] public class DataCollectionContainer { DataCollection items = new DataCollection (); [DataMember] public DataCollection Items { get { return items; } } } [DataContract] class SerializeNonDCArrayType { [DataMember] public NonDCItem [] IPAddresses = new NonDCItem [0]; } public class NonDCItem { public int [] Data { get; set; } } [DataContract] public class VerifyObjectNameTestData { [DataMember] string Member1 = "foo"; public string GetMember() { return Member1; } } [XmlRoot(ElementName = "simple", Namespace = "")] public class SimpleXml : IXmlSerializable { void IXmlSerializable.ReadXml (XmlReader reader) { } void IXmlSerializable.WriteXml (XmlWriter writer) { } XmlSchema IXmlSerializable.GetSchema () { return null; } } [DataContract] public class ReferenceWrapper { [DataMember (Order = 1)] public ReferenceType T; [DataMember (Order = 2)] public ReferenceType T2; } [DataContract (IsReference = true)] public class ReferenceType { [DataMember] public string F = "x"; } public class MyList : IList { List l = new List (); public void Clear () { l.Clear (); } public void Add(string s) { l.Add (s);} public void Insert(int idx, string s) { l.Insert(idx,s);} public bool Contains(string s) { return l.Contains(s); } public IEnumerator GetEnumerator () { return l.GetEnumerator (); } IEnumerator IEnumerable.GetEnumerator () { return l.GetEnumerator (); } public bool Remove(string s) { return l.Remove(s); } public void RemoveAt(int i) { l.RemoveAt (i);} public void CopyTo (string [] arr, int index) { l.CopyTo (arr, index);} public int IndexOf (string s) { return l.IndexOf (s); } public int Count { get { return l.Count; } } public bool IsReadOnly { get { return ((IList) l).IsReadOnly; } } public string this [int index] { get { return l [index]; } set { l [index] = value; } } } [DataContract] internal class InterfaceCollectionType { [DataMember] public IList Array { get; set; } } [DataContract] public class NestedContractType { [DataMember] public NestedContractType Nested; [DataMember] public string X = "x"; } } [DataContract] class GlobalSample1 { } [DataContract] class Foo { [DataMember] public X Field; } [CollectionDataContract (Name = "NAME", Namespace = "urn:foo", ItemName = "ITEM", KeyName = "KEY", ValueName = "VALUE")] public class MyDictionary : Dictionary { } // bug #524086 [DataContract(Namespace="http://example.com/schemas/asx")] public class DummyEntry { [DataMember] public DummyEntryInfo EntryInfo { get; set; } [DataMember] public string Href { get; set; } } [DataContract(Namespace="http://example.com/schemas/asx"), KnownType(typeof(PartDummyEntryInfo))] public abstract class DummyEntryInfo { } [DataContract(Namespace="http://example.com/schemas/asx")] public class DummyPlaylist { public IList entries = new List (); [DataMember] public IList Entries { get { return entries; } set {entries = value;} } } [DataContract(Namespace="http://example.com/schemas/asx")] public class PartDummyEntryInfo : DummyEntryInfo { public PartDummyEntryInfo() {} } // bug #524088 [DataContract(Namespace="http://example.com/schemas/asx")] public class AsxEntryInfo { [DataMember] public string AdvertPrompt { get; set; } } // bug #560155 [DataContract] public class Person { [DataMember] readonly public string name; [DataMember] readonly public Guid Id = Guid.Empty; public Person (string nameIn, Guid idIn) { name = nameIn; Id = idIn; } public override string ToString() { return string.Format ("name={0},id={1}", name, Id); } }