Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
//
// AttributesTest.cs
//
// Author:
// Eyal Alaluf <mainsoft.com>
//
// Copyright (C) 2008 Mainsoft.co http://www.mainsoft.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 attributes in System.Runtime.Serialization
//
using System;
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;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class AttributesTest
{
[Test]
public void TestContractNamespaceAttribute ()
{
ContractNamespaceAttribute x = new ContractNamespaceAttribute ("test");
Assert.AreEqual (null, x.ClrNamespace, "#01");
Assert.AreEqual ("test", x.ContractNamespace, "#02");
}
[Test]
public void TestDataContractAttribute ()
{
DataContractAttribute x = new DataContractAttribute ();
Assert.AreEqual (null, x.Name, "#01");
Assert.AreEqual (null, x.Namespace, "#02");
}
[Test]
public void TestDataMemberAttribute ()
{
DataMemberAttribute x = new DataMemberAttribute ();
Assert.AreEqual (null, x.Name, "#01");
Assert.AreEqual (-1, x.Order, "#02");
Assert.AreEqual (true, x.EmitDefaultValue, "#02");
Assert.AreEqual (false, x.IsRequired, "#02");
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Text;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[XmlSchemaProvider(null, IsAny = true)]
public class TestElement : IXmlSerializable
{
public string Value { get; set; }
void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteElementString("dummy", Value);
}
void IXmlSerializable.ReadXml(XmlReader reader)
{
Value = reader.ReadElementString("dummy");
}
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
}
[TestFixture]
public class Bug11916Test
{
[Test]
public void TestIsAnyTrueDataContractSerializer()
{
TestElement element = new TestElement();
element.Value = "bar";
StringBuilder stringBuilder = new StringBuilder ();
DataContractSerializer ser = new DataContractSerializer (typeof (TestElement));
using (var xw = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (new StringWriter (stringBuilder))))
{
ser.WriteObject(xw, element);
}
string actualXml = stringBuilder.ToString ();
string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?><dummy>bar</dummy>";
Assert.AreEqual (expectedXml, actualXml, "#1 IsAny=true DataContractSerializer");
}
}
}

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Xml;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
public class DataItemTest242
{
public string Name { get; set; }
}
public class DataTest242
{
public DataItemTest242[] DataArray { get; set; }
public IList<DataItemTest242> DataIList { get; set; }
public List<DataItemTest242> DataList { get; set; }
public ICollection<DataItemTest242> DataICollection { get; set; }
public IEnumerable<DataItemTest242> DataIEnumerable { get; set; }
}
[TestFixture]
public class Bug242Test
{
[Test]
public void TestMixListArraySerialize()
{
var dataItems = new[] { new DataItemTest242 () { Name = "aaaaa" },
new DataItemTest242 () { Name = "bbbbb" } };
var data = new DataTest242 ()
{
DataArray = dataItems,
DataIList = dataItems.ToList (),
DataList = dataItems.ToList (),
DataICollection = dataItems.ToList (),
DataIEnumerable = dataItems.ToList ()
};
// Serialize
string xml;
using (var stream = new MemoryStream ())
{
var serializer = new DataContractSerializer (typeof (DataTest242));
serializer.WriteObject (stream, data);
xml = Encoding.UTF8.GetString (stream.ToArray ());
}
// Deserialize
DataTest242 clonedData;
using (var reader = XmlDictionaryReader.CreateTextReader (Encoding.UTF8.GetBytes (xml), new XmlDictionaryReaderQuotas ()))
{
var serializer = new DataContractSerializer (typeof (DataTest242));
clonedData = (DataTest242)serializer.ReadObject (reader);
}
// ensure resulting object is populated
Assert.AreEqual (clonedData.DataArray.Length , data.DataArray.Length,"#1 clonedData.DataArray.Length" );
Assert.AreEqual (clonedData.DataList.Count, data.DataList.Count,"#2 clonedData.DataList.Count" );
Assert.AreEqual (clonedData.DataIList.Count, data.DataIList.Count,"#3 clonedData.DataIList.Count" );
Assert.AreEqual (clonedData.DataICollection.Count, data.DataICollection.Count,"#4 clonedData.DataICollection.Count" );
Assert.AreEqual (clonedData.DataIEnumerable.Count (), data.DataIEnumerable.Count (),"#5 clonedData.DataIEnumerable.Count()" );
}
}
}

View File

