From 5800e97ff36d3dacea20ec75e80ebfa5f76100cd Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 15 Mar 2012 18:34:51 +1300 Subject: [PATCH] -Added Newtonsoft.Json.Metro build (whew, what a pain!) -Added .gitignore file --- .gitignore | 5 + Src/Newtonsoft.Json.Metro.sln | 64 +++ .../Bson/BsonReaderTests.cs | 64 ++- .../Bson/BsonWriterTests.cs | 86 +-- .../Converters/BinaryConverterTests.cs | 19 +- .../CustomCreationConverterTests.cs | 7 + .../Converters/DataSetConverterTests.cs | 8 +- .../Converters/DataTableConverterTests.cs | 10 +- .../Converters/ExpandoObjectConverterTests.cs | 27 +- .../Converters/IsoDateTimeConverterTests.cs | 18 +- .../JavaScriptDateTimeConverterTests.cs | 16 +- .../Converters/ObjectIdConverterTests.cs | 11 +- .../Converters/RegexConverterTests.cs | 11 +- .../Converters/StringEnumConverterTests.cs | 20 +- .../Converters/VersionConverterTests.cs | 7 + .../Converters/XmlNodeConverterTest.cs | 9 +- Src/Newtonsoft.Json.Tests/ExceptionTests.cs | 7 + .../Images/UnitTestLogo.png | Bin 0 -> 5789 bytes .../Images/UnitTestSmallLogo.png | Bin 0 -> 745 bytes .../Images/UnitTestSplashScreen.png | Bin 0 -> 9381 bytes .../Images/UnitTestStoreLogo.png | Bin 0 -> 2005 bytes .../JsonArrayAttributeTests.cs | 7 + Src/Newtonsoft.Json.Tests/JsonConvertTest.cs | 35 +- .../JsonTextReaderTest.cs | 237 ++++++-- .../JsonTextWriterTest.cs | 25 +- .../JsonValidatingReaderTests.cs | 50 +- .../Linq/ComponentModel/BindingTests.cs | 3 +- .../JPropertyDescriptorTests.cs | 3 +- .../Linq/DynamicTests.cs | 137 +++-- Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs | 93 ++- .../Linq/JConstructorTests.cs | 16 +- .../Linq/JObjectTests.cs | 289 ++++++---- Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs | 69 ++- .../Linq/JPropertyTests.cs | 33 +- Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs | 9 +- .../Linq/JTokenEqualityComparerTests.cs | 7 + .../Linq/JTokenReaderTest.cs | 82 ++- Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs | 33 +- .../Linq/JTokenWriterTest.cs | 9 +- Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs | 82 ++- .../Linq/LinqToJsonTest.cs | 48 +- .../Newtonsoft.Json.Tests.Metro.csproj | 320 +++++++++++ ...wtonsoft.Json.Tests.Metro_TemporaryKey.pfx | Bin 0 -> 2460 bytes .../Package.appxmanifest | 54 ++ Src/Newtonsoft.Json.Tests/PerformanceTests.cs | 11 +- .../Properties/AssemblyInfo.cs | 2 +- .../Schema/ExtensionsTests.cs | 97 ++-- .../Schema/JsonSchemaBuilderTests.cs | 18 +- .../Schema/JsonSchemaGeneratorTests.cs | 22 +- .../Schema/JsonSchemaModelBuilderTests.cs | 7 + .../Schema/JsonSchemaNodeTests.cs | 7 + .../Schema/JsonSchemaTests.cs | 7 + ...lCasePropertyNamesContractResolverTests.cs | 9 + .../Serialization/ConstructorHandlingTests.cs | 17 +- .../Serialization/ContractResolverTests.cs | 20 + .../DefaultValueHandlingTests.cs | 7 + .../Serialization/DynamicTests.cs | 32 +- .../EntitiesSerializationTests.cs | 9 +- .../JsonPropertyCollectionTests.cs | 7 + .../Serialization/JsonSerializerTest.cs | 382 +++++++++---- .../MissingMemberHandlingTests.cs | 19 +- .../Serialization/NullValueHandlingTests.cs | 7 + .../Serialization/PopulateTests.cs | 14 +- .../PreserveReferencesHandlingTests.cs | 20 +- .../SerializationErrorHandlingTests.cs | 7 + .../SerializationEventAttributeTests.cs | 10 +- .../Serialization/TypeNameHandlingTests.cs | 56 +- Src/Newtonsoft.Json.Tests/SilverlightTests.cs | 6 + Src/Newtonsoft.Json.Tests/TestFixtureBase.cs | 72 ++- .../TestObjects/ConverableMembers.cs | 2 + .../DefaultValueAttributeTestClass.cs | 2 +- .../TestObjects/ListOfIds.cs | 1 + .../TestObjects/Person.cs | 2 +- .../TestObjects/SerializationEventTestList.cs | 1 - .../TestObjects/TypedSubHashtable.cs | 2 +- .../DynamicReflectionDelegateFactoryTests.cs | 63 +- .../Utilities/ReflectionUtilsTests.cs | 7 + Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs | 4 + Src/Newtonsoft.Json/Bson/BsonReader.cs | 4 + Src/Newtonsoft.Json/Bson/BsonWriter.cs | 8 +- .../Converters/BinaryConverter.cs | 10 +- .../Converters/CustomCreationConverter.cs | 1 + .../Converters/DataSetConverter.cs | 2 +- .../Converters/DataTableConverter.cs | 2 +- .../Converters/EntityKeyMemberConverter.cs | 2 +- .../Converters/KeyValuePairConverter.cs | 2 +- .../Converters/StringEnumConverter.cs | 2 +- .../Converters/XmlNodeConverter.cs | 14 +- Src/Newtonsoft.Json/FormatterAssemblyStyle.cs | 2 +- Src/Newtonsoft.Json/JsonConvert.cs | 19 +- Src/Newtonsoft.Json/JsonReader.cs | 4 +- Src/Newtonsoft.Json/JsonReaderException.cs | 4 +- .../JsonSerializationException.cs | 4 +- Src/Newtonsoft.Json/JsonTextReader.cs | 4 + Src/Newtonsoft.Json/JsonTextWriter.cs | 4 + Src/Newtonsoft.Json/JsonWriter.cs | 7 +- Src/Newtonsoft.Json/JsonWriterException.cs | 4 +- Src/Newtonsoft.Json/Linq/JContainer.cs | 20 +- Src/Newtonsoft.Json/Linq/JObject.cs | 16 +- .../Linq/JPropertyDescriptor.cs | 2 +- Src/Newtonsoft.Json/Linq/JToken.cs | 4 +- Src/Newtonsoft.Json/Linq/JTokenWriter.cs | 8 +- Src/Newtonsoft.Json/Linq/JValue.cs | 2 + .../Newtonsoft.Json.Metro.csproj | 282 +++++++++ .../Newtonsoft.Json.Net20.csproj | 1 + .../Newtonsoft.Json.Net35.csproj | 1 + .../Newtonsoft.Json.Silverlight.csproj | 1 + .../Newtonsoft.Json.WindowsPhone.csproj | 1 + Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 1 + .../Properties/AssemblyInfo.cs | 2 +- .../Schema/JsonSchemaException.cs | 4 +- .../Schema/JsonSchemaGenerator.cs | 18 +- .../Serialization/CachedAttributeGetter.cs | 3 + .../Serialization/DefaultContractResolver.cs | 69 ++- .../DefaultSerializationBinder.cs | 9 +- .../Serialization/JsonArrayContract.cs | 4 +- .../Serialization/JsonContract.cs | 7 +- .../Serialization/JsonDictionaryContract.cs | 6 +- .../Serialization/JsonFormatterConverter.cs | 2 +- .../JsonISerializableContract.cs | 2 +- .../JsonSerializerInternalBase.cs | 2 +- .../JsonSerializerInternalReader.cs | 18 +- .../JsonSerializerInternalWriter.cs | 20 +- .../Serialization/JsonTypeReflector.cs | 80 ++- .../LateBoundMetadataTypeAttribute.cs | 2 +- Src/Newtonsoft.Json/SerializationBinder.cs | 2 +- .../Utilities/CollectionUtils.cs | 4 + .../Utilities/CollectionWrapper.cs | 2 +- Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 202 ++++++- .../Utilities/DateTimeUtils.cs | 2 + .../Utilities/DictionaryWrapper.cs | 286 ++++++---- .../Utilities/DynamicProxyMetaObject.cs | 12 +- .../DynamicReflectionDelegateFactory.cs | 12 +- .../Utilities/DynamicWrapper.cs | 56 +- Src/Newtonsoft.Json/Utilities/EnumUtils.cs | 4 +- .../Utilities/ILGeneratorExtensions.cs | 6 +- .../LateBoundReflectionDelegateFactory.cs | 2 +- .../Utilities/ReflectionUtils.cs | 216 ++++--- Src/Newtonsoft.Json/Utilities/StringUtils.cs | 8 +- .../Utilities/TypeExtensions.cs | 537 ++++++++++++++++++ .../Utilities/ValidationUtils.cs | 2 +- 141 files changed, 3921 insertions(+), 1097 deletions(-) create mode 100644 .gitignore create mode 100644 Src/Newtonsoft.Json.Metro.sln create mode 100644 Src/Newtonsoft.Json.Tests/Images/UnitTestLogo.png create mode 100644 Src/Newtonsoft.Json.Tests/Images/UnitTestSmallLogo.png create mode 100644 Src/Newtonsoft.Json.Tests/Images/UnitTestSplashScreen.png create mode 100644 Src/Newtonsoft.Json.Tests/Images/UnitTestStoreLogo.png create mode 100644 Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj create mode 100644 Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro_TemporaryKey.pfx create mode 100644 Src/Newtonsoft.Json.Tests/Package.appxmanifest create mode 100644 Src/Newtonsoft.Json/Newtonsoft.Json.Metro.csproj create mode 100644 Src/Newtonsoft.Json/Utilities/TypeExtensions.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c3673c23 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +[Bb]in/ +[Oo]bj/ +[Ww]orking/ +*.suo +*.user \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Metro.sln b/Src/Newtonsoft.Json.Metro.sln new file mode 100644 index 00000000..687fce8f --- /dev/null +++ b/Src/Newtonsoft.Json.Metro.sln @@ -0,0 +1,64 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 11 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Metro", "Newtonsoft.Json\Newtonsoft.Json.Metro.csproj", "{263136A2-B89B-424E-A87A-F988CAA8D032}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.Metro", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.Metro.csproj", "{8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|ARM.ActiveCfg = Debug|ARM + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|ARM.Build.0 = Debug|ARM + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|Any CPU.Build.0 = Debug|Any CPU + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|x64.ActiveCfg = Debug|x64 + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|x64.Build.0 = Debug|x64 + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|x86.ActiveCfg = Debug|x86 + {263136A2-B89B-424E-A87A-F988CAA8D032}.Debug|x86.Build.0 = Debug|x86 + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|ARM.ActiveCfg = Release|ARM + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|ARM.Build.0 = Release|ARM + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|Any CPU.ActiveCfg = Release|Any CPU + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|Any CPU.Build.0 = Release|Any CPU + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|x64.ActiveCfg = Release|x64 + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|x64.Build.0 = Release|x64 + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|x86.ActiveCfg = Release|x86 + {263136A2-B89B-424E-A87A-F988CAA8D032}.Release|x86.Build.0 = Release|x86 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|ARM.ActiveCfg = Debug|ARM + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|ARM.Build.0 = Debug|ARM + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|ARM.Deploy.0 = Debug|ARM + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|x64.ActiveCfg = Debug|x64 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|x64.Build.0 = Debug|x64 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|x64.Deploy.0 = Debug|x64 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|x86.ActiveCfg = Debug|x86 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|x86.Build.0 = Debug|x86 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Debug|x86.Deploy.0 = Debug|x86 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|ARM.ActiveCfg = Release|ARM + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|ARM.Build.0 = Release|ARM + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|ARM.Deploy.0 = Release|ARM + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|Any CPU.Build.0 = Release|Any CPU + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|Any CPU.Deploy.0 = Release|Any CPU + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|x64.ActiveCfg = Release|x64 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|x64.Build.0 = Release|x64 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|x64.Deploy.0 = Release|x64 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|x86.ActiveCfg = Release|x86 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|x86.Build.0 = Release|x86 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}.Release|x86.Deploy.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs index 6c3ae9d4..d99cecaf 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs @@ -28,7 +28,13 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Bson; using System.IO; using Newtonsoft.Json.Tests.Serialization; @@ -37,6 +43,7 @@ using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Bson { + [TestFixture] public class BsonReaderTests : TestFixtureBase { private const char Euro = '\u20ac'; @@ -76,7 +83,7 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(1, reader.Value); + Assert.AreEqual(1L, reader.Value); Assert.AreEqual(typeof(long), reader.ValueType); Assert.IsTrue(reader.Read()); @@ -111,22 +118,22 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(int.MaxValue, reader.Value); + Assert.AreEqual((long)int.MaxValue, reader.Value); Assert.AreEqual(typeof(long), reader.ValueType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(int.MaxValue, reader.Value); + Assert.AreEqual((long)int.MaxValue, reader.Value); Assert.AreEqual(typeof(long), reader.ValueType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(byte.MaxValue, reader.Value); + Assert.AreEqual((long)byte.MaxValue, reader.Value); Assert.AreEqual(typeof(long), reader.ValueType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(sbyte.MaxValue, reader.Value); + Assert.AreEqual((long)sbyte.MaxValue, reader.Value); Assert.AreEqual(typeof(long), reader.ValueType); Assert.IsTrue(reader.Read()); @@ -136,17 +143,17 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(decimal.MaxValue, reader.Value); + Assert.AreEqual((double)decimal.MaxValue, reader.Value); Assert.AreEqual(typeof(double), reader.ValueType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(double.MaxValue, reader.Value); + Assert.AreEqual((double)double.MaxValue, reader.Value); Assert.AreEqual(typeof(double), reader.ValueType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(float.MaxValue, reader.Value); + Assert.AreEqual((double)float.MaxValue, reader.Value); Assert.AreEqual(typeof(double), reader.ValueType); Assert.IsTrue(reader.Read()); @@ -156,7 +163,7 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); - Assert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, reader.Value); + CollectionAssert.AreEquivalent(new byte[] { 0, 1, 2, 3, 4 }, (byte[])reader.Value); Assert.AreEqual(typeof(byte[]), reader.ValueType); Assert.IsTrue(reader.Read()); @@ -268,27 +275,30 @@ namespace Newtonsoft.Json.Tests.Bson } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to integer: a.")] public void ReadAsInt32BadString() { - byte[] data = MiscellaneousUtils.HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00"); + ExceptionAssert.Throws("Could not convert string to integer: a.", + () => + { + byte[] data = MiscellaneousUtils.HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00"); - MemoryStream ms = new MemoryStream(data); - BsonReader reader = new BsonReader(ms); + MemoryStream ms = new MemoryStream(data); + BsonReader reader = new BsonReader(ms); - Assert.AreEqual(false, reader.ReadRootValueAsArray); - Assert.AreEqual(DateTimeKind.Local, reader.DateTimeKindHandling); + Assert.AreEqual(false, reader.ReadRootValueAsArray); + Assert.AreEqual(DateTimeKind.Local, reader.DateTimeKindHandling); - reader.ReadRootValueAsArray = true; - reader.DateTimeKindHandling = DateTimeKind.Utc; + reader.ReadRootValueAsArray = true; + reader.DateTimeKindHandling = DateTimeKind.Utc; - Assert.AreEqual(true, reader.ReadRootValueAsArray); - Assert.AreEqual(DateTimeKind.Utc, reader.DateTimeKindHandling); + Assert.AreEqual(true, reader.ReadRootValueAsArray); + Assert.AreEqual(DateTimeKind.Utc, reader.DateTimeKindHandling); - Assert.IsTrue(reader.Read()); - Assert.AreEqual(JsonToken.StartArray, reader.TokenType); + Assert.IsTrue(reader.Read()); + Assert.AreEqual(JsonToken.StartArray, reader.TokenType); - reader.ReadAsInt32(); + reader.ReadAsInt32(); + }); } [Test] @@ -349,7 +359,7 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); - Assert.AreEqual(MiscellaneousUtils.HexToBytes("4ABBED9D1D8B0F0218000001"), reader.Value); + CollectionAssert.AreEquivalent(MiscellaneousUtils.HexToBytes("4ABBED9D1D8B0F0218000001"), (byte[])reader.Value); Assert.AreEqual(typeof(byte[]), reader.ValueType); Assert.IsTrue(reader.Read()); @@ -387,7 +397,7 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); - Assert.AreEqual(MiscellaneousUtils.HexToBytes("4A-78-93-79-17-22-00-00-00-00-61-CF"), reader.Value); + CollectionAssert.AreEquivalent(MiscellaneousUtils.HexToBytes("4A-78-93-79-17-22-00-00-00-00-61-CF"), (byte[])reader.Value); Assert.AreEqual(typeof(byte[]), reader.ValueType); Assert.IsTrue(reader.Read()); @@ -623,7 +633,7 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); - Assert.AreEqual(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, reader.Value); + CollectionAssert.AreEquivalent(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, (byte[])reader.Value); Assert.AreEqual(typeof(byte[]), reader.ValueType); Assert.IsTrue(reader.Read()); @@ -1282,11 +1292,11 @@ namespace Newtonsoft.Json.Tests.Bson TestObject newObject = (TestObject)serializer.Deserialize(bsonReader); Assert.AreEqual("Test", newObject.Name); - Assert.AreEqual(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data); + CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data); } } -#if !(WINDOWS_PHONE || SILVERLIGHT || NET20 || NET35) +#if !(WINDOWS_PHONE || SILVERLIGHT || NET20 || NET35 || NETFX_CORE) public void Utf8Text() { string badText =System.IO.File.ReadAllText(@"PoisonText.txt"); diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs index 0e438a03..d5c1d99a 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs @@ -27,7 +27,13 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Bson; using System.IO; using Newtonsoft.Json.Utilities; @@ -36,6 +42,7 @@ using System.Globalization; namespace Newtonsoft.Json.Tests.Bson { + [TestFixture] public class BsonWriterTests : TestFixtureBase { [Test] @@ -150,7 +157,7 @@ namespace Newtonsoft.Json.Tests.Bson reader.Read(); reader.Read(); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); - Assert.AreEqual(data, reader.Value); + CollectionAssert.AreEquivalent(data, (byte[])reader.Value); } [Test] @@ -237,7 +244,7 @@ namespace Newtonsoft.Json.Tests.Bson serializer.Serialize(writer1, s1); - Assert.AreEqual(ms.ToArray(), ms1.ToArray()); + CollectionAssert.AreEquivalent(ms.ToArray(), ms1.ToArray()); string s = JsonConvert.SerializeObject(s1); byte[] textData = Encoding.UTF8.GetBytes(s); @@ -365,47 +372,59 @@ namespace Newtonsoft.Json.Tests.Bson } [Test] - [ExpectedException(typeof(JsonWriterException), ExpectedMessage = "Cannot write JSON comment as BSON.")] public void WriteComment() { - MemoryStream ms = new MemoryStream(); - BsonWriter writer = new BsonWriter(ms); + ExceptionAssert.Throws("Cannot write JSON comment as BSON.", + () => + { + MemoryStream ms = new MemoryStream(); + BsonWriter writer = new BsonWriter(ms); - writer.WriteStartArray(); - writer.WriteComment("fail"); + writer.WriteStartArray(); + writer.WriteComment("fail"); + }); } [Test] - [ExpectedException(typeof(JsonWriterException), ExpectedMessage = "Cannot write JSON constructor as BSON.")] public void WriteConstructor() { - MemoryStream ms = new MemoryStream(); - BsonWriter writer = new BsonWriter(ms); + ExceptionAssert.Throws("Cannot write JSON constructor as BSON.", + () => + { + MemoryStream ms = new MemoryStream(); + BsonWriter writer = new BsonWriter(ms); - writer.WriteStartArray(); - writer.WriteStartConstructor("fail"); + writer.WriteStartArray(); + writer.WriteStartConstructor("fail"); + }); } [Test] - [ExpectedException(typeof(JsonWriterException), ExpectedMessage = "Cannot write raw JSON as BSON.")] public void WriteRaw() { - MemoryStream ms = new MemoryStream(); - BsonWriter writer = new BsonWriter(ms); + ExceptionAssert.Throws("Cannot write raw JSON as BSON.", + () => + { + MemoryStream ms = new MemoryStream(); + BsonWriter writer = new BsonWriter(ms); - writer.WriteStartArray(); - writer.WriteRaw("fail"); + writer.WriteStartArray(); + writer.WriteRaw("fail"); + }); } [Test] - [ExpectedException(typeof(JsonWriterException), ExpectedMessage = "Cannot write raw JSON as BSON.")] public void WriteRawValue() { - MemoryStream ms = new MemoryStream(); - BsonWriter writer = new BsonWriter(ms); + ExceptionAssert.Throws("Cannot write raw JSON as BSON.", + () => + { + MemoryStream ms = new MemoryStream(); + BsonWriter writer = new BsonWriter(ms); - writer.WriteStartArray(); - writer.WriteRawValue("fail"); + writer.WriteStartArray(); + writer.WriteRawValue("fail"); + }); } [Test] @@ -476,7 +495,7 @@ namespace Newtonsoft.Json.Tests.Bson Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); - Assert.AreEqual(oid, reader.Value); + CollectionAssert.AreEquivalent(oid, (byte[])reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); @@ -497,7 +516,7 @@ namespace Newtonsoft.Json.Tests.Bson byte[] expected = MiscellaneousUtils.HexToBytes("29000000075F6964004ABBED9D1D8B0F02180000010274657374000900000031323334C2A335360000"); - Assert.AreEqual(expected, ms.ToArray()); + CollectionAssert.AreEquivalent(expected, ms.ToArray()); } [Test] @@ -515,7 +534,7 @@ namespace Newtonsoft.Json.Tests.Bson byte[] expected = MiscellaneousUtils.HexToBytes("1A-00-00-00-0B-72-65-67-65-78-00-61-62-63-00-69-00-0B-74-65-73-74-00-00-00-00"); - Assert.AreEqual(expected, ms.ToArray()); + CollectionAssert.AreEquivalent(expected, ms.ToArray()); } [Test] @@ -627,16 +646,19 @@ namespace Newtonsoft.Json.Tests.Bson } [Test] - [ExpectedException(typeof(JsonWriterException), ExpectedMessage = "Error writing String value. BSON must start with an Object or Array.")] public void WriteValueOutsideOfObjectOrArray() { - MemoryStream stream = new MemoryStream(); - - using (BsonWriter writer = new BsonWriter(stream)) + ExceptionAssert.Throws("Error writing String value. BSON must start with an Object or Array.", + () => { - writer.WriteValue("test"); - writer.Flush(); - } + MemoryStream stream = new MemoryStream(); + + using (BsonWriter writer = new BsonWriter(stream)) + { + writer.WriteValue("test"); + writer.Flush(); + } + }); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs index 94ca068e..86d4dce5 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs @@ -1,19 +1,26 @@ using System; using System.Collections.Generic; -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE using System.Data.Linq; #endif -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) using System.Data.SqlTypes; #endif using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class BinaryConverterTests : TestFixtureBase { private static readonly byte[] TestData = Encoding.UTF8.GetBytes("This is some test data!!!"); @@ -24,7 +31,7 @@ namespace Newtonsoft.Json.Tests.Converters public byte[] NullByteArray { get; set; } } -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE [Test] public void DeserializeBinaryClass() { @@ -90,7 +97,7 @@ namespace Newtonsoft.Json.Tests.Converters }", json); } -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) public class SqlBinaryClass { public SqlBinary SqlBinary { get; set; } @@ -142,7 +149,7 @@ namespace Newtonsoft.Json.Tests.Converters ByteArrayClass byteArrayClass = JsonConvert.DeserializeObject(json, new BinaryConverter()); - Assert.AreEqual(TestData, byteArrayClass.ByteArray); + CollectionAssert.AreEquivalent(TestData, byteArrayClass.ByteArray); Assert.AreEqual(null, byteArrayClass.NullByteArray); } @@ -157,7 +164,7 @@ namespace Newtonsoft.Json.Tests.Converters ByteArrayClass c = JsonConvert.DeserializeObject(json); Assert.IsNotNull(c.ByteArray); Assert.AreEqual(4, c.ByteArray.Length); - Assert.AreEqual(new byte[] { 0, 1, 2, 3 }, c.ByteArray); + CollectionAssert.AreEquivalent(new byte[] { 0, 1, 2, 3 }, c.ByteArray); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs index 43a15023..eae51bbb 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs @@ -3,10 +3,17 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class CustomCreationConverterTests : TestFixtureBase { public interface IPerson diff --git a/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs index c333acca..ba1dad39 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs @@ -1,10 +1,16 @@ -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using System.Data; diff --git a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs index fc4a6861..3b392806 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs @@ -1,12 +1,20 @@ -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using System.Data; +#endif namespace Newtonsoft.Json.Tests.Converters { diff --git a/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs index f07de570..6259ac7f 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs @@ -2,21 +2,28 @@ using System; using System.Collections.Generic; -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE using System.Data.Linq; #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE using System.Data.SqlTypes; #endif using System.Dynamic; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class ExpandoObjectConverterTests : TestFixtureBase { public class ExpandoContainer @@ -110,32 +117,32 @@ namespace Newtonsoft.Json.Tests.Converters Assert.IsNotNull(o.Expando); dynamic d = o.Expando; - Assert.IsInstanceOfType(typeof(ExpandoObject), d); + CustomAssert.IsInstanceOfType(typeof(ExpandoObject), d); Assert.AreEqual("String!", d.String); - Assert.IsInstanceOfType(typeof(string), d.String); + CustomAssert.IsInstanceOfType(typeof(string), d.String); Assert.AreEqual(234, d.Integer); - Assert.IsInstanceOfType(typeof(long), d.Integer); + CustomAssert.IsInstanceOfType(typeof(long), d.Integer); Assert.AreEqual(1.23, d.Float); - Assert.IsInstanceOfType(typeof(double), d.Float); + CustomAssert.IsInstanceOfType(typeof(double), d.Float); Assert.IsNotNull(d.List); Assert.AreEqual(3, d.List.Count); - Assert.IsInstanceOfType(typeof(List), d.List); + CustomAssert.IsInstanceOfType(typeof(List), d.List); Assert.AreEqual("First", d.List[0]); - Assert.IsInstanceOfType(typeof(string), d.List[0]); + CustomAssert.IsInstanceOfType(typeof(string), d.List[0]); Assert.AreEqual("Second", d.List[1]); Assert.AreEqual("Third", d.List[2]); Assert.IsNotNull(d.Object); - Assert.IsInstanceOfType(typeof(ExpandoObject), d.Object); + CustomAssert.IsInstanceOfType(typeof(ExpandoObject), d.Object); Assert.AreEqual(1, d.Object.First); - Assert.IsInstanceOfType(typeof(long), d.Object.First); + CustomAssert.IsInstanceOfType(typeof(long), d.Object.First); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs index e7ac34d1..634ca036 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs @@ -28,7 +28,13 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; using System.Globalization; @@ -36,6 +42,7 @@ using System.Xml; namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class IsoDateTimeConverterTests : TestFixtureBase { [Test] @@ -112,7 +119,7 @@ namespace Newtonsoft.Json.Tests.Converters Assert.AreEqual(2006, d.Year); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void SerializeFormattedDateTimeNewZealandCulture() { @@ -212,11 +219,14 @@ namespace Newtonsoft.Json.Tests.Converters } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Cannot convert null value to System.DateTime.")] public void DeserializeNullToNonNullable() { - DateTimeTestClass c2 = - JsonConvert.DeserializeObject(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal }); + ExceptionAssert.Throws("Cannot convert null value to System.DateTime.", + () => + { + DateTimeTestClass c2 = + JsonConvert.DeserializeObject(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal }); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs index c13dd0bd..f0111266 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs @@ -28,11 +28,18 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Converters; namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class JavaScriptDateTimeConverterTests : TestFixtureBase { [Test] @@ -94,11 +101,14 @@ namespace Newtonsoft.Json.Tests.Converters } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Cannot convert null value to System.DateTime.")] public void DeserializeNullToNonNullable() { - DateTimeTestClass c2 = - JsonConvert.DeserializeObject(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new JavaScriptDateTimeConverter()); + ExceptionAssert.Throws("Cannot convert null value to System.DateTime.", + () => + { + DateTimeTestClass c2 = + JsonConvert.DeserializeObject(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new JavaScriptDateTimeConverter()); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs index 55600d26..40d99f84 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs @@ -6,10 +6,17 @@ using System.Text; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class ObjectIdConverterTests : TestFixtureBase { public class ObjectIdTestClass @@ -38,7 +45,7 @@ namespace Newtonsoft.Json.Tests.Converters byte[] expected = MiscellaneousUtils.HexToBytes("29000000075F6964004ABBED9D1D8B0F02180000010274657374000900000031323334C2A335360000"); - Assert.AreEqual(expected, ms.ToArray()); + CollectionAssert.AreEquivalent(expected, ms.ToArray()); } [Test] @@ -51,7 +58,7 @@ namespace Newtonsoft.Json.Tests.Converters BsonReader reader = new BsonReader(new MemoryStream(bson)); ObjectIdTestClass c = serializer.Deserialize(reader); - Assert.AreEqual(c.Id.Value, MiscellaneousUtils.HexToBytes("4ABBED9D1D8B0F0218000001")); + CollectionAssert.AreEquivalent(c.Id.Value, MiscellaneousUtils.HexToBytes("4ABBED9D1D8B0F0218000001")); Assert.AreEqual(c.Test, "1234£56"); } } diff --git a/Src/Newtonsoft.Json.Tests/Converters/RegexConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/RegexConverterTests.cs index 7f0b4d86..f5ed3f61 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/RegexConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/RegexConverterTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE using System.Data.Linq; #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE using System.Data.SqlTypes; #endif using System.IO; @@ -13,11 +13,18 @@ using System.Text.RegularExpressions; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class RegexConverterTests : TestFixtureBase { public class RegexTestClass diff --git a/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs index 685495bb..4a7226c2 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs @@ -4,11 +4,18 @@ using System.Linq; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class StringEnumConverterTests : TestFixtureBase { public class EnumClass @@ -66,15 +73,18 @@ namespace Newtonsoft.Json.Tests.Converters #if !NET20 [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Enum name 'Third' already exists on enum 'NamedEnumDuplicate'.")] public void NamedEnumDuplicateTest() { - EnumContainer c = new EnumContainer + ExceptionAssert.Throws("Enum name 'Third' already exists on enum 'NamedEnumDuplicate'.", + () => { - Enum = NamedEnumDuplicate.First - }; + EnumContainer c = new EnumContainer + { + Enum = NamedEnumDuplicate.First + }; - JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter()); + JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter()); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs index eaaaf941..48f08585 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs @@ -28,7 +28,13 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Converters @@ -53,6 +59,7 @@ namespace Newtonsoft.Json.Tests.Converters public string StringProperty2 { get; set; } } + [TestFixture] public class VersionConverterTests : TestFixtureBase { private void SerializeVersionClass(string version1, string version2) diff --git a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs index c672ac5b..c4e4c93d 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs @@ -23,12 +23,18 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE using System; using System.Collections.Generic; using Newtonsoft.Json.Tests.Serialization; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json; using System.IO; using System.Xml; @@ -41,6 +47,7 @@ using System.Xml.Linq; namespace Newtonsoft.Json.Tests.Converters { + [TestFixture] public class XmlNodeConverterTest : TestFixtureBase { private string SerializeXmlNode(XmlNode node) diff --git a/Src/Newtonsoft.Json.Tests/ExceptionTests.cs b/Src/Newtonsoft.Json.Tests/ExceptionTests.cs index c710c9fd..2fb82123 100644 --- a/Src/Newtonsoft.Json.Tests/ExceptionTests.cs +++ b/Src/Newtonsoft.Json.Tests/ExceptionTests.cs @@ -28,10 +28,17 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Schema; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests { + [TestFixture] public class ExceptionTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Images/UnitTestLogo.png b/Src/Newtonsoft.Json.Tests/Images/UnitTestLogo.png new file mode 100644 index 0000000000000000000000000000000000000000..ebd735aa9352cf97bfcbe11dc4281617d570dca4 GIT binary patch literal 5789 zcmbVQhdons_quWX^nDTL^UGD1W-M)v9$NwN~MJA93- zj3}e~I=}n-2kt$ObDYQdIOqL&yFDB;YCRff7OZo zzr!1qpV5s#A|g5*;YHl%`^uGw2w`EYuVWLIx0&x{nmcjY*YQqvGKXl5Xzbvu`hN-~3vVQfC}-5L3(A;*@D-)(~>zUC6%_N{FA>F7+BQ z2aofMWTv?E9X;$K5A1XH_TDCosdb%+j5s+eT-kfr89zjSoUx}iq|&j%X=`k3Ohl@S zL5*<{p>FAR^IMWIrf5^?OOgmNU@0@T|F0Kx6ME2m8XEaqGHmAaq_C{uAOhef) zaY-!vS5moqu1dF&D(1Gj6>86wFgVvvDF-Z3(s8LKw6>}@<4~mfl?jy5oHe~-g*&*xb-3u!Sb=9T4-;*6NTJ66FeT%B9Xd^Xw9N%W|h7>0=6e>`{S_ho7;u|sd)O^R>Q9HLw|qQNb!}Qy&S#^`)gxIi&rv2O zCX#v7+bQRpXJ%#bNlVjPl{0g3ajpLN5kIi}@OFf~6f11Q$mH9}CaQMIvfL)kNKl52 zM%LF!JnK7QBVJw-%+zF%u}|)Dl8CFO(?!&VNn}K++#2`BJrj)tbwffF9ixA{83{54 z1qBt9l~K?=I2Whw{VOfQq{LE``Q~Fcq$J`fQj?v7!$th-8;2H4YwP$6BIX6{?c5hH zUL=Z5PNsqgB_$=hD=&$oFi68>_ix*-yGc#)p`^g`v>11=KX3CqHnR($ux`1-@iL$ta#EW&=L3cTqQQl5oth>8= z!PuINic0dy$w~coN)NiOq2cX;x=;xG`jt-O$jGf8D_3>Q%n%0X_E2TBPL5($b>BLOwLMrl!Wy$tm^SJH;akwGYeHni*d`0K{#Q`J24TSn)Oo%!Z7Qa(?2E&3H$idx#)QCHb=jBZns zl5na9QQo<8Cv2-}CGFX>rnP#_7xah}p$eO;6d0!SMECFChtXGLIgi{lXx}f9F08I* zxcrPJTiWTqdD(Ob+JES|Mq0lsYS0^!0L#fMD*8wuQhIcwqcz)iv)&fe*Rve|+MHHg zHn*_QgG6|GiZA6b5gVGOX(k&M$MvA&=C|j6*MQi_{YN>ux$%x~`?|aJCuK)y z@m730^ZvGtYkX>I9MbJa{Bx0eW_g-Xf699{oY^se2F&V*Gl5=vPSB&l!NJO*Tb$pf zr*TiIiF$i`Ayi$H<79GtxFiu956^=x=g#-t>8L4 zi8ewaCedVKQc}I;)@8iuMt*GdW51@0e%Q<$| zC-q2SH6a~M+zAUnqV&atleBrY9UQnme*DOf*f$PS=YAe@c6TSNHH~65S5{H+epgr5 zs|ntCf0_EyZH7i zp(7(XPft&gj*g{jnXjB%k>PFJ?zJkyLjB2|lap-tG2ZHP-PEOerCC|t2@^knGH^RP zGP8yHwD=y9Smcg`Y(LI=MLM46=lAUI%jXyRoPQ0FP|D&8Bd>gSSC9a~mvaXf z{l31tJwt;?Nh~Vj2b$}P!lxl?8XGBFX4^OSlP7*Wn&QkhEbfZfZlh>( z3=CY|+%y1ua=g2omF87SsSP9QdijR^H^_3MKc2j~r3EMi?f7q8|EEtU9mw_q=nsga z&h8R4*Ta;QhDr;O?ic0dV)m_Jj4{6loMhzXNgJlQ_7u@lh-$m5br3>EKPf;wU`x5p z$JL)h<|t=pqK@O)?cu4Z)~r;r>AEgj4~iszpE|^g|ew%OgO-#rs7j$ zP6Xzn4jpLd>Bp=lSVFP)B&DTsu9s0B9+c(f<$?;mNfh+l3)vkfLaJ(NvI+_Y)5R`z z$z+wE@0yvKE_B6HAmQ$&!qdNG!`}Bc&iVlBE?n>U!?HEsVbMQhqdY8*s8+2GZL()$ zV~ZW}NH7xQFPAml2vM7hKE89ZW)X9*2W^}r65+x6pFBc%PEPZ7o|u1BI;5#R>)ExA zr-lgGo|>9Um{J!+b(7dq`~tc-I_&sM3u0z;)anVl63XA7@%kJ4F6ro>=KmhLplMRSe@6#sF8r0beEHsaR;h)}hWS!gVikm79#RJs4rmDoH?^)#9w02C zZgIn0n1NEe$`)Uybt;;ND}#cv%zuDxiTtxx=GSDOHn1#vm-%_Jq?A-qaq&5= z-~ATD6BF5KZC^43>ySDCfL}ZnfUs$j^+^gXKdjzs_rp$kAK`e;VxcAE+}}#}j$;Ks zI#{Svk&;l&>zzttRg*XGX#Ud2nKEESEGeMM*tydo&8K5`SOMN z>)a1D7MQg6?{xuh@4>Wt$O~^=7^4zFQx-vGd(+-B6slq+S=`JWg;Fd5-KVeSy)(<1OK4`PMI*jAe3NXWyJ&lU0_u%qoG0D zGHd?hz5FFK7AfiK>Pk>PT1Q>z+v>T0b$J;mEgc*l&CJ+C9zT8h)E(u_a~%tc5%m7f>~=J()A6^7_UiK=f5ze# zoww)OK&29B61N!Jhflt_&BBVk7ifLy(xtGyK_&mA9n|iEejWpLqF4EdPXlf_pvTSG zq6rCN5v1?i)?MoMz5H!${&dSJPSiOoYwL+Eb`fD=*pJ!o&gWKGQW9c1ZuKPJnB!^X z;B{s(xl%^O+(#M_zY1DgIrsMVa&mHFr#DL_6|DFX4{$m@K2ndlH6GU98u~t5s3&+J zMA_8T^s1`L05T;E%PJ{dG4{kXA^ZFLK@5BN`t~)nA6#N)Vd>djrjmsXEIzySJkCS%Mc#@C3B?U8zqzFETPLz&J}ti6&s;w;-%?Y< zl)>c!GLm4QO#h=Ed-m^k=WOe+dx0(@h_vNz1Q`{*U(B<(vxvjY&6t&qExu1YAGWj5 z^>kwJ(xB;J_XAwAtbiZUJ85}FEcg7`_Inr zNH8PJ2*fCtNwga{t*2(0iD6HP=cc2>fe* zQ$w2U8v|G9&i+hv^e#~{0O4~e`4rUF%B{z%K<%$xyVf;Xk(S^zIz>tM;KIStN6-2q za6B-T^Qd~ek>TN3P@4KDI^-n8pN59;qa|12hHTv2hW{&~1i}Xa@<5_5t*n4_F<`!s zFJn~+KKaA)ZW1-XrZl%^WYU{AQub}(!FOa2Kj*7~O-xa){}ZXnMneuRDXh)WzBz~r zG=tIY=D2hzXk!M+}zxd zWC_t7Ja$!x7m>SEZ|s|D7VlTXC$MQCOX$>s$qp;FH#ei!kGmWApJT-if~g|VsT``}&-eg6C%?1~KgBf@NgoY7ojZCbb~mLbqn7b_*?2`{Eza^SlS3aF$u< zVReFDU4GZ*f^T>+%qURc=6A{4?op>J~N@!AXTW0 ztGoOCJi7SX)n#QOFTMJDdw04hcsf1gzc2M?g#DVj)xbFkxWz%8NCMl=$;+b=E7b>& z2bt9=wB(hO3mo$T3=fZp_&IWgN2kj6fdVgmDemFJhiMZ$r_oyb;TrqlQ6Dx*SBAh* zI?J>BZ%ks%LZ=8)-AE8{1;dnbt%0ySQ?e_LRv+Y|JUgwFV{6j<-?PJ`iHSF%(#W@89`-=G(daBdo2h3GD{t?iju%R99D5 z$uSAaORwC9AJC+tMl|bVu+Rrk&$F|$s~a1bew}Yn5Dg6tKHAFoF*fpe zz6!-zA0?o3U^T*SPmcTn3w^7iq_WQgyO-NEZ(dMOCULPUG!>3mSLb>=kus!tOyk>j zfS9|x!bL+v)4dV&>t=&bVqMzCLHNkn*o9g$Z=klA6FiS{%$d68*%7|%S0HOj560vH zW(^B&AM`14<>!L=_9(E4TwzB$eD+e;O{XujKMFfJk_Ad=T&pwO$*i&5BFCXXZ^QI} zc8?$N(1+Px3Q!3M3@o$}Pk;IpaTt#ih+{;Tl$7Ye&P7Bh*dLKQI5@0sZQX|xDOWvN z2p3|5vnkK92l6M;S_JQW`I+c#r`O}?fB+_#Dlpmv4ly>S>PE}LztMBhh4+EgmT-Ep^8Qt%kG|H*?Trfn$P( zSLUSS)Qn{FY2dJzQd%^(Idx*=dkQWNeCqyw(9Ank`x`g9s%|#ye3BcgyfCnRSlrRU z17`zL*rU^EWR-2?Zoi0;v2kJ4>rG4NZim9LHDEiNnb5y&QOCdTw-tj;7|d0|pAo}& zgMCuxGcTW~GfXmIh1lcc<1MI|DM=SXT3n))8pn9ice*})r1qI<#F|&Ow`)Qd4zu0( zuGjtTey)6#s=p4Z*-mS{SQ;;^yL5m literal 0 HcmV?d00001 diff --git a/Src/Newtonsoft.Json.Tests/Images/UnitTestSmallLogo.png b/Src/Newtonsoft.Json.Tests/Images/UnitTestSmallLogo.png new file mode 100644 index 0000000000000000000000000000000000000000..92dd1058fbfb70c4491d934fe5f60ff2bacd41e9 GIT binary patch literal 745 zcmVGVQpR4ciyoglSwB91#GhGhn{+`40 zKOYZLtJUy5M#Hz+??BTuEf5G^US9q^+F&rqWU^c?_f@o5EFKPriyn{1Bb7>Dq2Gpm zj6OIx0Dx2~HJwfYfY0ae?(T|2B8f!u{QL|62qB-(r&KC$Z*SK_*J?F}VN52|>FMcU zFfbSl3WWjytX69-my^roXJ=<#ua{)79{TC&>GAP#Z*OmVdpj13x!rDr5V@9aw;PYg zH#axi?RKlx`izXlVo|Hrs#L0EGRd+maoTJ)o6W}O^8uh-F3h|y@YSS;jQC=}8(jWHGo1n>Siolbo|pUdSMkH^GQuh+}v@;m@7 z&Jc>C4i68Hj*hr+T!t~ezP`S?y22R0k0z$q>n|=YHa0d^OdOHmY;9-&aER;zuc8|`*G;bM$g zmK6$x05F+MNKYb!91h14^s=n;`Mg%E?Q}Y^Sj_A71_A*9C=?2bL}EUktX3=67~#xX zqtR?_Z50ZIlarIdV8G+?{C+<<@8RKLe}A70Rh>@PY&O@+Iv5NhgzoO{=BuF5Xoy6j zot>Spu7XS^v$&ZilS!#ml1in7OJvMsGGeiKZ5iKgy!-omnN0R!*h(_~++zV_yx462 b>BH;~a9|}kOw?>(00000NkvXXu0mjfaI93Z literal 0 HcmV?d00001 diff --git a/Src/Newtonsoft.Json.Tests/Images/UnitTestSplashScreen.png b/Src/Newtonsoft.Json.Tests/Images/UnitTestSplashScreen.png new file mode 100644 index 0000000000000000000000000000000000000000..193187f108f50dd242cb5c589b02a29691b7432a GIT binary patch literal 9381 zcmeHs_dDBt)PI_yHA>VTRkZe|wPy)R?Y(D>nzd(8MXaJ~uc9_FOYOTxRcpoGYExp@ zitu$y`dr^X;d!p>{^4^a`Mk$D=XGA^^&W{-S5>%&M~w#n0Pa0kl+y$NfQ|sbEzY|* z*KZ(9yQ9}1Shg}MG5|pJy8xs{;`MKOD@9Ee03d=00EoGMP}hS(qyd0HUjSe;8UPSq z1puh}+{MGZ0RTJ^ds$g^bvqXi7k4`sSNi9&vh=QQE;ja#F986>o~&eVZS4v2h{0BG zzubOapl0}d^FM%L|3p);MJkm!>uo}TC)EsjKw_|5I-{a`S1?@tv94S-h*Z1k&f~kR ze3W2qP8a#{Xjpm6$-x0~x!eU&d(w#9ZXGnF0K6~aNlC#`z7_w2WG_@abCWnh!($r| ze2dOJm<{kkSH8)t%Kt8?_h)}tHiH|`4C~gOpMDF_b!12&SoO|T&L@M-fRK$;0C7gG z2o)zW1yqt!5xII@MTy!V7kL~dwnR{+@I$h>u#k#;13)l%@=1A+c9Wfc!97$`T z1(5Gv81OGm4}-z=Pd?YzJ$WL)k1AEa@;r1=nw*+OpiEP2^=n<-Wa5-g{`(Y1L@2e0_T0)g z+sBeSaR);tBKt2aqJp_$G#p$^D&LE2KM5GnHZA5voIbpB=}Ctplj%d4(@6q;8(A3h zQyKI*qh}58i@msL%1KW8DN*O;r|w4b$l+6Bb*q@*QBQVh2;vSa9x*)}*==%_@6vY4 zOAql~WKWECzuFZ-*?uipVhYXJ6B%G)eLHafK!D<;Yw-TZTelQ}?D2PgNI%#B$eQDn z2Xnb%IsZd*8VUm8>fR<-#3~6Us*$Ff#KM!|o5Vd1ex-hgT1LPQyGMpa7<(X8`4{z< zTh5_KbJ7>Vw&vt5IQSqe3kH6LpH^f z?4hN(e#KPhbfUOf5ise{Arm`-^l(VT{MWlL-jr0`FUO|oB)GO0BKu3n71)9^5QhKj zfh*H2;9;29ufx5kr-I^mQlaahU=T5NUKAxGK^OMELSDSj+qiOtsCc|jx9q`936d+! z{84@ME*g}i*kA>!JV%Y}Vs%pd&p4mybl#N8KaltQ=%*p1VO4A}s_=xW0y?fR^Rab^ zcmvCWya{9y;{2>3pC`{HpJk|$kCNbCer$Dzk0m4D^VH9&_xmJY(5%tgfCS#9by`** z=m(ZR7=QS)3$H3{l6_la+h7~y1w`T~bd~(-bKUvEN=uXySN6|?uUTL3Ei%8x_hD;c zp2yjZvt4%ID>#)85V{nF0NbVGne9ln?=rl7+`;^eDL2VAVJ~>^z2f6i;)=)+Iquhw zs^9y>_@oKT2PnU1*i0~1gg<7mzq1M2q}}A+WJ-H6&M5Xi|2y!2&`sbBct(5{iv{jb z>`;EgRV|YzpC@anxYYRAR8wpCx!Y%Jn043+ZtvE60Zkt^E;b6b!co5x>XJmwN1E=# zr1o0&L7Uo}_ctF6>wPM+uHrZ3cjk9Y1Ez)YQ&@jvy9>@*dS;;^s6~A}kVKn6C*wC* zC68RIJ)cnB_T@|Kl-}@Oo1f#~vy&ebFg)Q(r{D_HRT5LBDQq>$tLw7Iwe3A-s!$G3 z?)%A=cR7Bu;jqDU#ET~@g^NCwujGD!X%~3N*vqFCZWm{MGKK}n`x=JjSyp!Fu<41E z9em(c_RcFB;@E6GGSC6*sOjXsYW*Gj`%QYiVXGJ*E<+vZ1c0d`AV335Y$2 z6^+fNaiCP7+U4I7xU{phcyBpu=eD5zZFJ_zLfy=fw}6B|vO(+=mwQcP^BK+|_aVj4 zqmf*DlRN;OmgNpDbIw~L%Cz z(yhic$+WGSs_LOwu9&&lfTKx5Dg|-o5v}t@c0c zr|d&F&o{$1^Bo+=w+#e-o-7Kzl%^`wAqH9hrhW;LL(taH!nB&p=Glu zAn~H+LNB9J$eV(d%#o9FVX3;HKs_(sOt@yu%VAD%RB)$01hF<#Rv*M^Nnyez$OdDD zn02r>p2uzqB`pL@6SrG^9If%VQteZnA6PUYY$i;3p0b)8yL&t{r=iNj!yfdR#bz)m z>Lr<{Kdyh6zXC@fM|0_uQZL=sO4afu-CopBgv@|r>e{hZojgK0A&fX&n@B>u?ZFy!)Bt5&=e)N{blx0nDR(c*89W`88?`t80SEYMA z%eG8}%3VB&xF3oOtnhkV7H;(`H?%mLG`B7t|8m{f%SzZtfQxO5X?bhyw0%kOby>Xp zc4y-bn5ckGS6nk-bgy=2&?!GTzo^H!=ltOvsWzzr>Y!ugZ#=s!c-iqe+Am692&$#2 zWTkuMwC#JWjzrpS4wBp81tnd6K5iU1dMmMPHvQ2qe)MXpEW0td zQK3@HjHi#HH6h6Tlxx{(p?S|c5#M09dY40L1F~_sak&4rXjCod68m=Q;YCx|#>n-C z6W3MIz#Ra0e za^0u;xtxr)k11l#rOVVd9k3UpZJ;F2pGGtTXJ38UHZbr))(5u)q$GI{^?^q~l=&^w zhpO-xUtESPyZ)*V7J8czrT1cCyrc5@d<6uZlRIxU3+qLdQZFWtshAT18xDa?t zksuV{$9X9KI)CJJ#Qq7&=+gfR*%$=jmdZf|1mZYqKE{Mq#{$A0bFTXdcLpOpaw%uV zrD_+prFy2EcxWU@Fbcp-55gXawBwO)ZmoFb*a>mFh*|E!(l7XnjBu(nDVQZ6$ z#0i_e)c=;WpCzteD5-)`63PT=QYkSwOu^`)-(aSDLIyeLBe0W2{2D(ABQ;e`(xjpb z(O!oDoe|spsTSxjy)nJy!JZu7{eL=-M=$M`{uGhV526ms1}*}Q6H!i0FX`I&O#;sm z&(Ssr4CwJP1mKWbnU@|yl8JhrYwL0K30B8Oe{z;re72m^Cej2gM_4d){^%LPYVDOj zXOIs(*V^`fH0=(5S4U@V5lq`aEw%jJM|X~2O)u@3&;A<*r*R5s$LhoU)<(;ML;7QX zuIZ^i3a_q6sPxFpzBT?x_LZ84Sj+zvOh;Bwx6&nRP!b|^ax=ipc6eN+QuHu+-)6SV zabn^@=Osp5Lv*q8-kd?|7GUbVD|!*@hW83r2OeEs{P0Su^cz`5az*6(V}$r0w-8n( z7)-r*HSUn*4^3qs%QQQMmaz%UjtJ938Xu@p9>6gj#Kkraq1g5IB6}J02Vr+sKIGC6 z?^gY@kH>Irs;*$9p((0Y_^$)98Uf-oh;|zG4;KlS1$J>>-DFlMONMMS58>lQ_JzV| zlHsi>m?b|U8aH065LQvhmlen1nf=R!*{*sg7$uKOl+kpyi~lwXWjhb&zbZsTn0&M5 zM0;g!1Jnq+sLQ>7#yIa^P4u4fBrE;P{3cs=K;ARIQ70+HBW|nvXxK<7pg)#Z!+|UL zK9vo3J_%(F{B|%Leq`7*>cn$Gmhl?*W<3gt#FhK}nsd7OUYLTUUTuafBOINnpjEraK27n2L&B{MB|ETuzZ% zuh;piMyEqV`1QXXXS&0M7o0-CDQJ}b8O5fC)E=k!RF0JKq!`5InwLe@x1>KsDP=6w zab?);V#>q}SMKTSg2LicaZ@RYCuP;7jyiBJ(WQ!Jvzesasi+7v(WbA2OgeGINy#v(e6yErwFI4O+|YZ5^`6LI6;lKcn0Us(+x;XHJRgBT76Rn%0@IB z${T-0(t!po^gfi4A?MzCPx{h&$HzA&cWq*@jdbcviX$b~zt$>51Pn#S-q<~20AW9y zYaKs6huUWG^%z#^fM-lqE?~4K>-1GTH`z_SE*Q&C1^ZM zepgdCjv3Sk9NTTuIqg<#Sp;FY@eFv+EXkNdUKX*tmAiIpsb>JOGVr5>I;aA9fYXx04102YV*rJKws) zYZ}zV)bg3xW6c|DLp9Rn2bJXH$O%Kb`r4f$(<&zGl~Y58K|L{9K@5CDFlo-C95QmG z0OH-W$*us~q*8$yQ?$gvK_s~_Wceph#jkUI9#__k?&|MM#DD4ZF+DAhB7@Gr7D7^SAy!;@dw zXjdie^m^IS^h8QxSelKM7w`K?y)S^c@&SVFlWusH##gT=ZvAIQvvl^@x<%;trIEnu z(p_@$lV(KREaI*^+oa}GH!g|N9|(yiiIo_6v_CAMXyocMzS@RX;&Av#A6|Xyv$m87 zK9W4lf-p`F4MXW#yw2%Eh||64D>vtun_nKEz7s)&*<*KtpwHGup79BkEL7^4k&KT! zcBV!mz{HVsY>$!ah}e%T=#+jG2+<$SVddOD5ySu38M5XPUcs)uOW_8|lXa8DfH(t! zVz+wWLo;SJ{Otn!s?3`WzWZu6yrP=sW2QsrDoUDjg90!5JXRNHt8s*i+;IY5#BAG_ znm`TBigFGR{<*Td!Kkf%l?ms{#c)#(6osL8HnycqP<~Z$&X!2IZnz8kq$p%Ji*ol& z_x4_zmM>IMr%4b0b+1p|+}U<=?MXLZ!$4KPeaEWO&HQAk zBQBGLV$rL8md>bfC+9?Nvws~-E&L}Fc0X&4VBB_<9p2dgCE#C#&1-0Or2a}odF0BO$OwZ6k&pV(II6J)SF=yMugy{Y37Qs^5*Y)8`D#DL_D>(*-XLr!?3 zN)vj<^y_^=t2XN-x2nL5?@O{nziQqFo_=MSdbAn=uTx~k%K2M}IevOu3+menqs&2B z0B(XVq`xM@R7W1f9j~!pA|iDnBdpO0p`q`7l8ja=I~98JBbI9_p~i7WU)uutDo^m; zk#e@TD52=(ZZbPKW8Hbsja8!2en;Kr87WWU_qJtP}m*zaK zB*&{aJ9(IPSC!^4KcZ9uCov$DG%A#UUSL^1VW zoS3=P50OQOiK>2#z1_1}Jfsc}RUS*&V^oC*`xT70MZxYA$mji#6t8}(GtT(!&CJ37 z7y_$*?UItC0_?pj-fhp8NcRm+rTfloJ^_VdbY$*sSI3o?#ePs(20XSVQo3(qt|N19 z_7hJI13EDIYjRwrrPn@Xkq2FFKZ|J;)e$h;X%%eFm+AP|3NJ?pD`1|7^p?vYp2g$d zZ{l;@ePf7(w>&S<^=Ynk-JV@0;;?*{myuV$*BHJ4%W}35HoYghQ6g6c9Ox)Gl87##Yr@~DMP-N}2LB>lw6Emf5oOnXa2=dJYr zE+psIJFH)ZDsZoo%G5P+=f3WO^s_I5wiJzM;hMsi3)zG8>*eqCk1xWB-Cgt6%GBeC zwp{55(7J)c1_E~oJhk=Q>Df}aLv_^kMrqw{(`33$tlFah?dDxa#-Y8jjf{+=b%8D1 zw^tc$cqW5=^ZyeeZ;O%ElP_Zm(F$^@*GX8OBaaw+iY5@Rdq66Pky4+LdgoJt2WnnBtk;+e&){RH);#HPBK(973dT4VYsD8(zh z$dCb+fo03zkU8^Dt_u{qd=&KDr0owzuvzEHqP$m*e* z94oER=6$Zf-}N36Yw>^Yt!VY>qoOLo$d|H<32{0H+wj2QP2!53*ILihvdzTyRyJ<9 zaZS)FGkUxjj(cFE`NAczWdvb?Y+cig*W*Pp)xXBZvGOKQpUc9NU0TTyCF4L!*Pb-* zq#zQw8cyb$A&g9v+?9L!UQMppKSqa~!?(RY=$)4jyNJ+gg0JqG&Ag|PpYNNmw1js> zZfG5ndsl9M-@2|anz+XG%%o00HnK5Rn7^HUu(0;k=E~GZrx(GJ7C)7aCTflk8*fXsSwo$I+=)rhb4vf(#maM?GTATdi~tYz?5A8v7(-Tl zJ`oN7&nfz#Z2mb)zLF^D?uQUJ4xo~_8=3bzV2NX7-TDJvH&#rB>XBb;s=bw-9FA8LOgrOxC4kM_0 zu-C3q-obCjCIdWK(@v+)Ry# zwY$08=zW%(d^LXs*~!WIIcO`@6P{7=9Zf9^%zyccmfioF{)6Q|Cj2j}f_&mrDTv9& Wc>{ycr|W-s0MEgya{drMKsZ^rAz8-3|8d+Ic`2PKS@(c;{5kDToaT(HAsZ>y@R9IPAVH+D86hVdo zpwiM(=yWqACH1{xb1(cIh&yuSwG44ZEk9#7H8rt&_wJEWsRUz; z5fQDguVZOxiD@(%QmIsaSw=+UcDu2%vcfbPO~@Qcl5qe2eb(OIP7!t_c~J`hhzKJi zBec4@3Z+sBzXoY(X(%WtpfFkT^NLcbr10^zwKWV44N(+WB`<3E+tSh!L{Y@Wix(3j zGn>r@hr_X_gcxWX$Kl|?gV=&c$To5u7l=kPGcyznpD2lA#Q*%`Q&UqYDJfz8P1@Yt z{0&+jj|X4BehvR``=n8!P(ZKOqp7J0`T6;NW&fVU^AH39j4|>%G{p!vQ8BYMURPI# z^73*bB6z)C$g&)~xa4#?(bv}ptJNCakXT&t^5sitwOU-gdKD*6o`gc7NJ^emSXdZw z+~@PbX0xHUw--Z0LjjJ8xa->;J_v$<%F0T1`SN9|udhc&M#i>~i5FV2WIP@ZhKGmI z+1bfPMn))>5pg-YEXxo@kroyfFg-numX;PAI&^4TIPJ6rKkM7KZ|LdifyH8h!{H#W z*SkHB#CsgX7(-@eCTeSIapT4foH%h}&!Oh?`Czx((ca#U{{DU}FE7W<^udJ4g5q;T z5@L)oK@d<}Tuira-NKnOXIM%~%5PDNZAFFPJ`qv0aRBgoy-XBEdid}m-o1OrHa0c_ zVlfCYz$d{`i?$;n`nw_0oM32#L(boiHXhvF`cV|Uq7vecp;c2;6Mz=a^GShLTU#5f zR_o576^|hbg#v|zg}89xLWr}+ozTS@-J&=<_Qcu!;rGgwD|GJMxj#1i#xz8wQlY7- zDd~h53u-o-4NsmtK~GPQzogz7j|hSQlgR{=$pl%JF+M*2YtpY21?lPOC@LySNa4A; zIsE+j6TvA;aI37W#M06d`uqE%vU}8|adUGM6B84dnVIp2Qwnx`j^n@>V+{=rbo=)0 zgp$S=FJ7Rdqk{n;pU(%M&le&_MC9>!V){zdq|xW|VR3PB+f%^S*4BiRMx9QFj~_qA zTaWDh0o{QE2T)a2m9Q@yJ9Z2@oeon|Q~P^B=ZBZcWMXQyI)tTnQ|hWzD%8}}Fo(mj z|D`U+aj34Yrj(QvKNQL7bYgID5LT;|u3x{7>gsB692a2f$;nBywY5=IRTUZ<8jzct zOB~06=Xsb+ChF+ufFw!#Tk7WIC>kW1tumYFgG`cf`S4t#;~}!7{W!eEMs(Z6!Y`*f!#3}4Cv|U zf!pogA49UUv*C8T@!-J&3=IuMWZdQDWsHxH!(cFg=XrYn{yi2J7JiePpP$F$$B!{R zJ&m%mGUVsy?<#uj>VPizT0xfONOc1PKt`hxj~+dOLZM)H@7|?n&z}8R*9vQEYgk)b zi&euA08CC!!r^d0tyWXexo*TcvMiI+>HKF7=(cNaw;KZk1IWqA!SeEQQWMOi-yvG9 zR%o@_q~0G!@{y==_`hFI6A|JtBB6Ke1X_uH!V!<$zv2@P{3$z("Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.", + () => + { + JsonConvert.ToString(new Version(1, 0)); + }); } [Test] @@ -261,8 +271,10 @@ now brown cow?", '"', true); value = null; Assert.AreEqual("null", JsonConvert.ToString(value)); +#if !NETFX_CORE value = DBNull.Value; Assert.AreEqual("null", JsonConvert.ToString(value)); +#endif value = "I am a string"; Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value)); @@ -275,17 +287,20 @@ now brown cow?", '"', true); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: t. Line 1, position 19.")] public void TestInvalidStrings() { - string orig = @"this is a string ""that has quotes"" "; + ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: t. Line 1, position 19.", + () => + { + string orig = @"this is a string ""that has quotes"" "; - string serialized = JsonConvert.SerializeObject(orig); + string serialized = JsonConvert.SerializeObject(orig); - // *** Make string invalid by stripping \" \" - serialized = serialized.Replace(@"\""", "\""); + // *** Make string invalid by stripping \" \" + serialized = serialized.Replace(@"\""", "\""); - JsonConvert.DeserializeObject(serialized); + JsonConvert.DeserializeObject(serialized); + }); } [Test] @@ -541,6 +556,7 @@ now brown cow?", '"', true); TestDateTimeFormat(value, new IsoDateTimeConverter()); +#if !NETFX_CORE if (value is DateTime) { Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind)); @@ -549,6 +565,7 @@ now brown cow?", '"', true); { Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value)); } +#endif #if !NET20 MemoryStream ms = new MemoryStream(); @@ -681,7 +698,7 @@ now brown cow?", '"', true); var taskObject = JsonConvert.DeserializeObjectAsync("[]"); taskObject.Wait(); - Assert.AreEqual(new JArray(), taskObject.Result); + CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result); Task taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings { diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs index 173117bc..929b90f9 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs @@ -27,7 +27,13 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json; using System.IO; using System.Xml; @@ -35,6 +41,7 @@ using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { + [TestFixture] public class JsonTextReaderTest : TestFixtureBase { [Test] @@ -102,7 +109,7 @@ namespace Newtonsoft.Json.Tests Assert.AreEqual("Date", reader.Value); Assert.IsTrue(reader.Read()); - Assert.AreEqual(0, reader.Value); + Assert.AreEqual(0L, reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual("hi", reader.Value); @@ -115,7 +122,11 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2." +#endif + )] public void ParseAdditionalContent_Comma() { string json = @"[ @@ -131,7 +142,11 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: c. Line 5, position 2.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Additional text encountered after finished reading JSON content: c. Line 5, position 2." +#endif + )] public void ParseAdditionalContent_Text() { string json = @"[ @@ -179,7 +194,11 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: a. Line 1, position 5.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Additional text encountered after finished reading JSON content: a. Line 1, position 5." +#endif + )] public void ParseAdditionalContent_WhitespaceThenText() { string json = @"'hi' a"; @@ -311,13 +330,13 @@ namespace Newtonsoft.Json.Tests reader.Read(); Assert.AreEqual(reader.TokenType, JsonToken.Integer); - Assert.AreEqual(1, reader.Value); + Assert.AreEqual(1L, reader.Value); Assert.AreEqual(2, reader.Depth); Assert.AreEqual("array[0]", reader.Path); reader.Read(); Assert.AreEqual(reader.TokenType, JsonToken.Integer); - Assert.AreEqual(2, reader.Value); + Assert.AreEqual(2L, reader.Value); Assert.AreEqual(2, reader.Depth); Assert.AreEqual("array[1]", reader.Path); @@ -329,7 +348,7 @@ namespace Newtonsoft.Json.Tests reader.Read(); Assert.AreEqual(reader.TokenType, JsonToken.Integer); - Assert.AreEqual(1, reader.Value); + Assert.AreEqual(1L, reader.Value); Assert.AreEqual(3, reader.Depth); Assert.AreEqual("array[2][0]", reader.Path); @@ -397,15 +416,23 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null. -Parameter name: reader")] + [ExpectedException(typeof(ArgumentNullException) +#if !NETFX_CORE + , ExpectedMessage = @"Value cannot be null. +Parameter name: reader" +#endif + )] public void NullTextReader() { new JsonTextReader(null); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3." +#endif + )] public void UnexpectedEndOfString() { JsonReader reader = new JsonTextReader(new StringReader("'hi")); @@ -442,7 +469,7 @@ Parameter name: reader")] for (int i = 0; i < valueCount; i++) { Assert.IsTrue(reader.Read()); - Assert.AreEqual(i, reader.Value); + Assert.AreEqual((long)i, reader.Value); } Assert.IsTrue(reader.Read()); Assert.IsFalse(reader.Read()); @@ -570,7 +597,11 @@ Parameter name: reader")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing unicode character. Line 1, position 4.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected end while parsing unicode character. Line 1, position 4." +#endif + )] public void UnexpectedEndOfHex() { JsonReader reader = new JsonTextReader(new StringReader(@"'h\u123")); @@ -578,7 +609,11 @@ Parameter name: reader")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3." +#endif + )] public void UnexpectedEndOfControlCharacter() { JsonReader reader = new JsonTextReader(new StringReader(@"'h\")); @@ -586,7 +621,11 @@ Parameter name: reader")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading bytes. Unexpected token: Boolean. Line 1, position 4.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error reading bytes. Unexpected token: Boolean. Line 1, position 4." +#endif + )] public void ReadBytesWithBadCharacter() { JsonReader reader = new JsonTextReader(new StringReader(@"true")); @@ -594,7 +633,11 @@ Parameter name: reader")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 17.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 17." +#endif + )] public void ReadBytesWithUnexpectedEnd() { string helloWorld = "Hello world!"; @@ -615,7 +658,11 @@ Parameter name: reader")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing unquoted property name. Line 1, position 4.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected end while parsing unquoted property name. Line 1, position 4." +#endif + )] public void UnexpectedEndWhenParsingUnquotedProperty() { JsonReader reader = new JsonTextReader(new StringReader(@"{aww")); @@ -681,7 +728,7 @@ Parameter name: reader")] Assert.IsTrue(reader.Read()); Assert.AreEqual(61, reader.LineNumber); - Assert.AreEqual(1, reader.Value); + Assert.AreEqual(1L, reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(73, reader.LineNumber); @@ -725,7 +772,7 @@ Parameter name: reader")] bye", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(1, reader.Value); + Assert.AreEqual(1L, reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); @@ -743,7 +790,7 @@ bye", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); byte[] data = reader.ReadAsBytes(); - Assert.AreEqual(helloWorldData, data); + CollectionAssert.AreEquivalent(helloWorldData, data); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndArray, reader.TokenType); @@ -765,7 +812,7 @@ bye", reader.Value); Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.IsTrue(reader.Read()); byte[] data = reader.ReadAsBytes(); - Assert.AreEqual(helloWorldData, data); + CollectionAssert.AreEquivalent(helloWorldData, data); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); @@ -1063,15 +1110,15 @@ bye", reader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); - Assert.AreEqual(0, jsonReader.Value); + Assert.AreEqual(0d, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); - Assert.AreEqual(0.0000025, jsonReader.Value); + Assert.AreEqual(0.0000025d, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); - Assert.AreEqual(3000000000, jsonReader.Value); + Assert.AreEqual(3000000000d, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.EndArray, jsonReader.TokenType); @@ -1079,7 +1126,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = @"Invalid character after parsing property name. Expected ':' but got: "". Line 3, position 9.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = @"Invalid character after parsing property name. Expected ':' but got: "". Line 3, position 9." +#endif + )] public void MissingColon() { string json = @"{ @@ -1124,15 +1175,15 @@ bye", reader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); - Assert.AreEqual(250, jsonReader.Value); + Assert.AreEqual(250L, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); - Assert.AreEqual(250, jsonReader.Value); + Assert.AreEqual(250L, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); - Assert.AreEqual(250, jsonReader.Value); + Assert.AreEqual(250L, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndArray, jsonReader.TokenType); @@ -1171,7 +1222,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected character encountered while parsing value: }. Line 1, position 1.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected character encountered while parsing value: }. Line 1, position 1." +#endif + )] public void ReadBadCharInArray() { JsonTextReader reader = new JsonTextReader(new StringReader(@"[}")); @@ -1199,7 +1254,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 1.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 1." +#endif + )] public void ReadAsBytesNoContentWrappedObject() { JsonTextReader reader = new JsonTextReader(new StringReader(@"{")); @@ -1219,7 +1278,11 @@ bye", reader.Value); #endif [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading decimal. Unexpected token: StartConstructor. Line 1, position 9.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error reading decimal. Unexpected token: StartConstructor. Line 1, position 9." +#endif + )] public void ReadAsDecimalBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); @@ -1229,7 +1292,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading bytes. Unexpected token: StartConstructor. Line 1, position 9.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error reading bytes. Unexpected token: StartConstructor. Line 1, position 9." +#endif + )] public void ReadAsBytesBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); @@ -1239,7 +1306,11 @@ bye", reader.Value); #if !NET20 [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading date. Unexpected token: StartConstructor. Line 1, position 9.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error reading date. Unexpected token: StartConstructor. Line 1, position 9." +#endif + )] public void ReadAsDateTimeOffsetBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); @@ -1260,7 +1331,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 2.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 2." +#endif + )] public void ReadAsBytesIntegerArrayWithNoEnd() { JsonTextReader reader = new JsonTextReader(new StringReader(@"[1")); @@ -1269,7 +1344,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected token when reading bytes: Float. Line 1, position 4.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected token when reading bytes: Float. Line 1, position 4." +#endif + )] public void ReadAsBytesArrayWithBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"[1.0]")); @@ -1369,7 +1448,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22." +#endif + )] public void ReadAsDateTimeOffsetBadString() { string json = @"{""Offset"":""blablahbla""}"; @@ -1518,11 +1601,15 @@ bye", reader.Value); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); Assert.AreEqual(typeof(decimal), reader.ValueType); - Assert.AreEqual(1, reader.Value); + Assert.AreEqual(1m, reader.Value); } [Test] - [ExpectedException(typeof(FormatException), ExpectedMessage = "Input string was not in a correct format.")] + [ExpectedException(typeof(FormatException) +#if !NETFX_CORE + , ExpectedMessage = "Input string was not in a correct format." +#endif + )] public void ReadAsIntDecimal() { string json = @"{""Name"": 1.1}"; @@ -1542,7 +1629,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 0, position 0.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error parsing null value. Line 0, position 0." +#endif + )] public void MatchWithInsufficentCharacters() { JsonTextReader reader = new JsonTextReader(new StringReader(@"nul")); @@ -1550,7 +1641,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 0, position 0.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error parsing null value. Line 0, position 0." +#endif + )] public void MatchWithWrongCharacters() { JsonTextReader reader = new JsonTextReader(new StringReader(@"nulz")); @@ -1558,7 +1653,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 1, position 4.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error parsing null value. Line 1, position 4." +#endif + )] public void MatchWithNoTrailingSeperator() { JsonTextReader reader = new JsonTextReader(new StringReader(@"nullz")); @@ -1566,7 +1665,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing comment. Line 1, position 6.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected end while parsing comment. Line 1, position 6." +#endif + )] public void UnclosedComment() { JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf")); @@ -1574,7 +1677,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing comment. Expected: *, got s. Line 1, position 1.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error parsing comment. Expected: *, got s. Line 1, position 1." +#endif + )] public void BadCommentStart() { JsonTextReader reader = new JsonTextReader(new StringReader(@"/sdf")); @@ -1750,7 +1857,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing constructor. Line 1, position 7.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected end while parsing constructor. Line 1, position 7." +#endif + )] public void ParseConstructorWithUnexpectedEnd() { string json = "new Dat"; @@ -1760,7 +1871,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected character while parsing constructor: !. Line 1, position 9.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected character while parsing constructor: !. Line 1, position 9." +#endif + )] public void ParseConstructorWithUnexpectedCharacter() { string json = "new Date !"; @@ -1808,7 +1923,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing boolean value. Line 1, position 4.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error parsing boolean value. Line 1, position 4." +#endif + )] public void ParseIncompleteCommentSeperator() { JsonTextReader reader = new JsonTextReader(new StringReader("true/")); @@ -1830,7 +1949,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected character while parsing constructor: ,. Line 1, position 8.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected character while parsing constructor: ,. Line 1, position 8." +#endif + )] public void ParseConstructorWithBadCharacter() { string json = "new Date,()"; @@ -1991,7 +2114,11 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: }. Line 1, position 2.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Additional text encountered after finished reading JSON content: }. Line 1, position 2." +#endif + )] public void UnexpectedEndTokenWhenParsingOddEndToken() { JsonReader reader = new JsonTextReader(new StringReader(@"{}}")); @@ -2020,19 +2147,19 @@ bye", reader.Value); reader.Read(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(0, reader.Value); + Assert.AreEqual(0d, reader.Value); reader.Read(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(0, reader.Value); + Assert.AreEqual(0d, reader.Value); reader.Read(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(0.0000025, reader.Value); + Assert.AreEqual(0.0000025d, reader.Value); reader.Read(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(3000000000, reader.Value); + Assert.AreEqual(3000000000d, reader.Value); reader.Read(); Assert.AreEqual(JsonToken.Float, reader.TokenType); @@ -2047,19 +2174,19 @@ bye", reader.Value); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(0, reader.Value); + Assert.AreEqual(0m, reader.Value); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(0, reader.Value); + Assert.AreEqual(0m, reader.Value); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(0.0000025, reader.Value); + Assert.AreEqual(0.0000025m, reader.Value); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); - Assert.AreEqual(3000000000, reader.Value); + Assert.AreEqual(3000000000m, reader.Value); reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); diff --git a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs index ad1effc8..e48b913e 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs @@ -29,7 +29,13 @@ using System.Globalization; using System.Runtime.Serialization; using System.Text; using System.Xml; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; @@ -37,6 +43,7 @@ using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { + [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] @@ -165,7 +172,11 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation." +#endif + )] public void WriteValueObjectWithUnsupportedValue() { StringWriter sw = new StringWriter(); @@ -583,7 +594,11 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(JsonWriterException), ExpectedMessage = "No token to close.")] + [ExpectedException(typeof(JsonWriterException) +#if !NETFX_CORE + , ExpectedMessage = "No token to close." +#endif + )] public void BadWriteEndArray() { StringBuilder sb = new StringBuilder(); @@ -601,7 +616,11 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Invalid JavaScript string quote character. Valid quote characters are ' and "".")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = @"Invalid JavaScript string quote character. Valid quote characters are ' and ""." +#endif + )] public void InvalidQuoteChar() { StringBuilder sb = new StringBuilder(); diff --git a/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs b/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs index b8950d72..fabfa6b6 100644 --- a/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs @@ -3,7 +3,13 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using System.Xml; using System.Xml.Schema; using Newtonsoft.Json.Schema; @@ -12,6 +18,7 @@ using ValidationEventArgs = Newtonsoft.Json.Schema.ValidationEventArgs; namespace Newtonsoft.Json.Tests { + [TestFixture] public class JsonValidatingReaderTests : TestFixtureBase { [Test] @@ -315,18 +322,21 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof (JsonSchemaException), ExpectedMessage = "Integer 10 exceeds maximum value of 5. Line 1, position 2.")] public void ThrowExceptionWhenNoValidationEventHandler() { - string schemaJson = @"{ + ExceptionAssert.Throws("Integer 10 exceeds maximum value of 5. Line 1, position 2.", + () => + { + string schemaJson = @"{ ""type"":""integer"", ""maximum"":5 }"; - JsonValidatingReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader("10"))); - reader.Schema = JsonSchema.Parse(schemaJson); + JsonValidatingReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader("10"))); + reader.Schema = JsonSchema.Parse(schemaJson); - Assert.IsTrue(reader.Read()); + Assert.IsTrue(reader.Read()); + }); } [Test] @@ -1401,7 +1411,7 @@ namespace Newtonsoft.Json.Tests }; byte[] bytes = reader.ReadAsBytes(); - Assert.AreEqual(data, bytes); + CollectionAssert.AreEquivalent(data, bytes); } [Test] @@ -1419,17 +1429,20 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof (JsonSchemaException), ExpectedMessage = "Integer 5 exceeds maximum value of 2. Line 1, position 1.")] public void ReadAsInt32Failure() { - JsonSchema s = new JsonSchemaGenerator().Generate(typeof (int)); - s.Maximum = 2; + ExceptionAssert.Throws("Integer 5 exceeds maximum value of 2. Line 1, position 1.", + () => + { + JsonSchema s = new JsonSchemaGenerator().Generate(typeof(int)); + s.Maximum = 2; - JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5"))) + JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5"))) { Schema = s }; - reader.ReadAsInt32(); + reader.ReadAsInt32(); + }); } [Test] @@ -1443,21 +1456,24 @@ namespace Newtonsoft.Json.Tests }; decimal? d = reader.ReadAsDecimal(); - Assert.AreEqual(1.5, d); + Assert.AreEqual(1.5m, d); } [Test] - [ExpectedException(typeof (JsonSchemaException), ExpectedMessage = "Float 5.5 is not evenly divisible by 1. Line 1, position 3.")] public void ReadAsDecimalFailure() { - JsonSchema s = new JsonSchemaGenerator().Generate(typeof (decimal)); - s.DivisibleBy = 1; + ExceptionAssert.Throws("Float 5.5 is not evenly divisible by 1. Line 1, position 3.", + () => + { + JsonSchema s = new JsonSchemaGenerator().Generate(typeof(decimal)); + s.DivisibleBy = 1; - JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5.5"))) + JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5.5"))) { Schema = s }; - reader.ReadAsDecimal(); + reader.ReadAsDecimal(); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/BindingTests.cs b/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/BindingTests.cs index da7ef71b..dc54d4dc 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/BindingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/BindingTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !PocketPC && !SILVERLIGHT +#if !PocketPC && !SILVERLIGHT && !NETFX_CORE using System; using System.Collections.Generic; using System.Linq; @@ -34,6 +34,7 @@ using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Linq.ComponentModel { + [TestFixture] public class BindingTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs b/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs index e22adca8..df790477 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE using System; using System.Collections.Generic; using System.Linq; @@ -33,6 +33,7 @@ using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Linq.ComponentModel { + [TestFixture] public class JPropertyDescriptorTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs index 83b3f8f6..ca2432d9 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs @@ -5,12 +5,19 @@ using System.Dynamic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Utilities; using System.Globalization; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class DynamicTests : TestFixtureBase { [Test] @@ -79,7 +86,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Could not determine JSON object type for type System.String[].")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = "Could not determine JSON object type for type System.String[]." +#endif + )] public void JObjectPropertyNameWithNonToken() { dynamic d = new JObject(); @@ -234,9 +245,9 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(4.1, (double)r); r = d.Integer + 1.1d; - Assert.AreEqual(2.1, (decimal)r); + Assert.AreEqual(2.1m, (decimal)r); r += 2; - Assert.AreEqual(4.1, (decimal)r); + Assert.AreEqual(4.1m, (decimal)r); r = d.Integer + null; Assert.AreEqual(null, r.Value); @@ -244,19 +255,19 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Float + 1; - Assert.AreEqual(2.1, (double)r); + Assert.AreEqual(2.1d, (double)r); r += 2; - Assert.AreEqual(4.1, (double)r); + Assert.AreEqual(4.1d, (double)r); r = d.Float + 1.1; - Assert.AreEqual(2.2, (double)r); + Assert.AreEqual(2.2d, (double)r); r += 2; - Assert.AreEqual(4.2, (double)r); + Assert.AreEqual(4.2d, (double)r); r = d.Float + 1.1d; - Assert.AreEqual(2.2, (decimal)r); + Assert.AreEqual(2.2m, (decimal)r); r += 2; - Assert.AreEqual(4.2, (decimal)r); + Assert.AreEqual(4.2m, (decimal)r); r = d.Float + null; Assert.AreEqual(null, r.Value); @@ -264,19 +275,19 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Decimal + 1; - Assert.AreEqual(2.1, (decimal)r); + Assert.AreEqual(2.1m, (decimal)r); r += 2; - Assert.AreEqual(4.1, (decimal)r); + Assert.AreEqual(4.1m, (decimal)r); r = d.Decimal + 1.1; - Assert.AreEqual(2.2, (decimal)r); + Assert.AreEqual(2.2m, (decimal)r); r += 2; - Assert.AreEqual(4.2, (decimal)r); + Assert.AreEqual(4.2m, (decimal)r); r = d.Decimal + 1.1d; - Assert.AreEqual(2.2, (decimal)r); + Assert.AreEqual(2.2m, (decimal)r); r += 2; - Assert.AreEqual(4.2, (decimal)r); + Assert.AreEqual(4.2m, (decimal)r); r = d.Decimal + null; Assert.AreEqual(null, r.Value); @@ -291,14 +302,14 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(-2, (int)r); r = d.Integer - 1.1; - Assert.AreEqual(-0.1, (double)r, 0.00001); + Assert.AreEqual(-0.1d, (double)r, 0.00001); r -= 2; - Assert.AreEqual(-2.1, (double)r); + Assert.AreEqual(-2.1d, (double)r); r = d.Integer - 1.1d; - Assert.AreEqual(-0.1, (decimal)r); + Assert.AreEqual(-0.1m, (decimal)r); r -= 2; - Assert.AreEqual(-2.1, (decimal)r); + Assert.AreEqual(-2.1m, (decimal)r); r = d.Integer - null; Assert.AreEqual(null, r.Value); @@ -306,19 +317,19 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Float - 1; - Assert.AreEqual(0.1, (double)r, 0.00001); + Assert.AreEqual(0.1d, (double)r, 0.00001); r -= 2; - Assert.AreEqual(-1.9, (double)r); + Assert.AreEqual(-1.9d, (double)r); r = d.Float - 1.1; - Assert.AreEqual(0, (double)r); + Assert.AreEqual(0d, (double)r); r -= 2; - Assert.AreEqual(-2, (double)r); + Assert.AreEqual(-2d, (double)r); r = d.Float - 1.1d; - Assert.AreEqual(0, (decimal)r); + Assert.AreEqual(0m, (decimal)r); r -= 2; - Assert.AreEqual(-2, (decimal)r); + Assert.AreEqual(-2m, (decimal)r); r = d.Float - null; Assert.AreEqual(null, r.Value); @@ -326,19 +337,19 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Decimal - 1; - Assert.AreEqual(0.1, (decimal)r); + Assert.AreEqual(0.1m, (decimal)r); r -= 2; - Assert.AreEqual(-1.9, (decimal)r); + Assert.AreEqual(-1.9m, (decimal)r); r = d.Decimal - 1.1; - Assert.AreEqual(0, (decimal)r); + Assert.AreEqual(0m, (decimal)r); r -= 2; - Assert.AreEqual(-2, (decimal)r); + Assert.AreEqual(-2m, (decimal)r); r = d.Decimal - 1.1d; - Assert.AreEqual(0, (decimal)r); + Assert.AreEqual(0m, (decimal)r); r -= 2; - Assert.AreEqual(-2, (decimal)r); + Assert.AreEqual(-2m, (decimal)r); r = d.Decimal - null; Assert.AreEqual(null, r.Value); @@ -353,14 +364,14 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(2, (int)r); r = d.Integer * 1.1; - Assert.AreEqual(1.1, (double)r); + Assert.AreEqual(1.1d, (double)r); r *= 2; - Assert.AreEqual(2.2, (double)r); + Assert.AreEqual(2.2d, (double)r); r = d.Integer * 1.1d; - Assert.AreEqual(1.1, (decimal)r); + Assert.AreEqual(1.1m, (decimal)r); r *= 2; - Assert.AreEqual(2.2, (decimal)r); + Assert.AreEqual(2.2m, (decimal)r); r = d.Integer * null; Assert.AreEqual(null, r.Value); @@ -368,19 +379,19 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Float * 1; - Assert.AreEqual(1.1, (double)r); + Assert.AreEqual(1.1d, (double)r); r *= 2; - Assert.AreEqual(2.2, (double)r); + Assert.AreEqual(2.2d, (double)r); r = d.Float * 1.1; - Assert.AreEqual(1.21, (double)r, 0.00001); + Assert.AreEqual(1.21d, (double)r, 0.00001); r *= 2; - Assert.AreEqual(2.42, (double)r, 0.00001); + Assert.AreEqual(2.42d, (double)r, 0.00001); r = d.Float * 1.1d; - Assert.AreEqual(1.21, (decimal)r); + Assert.AreEqual(1.21m, (decimal)r); r *= 2; - Assert.AreEqual(2.42, (decimal)r); + Assert.AreEqual(2.42m, (decimal)r); r = d.Float * null; Assert.AreEqual(null, r.Value); @@ -388,19 +399,19 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Decimal * 1; - Assert.AreEqual(1.1, (decimal)r); + Assert.AreEqual(1.1m, (decimal)r); r *= 2; - Assert.AreEqual(2.2, (decimal)r); + Assert.AreEqual(2.2m, (decimal)r); r = d.Decimal * 1.1; - Assert.AreEqual(1.21, (decimal)r); + Assert.AreEqual(1.21m, (decimal)r); r *= 2; - Assert.AreEqual(2.42, (decimal)r); + Assert.AreEqual(2.42m, (decimal)r); r = d.Decimal * 1.1d; - Assert.AreEqual(1.21, (decimal)r); + Assert.AreEqual(1.21m, (decimal)r); r *= 2; - Assert.AreEqual(2.42, (decimal)r); + Assert.AreEqual(2.42m, (decimal)r); r = d.Decimal * null; Assert.AreEqual(null, r.Value); @@ -415,9 +426,9 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(0, (int)r); r = d.Integer / 1.1; - Assert.AreEqual(0.9090909090909091, (double)r); + Assert.AreEqual(0.9090909090909091d, (double)r); r /= 2; - Assert.AreEqual(0.454545454545455, (double)r, 0.00001); + Assert.AreEqual(0.454545454545455d, (double)r, 0.00001); r = d.Integer / 1.1d; Assert.AreEqual(0.909090909090909m, (decimal)r); @@ -430,14 +441,14 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Float / 1; - Assert.AreEqual(1.1, (double)r); + Assert.AreEqual(1.1d, (double)r); r /= 2; - Assert.AreEqual(0.55, (double)r); + Assert.AreEqual(0.55d, (double)r); r = d.Float / 1.1; - Assert.AreEqual(1, (double)r, 0.00001); + Assert.AreEqual(1d, (double)r, 0.00001); r /= 2; - Assert.AreEqual(0.5, (double)r, 0.00001); + Assert.AreEqual(0.5d, (double)r, 0.00001); r = d.Float / 1.1d; Assert.AreEqual(1m, (decimal)r); @@ -450,19 +461,19 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, r.Value); r = d.Decimal / 1; - Assert.AreEqual(1.1d, (decimal)r); + Assert.AreEqual(1.1m, (decimal)r); r /= 2; - Assert.AreEqual(0.55d, (decimal)r); + Assert.AreEqual(0.55m, (decimal)r); r = d.Decimal / 1.1; - Assert.AreEqual(1d, (decimal)r); + Assert.AreEqual(1m, (decimal)r); r /= 2; - Assert.AreEqual(0.5d, (decimal)r); + Assert.AreEqual(0.5m, (decimal)r); r = d.Decimal / 1.1d; - Assert.AreEqual(1d, (decimal)r); + Assert.AreEqual(1m, (decimal)r); r /= 2; - Assert.AreEqual(0.5d, (decimal)r); + Assert.AreEqual(0.5m, (decimal)r); r = d.Decimal / null; Assert.AreEqual(null, r.Value); @@ -547,12 +558,12 @@ namespace Newtonsoft.Json.Tests.Linq AssertValueConverted(null); AssertValueConverted(99.9m); AssertValueConverted(99.9m); - AssertValueConverted(1); + AssertValueConverted(1m); AssertValueConverted(1.1f, 1.1m); AssertValueConverted("1.1", 1.1m); AssertValueConverted(99.9); - AssertValueConverted(99.9m); - AssertValueConverted(99.9); + AssertValueConverted(99.9d); + AssertValueConverted(99.9d); AssertValueConverted(99.9f); AssertValueConverted(99.9f); AssertValueConverted(int.MinValue); @@ -566,7 +577,7 @@ namespace Newtonsoft.Json.Tests.Linq AssertValueConverted(1, "1"); AssertValueConverted(uint.MinValue); AssertValueConverted(uint.MinValue); - AssertValueConverted("1", 1); + AssertValueConverted("1", (uint)1); AssertValueConverted(ulong.MaxValue); AssertValueConverted(ulong.MaxValue); AssertValueConverted(ushort.MinValue); diff --git a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs index dc6cd1b7..6ebef284 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs @@ -3,11 +3,18 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JArrayTests : TestFixtureBase { [Test] @@ -68,8 +75,12 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null. -Parameter name: array")] + [ExpectedException(typeof(ArgumentNullException) +#if !NETFX_CORE + , ExpectedMessage = @"Value cannot be null. +Parameter name: array" +#endif + )] public void GenericCollectionCopyToNullArrayShouldThrow() { JArray j = new JArray(); @@ -77,8 +88,12 @@ Parameter name: array")] } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"arrayIndex is less than 0. -Parameter name: arrayIndex")] + [ExpectedException(typeof(ArgumentOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = @"arrayIndex is less than 0. +Parameter name: arrayIndex" +#endif + )] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { JArray j = new JArray(); @@ -86,7 +101,11 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"arrayIndex is equal to or greater than the length of array.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = @"arrayIndex is equal to or greater than the length of array." +#endif + )] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { JArray j = new JArray(); @@ -94,7 +113,11 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array." +#endif + )] public void GenericCollectionCopyToInsufficientArrayCapacity() { JArray j = new JArray(); @@ -174,8 +197,12 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"Index is equal to or greater than Count. -Parameter name: index")] + [ExpectedException(typeof(ArgumentOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = @"Index is equal to or greater than Count. +Parameter name: index" +#endif + )] public void RemoveAtOutOfRangeIndexShouldError() { JArray j = new JArray(); @@ -183,8 +210,12 @@ Parameter name: index")] } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"Index is less than 0. -Parameter name: index")] + [ExpectedException(typeof(ArgumentOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = @"Index is less than 0. +Parameter name: index" +#endif + )] public void RemoveAtNegativeIndexShouldError() { JArray j = new JArray(); @@ -262,8 +293,12 @@ Parameter name: index")] } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"Index was out of range. Must be non-negative and less than the size of the collection. -Parameter name: index")] + [ExpectedException(typeof(ArgumentOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = @"Index was out of range. Must be non-negative and less than the size of the collection. +Parameter name: index" +#endif + )] public void InsertNegativeIndexShouldThrow() { JArray j = new JArray(); @@ -271,8 +306,12 @@ Parameter name: index")] } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"Index must be within the bounds of the List. -Parameter name: index")] + [ExpectedException(typeof(ArgumentOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = @"Index must be within the bounds of the List. +Parameter name: index" +#endif + )] public void InsertOutOfRangeIndexShouldThrow() { JArray j = new JArray(); @@ -302,7 +341,11 @@ Parameter name: index")] } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject" +#endif + )] public void Parse_ShouldThrowOnUnexpectedToken() { string json = @"{""prop"":""value""}"; @@ -378,7 +421,7 @@ Parameter name: index")] } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void ITypedListGetItemProperties() { @@ -407,7 +450,11 @@ Parameter name: index")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Set JArray values with invalid key value: ""badvalue"". Array position index expected.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = @"Set JArray values with invalid key value: ""badvalue"". Array position index expected." +#endif + )] public void SetValueWithInvalidIndex() { JArray a = new JArray(); @@ -440,7 +487,11 @@ Parameter name: index")] } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected end of content while loading JArray.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected end of content while loading JArray." +#endif + )] public void ParseIncomplete() { JArray.Parse("[1"); @@ -459,7 +510,11 @@ Parameter name: index")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2." +#endif + )] public void ParseAdditionalContent() { string json = @"[ diff --git a/Src/Newtonsoft.Json.Tests/Linq/JConstructorTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JConstructorTests.cs index fc85baf3..7c43332f 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JConstructorTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JConstructorTests.cs @@ -3,11 +3,18 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using System.IO; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JConstructorTests : TestFixtureBase { [Test] @@ -46,11 +53,14 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Set JConstructor values with invalid key value: ""badvalue"". Argument position index expected.")] public void SetValueWithInvalidIndex() { - JConstructor c = new JConstructor(); - c["badvalue"] = new JValue(3); + ExceptionAssert.Throws(@"Set JConstructor values with invalid key value: ""badvalue"". Argument position index expected.", + () => + { + JConstructor c = new JConstructor(); + c["badvalue"] = new JValue(3); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs index c8060c06..5790febc 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs @@ -4,18 +4,25 @@ using System.ComponentModel; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; using Newtonsoft.Json.Converters; using System.IO; using System.Collections; using System.Collections.Specialized; -#if !PocketPC && !SILVERLIGHT +#if !PocketPC && !SILVERLIGHT && !NETFX_CORE using System.Web.UI; #endif namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JObjectTests : TestFixtureBase { [Test] @@ -91,7 +98,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object." +#endif + )] public void DuplicatePropertyNameShouldThrow() { JObject o = new JObject(); @@ -201,8 +212,12 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null. -Parameter name: array")] + [ExpectedException(typeof(ArgumentNullException) +#if !NETFX_CORE + , ExpectedMessage = @"Value cannot be null. +Parameter name: array" +#endif + )] public void GenericCollectionCopyToNullArrayShouldThrow() { JObject o = new JObject(); @@ -210,8 +225,12 @@ Parameter name: array")] } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"arrayIndex is less than 0. -Parameter name: arrayIndex")] + [ExpectedException(typeof(ArgumentOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = @"arrayIndex is less than 0. +Parameter name: arrayIndex" +#endif + )] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { JObject o = new JObject(); @@ -219,7 +238,11 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"arrayIndex is equal to or greater than the length of array.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = @"arrayIndex is equal to or greater than the length of array." +#endif + )] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { JObject o = new JObject(); @@ -227,7 +250,11 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array." +#endif + )] public void GenericCollectionCopyToInsufficientArrayCapacity() { JObject o = new JObject(); @@ -319,11 +346,14 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray")] public void Parse_ShouldThrowOnUnexpectedToken() { - string json = @"[""prop""]"; - JObject.Parse(json); + ExceptionAssert.Throws("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray", + () => + { + string json = @"[""prop""]"; + JObject.Parse(json); + }); } [Test] @@ -352,15 +382,19 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Invalid property identifier character: ]. Line 3, position 9.")] public void Blog() { - JObject person = JObject.Parse(@"{ - ""name"": ""James"", - ]!#$THIS IS: BAD JSON![{}}}}] - }"); + ExceptionAssert.Throws( + "Invalid property identifier character: ]. Line 3, position 5.", + () => + { + JObject person = JObject.Parse(@"{ + ""name"": ""James"", + ]!#$THIS IS: BAD JSON![{}}}}] + }"); - // Invalid property identifier character: ]. Line 3, position 9. + // Invalid property identifier character: ]. Line 3, position 9. + }); } [Test] @@ -599,7 +633,7 @@ Parameter name: arrayIndex")] Assert.AreEqual(p4, l[1]); } -#if !PocketPC && !SILVERLIGHT && !NET20 +#if !PocketPC && !SILVERLIGHT && !NET20 && !NETFX_CORE [Test] public void PropertyChanging() { @@ -765,38 +799,50 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void IListAddBadToken() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws( + "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - l.Add(new JValue("Bad!")); + l.Add(new JValue("Bad!")); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Argument is not a JToken.")] public void IListAddBadValue() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws( + "Argument is not a JToken.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - l.Add("Bad!"); + l.Add("Bad!"); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void IListAddPropertyWithExistingName() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws( + "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - JProperty p3 = new JProperty("Test2", "II"); + JProperty p3 = new JProperty("Test2", "II"); - l.Add(p3); + l.Add(p3); + }); } [Test] @@ -887,28 +933,36 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void IListSetItemAlreadyExists() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws( + "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - JProperty p3 = new JProperty("Test3", "III"); + JProperty p3 = new JProperty("Test3", "III"); - l[0] = p3; - l[1] = p3; + l[0] = p3; + l[1] = p3; + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void IListSetItemInvalid() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws( + @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - l[0] = new JValue(true); + l[0] = new JValue(true); + }); } [Test] @@ -995,39 +1049,48 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void GenericListJTokenAddBadToken() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - l.Add(new JValue("Bad!")); + l.Add(new JValue("Bad!")); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] public void GenericListJTokenAddBadValue() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - // string is implicitly converted to JValue - l.Add("Bad!"); + // string is implicitly converted to JValue + l.Add("Bad!"); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void GenericListJTokenAddPropertyWithExistingName() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws("Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - JProperty p3 = new JProperty("Test2", "II"); + JProperty p3 = new JProperty("Test2", "II"); - l.Add(p3); + l.Add(p3); + }); } [Test] @@ -1111,20 +1174,23 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")] public void GenericListJTokenSetItemAlreadyExists() { - JProperty p1 = new JProperty("Test1", 1); - JProperty p2 = new JProperty("Test2", "Two"); - IList l = new JObject(p1, p2); + ExceptionAssert.Throws("Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", + () => + { + JProperty p1 = new JProperty("Test1", 1); + JProperty p2 = new JProperty("Test2", "Two"); + IList l = new JObject(p1, p2); - JProperty p3 = new JProperty("Test3", "III"); + JProperty p3 = new JProperty("Test3", "III"); - l[0] = p3; - l[1] = p3; + l[0] = p3; + l[1] = p3; + }); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void IBindingListSortDirection() { @@ -1405,11 +1471,14 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Set JObject values with invalid key value: 0. Object property name expected.")] public void SetValueWithInvalidPropertyName() { - JObject o = new JObject(); - o[0] = new JValue(3); + ExceptionAssert.Throws("Set JObject values with invalid key value: 0. Object property name expected.", + () => + { + JObject o = new JObject(); + o[0] = new JValue(3); + }); } [Test] @@ -1437,6 +1506,7 @@ Parameter name: arrayIndex")] Assert.AreEqual("Name2", value); } +#if !NETFX_CORE [Test] public void WriteObjectNullDBNullValue() { @@ -1454,51 +1524,64 @@ Parameter name: arrayIndex")] ""title"": null }", output); } +#endif [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")] public void InvalidValueCastExceptionMessage() { - string json = @"{ + ExceptionAssert.Throws("Can not convert Object to String.", + () => + { + string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; - JObject o = JObject.Parse(json); + JObject o = JObject.Parse(json); - string name = (string)o["responseData"]; + string name = (string)o["responseData"]; + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")] public void InvalidPropertyValueCastExceptionMessage() { - string json = @"{ + ExceptionAssert.Throws("Can not convert Object to String.", + () => + { + string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; - JObject o = JObject.Parse(json); + JObject o = JObject.Parse(json); - string name = (string)o.Property("responseData"); + string name = (string)o.Property("responseData"); + }); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "JSON integer 307953220000517141511 is too large or small for an Int64.")] public void NumberTooBigForInt64() { - string json = @"{""code"": 307953220000517141511}"; + ExceptionAssert.Throws("JSON integer 307953220000517141511 is too large or small for an Int64.", + () => + { + string json = @"{""code"": 307953220000517141511}"; - JObject.Parse(json); + JObject.Parse(json); + }); } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected end of content while loading JObject.")] public void ParseIncomplete() { - JObject.Parse("{ foo:"); + ExceptionAssert.Throws("Unexpected end of content while loading JObject.", + () => + { + JObject.Parse("{ foo:"); + }); } [Test] @@ -1531,27 +1614,30 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected end of content while loading JObject.")] public void LoadFromNestedObjectIncomplete() { - string jsonText = @"{ + ExceptionAssert.Throws("Unexpected end of content while loading JObject.", + () => + { + string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; - JsonReader reader = new JsonTextReader(new StringReader(jsonText)); - reader.Read(); - reader.Read(); - reader.Read(); - reader.Read(); - reader.Read(); + JsonReader reader = new JsonTextReader(new StringReader(jsonText)); + reader.Read(); + reader.Read(); + reader.Read(); + reader.Read(); + reader.Read(); - JToken.ReadFrom(reader); + JToken.ReadFrom(reader); + }); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void GetProperties() { @@ -1626,10 +1712,12 @@ Parameter name: arrayIndex")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 10, position 2.")] public void ParseAdditionalContent() { - string json = @"{ + ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: ,. Line 10, position 2.", + () => + { + string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, @@ -1640,7 +1728,8 @@ Parameter name: arrayIndex")] ] }, 987987"; - JObject o = JObject.Parse(json); + JObject o = JObject.Parse(json); + }); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs index 08031bed..108df02d 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs @@ -4,7 +4,13 @@ using System.ComponentModel; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; using Newtonsoft.Json.Converters; using System.IO; @@ -12,6 +18,7 @@ using System.Collections; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JPathTests : TestFixtureBase { [Test] @@ -54,14 +61,22 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = @"Unexpected character while parsing path indexer: [")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = @"Unexpected character while parsing path indexer: [" +#endif + )] public void BadCharactersInIndexer() { new JPath("Blah[[0]].Two.Three[1].Four"); } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = @"Path ended with open indexer. Expected ]")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = @"Path ended with open indexer. Expected ]" +#endif + )] public void UnclosedIndexer() { new JPath("Blah[0"); @@ -89,14 +104,22 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Empty path indexer.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Empty path indexer." +#endif + )] public void EmptyIndexer() { new JPath("[]"); } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected character while parsing path: ]")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected character while parsing path: ]" +#endif + )] public void IndexerCloseInProperty() { new JPath("]"); @@ -114,7 +137,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Unexpected character following indexer: B")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Unexpected character following indexer: B" +#endif + )] public void MissingDotAfterIndexer() { new JPath("[1]Blah"); @@ -153,7 +180,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = @"Index 1 not valid on JObject.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = @"Index 1 not valid on JObject." +#endif + )] public void EvaluateIndexerOnObjectWithError() { JObject o = new JObject( @@ -172,7 +203,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = @"Property 'BlahBlah' not valid on JArray.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = @"Property 'BlahBlah' not valid on JArray." +#endif + )] public void EvaluatePropertyOnArrayWithError() { JArray a = new JArray(1, 2, 3, 4, 5); @@ -181,7 +216,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(IndexOutOfRangeException), ExpectedMessage = @"Index 1 outside the bounds of JConstructor.")] + [ExpectedException(typeof(IndexOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = @"Index 1 outside the bounds of JConstructor." +#endif + )] public void EvaluateConstructorOutOfBoundsIndxerWithError() { JConstructor c = new JConstructor("Blah"); @@ -190,7 +229,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Property 'Missing' does not exist on JObject.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Property 'Missing' does not exist on JObject." +#endif + )] public void EvaluateMissingPropertyWithError() { JObject o = new JObject( @@ -209,7 +252,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(IndexOutOfRangeException), ExpectedMessage = "Index 1000 outside the bounds of JArray.")] + [ExpectedException(typeof(IndexOutOfRangeException) +#if !NETFX_CORE + , ExpectedMessage = "Index 1000 outside the bounds of JArray." +#endif + )] public void EvaluateArrayOutOfBoundsIndxerWithError() { JArray a = new JArray(1, 2, 3, 4, 5); @@ -277,7 +324,7 @@ namespace Newtonsoft.Json.Tests.Linq ]"); JValue v = (JValue)a.SelectToken("[1].Property2[1][0]"); - Assert.AreEqual(1, v.Value); + Assert.AreEqual(1L, v.Value); } diff --git a/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs index b389cc0e..a1881965 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs @@ -5,11 +5,18 @@ using System.ComponentModel; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using System.IO; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JPropertyTests : TestFixtureBase { [Test] @@ -26,7 +33,7 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(p, p.Value.Parent); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void ListChanged() { @@ -59,7 +66,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty." +#endif + )] public void IListClear() { JProperty p = new JProperty("TestProperty", null); @@ -69,7 +80,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values." +#endif + )] public void IListAdd() { JProperty p = new JProperty("TestProperty", null); @@ -79,7 +94,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty." +#endif + )] public void IListRemove() { JProperty p = new JProperty("TestProperty", null); @@ -128,7 +147,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values.")] + [ExpectedException(typeof(Exception) +#if !NETFX_CORE + , ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values." +#endif + )] public void IListGenericAdd() { IList t = new JProperty("error", new List { "one", "two" }); diff --git a/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs index 8013ad17..d52d4ab1 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs @@ -2,11 +2,18 @@ using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JRawTests : TestFixtureBase { [Test] @@ -26,7 +33,7 @@ namespace Newtonsoft.Json.Tests.Linq JRaw r1 = new JRaw("raw1"); JToken r2 = r1.CloneToken(); - Assert.IsInstanceOfType(typeof(JRaw), r2); + CustomAssert.IsInstanceOfType(typeof(JRaw), r2); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenEqualityComparerTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenEqualityComparerTests.cs index ef253320..feb8c6ef 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenEqualityComparerTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenEqualityComparerTests.cs @@ -2,11 +2,18 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JTokenEqualityComparerTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs index 64136e6c..cf9194d1 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs @@ -26,7 +26,13 @@ using System; using System.Collections.Generic; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; @@ -35,6 +41,7 @@ using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JTokenReaderTest : TestFixtureBase { #if !PocketPC && !NET20 @@ -116,7 +123,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22." +#endif + )] public void ReadAsDateTimeOffsetBadString() { string json = @"{""Offset"":""blablahbla""}"; @@ -135,7 +146,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading date. Unexpected token: Boolean. Line 1, position 14.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error reading date. Unexpected token: Boolean. Line 1, position 14." +#endif + )] public void ReadAsDateTimeOffsetBoolean() { string json = @"{""Offset"":true}"; @@ -294,25 +309,28 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading bytes. Unexpected token: Integer.")] public void ReadBytesFailure() { - JObject o = - new JObject( - new JProperty("Test1", 1) - ); - - using (JTokenReader jsonReader = new JTokenReader(o)) + ExceptionAssert.Throws("Error reading bytes. Unexpected token: Integer.", + () => { - jsonReader.Read(); - Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); + JObject o = + new JObject( + new JProperty("Test1", 1) + ); - jsonReader.Read(); - Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); - Assert.AreEqual("Test1", jsonReader.Value); + using (JTokenReader jsonReader = new JTokenReader(o)) + { + jsonReader.Read(); + Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); - jsonReader.ReadAsBytes(); - } + jsonReader.Read(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test1", jsonReader.Value); + + jsonReader.ReadAsBytes(); + } + }); } public class HasBytes @@ -336,7 +354,7 @@ namespace Newtonsoft.Json.Tests.Linq var result2 = (HasBytes)JsonSerializer.Create(null) .Deserialize(jsonReader, typeof(HasBytes)); - Assert.AreEqual(new byte[] { 1, 2, 3, 4 }, result2.Bytes); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4 }, result2.Bytes); } [Test] @@ -355,7 +373,7 @@ namespace Newtonsoft.Json.Tests.Linq var result2 = (HasBytes)JsonSerializer.Create(null) .Deserialize(jsonReader, typeof(HasBytes)); - Assert.AreEqual(new byte[0], result2.Bytes); + CollectionAssert.AreEquivalent(new byte[0], result2.Bytes); } public class ReadAsBytesTestObject @@ -394,7 +412,7 @@ namespace Newtonsoft.Json.Tests.Linq TestObject newObject = (TestObject)serializer.Deserialize(nodeReader); Assert.AreEqual("Test", newObject.Name); - Assert.AreEqual(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data); + CollectionAssert.AreEquivalent(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data); } } @@ -437,7 +455,7 @@ namespace Newtonsoft.Json.Tests.Linq reader.ReadAsDecimal(); Assert.AreEqual(JsonToken.Float, reader.TokenType); Assert.AreEqual(typeof(decimal), reader.ValueType); - Assert.AreEqual(1, reader.Value); + Assert.AreEqual(1m, reader.Value); } [Test] @@ -462,7 +480,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to integer: hi. Line 1, position 12.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Could not convert string to integer: hi. Line 1, position 12." +#endif + )] public void ReadAsInt32BadString() { string json = @"{""Name"":""hi""}"; @@ -484,7 +506,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading integer. Unexpected token: Boolean. Line 1, position 12.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error reading integer. Unexpected token: Boolean. Line 1, position 12." +#endif + )] public void ReadAsInt32Boolean() { string json = @"{""Name"":true}"; @@ -524,7 +550,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to decimal: blah. Line 1, position 14.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Could not convert string to decimal: blah. Line 1, position 14." +#endif + )] public void ReadAsDecimalBadString() { string json = @"{""Name"":""blah""}"; @@ -543,7 +573,11 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading decimal. Unexpected token: Boolean. Line 1, position 12.")] + [ExpectedException(typeof(JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = "Error reading decimal. Unexpected token: Boolean. Line 1, position 12." +#endif + )] public void ReadAsDecimalBoolean() { string json = @"{""Name"":true}"; diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs index f578e513..1cf69068 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs @@ -28,12 +28,19 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; using System.IO; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JTokenTests : TestFixtureBase { [Test] @@ -534,15 +541,22 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.")] public void AddPropertyToArray() { - JArray a = new JArray(); - a.Add(new JProperty("PropertyName")); + ExceptionAssert.Throws("Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.", + () => + { + JArray a = new JArray(); + a.Add(new JProperty("PropertyName")); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")] + [ExpectedException(typeof(ArgumentException) +#if !NETFX_CORE + , ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject." +#endif + )] public void AddValueToObject() { JObject o = new JObject(); @@ -690,7 +704,7 @@ namespace Newtonsoft.Json.Tests.Linq Assert.IsTrue(a.DeepEquals(a2)); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void Clone() { @@ -741,16 +755,19 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2.")] public void ParseAdditionalContent() { - string json = @"[ + ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: ,. Line 5, position 2.", + () => + { + string json = @"[ ""Small"", ""Medium"", ""Large"" ],"; - JToken.Parse(json); + JToken.Parse(json); + }); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs index a6538c30..08f28546 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs @@ -26,7 +26,13 @@ using System; using System.Collections.Generic; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; @@ -34,6 +40,7 @@ using System.Linq; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JTokenWriterTest : TestFixtureBase { [Test] @@ -63,7 +70,7 @@ namespace Newtonsoft.Json.Tests.Linq root = jsonWriter.Token; } - Assert.IsInstanceOfType(typeof(JArray), root); + CustomAssert.IsInstanceOfType(typeof(JArray), root); Assert.AreEqual(13, root.Children().Count()); Assert.AreEqual("@", (string)root[0]); Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]); diff --git a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs index df117f8c..b6373756 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs @@ -27,12 +27,19 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; using System.Globalization; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class JValueTests : TestFixtureBase { [Test] @@ -58,9 +65,11 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual("Pie", v.Value); Assert.AreEqual(JTokenType.String, v.Type); +#if !NETFX_CORE v.Value = DBNull.Value; Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); +#endif byte[] data = new byte[0]; v.Value = data; @@ -140,11 +149,14 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Cannot access child value on Newtonsoft.Json.Linq.JValue.")] public void Last() { - JValue v = new JValue(true); - JToken last = v.Last; + ExceptionAssert.Throws("Cannot access child value on Newtonsoft.Json.Linq.JValue.", + () => + { + JValue v = new JValue(true); + JToken last = v.Last; + }); } [Test] @@ -156,35 +168,47 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Cannot access child value on Newtonsoft.Json.Linq.JValue.")] public void First() { - JValue v = new JValue(true); - JToken first = v.First; + ExceptionAssert.Throws("Cannot access child value on Newtonsoft.Json.Linq.JValue.", + () => + { + JValue v = new JValue(true); + JToken first = v.First; + }); } [Test] - [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Cannot access child value on Newtonsoft.Json.Linq.JValue.")] public void Item() { - JValue v = new JValue(true); - JToken first = v[0]; + ExceptionAssert.Throws("Cannot access child value on Newtonsoft.Json.Linq.JValue.", + () => + { + JValue v = new JValue(true); + JToken first = v[0]; + }); } [Test] - [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Cannot access child value on Newtonsoft.Json.Linq.JValue.")] public void Values() { - JValue v = new JValue(true); - v.Values(); + ExceptionAssert.Throws("Cannot access child value on Newtonsoft.Json.Linq.JValue.", + () => + { + JValue v = new JValue(true); + v.Values(); + }); } [Test] - [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "The parent is missing.")] public void RemoveParentNull() { - JValue v = new JValue(true); - v.Remove(); + ExceptionAssert.Throws("The parent is missing.", + () => + { + JValue v = new JValue(true); + v.Remove(); + }); } [Test] @@ -223,33 +247,39 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Cannot set child value on Newtonsoft.Json.Linq.JValue.")] public void SetValue() { - JToken t = new JValue(5L); - t[0] = new JValue(3); + ExceptionAssert.Throws("Cannot set child value on Newtonsoft.Json.Linq.JValue.", + () => + { + JToken t = new JValue(5L); + t[0] = new JValue(3); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Null to Int32.")] public void CastNullValueToNonNullable() { - JValue v = new JValue((object)null); - int i = (int) v; + ExceptionAssert.Throws("Can not convert Null to Int32.", + () => + { + JValue v = new JValue((object)null); + int i = (int)v; + }); } [Test] public void ConvertValueToCompatibleType() { IComparable c = (new JValue(1).Value()); - Assert.AreEqual(1, c); + Assert.AreEqual(1L, c); } [Test] public void ConvertValueToFormattableType() { IFormattable f = (new JValue(1).Value()); - Assert.AreEqual(1, f); + Assert.AreEqual(1L, f); Assert.AreEqual("01", f.ToString("00", CultureInfo.InvariantCulture)); } @@ -265,9 +295,9 @@ namespace Newtonsoft.Json.Tests.Linq IList orderedValues = o.Values().Cast().OrderBy(v => v).Select(v => v.Value).ToList(); - Assert.AreEqual(1, orderedValues[0]); - Assert.AreEqual(1.1, orderedValues[1]); - Assert.AreEqual(1.2, orderedValues[2]); + Assert.AreEqual(1L, orderedValues[0]); + Assert.AreEqual(1.1m, orderedValues[1]); + Assert.AreEqual(1.2d, orderedValues[2]); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs index e717cb41..7975b6d0 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs @@ -28,7 +28,13 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; using System.Xml; using System.IO; @@ -38,6 +44,7 @@ using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Linq { + [TestFixture] public class LinqToJsonTest : TestFixtureBase { [Test] @@ -513,7 +520,7 @@ keyword such as type of business."" Assert.AreEqual(null, o["purple"]); Assert.AreEqual(null, o.Value("purple")); - Assert.IsInstanceOfType(typeof(JArray), o["channel"]["item"]); + CustomAssert.IsInstanceOfType(typeof(JArray), o["channel"]["item"]); Assert.AreEqual(2, o["channel"]["item"].Children()["title"].Count()); Assert.AreEqual(0, o["channel"]["item"].Children()["monkey"].Count()); @@ -524,27 +531,36 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Accessed JObject values with invalid key value: 0. Object property name expected.")] public void JObjectIntIndex() { - JObject o = new JObject(); - Assert.AreEqual(null, o[0]); + ExceptionAssert.Throws("Accessed JObject values with invalid key value: 0. Object property name expected.", + () => + { + JObject o = new JObject(); + Assert.AreEqual(null, o[0]); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Accessed JArray values with invalid key value: ""purple"". Array position index expected.")] public void JArrayStringIndex() { - JArray a = new JArray(); - Assert.AreEqual(null, a["purple"]); + ExceptionAssert.Throws(@"Accessed JArray values with invalid key value: ""purple"". Array position index expected.", + () => + { + JArray a = new JArray(); + Assert.AreEqual(null, a["purple"]); + }); } [Test] - [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Accessed JConstructor values with invalid key value: ""purple"". Argument position index expected.")] public void JConstructorStringIndex() { - JConstructor c = new JConstructor("ConstructorValue"); - Assert.AreEqual(null, c["purple"]); + ExceptionAssert.Throws(@"Accessed JConstructor values with invalid key value: ""purple"". Argument position index expected.", + () => + { + JConstructor c = new JConstructor("ConstructorValue"); + Assert.AreEqual(null, c["purple"]); + }); } #if !PocketPC && !NET20 @@ -628,13 +644,13 @@ keyword such as type of business."" }); Console.WriteLine(o.ToString()); - Assert.IsInstanceOfType(typeof(JObject), o); - Assert.IsInstanceOfType(typeof(JObject), o["channel"]); + CustomAssert.IsInstanceOfType(typeof(JObject), o); + CustomAssert.IsInstanceOfType(typeof(JObject), o["channel"]); Assert.AreEqual("James Newton-King", (string)o["channel"]["title"]); Assert.AreEqual(2, o["channel"]["item"].Children().Count()); JArray a = JArray.FromObject(new List() { 0, 1, 2, 3, 4 }); - Assert.IsInstanceOfType(typeof(JArray), a); + CustomAssert.IsInstanceOfType(typeof(JArray), a); Assert.AreEqual(5, a.Count()); } @@ -665,13 +681,13 @@ keyword such as type of business."" }); Console.WriteLine(o.ToString()); - Assert.IsInstanceOfType(typeof(JObject), o); - Assert.IsInstanceOfType(typeof(JObject), o["channel"]); + CustomAssert.IsInstanceOfType(typeof(JObject), o); + CustomAssert.IsInstanceOfType(typeof(JObject), o["channel"]); Assert.AreEqual("James Newton-King", (string)o["channel"]["title"]); Assert.AreEqual(2, o["channel"]["item"].Children().Count()); JArray a = JArray.FromObject(new List() { 0, 1, 2, 3, 4 }); - Assert.IsInstanceOfType(typeof(JArray), a); + CustomAssert.IsInstanceOfType(typeof(JArray), a); Assert.AreEqual(5, a.Count()); } diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj new file mode 100644 index 00000000..31b40504 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj @@ -0,0 +1,320 @@ + + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {8D9C2E69-9FD7-4A7A-866C-739C9207CD0B} + Library + Properties + Newtonsoft.Json.Tests + Newtonsoft.Json.Tests + en-US + 512 + {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + Newtonsoft.Json.Tests.Metro_TemporaryKey.pfx + E58487D6BF8E40BC44C9BE962D19FB3EFBEB81BD + + + true + full + false + bin\Debug\ + DEBUG;TRACE;NETFX_CORE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE;NETFX_CORE + prompt + 4 + + + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE + ;2008 + full + ARM + false + prompt + ExpressRules.ruleset + true + + + bin\ARM\Release\ + TRACE;NETFX_CORE + true + ;2008 + pdbonly + ARM + false + prompt + ExpressRules.ruleset + true + + + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE + ;2008 + full + x64 + false + prompt + ExpressRules.ruleset + true + + + bin\x64\Release\ + TRACE;NETFX_CORE + true + ;2008 + pdbonly + x64 + false + prompt + ExpressRules.ruleset + true + + + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE + ;2008 + full + x86 + false + prompt + ExpressRules.ruleset + true + + + bin\x86\Release\ + TRACE;NETFX_CORE + true + ;2008 + pdbonly + x86 + false + prompt + ExpressRules.ruleset + true + + + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Designer + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + {263136a2-b89b-424e-a87a-f988caa8d032} + Newtonsoft.Json.Metro + + + + + + + 11.0 + + + + \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro_TemporaryKey.pfx b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro_TemporaryKey.pfx new file mode 100644 index 0000000000000000000000000000000000000000..75e05db9a4357d11a7ace246383960ecccea6904 GIT binary patch literal 2460 zcmY+Ec|6qX7stQD7>#6UxJ)vZ$Tq`_WvtmLgzOYk##Uq*WkT6ThOyOTNnB;U%F;HB zB-)InkYvq>$kL4%UE4Ie_uGB_e)qoa>%7kMob&#ibDrm~gQdWW_#pgP3fvn8SEnAK zZtj5yLdqy`J17Ni17Zs-MS%MsN#F~VBCr7BSUhv^v3P~+nh9Dq`wW4jHArz*O%=(jc!O~%h8_;U$YY*$X;#J^9yjZ{!~ ziPjai#<;qe5WVeWG>dovLJ^sFz8Z)5cgCJ?Q>54Awr9Vziht0nbbqpVhxF-$n-a~E zJ8~stSmdyW$eM@GH_h24cOuRE48O6*M~MVoYF*BNXYVpEL&j};I(^~A5=P3N`xTX_ z>qyt@pT{VALG`Ua59N||s%xL^8gP(qKZYyeDBFFF6?;BXXKuK~7K|Uh(;-7^ioXVRmdS0a_LYX?&v>-4RCknFj3eeoVaxs3m~js93=SWuo59T#L1o<*qqSRGVx za^hA{LcWSmR8o?|J>zy9@i!jK?HP(KrIP3zz7*GZY7Wt;AvMN3F)u7_Cu`?!Az8{G zzEjTF7=@p9KAzt#;NJGl{%ufsMz7r0v>2CSe3H|5M?F3Ar9dZ@^|!r-Vmq&@>TA~9 zy+>EKVY?!rL1>*P;q%4RF5~Cqp_yR15#hoLo~xHHpADcYvXETuGC%fcfot98^eX9@ zoP0ym-;F;gJfhM_(Rl+Fi?Xc#mS&>aS@o3A+71TVIwhX?QozWXHmDj#vqIpZVBzM) z!dbq750fc63J5g)UlUl?L44Adxtfjn18ucAf{y z8+&r_9A{Jn+i(C#e3M-_Fkbt|f)3(HUGK8{#-gJC%HWHoEb+659;Vg_vqv(z&6&5& z-Dka}m=3hnrO?#tQM=tF;nLSRg|j~O4Si4damXbl_Z{N)XsmF_0g=`mqovX+BfoPg zW)hnX6(h>gTTk=j&=Y^cc#{SJLuwGqU{0#lw@clA)Z$YDb<7ZH&O&Fs?oU5R*MXiMa&E=%YJF4^(n{_RY9f*5V#6g0%yR{9@E$!&Ehq5aoi zYu7eq5g&-T3)ZWQ8JSWS8GI&6+nKNS0>LYt2!^WD_l8y(P9#d^1EZ3ahgjl2?x{IV-7 zPh4rQ@+x_RO{0Ftew@<}=XsbE7x$O6h?WK}er1bTcBJCd3N@0N*Yq#6L}Jm^^@|Jf zX?NlM8^>^-eF)CVG%lqNi}+_z!0M_eYD1oy_9Rd773jp*09B8_rV}Kx# z7y@`O`kCWE4FeECs{MDQ4XQez>w`5!AQ038K~BW_!QdJ&2oyrm7l+`Ep_~9m;0!o8 z8i)kWfgTK;2jl@a@cc<4fDkaV0^>L!3S^OB9t{qS0#5(kB@Z0?yN(QIf#B28SPH+{ zKR*|Ql~MSyAVTv&0Ps@&SAqOz<->li{Q8ae%6RiSnV%~^nZmb~aBOPztgy3GQGz_p z?xBn(eQaUB|L{m+xCrO*ru{=qH7^zGd)#7BX~;Xmz%@=j-A-VSL0P?B$2J9WQ{(dU zIMf?0>|t0fk@SK%+X0ac}9`!OiRO-w{9QhrF^ z{jo*Z%jdc-M@|hC4h|KNlyZDccN;OA#IB1!QJ_ZPZ@+GI9A9r*uMe6#A!r>wwutn~ zTa*=|f4h%qdG?gp*0_0fF17E?1q5a$rD3qi(S{~rc-oBiXua1tOlqB>C##mhetVGq zZ2#>La%BdopcrGa&*JMFe$ffSS&>z)6m}?^rquYddq8Y0YITRDAwE7Y!(>7aT*O%i zMhJ*(_I90T?}SyCgd^1s@wkxWt%@Vj1O=xN6rQ2jQX#*ME-|w)MjNt%tQJR`7^$SB zo7#lE-C1k5D`T!)jES7j5Zz%v_b;VS?ErDdYprFP11`l3ghrs-Vk@rj5cT}w56Kp> z<+A75$zE+lY0uCpmX?%EkB!`pb;Wd&C`8BhGRC1hr>Edx&G^c!7t3^P`vB?3QCp{1 zjJryrc-zH2@Ail{9!hoTJ-6F z_bR@h)efW_?^2$y--=VOpHJ1t9nNTX#8vef|HiKi4+-|uH`2Sc*GlbJsI;2DYD8&L znq@MdOald_k22N8F^96MKO9tJcwC-fRMO!W8ghku$8+7f&o$HS7e+>=1<|JG?`$X3 zsCx7xoof&7BMD}j_iT+BBb`71st-FzBDeI07!$$A`{zd)`EoFT|P&Ls++ z7aJxHCSQdYG`^N|C+7v7{PBJuc+2Du)9Psp-`$K~FF1Vbky4#2r!j^lE}0{qsK$y1 zo0|--)YeaDCB{ZBUw-Su!e + + + + + + UnitTestProject1 + James + Images\UnitTestStoreLogo.png + UnitTestProject1 + + + + 6.2 + 6.2 + + + + + + + + + + + + + + + + + + + + + diff --git a/Src/Newtonsoft.Json.Tests/PerformanceTests.cs b/Src/Newtonsoft.Json.Tests/PerformanceTests.cs index 268fe13c..1a90f5cf 100644 --- a/Src/Newtonsoft.Json.Tests/PerformanceTests.cs +++ b/Src/Newtonsoft.Json.Tests/PerformanceTests.cs @@ -1,4 +1,4 @@ -#if !SILVERLIGHT && !PocketPC && !NET20 && !NET35 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NET35 && !NETFX_CORE using System; using System.Collections.Generic; using System.Globalization; @@ -37,12 +37,13 @@ namespace Newtonsoft.Json.Tests public byte[] Data { get; set; } } + [TestFixture] public class PerformanceTests : TestFixtureBase { //private const int Iterations = 100; private const int Iterations = 5000; - #region Data +#region Data private const string BsonHex = @"A9-01-00-00-04-73-74-72-69-6E-67-73-00-2B-00-00-00-0A-30-00-02-31-00-19-00-00-00-4D-61-72-6B-75-73-20-65-67-67-65-72-20-5D-3E-3C-5B-2C-20-28-32-6E-64-29-00-0A-32-00-00-03-64-69-63-74-69-6F-6E-61-72-79-00-37-00-00-00-10-56-61-6C-20-26-20-61-73-64-31-00-01-00-00-00-10-56-61-6C-32-20-26-20-61-73-64-31-00-03-00-00-00-10-56-61-6C-33-20-26-20-61-73-64-31-00-04-00-00-00-00-02-4E-61-6D-65-00-05-00-00-00-52-69-63-6B-00-09-4E-6F-77-00-EF-BD-69-EC-25-01-00-00-01-42-69-67-4E-75-6D-62-65-72-00-E7-7B-CC-26-96-C7-1F-42-03-41-64-64-72-65-73-73-31-00-47-00-00-00-02-53-74-72-65-65-74-00-0B-00-00-00-66-66-66-20-53-74-72-65-65-74-00-02-50-68-6F-6E-65-00-0F-00-00-00-28-35-30-33-29-20-38-31-34-2D-36-33-33-35-00-09-45-6E-74-65-72-65-64-00-6F-FF-31-53-26-01-00-00-00-04-41-64-64-72-65-73-73-65-73-00-A2-00-00-00-03-30-00-4B-00-00-00-02-53-74-72-65-65-74-00-0F-00-00-00-1F-61-72-72-61-79-3C-61-64-64-72-65-73-73-00-02-50-68-6F-6E-65-00-0F-00-00-00-28-35-30-33-29-20-38-31-34-2D-36-33-33-35-00-09-45-6E-74-65-72-65-64-00-6F-73-0C-E7-25-01-00-00-00-03-31-00-4C-00-00-00-02-53-74-72-65-65-74-00-10-00-00-00-61-72-72-61-79-20-32-20-61-64-64-72-65-73-73-00-02-50-68-6F-6E-65-00-0F-00-00-00-28-35-30-33-29-20-38-31-34-2D-36-33-33-35-00-09-45-6E-74-65-72-65-64-00-6F-17-E6-E1-25-01-00-00-00-00-00"; @@ -339,7 +340,7 @@ namespace Newtonsoft.Json.Tests Console.WriteLine("BinaryFormatter size: {0} bytes", binaryFormatterBytes.Length); } - #region Serialize +#region Serialize private static readonly byte[] Buffer = new byte[4096]; @@ -524,7 +525,7 @@ namespace Newtonsoft.Json.Tests #endregion - #region Deserialize +#region Deserialize public void BenchmarkDeserializeMethod(SerializeMethod method, object json) { @@ -751,7 +752,7 @@ namespace Newtonsoft.Json.Tests public int Integer { get; set; } } - #region Classes +#region Classes [Serializable] [DataContract] diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index 1646871c..c6bc0562 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -72,5 +72,5 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.0.8.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.0.8.14710")] +[assembly: AssemblyFileVersion("4.0.8.14715")] #endif diff --git a/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs b/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs index 36e042ab..586f7931 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs @@ -27,17 +27,24 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Schema; using Newtonsoft.Json.Linq; using System.IO; using Newtonsoft.Json.Tests.TestObjects; -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) using System.Data; #endif namespace Newtonsoft.Json.Tests.Schema { + [TestFixture] public class ExtensionsTests : TestFixtureBase { [Test] @@ -77,12 +84,15 @@ namespace Newtonsoft.Json.Tests.Schema } [Test] - [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = @"String 'pie' does not match regex pattern 'lol'.")] public void ValidateWithOutEventHandlerFailure() { - JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}"); - JToken stringToken = JToken.FromObject("pie"); - stringToken.Validate(schema); + ExceptionAssert.Throws(@"String 'pie' does not match regex pattern 'lol'.", + () => + { + JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}"); + JToken stringToken = JToken.FromObject("pie"); + stringToken.Validate(schema); + }); } [Test] @@ -194,7 +204,7 @@ namespace Newtonsoft.Json.Tests.Schema #if !NET20 && !PocketPC GenerateSchemaAndSerializeFromType(new NullableDateTimeTestClass()); #endif -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) GenerateSchemaAndSerializeFromType(new DataSet()); #endif GenerateSchemaAndSerializeFromType(new object()); @@ -202,7 +212,9 @@ namespace Newtonsoft.Json.Tests.Schema GenerateSchemaAndSerializeFromType("Hi"); GenerateSchemaAndSerializeFromType(new DateTime(2000, 12, 29, 23, 59, 0, DateTimeKind.Utc)); GenerateSchemaAndSerializeFromType(TimeSpan.FromTicks(1000000)); +#if !NETFX_CORE GenerateSchemaAndSerializeFromType(DBNull.Value); +#endif GenerateSchemaAndSerializeFromType(new JsonPropertyWithHandlingValues()); } @@ -227,62 +239,77 @@ namespace Newtonsoft.Json.Tests.Schema } [Test] - [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Integer 10 equals maximum value of 10 and exclusive maximum is true.")] public void ExclusiveMaximum_Int() { - JsonSchema schema = new JsonSchema(); - schema.Maximum = 10; - schema.ExclusiveMaximum = true; + ExceptionAssert.Throws("Integer 10 equals maximum value of 10 and exclusive maximum is true.", + () => + { + JsonSchema schema = new JsonSchema(); + schema.Maximum = 10; + schema.ExclusiveMaximum = true; - JValue v = new JValue(10); - v.Validate(schema); + JValue v = new JValue(10); + v.Validate(schema); + }); } [Test] - [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.")] public void ExclusiveMaximum_Float() { - JsonSchema schema = new JsonSchema(); - schema.Maximum = 10.1; - schema.ExclusiveMaximum = true; + ExceptionAssert.Throws("Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.", + () => + { + JsonSchema schema = new JsonSchema(); + schema.Maximum = 10.1; + schema.ExclusiveMaximum = true; - JValue v = new JValue(10.1); - v.Validate(schema); + JValue v = new JValue(10.1); + v.Validate(schema); + }); } [Test] - [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Integer 10 equals minimum value of 10 and exclusive minimum is true.")] public void ExclusiveMinimum_Int() { - JsonSchema schema = new JsonSchema(); - schema.Minimum = 10; - schema.ExclusiveMinimum = true; + ExceptionAssert.Throws("Integer 10 equals minimum value of 10 and exclusive minimum is true.", + () => + { + JsonSchema schema = new JsonSchema(); + schema.Minimum = 10; + schema.ExclusiveMinimum = true; - JValue v = new JValue(10); - v.Validate(schema); + JValue v = new JValue(10); + v.Validate(schema); + }); } [Test] - [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.")] public void ExclusiveMinimum_Float() { - JsonSchema schema = new JsonSchema(); - schema.Minimum = 10.1; - schema.ExclusiveMinimum = true; + ExceptionAssert.Throws("Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.", + () => + { + JsonSchema schema = new JsonSchema(); + schema.Minimum = 10.1; + schema.ExclusiveMinimum = true; - JValue v = new JValue(10.1); - v.Validate(schema); + JValue v = new JValue(10.1); + v.Validate(schema); + }); } [Test] - [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Integer 10 is not evenly divisible by 3.")] public void DivisibleBy_Int() { - JsonSchema schema = new JsonSchema(); - schema.DivisibleBy = 3; + ExceptionAssert.Throws("Integer 10 is not evenly divisible by 3.", + () => + { + JsonSchema schema = new JsonSchema(); + schema.DivisibleBy = 3; - JValue v = new JValue(10); - v.Validate(schema); + JValue v = new JValue(10); + v.Validate(schema); + }); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs index 826f74f4..97912867 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs @@ -27,13 +27,20 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Schema; using System.IO; using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Schema { + [TestFixture] public class JsonSchemaBuilderTests : TestFixtureBase { [Test] @@ -435,18 +442,21 @@ namespace Newtonsoft.Json.Tests.Schema } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = @"Could not resolve schema reference for Id 'MyUnresolvedReference'.")] public void UnresolvedReference() { - string json = @"{ + ExceptionAssert.Throws(@"Could not resolve schema reference for Id 'MyUnresolvedReference'.", + () => + { + string json = @"{ ""id"":""CircularReferenceArray"", ""description"":""CircularReference"", ""type"":[""array""], ""items"":{""$ref"":""MyUnresolvedReference""} }"; - JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); - JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json))); + JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); + JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json))); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs index 9080aea2..1e29588e 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs @@ -31,7 +31,13 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Schema; using System.IO; using System.Linq; @@ -41,6 +47,7 @@ using Extensions=Newtonsoft.Json.Schema.Extensions; namespace Newtonsoft.Json.Tests.Schema { + [TestFixture] public class JsonSchemaGeneratorTests : TestFixtureBase { [Test] @@ -79,7 +86,7 @@ namespace Newtonsoft.Json.Tests.Schema Assert.IsTrue(o.IsValid(schema)); } -#if !PocketPC +#if !PocketPC && !NETFX_CORE [Test] public void Generate_DefaultValueAttributeTestClass() { @@ -267,11 +274,14 @@ namespace Newtonsoft.Json.Tests.Schema } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.")] public void CircularReferenceError() { - JsonSchemaGenerator generator = new JsonSchemaGenerator(); - generator.Generate(typeof(CircularReferenceClass)); + ExceptionAssert.Throws(@"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.", + () => + { + JsonSchemaGenerator generator = new JsonSchemaGenerator(); + generator.Generate(typeof(CircularReferenceClass)); + }); } [Test] @@ -317,7 +327,7 @@ namespace Newtonsoft.Json.Tests.Schema Assert.IsTrue(v.IsValid(schema)); } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE [Test] public void GenerateSchemaForISerializable() { @@ -332,6 +342,7 @@ namespace Newtonsoft.Json.Tests.Schema } #endif +#if !NETFX_CORE [Test] public void GenerateSchemaForDBNull() { @@ -461,6 +472,7 @@ namespace Newtonsoft.Json.Tests.Schema Assert.AreEqual(0, errors.Count); } +#endif [Test] public void GenerateSchemaCamelCase() diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs index ae2e01aa..accc5ed2 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs @@ -29,10 +29,17 @@ using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json.Schema; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Schema { + [TestFixture] public class JsonSchemaModelBuilderTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs index d5a8de12..35542bcb 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs @@ -28,10 +28,17 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Schema; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Schema { + [TestFixture] public class JsonSchemaNodeTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs index 959560b1..89f26e7a 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs @@ -29,10 +29,17 @@ using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json.Schema; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Schema { + [TestFixture] public class JsonSchemaTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs index e59bc4e1..d3b0d507 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs @@ -28,7 +28,13 @@ using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Serialization; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Linq; using System.Reflection; @@ -36,6 +42,7 @@ using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase { [Test] @@ -97,6 +104,7 @@ namespace Newtonsoft.Json.Tests.Serialization string json = o.ToString(); } +#if !NETFX_CORE [Test] public void MemberSearchFlags() { @@ -128,6 +136,7 @@ namespace Newtonsoft.Json.Tests.Serialization // readonly Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass)); } +#endif [Test] public void BlogPostExample() diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs index 1d48a81b..350b6ab3 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs @@ -1,9 +1,16 @@ using System.Reflection; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class ConstructorHandlingTests : TestFixtureBase { [Test] @@ -31,12 +38,16 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(TargetInvocationException))] public void FailWithPrivateConstructorPlusParametizedAndDefault() { - string json = @"{Name:""Name!""}"; + ExceptionAssert.Throws( + null, + () => + { + string json = @"{Name:""Name!""}"; - PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject(json); + PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject(json); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs index 178e105d..000c85e4 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs @@ -2,10 +2,18 @@ using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using System.Reflection; +using Newtonsoft.Json.Utilities; +using System.Globalization; namespace Newtonsoft.Json.Tests.Serialization { @@ -50,8 +58,18 @@ namespace Newtonsoft.Json.Tests.Serialization } } + [TestFixture] public class ContractResolverTests : TestFixtureBase { + [Test] + public void ResolveProperties_IgnoreStatic() + { + var resolver = new DefaultContractResolver(); + var contract = (JsonObjectContract)resolver.ResolveContract(typeof(NumberFormatInfo)); + + Assert.IsFalse(contract.Properties.Any(c => c.PropertyName == "InvariantInfo")); + } + [Test] public void SerializeInterface() { @@ -115,6 +133,7 @@ namespace Newtonsoft.Json.Tests.Serialization }", startingWithB); } +#if !NETFX_CORE [Test] public void SerializeCompilerGeneratedMembers() { @@ -159,5 +178,6 @@ namespace Newtonsoft.Json.Tests.Serialization ""IntProperty"": 2 }", includeCompilerGeneratedJson); } +#endif } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs index 4c90247a..8788a9a0 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs @@ -4,10 +4,17 @@ using System.ComponentModel; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class DefaultValueHandlingTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs index b54690c2..b87450b9 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs @@ -11,10 +11,17 @@ using System.Text; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class DynamicTests : TestFixtureBase { public class DynamicChildObject @@ -129,12 +136,6 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual(dynamicObject.ChildObject.Text, d.ChildObject.Text); } - [Test] - public void sdfsdf() - { - ErrorSettingDynamicObject d = JsonConvert.DeserializeObject("{'hi':5}"); - } - [Test] public void SerializeDynamicObjectWithObjectTracking() { @@ -175,26 +176,29 @@ namespace Newtonsoft.Json.Tests.Serialization TypeNameAssemblyFormat = FormatterAssemblyStyle.Full }); - Assert.IsInstanceOfType(typeof(ExpandoObject), n); + CustomAssert.IsInstanceOfType(typeof(ExpandoObject), n); Assert.AreEqual("Text!", n.Text); Assert.AreEqual(int.MaxValue, n.Integer); - Assert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject); + CustomAssert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject); Assert.AreEqual("Child text!", n.DynamicChildObject.Text); Assert.AreEqual(int.MinValue, n.DynamicChildObject.Integer); } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.")] public void NoPublicDefaultConstructor() { - var settings = new JsonSerializerSettings(); - settings.NullValueHandling = NullValueHandling.Ignore; - var json = @"{ + ExceptionAssert.Throws("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.", + () => + { + var settings = new JsonSerializerSettings(); + settings.NullValueHandling = NullValueHandling.Ignore; + var json = @"{ ""contributors"": null }"; - - JsonConvert.DeserializeObject(json, settings); + + JsonConvert.DeserializeObject(json, settings); + }); } public class DictionaryDynamicObject : DynamicObject diff --git a/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs index a391ff02..48d2a103 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs @@ -23,17 +23,24 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || SILVERLIGHT) +#if !(NET35 || NET20 || SILVERLIGHT || NETFX_CORE) using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Newtonsoft.Json.Converters; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class EntitiesSerializationTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonPropertyCollectionTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonPropertyCollectionTests.cs index b2a67827..6ab0df56 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonPropertyCollectionTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonPropertyCollectionTests.cs @@ -27,12 +27,19 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class JsonPropertyCollectionTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 0f7f7ff6..e8f1a894 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -28,7 +28,7 @@ using System; using System.Collections.Concurrent; #endif using System.Collections.Generic; -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE using System.ComponentModel.DataAnnotations; using System.Configuration; using System.Runtime.CompilerServices; @@ -37,7 +37,13 @@ using System.Threading; using System.Web.Script.Serialization; #endif using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json; using System.IO; using System.Collections; @@ -69,6 +75,7 @@ using System.ComponentModel; namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class JsonSerializerTest : TestFixtureBase { [Test] @@ -112,7 +119,7 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual("Apple", deserializedProduct.Name); Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProduct.ExpiryDate); - Assert.AreEqual(3.99, deserializedProduct.Price); + Assert.AreEqual(3.99m, deserializedProduct.Price); Assert.AreEqual("Small", deserializedProduct.Sizes[0]); Assert.AreEqual("Medium", deserializedProduct.Sizes[1]); Assert.AreEqual("Large", deserializedProduct.Sizes[2]); @@ -145,7 +152,7 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual("Orange", p.Name); Assert.AreEqual(new DateTime(2010, 1, 24, 12, 0, 0), p.ExpiryDate); - Assert.AreEqual(3.99, p.Price); + Assert.AreEqual(3.99m, p.Price); } [Test] @@ -170,11 +177,6 @@ namespace Newtonsoft.Json.Tests.Serialization DateTime deserializedDate = (DateTime) deserializedDictionary["date"]; Assert.AreEqual(dateValue, deserializedDate); - - Console.WriteLine("DeserializeJavaScriptDate"); - Console.WriteLine(jsonText); - Console.WriteLine(); - Console.WriteLine(jsonText); } [Test] @@ -192,11 +194,11 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreNotSame(executorObject, executorObject2); Assert.AreEqual(executorObject2.serverClassName, "BanSubs"); Assert.AreEqual(executorObject2.serverMethodParams.Length, 4); - Assert.Contains("101", executorObject2.serverMethodParams); + CustomAssert.Contains(executorObject2.serverMethodParams, "101"); Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB"); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void HashtableDeserialization() { @@ -381,7 +383,11 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name." +#endif + )] public void BadJsonPropertyClassSerialize() { JsonConvert.SerializeObject(new BadJsonPropertyClass()); @@ -437,7 +443,7 @@ keyword such as type of business."" { string json = @"[""vvv\/vvv\tvvv\""vvv\bvvv\nvvv\rvvv\\vvv\fvvv""]"; -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); List javaScriptSerializerResult = javaScriptSerializer.Deserialize>(json); #endif @@ -449,13 +455,17 @@ keyword such as type of business."" Assert.AreEqual(1, jsonNetResult.Count); Assert.AreEqual(dataContractResult[0], jsonNetResult[0]); -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE Assert.AreEqual(javaScriptSerializerResult[0], jsonNetResult[0]); #endif } [Test] - [ExpectedException(typeof (JsonReaderException), ExpectedMessage = @"Bad JSON escape sequence: \j. Line 1, position 7.")] + [ExpectedException(typeof (JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = @"Bad JSON escape sequence: \j. Line 1, position 7." +#endif + )] public void InvalidBackslash() { string json = @"[""vvv\jvvv""]"; @@ -669,14 +679,52 @@ keyword such as type of business."" [Test] public void SerializeConverableObjects() { - string json = JsonConvert.SerializeObject(new ConverableMembers()); + string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented); - Assert.AreEqual(@"{""String"":""string"",""Int32"":2147483647,""UInt32"":4294967295,""Byte"":255,""SByte"":127,""Short"":32767,""UShort"":65535,""Long"":9223372036854775807,""ULong"":9223372036854775807,""Double"":1.7976931348623157E+308,""Float"":3.40282347E+38,""DBNull"":null,""Bool"":true,""Char"":""\u0000""}", json); + string expected = null; +#if !NETFX_CORE + expected = @"{ + ""String"": ""string"", + ""Int32"": 2147483647, + ""UInt32"": 4294967295, + ""Byte"": 255, + ""SByte"": 127, + ""Short"": 32767, + ""UShort"": 65535, + ""Long"": 9223372036854775807, + ""ULong"": 9223372036854775807, + ""Double"": 1.7976931348623157E+308, + ""Float"": 3.40282347E+38, + ""DBNull"": null, + ""Bool"": true, + ""Char"": ""\u0000"" +}"; +#else + expected = @"{ + ""String"": ""string"", + ""Int32"": 2147483647, + ""UInt32"": 4294967295, + ""Byte"": 255, + ""SByte"": 127, + ""Short"": 32767, + ""UShort"": 65535, + ""Long"": 9223372036854775807, + ""ULong"": 9223372036854775807, + ""Double"": 1.7976931348623157E+308, + ""Float"": 3.40282347E+38, + ""Bool"": true, + ""Char"": ""\u0000"" +}"; +#endif + + Assert.AreEqual(expected, json); ConverableMembers c = JsonConvert.DeserializeObject(json); Assert.AreEqual("string", c.String); Assert.AreEqual(double.MaxValue, c.Double); +#if !NETFX_CORE Assert.AreEqual(DBNull.Value, c.DBNull); +#endif } [Test] @@ -745,7 +793,7 @@ keyword such as type of business."" Assert.AreEqual(99, c.Field); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void SerializeArrayAsArrayList() { @@ -918,11 +966,15 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "JsonConverter IsoDateTimeConverter on Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass is not compatible with member type IncompatibleJsonAttributeClass.")] public void IncompatibleJsonAttributeShouldThrow() { - IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass(); - JsonConvert.SerializeObject(c); + ExceptionAssert.Throws( + "JsonConverter IsoDateTimeConverter on Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass is not compatible with member type IncompatibleJsonAttributeClass.", + () => + { + IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass(); + JsonConvert.SerializeObject(c); + }); } [Test] @@ -1077,24 +1129,29 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Required property 'FirstName' expects a value but got null. Line 6, position 2.")] public void DeserializeRequiredMembersClassNullRequiredValueProperty() { - string json = @"{ + ExceptionAssert.Throws("Required property 'FirstName' expects a value but got null. Line 6, position 2.", + () => + { + string json = @"{ ""FirstName"": null, ""MiddleName"": null, ""LastName"": null, ""BirthDate"": ""\/Date(977309755000)\/"" }"; - JsonConvert.DeserializeObject(json); + JsonConvert.DeserializeObject(json); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Cannot write a null value for property 'FirstName'. Property requires a value.")] public void SerializeRequiredMembersClassNullRequiredValueProperty() { - RequiredMembersClass requiredMembersClass = new RequiredMembersClass + ExceptionAssert.Throws("Cannot write a null value for property 'FirstName'. Property requires a value.", + () => + { + RequiredMembersClass requiredMembersClass = new RequiredMembersClass { FirstName = null, BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc), @@ -1102,19 +1159,23 @@ keyword such as type of business."" MiddleName = null }; - string json = JsonConvert.SerializeObject(requiredMembersClass); - Console.WriteLine(json); + string json = JsonConvert.SerializeObject(requiredMembersClass); + Console.WriteLine(json); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Required property 'LastName' not found in JSON. Line 3, position 2.")] public void RequiredMembersClassMissingRequiredProperty() { - string json = @"{ + ExceptionAssert.Throws("Required property 'LastName' not found in JSON. Line 3, position 2.", + () => + { + string json = @"{ ""FirstName"": ""Bob"" }"; - JsonConvert.DeserializeObject(json); + JsonConvert.DeserializeObject(json); + }); } [Test] @@ -1193,7 +1254,11 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14." +#endif + )] public void DeserializeInterfaceProperty() { InterfacePropertyTestClass testClass = new InterfacePropertyTestClass(); @@ -1214,28 +1279,6 @@ keyword such as type of business."" return person; } - //[Test] - public void WriteJsonToFile() - { - //Person person = GetPerson(); - - //string json = JsonConvert.SerializeObject(person, Formatting.Indented); - - //File.WriteAllText(@"c:\person.json", json); - - Person person = GetPerson(); - - using (FileStream fs = System.IO.File.Open(@"c:\person.json", FileMode.CreateNew)) - using (StreamWriter sw = new StreamWriter(fs)) - using (JsonWriter jw = new JsonTextWriter(sw)) - { - jw.Formatting = Formatting.Indented; - - JsonSerializer serializer = new JsonSerializer(); - serializer.Serialize(jw, person); - } - } - [Test] public void WriteJsonDates() { @@ -1422,7 +1465,7 @@ keyword such as type of business."" Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]); } -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE [MetadataType(typeof (OptInClassMetadata))] public class OptInClass { @@ -1596,7 +1639,7 @@ keyword such as type of business."" Assert.AreEqual("Apple", deserializedProduct.Name); Assert.AreEqual(new DateTime(2008, 12, 28, 0, 0, 0, DateTimeKind.Utc), deserializedProduct.ExpiryDate); - Assert.AreEqual(3.99, deserializedProduct.Price); + Assert.AreEqual(3.99m, deserializedProduct.Price); Assert.AreEqual("Small", deserializedProduct.Sizes[0]); Assert.AreEqual("Medium", deserializedProduct.Sizes[1]); Assert.AreEqual("Large", deserializedProduct.Sizes[2]); @@ -1744,9 +1787,9 @@ keyword such as type of business."" Assert.AreEqual("Navigate", o.Method); Assert.AreEqual(3, o.Data.Length); Assert.AreEqual("dashboard", o.Data[0]); - Assert.IsInstanceOfType(typeof (JArray), o.Data[1]); + CustomAssert.IsInstanceOfType(typeof (JArray), o.Data[1]); Assert.AreEqual(4, ((JArray) o.Data[1]).Count); - Assert.IsInstanceOfType(typeof (JObject), o.Data[2]); + CustomAssert.IsInstanceOfType(typeof (JObject), o.Data[2]); Assert.AreEqual(1, ((JObject) o.Data[2]).Count); Assert.AreEqual(1, (int) ((JObject) o.Data[2])["one"]); } @@ -1865,7 +1908,11 @@ keyword such as type of business."" #endif [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Line 1, position 15.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Line 1, position 15." +#endif + )] 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)\/""}"; @@ -1905,9 +1952,13 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person'. + [ExpectedException(typeof(JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person'. The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList. -To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Line 1, position 1.")] +To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Line 1, position 1." +#endif + )] public void CannotDeserializeArrayIntoObject() { string json = @"[]"; @@ -1916,9 +1967,13 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Line } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON object (i.e. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Cannot deserialize JSON object (i.e. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List) or a dictionary type (i.e. Dictionary). -To force JSON objects to deserialize add the JsonObjectAttribute to the type. Line 1, position 2.")] +To force JSON objects to deserialize add the JsonObjectAttribute to the type. Line 1, position 2." +#endif + )] public void CannotDeserializeObjectIntoArray() { string json = @"{}"; @@ -1927,7 +1982,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1." +#endif + )] public void CannotPopulateArrayIntoObject() { string json = @"[]"; @@ -1936,7 +1995,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2." +#endif + )] public void CannotPopulateObjectIntoArray() { string json = @"{}"; @@ -1954,28 +2017,44 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'." +#endif + )] public void SerializePropertyGetError() { JsonConvert.SerializeObject(new MemoryStream()); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'." +#endif + )] public void DeserializePropertySetError() { JsonConvert.DeserializeObject("{ReadTimeout:0}"); } [Test] - [ExpectedException(typeof (JsonReaderException), ExpectedMessage = @"Could not convert string to integer: . Line 1, position 15.")] + [ExpectedException(typeof (JsonReaderException) +#if !NETFX_CORE + , ExpectedMessage = @"Could not convert string to integer: . Line 1, position 15." +#endif + )] public void DeserializeEnsureTypeEmptyStringToIntError() { JsonConvert.DeserializeObject("{ReadTimeout:''}"); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17." +#endif + )] public void DeserializeEnsureTypeNullToIntError() { JsonConvert.DeserializeObject("{ReadTimeout:null}"); @@ -2090,16 +2169,19 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Line 2, position 46.")] public void DeserializePersonKeyedDictionary() { - string json = - @"{ + ExceptionAssert.Throws("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Line 2, position 46.", + () => + { + string json = + @"{ ""Newtonsoft.Json.Tests.TestObjects.Person"": 1, ""Newtonsoft.Json.Tests.TestObjects.Person"": 2 }"; - JsonConvert.DeserializeObject>(json); + JsonConvert.DeserializeObject>(json); + }); } [Test] @@ -2355,7 +2437,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6." +#endif + )] public void DeserializeDictionaryWithNoDefaultConstructor() { string json = "{key1:'value',key2:'value',key3:'value'}"; @@ -2431,7 +2517,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li var json = "{ Key: 'abc', Value: 123 }"; var item = JsonConvert.DeserializeObject(json); - Assert.AreEqual(123, item.Value); + Assert.AreEqual(123L, item.Value); } public abstract class Animal @@ -2478,13 +2564,13 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li byte[] jsonBytes = ms.ToArray(); string json = Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length); - Console.WriteLine(JObject.Parse(json).ToString()); - Console.WriteLine(); + //Console.WriteLine(JObject.Parse(json).ToString()); + //Console.WriteLine(); - Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings - { - // TypeNameHandling = TypeNameHandling.Objects - })); + //Console.WriteLine(JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings + // { + // // TypeNameHandling = TypeNameHandling.Objects + // })); } #endif @@ -2625,7 +2711,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li Assert.AreEqual("value", newModelStateDictionary["key"]); } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE public class ISerializableTestObject : ISerializable { internal string _stringValue; @@ -3030,7 +3116,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE public class XmlNodeTestObject { public XmlDocument Document { get; set; } @@ -3068,7 +3154,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE [Test] public void SerializeDeserializeXmlNodeProperties() { @@ -3361,7 +3447,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11." +#endif + )] public void SerializeRefAdditionalContent() { //Additional text found in JSON string after finishing deserializing object. @@ -3380,22 +3470,25 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "JSON reference $ref property must have a string or null value. Line 5, position 14.")] public void SerializeRefBadType() { - //Additional text found in JSON string after finishing deserializing object. - //Test 1 - var reference = new Dictionary(); - reference.Add("$ref", 1); - reference.Add("$id", 1); + ExceptionAssert.Throws("JSON reference $ref property must have a string or null value. Line 5, position 14.", + () => + { + //Additional text found in JSON string after finishing deserializing object. + //Test 1 + var reference = new Dictionary(); + reference.Add("$ref", 1); + reference.Add("$id", 1); - var child = new Dictionary(); - child.Add("_id", 2); - child.Add("Name", "Isabell"); - child.Add("Father", reference); + var child = new Dictionary(); + child.Add("_id", 2); + child.Add("Name", "Isabell"); + child.Add("Father", reference); - var json = JsonConvert.SerializeObject(child, Formatting.Indented); - JsonConvert.DeserializeObject>(json); + var json = JsonConvert.SerializeObject(child, Formatting.Indented); + JsonConvert.DeserializeObject>(json); + }); } [Test] @@ -3810,7 +3903,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li Assert.AreEqual(0, z[1].Prop1.Length); } -#if !NET20 && !PocketPC && !SILVERLIGHT +#if !NET20 && !PocketPC && !SILVERLIGHT && !NETFX_CORE public class StringDictionaryTestClass { public StringDictionary StringDictionaryProperty { get; set; } @@ -3960,19 +4053,19 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li IDictionary newExpando = JsonConvert.DeserializeObject(json); - Assert.IsInstanceOfType(typeof (long), newExpando["Int"]); - Assert.AreEqual(expando.Int, newExpando["Int"]); + CustomAssert.IsInstanceOfType(typeof (long), newExpando["Int"]); + Assert.AreEqual((long)expando.Int, newExpando["Int"]); - Assert.IsInstanceOfType(typeof (double), newExpando["Decimal"]); + CustomAssert.IsInstanceOfType(typeof (double), newExpando["Decimal"]); Assert.AreEqual(expando.Decimal, newExpando["Decimal"]); - Assert.IsInstanceOfType(typeof (ExpandoObject), newExpando["Complex"]); + CustomAssert.IsInstanceOfType(typeof (ExpandoObject), newExpando["Complex"]); IDictionary o = (ExpandoObject) newExpando["Complex"]; - Assert.IsInstanceOfType(typeof (string), o["String"]); + CustomAssert.IsInstanceOfType(typeof (string), o["String"]); Assert.AreEqual(expando.Complex.String, o["String"]); - Assert.IsInstanceOfType(typeof (DateTime), o["DateTime"]); + CustomAssert.IsInstanceOfType(typeof (DateTime), o["DateTime"]); Assert.AreEqual(expando.Complex.DateTime, o["DateTime"]); } #endif @@ -4099,7 +4192,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li Assert.AreEqual(meh.IDontWork, "meh"); } -#if !(SILVERLIGHT || PocketPC || NET20) +#if !(SILVERLIGHT || PocketPC || NET20 || NETFX_CORE) [DataContract] public struct StructISerializable : ISerializable { @@ -4391,11 +4484,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li DeserializeStringConvert p = JsonConvert.DeserializeObject(json); Assert.AreEqual(40, p.Age); Assert.AreEqual(44.4, p.Height); - Assert.AreEqual(4d, p.Price); + Assert.AreEqual(4m, p.Price); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4." +#endif + )] public void DeserializeNullDateTimeValueTest() { JsonConvert.DeserializeObject("null", typeof (DateTime)); @@ -4901,7 +4998,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } } -#if !(SILVERLIGHT || WINDOWS_PHONE) +#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE) [Test] public void SerializeException1() { @@ -5102,7 +5199,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (Exception), ExpectedMessage = "Could not deserialize Null to KeyValuePair.")] + [ExpectedException(typeof (Exception) +#if !NETFX_CORE + , ExpectedMessage = "Could not deserialize Null to KeyValuePair." +#endif + )] public void DeserializeNullToNonNullableKeyValuePairArray() { string json = @"[ null ]"; @@ -5157,11 +5258,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li TestObject newObject = (TestObject) serializer.Deserialize(bsonReader); Assert.AreEqual("Test", newObject.Name); - Assert.AreEqual(new byte[] {72, 63, 62, 71, 92, 55}, newObject.Data); + CollectionAssert.AreEquivalent(new byte[] {72, 63, 62, 71, 92, 55}, newObject.Data); } } -#if !(SILVERLIGHT || WINDOWS_PHONE || NET20) +#if !(SILVERLIGHT || WINDOWS_PHONE || NET20 || NETFX_CORE) [Test] public void DeserializeDecimalsWithCulture() { @@ -5246,7 +5347,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.Int32'. Line 5, position 7.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "Error converting value {null} to type 'System.Int32'. Line 5, position 7." +#endif + )] public void DeserializeNullInt() { string json = @"[ @@ -5283,25 +5388,31 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading integer. Unexpected token: Boolean. Line 2, position 22.")] public void DeserializeBoolInt() { - string json = @"{ + ExceptionAssert.Throws("Error reading integer. Unexpected token: Boolean. Line 2, position 22.", + () => + { + string json = @"{ ""PreProperty"": true, ""PostProperty"": ""-1"" }"; - JsonConvert.DeserializeObject(json); + JsonConvert.DeserializeObject(json); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Unexpected end when setting PreProperty's value. Line 2, position 18.")] public void DeserializeUnexpectedEndInt() { - string json = @"{ + ExceptionAssert.Throws("Unexpected end when setting PreProperty's value. Line 2, position 18.", + () => + { + string json = @"{ ""PreProperty"": "; - JsonConvert.DeserializeObject(json); + JsonConvert.DeserializeObject(json); + }); } [Test] @@ -5349,7 +5460,8 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID); Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID); - Assert.AreEqual(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, actual.Payload); + byte[] bytes = (byte[])actual.Payload; + CollectionAssert.AreEquivalent((new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).ToList(), bytes.ToList()); } [Test] @@ -5445,21 +5557,33 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "No JSON content found and type 'System.Double' is not nullable.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "No JSON content found and type 'System.Double' is not nullable." +#endif + )] public void DeserializeDoubleFromEmptyString() { JsonConvert.DeserializeObject(""); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "No JSON content found and type 'System.StringComparison' is not nullable.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "No JSON content found and type 'System.StringComparison' is not nullable." +#endif + )] public void DeserializeEnumFromEmptyString() { JsonConvert.DeserializeObject(""); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "No JSON content found and type 'System.Int32' is not nullable.")] + [ExpectedException(typeof (JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "No JSON content found and type 'System.Int32' is not nullable." +#endif + )] public void DeserializeInt32FromEmptyString() { JsonConvert.DeserializeObject(""); @@ -5473,16 +5597,24 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (ArgumentNullException), ExpectedMessage = @"Value cannot be null. -Parameter name: value")] + [ExpectedException(typeof (ArgumentNullException) +#if !NETFX_CORE + , ExpectedMessage = @"Value cannot be null. +Parameter name: value" +#endif + )] public void DeserializeDoubleFromNullString() { JsonConvert.DeserializeObject(null); } [Test] - [ExpectedException(typeof (ArgumentNullException), ExpectedMessage = @"Value cannot be null. -Parameter name: value")] + [ExpectedException(typeof (ArgumentNullException) +#if !NETFX_CORE + , ExpectedMessage = @"Value cannot be null. +Parameter name: value" +#endif + )] public void DeserializeFromNullString() { JsonConvert.DeserializeObject(null); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs index 5cdcf339..a80f2631 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs @@ -27,14 +27,25 @@ using System; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class MissingMemberHandlingTests : TestFixtureBase { [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'. Line 4, position 11.")] + [ExpectedException(typeof(JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'. Line 4, position 11." +#endif + )] public void MissingMemberDeserialize() { Product product = new Product(); @@ -115,7 +126,11 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'. Line 1, position 11.")] + [ExpectedException(typeof(JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'. Line 1, position 11." +#endif + )] public void MissingMemeber() { string json = @"{""Missing"":1}"; diff --git a/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs index 21ed6a5f..c6b9e4fb 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs @@ -29,10 +29,17 @@ using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class NullValueHandlingTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs index f00a40a4..b79f1375 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs @@ -29,11 +29,18 @@ using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class PopulateTests : TestFixtureBase { [Test] @@ -134,10 +141,13 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Line 1, position 1.")] public void PopulateWithBadJson() { - JsonConvert.PopulateObject("1", new Person()); + ExceptionAssert.Throws("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Line 1, position 1.", + () => + { + JsonConvert.PopulateObject("1", new Person()); + }); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs index 40f52514..e6012bf4 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs @@ -30,10 +30,17 @@ using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class PreserveReferencesHandlingTests : TestFixtureBase { [Test] @@ -133,7 +140,6 @@ namespace Newtonsoft.Json.Tests.Serialization string json = JsonConvert.SerializeObject(circularList, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); - WriteEscapedJson(json); Assert.AreEqual(@"{ ""$id"": ""1"", ""$values"": [ @@ -202,7 +208,11 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot preserve reference to array or readonly list: System.String[][]. Line 3, position 15.")] + [ExpectedException(typeof(JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Cannot preserve reference to array or readonly list: System.String[][]. Line 3, position 15." +#endif + )] public void DeserializeArraysWithPreserveObjectReferences() { string json = @"{ @@ -268,7 +278,11 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unexpected end when deserializing object. Line 2, position 9.")] + [ExpectedException(typeof(JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = @"Unexpected end when deserializing object. Line 2, position 9." +#endif + )] public void UnexpectedEnd() { string json = @"{ diff --git a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs index 6532f969..5387a786 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs @@ -29,13 +29,20 @@ using System.Linq; using System.Text; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Serialization; using System.IO; using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class SerializationErrorHandlingTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs index c440f499..27a0aa4b 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs @@ -34,12 +34,20 @@ using System.Text; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Linq; using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class SerializationEventAttributeTests : TestFixtureBase { [Test] @@ -260,7 +268,7 @@ namespace Newtonsoft.Json.Tests.Serialization }", json); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE public class SerializationEventContextTestObject { public string TestMember { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs index 48af72c6..be2aeff6 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs @@ -31,7 +31,13 @@ using System.Runtime.Serialization.Formatters; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Tests.TestObjects; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Utilities; using System.Net; using System.Runtime.Serialization; @@ -39,6 +45,7 @@ using System.IO; namespace Newtonsoft.Json.Tests.Serialization { + [TestFixture] public class TypeNameHandlingTests : TestFixtureBase { public class Wrapper @@ -48,7 +55,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - public void sdfsdf() + public void SerializeWrapper() { Wrapper wrapper = new Wrapper(); wrapper.Array = new List @@ -83,8 +90,8 @@ namespace Newtonsoft.Json.Tests.Serialization }", json); Wrapper w2 = JsonConvert.DeserializeObject(json); - Assert.IsInstanceOfType(typeof(List), w2.Array); - Assert.IsInstanceOfType(typeof(Dictionary), w2.Dictionary); + CustomAssert.IsInstanceOfType(typeof(List), w2.Array); + CustomAssert.IsInstanceOfType(typeof(Dictionary), w2.Dictionary); } [Test] @@ -124,11 +131,11 @@ namespace Newtonsoft.Json.Tests.Serialization TypeNameHandling = TypeNameHandling.Objects }); - Assert.IsInstanceOfType(typeof(EmployeeReference), employee); + CustomAssert.IsInstanceOfType(typeof(EmployeeReference), employee); Assert.AreEqual("Name!", ((EmployeeReference)employee).Name); } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE [Test] public void DeserializeTypeNameFromGacAssembly() { @@ -144,7 +151,7 @@ namespace Newtonsoft.Json.Tests.Serialization TypeNameHandling = TypeNameHandling.Objects }); - Assert.IsInstanceOfType(typeof(Cookie), cookie); + CustomAssert.IsInstanceOfType(typeof(Cookie), cookie); } #endif @@ -247,7 +254,7 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.LastModified); Assert.AreEqual("String!", values[2]); - Assert.AreEqual(int.MinValue, values[3]); + Assert.AreEqual((long)int.MinValue, values[3]); } [Test] @@ -291,7 +298,11 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Line 3, position 56.")] + [ExpectedException(typeof(JsonSerializationException) +#if !NETFX_CORE + , ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Line 3, position 56." +#endif + )] public void DeserializeTypeNameOnly() { string json = @"{ @@ -354,7 +365,7 @@ namespace Newtonsoft.Json.Tests.Serialization TypeNameAssemblyFormat = FormatterAssemblyStyle.Full }); - Assert.IsInstanceOfType(typeof(SendHttpRequest), message); + CustomAssert.IsInstanceOfType(typeof(SendHttpRequest), message); SendHttpRequest request = (SendHttpRequest)message; Assert.AreEqual("xyz", request.CorrelationId); @@ -429,7 +440,7 @@ namespace Newtonsoft.Json.Tests.Serialization TypeNameProperty deserialized = JsonConvert.DeserializeObject(json); Assert.AreEqual("Name!", deserialized.Name); - Assert.IsInstanceOfType(typeof(TypeNameProperty), deserialized.Value); + CustomAssert.IsInstanceOfType(typeof(TypeNameProperty), deserialized.Value); TypeNameProperty nested = (TypeNameProperty)deserialized.Value; Assert.AreEqual("Nested!", nested.Name); @@ -465,7 +476,7 @@ namespace Newtonsoft.Json.Tests.Serialization TypeNameProperty deserialized = JsonConvert.DeserializeObject(json); Assert.AreEqual("Name!", deserialized.Name); - Assert.IsInstanceOfType(typeof(List), deserialized.Value); + CustomAssert.IsInstanceOfType(typeof(List), deserialized.Value); List nested = (List)deserialized.Value; Assert.AreEqual(5, nested.Count); @@ -491,7 +502,7 @@ namespace Newtonsoft.Json.Tests.Serialization Binder = new CustomSerializationBinder() }); - Assert.IsInstanceOfType(typeof(Person), p); + CustomAssert.IsInstanceOfType(typeof(Person), p); Person person = (Person)p; @@ -565,11 +576,11 @@ namespace Newtonsoft.Json.Tests.Serialization Binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests") }); - Assert.IsInstanceOfType(typeof(Customer), newValues[0]); + CustomAssert.IsInstanceOfType(typeof(Customer), newValues[0]); Customer customer = (Customer)newValues[0]; Assert.AreEqual("Caroline Customer", customer.Name); - Assert.IsInstanceOfType(typeof(Purchase), newValues[1]); + CustomAssert.IsInstanceOfType(typeof(Purchase), newValues[1]); Purchase purchase = (Purchase)newValues[1]; Assert.AreEqual("Elbow Grease", purchase.ProductName); } @@ -665,15 +676,15 @@ namespace Newtonsoft.Json.Tests.Serialization } Assert.IsNotNull(anotherTestObject); - Assert.IsInstanceOfType(typeof(ContentSubClass), anotherTestObject.TestMember); - Assert.IsInstanceOfType(typeof(Dictionary>), anotherTestObject.AnotherTestMember); + CustomAssert.IsInstanceOfType(typeof(ContentSubClass), anotherTestObject.TestMember); + CustomAssert.IsInstanceOfType(typeof(Dictionary>), anotherTestObject.AnotherTestMember); Assert.AreEqual(1, anotherTestObject.AnotherTestMember.Count); IList list = anotherTestObject.AnotherTestMember[1]; - Assert.IsInstanceOfType(typeof(List), list); + CustomAssert.IsInstanceOfType(typeof(List), list); Assert.AreEqual(1, list.Count); - Assert.IsInstanceOfType(typeof(ContentSubClass), list[0]); + CustomAssert.IsInstanceOfType(typeof(ContentSubClass), list[0]); } [Test] @@ -768,7 +779,7 @@ namespace Newtonsoft.Json.Tests.Serialization TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple }); - Assert.IsInstanceOfType(typeof(Dictionary), c); + CustomAssert.IsInstanceOfType(typeof(Dictionary), c); Dictionary newCollection = (Dictionary)c; Assert.AreEqual(3, newCollection.Count); @@ -888,10 +899,11 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.IsTrue(obj.Objects[0] is byte[]); - Assert.AreEqual(data, obj.Objects[0]); + byte[] d = (byte[])obj.Objects[0]; + CollectionAssert.AreEquivalent(data, d); } -#if !(WINDOWS_PHONE || SILVERLIGHT) +#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE) [Test] public void ISerializableTypeNameHandlingTest() { @@ -967,7 +979,7 @@ namespace Newtonsoft.Json.Tests.Serialization public int Quantity { get; set; } } -#if !(WINDOWS_PHONE || SILVERLIGHT) +#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE) public class SerializableWrapper { public object Content { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/SilverlightTests.cs b/Src/Newtonsoft.Json.Tests/SilverlightTests.cs index e037eed5..15756f79 100644 --- a/Src/Newtonsoft.Json.Tests/SilverlightTests.cs +++ b/Src/Newtonsoft.Json.Tests/SilverlightTests.cs @@ -1,6 +1,12 @@ using System; using System.Reflection; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif namespace Newtonsoft.Json.Tests { diff --git a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs index 0a470160..90162e9b 100644 --- a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs +++ b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs @@ -30,14 +30,31 @@ using System.IO; using System.Linq; using System.Text; using System.Threading; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using TestMethod = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Utilities; +using System.Collections; namespace Newtonsoft.Json.Tests { [TestFixture] public abstract class TestFixtureBase { + protected string GetOffset(DateTime d, DateFormatHandling dateFormatHandling) + { + StringWriter sw = new StringWriter(); + JsonConvert.WriteDateTimeOffset(sw, DateTime.SpecifyKind(d, DateTimeKind.Local).GetUtcOffset(), dateFormatHandling); + sw.Flush(); + + return sw.ToString(); + } + +#if !NETFX_CORE [SetUp] protected void TestSetup() { @@ -55,14 +72,59 @@ namespace Newtonsoft.Json.Tests { return @"@""" + json.Replace(@"""", @"""""") + @""""; } +#endif + } - protected string GetOffset(DateTime d, DateFormatHandling dateFormatHandling) + public static class Console + { + public static void WriteLine(params object[] args) { - StringWriter sw = new StringWriter(); - JsonConvert.WriteDateTimeOffset(sw, DateTime.SpecifyKind(d, DateTimeKind.Local).GetUtcOffset(), dateFormatHandling); - sw.Flush(); + } + } - return sw.ToString(); + public static class CustomAssert + { + public static void IsInstanceOfType(Type t, object instance) + { +#if !NETFX_CORE + Assert.IsInstanceOfType(t, instance); +#else + if (!instance.GetType().IsAssignableFrom(t)) + throw new Exception("Blah"); +#endif + } + + public static void Contains(IList collection, object value) + { +#if !NETFX_CORE + Assert.Contains(value, collection); +#else + if (!collection.Cast().Any(i => i.Equals(value))) + throw new Exception("Value not found in collection."); +#endif + } + } + + public static class ExceptionAssert + { + public static void Throws(string message, Action action) + where TException : Exception + { + try + { + action(); + + Assert.Fail("Exception of type {0} expected; got none exception", typeof(TException).Name); + } + catch (TException ex) + { + if (message != null) + Assert.AreEqual(message, ex.Message); + } + catch (Exception ex) + { + throw new Exception(string.Format("Exception of type {0} expected; got exception of type {1}.", typeof(TException).Name, ex.GetType().Name), ex); + } } } } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs index 9b2e1014..6e2c031f 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs @@ -41,7 +41,9 @@ namespace Newtonsoft.Json.Tests.TestObjects public ulong ULong = long.MaxValue; public double Double = double.MaxValue; public float Float = float.MaxValue; +#if !NETFX_CORE public DBNull DBNull = DBNull.Value; +#endif public bool Bool = true; public char Char = '\0'; } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/DefaultValueAttributeTestClass.cs b/Src/Newtonsoft.Json.Tests/TestObjects/DefaultValueAttributeTestClass.cs index eeefa5e3..394d2463 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/DefaultValueAttributeTestClass.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/DefaultValueAttributeTestClass.cs @@ -27,7 +27,7 @@ using System.ComponentModel; namespace Newtonsoft.Json.Tests.TestObjects { -#if !PocketPC +#if !PocketPC && !NETFX_CORE [Description("DefaultValueAttributeTestClass description!")] #endif public sealed class DefaultValueAttributeTestClass diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs index 7d0ccc3b..75769652 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.TestObjects { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Person.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Person.cs index 70176b82..91362967 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Person.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Person.cs @@ -29,7 +29,7 @@ using System.ComponentModel; namespace Newtonsoft.Json.Tests.TestObjects { [JsonObject(Id = "Person", Title = "Title!", Description = "JsonObjectAttribute description!", MemberSerialization = MemberSerialization.OptIn)] -#if !PocketPC +#if !PocketPC && !NETFX_CORE [Description("DescriptionAttribute description!")] #endif public class Person diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/SerializationEventTestList.cs b/Src/Newtonsoft.Json.Tests/TestObjects/SerializationEventTestList.cs index c21c325f..017e1bb7 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/SerializationEventTestList.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/SerializationEventTestList.cs @@ -26,7 +26,6 @@ #if !PocketPC using System.Collections.ObjectModel; using System.Runtime.Serialization; -using Newtonsoft.Json.Tests.Serialization; namespace Newtonsoft.Json.Tests.TestObjects { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs b/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs index 1c8efe8b..d9607ab7 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs @@ -27,7 +27,7 @@ using System.Collections; namespace Newtonsoft.Json.Tests.TestObjects { -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE public class TypedSubHashtable { public string Name; diff --git a/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs b/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs index 59c39b00..6da97cb5 100644 --- a/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs +++ b/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs @@ -31,67 +31,86 @@ using System.Reflection; using System.Reflection.Emit; using System.Text; using Newtonsoft.Json.Tests.Linq; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Tests.Serialization; namespace Newtonsoft.Json.Tests.Utilities { + [TestFixture] public class DynamicReflectionDelegateFactoryTests : TestFixtureBase { [Test] - [ExpectedException(typeof(InvalidCastException), ExpectedMessage = "Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.")] public void CreateGetWithBadObjectTarget() { - Person p = new Person(); - p.Name = "Hi"; + ExceptionAssert.Throws("Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.", + () => + { + Person p = new Person(); + p.Name = "Hi"; - Func setter = DynamicReflectionDelegateFactory.Instance.CreateGet(typeof(Movie).GetProperty("Name")); + Func setter = DynamicReflectionDelegateFactory.Instance.CreateGet(typeof(Movie).GetProperty("Name")); - setter(p); + setter(p); + }); } [Test] - [ExpectedException(typeof(InvalidCastException), ExpectedMessage = "Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.")] public void CreateSetWithBadObjectTarget() { - Person p = new Person(); - Movie m = new Movie(); + ExceptionAssert.Throws("Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.", + () => + { + Person p = new Person(); + Movie m = new Movie(); - Action setter = DynamicReflectionDelegateFactory.Instance.CreateSet(typeof(Movie).GetProperty("Name")); + Action setter = DynamicReflectionDelegateFactory.Instance.CreateSet(typeof(Movie).GetProperty("Name")); - setter(m, "Hi"); + setter(m, "Hi"); - Assert.AreEqual(m.Name, "Hi"); + Assert.AreEqual(m.Name, "Hi"); - setter(p, "Hi"); + setter(p, "Hi"); + }); } [Test] - [ExpectedException(typeof(InvalidCastException), ExpectedMessage = "Specified cast is not valid.")] public void CreateSetWithBadTarget() { - object structTest = new StructTest(); + ExceptionAssert.Throws("Specified cast is not valid.", + () => + { + object structTest = new StructTest(); - Action setter = DynamicReflectionDelegateFactory.Instance.CreateSet(typeof(StructTest).GetProperty("StringProperty")); + Action setter = DynamicReflectionDelegateFactory.Instance.CreateSet(typeof(StructTest).GetProperty("StringProperty")); - setter(structTest, "Hi"); + setter(structTest, "Hi"); - Assert.AreEqual("Hi", ((StructTest)structTest).StringProperty); + Assert.AreEqual("Hi", ((StructTest)structTest).StringProperty); - setter(new TimeSpan(), "Hi"); + setter(new TimeSpan(), "Hi"); + }); } [Test] - [ExpectedException(typeof(InvalidCastException), ExpectedMessage = "Unable to cast object of type 'System.Version' to type 'System.String'.")] public void CreateSetWithBadObjectValue() { - Movie m = new Movie(); + ExceptionAssert.Throws("Unable to cast object of type 'System.Version' to type 'System.String'.", + () => + { + Movie m = new Movie(); - Action setter = DynamicReflectionDelegateFactory.Instance.CreateSet(typeof(Movie).GetProperty("Name")); + Action setter = DynamicReflectionDelegateFactory.Instance.CreateSet(typeof(Movie).GetProperty("Name")); - setter(m, new Version()); + setter(m, new Version("1.1.1.1")); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Utilities/ReflectionUtilsTests.cs b/Src/Newtonsoft.Json.Tests/Utilities/ReflectionUtilsTests.cs index 9f17faf6..a4b08385 100644 --- a/Src/Newtonsoft.Json.Tests/Utilities/ReflectionUtilsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Utilities/ReflectionUtilsTests.cs @@ -3,11 +3,18 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization.Formatters; using System.Text; +#if !NETFX_CORE using NUnit.Framework; +#else +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; +using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; +#endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Utilities { + [TestFixture] public class ReflectionUtilsTests : TestFixtureBase { [Test] diff --git a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs index ff2f08c4..7b5f8ceb 100644 --- a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs @@ -31,7 +31,11 @@ namespace Newtonsoft.Json.Bson public void Close() { +#if !NETFX_CORE _writer.Close(); +#else + _writer.Dispose(); +#endif } public void WriteToken(BsonToken t) diff --git a/Src/Newtonsoft.Json/Bson/BsonReader.cs b/Src/Newtonsoft.Json/Bson/BsonReader.cs index 099e5619..2c4a7739 100644 --- a/Src/Newtonsoft.Json/Bson/BsonReader.cs +++ b/Src/Newtonsoft.Json/Bson/BsonReader.cs @@ -295,7 +295,11 @@ namespace Newtonsoft.Json.Bson base.Close(); if (CloseInput && _reader != null) +#if !NETFX_CORE _reader.Close(); +#else + _reader.Dispose(); +#endif } private bool ReadCodeWScope() diff --git a/Src/Newtonsoft.Json/Bson/BsonWriter.cs b/Src/Newtonsoft.Json/Bson/BsonWriter.cs index 09c5283c..2b311639 100644 --- a/Src/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonWriter.cs @@ -356,7 +356,13 @@ namespace Newtonsoft.Json.Bson public override void WriteValue(char value) { base.WriteValue(value); - AddToken(new BsonString(value.ToString(CultureInfo.InvariantCulture), true)); + string s = null; +#if !NETFX_CORE + s = value.ToString(CultureInfo.InvariantCulture); +#else + s = value.ToString(); +#endif + AddToken(new BsonString(s, true)); } /// diff --git a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs index 361c622b..4f39ff1a 100644 --- a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -24,7 +24,7 @@ #endregion using System; -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE using System.Data.SqlTypes; #endif using System.Globalization; @@ -70,14 +70,14 @@ namespace Newtonsoft.Json.Converters private byte[] GetByteArray(object value) { -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE if (value.GetType().AssignableToTypeName(BinaryTypeName)) { IBinary binary = DynamicWrapper.CreateWrapper(value); return binary.ToArray(); } #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE if (value is SqlBinary) return ((SqlBinary) value).Value; #endif @@ -129,7 +129,7 @@ namespace Newtonsoft.Json.Converters if (t.AssignableToTypeName(BinaryTypeName)) return Activator.CreateInstance(t, data); #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE if (t == typeof(SqlBinary)) return new SqlBinary(data); #endif @@ -173,7 +173,7 @@ namespace Newtonsoft.Json.Converters if (objectType.AssignableToTypeName(BinaryTypeName)) return true; #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?)) return true; #endif diff --git a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs index a7eb4996..de98d667 100644 --- a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs +++ b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs @@ -24,6 +24,7 @@ #endregion using System; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Converters { diff --git a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs index af97e70a..dd698d80 100644 --- a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) using System; using System.Data; using Newtonsoft.Json.Serialization; diff --git a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs index ec0de77d..6fdc07fe 100644 --- a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE using System; using System.Data; using Newtonsoft.Json.Serialization; diff --git a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs index 6dfc2878..18c37528 100644 --- a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs +++ b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !PocketPC && !SILVERLIGHT && !NET20 +#if !PocketPC && !SILVERLIGHT && !NET20 && !NETFX_CORE using System; using Newtonsoft.Json.Serialization; using System.Globalization; diff --git a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index 791da1ee..7ea57ea4 100644 --- a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -101,7 +101,7 @@ namespace Newtonsoft.Json.Converters ? Nullable.GetUnderlyingType(objectType) : objectType; - if (t.IsValueType && t.IsGenericType) + if (t.IsValueType() && t.IsGenericType()) return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)); return false; diff --git a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs index cc5d4804..137bc64e 100644 --- a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -191,7 +191,7 @@ namespace Newtonsoft.Json.Converters ? Nullable.GetUnderlyingType(objectType) : objectType; - return t.IsEnum; + return t.IsEnum(); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index e3a82960..300e5e85 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT || WINDOWS_PHONE +#if (!SILVERLIGHT || WINDOWS_PHONE) using System; using System.Collections.Generic; using System.Globalization; @@ -37,7 +37,7 @@ using System.Linq; namespace Newtonsoft.Json.Converters { #region XmlNodeWrappers -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument { private readonly XmlDocument _document; @@ -803,7 +803,7 @@ namespace Newtonsoft.Json.Converters if (value is XObject) return XContainerWrapper.WrapNode((XObject)value); #endif -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) if (value is XmlNode) return new XmlNodeWrapper((XmlNode)value); #endif @@ -1088,7 +1088,7 @@ namespace Newtonsoft.Json.Converters rootNode = document; } #endif -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) if (typeof(XmlNode).IsAssignableFrom(objectType)) { if (objectType != typeof (XmlDocument)) @@ -1242,7 +1242,11 @@ namespace Newtonsoft.Json.Converters else if (reader.TokenType == JsonToken.Date) { DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture); +#if !NETFX_CORE return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)); +#else + return XmlConvert.ToString(d); +#endif } else if (reader.TokenType == JsonToken.Null) { @@ -1531,7 +1535,7 @@ namespace Newtonsoft.Json.Converters if (typeof(XObject).IsAssignableFrom(valueType)) return true; #endif -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) if (typeof(XmlNode).IsAssignableFrom(valueType)) return true; #endif diff --git a/Src/Newtonsoft.Json/FormatterAssemblyStyle.cs b/Src/Newtonsoft.Json/FormatterAssemblyStyle.cs index 7cfff8ba..95d7dc6b 100644 --- a/Src/Newtonsoft.Json/FormatterAssemblyStyle.cs +++ b/Src/Newtonsoft.Json/FormatterAssemblyStyle.cs @@ -1,4 +1,4 @@ -#if SILVERLIGHT || PocketPC +#if SILVERLIGHT || PocketPC || NETFX_CORE namespace System.Runtime.Serialization.Formatters { /// diff --git a/Src/Newtonsoft.Json/JsonConvert.cs b/Src/Newtonsoft.Json/JsonConvert.cs index 33689def..d840564d 100644 --- a/Src/Newtonsoft.Json/JsonConvert.cs +++ b/Src/Newtonsoft.Json/JsonConvert.cs @@ -36,6 +36,9 @@ using System.Text; #if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE) using System.Xml.Linq; #endif +#if NETFX_CORE +using IConvertible = Newtonsoft.Json.Utilities.Convertible; +#endif namespace Newtonsoft.Json { @@ -480,7 +483,15 @@ namespace Newtonsoft.Json /// A JSON string representation of the . public static string ToString(Guid value) { - return '"' + value.ToString("D", CultureInfo.InvariantCulture) + '"'; + string text = null; + +#if !NETFX_CORE + text = value.ToString("D", CultureInfo.InvariantCulture); +#else + text = value.ToString("D"); +#endif + + return '"' + text + '"'; } /// @@ -537,7 +548,7 @@ namespace Newtonsoft.Json if (value == null) return Null; - IConvertible convertible = value as IConvertible; + IConvertible convertible = ConvertUtils.ToConvertible(value); if (convertible != null) { @@ -643,7 +654,7 @@ namespace Newtonsoft.Json if (type == typeof (Guid)) return true; - return IsJsonPrimitiveTypeCode(Type.GetTypeCode(type)); + return IsJsonPrimitiveTypeCode(ConvertUtils.GetTypeCode(type)); } #region Serialize @@ -1030,7 +1041,7 @@ namespace Newtonsoft.Json } #endif -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) /// /// Serializes the XML node to a JSON string. /// diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index c7fb0aa6..98ab579f 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -537,8 +537,8 @@ namespace Newtonsoft.Json if (Value != null) { string s; - if (Value is IConvertible) - s = ((IConvertible)Value).ToString(Culture); + if (ConvertUtils.IsConvertible(Value)) + s = ConvertUtils.ToConvertible(Value).ToString(Culture); else if (Value is IFormattable) s = ((IFormattable)Value).ToString(null, Culture); else diff --git a/Src/Newtonsoft.Json/JsonReaderException.cs b/Src/Newtonsoft.Json/JsonReaderException.cs index e10f39a4..71eff9cc 100644 --- a/Src/Newtonsoft.Json/JsonReaderException.cs +++ b/Src/Newtonsoft.Json/JsonReaderException.cs @@ -31,7 +31,7 @@ namespace Newtonsoft.Json /// /// The exception thrown when an error occurs while reading Json text. /// -#if (!SILVERLIGHT && !WINDOWS_PHONE) +#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE) [Serializable] #endif public class JsonReaderException : Exception @@ -83,7 +83,7 @@ namespace Newtonsoft.Json { } -#if !(WINDOWS_PHONE || SILVERLIGHT) +#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE) /// /// Initializes a new instance of the class. /// diff --git a/Src/Newtonsoft.Json/JsonSerializationException.cs b/Src/Newtonsoft.Json/JsonSerializationException.cs index 25d3a33a..8de7b10b 100644 --- a/Src/Newtonsoft.Json/JsonSerializationException.cs +++ b/Src/Newtonsoft.Json/JsonSerializationException.cs @@ -33,7 +33,7 @@ namespace Newtonsoft.Json /// /// The exception thrown when an error occurs during Json serialization or deserialization. /// -#if (!SILVERLIGHT && !WINDOWS_PHONE) +#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE) [Serializable] #endif public class JsonSerializationException : Exception @@ -66,7 +66,7 @@ namespace Newtonsoft.Json { } -#if !(WINDOWS_PHONE || SILVERLIGHT) +#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE) /// /// Initializes a new instance of the class. /// diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs index c7ffa80c..787d62a5 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.cs @@ -1497,7 +1497,11 @@ namespace Newtonsoft.Json base.Close(); if (CloseInput && _reader != null) +#if !NETFX_CORE _reader.Close(); +#else + _reader.Dispose(); +#endif if (_buffer != null) _buffer.Clear(); diff --git a/Src/Newtonsoft.Json/JsonTextWriter.cs b/Src/Newtonsoft.Json/JsonTextWriter.cs index 1859a213..a7260c68 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.cs @@ -136,7 +136,11 @@ namespace Newtonsoft.Json base.Close(); if (CloseOutput && _writer != null) +#if !NETFX_CORE _writer.Close(); +#else + _writer.Dispose(); +#endif } /// diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs index 6e7f62f5..cd3f709b 100644 --- a/Src/Newtonsoft.Json/JsonWriter.cs +++ b/Src/Newtonsoft.Json/JsonWriter.cs @@ -32,6 +32,9 @@ using System.Xml; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; using System.Globalization; +#if NETFX_CORE +using IConvertible = Newtonsoft.Json.Utilities.Convertible; +#endif namespace Newtonsoft.Json { @@ -1157,9 +1160,9 @@ namespace Newtonsoft.Json WriteNull(); return; } - else if (value is IConvertible) + else if (ConvertUtils.IsConvertible(value)) { - IConvertible convertible = value as IConvertible; + IConvertible convertible = ConvertUtils.ToConvertible(value); switch (convertible.GetTypeCode()) { diff --git a/Src/Newtonsoft.Json/JsonWriterException.cs b/Src/Newtonsoft.Json/JsonWriterException.cs index 70c57ebb..0c931439 100644 --- a/Src/Newtonsoft.Json/JsonWriterException.cs +++ b/Src/Newtonsoft.Json/JsonWriterException.cs @@ -33,7 +33,7 @@ namespace Newtonsoft.Json /// /// The exception thrown when an error occurs while reading Json text. /// -#if (!SILVERLIGHT && !WINDOWS_PHONE) +#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE) [Serializable] #endif public class JsonWriterException : Exception @@ -66,7 +66,7 @@ namespace Newtonsoft.Json { } -#if !(WINDOWS_PHONE || SILVERLIGHT) +#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE) /// /// Initializes a new instance of the class. /// diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index ec992fea..05f54dad 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -40,16 +40,16 @@ namespace Newtonsoft.Json.Linq /// Represents a token that can contain other tokens. /// public abstract class JContainer : JToken, IList -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) , ITypedList, IBindingList #else , IList, INotifyCollectionChanged #endif -#if !(SILVERLIGHT || NET20 || NET35) +#if !(SILVERLIGHT || NET20 || NET35 || NETFX_CORE) , INotifyCollectionChanged #endif { -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE /// /// Occurs when the list changes or an item in the list changes. /// @@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Linq throw new InvalidOperationException("Cannot change {0} during a collection change event.".FormatWith(CultureInfo.InvariantCulture, GetType())); } - #if !SILVERLIGHT + #if !SILVERLIGHT && !NETFX_CORE /// /// Raises the event. /// @@ -329,7 +329,7 @@ namespace Newtonsoft.Json.Linq ChildrenTokens.Insert(index, item); -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE if (ListChanged != null) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index)); #endif @@ -363,7 +363,7 @@ namespace Newtonsoft.Json.Linq ChildrenTokens.RemoveAt(index); -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index)); #endif #if SILVERLIGHT || !(NET20 || NET35) @@ -425,7 +425,7 @@ namespace Newtonsoft.Json.Linq existing.Previous = null; existing.Next = null; -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index)); #endif #if SILVERLIGHT || !(NET20 || NET35) @@ -446,7 +446,7 @@ namespace Newtonsoft.Json.Linq ChildrenTokens.Clear(); -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); #endif #if SILVERLIGHT || !(NET20 || NET35) @@ -718,7 +718,7 @@ namespace Newtonsoft.Json.Linq return hashCode; } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE string ITypedList.GetListName(PropertyDescriptor[] listAccessors) { return string.Empty; @@ -897,7 +897,7 @@ namespace Newtonsoft.Json.Linq #region IBindingList Members -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE void IBindingList.AddIndex(PropertyDescriptor property) { } diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index 13ca2fdc..7d8dd29f 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -43,10 +43,10 @@ namespace Newtonsoft.Json.Linq /// Represents a JSON object. /// public class JObject : JContainer, IDictionary, INotifyPropertyChanged -#if !(PocketPC || SILVERLIGHT) +#if !(PocketPC || SILVERLIGHT || NETFX_CORE) , ICustomTypeDescriptor #endif -#if !(PocketPC || SILVERLIGHT || NET20) +#if !(PocketPC || SILVERLIGHT || NET20 || NETFX_CORE) , INotifyPropertyChanging #endif { @@ -99,7 +99,7 @@ namespace Newtonsoft.Json.Linq /// public event PropertyChangedEventHandler PropertyChanged; -#if !(PocketPC || SILVERLIGHT || NET20) +#if !(PocketPC || SILVERLIGHT || NET20 || NETFX_CORE) /// /// Occurs when a property value is changing. /// @@ -179,7 +179,7 @@ namespace Newtonsoft.Json.Linq internal void InternalPropertyChanged(JProperty childProperty) { OnPropertyChanged(childProperty.Name); -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); #endif #if SILVERLIGHT || !(NET20 || NET35) @@ -189,7 +189,7 @@ namespace Newtonsoft.Json.Linq internal void InternalPropertyChanging(JProperty childProperty) { -#if !PocketPC && !SILVERLIGHT && !NET20 +#if !PocketPC && !SILVERLIGHT && !NET20 && !NETFX_CORE OnPropertyChanging(childProperty.Name); #endif } @@ -294,7 +294,7 @@ namespace Newtonsoft.Json.Linq } else { -#if !PocketPC && !SILVERLIGHT && !NET20 +#if !PocketPC && !SILVERLIGHT && !NET20 && !NETFX_CORE OnPropertyChanging(propertyName); #endif Add(new JProperty(propertyName, value)); @@ -543,7 +543,7 @@ namespace Newtonsoft.Json.Linq PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } -#if !PocketPC && !SILVERLIGHT && !NET20 +#if !PocketPC && !SILVERLIGHT && !NET20 && !NETFX_CORE /// /// Raises the event with the provided arguments. /// @@ -555,7 +555,7 @@ namespace Newtonsoft.Json.Linq } #endif -#if !PocketPC && !SILVERLIGHT +#if !PocketPC && !SILVERLIGHT && !NETFX_CORE // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type #region ICustomTypeDescriptor /// diff --git a/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs b/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs index dd49c08d..13736dab 100644 --- a/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs +++ b/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE using System; using System.ComponentModel; using Newtonsoft.Json.Utilities; diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 15cb4a97..35d94ab0 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -43,7 +43,7 @@ namespace Newtonsoft.Json.Linq /// Represents an abstract JSON token. /// public abstract class JToken : IJEnumerable, IJsonLineInfo -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE , ICloneable #endif #if !(NET35 || NET20 || WINDOWS_PHONE) @@ -1337,7 +1337,7 @@ namespace Newtonsoft.Json.Linq } #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE object ICloneable.Clone() { return DeepClone(); diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs index ccc02b86..6e5bcf8e 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -304,7 +304,13 @@ namespace Newtonsoft.Json.Linq public override void WriteValue(char value) { base.WriteValue(value); - AddValue(value.ToString(CultureInfo.InvariantCulture), JsonToken.String); + string s = null; +#if !NETFX_CORE + s = value.ToString(CultureInfo.InvariantCulture); +#else + s = value.ToString(); +#endif + AddValue(s, JsonToken.String); } /// diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 7d574128..11d76747 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -419,8 +419,10 @@ namespace Newtonsoft.Json.Linq { if (value == null) return JTokenType.Null; +#if !NETFX_CORE else if (value == DBNull.Value) return JTokenType.Null; +#endif else if (value is string) return GetStringValueType(current); else if (value is long || value is int || value is short || value is sbyte diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Metro.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Metro.csproj new file mode 100644 index 00000000..aa54ccb4 --- /dev/null +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Metro.csproj @@ -0,0 +1,282 @@ + + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {263136A2-B89B-424E-A87A-F988CAA8D032} + Library + Properties + Newtonsoft.Json + Newtonsoft.Json + en-US + 512 + {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + true + full + false + bin\Debug\ + DEBUG;TRACE;NETFX_CORE + prompt + 3 + + + pdbonly + true + bin\Release\ + TRACE;NETFX_CORE + prompt + 4 + + + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE + ;2008 + full + ARM + false + prompt + ExpressRules.ruleset + true + + + bin\ARM\Release\ + TRACE;NETFX_CORE + true + ;2008 + pdbonly + ARM + false + prompt + ExpressRules.ruleset + true + + + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE + ;2008 + full + x64 + false + prompt + ExpressRules.ruleset + true + + + bin\x64\Release\ + TRACE;NETFX_CORE + true + ;2008 + pdbonly + x64 + false + prompt + ExpressRules.ruleset + true + + + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE + ;2008 + full + x86 + false + prompt + ExpressRules.ruleset + true + + + bin\x86\Release\ + TRACE;NETFX_CORE + true + ;2008 + pdbonly + x86 + false + prompt + ExpressRules.ruleset + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11.0 + + + + \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj index 42f64b0b..36b4d2b7 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj @@ -224,6 +224,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj index 22bd2a81..4d76b440 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj @@ -239,6 +239,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj index 7ea6e09a..3dae2a83 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj @@ -218,6 +218,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj index 3014bec8..e5380222 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj @@ -188,6 +188,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index d1b70ade..5fb317e3 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -235,6 +235,7 @@ + diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index 4f81f4de..b9f40df1 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -85,7 +85,7 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.0.8.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.0.8.14710")] +[assembly: AssemblyFileVersion("4.0.8.14715")] #endif [assembly: CLSCompliant(true)] diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs index 5699d38e..d72f73d8 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs @@ -31,7 +31,7 @@ namespace Newtonsoft.Json.Schema /// /// Returns detailed information about the schema exception. /// -#if (!SILVERLIGHT && !WINDOWS_PHONE) +#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE) [Serializable] #endif public class JsonSchemaException : Exception @@ -83,7 +83,7 @@ namespace Newtonsoft.Json.Schema { } - #if !(WINDOWS_PHONE || SILVERLIGHT) + #if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE) /// /// Initializes a new instance of the class. /// diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs index b3a2db52..66156601 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs @@ -31,6 +31,10 @@ using System.Collections.Generic; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Serialization; +using System.Reflection; +#if NETFX_CORE +using IConvertible = Newtonsoft.Json.Utilities.Convertible; +#endif namespace Newtonsoft.Json.Schema { @@ -175,7 +179,7 @@ namespace Newtonsoft.Json.Schema if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description)) return containerAttribute.Description; -#if !PocketPC +#if !PocketPC && !NETFX_CORE DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute(type); if (descriptionAttribute != null) return descriptionAttribute.Description; @@ -285,7 +289,7 @@ namespace Newtonsoft.Json.Schema case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); - if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof (FlagsAttribute), true)) + if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true)) { CurrentSchema.Enum = new List(); CurrentSchema.Options = new Dictionary(); @@ -317,13 +321,13 @@ namespace Newtonsoft.Json.Schema if (keyType != null) { // can be converted to a string - if (typeof (IConvertible).IsAssignableFrom(keyType)) + if (ConvertUtils.IsConvertible(keyType)) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } break; -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE case JsonContractType.Serializable: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); @@ -378,11 +382,11 @@ namespace Newtonsoft.Json.Schema } } - if (type.IsSealed) + if (type.IsSealed()) CurrentSchema.AllowAdditionalProperties = false; } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE private void GenerateISerializableContract(Type type, JsonISerializableContract contract) { CurrentSchema.AllowAdditionalProperties = true; @@ -416,7 +420,7 @@ namespace Newtonsoft.Json.Schema type = Nullable.GetUnderlyingType(type); } - TypeCode typeCode = Type.GetTypeCode(type); + TypeCode typeCode = ConvertUtils.GetTypeCode(type); switch (typeCode) { diff --git a/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs b/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs index 752d75c2..255f7482 100644 --- a/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs +++ b/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs @@ -29,6 +29,9 @@ using System.Linq; using System.Reflection; using System.Text; using Newtonsoft.Json.Utilities; +#if NETFX_CORE +using ICustomAttributeProvider = Newtonsoft.Json.Utilities.CustomAttributeProvider; +#endif namespace Newtonsoft.Json.Serialization { diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 803970b0..ce4ea622 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -37,12 +37,17 @@ using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; +#if !NETFX_CORE using System.Security.Permissions; +#endif using System.Xml.Serialization; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; using System.Runtime.CompilerServices; +#if NETFX_CORE +using ICustomAttributeProvider = Newtonsoft.Json.Utilities.CustomAttributeProvider; +#endif namespace Newtonsoft.Json.Serialization { @@ -88,7 +93,7 @@ namespace Newtonsoft.Json.Serialization } private static readonly IList BuiltInConverters = new List { -#if !PocketPC && !SILVERLIGHT && !NET20 +#if !PocketPC && !SILVERLIGHT && !NET20 && !NETFX_CORE new EntityKeyMemberConverter(), #endif #if !(NET35 || NET20 || WINDOWS_PHONE) @@ -96,10 +101,10 @@ namespace Newtonsoft.Json.Serialization #endif new BinaryConverter(), new KeyValuePairConverter(), -#if !SILVERLIGHT || WINDOWS_PHONE +#if (!SILVERLIGHT || WINDOWS_PHONE) new XmlNodeConverter(), #endif -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE new DataSetConverter(), new DataTableConverter(), #endif @@ -124,11 +129,15 @@ namespace Newtonsoft.Json.Serialization get { return JsonTypeReflector.DynamicCodeGeneration; } } +#if !NETFX_CORE /// /// Gets or sets the default members search flags. /// /// The default members search flags. public BindingFlags DefaultMembersSearchFlags { get; set; } +#else + private BindingFlags DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public; +#endif /// /// Gets or sets a value indicating whether compiler generated members should be serialized. @@ -157,7 +166,9 @@ namespace Newtonsoft.Json.Serialization /// public DefaultContractResolver(bool shareCache) { +#if !NETFX_CORE DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.Instance; +#endif _sharedCache = shareCache; } @@ -241,10 +252,10 @@ namespace Newtonsoft.Json.Serialization else { // add members that are explicitly marked with JsonProperty/DataMember attribute - if (JsonTypeReflector.GetAttribute(member) != null) + if (JsonTypeReflector.GetAttribute(member.GetCustomAttributeProvider()) != null) serializableMembers.Add(member); #if !PocketPC && !NET20 - else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute(member) != null) + else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute(member.GetCustomAttributeProvider()) != null) serializableMembers.Add(member); #endif } @@ -267,7 +278,7 @@ namespace Newtonsoft.Json.Serialization PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) { - if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1") + if (propertyInfo.PropertyType.IsGenericType() && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1") return false; } @@ -324,7 +335,7 @@ namespace Newtonsoft.Json.Serialization private ConstructorInfo GetParametrizedConstructor(Type objectType) { - IList constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance); + IList constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).ToList(); if (constructors.Count == 1) return constructors[0]; @@ -375,7 +386,7 @@ namespace Newtonsoft.Json.Serialization bool allowNonPublicAccess; bool hasExplicitAttribute; - SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess, out hasExplicitAttribute); + SetPropertySettingsFromAttributes(property, parameterInfo.GetCustomAttributeProvider(), parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess, out hasExplicitAttribute); property.Readable = false; property.Writable = true; @@ -406,7 +417,7 @@ namespace Newtonsoft.Json.Serialization /// protected virtual JsonConverter ResolveContractConverter(Type objectType) { - return JsonTypeReflector.GetJsonConverter(objectType, objectType); + return JsonTypeReflector.GetJsonConverter(objectType.GetCustomAttributeProvider(), objectType); } private Func GetDefaultCreator(Type createdType) @@ -440,11 +451,11 @@ namespace Newtonsoft.Json.Serialization contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.NonNullableUnderlyingType); if (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, true) - || contract.CreatedType.IsValueType) + || contract.CreatedType.IsValueType()) { contract.DefaultCreator = GetDefaultCreator(contract.CreatedType); - contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType && + contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType() && ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null); } @@ -453,8 +464,8 @@ namespace Newtonsoft.Json.Serialization private void ResolveCallbackMethods(JsonContract contract, Type t) { - if (t.BaseType != null) - ResolveCallbackMethods(contract, t.BaseType); + if (t.BaseType() != null) + ResolveCallbackMethods(contract, t.BaseType()); MethodInfo onSerializing; MethodInfo onSerialized; @@ -465,7 +476,14 @@ namespace Newtonsoft.Json.Serialization GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError); if (onSerializing != null) + { +#if NETFX_CORE + if (!t.IsGenericType() || (t.GetGenericTypeDefinition() != typeof(ConcurrentDictionary<,>))) + contract.OnSerializing = onSerializing; +#else contract.OnSerializing = onSerializing; +#endif + } if (onSerialized != null) contract.OnSerialized = onSerialized; @@ -477,7 +495,7 @@ namespace Newtonsoft.Json.Serialization { // ConcurrentDictionary throws an error here so don't use its OnDeserialized - http://json.codeplex.com/discussions/257093 #if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE) - if (!t.IsGenericType || (t.GetGenericTypeDefinition() != typeof(ConcurrentDictionary<,>))) + if (!t.IsGenericType() || (t.GetGenericTypeDefinition() != typeof(ConcurrentDictionary<,>))) contract.OnDeserialized = onDeserialized; #else contract.OnDeserialized = onDeserialized; @@ -583,7 +601,7 @@ namespace Newtonsoft.Json.Serialization return contract; } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE /// /// Creates a for the given type. /// @@ -667,7 +685,7 @@ namespace Newtonsoft.Json.Serialization if (CanConvertToString(t)) return CreateStringContract(objectType); -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE if (typeof(ISerializable).IsAssignableFrom(t)) return CreateISerializableContract(objectType); #endif @@ -682,7 +700,7 @@ namespace Newtonsoft.Json.Serialization internal static bool CanConvertToString(Type type) { -#if !PocketPC +#if !PocketPC && !NETFX_CORE TypeConverter converter = ConvertUtils.GetConverter(type); // use the objectType's TypeConverter if it has one and can convert to a string @@ -744,7 +762,7 @@ namespace Newtonsoft.Json.Serialization internal static string GetClrTypeFullName(Type type) { - if (type.IsGenericTypeDefinition || !type.ContainsGenericParameters) + if (type.IsGenericTypeDefinition() || !type.ContainsGenericParameters()) return type.FullName; return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { type.Namespace, type.Name }); @@ -813,7 +831,7 @@ namespace Newtonsoft.Json.Serialization bool allowNonPublicAccess; bool hasExplicitAttribute; - SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess, out hasExplicitAttribute); + SetPropertySettingsFromAttributes(property, member.GetCustomAttributeProvider(), member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess, out hasExplicitAttribute); property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess); property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess, hasExplicitAttribute); @@ -831,9 +849,16 @@ namespace Newtonsoft.Json.Serialization #if !PocketPC && !NET20 DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); + MemberInfo memberInfo = null; +#if !NETFX_CORE + memberInfo = attributeProvider as MemberInfo; +#else + memberInfo = attributeProvider.UnderlyingObject as MemberInfo; +#endif + DataMemberAttribute dataMemberAttribute; - if (dataContractAttribute != null && attributeProvider is MemberInfo) - dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)attributeProvider); + if (dataContractAttribute != null && memberInfo != null) + dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)memberInfo); else dataMemberAttribute = null; #endif @@ -914,7 +939,7 @@ namespace Newtonsoft.Json.Serialization private Predicate CreateShouldSerializeTest(MemberInfo member) { - MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, new Type[0]); + MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool)) return null; diff --git a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs index 9f0176a1..81b8d6e2 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs @@ -49,12 +49,14 @@ namespace Newtonsoft.Json.Serialization { Assembly assembly; -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE // look, I don't like using obsolete methods as much as you do but this is the only way // Assembly.Load won't check the GAC for a partial name #pragma warning disable 618,612 assembly = Assembly.LoadWithPartialName(assemblyName); #pragma warning restore 618,612 +#elif NETFX_CORE + assembly = Assembly.Load(new AssemblyName(assemblyName)); #else assembly = Assembly.Load(assemblyName); #endif @@ -126,7 +128,10 @@ namespace Newtonsoft.Json.Serialization /// Specifies the name of the serialized object. public override void BindToName(Type serializedType, out string assemblyName, out string typeName) { -#if !SILVERLIGHT +#if NETFX_CORE + assemblyName = serializedType.GetTypeInfo().Assembly.FullName; + typeName = serializedType.FullName; +#elif !SILVERLIGHT assemblyName = serializedType.Assembly.FullName; typeName = serializedType.FullName; #else diff --git a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs index 32044845..234cca30 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -63,7 +63,7 @@ namespace Newtonsoft.Json.Serialization { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; } - else if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + else if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = typeof (IEnumerable<>); CollectionItemType = underlyingType.GetGenericArguments()[0]; @@ -133,7 +133,7 @@ namespace Newtonsoft.Json.Serialization private bool IsTypeGenericCollectionInterface(Type type) { - if (!type.IsGenericType) + if (!type.IsGenericType()) return false; Type genericDefinition = type.GetGenericTypeDefinition(); diff --git a/Src/Newtonsoft.Json/Serialization/JsonContract.cs b/Src/Newtonsoft.Json/Serialization/JsonContract.cs index 8a399a42..423683fa 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonContract.cs @@ -27,6 +27,9 @@ using System; using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Utilities; +#if NETFX_CORE +using IConvertible = Newtonsoft.Json.Utilities.Convertible; +#endif namespace Newtonsoft.Json.Serialization { @@ -41,7 +44,7 @@ namespace Newtonsoft.Json.Serialization #if !(NET35 || NET20 || WINDOWS_PHONE) Dynamic, #endif -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE Serializable, #endif Linq @@ -179,7 +182,7 @@ namespace Newtonsoft.Json.Serialization CreatedType = NonNullableUnderlyingType; - IsConvertable = typeof(IConvertible).IsAssignableFrom(NonNullableUnderlyingType); + IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); if (NonNullableUnderlyingType == typeof(byte[])) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index c3af3f33..bf36008c 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -92,16 +92,20 @@ namespace Newtonsoft.Json.Serialization { CreatedType = ReflectionUtils.MakeGenericType(typeof(Dictionary<,>), keyType, valueType); } +#if !NETFX_CORE else if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof (Dictionary); } +#endif } internal IWrappedDictionary CreateWrapper(object dictionary) { +#if !NETFX_CORE if (dictionary is IDictionary && (DictionaryValueType == null || !_isDictionaryValueTypeNullableType)) return new DictionaryWrapper((IDictionary)dictionary); +#endif if (_genericWrapperCreator == null) { @@ -116,7 +120,7 @@ namespace Newtonsoft.Json.Serialization private bool IsTypeGenericDictionaryInterface(Type type) { - if (!type.IsGenericType) + if (!type.IsGenericType()) return false; Type genericDefinition = type.GetGenericTypeDefinition(); diff --git a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index 36b25633..49f19b47 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT && !PocketPC +#if !(SILVERLIGHT || NETFX_CORE) using System; using System.Collections.Generic; using System.Globalization; diff --git a/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs b/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs index c033f766..b8b9a119 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE using System; using System.Collections.Generic; using System.Linq; diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs index 1c513469..72fff393 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs @@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Serialization int IEqualityComparer.GetHashCode(object obj) { -#if !PocketPC +#if !PocketPC && !NETFX_CORE // put objects in a bucket based on their reference return RuntimeHelpers.GetHashCode(obj); #else diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 75563239..7684298d 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Serialization internal class JsonSerializerInternalReader : JsonSerializerInternalBase { private JsonSerializerProxy _internalSerializer; -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE private JsonFormatterConverter _formatterConverter; #endif @@ -130,7 +130,7 @@ namespace Newtonsoft.Json.Serialization return _internalSerializer; } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE private JsonFormatterConverter GetFormatterConverter() { if (_formatterConverter == null) @@ -264,8 +264,10 @@ namespace Newtonsoft.Json.Serialization return constructorName; case JsonToken.Null: case JsonToken.Undefined: +#if !NETFX_CORE if (objectType == typeof (DBNull)) return DBNull.Value; +#endif return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Raw: @@ -461,7 +463,7 @@ namespace Newtonsoft.Json.Serialization JsonDynamicContract dynamicContract = (JsonDynamicContract) contract; return CreateDynamic(reader, dynamicContract, id); #endif -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE case JsonContractType.Serializable: JsonISerializableContract serializableContract = (JsonISerializableContract) contract; return CreateISerializable(reader, serializableContract, id); @@ -539,7 +541,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For if (contract.IsConvertable) { - if (contract.NonNullableUnderlyingType.IsEnum) + if (contract.NonNullableUnderlyingType.IsEnum()) { if (value is string) return Enum.Parse(contract.NonNullableUnderlyingType, value.ToString(), true); @@ -597,7 +599,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For useExistingValue = (currentValue != null && !property.PropertyType.IsArray && !ReflectionUtils.InheritsGenericDefinition(property.PropertyType, typeof (ReadOnlyCollection<>)) - && !property.PropertyType.IsValueType); + && !property.PropertyType.IsValueType()); } if (!property.Writable && !useExistingValue) @@ -818,7 +820,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For throw CreateSerializationException(reader, "Unexpected end when deserializing array."); } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id) { Type objectType = contract.UnderlyingType; @@ -868,7 +870,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For { IDynamicMetaObjectProvider newObject = null; - if (contract.UnderlyingType.IsInterface || contract.UnderlyingType.IsAbstract) + if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract()) throw CreateSerializationException(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (contract.DefaultCreator != null && @@ -947,7 +949,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For { object newObject = null; - if (contract.UnderlyingType.IsInterface || contract.UnderlyingType.IsAbstract) + if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract()) throw CreateSerializationException(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (contract.OverrideConstructor != null) diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index 30341ef9..03705d73 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -138,7 +138,7 @@ namespace Newtonsoft.Json.Serialization SerializeDynamic(writer, (IDynamicMetaObjectProvider) value, (JsonDynamicContract) valueContract); break; #endif -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE case JsonContractType.Serializable: SerializeISerializable(writer, (ISerializable) value, (JsonISerializableContract) valueContract, member, collectionValueContract); break; @@ -242,7 +242,7 @@ namespace Newtonsoft.Json.Serialization internal static bool TryConvertToString(object value, Type type, out string s) { -#if !PocketPC +#if !(PocketPC || NETFX_CORE) TypeConverter converter = ConvertUtils.GetConverter(type); // use the objectType's TypeConverter if it has one and can convert to a string @@ -264,7 +264,7 @@ namespace Newtonsoft.Json.Serialization } #endif -#if SILVERLIGHT || PocketPC +#if SILVERLIGHT || PocketPC || NETFX_CORE if (value is Guid || value is Uri || value is TimeSpan) { s = value.ToString(); @@ -323,7 +323,7 @@ namespace Newtonsoft.Json.Serialization property.PropertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType); object memberValue = property.ValueProvider.GetValue(value); - JsonContract memberContract = (property.PropertyContract.UnderlyingType.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); + JsonContract memberContract = (property.PropertyContract.UnderlyingType.IsSealed()) ? property.PropertyContract : GetContractSafe(memberValue); WriteMemberInfoProperty(writer, memberValue, property, memberContract); } @@ -411,7 +411,7 @@ namespace Newtonsoft.Json.Serialization if (contract.CollectionItemContract == null) contract.CollectionItemContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object)); - JsonContract collectionItemValueContract = (contract.CollectionItemContract.UnderlyingType.IsSealed) ? contract.CollectionItemContract : null; + JsonContract collectionItemValueContract = (contract.CollectionItemContract.UnderlyingType.IsSealed()) ? contract.CollectionItemContract : null; writer.WriteStartArray(); @@ -462,7 +462,7 @@ namespace Newtonsoft.Json.Serialization contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context); } -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE #if !NET20 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")] [SecuritySafeCritical] @@ -577,12 +577,16 @@ namespace Newtonsoft.Json.Serialization if (contract.DictionaryValueContract == null) contract.DictionaryValueContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); - JsonContract dictionaryValueContract = (contract.DictionaryValueContract.UnderlyingType.IsSealed) ? contract.DictionaryValueContract : null; + JsonContract dictionaryValueContract = (contract.DictionaryValueContract.UnderlyingType.IsSealed()) ? contract.DictionaryValueContract : null; int initialDepth = writer.Top; +#if !NETFX_CORE // Mono Unity 3.0 fix IDictionary d = values; +#else + IWrappedDictionary d = values; +#endif foreach (DictionaryEntry entry in d) { @@ -631,7 +635,7 @@ namespace Newtonsoft.Json.Serialization { string propertyName; - if (entry.Key is IConvertible) + if (ConvertUtils.IsConvertible(entry.Key)) return Convert.ToString(entry.Key, CultureInfo.InvariantCulture); else if (TryConvertToString(entry.Key, entry.Key.GetType(), out propertyName)) return propertyName; diff --git a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs index 0a6b31f2..12e8ea59 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs @@ -29,12 +29,17 @@ using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; +#if !NETFX_CORE using System.Security.Permissions; +#endif using Newtonsoft.Json.Utilities; +#if NETFX_CORE +using ICustomAttributeProvider = Newtonsoft.Json.Utilities.CustomAttributeProvider; +#endif namespace Newtonsoft.Json.Serialization { -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE internal interface IMetadataTypeAttribute { Type MetadataClassType { get; } @@ -53,7 +58,7 @@ namespace Newtonsoft.Json.Serialization public const string SpecifiedPostfix = "Specified"; private static readonly ThreadSafeStore JsonConverterTypeCache = new ThreadSafeStore(GetJsonConverterTypeFromAttribute); -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE private static readonly ThreadSafeStore AssociatedMetadataTypesCache = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); private const string MetadataTypeAttributeTypeName = @@ -80,7 +85,7 @@ namespace Newtonsoft.Json.Serialization public static JsonContainerAttribute GetJsonContainerAttribute(Type type) { - return CachedAttributeGetter.GetAttribute(type); + return CachedAttributeGetter.GetAttribute(type.GetCustomAttributeProvider()); } public static JsonObjectAttribute GetJsonObjectAttribute(Type type) @@ -93,7 +98,7 @@ namespace Newtonsoft.Json.Serialization return GetJsonContainerAttribute(type) as JsonArrayAttribute; } -#if !PocketPC && !NET20 +#if !PocketPC && !NET20 public static DataContractAttribute GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance @@ -101,8 +106,8 @@ namespace Newtonsoft.Json.Serialization Type currentType = type; while (result == null && currentType != null) { - result = CachedAttributeGetter.GetAttribute(currentType); - currentType = currentType.BaseType; + result = CachedAttributeGetter.GetAttribute(currentType.GetCustomAttributeProvider()); + currentType = currentType.BaseType(); } return result; @@ -113,12 +118,12 @@ namespace Newtonsoft.Json.Serialization // DataMemberAttribute does not have inheritance // can't override a field - if (memberInfo.MemberType == MemberTypes.Field) - return CachedAttributeGetter.GetAttribute(memberInfo); + if (memberInfo.MemberType() == MemberTypes.Field) + return CachedAttributeGetter.GetAttribute(memberInfo.GetCustomAttributeProvider()); // search property and then search base properties if nothing is returned and the property is virtual PropertyInfo propertyInfo = (PropertyInfo) memberInfo; - DataMemberAttribute result = CachedAttributeGetter.GetAttribute(propertyInfo); + DataMemberAttribute result = CachedAttributeGetter.GetAttribute(propertyInfo.GetCustomAttributeProvider()); if (result == null) { if (propertyInfo.IsVirtual()) @@ -129,9 +134,9 @@ namespace Newtonsoft.Json.Serialization { PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); if (baseProperty != null && baseProperty.IsVirtual()) - result = CachedAttributeGetter.GetAttribute(baseProperty); + result = CachedAttributeGetter.GetAttribute(baseProperty.GetCustomAttributeProvider()); - currentType = currentType.BaseType; + currentType = currentType.BaseType(); } } } @@ -174,6 +179,13 @@ namespace Newtonsoft.Json.Serialization public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType) { + object provider = null; +#if !NETFX_CORE + provider = attributeProvider as MemberInfo; +#else + provider = attributeProvider.UnderlyingObject; +#endif + Type converterType = GetJsonConverterType(attributeProvider); if (converterType != null) @@ -181,7 +193,7 @@ namespace Newtonsoft.Json.Serialization JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType); if (!memberConverter.CanConvert(targetConvertedType)) - throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name)); + throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, provider, targetConvertedType.Name)); return memberConverter; } @@ -189,6 +201,7 @@ namespace Newtonsoft.Json.Serialization return null; } +#if !NETFX_CORE #if !PocketPC public static TypeConverter GetTypeConverter(Type type) { @@ -201,11 +214,12 @@ namespace Newtonsoft.Json.Serialization return (TypeConverter)ReflectionUtils.CreateInstance(converterType); return null; +#endif #endif } #endif -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE private static Type GetAssociatedMetadataType(Type type) { return AssociatedMetadataTypesCache.Get(type); @@ -250,7 +264,7 @@ namespace Newtonsoft.Json.Serialization { T attribute; -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE Type metadataType = GetAssociatedMetadataType(type); if (metadataType != null) { @@ -260,13 +274,13 @@ namespace Newtonsoft.Json.Serialization } #endif - attribute = ReflectionUtils.GetAttribute(type, true); + attribute = ReflectionUtils.GetAttribute(type.GetCustomAttributeProvider(), true); if (attribute != null) return attribute; foreach (Type typeInterface in type.GetInterfaces()) { - attribute = ReflectionUtils.GetAttribute(typeInterface, true); + attribute = ReflectionUtils.GetAttribute(typeInterface.GetCustomAttributeProvider(), true); if (attribute != null) return attribute; } @@ -278,7 +292,7 @@ namespace Newtonsoft.Json.Serialization { T attribute; -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); if (metadataType != null) { @@ -293,19 +307,22 @@ namespace Newtonsoft.Json.Serialization } #endif - attribute = ReflectionUtils.GetAttribute(memberInfo, true); + attribute = ReflectionUtils.GetAttribute(memberInfo.GetCustomAttributeProvider(), true); if (attribute != null) return attribute; - foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces()) + if (memberInfo.DeclaringType != null) { - MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); - - if (interfaceTypeMemberInfo != null) + foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces()) { - attribute = ReflectionUtils.GetAttribute(interfaceTypeMemberInfo, true); - if (attribute != null) - return attribute; + MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); + + if (interfaceTypeMemberInfo != null) + { + attribute = ReflectionUtils.GetAttribute(interfaceTypeMemberInfo.GetCustomAttributeProvider(), true); + if (attribute != null) + return attribute; + } } } @@ -314,11 +331,18 @@ namespace Newtonsoft.Json.Serialization public static T GetAttribute(ICustomAttributeProvider attributeProvider) where T : Attribute { - Type type = attributeProvider as Type; + object provider = null; +#if !NETFX_CORE + provider = attributeProvider; +#else + provider = attributeProvider.UnderlyingObject; +#endif + + Type type = provider as Type; if (type != null) return GetAttribute(type); - MemberInfo memberInfo = attributeProvider as MemberInfo; + MemberInfo memberInfo = provider as MemberInfo; if (memberInfo != null) return GetAttribute(memberInfo); @@ -333,7 +357,7 @@ namespace Newtonsoft.Json.Serialization { if (_dynamicCodeGeneration == null) { -#if !PocketPC && !SILVERLIGHT +#if !PocketPC && !SILVERLIGHT && !NETFX_CORE try { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); diff --git a/Src/Newtonsoft.Json/Serialization/LateBoundMetadataTypeAttribute.cs b/Src/Newtonsoft.Json/Serialization/LateBoundMetadataTypeAttribute.cs index 815f20be..7bc384f4 100644 --- a/Src/Newtonsoft.Json/Serialization/LateBoundMetadataTypeAttribute.cs +++ b/Src/Newtonsoft.Json/Serialization/LateBoundMetadataTypeAttribute.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !SILVERLIGHT && !PocketPC && !NET20 +#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE using System; using System.Collections.Generic; using System.Linq; diff --git a/Src/Newtonsoft.Json/SerializationBinder.cs b/Src/Newtonsoft.Json/SerializationBinder.cs index 0d5fffa2..760068c7 100644 --- a/Src/Newtonsoft.Json/SerializationBinder.cs +++ b/Src/Newtonsoft.Json/SerializationBinder.cs @@ -1,4 +1,4 @@ -#if SILVERLIGHT || PocketPC +#if SILVERLIGHT || PocketPC || NETFX_CORE using System; using System.Reflection; diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index fec0c945..197f03a5 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -97,8 +97,10 @@ namespace Newtonsoft.Json.Utilities { ValidationUtils.ArgumentNotNull(type, "type"); +#if !NETFX_CORE if (typeof(IDictionary).IsAssignableFrom(type)) return true; +#endif if (ReflectionUtils.ImplementsGenericDefinition(type, typeof (IDictionary<,>))) return true; @@ -152,10 +154,12 @@ namespace Newtonsoft.Json.Utilities return (IWrappedDictionary)ReflectionUtils.CreateGeneric(typeof(DictionaryWrapper<,>), new[] { dictionaryKeyType, dictionaryValueType }, instanceCreator, dictionary); } +#if !NETFX_CORE else if (dictionary is IDictionary) { return new DictionaryWrapper((IDictionary)dictionary); } +#endif else { throw new Exception("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType())); diff --git a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs index 4d088404..e6676371 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -258,7 +258,7 @@ namespace Newtonsoft.Json.Utilities private static bool IsCompatibleObject(object value) { - if (!(value is T) && (value != null || (typeof(T).IsValueType && !ReflectionUtils.IsNullableType(typeof(T))))) + if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T))))) return false; return true; diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index e3b3d9d4..5f5a3478 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -30,16 +30,197 @@ using System.Text; using System.Globalization; using System.ComponentModel; using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Utilities; using System.Reflection; -#if !SILVERLIGHT +#if !(SILVERLIGHT || NETFX_CORE) using System.Data.SqlTypes; #endif +#if NETFX_CORE +using IConvertible = Newtonsoft.Json.Utilities.Convertible; +#endif namespace Newtonsoft.Json.Utilities { + internal class Convertible + { + private object _underlyingValue; + + public Convertible(object o) + { + _underlyingValue = o; + } + + public TypeCode GetTypeCode() + { + return ConvertUtils.GetTypeCode(_underlyingValue); + } + + public bool ToBoolean(IFormatProvider provider) + { + return Convert.ToBoolean(_underlyingValue, provider); + } + public byte ToByte(IFormatProvider provider) + { + return Convert.ToByte(_underlyingValue, provider); + } + public char ToChar(IFormatProvider provider) + { + return Convert.ToChar(_underlyingValue, provider); + } + public DateTime ToDateTime(IFormatProvider provider) + { + return Convert.ToDateTime(_underlyingValue, provider); + } + public decimal ToDecimal(IFormatProvider provider) + { + return Convert.ToDecimal(_underlyingValue, provider); + } + public double ToDouble(IFormatProvider provider) + { + return Convert.ToDouble(_underlyingValue, provider); + } + public short ToInt16(IFormatProvider provider) + { + return Convert.ToInt16(_underlyingValue, provider); + } + public int ToInt32(IFormatProvider provider) + { + return Convert.ToInt32(_underlyingValue, provider); + } + public long ToInt64(IFormatProvider provider) + { + return Convert.ToInt64(_underlyingValue, provider); + } + public sbyte ToSByte(IFormatProvider provider) + { + return Convert.ToSByte(_underlyingValue, provider); + } + public float ToSingle(IFormatProvider provider) + { + return Convert.ToSingle(_underlyingValue, provider); + } + public string ToString(IFormatProvider provider) + { + return Convert.ToString(_underlyingValue, provider); + } + public object ToType(Type conversionType, IFormatProvider provider) + { + return Convert.ChangeType(_underlyingValue, conversionType, provider); + } + public ushort ToUInt16(IFormatProvider provider) + { + return Convert.ToUInt16(_underlyingValue, provider); + } + public uint ToUInt32(IFormatProvider provider) + { + return Convert.ToUInt32(_underlyingValue, provider); + } + public ulong ToUInt64(IFormatProvider provider) + { + return Convert.ToUInt64(_underlyingValue, provider); + } + } + internal static class ConvertUtils { + public static TypeCode GetTypeCode(this IConvertible convertible) + { +#if !NETFX_CORE + return convertible.GetTypeCode(); +#else + return GetTypeCode((object)convertible); +#endif + } + + public static TypeCode GetTypeCode(object o) + { +#if !NETFX_CORE + return System.Convert.GetTypeCode(o); +#else + return GetTypeCode(o.GetType()); +#endif + } + + public static TypeCode GetTypeCode(Type t) + { +#if !NETFX_CORE + return Type.GetTypeCode(t); +#else + if (t == typeof(bool)) + return TypeCode.Boolean; + if (t == typeof(byte)) + return TypeCode.Byte; + if (t == typeof(char)) + return TypeCode.Char; + if (t == typeof(DateTime)) + return TypeCode.DateTime; + if (t == typeof(decimal)) + return TypeCode.Decimal; + if (t == typeof(double)) + return TypeCode.Double; + if (t == typeof(short)) + return TypeCode.Int16; + if (t == typeof(int)) + return TypeCode.Int32; + if (t == typeof(long)) + return TypeCode.Int64; + if (t == typeof(sbyte)) + return TypeCode.SByte; + if (t == typeof(float)) + return TypeCode.Single; + if (t == typeof(string)) + return TypeCode.String; + if (t == typeof(ushort)) + return TypeCode.UInt16; + if (t == typeof(uint)) + return TypeCode.UInt32; + if (t == typeof(ulong)) + return TypeCode.UInt64; + if (t.IsEnum()) + return GetTypeCode(Enum.GetUnderlyingType(t)); + + return TypeCode.Object; +#endif + } + + public static IConvertible ToConvertible(object o) + { +#if !NETFX_CORE + return o as IConvertible; +#else + if (!IsConvertible(o)) + return null; + + return new IConvertible(o); +#endif + } + + public static bool IsConvertible(object o) + { +#if !NETFX_CORE + return o is IConvertible; +#else + if (o == null) + return false; + + return ( + o is bool || o is byte || o is char || o is DateTime || o is decimal || o is double || o is short || o is int || + o is long || o is sbyte || o is float || o is string || o is ushort || o is uint || o is ulong || o is Enum); +#endif + } + + public static bool IsConvertible(Type t) + { +#if !NETFX_CORE + return typeof(IConvertible).IsAssignableFrom(t); +#else + return ( + t == typeof(bool) || t == typeof(byte) || t == typeof(char) || t == typeof(DateTime) || t == typeof(decimal) || t == typeof(double) || t == typeof(short) || t == typeof(int) || + t == typeof(long) || t == typeof(sbyte) || t == typeof(float) || t == typeof(string) || t == typeof(ushort) || t == typeof(uint) || t == typeof(ulong) || t.IsEnum()); +#endif + } + internal struct TypeConvertKey : IEquatable { private readonly Type _initialType; @@ -119,9 +300,9 @@ namespace Newtonsoft.Json.Utilities return initialValue; // use Convert.ChangeType if both types are IConvertible - if (initialValue is IConvertible && typeof(IConvertible).IsAssignableFrom(targetType)) + if (ConvertUtils.IsConvertible(initialValue) && ConvertUtils.IsConvertible(targetType)) { - if (targetType.IsEnum) + if (targetType.IsEnum()) { if (initialValue is string) return Enum.Parse(targetType, initialValue.ToString(), true); @@ -135,7 +316,7 @@ namespace Newtonsoft.Json.Utilities if (initialValue is string && typeof(Type).IsAssignableFrom(targetType)) return Type.GetType((string) initialValue, true); - if (targetType.IsInterface || targetType.IsGenericTypeDefinition || targetType.IsAbstract) + if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract()) throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType"); #if !PocketPC && !NET20 @@ -157,7 +338,7 @@ namespace Newtonsoft.Json.Utilities #endif } -#if !PocketPC +#if !PocketPC && !NETFX_CORE // see if source or target types have a TypeConverter that converts between the two TypeConverter toConverter = GetConverter(initialType); @@ -181,7 +362,7 @@ namespace Newtonsoft.Json.Utilities #endif } #endif - +#if !NETFX_CORE // handle DBNull and INullable if (initialValue == DBNull.Value) { @@ -190,7 +371,8 @@ namespace Newtonsoft.Json.Utilities throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType)); } -#if !SILVERLIGHT +#endif +#if !SILVERLIGHT && !NETFX_CORE if (initialValue is INullable) return EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType); #endif @@ -267,7 +449,7 @@ namespace Newtonsoft.Json.Utilities throw new Exception("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); } -#if !SILVERLIGHT +#if !SILVERLIGHT && !NETFX_CORE public static object ToValue(INullable nullableValue) { if (nullableValue == null) @@ -287,7 +469,7 @@ namespace Newtonsoft.Json.Utilities } #endif -#if !PocketPC +#if !PocketPC && !NETFX_CORE internal static TypeConverter GetConverter(Type t) { return JsonTypeReflector.GetTypeConverter(t); @@ -296,7 +478,7 @@ namespace Newtonsoft.Json.Utilities public static bool IsInteger(object value) { - switch (System.Convert.GetTypeCode(value)) + switch (GetTypeCode(value)) { case TypeCode.SByte: case TypeCode.Byte: diff --git a/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs b/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs index bf037132..52345e4b 100644 --- a/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs @@ -25,6 +25,7 @@ namespace Newtonsoft.Json.Utilities #endif } +#if !NETFX_CORE public static XmlDateTimeSerializationMode ToSerializationMode(DateTimeKind kind) { switch (kind) @@ -39,5 +40,6 @@ namespace Newtonsoft.Json.Utilities throw MiscellaneousUtils.CreateArgumentOutOfRangeException("kind", kind, "Unexpected DateTimeKind value."); } } +#endif } } diff --git a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs index d67734d6..6d43f654 100644 --- a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs @@ -7,23 +7,66 @@ using System.Threading; namespace Newtonsoft.Json.Utilities { - internal interface IWrappedDictionary : IDictionary +#if NETFX_CORE + internal interface IDictionary : ICollection + { + object this[object key] { get; set; } + void Add(object key, object value); + new IDictionaryEnumerator GetEnumerator(); + } + + public interface IDictionaryEnumerator : IEnumerator + { + DictionaryEntry Entry { get; } + object Key { get; } + object Value { get; } + } + + public struct DictionaryEntry + { + private readonly object _key; + private readonly object _value; + + public DictionaryEntry(object key, object value) + { + _key = key; + _value = value; + } + + public object Key + { + get { return _key; } + } + + public object Value + { + get { return _value; } + } + } +#endif + + internal interface IWrappedDictionary + : IDictionary { object UnderlyingDictionary { get; } } internal class DictionaryWrapper : IDictionary, IWrappedDictionary { +#if !(NETFX_CORE) private readonly IDictionary _dictionary; +#endif private readonly IDictionary _genericDictionary; private object _syncRoot; +#if !(NETFX_CORE) public DictionaryWrapper(IDictionary dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); _dictionary = dictionary; } +#endif public DictionaryWrapper(IDictionary dictionary) { @@ -34,38 +77,41 @@ namespace Newtonsoft.Json.Utilities public void Add(TKey key, TValue value) { - if (_genericDictionary != null) - _genericDictionary.Add(key, value); - else +#if !NETFX_CORE + if (_dictionary != null) _dictionary.Add(key, value); + else +#endif + _genericDictionary.Add(key, value); } public bool ContainsKey(TKey key) { - if (_genericDictionary != null) - return _genericDictionary.ContainsKey(key); - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.Contains(key); + else +#endif + return _genericDictionary.ContainsKey(key); } public ICollection Keys { get { - if (_genericDictionary != null) - return _genericDictionary.Keys; - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.Keys.Cast().ToList(); + else +#endif + return _genericDictionary.Keys; } } public bool Remove(TKey key) { - if (_genericDictionary != null) - { - return _genericDictionary.Remove(key); - } - else +#if !NETFX_CORE + if (_dictionary != null) { if (_dictionary.Contains(key)) { @@ -77,15 +123,15 @@ namespace Newtonsoft.Json.Utilities return false; } } +#endif + + return _genericDictionary.Remove(key); } public bool TryGetValue(TKey key, out TValue value) { - if (_genericDictionary != null) - { - return _genericDictionary.TryGetValue(key, out value); - } - else +#if !NETFX_CORE + if (_dictionary != null) { if (!_dictionary.Contains(key)) { @@ -98,16 +144,21 @@ namespace Newtonsoft.Json.Utilities return true; } } +#endif + + return _genericDictionary.TryGetValue(key, out value); } public ICollection Values { get { - if (_genericDictionary != null) - return _genericDictionary.Values; - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.Values.Cast().ToList(); + else +#endif + return _genericDictionary.Values; } } @@ -115,67 +166,80 @@ namespace Newtonsoft.Json.Utilities { get { - if (_genericDictionary != null) - return _genericDictionary[key]; - else +#if !NETFX_CORE + if (_dictionary != null) return (TValue)_dictionary[key]; +#endif + return _genericDictionary[key]; } set { - if (_genericDictionary != null) - _genericDictionary[key] = value; - else +#if !NETFX_CORE + if (_dictionary != null) _dictionary[key] = value; + else +#endif + _genericDictionary[key] = value; } } public void Add(KeyValuePair item) { - if (_genericDictionary != null) - _genericDictionary.Add(item); - else +#if !NETFX_CORE + if (_dictionary != null) ((IList)_dictionary).Add(item); + else +#endif + _genericDictionary.Add(item); } public void Clear() { - if (_genericDictionary != null) - _genericDictionary.Clear(); - else +#if !NETFX_CORE + if (_dictionary != null) _dictionary.Clear(); + else +#endif + _genericDictionary.Clear(); } public bool Contains(KeyValuePair item) { - if (_genericDictionary != null) - return _genericDictionary.Contains(item); - else +#if !NETFX_CORE + if (_dictionary != null) return ((IList)_dictionary).Contains(item); + else +#endif + return _genericDictionary.Contains(item); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { - if (_genericDictionary != null) - { - _genericDictionary.CopyTo(array, arrayIndex); - } - else +#if !NETFX_CORE + if (_dictionary != null) { foreach (DictionaryEntry item in _dictionary) { array[arrayIndex++] = new KeyValuePair((TKey)item.Key, (TValue)item.Value); } } + else +#endif + { + _genericDictionary.CopyTo(array, arrayIndex); + } } public int Count { get { - if (_genericDictionary != null) - return _genericDictionary.Count; - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.Count; + else +#endif + return _genericDictionary.Count; } } @@ -183,20 +247,19 @@ namespace Newtonsoft.Json.Utilities { get { - if (_genericDictionary != null) - return _genericDictionary.IsReadOnly; - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.IsReadOnly; + else +#endif + return _genericDictionary.IsReadOnly; } } public bool Remove(KeyValuePair item) { - if (_genericDictionary != null) - { - return _genericDictionary.Remove(item); - } - else +#if !NETFX_CORE + if (_dictionary != null) { if (_dictionary.Contains(item.Key)) { @@ -217,14 +280,21 @@ namespace Newtonsoft.Json.Utilities return true; } } + else +#endif + { + return _genericDictionary.Remove(item); + } } public IEnumerator> GetEnumerator() { - if (_genericDictionary != null) - return _genericDictionary.GetEnumerator(); - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.Cast().Select(de => new KeyValuePair((TKey)de.Key, (TValue)de.Value)).GetEnumerator(); + else +#endif + return _genericDictionary.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() @@ -234,18 +304,34 @@ namespace Newtonsoft.Json.Utilities void IDictionary.Add(object key, object value) { - if (_genericDictionary != null) - _genericDictionary.Add((TKey)key, (TValue)value); - else +#if !NETFX_CORE + if (_dictionary != null) _dictionary.Add(key, value); + else +#endif + _genericDictionary.Add((TKey)key, (TValue)value); } - bool IDictionary.Contains(object key) + object IDictionary.this[object key] { - if (_genericDictionary != null) - return _genericDictionary.ContainsKey((TKey)key); - else - return _dictionary.Contains(key); + get + { +#if !NETFX_CORE + if (_dictionary != null) + return _dictionary[key]; + else +#endif + return _genericDictionary[(TKey)key]; + } + set + { +#if !NETFX_CORE + if (_dictionary != null) + _dictionary[key] = value; + else +#endif + _genericDictionary[(TKey)key] = (TValue)value; + } } private struct DictionaryEnumerator : IDictionaryEnumerator @@ -291,10 +377,21 @@ namespace Newtonsoft.Json.Utilities IDictionaryEnumerator IDictionary.GetEnumerator() { - if (_genericDictionary != null) - return new DictionaryEnumerator(_genericDictionary.GetEnumerator()); - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.GetEnumerator(); + else +#endif + return new DictionaryEnumerator(_genericDictionary.GetEnumerator()); + } + +#if !NETFX_CORE + bool IDictionary.Contains(object key) + { + if (_genericDictionary != null) + return _genericDictionary.ContainsKey((TKey)key); + else + return _dictionary.Contains(key); } bool IDictionary.IsFixedSize @@ -318,15 +415,19 @@ namespace Newtonsoft.Json.Utilities return _dictionary.Keys; } } +#endif public void Remove(object key) { - if (_genericDictionary != null) - _genericDictionary.Remove((TKey)key); - else +#if !NETFX_CORE + if (_dictionary != null) _dictionary.Remove(key); + else +#endif + _genericDictionary.Remove((TKey)key); } +#if !NETFX_CORE ICollection IDictionary.Values { get @@ -337,41 +438,28 @@ namespace Newtonsoft.Json.Utilities return _dictionary.Values; } } - - object IDictionary.this[object key] - { - get - { - if (_genericDictionary != null) - return _genericDictionary[(TKey)key]; - else - return _dictionary[key]; - } - set - { - if (_genericDictionary != null) - _genericDictionary[(TKey)key] = (TValue)value; - else - _dictionary[key] = value; - } - } +#endif void ICollection.CopyTo(Array array, int index) { - if (_genericDictionary != null) - _genericDictionary.CopyTo((KeyValuePair[])array, index); - else +#if !NETFX_CORE + if (_dictionary != null) _dictionary.CopyTo(array, index); + else +#endif + _genericDictionary.CopyTo((KeyValuePair[])array, index); } bool ICollection.IsSynchronized { get { - if (_genericDictionary != null) - return false; - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary.IsSynchronized; + else +#endif + return false; } } @@ -390,10 +478,12 @@ namespace Newtonsoft.Json.Utilities { get { - if (_genericDictionary != null) - return _genericDictionary; - else +#if !NETFX_CORE + if (_dictionary != null) return _dictionary; + else +#endif + return _genericDictionary; } } } diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index bd610269..5565f2dd 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -27,8 +27,12 @@ namespace Newtonsoft.Json.Utilities return _proxy.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance).Cast() .Any(info => // check that the method overrides the original on DynamicObjectProxy - info.DeclaringType != typeof(DynamicProxy) && - info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy)); + info.DeclaringType != typeof(DynamicProxy) + // todo - find out whether there is a way to do this in winrt +#if !NETFX_CORE + && info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy) +#endif + ); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) @@ -176,8 +180,8 @@ namespace Newtonsoft.Json.Utilities private static ConstantExpression Constant(DynamicMetaObjectBinder binder) { Type t = binder.GetType(); - while (!t.IsVisible) - t = t.BaseType; + while (!t.IsVisible()) + t = t.BaseType(); return Expression.Constant(binder, t); } diff --git a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index eaf7d3c6..e6b92702 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -40,9 +40,9 @@ namespace Newtonsoft.Json.Utilities private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { - DynamicMethod dynamicMethod = !owner.IsInterface + DynamicMethod dynamicMethod = !owner.IsInterface() ? new DynamicMethod(name, returnType, parameterTypes, owner, true) - : new DynamicMethod(name, returnType, parameterTypes, owner.Module, true); + : new DynamicMethod(name, returnType, parameterTypes, owner.Module(), true); return dynamicMethod; } @@ -68,7 +68,7 @@ namespace Newtonsoft.Json.Utilities generator.Emit(OpCodes.Ldc_I4, args.Length); generator.Emit(OpCodes.Beq, argsOk); - generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(Type.EmptyTypes)); + generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes)); generator.Emit(OpCodes.Throw); generator.MarkLabel(argsOk); @@ -104,7 +104,7 @@ namespace Newtonsoft.Json.Utilities public override Func CreateDefaultConstructor(Type type) { - DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), Type.EmptyTypes, type); + DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), ReflectionUtils.EmptyTypes, type); dynamicMethod.InitLocals = true; ILGenerator generator = dynamicMethod.GetILGenerator(); @@ -115,7 +115,7 @@ namespace Newtonsoft.Json.Utilities private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator) { - if (type.IsValueType) + if (type.IsValueType()) { generator.DeclareLocal(type); generator.Emit(OpCodes.Ldloc_0); @@ -125,7 +125,7 @@ namespace Newtonsoft.Json.Utilities { ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, - Type.EmptyTypes, null); + ReflectionUtils.EmptyTypes, null); if (constructorInfo == null) throw new Exception("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); diff --git a/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs b/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs index 78995094..5882bd6d 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs @@ -1,4 +1,4 @@ -#if !SILVERLIGHT && !PocketPC +#if !SILVERLIGHT && !PocketPC && !NETFX_CORE using System; using System.Collections.Generic; using System.IO; @@ -108,7 +108,7 @@ namespace Newtonsoft.Json.Utilities WrapperMethodBuilder wrapperMethod = new WrapperMethodBuilder(underlyingType, wrapperBuilder); - foreach (MethodInfo method in interfaceType.AllMethods()) + foreach (MethodInfo method in interfaceType.GetAllMethods()) { wrapperMethod.Generate(method); } @@ -233,57 +233,5 @@ namespace Newtonsoft.Json.Utilities _wrapperTypes.Add(key, wrapperType); } } - - internal static class TypeExtensions - { - public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes) - { - var methods = type.GetMethods().Where(method => method.Name == name); - - foreach (var method in methods) - { - if (method.HasParameters(parameterTypes)) - return method; - } - - return null; - } - - public static bool HasParameters(this MethodInfo method, params Type[] parameterTypes) - { - var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); - - if (methodParameters.Length != parameterTypes.Length) - return false; - - for (int i = 0; i < methodParameters.Length; i++) - if (methodParameters[i].ToString() != parameterTypes[i].ToString()) - return false; - - return true; - } - - public static IEnumerable AllInterfaces(this Type target) - { - foreach (var IF in target.GetInterfaces()) - { - yield return IF; - foreach (var childIF in IF.AllInterfaces()) - { - yield return childIF; - } - } - } - - public static IEnumerable AllMethods(this Type target) - { - var allTypes = target.AllInterfaces().ToList(); - allTypes.Add(target); - - return from type in allTypes - from method in type.GetMethods() - select method; - } - } } #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index 1d904f2e..57e034f9 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -103,7 +103,7 @@ namespace Newtonsoft.Json.Utilities public static IList GetValues(Type enumType) { - if (!enumType.IsEnum) + if (!enumType.IsEnum()) throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); List values = new List(); @@ -123,7 +123,7 @@ namespace Newtonsoft.Json.Utilities public static IList GetNames(Type enumType) { - if (!enumType.IsEnum) + if (!enumType.IsEnum()) throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); List values = new List(); diff --git a/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs b/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs index c508fc49..1739d124 100644 --- a/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs +++ b/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs @@ -38,7 +38,7 @@ namespace Newtonsoft.Json.Utilities public static void PushInstance(this ILGenerator generator, Type type) { generator.Emit(OpCodes.Ldarg_0); - if (type.IsValueType) + if (type.IsValueType()) generator.Emit(OpCodes.Unbox, type); else generator.Emit(OpCodes.Castclass, type); @@ -46,7 +46,7 @@ namespace Newtonsoft.Json.Utilities public static void BoxIfNeeded(this ILGenerator generator, Type type) { - if (type.IsValueType) + if (type.IsValueType()) generator.Emit(OpCodes.Box, type); else generator.Emit(OpCodes.Castclass, type); @@ -54,7 +54,7 @@ namespace Newtonsoft.Json.Utilities public static void UnboxIfNeeded(this ILGenerator generator, Type type) { - if (type.IsValueType) + if (type.IsValueType()) generator.Emit(OpCodes.Unbox_Any, type); else generator.Emit(OpCodes.Castclass, type); diff --git a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs index c96be702..f83e3160 100644 --- a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs @@ -53,7 +53,7 @@ namespace Newtonsoft.Json.Utilities { ValidationUtils.ArgumentNotNull(type, "type"); - if (type.IsValueType) + if (type.IsValueType()) return () => (T)ReflectionUtils.CreateInstance(type); ConstructorInfo constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true); diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index be3f467c..2764cab6 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -33,11 +33,107 @@ using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Text.RegularExpressions; +#if NETFX_CORE +using IConvertible = Newtonsoft.Json.Utilities.Convertible; +using ICustomAttributeProvider = Newtonsoft.Json.Utilities.CustomAttributeProvider; +#endif namespace Newtonsoft.Json.Utilities { +#if NETFX_CORE + internal enum TypeCode + { + Empty, + Object, + String, + Char, + Boolean, + SByte, + Int16, + UInt16, + Int32, + Byte, + UInt32, + Int64, + UInt64, + Single, + Double, + DateTime, + Decimal + } + + internal enum MemberTypes + { + Property, + Field, + Event, + Method, + Other + } + + [Flags] + internal enum BindingFlags + { + Default = 0, + IgnoreCase = 1, + DeclaredOnly = 2, + Instance = 4, + Static = 8, + Public = 16, + NonPublic = 32, + FlattenHierarchy = 64, + InvokeMethod = 256, + CreateInstance = 512, + GetField = 1024, + SetField = 2048, + GetProperty = 4096, + SetProperty = 8192, + PutDispProperty = 16384, + ExactBinding = 65536, + PutRefDispProperty = 32768, + SuppressChangeType = 131072, + OptionalParamBinding = 262144, + IgnoreReturn = 16777216 + } + + internal class CustomAttributeProvider + { + private readonly object _underlyingObject; + + public CustomAttributeProvider(object o) + { + _underlyingObject = o; + } + + public object UnderlyingObject + { + get { return _underlyingObject; } + } + } +#endif + internal static class ReflectionUtils { + public static readonly Type[] EmptyTypes; + + static ReflectionUtils() + { +#if !NETFX_CORE + EmptyTypes = Type.EmptyTypes; +#else + EmptyTypes = new Type[0]; +#endif + } + + public static ICustomAttributeProvider GetCustomAttributeProvider(this object o) + { +#if !NETFX_CORE + return (ICustomAttributeProvider)o; +#else + return new ICustomAttributeProvider(o); +#endif + } + public static bool IsVirtual(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); @@ -139,7 +235,7 @@ namespace Newtonsoft.Json.Utilities { ValidationUtils.ArgumentNotNull(t, "t"); - if (t.IsAbstract || t.IsInterface || t.IsArray || t.IsGenericTypeDefinition || t == typeof(void)) + if (t.IsAbstract() || t.IsInterface() || t.IsArray || t.IsGenericTypeDefinition() || t == typeof(void)) return false; if (!HasDefaultConstructor(t)) @@ -157,7 +253,7 @@ namespace Newtonsoft.Json.Utilities { ValidationUtils.ArgumentNotNull(t, "t"); - if (t.IsValueType) + if (t.IsValueType()) return true; return (GetDefaultConstructor(t, nonPublic) != null); @@ -170,19 +266,18 @@ namespace Newtonsoft.Json.Utilities public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { - BindingFlags accessModifier = BindingFlags.Public; - + BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) - accessModifier = accessModifier | BindingFlags.NonPublic; + bindingFlags = bindingFlags | BindingFlags.NonPublic; - return t.GetConstructor(accessModifier | BindingFlags.Instance, null, new Type[0], null); + return t.GetConstructor(bindingFlags, null, ReflectionUtils.EmptyTypes, null); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); - if (t.IsValueType) + if (t.IsValueType()) return IsNullableType(t); return true; @@ -192,7 +287,7 @@ namespace Newtonsoft.Json.Utilities { ValidationUtils.ArgumentNotNull(t, "t"); - return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); + return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type EnsureNotNullableType(Type t) @@ -213,12 +308,12 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); - if (!genericInterfaceDefinition.IsInterface || !genericInterfaceDefinition.IsGenericTypeDefinition) + if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); - if (type.IsInterface) + if (type.IsInterface()) { - if (type.IsGenericType) + if (type.IsGenericType()) { Type interfaceDefinition = type.GetGenericTypeDefinition(); @@ -232,7 +327,7 @@ namespace Newtonsoft.Json.Utilities foreach (Type i in type.GetInterfaces()) { - if (i.IsGenericType) + if (i.IsGenericType()) { Type interfaceDefinition = i.GetGenericTypeDefinition(); @@ -248,40 +343,6 @@ namespace Newtonsoft.Json.Utilities return false; } - public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) - { - Type current = type; - - while (current != null) - { - if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) - { - match = current; - return true; - } - - current = current.BaseType; - } - - foreach (Type i in type.GetInterfaces()) - { - if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) - { - match = type; - return true; - } - } - - match = null; - return false; - } - - public static bool AssignableToTypeName(this Type type, string fullTypeName) - { - Type match; - return type.AssignableToTypeName(fullTypeName, out match); - } - public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; @@ -293,7 +354,7 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); - if (!genericClassDefinition.IsClass || !genericClassDefinition.IsGenericTypeDefinition) + if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); @@ -301,7 +362,7 @@ namespace Newtonsoft.Json.Utilities private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { - if (currentType.IsGenericType) + if (currentType.IsGenericType()) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); @@ -312,13 +373,13 @@ namespace Newtonsoft.Json.Utilities } } - if (currentType.BaseType == null) + if (currentType.BaseType() == null) { implementingType = null; return false; } - return InheritsGenericDefinitionInternal(currentType.BaseType, genericClassDefinition, out implementingType); + return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType); } /// @@ -337,7 +398,7 @@ namespace Newtonsoft.Json.Utilities } else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { - if (genericListType.IsGenericTypeDefinition) + if (genericListType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; @@ -359,7 +420,7 @@ namespace Newtonsoft.Json.Utilities Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { - if (genericDictionaryType.IsGenericTypeDefinition) + if (genericDictionaryType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); @@ -407,7 +468,7 @@ namespace Newtonsoft.Json.Utilities { ValidationUtils.ArgumentNotNull(member, "member"); - switch (member.MemberType) + switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; @@ -464,7 +525,7 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); - switch (member.MemberType) + switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); @@ -493,7 +554,7 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); - switch (member.MemberType) + switch (member.MemberType()) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); @@ -516,7 +577,7 @@ namespace Newtonsoft.Json.Utilities /// public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { - switch (member.MemberType) + switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; @@ -550,7 +611,7 @@ namespace Newtonsoft.Json.Utilities /// public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly) { - switch (member.MemberType) + switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; @@ -608,11 +669,12 @@ namespace Newtonsoft.Json.Utilities private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { - if (memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) + MemberTypes memberType = memberInfo.MemberType(); + if (memberType != MemberTypes.Field && memberType != MemberTypes.Property) throw new ArgumentException("Member must be a field or property."); Type declaringType = memberInfo.DeclaringType; - if (!declaringType.IsGenericType) + if (!declaringType.IsGenericType()) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) @@ -639,6 +701,7 @@ namespace Newtonsoft.Json.Utilities return attributes.SingleOrDefault(); } +#if !NETFX_CORE public static T[] GetAttributes(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); @@ -663,12 +726,35 @@ namespace Newtonsoft.Json.Utilities return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); } +#else + public static T[] GetAttributes(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute + { + object provider = attributeProvider.UnderlyingObject; + + if (provider is Type) + return ((Type)provider).GetTypeInfo().GetCustomAttributes(inherit).ToArray(); + + if (provider is Assembly) + return ((Assembly)provider).GetCustomAttributes().ToArray(); + + if (provider is MemberInfo) + return ((MemberInfo)provider).GetCustomAttributes(inherit).ToArray(); + + if (provider is Module) + return ((Module)provider).GetCustomAttributes().ToArray(); + + if (provider is ParameterInfo) + return ((ParameterInfo)provider).GetCustomAttributes(inherit).ToArray(); + + throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); + } +#endif public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty(innerTypes, "innerTypes"); - ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition)); + ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition(), "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition)); return genericTypeDefinition.MakeGenericType(innerTypes); } @@ -780,7 +866,7 @@ namespace Newtonsoft.Json.Utilities { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; - switch (memberInfo.MemberType) + switch (memberInfo.MemberType()) { case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo) memberInfo; @@ -789,7 +875,7 @@ namespace Newtonsoft.Json.Utilities return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null); default: - return targetType.GetMember(memberInfo.Name, memberInfo.MemberType, bindingAttr).SingleOrDefault(); + return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault(); } } @@ -798,9 +884,11 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(targetType, "targetType"); List fieldInfos = new List(targetType.GetFields(bindingAttr)); +#if !NETFX_CORE // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); +#endif return fieldInfos.Cast(); } @@ -814,7 +902,7 @@ namespace Newtonsoft.Json.Utilities // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); - while ((targetType = targetType.BaseType) != null) + while ((targetType = targetType.BaseType()) != null) { // filter out protected fields IEnumerable childPrivateFields = @@ -862,7 +950,7 @@ namespace Newtonsoft.Json.Utilities // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); - while ((targetType = targetType.BaseType) != null) + while ((targetType = targetType.BaseType()) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(nonPublicBindingAttr)) { diff --git a/Src/Newtonsoft.Json/Utilities/StringUtils.cs b/Src/Newtonsoft.Json/Utilities/StringUtils.cs index e6cd6c6d..91cd3c83 100644 --- a/Src/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/StringUtils.cs @@ -136,7 +136,13 @@ namespace Newtonsoft.Json.Utilities if (!char.IsUpper(s[0])) return s; - string camelCase = char.ToLower(s[0], CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); + string camelCase = null; +#if !NETFX_CORE + camelCase = char.ToLower(s[0], CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); +#else + camelCase = char.ToLower(s[0]).ToString(); +#endif + if (s.Length > 1) camelCase += s.Substring(1); diff --git a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs new file mode 100644 index 00000000..7d761f91 --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs @@ -0,0 +1,537 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace Newtonsoft.Json.Utilities +{ + internal static class TypeExtensions + { +#if NETFX_CORE + private static BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; + + public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo) + { + return propertyInfo.GetGetMethod(false); + } + + public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) + { + MethodInfo getMethod = propertyInfo.GetMethod; + if (getMethod != null && (getMethod.IsPublic || nonPublic)) + return getMethod; + + return null; + } + + public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo) + { + return propertyInfo.GetSetMethod(false); + } + + public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) + { + MethodInfo setMethod = propertyInfo.SetMethod; + if (setMethod != null && (setMethod.IsPublic || nonPublic)) + return setMethod; + + return null; + } + + public static bool IsSubclassOf(this Type type, Type c) + { + return type.GetTypeInfo().IsSubclassOf(c); + } + + public static bool IsAssignableFrom(this Type type, Type c) + { + return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo()); + } +#endif + + public static MemberTypes MemberType(this MemberInfo memberInfo) + { +#if !NETFX_CORE + return memberInfo.MemberType; +#else + if (memberInfo is PropertyInfo) + return MemberTypes.Property; + else if (memberInfo is FieldInfo) + return MemberTypes.Field; + else if (memberInfo is EventInfo) + return MemberTypes.Event; + else if (memberInfo is MethodInfo) + return MemberTypes.Method; + else + return MemberTypes.Other; +#endif + } + + public static Module Module(this Type type) + { +#if !NETFX_CORE + return type.Module; +#else + return type.GetTypeInfo().Module; +#endif + } + + public static bool ContainsGenericParameters(this Type type) + { +#if !NETFX_CORE + return type.ContainsGenericParameters; +#else + return type.GetTypeInfo().ContainsGenericParameters; +#endif + } + + public static bool IsInterface(this Type type) + { +#if !NETFX_CORE + return type.IsInterface; +#else + return type.GetTypeInfo().IsInterface; +#endif + } + + public static bool IsGenericType(this Type type) + { +#if !NETFX_CORE + return type.IsGenericType; +#else + return type.GetTypeInfo().IsGenericType; +#endif + } + + public static bool IsGenericTypeDefinition(this Type type) + { +#if !NETFX_CORE + return type.IsGenericTypeDefinition; +#else + return type.GetTypeInfo().IsGenericTypeDefinition; +#endif + } + + public static Type BaseType(this Type type) + { +#if !NETFX_CORE + return type.BaseType; +#else + return type.GetTypeInfo().BaseType; +#endif + } + + public static bool IsEnum(this Type type) + { +#if !NETFX_CORE + return type.IsEnum; +#else + return type.GetTypeInfo().IsEnum; +#endif + } + + public static bool IsClass(this Type type) + { +#if !NETFX_CORE + return type.IsClass; +#else + return type.GetTypeInfo().IsClass; +#endif + } + + public static bool IsSealed(this Type type) + { +#if !NETFX_CORE + return type.IsSealed; +#else + return type.GetTypeInfo().IsSealed; +#endif + } + +#if NETFX_CORE + public static bool IsDefined(this Type type, Type attributeType, bool inherit) + { + return type.GetTypeInfo().CustomAttributes.Any(a => a.AttributeType == attributeType); + } + + public static MethodInfo GetMethod(this Type type, string name) + { + return type.GetMethod(name, DefaultFlags); + } + + public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetDeclaredMethod(name); + } + + public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags, object placeholder1, Type propertyType, IList indexParameters, object placeholder2) + { + return type.GetTypeInfo().DeclaredProperties.Where(p => + { + if (name != null && name != p.Name) + return false; + if (propertyType != null && propertyType != p.PropertyType) + return false; + if (indexParameters != null) + { + if (!p.GetIndexParameters().Select(ip => ip.ParameterType).SequenceEqual(indexParameters)) + return false; + } + + return true; + }).SingleOrDefault(); + } + + public static IEnumerable GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetMembersRecursive().Where(m => + { + if (name != null && name != m.Name) + return false; + if (m.GetMemberType() != memberType) + return false; + if (!TestAccessibility(m, bindingFlags)) + return false; + + return true; + }); + } + + public static MethodInfo GetMethod(this Type type, IList parameterTypes) + { + return type.GetMethod(null, parameterTypes); + } + + public static MethodInfo GetMethod(this Type type, string name, IList parameterTypes) + { + return type.GetMethod(name, DefaultFlags, null, parameterTypes, null); + } + + public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags, object placeHolder1, IList parameterTypes, object placeHolder2) + { + return type.GetTypeInfo().DeclaredMethods.Where(m => + { + if (name != null && m.Name != name) + return false; + + if (!TestAccessibility(m, bindingFlags)) + return false; + + return m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes); + }).SingleOrDefault(); + } + + public static IEnumerable GetConstructors(this Type type) + { + return type.GetConstructors(DefaultFlags); + } + + public static IEnumerable GetConstructors(this Type type, BindingFlags bindingFlags) + { + return type.GetConstructors(bindingFlags, null); + } + + private static IEnumerable GetConstructors(this Type type, BindingFlags bindingFlags, IList parameterTypes) + { + return type.GetTypeInfo().DeclaredConstructors.Where(c => + { + if (!TestAccessibility(c, bindingFlags)) + return false; + + if (parameterTypes != null && !c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)) + return false; + + return true; + }); + } + + public static ConstructorInfo GetConstructor(this Type type, IList parameterTypes) + { + return type.GetConstructor(DefaultFlags, null, parameterTypes, null); + } + + public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object placeholder1, IList parameterTypes, object placeholder2) + { + return type.GetConstructors(bindingFlags, parameterTypes).SingleOrDefault(); + } + + public static MemberInfo[] GetMember(this Type type, string member) + { + return type.GetMember(member, DefaultFlags); + } + + public static MemberInfo[] GetMember(this Type type, string member, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetMembersRecursive().Where(m => m.Name == member && TestAccessibility(m, bindingFlags)).ToArray(); + } + + public static MemberInfo GetField(this Type type, string member) + { + return type.GetField(member, DefaultFlags); + } + + public static MemberInfo GetField(this Type type, string member, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetDeclaredField(member); + } + + public static IEnumerable GetProperties(this Type type, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetPropertiesRecursive().Where(p => TestAccessibility(p, bindingFlags)); + } + + private static IList GetMembersRecursive(this TypeInfo type) + { + TypeInfo t = type; + IList members = new List(); + while (t != null) + { + foreach (var member in t.DeclaredMembers) + { + if (!members.Any(p => p.Name == member.Name)) + members.Add(member); + } + t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; + } + + return members; + } + + private static IList GetPropertiesRecursive(this TypeInfo type) + { + TypeInfo t = type; + IList properties = new List(); + while (t != null) + { + foreach (var member in t.DeclaredProperties) + { + if (!properties.Any(p => p.Name == member.Name)) + properties.Add(member); + } + t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; + } + + return properties; + } + + private static IList GetFieldsRecursive(this TypeInfo type) + { + TypeInfo t = type; + IList fields = new List(); + while (t != null) + { + foreach (var member in t.DeclaredFields) + { + if (!fields.Any(p => p.Name == member.Name)) + fields.Add(member); + } + t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; + } + + return fields; + } + + public static IEnumerable GetMethods(this Type type, BindingFlags bindingFlags) + { + return type.GetTypeInfo().DeclaredMethods; + } + + public static PropertyInfo GetProperty(this Type type, string name) + { + return type.GetProperty(name, DefaultFlags); + } + + public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetDeclaredProperty(name); + } + + public static IEnumerable GetFields(this Type type) + { + return type.GetFields(DefaultFlags); + } + + public static IEnumerable GetFields(this Type type, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetFieldsRecursive().Where(f => TestAccessibility(f, bindingFlags)).ToList(); + } + + private static bool TestAccessibility(PropertyInfo member, BindingFlags bindingFlags) + { + if (member.GetMethod != null && TestAccessibility(member.GetMethod, bindingFlags)) + return true; + + if (member.SetMethod != null && TestAccessibility(member.SetMethod, bindingFlags)) + return true; + + return false; + } + + private static bool TestAccessibility(MemberInfo member, BindingFlags bindingFlags) + { + if (member is FieldInfo) + { + return TestAccessibility((FieldInfo)member, bindingFlags); + } + else if (member is MethodBase) + { + return TestAccessibility((MethodBase)member, bindingFlags); + } + else if (member is PropertyInfo) + { + return TestAccessibility((PropertyInfo)member, bindingFlags); + } + + throw new Exception("Unexpected member type."); + } + + private static bool TestAccessibility(FieldInfo member, BindingFlags bindingFlags) + { + bool visibility = (member.IsPublic && bindingFlags.HasFlag(BindingFlags.Public)) || + (!member.IsPublic && bindingFlags.HasFlag(BindingFlags.NonPublic)); + + bool instance = (member.IsStatic && bindingFlags.HasFlag(BindingFlags.Static)) || + (!member.IsStatic && bindingFlags.HasFlag(BindingFlags.Instance)); + + return visibility && instance; + } + + private static bool TestAccessibility(MethodBase member, BindingFlags bindingFlags) + { + bool visibility = (member.IsPublic && bindingFlags.HasFlag(BindingFlags.Public)) || + (!member.IsPublic && bindingFlags.HasFlag(BindingFlags.NonPublic)); + + bool instance = (member.IsStatic && bindingFlags.HasFlag(BindingFlags.Static)) || + (!member.IsStatic && bindingFlags.HasFlag(BindingFlags.Instance)); + + return visibility && instance; + } + + public static Type[] GetGenericArguments(this Type type) + { + return type.GetTypeInfo().GenericTypeArguments; + } + + public static IEnumerable GetInterfaces(this Type type) + { + return type.GetTypeInfo().ImplementedInterfaces; + } + + public static IEnumerable GetMethods(this Type type) + { + return type.GetTypeInfo().DeclaredMethods; + } +#endif + + public static bool IsAbstract(this Type type) + { +#if !NETFX_CORE + return type.IsAbstract; +#else + return type.GetTypeInfo().IsAbstract; +#endif + } + + public static bool IsVisible(this Type type) + { +#if !NETFX_CORE + return type.IsVisible; +#else + return type.GetTypeInfo().IsVisible; +#endif + } + + public static bool IsValueType(this Type type) + { +#if !NETFX_CORE + return type.IsValueType; +#else + return type.GetTypeInfo().IsValueType; +#endif + } + + public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) + { + Type current = type; + + while (current != null) + { + if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) + { + match = current; + return true; + } + + current = current.BaseType(); + } + + foreach (Type i in type.GetInterfaces()) + { + if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) + { + match = type; + return true; + } + } + + match = null; + return false; + } + + public static bool AssignableToTypeName(this Type type, string fullTypeName) + { + Type match; + return type.AssignableToTypeName(fullTypeName, out match); + } + + public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes) + { + var methods = type.GetMethods().Where(method => method.Name == name); + + foreach (var method in methods) + { + if (method.HasParameters(parameterTypes)) + return method; + } + + return null; + } + + public static bool HasParameters(this MethodInfo method, params Type[] parameterTypes) + { + var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); + + if (methodParameters.Length != parameterTypes.Length) + return false; + + for (int i = 0; i < methodParameters.Length; i++) + if (methodParameters[i].ToString() != parameterTypes[i].ToString()) + return false; + + return true; + } + + public static IEnumerable GetAllInterfaces(this Type target) + { + foreach (var i in target.GetInterfaces()) + { + yield return i; + foreach (var ci in i.GetInterfaces()) + { + yield return ci; + } + } + } + + public static IEnumerable GetAllMethods(this Type target) + { + var allTypes = target.GetAllInterfaces().ToList(); + allTypes.Add(target); + + return from type in allTypes + from method in type.GetMethods() + select method; + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs b/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs index 47e724e6..4e905c6d 100644 --- a/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs @@ -46,7 +46,7 @@ namespace Newtonsoft.Json.Utilities { ArgumentNotNull(enumType, "enumType"); - if (!enumType.IsEnum) + if (!enumType.IsEnum()) throw new ArgumentException("Type {0} is not an Enum.".FormatWith(CultureInfo.InvariantCulture, enumType), parameterName); }