-Added type descriptor objects to support JObject property databinding

-Added OnErrorAttribute and ErrorContext for handling serialization errors
This commit is contained in:
JamesNK
2009-08-22 12:01:24 +00:00
parent 5167415f47
commit 95caaf9dc1
37 changed files with 1707 additions and 82 deletions
@@ -512,6 +512,17 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(@"<myRoot><available_sizes><available_sizes><available_sizes>113</available_sizes><available_sizes>150</available_sizes></available_sizes><available_sizes>assets/images/resized/0001/1070/11070v1-max-150x150.jpg</available_sizes></available_sizes><available_sizes><available_sizes><available_sizes>189</available_sizes><available_sizes>250</available_sizes></available_sizes><available_sizes>assets/images/resized/0001/1070/11070v1-max-250x250.jpg</available_sizes></available_sizes><available_sizes><available_sizes><available_sizes>341</available_sizes><available_sizes>450</available_sizes></available_sizes><available_sizes>assets/images/resized/0001/1070/11070v1-max-450x450.jpg</available_sizes></available_sizes></myRoot>", newDoc.InnerXml);
}
[Test]
public void Encoding()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<name>O""Connor</name>"); // i use "" so it will be easier to see the problem
string json = JsonConvert.SerializeXmlNode(doc);
Assert.AreEqual(@"{""name"":""O\""Connor""}", json);
}
}
}
#endif
@@ -0,0 +1,79 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
#if !PocketPC && !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Web.UI;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Linq.ComponentModel
{
public class BindingTests : TestFixtureBase
{
[Test]
public void DataBinderEval()
{
JObject o = new JObject(
new JProperty("First", "String!"),
new JProperty("Second", 12345.6789m),
new JProperty("Third", new JArray(
1,
2,
3,
4,
5,
new JObject(
new JProperty("Fourth", "String!"),
new JProperty("Fifth", new JObject(
new JProperty("Sixth", "String!")))))));
object value;
value = DataBinder.Eval(o, "First");
Assert.AreEqual(value, (string)o["First"]);
value = DataBinder.Eval(o, "Second");
Assert.AreEqual(value, (decimal)o["Second"]);
value = DataBinder.Eval(o, "Third");
Assert.AreEqual(value, o["Third"]);
value = DataBinder.Eval(o, "Third[0]");
// urg!
Assert.AreEqual((int)(JToken)value, (int)o["Third"][0]);
value = DataBinder.Eval(o, "Third[5].Fourth");
Assert.AreEqual(value, (string)o["Third"][5]["Fourth"]);
value = DataBinder.Eval(o, "Third[5].Fifth.Sixth");
Assert.AreEqual(value, (string)o["Third"][5]["Fifth"]["Sixth"]);
}
}
}
#endif
@@ -0,0 +1,91 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
#if !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Linq.ComponentModel;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Linq.ComponentModel
{
public class JPropertyDescriptorTests : TestFixtureBase
{
[Test]
public void GetValue()
{
JObject o = JObject.Parse("{prop1:'12345!',prop2:[1,'two','III']}");
JPropertyDescriptor prop1 = new JPropertyDescriptor("prop1", typeof(string));
JPropertyDescriptor prop2 = new JPropertyDescriptor("prop2", typeof(JArray));
Assert.AreEqual("12345!", prop1.GetValue(o));
Assert.AreEqual(o["prop2"], prop2.GetValue(o));
}
[Test]
public void SetValue()
{
JObject o = JObject.Parse("{prop1:'12345!'}");
JPropertyDescriptor propertyDescriptor1 = new JPropertyDescriptor("prop1", typeof(string));
propertyDescriptor1.SetValue(o, "54321!");
Assert.AreEqual("54321!", (string)o["prop1"]);
}
[Test]
public void ResetValue()
{
JObject o = JObject.Parse("{prop1:'12345!'}");
JPropertyDescriptor propertyDescriptor1 = new JPropertyDescriptor("prop1", typeof(string));
propertyDescriptor1.ResetValue(o);
Assert.AreEqual("12345!", (string)o["prop1"]);
}
[Test]
public void IsReadOnly()
{
JPropertyDescriptor propertyDescriptor1 = new JPropertyDescriptor("prop1", typeof(string));
Assert.AreEqual(false, propertyDescriptor1.IsReadOnly);
}
[Test]
public void PropertyType()
{
JPropertyDescriptor propertyDescriptor1 = new JPropertyDescriptor("prop1", typeof(string));
Assert.AreEqual(typeof(string), propertyDescriptor1.PropertyType);
}
}
}
#endif
@@ -0,0 +1,49 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
#if !PocketPC && !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
using Newtonsoft.Json.Linq.ComponentModel;
namespace Newtonsoft.Json.Tests.Linq.ComponentModel
{
public class JTypeDescriptionProviderTests : TestFixtureBase
{
[Test]
public void GetTypeDescriptor()
{
JTypeDescriptionProvider provider = new JTypeDescriptionProvider();
JTypeDescriptor descriptor = (JTypeDescriptor)provider.GetTypeDescriptor(typeof (JObject), new JObject());
Assert.IsNotNull(descriptor);
}
}
}
#endif
@@ -0,0 +1,80 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
#if !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq.ComponentModel;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
namespace Newtonsoft.Json.Tests.Linq.ComponentModel
{
public class JTypeDescriptorTests : TestFixtureBase
{
[Test]
public void GetProperties()
{
JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}");
JTypeDescriptor descriptor = new JTypeDescriptor(o);
PropertyDescriptorCollection properties = descriptor.GetProperties();
Assert.AreEqual(4, properties.Count);
PropertyDescriptor prop1 = properties[0];
Assert.AreEqual("prop1", prop1.Name);
Assert.AreEqual(typeof(long), prop1.PropertyType);
Assert.AreEqual(typeof(JObject), prop1.ComponentType);
Assert.AreEqual(false, prop1.CanResetValue(o));
Assert.AreEqual(false, prop1.ShouldSerializeValue(o));
PropertyDescriptor prop2 = properties[1];
Assert.AreEqual("prop2", prop2.Name);
Assert.AreEqual(typeof(string), prop2.PropertyType);
Assert.AreEqual(typeof(JObject), prop2.ComponentType);
Assert.AreEqual(false, prop2.CanResetValue(o));
Assert.AreEqual(false, prop2.ShouldSerializeValue(o));
PropertyDescriptor prop3 = properties[2];
Assert.AreEqual("prop3", prop3.Name);
Assert.AreEqual(typeof(object), prop3.PropertyType);
Assert.AreEqual(typeof(JObject), prop3.ComponentType);
Assert.AreEqual(false, prop3.CanResetValue(o));
Assert.AreEqual(false, prop3.ShouldSerializeValue(o));
PropertyDescriptor prop4 = properties[3];
Assert.AreEqual("prop4", prop4.Name);
Assert.AreEqual(typeof(JArray), prop4.PropertyType);
Assert.AreEqual(typeof(JObject), prop4.ComponentType);
Assert.AreEqual(false, prop4.CanResetValue(o));
Assert.AreEqual(false, prop4.ShouldSerializeValue(o));
}
}
}
#endif
@@ -7,6 +7,9 @@ using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.IO;
#if !PocketPC && !SILVERLIGHT
using System.Web.UI;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
@@ -556,5 +559,107 @@ Parameter name: arrayIndex")]
// "JobTitle": "Manager"
//}
}
#if !PocketPC && !SILVERLIGHT
[Test]
public void PropertyChanging()
{
object changing = null;
object changed = null;
int changingCount = 0;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanging += (sender, args) =>
{
JObject s = (JObject) sender;
changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changingCount++;
};
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual(null, changing);
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value1", changing);
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changingCount);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual("value2", changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changingCount);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
}
#endif
[Test]
public void PropertyChanged()
{
object changed = null;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changedCount);
}
}
}
@@ -61,6 +61,10 @@
<ItemGroup>
<Compile Include="Converters\BinaryConverterTests.cs" />
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Linq\ComponentModel\BindingTests.cs" />
<Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptionProviderTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptorTests.cs" />
<Compile Include="Linq\JTokenReaderTest.cs" />
<Compile Include="Linq\JTokenWriterTest.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
@@ -69,6 +73,7 @@
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\EntitiesSerializationTests.cs" />
<Compile Include="Serialization\JsonSerializerTest.cs" />
<Compile Include="Serialization\PopulateTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
@@ -132,7 +137,6 @@
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="JsonSerializerTest.cs" />
<Compile Include="JsonTextReaderTest.cs" />
<Compile Include="JsonTextWriterTest.cs" />
<Compile Include="Linq\JArrayTests.cs" />
@@ -68,7 +68,12 @@
<Compile Include="JsonArrayAttributeTests.cs" />
<Compile Include="ExceptionTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Linq\ComponentModel\BindingTests.cs" />
<Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptionProviderTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptorTests.cs" />
<Compile Include="Serialization\EntitiesSerializationTests.cs" />
<Compile Include="Serialization\JsonSerializerTest.cs" />
<Compile Include="Serialization\PopulateTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
@@ -136,7 +141,6 @@
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="JsonSerializerTest.cs" />
<Compile Include="JsonTextReaderTest.cs" />
<Compile Include="JsonTextWriterTest.cs" />
<Compile Include="Linq\JTokenReaderTest.cs" />
@@ -67,6 +67,10 @@
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="ExceptionTests.cs" />
<Compile Include="JsonArrayAttributeTests.cs" />
<Compile Include="Linq\ComponentModel\BindingTests.cs" />
<Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptionProviderTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptorTests.cs" />
<Compile Include="Linq\JTokenReaderTest.cs" />
<Compile Include="Linq\JTokenWriterTest.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
@@ -75,6 +79,7 @@
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\EntitiesSerializationTests.cs" />
<Compile Include="Serialization\JsonSerializerTest.cs" />
<Compile Include="Serialization\PopulateTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
@@ -138,7 +143,6 @@
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="JsonSerializerTest.cs" />
<Compile Include="JsonTextReaderTest.cs" />
<Compile Include="JsonTextWriterTest.cs" />
<Compile Include="Linq\JArrayTests.cs" />
@@ -105,6 +105,10 @@
</Compile>
<Compile Include="LinqToSql\LinqToSqlClassesSerializationTests.cs" />
<Compile Include="LinqToSql\Person.cs" />
<Compile Include="Linq\ComponentModel\BindingTests.cs" />
<Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptionProviderTests.cs" />
<Compile Include="Linq\ComponentModel\JTypeDescriptorTests.cs" />
<Compile Include="Serialization\EntitiesSerializationTests.cs" />
<Compile Include="Serialization\PopulateTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
@@ -173,7 +177,7 @@
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="JsonSerializerTest.cs" />
<Compile Include="Serialization\JsonSerializerTest.cs" />
<Compile Include="JsonTextReaderTest.cs" />
<Compile Include="JsonTextWriterTest.cs" />
<Compile Include="Linq\JTokenReaderTest.cs" />
@@ -46,7 +46,7 @@ using Newtonsoft.Json.Tests.TestObjects;
using System.Runtime.Serialization;
using System.Globalization;
namespace Newtonsoft.Json.Tests
namespace Newtonsoft.Json.Tests.Serialization
{
public class JsonSerializerTest : TestFixtureBase
{
@@ -1291,7 +1291,7 @@ keyword such as type of business.""
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.JsonSerializerTest+ICo. Type is an interface or abstract class and cannot be instantated.")]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ICo. Type is an interface or abstract class and cannot be instantated.")]
public void DeserializeInterfaceProperty()
{
Test testClass = new Test();
@@ -2049,5 +2049,158 @@ keyword such as type of business.""
NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
Assert.AreEqual(null, c.DateTimeField);
}
/// <summary>
/// What types of events are there? Just sticking to a basic set of four for now.
/// </summary>
/// <remarks></remarks>
public enum EventType
{
Debug = 0,
Info = 1,
Warning = 2,
Error = 3
}
public sealed class Event
{
/// <summary>
/// If no current user is specified, returns Nothing (0 from VB)
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
private static int GetCurrentUserId()
{
return 0;
}
/// <summary>
/// Gets either the application path or the current stack trace.
/// NOTE: You MUST call this from the top level entry point. Otherwise,
/// the stack trace will be buried in Logger itself.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
private static string GetCurrentSubLocation()
{
return "";
}
private string _sublocation;
private int _userId;
private EventType _type;
private string _summary;
private string _details;
private string _stackTrace;
private string _tag;
private DateTime _time;
public Event(string summary)
{
_summary = summary;
_time = DateTime.Now;
if (_userId == 0) _userId = GetCurrentUserId();
//This call only works at top level for now.
//If _stackTrace = Nothing Then _stackTrace = Environment.StackTrace
if (_sublocation == null) _sublocation = GetCurrentSubLocation();
}
public Event(string sublocation, int userId, EventType type, string summary, string details, string stackTrace, string tag)
{
_sublocation = sublocation;
_userId = userId;
_type = type;
_summary = summary;
_details = details;
_stackTrace = stackTrace;
_tag = tag;
_time = DateTime.Now;
if (_userId == 0) _userId = GetCurrentUserId();
//If _stackTrace = Nothing Then _stackTrace = Environment.StackTrace
if (_sublocation == null) _sublocation = GetCurrentSubLocation();
}
public override string ToString()
{
return string.Format("{{ sublocation = {0}, userId = {1}, type = {2}, summary = {3}, details = {4}, stackTrace = {5}, tag = {6} }}", _sublocation, _userId, _type, _summary, _details, _stackTrace, _tag);
}
public string sublocation
{
get { return _sublocation; }
set { _sublocation = value; }
}
public int userId
{
get { return _userId; }
set { _userId = value; }
}
public EventType type
{
get { return _type; }
set { _type = value; }
}
public string summary
{
get { return _summary; }
set { _summary = value; }
}
public string details
{
get { return _details; }
set { _details = value; }
}
public string stackTrace
{
get { return _stackTrace; }
set { _stackTrace = value; }
}
public string tag
{
get { return _tag; }
set { _tag = value; }
}
public DateTime time
{
get { return _time; }
}
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unable to determine which constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+Event. A class with no default constructor should have only one constructor with arguments.")]
public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments()
{
string json = @"{""sublocation"":""AlertEmailSender.Program.Main"",""userId"":0,""type"":0,""summary"":""Loading settings variables"",""details"":null,""stackTrace"":"" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at mr.Logging.Event..ctor(String summary) in C:\\Projects\\MRUtils\\Logging\\Event.vb:line 71\r\n at AlertEmailSender.Program.Main(String[] args) in C:\\Projects\\AlertEmailSender\\AlertEmailSender\\Program.cs:line 25"",""tag"":null,""time"":""\/Date(1249591032026-0400)\/""}";
Event e = JsonConvert.DeserializeObject<Event>(json);
}
public class SetOnlyPropertyClass2
{
private object _value;
public object SetOnlyProperty
{
set { _value = value; }
}
public object GetValue()
{
return _value;
}
}
[Test]
public void DeserializeObjectSetOnlyProperty()
{
string json = @"{'SetOnlyProperty':[1,2,3,4,5]}";
SetOnlyPropertyClass2 setOnly = JsonConvert.DeserializeObject<SetOnlyPropertyClass2>(json);
JArray a = (JArray)setOnly.GetValue();
Assert.AreEqual(5, a.Count);
Assert.AreEqual(1, (int)a[0]);
Assert.AreEqual(5, (int)a[a.Count - 1]);
}
}
}
@@ -1,4 +1,29 @@
using System;
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -15,8 +40,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
Person p = new Person();
JsonSerializer serializer = new JsonSerializer();
serializer.Populate(new StringReader(@"{""Name"":""James""}"), p);
JsonConvert.PopulateObject(@"{""Name"":""James""}", p);
Assert.AreEqual("James", p.Name);
}
@@ -71,9 +95,10 @@ namespace Newtonsoft.Json.Tests.Serialization
]
}";
JsonSerializer serializer = new JsonSerializer();
serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
serializer.Populate(new StringReader(json), s);
JsonConvert.PopulateObject(json, s, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});
Assert.AreEqual(1, s.Mottos.Count);
Assert.AreEqual("Fail whale", s.Mottos[0]);
@@ -26,13 +26,18 @@
#if !PocketPC && !SILVERLIGHT && !NET20
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using System.Collections;
namespace Newtonsoft.Json.Tests.Serialization
{
@@ -47,6 +52,7 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual("Hello World!", obj.Member2);
Assert.AreEqual("This is a nonserialized value", obj.Member3);
Assert.AreEqual(null, obj.Member4);
Assert.AreEqual(null, obj.Member5);
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.AreEqual(@"{
@@ -59,13 +65,22 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual("This value was reset after serialization.", obj.Member2);
Assert.AreEqual("This is a nonserialized value", obj.Member3);
Assert.AreEqual(null, obj.Member4);
Assert.AreEqual("Error message for member Member6 = Exception has been thrown by the target of an invocation.", obj.Member5);
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
JObject o = JObject.Parse(@"{
""Member1"": 11,
""Member2"": ""This value went into the data file during serialization."",
""Member4"": null
}");
o["Member6"] = "Dummy text for error";
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(o.ToString());
Assert.AreEqual(11, obj.Member1);
Assert.AreEqual("This value went into the data file during serialization.", obj.Member2);
Assert.AreEqual("This value was set during deserialization", obj.Member3);
Assert.AreEqual("This value was set after deserialization.", obj.Member4);
Assert.AreEqual("Error message for member Member6 = Exception has been thrown by the target of an invocation.", obj.Member5);
}
[Test]
@@ -98,6 +113,136 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual("This value was set after deserialization.", obj.Member4);
}
public class ListErrorObject
{
public string Member
{
get { throw new Exception("ListErrorObject.Member get error!"); }
set { throw new Exception("ListErrorObject.Member set error!"); }
}
}
public class ListErrorObjectCollection : Collection<ListErrorObject>
{
[OnError]
internal void OnErrorMethod(StreamingContext context, ErrorContext errorContext)
{
errorContext.Handled = true;
}
}
public class VersionKeyedCollection : KeyedCollection<string, Person>, IList
{
public List<string> Messages { get; set; }
public VersionKeyedCollection()
{
Messages = new List<string>();
}
protected override string GetKeyForItem(Person item)
{
return item.Name;
}
[OnError]
internal void OnErrorMethod(StreamingContext context, ErrorContext errorContext)
{
Messages.Add("Error message for member " + errorContext.Member + " = " + errorContext.Error.Message);
errorContext.Handled = true;
}
object IList.this[int index]
{
get
{
if (index % 2 == 0)
throw new Exception("Index even: " + index);
return this[index];
}
set { this[index] = (Person)value; }
}
}
[Test]
public void ErrorDeserializingListHandled()
{
string json = @"[
{
""Name"": ""Jim"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
},
{
""Name"": ""Jim"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
}
]";
VersionKeyedCollection c = JsonConvert.DeserializeObject<VersionKeyedCollection>(json);
Assert.AreEqual(1, c.Count);
Assert.AreEqual(1, c.Messages.Count);
Assert.AreEqual("Error message for member 1 = An item with the same key has already been added.", c.Messages[0]);
}
[Test]
public void ErrorSerializingListHandled()
{
VersionKeyedCollection c = new VersionKeyedCollection();
c.Add(new Person
{
Name = "Jim",
BirthDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
LastModified = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc)
});
c.Add(new Person
{
Name = "Jimbo",
BirthDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
LastModified = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc)
});
c.Add(new Person
{
Name = "Jimmy",
BirthDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
LastModified = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc)
});
c.Add(new Person
{
Name = "Jim Bean",
BirthDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
LastModified = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc)
});
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"[
{
""Name"": ""Jimbo"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
},
{
""Name"": ""Jim Bean"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
}
]", json);
Assert.AreEqual(2, c.Messages.Count);
Assert.AreEqual("Error message for member 0 = Index even: 0", c.Messages[0]);
Assert.AreEqual("Error message for member 2 = Index even: 2", c.Messages[1]);
}
[Test]
[ExpectedException(typeof(TargetInvocationException))]
public void ErrorInChild()
{
JsonConvert.DeserializeObject<ListErrorObjectCollection>(@"[{""Member"":""Value""}]");
}
[Test]
public void ListEvents()
{
@@ -187,6 +332,8 @@ namespace Newtonsoft.Json.Tests.Serialization
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
Console.WriteLine(obj.Member5);
// null
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
// {
@@ -203,6 +350,8 @@ namespace Newtonsoft.Json.Tests.Serialization
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
Console.WriteLine(obj.Member5);
// Error message for member Member6 = Exception has been thrown by the target of an invocation.
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
@@ -26,6 +26,7 @@
#if !PocketPC && !SILVERLIGHT
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json.Tests.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
@@ -23,11 +23,12 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !SILVERLIGHT
#if !PocketPC && !SILVERLIGHT && !NET20
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
@@ -48,6 +49,17 @@ namespace Newtonsoft.Json.Tests.TestObjects
// This field is set to null, but populated after deserialization.
public string Member4 { get; set; }
// This field is set to null, but populated after error.
[JsonIgnore]
public string Member5 { get; set; }
// Getting or setting this field will throw an error.
public string Member6
{
get { throw new Exception("Member5 get error!"); }
set { throw new Exception("Member5 set error!"); }
}
public SerializationEventTestObject()
{
Member1 = 11;
@@ -79,6 +91,13 @@ namespace Newtonsoft.Json.Tests.TestObjects
{
Member4 = "This value was set after deserialization.";
}
[OnError]
internal void OnErrorMethod(StreamingContext context, ErrorContext errorContext)
{
Member5 = "Error message for member " + errorContext.Member + " = " + errorContext.Error.Message;
errorContext.Handled = true;
}
}
}
#endif
@@ -24,7 +24,9 @@
#endregion
#if !PocketPC && !SILVERLIGHT
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{