@@ -0,0 +1,310 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Xml;
using System.ServiceModel.Dispatcher;
using System.Text;
using NUnit.Framework;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Client2843.EvalServiceReference {
using System.Runtime.Serialization;
using System;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Eval", Namespace="http://schemas.datacontract.org/2004/07/WcfServiceLibrary1")]
[System.SerializableAttribute()]
public partial class Eval : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string CommentsField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string IdField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string SubmitterField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private System.Nullable<System.DateTime> TimeSubmittedField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private System.Nullable<Client2843.EvalServiceReference.EvalType> etypeField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private System.Nullable<Client2843.EvalServiceReference.EvalType> etype2Field;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Comments {
get {
return this.CommentsField;
}
set {
if ((object.ReferenceEquals(this.CommentsField, value) != true)) {
this.CommentsField = value;
this.RaisePropertyChanged("Comments");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Id {
get {
return this.IdField;
}
set {
if ((object.ReferenceEquals(this.IdField, value) != true)) {
this.IdField = value;
this.RaisePropertyChanged("Id");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Submitter {
get {
return this.SubmitterField;
}
set {
if ((object.ReferenceEquals(this.SubmitterField, value) != true)) {
this.SubmitterField = value;
this.RaisePropertyChanged("Submitter");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<System.DateTime> TimeSubmitted {
get {
return this.TimeSubmittedField;
}
set {
if ((this.TimeSubmittedField.Equals(value) != true)) {
this.TimeSubmittedField = value;
this.RaisePropertyChanged("TimeSubmitted");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<Client2843.EvalServiceReference.EvalType> etype {
get {
return this.etypeField;
}
set {
if ((this.etypeField.Equals(value) != true)) {
this.etypeField = value;
this.RaisePropertyChanged("etype");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<Client2843.EvalServiceReference.EvalType> etype2 {
get {
return this.etype2Field;
}
set {
if ((this.etype2Field.Equals(value) != true)) {
this.etype2Field = value;
this.RaisePropertyChanged("etype2");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="EvalType", Namespace="http://schemas.datacontract.org/2004/07/WcfServiceLibrary1")]
public enum EvalType : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
SIMPLE = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
COMPLEX = 2,
[System.Runtime.Serialization.EnumMemberAttribute()]
NONE = 3,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="EvalServiceReference.IEvalService")]
public interface IEvalService {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IEvalService/SubmitEval", ReplyAction="http://tempuri.org/IEvalService/SubmitEvalResponse")]
void SubmitEval(Client2843.EvalServiceReference.Eval eval);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IEvalService/GetEvals", ReplyAction="http://tempuri.org/IEvalService/GetEvalsResponse")]
Client2843.EvalServiceReference.Eval[] GetEvals();
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IEvalService/RemoveEval", ReplyAction="http://tempuri.org/IEvalService/RemoveEvalResponse")]
void RemoveEval(string id);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IEvalServiceChannel : Client2843.EvalServiceReference.IEvalService, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class EvalServiceClient : System.ServiceModel.ClientBase<Client2843.EvalServiceReference.IEvalService>, Client2843.EvalServiceReference.IEvalService {
public EvalServiceClient() {
}
public EvalServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public EvalServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public EvalServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public EvalServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public void SubmitEval(Client2843.EvalServiceReference.Eval eval) {
base.Channel.SubmitEval(eval);
}
public Client2843.EvalServiceReference.Eval[] GetEvals() {
return base.Channel.GetEvals();
}
public void RemoveEval(string id) {
base.Channel.RemoveEval(id);
}
}
}
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class Bug2843Test
{
[Test]
public void TestNullableEnum()
{
string Name = "GetEvalsResult";
string Wrapper = "GetEvalsResponse";
string Namespace = "http://tempuri.org/";
Type type = typeof(Client2843.EvalServiceReference.Eval[]);
IEnumerable<Type> know_types = new List<Type>();
// This is the XML generated by WCF Server
string xml = "<GetEvalsResponse xmlns=\"http://tempuri.org/\"> <GetEvalsResult xmlns:a=\"http://schemas.datacontract.org/2004/07/WcfServiceLibrary1\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"> <a:Eval> <a:Comments>Comment 1</a:Comments> <a:Id>04836718-41a7-45fe-8c0b-ac3fc613b0f8</a:Id> <a:Submitter>Submitter 1</a:Submitter> <a:TimeSubmitted i:nil=\"true\" /> <a:etype>SIMPLE</a:etype> <a:etype2>COMPLEX</a:etype2> </a:Eval> <a:Eval> <a:Comments>Comment 2</a:Comments> <a:Id>fd17a406-4c2c-41ca-9a5d-1a1019d07535</a:Id> <a:Submitter>Submitter 2</a:Submitter> <a:TimeSubmitted>2012-02-26T13:41:00</a:TimeSubmitted> <a:etype i:nil=\"true\" /> <a:etype2>COMPLEX</a:etype2> </a:Eval> </GetEvalsResult> </GetEvalsResponse>";
Client2843.EvalServiceReference.Eval[] evals = null;
StringBuilder stringBuilder = new StringBuilder ();
var ds = new DataContractSerializer (type, Name, Namespace, know_types);
using (var xr = XmlDictionaryReader.CreateDictionaryReader ( XmlReader.Create (new StringReader (xml))))
{
xr.ReadStartElement (Wrapper, Namespace);
for (xr.MoveToContent (); xr.NodeType == XmlNodeType.Element; xr.MoveToContent ()) {
XmlQualifiedName key = new XmlQualifiedName (xr.LocalName, xr.NamespaceURI);
if ( Name == key.Name && Namespace == key.Namespace)
break;
}
evals = (Client2843.EvalServiceReference.Eval[])ds.ReadObject (xr, true);
}
using (var xw = XmlDictionaryWriter.CreateDictionaryWriter ( XmlWriter.Create( new StringWriter(stringBuilder)))) {
ds.WriteObject (xw, evals);
}
string actualXml = stringBuilder.ToString ();
Assert.AreEqual (evals.Length, 2, "Comment 1" , "Eval 1 Comment missmatch");
Client2843.EvalServiceReference.Eval ev1 = evals[0];
Client2843.EvalServiceReference.Eval ev2 = evals[1];
// Assert that object deserilized matches each value attribute.
Assert.AreEqual (ev1.Comments, "Comment 1" , "ev1.Comments missmatch");
Assert.AreEqual (ev1.Submitter, "Submitter 1", "ev1.Submitter missmatch");
Assert.IsNull (ev1.TimeSubmitted, "ev1.TimeSubmitted missmatch");
Assert.AreEqual (ev1.etype, Client2843.EvalServiceReference.EvalType.SIMPLE, "ev1.etype missmatch");
Assert.AreEqual (ev1.etype2, Client2843.EvalServiceReference.EvalType.COMPLEX, "ev1.etype2 missmatch");
Assert.AreEqual (ev2.Comments, "Comment 2", "ev2.Comments missmatch");
Assert.AreEqual (ev2.Submitter, "Submitter 2","ev2.Submitter missmatch");
Assert.AreEqual (ev2.TimeSubmitted, DateTime.Parse("2012-02-26T13:41:00"), "ev2.TimeSubmitted missmatch");
Assert.IsNull (ev2.etype, "ev2.etype missmatch");
Assert.AreEqual (ev2.etype2, Client2843.EvalServiceReference.EvalType.COMPLEX, "ev2.etype2 missmatch");
Client2843.EvalServiceReference.Eval[] evals2 = null;
using (var xr = XmlDictionaryReader.CreateDictionaryReader ( XmlReader.Create (new StringReader (actualXml))))
{
evals2 = (Client2843.EvalServiceReference.Eval[])ds.ReadObject (xr, true);
}
Client2843.EvalServiceReference.Eval e1 = evals2[0];
Client2843.EvalServiceReference.Eval e2 = evals2[1];
Assert.AreEqual (e1.Comments, "Comment 1" , "e1.Comments missmatch");
Assert.AreEqual (e1.Submitter, "Submitter 1", "e1.Submitter missmatch");
Assert.IsNull (e1.TimeSubmitted, "e1.TimeSubmitted missmatch");
Assert.AreEqual (e1.etype, Client2843.EvalServiceReference.EvalType.SIMPLE, "e1.etype missmatch");
Assert.AreEqual (e1.etype2, Client2843.EvalServiceReference.EvalType.COMPLEX, "e1.etype2 missmatch");
Assert.AreEqual (e2.Comments, "Comment 2", "e2.Comments missmatch");
Assert.AreEqual (e2.Submitter, "Submitter 2","e2.Submitter missmatch");
Assert.AreEqual (e2.TimeSubmitted, DateTime.Parse("2012-02-26T13:41:00"), "e2.TimeSubmitted missmatch");
Assert.IsNull (e2.etype, "e2.etype missmatch");
Assert.AreEqual (e2.etype2, Client2843.EvalServiceReference.EvalType.COMPLEX, "e2.etype2 missmatch");
}
}
}

View File

@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Text;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class Bug3258Test
{
[Test]
public void TestSerializeNullDateTimeOffsetNullable ()
{
// Create the writer object.
StringBuilder stringBuilder = new StringBuilder ();
DateTimeOffset? dto = null;
DataContractSerializer ser = new DataContractSerializer (typeof (DateTimeOffset?));
using (var xw = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (new StringWriter (stringBuilder))))
{
ser.WriteObject (xw, dto);
}
string actualXml = stringBuilder.ToString ();
string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DateTimeOffset i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/System\" />";
Assert.AreEqual (expectedXml, actualXml, "#1 Null DateTimeOffset? serialization error");
using (var xr = XmlDictionaryReader.CreateDictionaryReader (XmlReader.Create (new StringReader (actualXml))))
{
DateTimeOffset? actualDto = (DateTimeOffset?)ser.ReadObject (xr, true);
Assert.AreEqual (dto, actualDto, "#2 Null DateTimeOffset? deserialization error");
Assert.IsNull (actualDto, "#3 Null DateTimeOffset? deserialization error");
}
}
[Test]
public void TestSerializeDateTimeOffsetNullable ()
{
// Create the writer object.
StringBuilder stringBuilder = new StringBuilder ();
DateTimeOffset? dto = new DateTimeOffset (2012, 05, 04, 02, 34, 00, new TimeSpan (-2, 0, 0));;
DataContractSerializer ser = new DataContractSerializer (typeof (DateTimeOffset?));
using (var xw = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (new StringWriter (stringBuilder))))
{
ser.WriteObject (xw, dto);
}
string actualXml = stringBuilder.ToString ();
string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DateTimeOffset xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/System\"><DateTime>2012-05-04T04:34:00Z</DateTime><OffsetMinutes>-120</OffsetMinutes></DateTimeOffset>";
Assert.AreEqual (expectedXml, actualXml, "#1 Nullable DateTimeOffset serialization error");
using (var xr = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create (new StringReader (actualXml))))
{
DateTimeOffset? actualDto = (DateTimeOffset?)ser.ReadObject (xr, true);
Assert.AreEqual (dto, actualDto, "#2 Nullable DateTimeOffset deserialization error");
}
}
}
}

View File

@@ -0,0 +1,362 @@
#if !MOBILE
using System;
using System.Runtime.Serialization;
using System.IO;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Globalization;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Xml;
using System.CodeDom.Compiler;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class Bug666333Test
{
[Test]
public void Bug666333 ()
{
// xml : original xml in the test
// xml2 : when it is *appropriately* serialized
// xml3 : mixed, d4p1:activeuser comes first
// xml4 : mixed, d4p1:activeuser comes second
// (Note that d4p1:activeuser is the actual element to be deserialized which takes precedence over urn:foo activeuser.)
string xml = @"
<CheckLoginResponse xmlns='http://tempuri.org/'>
<playeractiveuser>
<activeuser>
<id>id</id>
<hkey>hkey</hkey>
<email>FOO@BAR.com</email>
<lastcheck>2011-01-21T22:50:52.02</lastcheck>
</activeuser>
<response>
<responsemessage>Acceso correcto, creado nuevo hkey!</responsemessage>
<responsecode>1</responsecode>
<langId>6</langId>
</response>
</playeractiveuser>
</CheckLoginResponse>
";
string xml2 = @"
<CheckLoginResponse xmlns='http://tempuri.org/'>
<playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
<d4p1:activeuser>
<d4p1:email i:nil='true' />
<d4p1:hkey i:nil='true' />
<d4p1:id>idd</d4p1:id>
<d4p1:lastcheck i:nil='true' />
</d4p1:activeuser>
<d4p1:response>
<d4p1:langId i:nil='true' />
<d4p1:responsecode>100</d4p1:responsecode>
<d4p1:responsemessage i:nil='true' />
</d4p1:response>
</playeractiveuser>
</CheckLoginResponse>";
string xml3 = @"
<CheckLoginResponse xmlns='http://tempuri.org/'>
<playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
<d4p1:activeuser>
<d4p1:email i:nil='true' />
<d4p1:hkey i:nil='true' />
<d4p1:id>iddd</d4p1:id>
<d4p1:lastcheck i:nil='true' />
</d4p1:activeuser>
<activeuser xmlns='urn:foo'>
<email i:nil='true' />
<hkey i:nil='true' />
<id>idd</id>
<lastcheck i:nil='true' />
</activeuser>
<response xmlns='urn:foo'>
<langId i:nil='true' />
<responsecode>200</responsecode>
<responsemessage i:nil='true' />
</response>
</playeractiveuser>
</CheckLoginResponse>";
string xml4 = @"
<CheckLoginResponse xmlns='http://tempuri.org/'>
<playeractiveuser xmlns:d4p1='http://schemas.datacontract.org/2004/07/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
<activeuser xmlns='urn:foo'>
<email i:nil='true' />
<hkey i:nil='true' />
<id>idd</id>
<lastcheck i:nil='true' />
</activeuser>
<d4p1:activeuser>
<d4p1:email i:nil='true' />
<d4p1:hkey i:nil='true' />
<d4p1:id>iddd</d4p1:id>
<d4p1:lastcheck i:nil='true' />
</d4p1:activeuser>
<response xmlns='urn:foo'>
<langId i:nil='true' />
<responsecode>200</responsecode>
<responsemessage i:nil='true' />
</response>
</playeractiveuser>
</CheckLoginResponse>";
var tm = TypedMessageConverter.Create (typeof (CheckLoginResponse), "urn:foo");
var m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml)));
m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml2)));
m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml3)));
var clr = (CheckLoginResponse) tm.FromMessage (m);
Assert.IsNotNull (clr.playeractiveuser, "#1");
Assert.IsNotNull (clr.playeractiveuser.activeuser, "#2");
Assert.AreEqual ("iddd", clr.playeractiveuser.activeuser.id, "#3");
m = Message.CreateMessage (MessageVersion.Default, "urn:foo", XmlReader.Create (new StringReader (xml4)));
Assert.AreEqual ("iddd", clr.playeractiveuser.activeuser.id, "#4");
}
}
}
// Generated code
[GeneratedCode("System.ServiceModel", "4.0.0.0"), DebuggerStepThrough, EditorBrowsable(EditorBrowsableState.Advanced), MessageContract(WrapperName="CheckLoginResponse", WrapperNamespace="http://tempuri.org/", IsWrapped=true)]
public class CheckLoginResponse
{
// Fields
[MessageBodyMember(Namespace="http://tempuri.org/", Order=0), XmlElement(IsNullable=true)]
public PlayerActiveUser playeractiveuser;
// Methods
public CheckLoginResponse()
{
}
public CheckLoginResponse(PlayerActiveUser playeractiveuser)
{
this.playeractiveuser = playeractiveuser;
}
}
[GeneratedCode("System.Xml", "4.0.30319.1"), DebuggerStepThrough, XmlType(Namespace="http://tempuri.org/")]
public class PlayerActiveUser : INotifyPropertyChanged
{
// Fields
private ActiveUserReference activeuserField;
//private PropertyChangedEventHandler PropertyChanged;
private Response responseField;
// Events
public event PropertyChangedEventHandler PropertyChanged;
// Methods
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// Properties
[XmlElement(Order=0)]
public ActiveUserReference activeuser
{
get
{
return this.activeuserField;
}
set
{
this.activeuserField = value;
this.RaisePropertyChanged("activeuser");
}
}
[XmlElement(Order=1)]
public Response response
{
get
{
return this.responseField;
}
set
{
this.responseField = value;
this.RaisePropertyChanged("response");
}
}
}
[XmlType(Namespace="http://tempuri.org/"), GeneratedCode("System.Xml", "4.0.30319.1"), DebuggerStepThrough]
public class Response : INotifyPropertyChanged
{
// Fields
private int? langIdField;
//private PropertyChangedEventHandler PropertyChanged;
private int? responsecodeField;
private string responsemessageField;
// Events
public event PropertyChangedEventHandler PropertyChanged;
// Methods
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// Properties
[XmlElement(IsNullable=true, Order=2)]
public int? langId
{
get
{
return this.langIdField;
}
set
{
this.langIdField = value;
this.RaisePropertyChanged("langId");
}
}
[XmlElement(IsNullable=true, Order=1)]
public int? responsecode
{
get
{
return this.responsecodeField;
}
set
{
this.responsecodeField = value;
this.RaisePropertyChanged("responsecode");
}
}
[XmlElement(Order=0)]
public string responsemessage
{
get
{
return this.responsemessageField;
}
set
{
this.responsemessageField = value;
this.RaisePropertyChanged("responsemessage");
}
}
}
[XmlType(Namespace="http://tempuri.org/"), DebuggerStepThrough, GeneratedCode("System.Xml", "4.0.30319.1")]
public class ActiveUserReference : ESObject
{
// Fields
private string emailField;
private string hkeyField;
private string idField;
private DateTime? lastcheckField;
// Properties
[XmlElement(Order=2)]
public string email
{
get
{
return this.emailField;
}
set
{
this.emailField = value;
base.RaisePropertyChanged("email");
}
}
[XmlElement(Order=1)]
public string hkey
{
get
{
return this.hkeyField;
}
set
{
this.hkeyField = value;
base.RaisePropertyChanged("hkey");
}
}
[XmlElement(Order=0)]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
base.RaisePropertyChanged("id");
}
}
[XmlElement(IsNullable=true, Order=3)]
public DateTime? lastcheck
{
get
{
return this.lastcheckField;
}
set
{
this.lastcheckField = value;
base.RaisePropertyChanged("lastcheck");
}
}
}
[XmlType(Namespace="http://tempuri.org/"), GeneratedCode("System.Xml", "4.0.30319.1"), XmlInclude(typeof(ActiveUserReference)), DebuggerStepThrough]
public abstract class ESObject : INotifyPropertyChanged
{
// Fields
//private PropertyChangedEventHandler PropertyChanged;
// Events
public event PropertyChangedEventHandler PropertyChanged;
// Methods
protected ESObject()
{
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
#endif

View File

@@ -0,0 +1,90 @@
using System;
using System.Runtime.Serialization;
using System.IO;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Globalization;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Xml;
using System.CodeDom.Compiler;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class Bug695203Test
{
[Test]
public void DoTest ()
{
using (var mem = new MemoryStream ()) {
BaseClass data = new DerivedA1 { Code = "1", CodeA = "A", CodeA1 = "A1" };
Serialize (data, mem);
mem.Position = 0;
var docResult = Deserialize<BaseClass> (mem);
}
using (var mem = new MemoryStream ()) {
BaseClass data = new DerivedA2 { Code = "1", CodeA = "A", CodeA2 = "A1" };
Serialize (data, mem);
mem.Position = 0;
var docResult = Deserialize<BaseClass> (mem);
}
}
void Serialize<T> (T instance, Stream destinationStream)
{
var serializer = new DataContractSerializer (typeof (T), null, int.MaxValue, false, true, null);
using (var writer = XmlDictionaryWriter.CreateBinaryWriter (destinationStream, null, null, false))
serializer.WriteObject (writer, instance);
}
public static T Deserialize<T> (Stream sourceStream)
{
var serializer = new DataContractSerializer (typeof (T), null, int.MaxValue, false, true, null);
using (var reader = XmlDictionaryReader.CreateBinaryReader(sourceStream, XmlDictionaryReaderQuotas.Max))
return (T) serializer.ReadObject (reader);
}
[DataContract]
[KnownType (typeof (DerivedA1))]
[KnownType (typeof (DerivedA))]
public abstract class BaseClass
{
[DataMember]
public string Code { get; set; }
}
[DataContract]
[KnownType (typeof (DerivedA1))]
[KnownType (typeof (DerivedA2))]
public abstract class DerivedA : BaseClass
{
public string CodeA { get; set; }
}
[DataContract]
public class DerivedA1 : DerivedA
{
[DataMember]
public string CodeA1 { get; set; }
}
[DataContract]
public class DerivedA2 : DerivedA
{
[DataMember]
public string CodeA2 { get; set; }
}
}
}

View File

@@ -0,0 +1,332 @@
2010-06-02 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : enable binary reader test for #601785.
2010-06-01 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for bug #601785, based on
the test by Raja Harinath.
2010-05-31 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : test PreserveObjectReferences too.
2010-05-31 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : add test for bug #610036.
2010-04-28 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : add test for bug #599899.
2010-03-04 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : test for empty array deserialization.
2010-03-01 Atsushi Enomoto <atsushi@ximian.com>
* XsdDataContractExporterTest.cs : remove [NotWorking].
2010-02-19 Atsushi Enomoto <atsushi@ximian.com>
* XsdDataContractImporterTest.cs : added Dictionary export tests.
2010-02-18 Atsushi Enomoto <atsushi@ximian.com>
* XsdDataContractImporterTest.cs : enabled new tests.
2010-02-17 Atsushi Enomoto <atsushi@ximian.com>
* XsdDataContractImporterTest.cs : added a bunch of tests for new
implementation. Disable yet.
2010-02-09 Atsushi Enomoto <atsushi@ximian.com>
* XsdDataContractImporterTest.cs : add test that it gives
appropriate code namespaces.
2010-02-08 Atsushi Enomoto <atsushi@ximian.com>
* XsdDataContractImporterTest.cs : add test that ArrayOfxxx type
is not added.
2010-01-25 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for bug #560155.
2010-01-08 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for bug #568763.
2009-09-28 Atsushi Enomoto <atsushi@ximian.com>
* XsdDataContractExporterTest.cs : disable some tests that started
to fail due to correctly sorted fields while xsd exporter has
some bugs that emits duplicate fields (hence ambiguity occurs).
2009-09-28 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : Test nested type serialization type
initialization.
2009-09-07 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : fix (here too) bad serialization-
compatibility-dependent test.
2009-09-07 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : fixed wrong EOLs that resulted in
failure in .NET.
* XsdDataContractExporterTest.cs : fix test that failed on .NET,
and marked as NotWorking (no proceeding wsdl work yet).
2009-09-04 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : add test for [IgnoreDataMember].
2009-07-23 Sebastien Pouliot <sebastien@ximian.com>
* XmlObjectSerializerTest.cs: Add test cases with a generic
dictionary (empty, broken with r138386, and with one element)
that both works on MS.NET and for which Moonlight depends on.
2009-07-22 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs :
Add test for bug #524086 by Rolf Bjarne Kvinge.
Add enum flags test, which should not raise an error.
2009-07-22 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : add test for bug #524083, by
Rolf Bjarne Kvinge.
2009-07-22 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : now we can make xml indented as
originally done in #524088.
2009-07-22 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for bug #524088 by
Rolf Bjarne Kvinge (a bit modified).
2009-06-01 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : enable interface collection test and
add some more test lines.
2009-05-14 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added serialization test for
interface collection.
2009-03-12 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for dictionary with
CollectionDataContractAttribute.
2009-03-12 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added tests for IDictionary
serialization (both generic and non-generic).
2009-03-11 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : test for generic IList of
DictionaryEntry. (no Hashtable serialization yet.)
2009-03-11 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : test for generic IList of KeyValuePair
(it is still different from full IDictionary support...!).
2009-03-11 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : test for generic IList serialization.
2009-03-10 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : test for generic type serialization.
2009-02-13 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : fixed non-contract serialization
tests and remove some NotWorking.
2009-02-13 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : fixed collection contract test and
added some notes.
2009-02-13 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added couple of test fixes in
collection serialization tests.
2008-11-23 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for IsReference = true.
2008-04-17 Eyal Alaluf <eyala@mainsoft.com>
* XmlObjectSerializerTest.cs: Add test for base class with a different XML
namespace then its derived class.
Add tests for derserialization of arrays.
2008-04-14 Eyal Alaluf <eyala@mainsoft.com>
* XmlObjectSerializerTest.cs: DataContract types don't need anymore an empty
ctor.
2008-04-10 Eyal Alaluf <eyala@mainsoft.com>
* XmlObjectSerializerTest.cs: Add test scenarios for testing serialization
and deserialization of more complex types, namespace support, etc.
2008-04-03 Igor Zelmanovich <igorz@mainsoft.com>
* DataContractSerializerTest_FrameworkTypes_mscorlib.cs:
* DataContractSerializerTest_FrameworkTypes_System.cs:
* DataContractSerializerTest_FrameworkTypes_System.Data.cs:
* XmlObjectSerializerTest.cs:
add NotWorking attribute.
2008-03-31 Igor Zelmanovich <igorz@mainsoft.com>
* DataContractSerializerTest_FrameworkTypes_System.Data.cs: new testfixture.
2008-03-31 Igor Zelmanovich <igorz@mainsoft.com>
* DataContractSerializerTest_FrameworkTypes_System.cs: new testfixture.
2008-03-31 Igor Zelmanovich <igorz@mainsoft.com>
* DataContractSerializerTest_FrameworkTypes.cs: refactoring.
* DataContractSerializerTest_FrameworkTypes_mscorlib.cs: new testfixture.
2008-03-31 Igor Zelmanovich <igorz@mainsoft.com>
* DataContractSerializerTest_FrameworkTypes.cs:
add infrastructure for following tests.
2008-03-30 Igor Zelmanovich <igorz@mainsoft.com>
* XmlObjectSerializerTest.cs: use XmlComparer, remove NotWorking.
2008-02-27 Eyal Alaluf <eyala@mainsoft.com>
* XmlObjectSerializerTest.cs: Added tests for Read/WriteObject
* AttributesTest.cs: Added tests for new Serialization attributes.
* XsdDataContractImporterTest.cs: Added null arguments tests to the
Import methods. marked ImportTest as not working.
2008-02-27 Eyal Alaluf <eyala@mainsoft.com>
* one.xml: Indentation change
2007-12-05 Atsushi Enomoto <atushi@ximian.com>
* XmlObjectSerializerTest.cs : test for .ctor() with null knownTypes.
2007-11-27 Atsushi Enomoto <atushi@ximian.com>
* XmlObjectSerializerTest.cs, XsdDataContractImporterTest.cs:
couple of tests are not working now.
2007-08-17 Atsushi Enomoto <atushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for ReadObject() with
verifyObjectData = false.
2007-07-27 Atsushi Enomoto <atushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for serializing IPAddress
(will be required for RegisterInfo).
2007-07-26 Atsushi Enomoto <atushi@ximian.com>
* XmlObjectSerializerTest.cs : added Guid serialization test.
2006-09-05 Ankit Jain <jankit@novell.com>
* XsdDataContractImporterTest.cs (PrimitiveType): Add a check for number
of schemas.
2006-09-04 Ankit Jain <jankit@novell.com>
* XsdDataContractExporterTest.cs (Ctor1): Remove 'NotWorking'.
(PrimitiveType): New.
(CanExportTest): New.
(GetSchemaTypeTest): New.
(Test2): Ensure that exception is "expected" from the second Export.
2006-09-01 Ankit Jain <jankit@novell.com>
* XsdDataContractExporterTest.cs: New.
* XmlObjectSerializerTest.cs: New tests for serializing arrays.
2006-08-31 Ankit Jain <jankit@novell.com>
* XmlObjectSerializerTest.cs: Add tests for serializing/deserializing
enums.
2006-08-16 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added non-setter collection case.
(I was just curious how DataContractSerializer is useless here.)
2006-07-27 Ankit Jain <jankit@novell.com>
* one.xml: New. Used by XsdDataContractImporterTest.cs
* XsdDataContractImporterTest.cs: New.
2006-07-18 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : the previous test is working now.
2006-07-18 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : finally I found out why non-
datacontract .ctor() does not fail while SerializeNonDC() fails.
2006-05-09 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added more .ctor() tests.
2006-05-09 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs :
Added test for nested class serialization.
2006-05-09 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added some .ctor() tests.
2006-04-06 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for string serialization.
QName as well but [Ignore] right now.
2006-03-09 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added test for WriteObjectContent()
without WriteStartObject().
2006-03-08 Ankit Jain <jankit@novell.com>
* XmlObjectSerializerTest.cs (SerializeDCWithName):
(SerializeDCWithEmptyName1):
(SerializeDCWithEmptyName2):
(SerializeDCWithNullName):
(SerializeDCWithEmptyNamespace1): New serialization tests.
2006-03-03 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : added more serialization tests.
2006-03-02 Atsushi Enomoto <atsushi@ximian.com>
* XmlObjectSerializerTest.cs : new file for serialization tests.

View File

@@ -0,0 +1,460 @@
//
// CollectionSerialization
//
// Authors:
// Martin Baulig (martin.baulig@xamarin.com)
//
// Copyright 2012 Xamarin Inc. (http://www.xamarin.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.
//
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ServiceModel;
using NUnit.Framework;
using NUnit.Framework.Constraints;
#if !MOBILE
using NUnit.Framework.SyntaxHelpers;
#endif
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class CollectionSerialization
{
[DataContract]
class Foo
{
[DataMember]
public int Hello;
}
class MyList<T> : List<T>, IMyList<T>
{
}
interface IMyList<T> : IList
{
}
[Serializable]
class CustomList<T> : IList<T>
{
List<T> list;
public CustomList (IList<T> elements)
{
list = new List<T> ();
if (elements != null)
list.AddRange (elements);
}
#region IList implementation
public int IndexOf (T item)
{
return list.IndexOf (item);
}
public void Insert (int index, T item)
{
list.Insert (index, item);
}
public void RemoveAt (int index)
{
list.RemoveAt (index);
}
public T this [int index] {
get {
return list [index];
}
set {
list [index] = value;
}
}
#endregion
#region ICollection implementation
public void Add (T item)
{
list.Add (item);
}
public void Clear ()
{
list.Clear ();
}
public bool Contains (T item)
{
return list.Contains (item);
}
public void CopyTo (T[] array, int arrayIndex)
{
list.CopyTo (array, arrayIndex);
}
public bool Remove (T item)
{
return list.Remove (item);
}
#endregion
#region IEnumerable implementation
public IEnumerator<T> GetEnumerator ()
{
return list.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
#region ICollection<T> implementation
int ICollection<T>.Count {
get {
return list.Count;
}
}
bool ICollection<T>.IsReadOnly {
get {
return ((ICollection<T>)list).IsReadOnly;
}
}
#endregion
public override int GetHashCode ()
{
return list.GetHashCode ();
}
public override bool Equals (object obj)
{
var custom = obj as CustomList<T>;
if (custom == null)
return false;
if (list.Count != custom.list.Count)
return false;
for (int i = 0; i < list.Count; i++)
if (!list [i].Equals (custom.list [i]))
return false;
return true;
}
}
class CustomCollection<T> : CustomList<T>
{
public CustomCollection ()
: base (null)
{
}
public CustomCollection (IList<T> elements)
: base (elements)
{
}
}
static object Serialize<T> (object arg)
{
using (var ms = new MemoryStream ()) {
try {
var serializer = new DataContractSerializer (typeof(T));
serializer.WriteObject (ms, arg);
} catch (Exception ex) {
return ex;
}
return new UTF8Encoding ().GetString (ms.GetBuffer (), 0, (int)ms.Position);
}
}
static T Deserialize<T> (string text)
{
var buffer = new UTF8Encoding ().GetBytes (text);
using (var ms = new MemoryStream (buffer)) {
var serializer = new DataContractSerializer (typeof(T));
return (T)serializer.ReadObject (ms);
}
}
[Test]
public void CollectionInterfaceContract ()
{
var array = new object[3] { 1, 2, 3 };
var arrayResult = (string)Serialize<object[]> (array);
var list = new List<int> (new[] { 1, 2, 3 });
Assert.That (Serialize<IList> (array), Is.EqualTo (arrayResult), "#1");
Assert.That (Serialize<IList> (list), Is.EqualTo (arrayResult), "#2");
Assert.That (Serialize<IEnumerable> (list), Is.EqualTo (arrayResult), "#3");
Assert.That (Serialize<ICollection> (list), Is.EqualTo (arrayResult), "#4");
var alist = new ArrayList ();
alist.AddRange (array);
Assert.That (Serialize<IList> (alist), Is.EqualTo (arrayResult), "#5");
Assert.That (Deserialize<IList> (arrayResult), Is.EqualTo (list), "#6");
Assert.That (Deserialize<IEnumerable> (arrayResult), Is.EqualTo (list), "#7");
Assert.That (Deserialize<ICollection> (arrayResult), Is.EqualTo (list), "#8");
}
[Test]
public void GenericCollectionInterfaceContract ()
{
var array = new[] { 1, 2, 3 };
var arrayResult = (string)Serialize<int[]> (array);
var list = new List<int> (array);
var mylist = new MyList<int> ();
mylist.AddRange (array);
var custom = new CustomList<int> (array);
Assert.That (Serialize<IList<int>> (list), Is.EqualTo (arrayResult), "#1");
Assert.That (Serialize<IEnumerable<int>> (list), Is.EqualTo (arrayResult), "#2");
Assert.That (Serialize<ICollection<int>> (list), Is.EqualTo (arrayResult), "#3");
Assert.That (Serialize<IList<object>> (list),
InstanceOf (typeof (InvalidCastException)), "#4");
Assert.That (Serialize<IList<int>> (mylist), Is.EqualTo (arrayResult), "#5");
Assert.That (Serialize<IList<int>> (list.AsReadOnly ()), Is.EqualTo (arrayResult), "#6");
Assert.That (Serialize<IList<int>> (custom), Is.EqualTo (arrayResult), "#7");
Assert.That (Deserialize<IList<int>> (arrayResult), Is.EqualTo (list), "#8");
Assert.That (Deserialize<List<int>> (arrayResult), Is.EqualTo (list), "#9");
}
[Test]
public void CustomCollectionInterfaceContract ()
{
var array = new[] { 1, 2, 3 };
var arrayResult = Serialize<int[]> (array);
var mylist = new MyList<int> ();
mylist.AddRange (array);
Assert.That (Serialize<IList<int>> (mylist), Is.EqualTo (arrayResult), "#1");
Assert.That (Serialize<List<int>> (mylist), Is.EqualTo (arrayResult), "#2");
Assert.That (Serialize<IMyList<int>> (mylist),
InstanceOf (typeof (SerializationException)), "#3");
Assert.That (Serialize<MyList<int>> (mylist), Is.EqualTo (arrayResult), "#4");
}
[Test]
public void CustomCollectionTypeContract ()
{
var array = new[] { 1, 2, 3 };
var arrayResult = (string)Serialize<int[]> (array);
var custom = new CustomList<int> (array);
var result = (string)Serialize<CustomList<int>> (custom);
Assert.That (result.Contains ("CustomListOfint"), Is.True, "#1");
Assert.That (Deserialize<CustomList<int>> (result), Is.EqualTo (custom), "#2");
var ro = array.ToList ().AsReadOnly ();
var result2 = (string)Serialize<ReadOnlyCollection<int>> (ro);
Assert.That (result2.Contains ("ReadOnlyCollectionOfint"), Is.True, "#3");
Assert.That (Deserialize<ReadOnlyCollection<int>> (result2), Is.EqualTo (ro), "#4");
/*
* CustomList<T> implements one of the collection interfaces, but does not have
* a public parameterless constructor. It is therefor treated like a normal
* [Serializable] type and can not be deserialized from an array.
*
* The same also applies to ReadOnlyCollection<T>.
*
*/
try {
Deserialize<CustomList<int>> (arrayResult);
Assert.Fail ("#5");
} catch (Exception ex) {
Assert.That (ex, InstanceOf (typeof (SerializationException)), "#6");
}
try {
Deserialize<ReadOnlyCollection<int>> (arrayResult);
Assert.Fail ("#7");
} catch (Exception ex) {
Assert.That (ex, InstanceOf (typeof (SerializationException)), "#8");
}
/*
* CustomCollection<T> does have the required public parameterless constructor,
* so it is treated as custom collection type and serialized as array.
*
*/
var collection = new CustomCollection<int> (array);
var result3 = (string)Serialize<CustomCollection<int>> (collection);
Assert.That (result3, Is.EqualTo (arrayResult), "#9");
Assert.That (Deserialize<CustomCollection<int>> (result3), Is.EqualTo (collection), "#10");
}
[Test]
public void ArrayContract ()
{
var array = new[] { 1, 2, 3 };
var list = new List<int> (array);
Assert.That (Serialize<int[]> (list),
InstanceOf (typeof (InvalidCastException)), "#1");
Assert.That (Serialize<object[]> (array),
InstanceOf (typeof (InvalidCastException)), "#2");
}
[Test]
public void ListOfArrays ()
{
var water = new[] { "Fish", "Mermaid" };
var land = new[] { "Horse", "Human", "Lion" };
var air = new[] { "Bird", "Drake" };
var species = new[] { water, land, air };
var serialized = (string)Serialize<string[][]> (species);
var list = new List<string[]> (species);
Assert.That (Serialize<IList<string[]>> (species), Is.EqualTo (serialized), "#1");
Assert.That (Serialize<IList<string[]>> (list), Is.EqualTo (serialized), "#2");
}
[CollectionDataContract (Name = "MyCollection")]
class MissingAddMethod<T> : IEnumerable<T>
{
#region IEnumerable implementation
public IEnumerator<T> GetEnumerator ()
{
throw new InvalidOperationException ();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
throw new InvalidOperationException ();
}
#endregion
}
[CollectionDataContract (Name = "MyCollection")]
class MissingEnumerable<T>
{
public void Add (T item)
{
throw new NotImplementedException ();
}
}
[CollectionDataContract (Name = "MyCollection")]
class MyDataContractCollection<T> : IEnumerable<T>
{
List<T> list;
public MyDataContractCollection ()
{
list = new List<T> ();
}
public MyDataContractCollection (IList<T> elements)
{
list = new List<T> ();
list.AddRange (elements);
}
#region IEnumerable implementation
public IEnumerator<T> GetEnumerator ()
{
return list.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
public void Add (T item)
{
list.Add (item);
}
}
class MyDerivedDataContract<T> : MyDataContractCollection<T>
{
}
[Test]
public void TestCollectionDataContract ()
{
Assert.That (Serialize<MissingAddMethod<int>> (new MissingAddMethod<int> ()),
InstanceOf (typeof (InvalidDataContractException)), "#1");
Assert.That (Serialize<MissingEnumerable<int>> (new MissingEnumerable<int> ()),
InstanceOf (typeof (InvalidDataContractException)), "#2");
var array = new[] { 1, 2, 3 };
var arrayResult = (string)Serialize<int[]> (array);
var collection = new MyDataContractCollection<int> (array);
var result = Serialize<MyDataContractCollection<int>> (collection);
Assert.That (result, InstanceOf (typeof(string)), "#3");
Assert.That (Serialize<MyDataContractCollection<int>> (array),
InstanceOf (typeof (SerializationException)), "#4");
var derived = new MyDerivedDataContract<int> ();
Assert.That (Serialize<MyDataContractCollection<int>> (derived),
InstanceOf (typeof (SerializationException)), "#5");
try {
Deserialize<MyDataContractCollection<int>> (arrayResult);
Assert.Fail ("#6");
} catch (Exception ex) {
Assert.That (ex, InstanceOf (typeof(SerializationException)), "#7");
}
var deserialized = Deserialize<MyDataContractCollection<int>> ((string)result);
Assert.That (deserialized, InstanceOf (typeof (MyDataContractCollection<int>)), "#8");
}
[Test]
public void Test ()
{
var derived = new MyDerivedDataContract<int> ();
Assert.That (Serialize<MyDataContractCollection<int>> (derived),
InstanceOf (typeof (SerializationException)), "#5");
}
public static InstanceOfTypeConstraint InstanceOf (Type expectedType)
{
return new InstanceOfTypeConstraint (expectedType);
}
}
}

View File

@@ -0,0 +1,118 @@
//
// XmlObjectSerializerTest.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
// Ankit Jain <JAnkit@novell.com>
//
// 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.
//
#if NET_4_0
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class DataContractResolverTest
{
[Test]
public void UseCase1 ()
{
var ds = new DataContractSerializer (typeof (Colors), null, 10000, false, false, null, new MyResolver ());
var sw = new StringWriter ();
using (var xw = XmlWriter.Create (sw))
ds.WriteObject (xw, new ResolvedClass ());
// xml and xml2 are equivalent in infoset, except for prefixes and position of namespace nodes. So the difference should not matter.
string xml = @"<?xml version='1.0' encoding='utf-16'?><Colors xmlns:i='http://www.w3.org/2001/XMLSchema-instance' xmlns:d1p1='urn:dummy' i:type='d1p1:ResolvedClass' xmlns='http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization'><Baz xmlns='http://schemas.datacontract.org/2004/07/'>c74376f0-5517-4cb7-8a07-35026423f565</Baz></Colors>".Replace ('\'', '"');
string xml2 = @"<?xml version='1.0' encoding='utf-16'?><Colors xmlns:i='http://www.w3.org/2001/XMLSchema-instance' xmlns:d1p1='urn:dummy' xmlns:d1p2='http://schemas.datacontract.org/2004/07/' i:type='d1p2:ResolvedClass' xmlns='http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization'><d1p2:Baz>c74376f0-5517-4cb7-8a07-35026423f565</d1p2:Baz></Colors>".Replace ('\'', '"');
try {
Assert.AreEqual (xml, sw.ToString (), "#1");
} catch (AssertionException) {
Assert.AreEqual (xml2, sw.ToString (), "#2");
}
using (var xr = XmlReader.Create (new StringReader (xml)))
Assert.AreEqual (typeof (ResolvedClass), ds.ReadObject (xr).GetType (), "#3");
using (var xr = XmlReader.Create (new StringReader (xml)))
Assert.AreEqual (typeof (ResolvedClass), ds.ReadObject (xr).GetType (), "#4");
}
}
public class MyResolver : DataContractResolver
{
public override bool TryResolveType (Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
//Console.WriteLine ("TryResolveType: {0} {1}", type, declaredType);
if (knownTypeResolver.TryResolveType (type, declaredType, null, out typeName, out typeNamespace))
return true;
return SafeResolveType (type, out typeName, out typeNamespace);
}
XmlDictionary dic = new XmlDictionary ();
bool SafeResolveType (Type type, out XmlDictionaryString name, out XmlDictionaryString ns)
{
// Console.WriteLine ("SafeResolveType: {0}", type);
name = dic.Add (type.Name);
ns = dic.Add (type.Namespace ?? "urn:dummy");
return true;
}
public override Type ResolveName (string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
{
//Console.WriteLine ("ResolveName: {0} {1} {2}", typeName, typeNamespace, declaredType);
return knownTypeResolver.ResolveName (typeName, typeNamespace, declaredType, null) ?? RecoveringResolveName (typeName, typeNamespace);
}
Type RecoveringResolveName (string typeName, string typeNamespace)
{
if (typeNamespace == "urn:dummy")
return Type.GetType (typeName);
else
return Type.GetType (typeNamespace + '.' + typeName);
}
}
}
[DataContract]
public class ResolvedClass
{
[DataMember]
public Guid Baz = Guid.Parse ("c74376f0-5517-4cb7-8a07-35026423f565");
}
#endif

View File

@@ -0,0 +1,97 @@
//
// DataContractSerializerTest.cs
//
// Author:
// Brendan Zagaeski
// Miguel de Icaza
//
// Copyright (C) 2013-2014 Xamarin Inc http://www.xamarin.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 attributes in System.Runtime.Serialization
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Reflection;
using System.Globalization;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;
namespace MonoTests.System.Runtime.Serialization
{
[KnownType (typeof(MyObject[]))]
[DataContract]
public class MyObject2
{
[DataMember]
public object NameList;
}
[KnownType(typeof(string[]))]
[DataContract]
public class MyObject
{
[DataMember]
public object NameList;
}
[TestFixture]
public class DataContractSerializerTestBugs {
// Bug #15574
[Test]
public void SerializeMyObject ()
{
var attrs = (KnownTypeAttribute[])typeof(MyObject).
GetCustomAttributes (typeof(KnownTypeAttribute), true);
for (int i = 0; i < attrs.Length; i ++) {
Console.WriteLine (attrs [i].Type);
}
var ser = new DataContractSerializer (typeof(MyObject));
}
[Test]
public void Bug ()
{
var s = "<MyObject xmlns=\"http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <NameList i:type=\"a:ArrayOfstring\" xmlns:a=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">\n" +
" <a:string>Name1</a:string>\n" +
" <a:string>Name2</a:string>\n" +
" </NameList>\n" +
"</MyObject>";
//<MyObject xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ServiceTest">
var ser = new DataContractSerializer(typeof(MyObject));
ser.ReadObject (XmlReader.Create(new StringReader(s)));
}
}
}

View File

@@ -0,0 +1,170 @@
//
// DataContractSerializerTest_DuplicateQName.cs
//
// Author:
// David Ferguson <davecferguson@gmail.com>
//
// Copyright (C) 2012 Dell AppAssure http://www.appassure.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 the DataContractSerializer
// concerning duplicate Qualified Names for the object graph and known types
//
using System;
using System.IO;
using System.Runtime.Serialization;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class DataContractSerializerTest_DuplicateQName
{
[DataContract (Name="name", Namespace="http://somecompany.com/function/api/2010/05")]
[Serializable]
public class DataContractBase
{
public DataContractBase ()
{
}
public DataContractBase (string val)
{
BaseValue1 = val;
}
[DataMember(Name="baseValue1", Order=1)]
public string BaseValue1 { get; set; }
}
[DataContract (Name="name", Namespace="http://somecompany.com/function/api/2010/05")]
[Serializable]
public class DataContract1 : DataContractBase
{
public DataContract1 ()
{
}
public DataContract1 (string val) : base (val)
{
}
}
[DataContract(Name = "name", Namespace = "http://somecompany.com/function/api/2010/05")]
[Serializable]
public class DataContract2
{
[DataMember]
public DataContract3 DataContract3 { get; set; }
}
[DataContract(Name = "name", Namespace = "http://somecompany.com/function/api/2010/05")]
[Serializable]
public class DataContract3
{
}
[DataContract(Name = "name", Namespace = "http://somecompany.com/function/api/2010/05")]
[Serializable]
public class DataContract4
{
[DataMember(Name = "name")]
public double
Test1;
}
[Test]
public void TestMultipleDataContractSameDataContractNameAndNamespace ()
{
// DataContract1 derives from DataContractBase and they both have
// the same QName specified in their respective DataContractAttribute.
var serializer = new DataContractSerializer (typeof(DataContract1));
var serializerBase = new DataContractSerializer (typeof(DataContractBase));
Assert.IsNotNull (serializer);
Assert.IsNotNull (serializerBase);
}
[Test]
public void TestDataContractWithPropertyHavingSameQName ()
{
// DataContract2 has a property of DataContract3. DataContract2 and
// DataContract3 both have the same QName specified in their
// respective DataContractAttribute. This was causing a failure due
// to the QName being saved in the SerializationMap twice. Bug 4794.
var serializer2 = new DataContractSerializer (typeof(DataContract2));
var d = new DataContract2 ();
var ms = new MemoryStream (2048);
Assert.IsNotNull (serializer2, "Failed to create the serializer for DataContract2");
serializer2.WriteObject (ms, d);
ms.Position = 0;
var d2 = serializer2.ReadObject (ms) as DataContract2;
Assert.IsNotNull (d2, "Failed to deserialize the data buffer into a DataContract2");
}
[Test]
public void TestDataContractWithPrimitiveHavingSameQName ()
{
// This test verifies that a primitive with the same qname as the
// DataContract succeeds in serializing and deserializing
var serializer4 = new DataContractSerializer (typeof(DataContract4));
var d = new DataContract4 ();
var ms = new MemoryStream (2048);
Assert.IsNotNull (serializer4, "Failed to create the serializer for DataContract4");
d.Test1 = 3.1416;
serializer4.WriteObject (ms, d);
ms.Position = 0;
var d2 = serializer4.ReadObject (ms) as DataContract4;
Assert.IsNotNull (d2, "Failed to deserialize the data buffer into a DataContract4");
Assert.AreEqual (d2.Test1, 3.1416, "Rehydrated Test1 property did not match original");
Assert.AreNotSame (d2, d, "The instances are the same and should not be");
}
[Test]
public void TestKnownTypes ()
{
// The .NET behavior is that the KnownTypes collection is not populated unless you
// do so through the constructor. It even ignores attributes on the type indicating
// a known type.
var serializer = new DataContractSerializer (typeof(DataContract1));
var serializerWithKnownType = new DataContractSerializer (
typeof(DataContract2),
new [] { typeof(DataContract3) }
);
Assert.AreEqual (serializer.KnownTypes.Count, 0, "Expected an empty known type collection");
Assert.AreEqual (serializerWithKnownType.KnownTypes.Count, 1, "Known count type did not match");
}
}
}

View File

@@ -0,0 +1,71 @@
//
// DataContractSerializerTest_InvalidCharacters.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc. (http://www.xamarin.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.
using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class DataContractSerializerTest_InvalidCharacters
{
[Serializable]
public class MyData
{
public string Text;
}
[Test]
public void Test ()
{
var data = new MyData
{
Text = "Test " + ASCIIEncoding.ASCII.GetString (new byte[] { 0x06 })
};
var serializer = new DataContractSerializer (typeof(MyData), "MyData", string.Empty);
string serialized;
using (var ms = new MemoryStream ()) {
serializer.WriteObject (ms, data);
serialized = new string (Encoding.UTF8.GetChars (ms.GetBuffer ()));
Assert.IsTrue (serialized.Contains ("Test &#x6;"), "#1");
ms.Seek (0, SeekOrigin.Begin);
var data2 = (MyData)serializer.ReadObject (ms);
Assert.AreEqual (data2.Text.Length, 6, "#2");
Assert.AreEqual (data2.Text [5], (char)0x06, "#3");
}
}
}
}

View File

@@ -0,0 +1,365 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Xml;
using System.ServiceModel.Dispatcher;
using System.Text;
using NUnit.Framework;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.261
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Client.EvalServiceReference {
using System.Runtime.Serialization;
using System;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Eval", Namespace="http://schemas.datacontract.org/2004/07/WcfServiceLibrary1")]
[System.SerializableAttribute()]
public partial class Eval : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string IdField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private Client.EvalServiceReference.EvalItem[] itemsListField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private System.Collections.Generic.Dictionary<string, Client.EvalServiceReference.EvalItem> itemsMapField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Id {
get {
return this.IdField;
}
set {
if ((object.ReferenceEquals(this.IdField, value) != true)) {
this.IdField = value;
this.RaisePropertyChanged("Id");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public Client.EvalServiceReference.EvalItem[] itemsList {
get {
return this.itemsListField;
}
set {
if ((object.ReferenceEquals(this.itemsListField, value) != true)) {
this.itemsListField = value;
this.RaisePropertyChanged("itemsList");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Collections.Generic.Dictionary<string, Client.EvalServiceReference.EvalItem> itemsMap {
get {
return this.itemsMapField;
}
set {
if ((object.ReferenceEquals(this.itemsMapField, value) != true)) {
this.itemsMapField = value;
this.RaisePropertyChanged("itemsMap");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="EvalItem", Namespace="http://schemas.datacontract.org/2004/07/WcfServiceLibrary1")]
[System.SerializableAttribute()]
public partial class EvalItem : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string ItemField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private System.Nullable<System.DateTime> ItemTimeField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private System.Nullable<Client.EvalServiceReference.EvalType> etypeField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Item {
get {
return this.ItemField;
}
set {
if ((object.ReferenceEquals(this.ItemField, value) != true)) {
this.ItemField = value;
this.RaisePropertyChanged("Item");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<System.DateTime> ItemTime {
get {
return this.ItemTimeField;
}
set {
if ((this.ItemTimeField.Equals(value) != true)) {
this.ItemTimeField = value;
this.RaisePropertyChanged("ItemTime");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<Client.EvalServiceReference.EvalType> etype {
get {
return this.etypeField;
}
set {
if ((this.etypeField.Equals(value) != true)) {
this.etypeField = value;
this.RaisePropertyChanged("etype");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="EvalType", Namespace="http://schemas.datacontract.org/2004/07/WcfServiceLibrary1")]
public enum EvalType : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
SIMPLE = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
COMPLEX = 2,
[System.Runtime.Serialization.EnumMemberAttribute()]
NONE = 3,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="EvalServiceReference.IEvalService")]
public interface IEvalService {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IEvalService/SubmitEval", ReplyAction="http://tempuri.org/IEvalService/SubmitEvalResponse")]
void SubmitEval(Client.EvalServiceReference.Eval eval);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IEvalService/GetEvals", ReplyAction="http://tempuri.org/IEvalService/GetEvalsResponse")]
Client.EvalServiceReference.Eval[] GetEvals();
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IEvalService/RemoveEval", ReplyAction="http://tempuri.org/IEvalService/RemoveEvalResponse")]
void RemoveEval(string id);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IEvalServiceChannel : Client.EvalServiceReference.IEvalService, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class EvalServiceClient : System.ServiceModel.ClientBase<Client.EvalServiceReference.IEvalService>, Client.EvalServiceReference.IEvalService {
public EvalServiceClient() {
}
public EvalServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public EvalServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public EvalServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public EvalServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public void SubmitEval(Client.EvalServiceReference.Eval eval) {
base.Channel.SubmitEval(eval);
}
public Client.EvalServiceReference.Eval[] GetEvals() {
return base.Channel.GetEvals();
}
public void RemoveEval(string id) {
base.Channel.RemoveEval(id);
}
}
}
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class SerializeNullableWithDictionaryTest
{
[Test]
public void TestNullableWithDictionary()
{
string Name = "GetEvalsResult";
string Wrapper = "GetEvalsResponse";
string Namespace = "http://tempuri.org/";
Type type = typeof(Client.EvalServiceReference.Eval[]);
IEnumerable<Type> know_types = new List<Type>();
// This is the XML generated by WCF Server
string xml = "<GetEvalsResponse xmlns=\"http://tempuri.org/\"> <GetEvalsResult xmlns:a=\"http://schemas.datacontract.org/2004/07/WcfServiceLibrary1\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"> <a:Eval> <a:Id>8215784f-bf5f-4df8-b239-34a0a029a54e</a:Id> <a:itemsList> <a:EvalItem> <a:Item>Item on List 3</a:Item> <a:ItemTime>2012-03-04T04:04:00</a:ItemTime> <a:etype>COMPLEX</a:etype> </a:EvalItem> <a:EvalItem i:nil=\"true\" /> </a:itemsList> <a:itemsMap xmlns:b=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"> <b:KeyValueOfstringEvalItemo8PfwX7N> <b:Key>Item3</b:Key> <b:Value> <a:Item>Item 2 on Map</a:Item> <a:ItemTime i:nil=\"true\" /> <a:etype>NONE</a:etype> </b:Value> </b:KeyValueOfstringEvalItemo8PfwX7N> <b:KeyValueOfstringEvalItemo8PfwX7N> <b:Key /> <b:Value i:nil=\"true\" /> </b:KeyValueOfstringEvalItemo8PfwX7N> </a:itemsMap> </a:Eval> </GetEvalsResult> </GetEvalsResponse>";
Client.EvalServiceReference.Eval[] evals = null;
StringBuilder stringBuilder = new StringBuilder ();
var ds = new DataContractSerializer (type, Name, Namespace, know_types);
using (var xr = XmlDictionaryReader.CreateDictionaryReader ( XmlReader.Create (new StringReader (xml))))
{
xr.ReadStartElement (Wrapper, Namespace);
for (xr.MoveToContent (); xr.NodeType == XmlNodeType.Element; xr.MoveToContent ()) {
XmlQualifiedName key = new XmlQualifiedName (xr.LocalName, xr.NamespaceURI);
if ( Name == key.Name && Namespace == key.Namespace)
break;
}
evals = (Client.EvalServiceReference.Eval[])ds.ReadObject (xr, true);
}
using (var xw = XmlDictionaryWriter.CreateDictionaryWriter ( XmlWriter.Create( new StringWriter(stringBuilder)))) {
ds.WriteObject (xw, evals);
}
string actualXml = stringBuilder.ToString ();
Assert.AreEqual (evals.Length, 1, "evals.Length missmatch");
Client.EvalServiceReference.Eval eval = evals[0];
Assert.AreEqual (eval.Id, "8215784f-bf5f-4df8-b239-34a0a029a54e", "eval.Id missmatch");
Assert.AreEqual (eval.itemsList.Length, 2, "eval.itemsList.Length missmatch");
Client.EvalServiceReference.EvalItem evalItem = eval.itemsList[0];
Assert.AreEqual (evalItem.Item, "Item on List 3", "evalItem.Item missmatch");
Assert.AreEqual (evalItem.ItemTime , DateTime.Parse("2012-03-04T04:04:00"), "evalItem.ItemTime missmatch");
Assert.AreEqual (evalItem.etype, Client.EvalServiceReference.EvalType.COMPLEX, "evalItem.etype missmatch");
Client.EvalServiceReference.EvalItem evalItem2 = eval.itemsList[1];
Assert.IsNull (evalItem2, "evalItem2 missmatch");
Assert.AreEqual (eval.itemsMap.Count, 2, "eval.itemsMap.Count missmatch");
Client.EvalServiceReference.EvalItem evalItem3 = eval.itemsMap["Item3"];
Assert.AreEqual (evalItem3.Item, "Item 2 on Map", "evalItem3.Item missmatch");
Assert.IsNull (evalItem3.ItemTime, "evalItem3.ItemTime missmatch");
Assert.AreEqual (evalItem3.etype, Client.EvalServiceReference.EvalType.NONE, "evalItem3.etype missmatch");
Client.EvalServiceReference.EvalItem evalItem4 = eval.itemsMap[""];
Assert.IsNull(evalItem4, "Item 2 on Map", "evalItem4");
Client.EvalServiceReference.Eval[] evals2 = null;
using (var xr = XmlDictionaryReader.CreateDictionaryReader ( XmlReader.Create (new StringReader (actualXml))))
{
evals2 = (Client.EvalServiceReference.Eval[])ds.ReadObject (xr, true);
}
Assert.AreEqual (evals2.Length, 1, "evals2.Length missmatch");
Client.EvalServiceReference.Eval eval2 = evals2[0];
Assert.AreEqual (eval2.Id, "8215784f-bf5f-4df8-b239-34a0a029a54e", "eval2.Id missmatch");
Assert.AreEqual (eval2.itemsList.Length, 2, "eval2.itemsList.Length missmatch");
Client.EvalServiceReference.EvalItem eval2Item = eval2.itemsList[0];
Assert.AreEqual (eval2Item.Item, "Item on List 3", "eval2Item.Item missmatch");
Assert.AreEqual (eval2Item.ItemTime , DateTime.Parse("2012-03-04T04:04:00"), "eval2Item.ItemTime missmatch");
Assert.AreEqual (eval2Item.etype, Client.EvalServiceReference.EvalType.COMPLEX, "eval2Item.etype missmatch");
Client.EvalServiceReference.EvalItem eval2Item2 = eval2.itemsList[1];
Assert.IsNull (eval2Item2, "eval2Item2 missmatch");
Assert.AreEqual (eval2.itemsMap.Count, 2, "eval2.itemsMap.Count missmatch");
Client.EvalServiceReference.EvalItem eval2Item3 = eval2.itemsMap["Item3"];
Assert.AreEqual (eval2Item3.Item, "Item 2 on Map", "eval2Item3.Item missmatch");
Assert.IsNull (eval2Item3.ItemTime, "eval2Item3.ItemTime missmatch");
Assert.AreEqual (eval2Item3.etype, Client.EvalServiceReference.EvalType.NONE, "eval2Item3.etype missmatch");
Client.EvalServiceReference.EvalItem eval2Item4 = eval.itemsMap[""];
Assert.IsNull(eval2Item4, "eval2Item4 missmatch");
}
}
}

View File

@@ -0,0 +1,170 @@
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2011 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.
//
#if NET_2_0
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml;
using NUnit.Framework;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class KnownTypeAttributeTest
{
void Serialize (object instance)
{
var ds = new DataContractSerializer (instance.GetType ());
using (var xw = XmlWriter.Create (TextWriter.Null))
ds.WriteObject (xw, instance);
}
[Test]
public void MethodName ()
{
Serialize (new Data () { X = new Bar () });
}
[Test]
public void MethodName2 ()
{
Serialize (new Data2 () { X = new Bar () });
}
[Test]
[ExpectedException (typeof (InvalidDataContractException))]
public void MethodName3 ()
{
Serialize (new Data3 () { X = new Bar () });
}
[Test]
[ExpectedException (typeof (InvalidDataContractException))]
public void MethodName4 ()
{
Serialize (new Data4 () { X = new Bar () });
}
[Test]
public void GenericTypeNameArgument ()
{
string expected = "<Foo_KnownTypeAttributeTest.Foo xmlns:i='http://www.w3.org/2001/XMLSchema-instance' xmlns:d1p1='http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization' xmlns='urn:foo'><KnownTypeAttributeTest.Foo><d1p1:S>z</d1p1:S></KnownTypeAttributeTest.Foo></Foo_KnownTypeAttributeTest.Foo>".Replace ('\'', '"');
var ds = new DataContractSerializer (typeof (MyList<Foo>));
var l = new MyList<Foo> ();
l.Add (new Foo () { S = "z" });
var sw = new StringWriter ();
var settings = new XmlWriterSettings () { OmitXmlDeclaration = true };
using (var xw = XmlWriter.Create (sw, settings))
ds.WriteObject (xw, l);
Assert.AreEqual (expected, sw.ToString (), "#1");
}
[Test]
[ExpectedException (typeof (InvalidDataContractException))]
public void DataContractOnCollection ()
{
Serialize (new MyListWrong<Foo> ());
}
public class Foo
{
public string S { get; set; }
}
public class Bar : Foo
{
public string T { get; set; }
}
[DataContract]
[KnownType ("GetTypes")]
public class Data
{
[DataMember]
public Foo X { get; set; }
public static IEnumerable<Type> GetTypes ()
{
yield return typeof (Bar);
}
}
[DataContract]
[KnownType ("GetTypes")]
public class Data2
{
[DataMember]
public Foo X { get; set; }
static IEnumerable<Type> GetTypes () // non-public
{
yield return typeof (Bar);
}
}
[DataContract]
[KnownType ("GetTypes")]
public class Data3
{
[DataMember]
public Foo X { get; set; }
public IEnumerable<Type> GetTypes () // non-static
{
yield return typeof (Bar);
}
}
[DataContract]
[KnownType ("GetTypes")]
public class Data4
{
[DataMember]
public Foo X { get; set; }
public static IEnumerable<Type> GetTypes (ICustomAttributeProvider provider) // wrong args
{
yield return typeof (Bar);
}
}
[CollectionDataContract (Name = "Foo_{0}", Namespace = "urn:foo")]
public class MyList<T> : List<T>
{
}
[DataContract (Name = "Foo_{0}", Namespace = "urn:foo")]
public class MyListWrong<T> : List<T>
{
}
}
}
#endif

View File

@@ -0,0 +1,183 @@
//
// WsdlHelper.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// 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.
#if !MOBILE
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceModel.Description;
using System.Web.Services.Discovery;
using System.Runtime.Serialization;
using WebServices = System.Web.Services;
using System.CodeDom;
namespace MonoTests.System.Runtime.Serialization
{
public static class WsdlHelper
{
/*
* This reads a normal .wsdl file from an embedded resource.
*
* You can simply fetch them from your server using
* 'curl http://yourserver/YourService.svc?singleWsdl > YourService.wsdl',
* add the .wsdl file to Test/Resources/WSDL and add it to `TEST_RESOURCE_FILES'
* in the Makefile.
*/
public static MetadataSet GetMetadataSet (string name)
{
var asm = Assembly.GetExecutingAssembly ();
using (var stream = asm.GetManifestResourceStream (name)) {
if (stream == null)
throw new InvalidOperationException (string.Format (
"Cannot find resource file '{0}'.", name));
return GetMetadataSet (stream);
}
}
public static MetadataSet GetMetadataSet (Stream stream)
{
var dr = new ContractReference ();
var doc = (WebServices.Description.ServiceDescription) dr.ReadDocument (stream);
var metadata = new MetadataSet ();
metadata.MetadataSections.Add (
new MetadataSection (MetadataSection.ServiceDescriptionDialect, "", doc));
return metadata;
}
public static CodeCompileUnit Import (MetadataSet metadata, ImportOptions options)
{
var importer = new WsdlImporter (metadata);
var xsdImporter = new XsdDataContractImporter ();
xsdImporter.Options = options;
importer.State.Add (typeof(XsdDataContractImporter), xsdImporter);
var contracts = importer.ImportAllContracts ();
CodeCompileUnit ccu = new CodeCompileUnit ();
var generator = new ServiceContractGenerator (ccu);
if (contracts.Count != 1)
throw new InvalidOperationException (string.Format (
"Metadata import failed: found {0} contracts.", contracts.Count));
var contract = contracts.First ();
generator.GenerateServiceContractType (contract);
return ccu;
}
public static CodeNamespace Find (this CodeNamespaceCollection collection, string name)
{
foreach (CodeNamespace ns in collection) {
if (ns.Name == name)
return ns;
}
return null;
}
public static CodeNamespace FindNamespace (this CodeCompileUnit unit, string name)
{
foreach (CodeNamespace ns in unit.Namespaces) {
if (ns.Name == name)
return ns;
}
return null;
}
public static CodeTypeDeclaration FindType (this CodeNamespace ns, string name)
{
foreach (CodeTypeDeclaration type in ns.Types) {
if (type.Name == name)
return type;
}
return null;
}
public static CodeTypeDeclaration FindType (this CodeCompileUnit unit, string name)
{
foreach (CodeNamespace ns in unit.Namespaces) {
foreach (CodeTypeDeclaration type in ns.Types) {
if (type.Name == name)
return type;
}
}
return null;
}
public static CodeMemberMethod FindMethod (this CodeTypeDeclaration type, string name)
{
foreach (var member in type.Members) {
var method = member as CodeMemberMethod;
if (method == null)
continue;
if (method.Name == name)
return method;
}
return null;
}
public static CodeMemberMethod FindMethod (this CodeCompileUnit unit, string typeName,
string methodName)
{
var type = unit.FindType (typeName);
if (type == null)
return null;
return type.FindMethod (methodName);
}
public static CodeAttributeDeclaration FindAttribute (this CodeTypeDeclaration type, string name)
{
foreach (CodeAttributeDeclaration attr in type.CustomAttributes) {
if (attr.Name == name)
return attr;
}
return null;
}
public static CodeAttributeArgument FindArgument (this CodeAttributeDeclaration attr, string name)
{
foreach (CodeAttributeArgument arg in attr.Arguments) {
if (arg.Name == name)
return arg;
}
return null;
}
}
}
#endif

View File

@@ -0,0 +1,414 @@
//
// XsdDataContractExporterTest.cs
//
// Author:
// Ankit Jain <JAnkit@novell.com>
//
// Copyright (C) 2006 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.
//
#if !MOBILE
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using NUnit.Framework;
using System.Xml.Schema;
using System.Collections;
using System.Xml.Serialization;
using System.Reflection;
using System.Xml;
using QName = System.Xml.XmlQualifiedName;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class XsdDataContractExporterTest
{
internal const string MSSimpleNamespace =
"http://schemas.microsoft.com/2003/10/Serialization/";
internal const string MSArraysNamespace =
"http://schemas.microsoft.com/2003/10/Serialization/Arrays";
internal const string DefaultClrNamespaceBase =
"http://schemas.datacontract.org/2004/07/";
[Test]
public void Ctor1 ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
Assert.IsNotNull (xdce.Schemas);
}
[Test]
public void PrimitiveType ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
Assert.AreEqual (1, xdce.Schemas.Count);
Assert.IsNull (xdce.GetSchemaType (typeof (int)));
Assert.AreEqual (new QName ("int", XmlSchema.Namespace), xdce.GetSchemaTypeName (typeof (int)));
xdce.Export (typeof (int));
Assert.IsNull (xdce.GetSchemaType (typeof (int)));
Assert.AreEqual (new QName ("int", XmlSchema.Namespace), xdce.GetSchemaTypeName (typeof (int)));
}
[Test]
public void CanExportTest ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
Assert.IsTrue (xdce.CanExport (typeof (int)), "#1");
Assert.IsTrue (xdce.CanExport (typeof (dc)), "#2");
//No DataContract/Serializable etc -> changed in 3.5
Assert.IsTrue (xdce.CanExport (this.GetType ()), "#3");
}
[Test]
public void GetSchemaTypeTest ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
Assert.IsNull (xdce.GetSchemaType (typeof (dc)));
Assert.AreEqual (new QName ("_dc", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"), xdce.GetSchemaTypeName (typeof (dc)));
}
[Test]
public void Test2 ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
xdce.Export (typeof (dc));
XmlSchemaSet set = xdce.Schemas;
xdce = new XsdDataContractExporter (set);
try {
xdce.Export (typeof (dc));
} catch (XmlSchemaException xe) {
return;
} catch (Exception e) {
Assert.Fail ("Expected XmlSchemaException, but got " + e.GetType ().ToString ());
}
Assert.Fail ("Expected XmlSchemaException");
}
[Test]
public void EnumTest ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
xdce.Export (typeof (XColors));
CheckEnum (xdce.Schemas, colors_qname, new List<string> (new string [] { "_Red" }));
}
[Test]
public void EnumNoDcTest ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
xdce.Export (typeof (EnumNoDc));
CheckEnum (xdce.Schemas,
new QName ("EnumNoDc",
"http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"),
new List<string> (new string [] { "Red", "Green", "Blue" }));
}
//Test case for class dc
[Test]
public void DcTest ()
{
XsdDataContractExporter xdce = new XsdDataContractExporter ();
xdce.Export (typeof (dc));
CheckDcFull (xdce.Schemas);
}
[Test]
public void Dc3Test ()
{
//Check for duplicate dc2 ?
XsdDataContractExporter xdce = new XsdDataContractExporter ();
xdce.Export (typeof (dc3));
CheckDcFull (xdce.Schemas);
}
[Test]
public void Dc3Test2 ()
{
//Check for duplicate dc2 ?
XsdDataContractExporter xdce = new XsdDataContractExporter ();
xdce.Export (typeof (dc3));
xdce.Export (typeof (dc3));
CheckDcFull (xdce.Schemas);
}
[Test]
public void GetSchemaTypeName ()
{
var xdce = new XsdDataContractExporter ();
// bug #670539
Assert.AreEqual (new XmlQualifiedName ("ArrayOfstring", MSArraysNamespace), xdce.GetSchemaTypeName (typeof (IEnumerable<string>)), "#1");
}
//Helper methods
XmlSchemas GetSchemas (XmlSchemaSet set)
{
XmlSchemas schemas = new XmlSchemas ();
foreach (XmlSchema schema in set.Schemas ())
schemas.Add (schema);
return schemas;
}
void CheckEnum (XmlSchemaSet schemas, QName qname, List<string> values)
{
XmlSchemaSimpleType simple = schemas.GlobalTypes [qname] as XmlSchemaSimpleType;
Assert.IsNotNull (simple, "#ce1");
XmlSchemaSimpleTypeRestriction restriction = simple.Content as XmlSchemaSimpleTypeRestriction;
Assert.IsNotNull (restriction, "#ce2");
Assert.AreEqual (new QName ("string", XmlSchema.Namespace), restriction.BaseTypeName, "#ce3");
//Check the values
Assert.AreEqual (values.Count, restriction.Facets.Count, "#ce4");
values.Sort ();
List<string> facets = new List<string> ();
foreach (XmlSchemaObject obj in restriction.Facets) {
XmlSchemaEnumerationFacet facet = obj as XmlSchemaEnumerationFacet;
Assert.IsNotNull (facet, "#ce5");
facets.Add (facet.Value);
}
facets.Sort ();
for (int i = 0;i < values.Count;i++)
Assert.AreEqual (values [i], facets [i], "#ce6");
//Check the corresponding element
CheckElement (schemas, qname);
}
void CheckElement (XmlSchemaSet schemas, QName qname)
{
XmlSchemaElement element = schemas.GlobalElements [qname] as XmlSchemaElement;
Assert.IsNotNull (element, "#c1");
Assert.IsTrue (element.IsNillable, "#c2");
Assert.AreEqual (qname, element.SchemaTypeName, "#c3");
}
XmlSchemaComplexType GetSchemaComplexType (XmlSchemaSet schemas, QName qname)
{
XmlSchemaComplexType type = schemas.GlobalTypes [qname] as XmlSchemaComplexType;
Assert.IsNotNull (type, "ComplexType " + qname.ToString () + " not found.");
return type;
}
//Check the <element .. > in a sequence
void CheckElementReference (XmlSchemaObject obj, string name, QName schema_type, bool nillable)
{
XmlSchemaElement element = obj as XmlSchemaElement;
Assert.IsNotNull (element, "XmlSchemaElement not found for " + schema_type.ToString ());
Assert.AreEqual (name, element.Name, "#v1, Element name did not match");
//FIXME: Assert.AreEqual (0, element.MinOccurs, "#v0, MinOccurs should be 0 for element '" + name + "'");
Assert.AreEqual (schema_type, element.SchemaTypeName, "#v2, SchemaTypeName for element '" + element.Name + "' did not match.");
Assert.AreEqual (nillable, element.IsNillable, "#v3, Element '" + element.Name + "', schema type = '" + schema_type + "' should have nillable = " + nillable);
}
void CheckArray (XmlSchemaSet schemas, QName qname, QName element_qname)
{
XmlSchemaComplexType type = GetSchemaComplexType (schemas, qname);
XmlSchemaSequence sequence = type.Particle as XmlSchemaSequence;
Assert.IsNotNull (sequence, "#ca1");
Assert.AreEqual (1, sequence.Items.Count, "#ca2, Sequence.Items.Count");
CheckElementReference (
sequence.Items [0],
element_qname.Name,
element_qname,
element_qname.Namespace != XmlSchema.Namespace);
XmlSchemaElement element = (XmlSchemaElement) sequence.Items [0];
Assert.AreEqual ("unbounded", element.MaxOccursString, "#ca3");
CheckElement (schemas, qname);
}
QName colors_qname = new QName ("_XColors", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
QName dc_qname = new QName ("_dc", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
QName other_qname = new QName ("_other", "http://schemas.datacontract.org/2004/07/OtherNs");
void CheckDcFull (XmlSchemaSet schemas)
{
Assert.IsTrue (schemas.IsCompiled, "#dt0, XmlSchemaSet not compiled");
XmlSchemaComplexType type = GetSchemaComplexType (schemas, dc_qname);
XmlSchemaSequence sequence = type.Particle as XmlSchemaSequence;
Assert.IsNotNull (sequence, "#dt1");
Assert.AreEqual (5, sequence.Items.Count, "#dt2, Sequence.Items.Count");
CheckElementReference (sequence.Items [0], "_color",
colors_qname, false);
CheckEnum (schemas, colors_qname, new List<string> (new string [] { "_Red" }));
CheckElementReference (sequence.Items [1], "_foo",
new QName ("string", XmlSchema.Namespace), true);
CheckElementReference (sequence.Items [2], "_o",
new QName ("ArrayOf_other", "http://schemas.datacontract.org/2004/07/OtherNs"), true);
CheckArray (schemas, new QName ("ArrayOf_other", "http://schemas.datacontract.org/2004/07/OtherNs"), other_qname);
CheckElementReference (sequence.Items [3], "_single_o",
new QName ("_other", "http://schemas.datacontract.org/2004/07/OtherNs"), true);
CheckOther (schemas);
CheckElementReference (sequence.Items [4], "i_array",
new QName ("ArrayOfint", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"), true);
CheckArray (schemas, new QName ("ArrayOfint", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"),
new QName ("int", XmlSchema.Namespace));
CheckElement (schemas, dc_qname);
}
void CheckOther (XmlSchemaSet schemas)
{
XmlSchemaComplexType type = GetSchemaComplexType (schemas, other_qname);
XmlSchemaSequence sequence = type.Particle as XmlSchemaSequence;
Assert.IsNotNull (sequence, "#ct0");
Assert.AreEqual (1, sequence.Items.Count, "#ct1");
CheckElementReference (sequence.Items [0], "_field_int", new QName ("int", XmlSchema.Namespace), false);
}
}
[DataContract (Name = "_XColors")]
public enum XColors
{
[EnumMember (Value = "_Red")]
Red,
Green,
Blue
}
public enum EnumNoDc
{
Red,
Green,
Blue
}
[DataContract (Name = "_dc")]
public class dc
{
[DataMember (Name = "_foo")]
public string foo;
int not_used;
[DataMember (Name = "_color")]
XColors color;
//[DataMember]
public dc me;
[DataMember (Name = "_o")]
public OtherNs.other [] o;
[DataMember (Name = "_single_o")]
public OtherNs.other single_o;
[DataMember]
public int [] i_array;
}
[DataContract (Name = "_dc2")]
public class dc2 : dc
{
[DataMember (Name = "_foo2")]
string foo2;
}
[DataContract]
public abstract class abstract_class
{
[DataMember]
public string foo;
}
[Serializable]
public class base_xs
{
public int base_int;
private string base_string;
}
[Serializable]
public class xs : base_xs
{
private string ignore;
public string useme;
}
[DataContract]
public class dc_with_basexs : base_xs
{
[DataMember (Name = "_foo")]
public string foo;
}
[XmlRoot]
public class xa
{
[XmlElement]
public string foo;
[XmlAttribute]
public int bar;
}
[DataContract (Name = "_dc3")]
public class dc3
{
[DataMember (Name = "_first")]
dc2 first;
[DataMember (Name = "_second")]
dc2 second;
}
}
namespace OtherNs
{
[DataContract (Name = "_other")]
public class other /*: MonoTests.System.Runtime.Serialization.dc*/
{
[DataMember (Name = "_field_int")]
public int field_int;
}
}
#endif

View File

@@ -0,0 +1,176 @@
//
// XsdDataContractExporterTest2.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// 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.
#if !MOBILE
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Web.Services.Discovery;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Microsoft.CSharp;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using NUnit.Framework.SyntaxHelpers;
using QName = System.Xml.XmlQualifiedName;
namespace MonoTests.System.Runtime.Serialization
{
[TestFixture]
public class XsdDataContractExporterTest2
{
internal const string MSArraysNamespace =
"http://schemas.microsoft.com/2003/10/Serialization/Arrays";
[Test]
public void ExportList ()
{
var exporter = new XsdDataContractExporter ();
Assert.That (exporter.CanExport (typeof(MyService)), Is.True, "#1");
exporter.Export (typeof(MyService));
var typeName = exporter.GetSchemaTypeName (typeof(MyService));
var type = exporter.Schemas.GlobalTypes [typeName];
Assert.That (type, Is.Not.Null, "#2");
Assert.That (type, Is.InstanceOfType (typeof (XmlSchemaComplexType)), "#3");
var complex = (XmlSchemaComplexType)type;
Assert.That (complex.Annotation, Is.Null, "#4");
var sequence = complex.Particle as XmlSchemaSequence;
Assert.That (sequence, Is.Not.Null, "#5");
Assert.That (sequence.Items.Count, Is.EqualTo (3), "#5a");
Assert.That (sequence.Annotation, Is.Null, "#5b");
Assert.That (sequence.MinOccursString, Is.Null, "#5c");
Assert.That (sequence.MaxOccursString, Is.Null, "#5d");
var list = GetElement (sequence, "list");
Assert.That (list, Is.Not.Null, "#6");
Assert.That (list.Annotation, Is.Null, "#6a");
Assert.That (list.Name, Is.EqualTo ("list"), "#6b");
Assert.That (list.ElementSchemaType, Is.InstanceOfType (typeof (XmlSchemaComplexType)), "#6c");
var listElement = (XmlSchemaComplexType)list.ElementSchemaType;
Assert.That (listElement.QualifiedName.Namespace, Is.EqualTo (MSArraysNamespace), "#6d");
Assert.That (listElement.QualifiedName.Name, Is.EqualTo ("ArrayOfint"), "#6e");
Assert.That (listElement.Particle, Is.InstanceOfType (typeof(XmlSchemaSequence)), "#7");
var listSeq = (XmlSchemaSequence)listElement.Particle;
Assert.That (listSeq.Items.Count, Is.EqualTo (1), "#7b");
Assert.That (listSeq.Items[0], Is.InstanceOfType (typeof(XmlSchemaElement)), "#7c");
Assert.That (listSeq.Annotation, Is.Null, "#7d");
var listSeqElement = (XmlSchemaElement)listSeq.Items[0];
Assert.That (listSeqElement.MaxOccursString, Is.EqualTo ("unbounded"), "#7e");
Assert.That (listSeqElement.MinOccursString, Is.EqualTo ("0"), "#7f");
var dict = GetElement (sequence, "dictionary");
Assert.That (dict, Is.Not.Null, "#8");
Assert.That (dict.Annotation, Is.Null, "#8a");
Assert.That (dict.Name, Is.EqualTo ("dictionary"), "#8b");
Assert.That (dict.ElementSchemaType, Is.InstanceOfType (typeof (XmlSchemaComplexType)), "#8c");
var dictElement = (XmlSchemaComplexType)dict.ElementSchemaType;
Assert.That (dictElement.QualifiedName.Namespace, Is.EqualTo (MSArraysNamespace), "#8d");
Assert.That (dictElement.QualifiedName.Name, Is.EqualTo ("ArrayOfKeyValueOfstringdouble"), "#8e");
Assert.That (dictElement.Particle, Is.InstanceOfType (typeof(XmlSchemaSequence)), "#9");
var dictSeq = (XmlSchemaSequence)dictElement.Particle;
Assert.That (dictSeq.Items.Count, Is.EqualTo (1), "#9b");
Assert.That (dictSeq.Items[0], Is.InstanceOfType (typeof(XmlSchemaElement)), "#9c");
Assert.That (dictSeq.Annotation, Is.Null, "#9d");
var dictSeqElement = (XmlSchemaElement)dictSeq.Items[0];
Assert.That (listSeqElement.MaxOccursString, Is.EqualTo ("unbounded"), "#9e");
Assert.That (listSeqElement.MinOccursString, Is.EqualTo ("0"), "#9f");
var custom = GetElement (sequence, "customCollection");
Assert.That (custom, Is.Not.Null, "#10");
Assert.That (custom.Annotation, Is.Null, "#10a");
Assert.That (custom.Name, Is.EqualTo ("customCollection"), "#10b");
Assert.That (custom.ElementSchemaType, Is.InstanceOfType (typeof (XmlSchemaComplexType)), "#10c");
var customElement = (XmlSchemaComplexType)custom.ElementSchemaType;
var customEQN = customElement.QualifiedName;
Assert.That (customEQN.Namespace, Is.EqualTo (typeName.Namespace), "#10d");
Assert.That (customEQN.Name.StartsWith ("XsdDataContractExporterTest2.MyCollectionOfstring", StringComparison.InvariantCultureIgnoreCase),
Is.True, "#10e");
Assert.That (customElement.Particle, Is.InstanceOfType (typeof(XmlSchemaSequence)), "#11");
var customSeq = (XmlSchemaSequence)customElement.Particle;
Assert.That (customSeq.Items.Count, Is.EqualTo (1), "#11b");
Assert.That (customSeq.Items[0], Is.InstanceOfType (typeof(XmlSchemaElement)), "#11c");
Assert.That (customSeq.Annotation, Is.Null, "#11d");
var customSeqElement = (XmlSchemaElement)customSeq.Items[0];
Assert.That (customSeqElement.MaxOccursString, Is.EqualTo ("unbounded"), "#11e");
Assert.That (customSeqElement.MinOccursString, Is.EqualTo ("0"), "#11f");
}
static XmlSchemaElement GetElement (XmlSchemaSequence sequence, string name)
{
foreach (XmlSchemaElement item in sequence.Items) {
if (item.Name.Equals (name))
return item;
}
return null;
}
[ServiceContract]
public class MyService
{
[DataMember]
public List<int> list;
[DataMember]
public Dictionary<string,double> dictionary;
[DataMember]
public MyCollection<string> customCollection;
}
[CollectionDataContract]
public class MyCollection<T> : List<T>
{
}
}
}
#endif

Some files were not shown because too many files have changed in this diff Show More