Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/mono/Newtonsoft.Json.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJames Newton-King <james@newtonking.com>2012-03-15 09:34:51 +0400
committerJames Newton-King <james@newtonking.com>2012-03-15 09:34:51 +0400
commit5800e97ff36d3dacea20ec75e80ebfa5f76100cd (patch)
tree25efafe5c48e846797bd9a4119ab2b130d686b8b
parentf9e5745425f3d4e7ca4da340f583a45c7d495660 (diff)
-Added Newtonsoft.Json.Metro build (whew, what a pain!)
-Added .gitignore file
-rw-r--r--.gitignore5
-rw-r--r--Src/Newtonsoft.Json.Metro.sln64
-rw-r--r--Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs64
-rw-r--r--Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs86
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs19
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs8
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs10
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs27
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs18
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs16
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs11
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/RegexConverterTests.cs11
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs20
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs9
-rw-r--r--Src/Newtonsoft.Json.Tests/ExceptionTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Images/UnitTestLogo.pngbin0 -> 5789 bytes
-rw-r--r--Src/Newtonsoft.Json.Tests/Images/UnitTestSmallLogo.pngbin0 -> 745 bytes
-rw-r--r--Src/Newtonsoft.Json.Tests/Images/UnitTestSplashScreen.pngbin0 -> 9381 bytes
-rw-r--r--Src/Newtonsoft.Json.Tests/Images/UnitTestStoreLogo.pngbin0 -> 2005 bytes
-rw-r--r--Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/JsonConvertTest.cs35
-rw-r--r--Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs237
-rw-r--r--Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs25
-rw-r--r--Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs50
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/ComponentModel/BindingTests.cs3
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs3
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs137
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs93
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JConstructorTests.cs16
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs289
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs69
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs33
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs9
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JTokenEqualityComparerTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs82
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs33
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs9
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs82
-rw-r--r--Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs48
-rw-r--r--Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj320
-rw-r--r--Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro_TemporaryKey.pfxbin0 -> 2460 bytes
-rw-r--r--Src/Newtonsoft.Json.Tests/Package.appxmanifest54
-rw-r--r--Src/Newtonsoft.Json.Tests/PerformanceTests.cs11
-rw-r--r--Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs2
-rw-r--r--Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs107
-rw-r--r--Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs18
-rw-r--r--Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs22
-rw-r--r--Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs9
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs17
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs20
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs32
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs9
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/JsonPropertyCollectionTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs386
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs19
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs14
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs20
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs7
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs10
-rw-r--r--Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs56
-rw-r--r--Src/Newtonsoft.Json.Tests/SilverlightTests.cs6
-rw-r--r--Src/Newtonsoft.Json.Tests/TestFixtureBase.cs72
-rw-r--r--Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs2
-rw-r--r--Src/Newtonsoft.Json.Tests/TestObjects/DefaultValueAttributeTestClass.cs2
-rw-r--r--Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs1
-rw-r--r--Src/Newtonsoft.Json.Tests/TestObjects/Person.cs2
-rw-r--r--Src/Newtonsoft.Json.Tests/TestObjects/SerializationEventTestList.cs1
-rw-r--r--Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs2
-rw-r--r--Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs63
-rw-r--r--Src/Newtonsoft.Json.Tests/Utilities/ReflectionUtilsTests.cs7
-rw-r--r--Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs4
-rw-r--r--Src/Newtonsoft.Json/Bson/BsonReader.cs4
-rw-r--r--Src/Newtonsoft.Json/Bson/BsonWriter.cs8
-rw-r--r--Src/Newtonsoft.Json/Converters/BinaryConverter.cs10
-rw-r--r--Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs1
-rw-r--r--Src/Newtonsoft.Json/Converters/DataSetConverter.cs2
-rw-r--r--Src/Newtonsoft.Json/Converters/DataTableConverter.cs2
-rw-r--r--Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs2
-rw-r--r--Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs2
-rw-r--r--Src/Newtonsoft.Json/Converters/StringEnumConverter.cs2
-rw-r--r--Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs14
-rw-r--r--Src/Newtonsoft.Json/FormatterAssemblyStyle.cs2
-rw-r--r--Src/Newtonsoft.Json/JsonConvert.cs19
-rw-r--r--Src/Newtonsoft.Json/JsonReader.cs4
-rw-r--r--Src/Newtonsoft.Json/JsonReaderException.cs4
-rw-r--r--Src/Newtonsoft.Json/JsonSerializationException.cs4
-rw-r--r--Src/Newtonsoft.Json/JsonTextReader.cs4
-rw-r--r--Src/Newtonsoft.Json/JsonTextWriter.cs4
-rw-r--r--Src/Newtonsoft.Json/JsonWriter.cs7
-rw-r--r--Src/Newtonsoft.Json/JsonWriterException.cs4
-rw-r--r--Src/Newtonsoft.Json/Linq/JContainer.cs20
-rw-r--r--Src/Newtonsoft.Json/Linq/JObject.cs16
-rw-r--r--Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs2
-rw-r--r--Src/Newtonsoft.Json/Linq/JToken.cs4
-rw-r--r--Src/Newtonsoft.Json/Linq/JTokenWriter.cs8
-rw-r--r--Src/Newtonsoft.Json/Linq/JValue.cs2
-rw-r--r--Src/Newtonsoft.Json/Newtonsoft.Json.Metro.csproj282
-rw-r--r--Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj1
-rw-r--r--Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj1
-rw-r--r--Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj1
-rw-r--r--Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj1
-rw-r--r--Src/Newtonsoft.Json/Newtonsoft.Json.csproj1
-rw-r--r--Src/Newtonsoft.Json/Properties/AssemblyInfo.cs2
-rw-r--r--Src/Newtonsoft.Json/Schema/JsonSchemaException.cs4
-rw-r--r--Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs18
-rw-r--r--Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs3
-rw-r--r--Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs69
-rw-r--r--Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs9
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs4
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonContract.cs7
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs6
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs2
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs2
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs2
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs18
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs20
-rw-r--r--Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs80
-rw-r--r--Src/Newtonsoft.Json/Serialization/LateBoundMetadataTypeAttribute.cs2
-rw-r--r--Src/Newtonsoft.Json/SerializationBinder.cs2
-rw-r--r--Src/Newtonsoft.Json/Utilities/CollectionUtils.cs4
-rw-r--r--Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs2
-rw-r--r--Src/Newtonsoft.Json/Utilities/ConvertUtils.cs202
-rw-r--r--Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs2
-rw-r--r--Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs284
-rw-r--r--Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs12
-rw-r--r--Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs12
-rw-r--r--Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs56
-rw-r--r--Src/Newtonsoft.Json/Utilities/EnumUtils.cs4
-rw-r--r--Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs6
-rw-r--r--Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs2
-rw-r--r--Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs216
-rw-r--r--Src/Newtonsoft.Json/Utilities/StringUtils.cs8
-rw-r--r--Src/Newtonsoft.Json/Utilities/TypeExtensions.cs537
-rw-r--r--Src/Newtonsoft.Json/Utilities/ValidationUtils.cs2
141 files changed, 3927 insertions, 1103 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c3673c2
--- /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 0000000..687fce8
--- /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 6c3ae9d..d99ceca 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<JsonReaderException>("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 0e438a0..d5c1d99 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<JsonWriterException>("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<JsonWriterException>("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<JsonWriterException>("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<JsonWriterException>("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<JsonWriterException>("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 94ca068..86d4dce 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<ByteArrayClass>(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<ByteArrayClass>(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 43a1502..eae51bb 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 c333acc..ba1dad3 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 fc4a686..3b39280 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 f07de57..6259ac7 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<object>), d.List);
+ CustomAssert.IsInstanceOfType(typeof(List<object>), 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 e7ac34d..634ca03 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<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
+ ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime.",
+ () =>
+ {
+ DateTimeTestClass c2 =
+ JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""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 c13dd0b..f011126 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<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new JavaScriptDateTimeConverter());
+ ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime.",
+ () =>
+ {
+ DateTimeTestClass c2 =
+ JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""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 55600d2..40d99f8 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<ObjectIdTestClass>(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 7f0b4d8..f5ed3f6 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 685495b..4a7226c 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<NamedEnumDuplicate> c = new EnumContainer<NamedEnumDuplicate>
+ ExceptionAssert.Throws<Exception>("Enum name 'Third' already exists on enum 'NamedEnumDuplicate'.",
+ () =>
{
- Enum = NamedEnumDuplicate.First
- };
+ EnumContainer<NamedEnumDuplicate> c = new EnumContainer<NamedEnumDuplicate>
+ {
+ 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 eaaaf94..48f0858 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 c672ac5..c4e4c93 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 c710c9f..2fb8212 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 0000000..ebd735a
--- /dev/null
+++ b/Src/Newtonsoft.Json.Tests/Images/UnitTestLogo.png
Binary files differ
diff --git a/Src/Newtonsoft.Json.Tests/Images/UnitTestSmallLogo.png b/Src/Newtonsoft.Json.Tests/Images/UnitTestSmallLogo.png
new file mode 100644
index 0000000..92dd105
--- /dev/null
+++ b/Src/Newtonsoft.Json.Tests/Images/UnitTestSmallLogo.png
Binary files differ
diff --git a/Src/Newtonsoft.Json.Tests/Images/UnitTestSplashScreen.png b/Src/Newtonsoft.Json.Tests/Images/UnitTestSplashScreen.png
new file mode 100644
index 0000000..193187f
--- /dev/null
+++ b/Src/Newtonsoft.Json.Tests/Images/UnitTestSplashScreen.png
Binary files differ
diff --git a/Src/Newtonsoft.Json.Tests/Images/UnitTestStoreLogo.png b/Src/Newtonsoft.Json.Tests/Images/UnitTestStoreLogo.png
new file mode 100644
index 0000000..3765186
--- /dev/null
+++ b/Src/Newtonsoft.Json.Tests/Images/UnitTestStoreLogo.png
Binary files differ
diff --git a/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs b/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs
index c370181..fa45495 100644
--- a/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs
+++ b/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs
@@ -27,10 +27,17 @@ 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
namespace Newtonsoft.Json.Tests
{
+ [TestFixture]
public class JsonArrayAttributeTests : TestFixtureBase
{
[Test]
diff --git a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
index 01bfb47..ab2b154 100644
--- a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
+++ b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
@@ -37,10 +37,17 @@ using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.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
{
+ [TestFixture]
public class JsonConvertTest : TestFixtureBase
{
#if Entities
@@ -185,10 +192,13 @@ now brown cow?", '"', true);
}
[Test]
- [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.")]
public void ToStringInvalid()
{
- JsonConvert.ToString(new Version(1, 0));
+ ExceptionAssert.Throws<ArgumentException>("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<JsonReaderException>("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<string>(serialized);
+ JsonConvert.DeserializeObject<string>(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<object> 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 173117b..929b90f 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 ad1effc..e48b913 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 b8950d7..fabfa6b 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<JsonSchemaException>("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<JsonSchemaException>("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<JsonSchemaException>("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 da7ef71..dc54d4d 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 e22adca..df79047 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 83b3f8f..ca2432d 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<DateTimeOffset?>(null);
AssertValueConverted<decimal>(99.9m);
AssertValueConverted<decimal?>(99.9m);
- AssertValueConverted<decimal>(1);
+ AssertValueConverted<decimal>(1m);
AssertValueConverted<decimal>(1.1f, 1.1m);
AssertValueConverted<decimal>("1.1", 1.1m);
AssertValueConverted<double>(99.9);
- AssertValueConverted<double>(99.9m);
- AssertValueConverted<double?>(99.9);
+ AssertValueConverted<double>(99.9d);
+ AssertValueConverted<double?>(99.9d);
AssertValueConverted<float>(99.9f);
AssertValueConverted<float?>(99.9f);
AssertValueConverted<int>(int.MinValue);
@@ -566,7 +577,7 @@ namespace Newtonsoft.Json.Tests.Linq
AssertValueConverted<string>(1, "1");
AssertValueConverted<uint>(uint.MinValue);
AssertValueConverted<uint?>(uint.MinValue);
- AssertValueConverted<uint?>("1", 1);
+ AssertValueConverted<uint?>("1", (uint)1);
AssertValueConverted<ulong>(ulong.MaxValue);
AssertValueConverted<ulong?>(ulong.MaxValue);
AssertValueConverted<ushort>(ushort.MinValue);
diff --git a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs
index dc6cd1b..6ebef28 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 fc85baf..7c43332 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<ArgumentException>(@"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 c8060c0..5790feb 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<Exception>("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<JsonReaderException>(
+ "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<ArgumentException>(
+ "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<ArgumentException>(
+ "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<ArgumentException>(
+ "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<ArgumentException>(
+ "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<ArgumentException>(
+ @"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<JToken> l = new JObject(p1, p2);
+ ExceptionAssert.Throws<ArgumentException>("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<JToken> 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<JToken> l = new JObject(p1, p2);
+ ExceptionAssert.Throws<ArgumentException>("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<JToken> 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<JToken> l = new JObject(p1, p2);
+ ExceptionAssert.Throws<ArgumentException>("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<JToken> 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<JToken> l = new JObject(p1, p2);
+ ExceptionAssert.Throws<ArgumentException>("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<JToken> 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<ArgumentException>("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<ArgumentException>("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<ArgumentException>("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<JsonReaderException>("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<Exception>("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<Exception>("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<JsonReaderException>("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 08031be..108df02 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 b389cc0..a188196 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<JToken> t = new JProperty("error", new List<string> { "one", "two" });
diff --git a/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs
index 8013ad1..d52d4ab 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 ef25332..feb8c6e 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 64136e6..cf9194d 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<JsonReaderException>("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 f578e51..1cf6906 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<ArgumentException>("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<JsonReaderException>("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 a6538c3..08f2854 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 df117f8..b637375 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<InvalidOperationException>("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<InvalidOperationException>("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<InvalidOperationException>("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<int>();
+ ExceptionAssert.Throws<InvalidOperationException>("Cannot access child value on Newtonsoft.Json.Linq.JValue.",
+ () =>
+ {
+ JValue v = new JValue(true);
+ v.Values<int>();
+ });
}
[Test]
- [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "The parent is missing.")]
public void RemoveParentNull()
{
- JValue v = new JValue(true);
- v.Remove();
+ ExceptionAssert.Throws<InvalidOperationException>("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<InvalidOperationException>("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<ArgumentException>("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<IComparable>());
- Assert.AreEqual(1, c);
+ Assert.AreEqual(1L, c);
}
[Test]
public void ConvertValueToFormattableType()
{
IFormattable f = (new JValue(1).Value<IFormattable>());
- 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<object> orderedValues = o.Values().Cast<JValue>().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 e717cb4..7975b6d 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<string>("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<ArgumentException>("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<ArgumentException>(@"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<ArgumentException>(@"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<int>() { 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<int>() { 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 0000000..31b4050
--- /dev/null
+++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj
@@ -0,0 +1,320 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>8.0.30703</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Newtonsoft.Json.Tests</RootNamespace>
+ <AssemblyName>Newtonsoft.Json.Tests</AssemblyName>
+ <DefaultLanguage>en-US</DefaultLanguage>
+ <FileAlignment>512</FileAlignment>
+ <ProjectTypeGuids>{BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+ <PackageCertificateKeyFile>Newtonsoft.Json.Tests.Metro_TemporaryKey.pfx</PackageCertificateKeyFile>
+ <PackageCertificateThumbprint>E58487D6BF8E40BC44C9BE962D19FB3EFBEB81BD</PackageCertificateThumbprint>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\ARM\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>full</DebugType>
+ <PlatformTarget>ARM</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
+ <OutputPath>bin\ARM\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <Optimize>true</Optimize>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>ARM</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\x64\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>full</DebugType>
+ <PlatformTarget>x64</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
+ <OutputPath>bin\x64\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <Optimize>true</Optimize>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>x64</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\x86\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>full</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
+ <OutputPath>bin\x86\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <Optimize>true</Optimize>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup>
+ <AppXPackage>True</AppXPackage>
+ </PropertyGroup>
+ <ItemGroup>
+ <!--A reference to the entire .Net Framework and Windows SDK are automatically included-->
+ <SDKReference Include="MSTestFramework, Version=11.0" />
+ <SDKReference Include="TestPlatform, Version=11.0" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Bson\BsonReaderTests.cs" />
+ <Compile Include="Bson\BsonWriterTests.cs" />
+ <Compile Include="Converters\BinaryConverterTests.cs" />
+ <Compile Include="Converters\CustomCreationConverterTests.cs" />
+ <Compile Include="Converters\DataSetConverterTests.cs" />
+ <Compile Include="Converters\DataTableConverterTests.cs" />
+ <Compile Include="Converters\ExpandoObjectConverterTests.cs" />
+ <Compile Include="Converters\IsoDateTimeConverterTests.cs" />
+ <Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
+ <Compile Include="Converters\ObjectIdConverterTests.cs" />
+ <Compile Include="Converters\RegexConverterTests.cs" />
+ <Compile Include="Converters\StringEnumConverterTests.cs" />
+ <Compile Include="Converters\VersionConverterTests.cs" />
+ <Compile Include="Converters\XmlNodeConverterTest.cs" />
+ <Compile Include="ExceptionTests.cs" />
+ <Compile Include="JsonArrayAttributeTests.cs" />
+ <Compile Include="JsonConvertTest.cs" />
+ <Compile Include="JsonTextReaderTest.cs" />
+ <Compile Include="JsonTextWriterTest.cs" />
+ <Compile Include="JsonValidatingReaderTests.cs" />
+ <Compile Include="Linq\ComponentModel\BindingTests.cs" />
+ <Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" />
+ <Compile Include="Linq\DynamicTests.cs" />
+ <Compile Include="Linq\JArrayTests.cs" />
+ <Compile Include="Linq\JConstructorTests.cs" />
+ <Compile Include="Linq\JObjectTests.cs" />
+ <Compile Include="Linq\JPathTests.cs" />
+ <Compile Include="Linq\JPropertyTests.cs" />
+ <Compile Include="Linq\JRawTests.cs" />
+ <Compile Include="Linq\JTokenEqualityComparerTests.cs" />
+ <Compile Include="Linq\JTokenReaderTest.cs" />
+ <Compile Include="Linq\JTokenTests.cs" />
+ <Compile Include="Linq\JTokenWriterTest.cs" />
+ <Compile Include="Linq\JValueTests.cs" />
+ <Compile Include="Linq\LinqToJsonTest.cs" />
+ <Compile Include="PerformanceTests.cs" />
+ <Compile Include="Schema\ExtensionsTests.cs" />
+ <Compile Include="Schema\JsonSchemaBuilderTests.cs" />
+ <Compile Include="Schema\JsonSchemaGeneratorTests.cs" />
+ <Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
+ <Compile Include="Schema\JsonSchemaNodeTests.cs" />
+ <Compile Include="Schema\JsonSchemaTests.cs" />
+ <Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
+ <Compile Include="Serialization\ConstructorHandlingTests.cs" />
+ <Compile Include="Serialization\ContractResolverTests.cs" />
+ <Compile Include="Serialization\DefaultValueHandlingTests.cs" />
+ <Compile Include="Serialization\DynamicTests.cs" />
+ <Compile Include="Serialization\EntitiesSerializationTests.cs" />
+ <Compile Include="Serialization\JsonPropertyCollectionTests.cs" />
+ <Compile Include="Serialization\JsonSerializerTest.cs" />
+ <Compile Include="Serialization\MissingMemberHandlingTests.cs" />
+ <Compile Include="Serialization\NullValueHandlingTests.cs" />
+ <Compile Include="Serialization\PopulateTests.cs" />
+ <Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
+ <Compile Include="Serialization\SerializationErrorHandlingTests.cs" />
+ <Compile Include="Serialization\SerializationEventAttributeTests.cs" />
+ <Compile Include="Serialization\TypeNameHandlingTests.cs" />
+ <Compile Include="SilverlightTests.cs" />
+ <Compile Include="TestFixtureBase.cs" />
+ <Compile Include="TestObjects\AbstractGenericBase.cs" />
+ <Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
+ <Compile Include="TestObjects\Article.cs" />
+ <Compile Include="TestObjects\ArticleCollection.cs" />
+ <Compile Include="TestObjects\BadJsonPropertyClass.cs" />
+ <Compile Include="TestObjects\Bar.cs" />
+ <Compile Include="TestObjects\Car.cs" />
+ <Compile Include="TestObjects\CircularReferenceClass.cs" />
+ <Compile Include="TestObjects\CircularReferenceWithIdClass.cs" />
+ <Compile Include="TestObjects\ClassAndMemberConverterClass.cs" />
+ <Compile Include="TestObjects\ClassConverterPrecedenceClassConverter.cs" />
+ <Compile Include="TestObjects\ClassWithArray.cs" />
+ <Compile Include="TestObjects\ClassWithGuid.cs" />
+ <Compile Include="TestObjects\Computer.cs" />
+ <Compile Include="TestObjects\ConstructorCaseSensitivityClass.cs" />
+ <Compile Include="TestObjects\ConstructorReadonlyFields.cs" />
+ <Compile Include="TestObjects\Container.cs" />
+ <Compile Include="TestObjects\Content.cs" />
+ <Compile Include="TestObjects\ContentBaseClass.cs" />
+ <Compile Include="TestObjects\ContentSubClass.cs" />
+ <Compile Include="TestObjects\ConverableMembers.cs" />
+ <Compile Include="TestObjects\ConverterPrecedenceClass.cs" />
+ <Compile Include="TestObjects\ConverterPrecedenceClassConverter.cs" />
+ <Compile Include="TestObjects\DateTimeErrorObjectCollection.cs" />
+ <Compile Include="TestObjects\DateTimeTestClass.cs" />
+ <Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
+ <Compile Include="TestObjects\DictionaryInterfaceClass.cs" />
+ <Compile Include="TestObjects\DoubleClass.cs" />
+ <Compile Include="TestObjects\EmployeeReference.cs" />
+ <Compile Include="TestObjects\Event.cs" />
+ <Compile Include="TestObjects\Foo.cs" />
+ <Compile Include="TestObjects\GenericImpl.cs" />
+ <Compile Include="TestObjects\GenericListAndDictionaryInterfaceProperties.cs" />
+ <Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
+ <Compile Include="TestObjects\GoogleMapGeocoderStructure.cs" />
+ <Compile Include="TestObjects\HolderClass.cs" />
+ <Compile Include="TestObjects\IncompatibleJsonAttributeClass.cs" />
+ <Compile Include="TestObjects\InterfacePropertyTestClass.cs" />
+ <Compile Include="TestObjects\Invoice.cs" />
+ <Compile Include="TestObjects\IPrivateImplementationA.cs" />
+ <Compile Include="TestObjects\IPrivateImplementationB.cs" />
+ <Compile Include="TestObjects\IPrivateOverriddenImplementation.cs" />
+ <Compile Include="TestObjects\JaggedArray.cs" />
+ <Compile Include="TestObjects\JsonIgnoreAttributeOnClassTestClass.cs" />
+ <Compile Include="TestObjects\JsonIgnoreAttributeTestClass.cs" />
+ <Compile Include="TestObjects\JsonPropertyClass.cs" />
+ <Compile Include="TestObjects\JsonPropertyWithHandlingValues.cs" />
+ <Compile Include="TestObjects\ListErrorObject.cs" />
+ <Compile Include="TestObjects\ListErrorObjectCollection.cs" />
+ <Compile Include="TestObjects\ListOfIds.cs" />
+ <Compile Include="TestObjects\ListTestClass.cs" />
+ <Compile Include="TestObjects\LogEntry.cs" />
+ <Compile Include="TestObjects\MemberConverterClass.cs" />
+ <Compile Include="TestObjects\MemberConverterPrecedenceClassConverter.cs" />
+ <Compile Include="TestObjects\MethodExecutorObject.cs" />
+ <Compile Include="TestObjects\Movie.cs" />
+ <Compile Include="TestObjects\MyClass.cs" />
+ <Compile Include="TestObjects\Name.cs" />
+ <Compile Include="TestObjects\NonRequest.cs" />
+ <Compile Include="TestObjects\NullableDateTimeTestClass.cs" />
+ <Compile Include="TestObjects\ObjectArrayPropertyTest.cs" />
+ <Compile Include="TestObjects\Person.cs" />
+ <Compile Include="TestObjects\PersonError.cs" />
+ <Compile Include="TestObjects\PersonPropertyClass.cs" />
+ <Compile Include="TestObjects\PersonRaw.cs" />
+ <Compile Include="TestObjects\PhoneNumber.cs" />
+ <Compile Include="TestObjects\PrivateConstructorTestClass.cs" />
+ <Compile Include="TestObjects\PrivateConstructorWithPublicParametizedConstructorTestClass.cs" />
+ <Compile Include="TestObjects\PrivateImplementationAClass.cs" />
+ <Compile Include="TestObjects\PrivateImplementationBClass.cs" />
+ <Compile Include="TestObjects\PrivateMembersClass.cs" />
+ <Compile Include="TestObjects\Product.cs" />
+ <Compile Include="TestObjects\ProductCollection.cs" />
+ <Compile Include="TestObjects\ProductShort.cs" />
+ <Compile Include="TestObjects\PropertyCase.cs" />
+ <Compile Include="TestObjects\PublicParametizedConstructorRequiringConverterTestClass.cs" />
+ <Compile Include="TestObjects\PublicParametizedConstructorTestClass.cs" />
+ <Compile Include="TestObjects\PublicParametizedConstructorWithNonPropertyParameterTestClass.cs" />
+ <Compile Include="TestObjects\PublicParametizedConstructorWithPropertyNameConflict.cs" />
+ <Compile Include="TestObjects\RequestOnly.cs" />
+ <Compile Include="TestObjects\RequiredMembersClass.cs" />
+ <Compile Include="TestObjects\RoleTransfer.cs" />
+ <Compile Include="TestObjects\SearchResult.cs" />
+ <Compile Include="TestObjects\SerializationEventTestDictionary.cs" />
+ <Compile Include="TestObjects\SerializationEventTestList.cs" />
+ <Compile Include="TestObjects\SerializationEventTestObject.cs" />
+ <Compile Include="TestObjects\SerializationEventTestObjectWithConstructor.cs" />
+ <Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
+ <Compile Include="TestObjects\SetOnlyPropertyClass2.cs" />
+ <Compile Include="TestObjects\Shortie.cs" />
+ <Compile Include="TestObjects\Store.cs" />
+ <Compile Include="TestObjects\StoreColor.cs" />
+ <Compile Include="TestObjects\StructTest.cs" />
+ <Compile Include="TestObjects\SubKlass.cs" />
+ <Compile Include="TestObjects\SuperKlass.cs" />
+ <Compile Include="TestObjects\TypeClass.cs" />
+ <Compile Include="TestObjects\TypedSubHashtable.cs" />
+ <Compile Include="TestObjects\UserNullable.cs" />
+ <Compile Include="TestObjects\VersionKeyedCollection.cs" />
+ <Compile Include="TestObjects\WagePerson.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Utilities\DynamicReflectionDelegateFactoryTests.cs" />
+ <Compile Include="Utilities\ReflectionUtilsTests.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <AppxManifest Include="Package.appxmanifest">
+ <SubType>Designer</SubType>
+ </AppxManifest>
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="Images\UnitTestLogo.png">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Images\UnitTestSmallLogo.png">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Images\UnitTestSplashScreen.png">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Images\UnitTestStoreLogo.png">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.Metro.csproj">
+ <Project>{263136a2-b89b-424e-a87a-f988caa8d032}</Project>
+ <Name>Newtonsoft.Json.Metro</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Newtonsoft.Json.Tests.Metro_TemporaryKey.pfx" />
+ </ItemGroup>
+ <PropertyGroup Condition=" '$(VisualStudioVersion)' == '' ">
+ <VisualStudioVersion>11.0</VisualStudioVersion>
+ </PropertyGroup>
+ <Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ 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 0000000..75e05db
--- /dev/null
+++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro_TemporaryKey.pfx
Binary files differ
diff --git a/Src/Newtonsoft.Json.Tests/Package.appxmanifest b/Src/Newtonsoft.Json.Tests/Package.appxmanifest
new file mode 100644
index 0000000..2a894fb
--- /dev/null
+++ b/Src/Newtonsoft.Json.Tests/Package.appxmanifest
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">
+
+ <Identity Name="416af769-23b3-4c62-bc3f-d2f756b8f292"
+ Publisher="CN=James"
+ Version="1.0.0.0" />
+
+ <Properties>
+ <DisplayName>UnitTestProject1</DisplayName>
+ <PublisherDisplayName>James</PublisherDisplayName>
+ <Logo>Images\UnitTestStoreLogo.png</Logo>
+ <Description>UnitTestProject1</Description>
+ </Properties>
+
+ <Prerequisites>
+ <OSMinVersion>6.2</OSMinVersion>
+ <OSMaxVersionTested>6.2</OSMaxVersionTested>
+ </Prerequisites>
+
+ <Resources>
+ <Resource Language="x-generate"/>
+ </Resources>
+
+ <Applications>
+ <Application Id="vstest.executionengine.App"
+ Executable="vstest.executionengine.appcontainer.exe"
+ EntryPoint="vstest.executionengine.App">
+ <VisualElements
+ DisplayName="NoUIEntryPoints"
+ Logo="Images\UnitTestLogo.png"
+ SmallLogo="Images\UnitTestSmallLogo.png"
+ Description="vstest.executionengine.App"
+ ForegroundText="light"
+ BackgroundColor="#0084FF">
+ <SplashScreen Image="Images\UnitTestSplashScreen.png" />
+ </VisualElements>
+ </Application>
+
+ <Application Id="vstest.executionengine.x86.App"
+ Executable="vstest.executionengine.appcontainer.x86.exe"
+ EntryPoint="vstest.executionengine.x86.App">
+ <VisualElements
+ DisplayName="NoUIEntryPoints"
+ Logo="Images\UnitTestLogo.png"
+ SmallLogo="Images\UnitTestSmallLogo.png"
+ Description="vstest.executionengine.x86.App"
+ ForegroundText="light"
+ BackgroundColor="#0084FF">
+ <SplashScreen Image="Images\UnitTestSplashScreen.png" />
+ </VisualElements>
+ </Application>
+ </Applications>
+
+</Package>
diff --git a/Src/Newtonsoft.Json.Tests/PerformanceTests.cs b/Src/Newtonsoft.Json.Tests/PerformanceTests.cs
index 268fe13..1a90f5c 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<T>(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 1646871..c6bc056 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 36e042a..586f793 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<JsonSchemaException>(@"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;
-
- JValue v = new JValue(10);
- v.Validate(schema);
+ ExceptionAssert.Throws<JsonSchemaException>("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);
+ });
}
[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;
-
- JValue v = new JValue(10.1);
- v.Validate(schema);
+ ExceptionAssert.Throws<JsonSchemaException>("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);
+ });
}
[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;
-
- JValue v = new JValue(10);
- v.Validate(schema);
+ ExceptionAssert.Throws<JsonSchemaException>("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);
+ });
}
[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;
-
- JValue v = new JValue(10.1);
- v.Validate(schema);
+ ExceptionAssert.Throws<JsonSchemaException>("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);
+ });
}
[Test]
- [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Integer 10 is not evenly divisible by 3.")]
public void DivisibleBy_Int()
{
- JsonSchema schema = new JsonSchema();
- schema.DivisibleBy = 3;
-
- JValue v = new JValue(10);
- v.Validate(schema);
+ ExceptionAssert.Throws<JsonSchemaException>("Integer 10 is not evenly divisible by 3.",
+ () =>
+ {
+ JsonSchema schema = new JsonSchema();
+ schema.DivisibleBy = 3;
+
+ 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 826f74f..9791286 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<Exception>(@"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 9080aea..1e29588 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<Exception>(@"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 ae2e01a..accc5ed 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 d5a8de1..35542bc 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 959560b..89f26e7 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 e59bc4e..d3b0d50 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 1d48a81..350b6ab 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<TargetInvocationException>(
+ null,
+ () =>
+ {
+ string json = @"{Name:""Name!""}";
- PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json);
+ PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json);
+ });
}
[Test]
diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs
index 178e105..000c85e 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,9 +58,19 @@ 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()
{
Employee employee = new Employee
@@ -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 4c90247..8788a9a 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 b54690c..b87450b 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
@@ -130,12 +137,6 @@ namespace Newtonsoft.Json.Tests.Serialization
}
[Test]
- public void sdfsdf()
- {
- ErrorSettingDynamicObject d = JsonConvert.DeserializeObject<ErrorSettingDynamicObject>("{'hi':5}");
- }
-
- [Test]
public void SerializeDynamicObjectWithObjectTracking()
{
dynamic o = new ExpandoObject();
@@ -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<JsonSerializationException>("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<DynamicObject>(json, settings);
+
+ JsonConvert.DeserializeObject<DynamicObject>(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 a391ff0..48d2a10 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 b2a6782..6ab0df5 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 0f7f7ff..e8f1a89 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<string> javaScriptSerializerResult = javaScriptSerializer.Deserialize<List<string>>(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);
+
+ 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(@"{""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);
+ Assert.AreEqual(expected, json);
ConverableMembers c = JsonConvert.DeserializeObject<ConverableMembers>(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<JsonSerializationException>(
+ "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<JsonSerializationException>("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<RequiredMembersClass>(json);
+ JsonConvert.DeserializeObject<RequiredMembersClass>(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<JsonSerializationException>("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<JsonSerializationException>("Required property 'LastName' not found in JSON. Line 3, position 2.",
+ () =>
+ {
+ string json = @"{
""FirstName"": ""Bob""
}";
- JsonConvert.DeserializeObject<RequiredMembersClass>(json);
+ JsonConvert.DeserializeObject<RequiredMembersClass>(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<T>) or a dictionary type (i.e. Dictionary<TKey, TValue>).
-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<MemoryStream>("{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<MemoryStream>("{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<MemoryStream>("{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<JsonSerializationException>("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<Dictionary<Person, int>>(json);
+ JsonConvert.DeserializeObject<Dictionary<Person, int>>(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<TestClass>(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<string, object>();
- reference.Add("$ref", 1);
- reference.Add("$id", 1);
-
- var child = new Dictionary<string, object>();
- child.Add("_id", 2);
- child.Add("Name", "Isabell");
- child.Add("Father", reference);
-
- var json = JsonConvert.SerializeObject(child, Formatting.Indented);
- JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
+ ExceptionAssert.Throws<JsonSerializationException>("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<string, object>();
+ reference.Add("$ref", 1);
+ reference.Add("$id", 1);
+
+ var child = new Dictionary<string, object>();
+ child.Add("_id", 2);
+ child.Add("Name", "Isabell");
+ child.Add("Father", reference);
+
+ var json = JsonConvert.SerializeObject(child, Formatting.Indented);
+ JsonConvert.DeserializeObject<Dictionary<string, object>>(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<string, object> newExpando = JsonConvert.DeserializeObject<ExpandoObject>(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<string, object> 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<DeserializeStringConvert>(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<JsonReaderException>("Error reading integer. Unexpected token: Boolean. Line 2, position 22.",
+ () =>
+ {
+ string json = @"{
""PreProperty"": true,
""PostProperty"": ""-1""
}";
- JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
+ JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
+ });
}
[Test]
- [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Unexpected end when setting PreProperty's value. Line 2, position 18.")]
public void DeserializeUnexpectedEndInt()
{
- string json = @"{
+ ExceptionAssert.Throws<JsonSerializationException>("Unexpected end when setting PreProperty's value. Line 2, position 18.",
+ () =>
+ {
+ string json = @"{
""PreProperty"": ";
- JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
+ JsonConvert.DeserializeObject<TestObjects.MyClass>(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<double>("");
}
[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<StringComparison>("");
}
[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<int>("");
@@ -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<double>(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 5cdcf33..a80f263 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 21ed6a5..c6b9e4f 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 f00a40a..b79f137 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<JsonSerializationException>("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 40f5251..e6012bf 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 6532f96..5387a78 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 c440f49..27a0aa4 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 48af72c..be2aeff 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<EmployeeReference>
@@ -83,8 +90,8 @@ namespace Newtonsoft.Json.Tests.Serialization
}", json);
Wrapper w2 = JsonConvert.DeserializeObject<Wrapper>(json);
- Assert.IsInstanceOfType(typeof(List<EmployeeReference>), w2.Array);
- Assert.IsInstanceOfType(typeof(Dictionary<string, EmployeeReference>), w2.Dictionary);
+ CustomAssert.IsInstanceOfType(typeof(List<EmployeeReference>), w2.Array);
+ CustomAssert.IsInstanceOfType(typeof(Dictionary<string, EmployeeReference>), 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<TypeNameProperty>(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<TypeNameProperty>(json);
Assert.AreEqual("Name!", deserialized.Name);
- Assert.IsInstanceOfType(typeof(List<int>), deserialized.Value);
+ CustomAssert.IsInstanceOfType(typeof(List<int>), deserialized.Value);
List<int> nested = (List<int>)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<int, IList<ContentBaseClass>>), anotherTestObject.AnotherTestMember);
+ CustomAssert.IsInstanceOfType(typeof(ContentSubClass), anotherTestObject.TestMember);
+ CustomAssert.IsInstanceOfType(typeof(Dictionary<int, IList<ContentBaseClass>>), anotherTestObject.AnotherTestMember);
Assert.AreEqual(1, anotherTestObject.AnotherTestMember.Count);
IList<ContentBaseClass> list = anotherTestObject.AnotherTestMember[1];
- Assert.IsInstanceOfType(typeof(List<ContentBaseClass>), list);
+ CustomAssert.IsInstanceOfType(typeof(List<ContentBaseClass>), 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<string, object>), c);
+ CustomAssert.IsInstanceOfType(typeof(Dictionary<string, object>), c);
Dictionary<string, object> newCollection = (Dictionary<string, object>)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 e037eed..15756f7 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 0a47016..90162e9 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<object>().Any(i => i.Equals(value)))
+ throw new Exception("Value not found in collection.");
+#endif
+ }
+ }
+
+ public static class ExceptionAssert
+ {
+ public static void Throws<TException>(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 9b2e101..6e2c031 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 eeefa5e..394d246 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 7d0ccc3..7576965 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 70176b8..9136296 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 c21c325..017e1bb 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 1c8efe8..d9607ab 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 59c39b0..6da97cb 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<InvalidCastException>("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<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(typeof(Movie).GetProperty("Name"));
+ Func<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(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<InvalidCastException>("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<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
+ Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(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<InvalidCastException>("Specified cast is not valid.",
+ () =>
+ {
+ object structTest = new StructTest();
- Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(StructTest).GetProperty("StringProperty"));
+ Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(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<InvalidCastException>("Unable to cast object of type 'System.Version' to type 'System.String'.",
+ () =>
+ {
+ Movie m = new Movie();
- Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
+ Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(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 9f17faf..a4b0838 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 ff2f08c..7b5f8ce 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 099e561..2c4a773 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 09c5283..2b31163 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));
}
/// <summary>
diff --git a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs
index 361c622..4f39ff1 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<IBinary>(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 a7eb499..de98d66 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 af97e70..dd698d8 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 ec0de77..6fdc07f 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 6dfc287..18c3752 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 791da1e..7ea57ea 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 cc5d480..137bc64 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 e3a8296..300e5e8 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 7cfff8b..95d7dc6 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
{
/// <summary>
diff --git a/Src/Newtonsoft.Json/JsonConvert.cs b/Src/Newtonsoft.Json/JsonConvert.cs
index 33689de..d840564 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
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
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 + '"';
}
/// <summary>
@@ -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)
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs
index c7fb0aa..98ab579 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 e10f39a..71eff9c 100644
--- a/Src/Newtonsoft.Json/JsonReaderException.cs
+++ b/Src/Newtonsoft.Json/JsonReaderException.cs
@@ -31,7 +31,7 @@ namespace Newtonsoft.Json
/// <summary>
/// The exception thrown when an error occurs while reading Json text.
/// </summary>
-#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)
/// <summary>
/// Initializes a new instance of the <see cref="JsonReaderException"/> class.
/// </summary>
diff --git a/Src/Newtonsoft.Json/JsonSerializationException.cs b/Src/Newtonsoft.Json/JsonSerializationException.cs
index 25d3a33..8de7b10 100644
--- a/Src/Newtonsoft.Json/JsonSerializationException.cs
+++ b/Src/Newtonsoft.Json/JsonSerializationException.cs
@@ -33,7 +33,7 @@ namespace Newtonsoft.Json
/// <summary>
/// The exception thrown when an error occurs during Json serialization or deserialization.
/// </summary>
-#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)
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class.
/// </summary>
diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs
index c7ffa80..787d62a 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 1859a21..a7260c6 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
}
/// <summary>
diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs
index 6e7f62f..cd3f709 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 70c57eb..0c93143 100644
--- a/Src/Newtonsoft.Json/JsonWriterException.cs
+++ b/Src/Newtonsoft.Json/JsonWriterException.cs
@@ -33,7 +33,7 @@ namespace Newtonsoft.Json
/// <summary>
/// The exception thrown when an error occurs while reading Json text.
/// </summary>
-#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)
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriterException"/> class.
/// </summary>
diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs
index ec992fe..05f54da 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.
/// </summary>
public abstract class JContainer : JToken, IList<JToken>
-#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
/// <summary>
/// Occurs when the list changes or an item in the list changes.
/// </summary>
@@ -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
/// <summary>
/// Raises the <see cref="AddingNew"/> event.
/// </summary>
@@ -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 13ca2fd..7d8dd29 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.
/// </summary>
public class JObject : JContainer, IDictionary<string, JToken>, 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
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
-#if !(PocketPC || SILVERLIGHT || NET20)
+#if !(PocketPC || SILVERLIGHT || NET20 || NETFX_CORE)
/// <summary>
/// Occurs when a property value is changing.
/// </summary>
@@ -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
/// <summary>
/// Raises the <see cref="PropertyChanging"/> event with the provided arguments.
/// </summary>
@@ -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
/// <summary>
diff --git a/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs b/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs
index dd49c08..13736da 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 15cb4a9..35d94ab 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.
/// </summary>
public abstract class JToken : IJEnumerable<JToken>, 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 ccc02b8..6e5bcf8 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);
}
/// <summary>
diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs
index 7d57412..11d7674 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 0000000..aa54ccb
--- /dev/null
+++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Metro.csproj
@@ -0,0 +1,282 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>8.0.30703</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{263136A2-B89B-424E-A87A-F988CAA8D032}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Newtonsoft.Json</RootNamespace>
+ <AssemblyName>Newtonsoft.Json</AssemblyName>
+ <DefaultLanguage>en-US</DefaultLanguage>
+ <FileAlignment>512</FileAlignment>
+ <ProjectTypeGuids>{BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>3</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\ARM\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>full</DebugType>
+ <PlatformTarget>ARM</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
+ <OutputPath>bin\ARM\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <Optimize>true</Optimize>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>ARM</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\x64\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>full</DebugType>
+ <PlatformTarget>x64</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
+ <OutputPath>bin\x64\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <Optimize>true</Optimize>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>x64</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\x86\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE;NETFX_CORE</DefineConstants>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>full</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
+ <OutputPath>bin\x86\Release\</OutputPath>
+ <DefineConstants>TRACE;NETFX_CORE</DefineConstants>
+ <Optimize>true</Optimize>
+ <NoWarn>;2008</NoWarn>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>ExpressRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <ItemGroup>
+ <!-- A reference to the entire .Net Framework and Windows SDK are automatically included -->
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Bson\BsonBinaryType.cs" />
+ <Compile Include="Bson\BsonBinaryWriter.cs" />
+ <Compile Include="Bson\BsonObjectId.cs" />
+ <Compile Include="Bson\BsonReader.cs" />
+ <Compile Include="Bson\BsonToken.cs" />
+ <Compile Include="Bson\BsonType.cs" />
+ <Compile Include="Bson\BsonWriter.cs" />
+ <Compile Include="ConstructorHandling.cs" />
+ <Compile Include="Converters\BinaryConverter.cs" />
+ <Compile Include="Converters\BsonObjectIdConverter.cs" />
+ <Compile Include="Converters\CustomCreationConverter.cs" />
+ <Compile Include="Converters\DataSetConverter.cs" />
+ <Compile Include="Converters\DataTableConverter.cs" />
+ <Compile Include="Converters\DateTimeConverterBase.cs" />
+ <Compile Include="Converters\EntityKeyMemberConverter.cs" />
+ <Compile Include="Converters\ExpandoObjectConverter.cs" />
+ <Compile Include="Converters\IsoDateTimeConverter.cs" />
+ <Compile Include="Converters\JavaScriptDateTimeConverter.cs" />
+ <Compile Include="Converters\KeyValuePairConverter.cs" />
+ <Compile Include="Converters\RegexConverter.cs" />
+ <Compile Include="Converters\StringEnumConverter.cs" />
+ <Compile Include="Converters\VersionConverter.cs" />
+ <Compile Include="Converters\XmlNodeConverter.cs" />
+ <Compile Include="DateFormatHandling.cs" />
+ <Compile Include="DateTimeZoneHandling.cs" />
+ <Compile Include="DefaultValueHandling.cs" />
+ <Compile Include="FormatterAssemblyStyle.cs" />
+ <Compile Include="Formatting.cs" />
+ <Compile Include="IJsonLineInfo.cs" />
+ <Compile Include="JsonArrayAttribute.cs" />
+ <Compile Include="JsonConstructorAttribute.cs" />
+ <Compile Include="JsonContainerAttribute.cs" />
+ <Compile Include="JsonConvert.cs" />
+ <Compile Include="JsonConverter.cs" />
+ <Compile Include="JsonConverterAttribute.cs" />
+ <Compile Include="JsonConverterCollection.cs" />
+ <Compile Include="JsonIgnoreAttribute.cs" />
+ <Compile Include="JsonObjectAttribute.cs" />
+ <Compile Include="JsonPosition.cs" />
+ <Compile Include="JsonPropertyAttribute.cs" />
+ <Compile Include="JsonReader.cs" />
+ <Compile Include="JsonReaderException.cs" />
+ <Compile Include="JsonSerializationException.cs" />
+ <Compile Include="JsonSerializer.cs" />
+ <Compile Include="JsonSerializerSettings.cs" />
+ <Compile Include="JsonTextReader.cs" />
+ <Compile Include="JsonTextWriter.cs" />
+ <Compile Include="JsonToken.cs" />
+ <Compile Include="JsonValidatingReader.cs" />
+ <Compile Include="JsonWriter.cs" />
+ <Compile Include="JsonWriterException.cs" />
+ <Compile Include="Linq\Extensions.cs" />
+ <Compile Include="Linq\IJEnumerable.cs" />
+ <Compile Include="Linq\JArray.cs" />
+ <Compile Include="Linq\JConstructor.cs" />
+ <Compile Include="Linq\JContainer.cs" />
+ <Compile Include="Linq\JEnumerable.cs" />
+ <Compile Include="Linq\JObject.cs" />
+ <Compile Include="Linq\JPath.cs" />
+ <Compile Include="Linq\JProperty.cs" />
+ <Compile Include="Linq\JPropertyDescriptor.cs" />
+ <Compile Include="Linq\JRaw.cs" />
+ <Compile Include="Linq\JToken.cs" />
+ <Compile Include="Linq\JTokenEqualityComparer.cs" />
+ <Compile Include="Linq\JTokenReader.cs" />
+ <Compile Include="Linq\JTokenType.cs" />
+ <Compile Include="Linq\JTokenWriter.cs" />
+ <Compile Include="Linq\JValue.cs" />
+ <Compile Include="MemberSerialization.cs" />
+ <Compile Include="MissingMemberHandling.cs" />
+ <Compile Include="NullValueHandling.cs" />
+ <Compile Include="ObjectCreationHandling.cs" />
+ <Compile Include="PreserveReferencesHandling.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="ReferenceLoopHandling.cs" />
+ <Compile Include="Required.cs" />
+ <Compile Include="Schema\Extensions.cs" />
+ <Compile Include="Schema\JsonSchema.cs" />
+ <Compile Include="Schema\JsonSchemaBuilder.cs" />
+ <Compile Include="Schema\JsonSchemaConstants.cs" />
+ <Compile Include="Schema\JsonSchemaException.cs" />
+ <Compile Include="Schema\JsonSchemaGenerator.cs" />
+ <Compile Include="Schema\JsonSchemaModel.cs" />
+ <Compile Include="Schema\JsonSchemaModelBuilder.cs" />
+ <Compile Include="Schema\JsonSchemaNode.cs" />
+ <Compile Include="Schema\JsonSchemaNodeCollection.cs" />
+ <Compile Include="Schema\JsonSchemaResolver.cs" />
+ <Compile Include="Schema\JsonSchemaType.cs" />
+ <Compile Include="Schema\JsonSchemaWriter.cs" />
+ <Compile Include="Schema\UndefinedSchemaIdHandling.cs" />
+ <Compile Include="Schema\ValidationEventArgs.cs" />
+ <Compile Include="Schema\ValidationEventHandler.cs" />
+ <Compile Include="SerializationBinder.cs" />
+ <Compile Include="Serialization\CachedAttributeGetter.cs" />
+ <Compile Include="Serialization\CamelCasePropertyNamesContractResolver.cs" />
+ <Compile Include="Serialization\DefaultContractResolver.cs" />
+ <Compile Include="Serialization\DefaultReferenceResolver.cs" />
+ <Compile Include="Serialization\DefaultSerializationBinder.cs" />
+ <Compile Include="Serialization\DynamicValueProvider.cs" />
+ <Compile Include="Serialization\ErrorContext.cs" />
+ <Compile Include="Serialization\ErrorEventArgs.cs" />
+ <Compile Include="Serialization\IContractResolver.cs" />
+ <Compile Include="Serialization\IReferenceResolver.cs" />
+ <Compile Include="Serialization\IValueProvider.cs" />
+ <Compile Include="Serialization\JsonArrayContract.cs" />
+ <Compile Include="Serialization\JsonContract.cs" />
+ <Compile Include="Serialization\JsonDictionaryContract.cs" />
+ <Compile Include="Serialization\JsonDynamicContract.cs" />
+ <Compile Include="Serialization\JsonFormatterConverter.cs" />
+ <Compile Include="Serialization\JsonISerializableContract.cs" />
+ <Compile Include="Serialization\JsonLinqContract.cs" />
+ <Compile Include="Serialization\JsonObjectContract.cs" />
+ <Compile Include="Serialization\JsonPrimitiveContract.cs" />
+ <Compile Include="Serialization\JsonProperty.cs" />
+ <Compile Include="Serialization\JsonPropertyCollection.cs" />
+ <Compile Include="Serialization\JsonSerializerInternalBase.cs" />
+ <Compile Include="Serialization\JsonSerializerInternalReader.cs" />
+ <Compile Include="Serialization\JsonSerializerInternalWriter.cs" />
+ <Compile Include="Serialization\JsonSerializerProxy.cs" />
+ <Compile Include="Serialization\JsonStringContract.cs" />
+ <Compile Include="Serialization\JsonTypeReflector.cs" />
+ <Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
+ <Compile Include="Serialization\ObjectConstructor.cs" />
+ <Compile Include="Serialization\OnErrorAttribute.cs" />
+ <Compile Include="Serialization\ReflectionValueProvider.cs" />
+ <Compile Include="StreamingContext.cs" />
+ <Compile Include="TypeNameHandling.cs" />
+ <Compile Include="Utilities\Base64Encoder.cs" />
+ <Compile Include="Utilities\BidirectionalDictionary.cs" />
+ <Compile Include="Utilities\CollectionUtils.cs" />
+ <Compile Include="Utilities\CollectionWrapper.cs" />
+ <Compile Include="Utilities\ConvertUtils.cs" />
+ <Compile Include="Utilities\DateTimeUtils.cs" />
+ <Compile Include="Utilities\DictionaryWrapper.cs" />
+ <Compile Include="Utilities\DynamicProxy.cs" />
+ <Compile Include="Utilities\DynamicProxyMetaObject.cs" />
+ <Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
+ <Compile Include="Utilities\DynamicUtils.cs" />
+ <Compile Include="Utilities\DynamicWrapper.cs" />
+ <Compile Include="Utilities\EnumUtils.cs" />
+ <Compile Include="Utilities\EnumValue.cs" />
+ <Compile Include="Utilities\EnumValues.cs" />
+ <Compile Include="Utilities\ILGeneratorExtensions.cs" />
+ <Compile Include="Utilities\JavaScriptUtils.cs" />
+ <Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
+ <Compile Include="Utilities\LinqBridge.cs" />
+ <Compile Include="Utilities\ListWrapper.cs" />
+ <Compile Include="Utilities\MathUtils.cs" />
+ <Compile Include="Utilities\MethodCall.cs" />
+ <Compile Include="Utilities\MiscellaneousUtils.cs" />
+ <Compile Include="Utilities\ReflectionDelegateFactory.cs" />
+ <Compile Include="Utilities\ReflectionUtils.cs" />
+ <Compile Include="Utilities\StringBuffer.cs" />
+ <Compile Include="Utilities\StringReference.cs" />
+ <Compile Include="Utilities\StringUtils.cs" />
+ <Compile Include="Utilities\ThreadSafeStore.cs" />
+ <Compile Include="Utilities\TypeExtensions.cs" />
+ <Compile Include="Utilities\ValidationUtils.cs" />
+ <Compile Include="WriteState.cs" />
+ </ItemGroup>
+ <PropertyGroup Condition=" '$(VisualStudioVersion)' == '' ">
+ <VisualStudioVersion>11.0</VisualStudioVersion>
+ </PropertyGroup>
+ <Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ 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 42f64b0..36b4d2b 100644
--- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj
+++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj
@@ -224,6 +224,7 @@
<Compile Include="Utilities\MiscellaneousUtils.cs" />
<Compile Include="Utilities\ReflectionUtils.cs" />
<Compile Include="Utilities\StringUtils.cs" />
+ <Compile Include="Utilities\TypeExtensions.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
<Compile Include="WriteState.cs" />
</ItemGroup>
diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj
index 22bd2a8..4d76b44 100644
--- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj
+++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj
@@ -239,6 +239,7 @@
<Compile Include="Utilities\MiscellaneousUtils.cs" />
<Compile Include="Utilities\ReflectionUtils.cs" />
<Compile Include="Utilities\StringUtils.cs" />
+ <Compile Include="Utilities\TypeExtensions.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
<Compile Include="WriteState.cs" />
</ItemGroup>
diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj
index 7ea6e09..3dae2a8 100644
--- a/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj
+++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj
@@ -218,6 +218,7 @@
<Compile Include="Utilities\StringReference.cs" />
<Compile Include="Utilities\StringUtils.cs" />
<Compile Include="Utilities\ThreadSafeStore.cs" />
+ <Compile Include="Utilities\TypeExtensions.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
<Compile Include="Schema\Extensions.cs" />
<Compile Include="Schema\JsonSchemaException.cs" />
diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj
index 3014bec..e538022 100644
--- a/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj
+++ b/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj
@@ -188,6 +188,7 @@
<Compile Include="Utilities\StringReference.cs" />
<Compile Include="Utilities\StringUtils.cs" />
<Compile Include="Utilities\ThreadSafeStore.cs" />
+ <Compile Include="Utilities\TypeExtensions.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
<Compile Include="Schema\Extensions.cs" />
<Compile Include="Schema\JsonSchemaException.cs" />
diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj
index d1b70ad..5fb317e 100644
--- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj
+++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj
@@ -235,6 +235,7 @@
<Compile Include="Utilities\MiscellaneousUtils.cs" />
<Compile Include="Utilities\ReflectionUtils.cs" />
<Compile Include="Utilities\StringUtils.cs" />
+ <Compile Include="Utilities\TypeExtensions.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
<Compile Include="WriteState.cs" />
</ItemGroup>
diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs
index 4f81f4d..b9f40df 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 5699d38..d72f73d 100644
--- a/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs
+++ b/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs
@@ -31,7 +31,7 @@ namespace Newtonsoft.Json.Schema
/// <summary>
/// Returns detailed information about the schema exception.
/// </summary>
-#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)
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class.
/// </summary>
diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs
index b3a2db5..6615660 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<DescriptionAttribute>(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<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
@@ -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 752d75c..255f748 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 803970b..ce4ea62 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<JsonConverter> BuiltInConverters = new List<JsonConverter>
{
-#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
/// <summary>
/// Gets or sets the default members search flags.
/// </summary>
/// <value>The default members search flags.</value>
public BindingFlags DefaultMembersSearchFlags { get; set; }
+#else
+ private BindingFlags DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public;
+#endif
/// <summary>
/// Gets or sets a value indicating whether compiler generated members should be serialized.
@@ -157,7 +166,9 @@ namespace Newtonsoft.Json.Serialization
/// </param>
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<JsonPropertyAttribute>(member) != null)
+ if (JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member.GetCustomAttributeProvider()) != null)
serializableMembers.Add(member);
#if !PocketPC && !NET20
- else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute<DataMemberAttribute>(member) != null)
+ else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute<DataMemberAttribute>(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<ConstructorInfo> constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
+ IList<ConstructorInfo> 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
/// <returns></returns>
protected virtual JsonConverter ResolveContractConverter(Type objectType)
{
- return JsonTypeReflector.GetJsonConverter(objectType, objectType);
+ return JsonTypeReflector.GetJsonConverter(objectType.GetCustomAttributeProvider(), objectType);
}
private Func<object> 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
/// <summary>
/// Creates a <see cref="JsonISerializableContract"/> for the given type.
/// </summary>
@@ -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<object> 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 9f0176a..81b8d6e 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
/// <param name="typeName">Specifies the <see cref="T:System.Type"/> name of the serialized object. </param>
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 3204484..234cca3 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 8a399a4..423683f 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 c3af3f3..bf36008 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<object, object>);
}
+#endif
}
internal IWrappedDictionary CreateWrapper(object dictionary)
{
+#if !NETFX_CORE
if (dictionary is IDictionary && (DictionaryValueType == null || !_isDictionaryValueTypeNullableType))
return new DictionaryWrapper<object, object>((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 36b2563..49f19b4 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 c033f76..b8b9a11 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 1c51346..72fff39 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<object>.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 7556323..7684298 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 30341ef..03705d7 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 0a6b31f..12e8ea5 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<ICustomAttributeProvider, Type> JsonConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetJsonConverterTypeFromAttribute);
-#if !SILVERLIGHT && !PocketPC && !NET20
+#if !SILVERLIGHT && !PocketPC && !NET20 && !NETFX_CORE
private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
private const string MetadataTypeAttributeTypeName =
@@ -80,7 +85,7 @@ namespace Newtonsoft.Json.Serialization
public static JsonContainerAttribute GetJsonContainerAttribute(Type type)
{
- return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type);
+ return CachedAttributeGetter<JsonContainerAttribute>.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<DataContractAttribute>.GetAttribute(currentType);
- currentType = currentType.BaseType;
+ result = CachedAttributeGetter<DataContractAttribute>.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<DataMemberAttribute>.GetAttribute(memberInfo);
+ if (memberInfo.MemberType() == MemberTypes.Field)
+ return CachedAttributeGetter<DataMemberAttribute>.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<DataMemberAttribute>.GetAttribute(propertyInfo);
+ DataMemberAttribute result = CachedAttributeGetter<DataMemberAttribute>.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<DataMemberAttribute>.GetAttribute(baseProperty);
+ result = CachedAttributeGetter<DataMemberAttribute>.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)
{
@@ -202,10 +215,11 @@ namespace Newtonsoft.Json.Serialization
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<T>(type, true);
+ attribute = ReflectionUtils.GetAttribute<T>(type.GetCustomAttributeProvider(), true);
if (attribute != null)
return attribute;
foreach (Type typeInterface in type.GetInterfaces())
{
- attribute = ReflectionUtils.GetAttribute<T>(typeInterface, true);
+ attribute = ReflectionUtils.GetAttribute<T>(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<T>(memberInfo, true);
+ attribute = ReflectionUtils.GetAttribute<T>(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<T>(interfaceTypeMemberInfo, true);
- if (attribute != null)
- return attribute;
+ MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo);
+
+ if (interfaceTypeMemberInfo != null)
+ {
+ attribute = ReflectionUtils.GetAttribute<T>(interfaceTypeMemberInfo.GetCustomAttributeProvider(), true);
+ if (attribute != null)
+ return attribute;
+ }
}
}
@@ -314,11 +331,18 @@ namespace Newtonsoft.Json.Serialization
public static T GetAttribute<T>(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<T>(type);
- MemberInfo memberInfo = attributeProvider as MemberInfo;
+ MemberInfo memberInfo = provider as MemberInfo;
if (memberInfo != null)
return GetAttribute<T>(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 815f20b..7bc384f 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 0d5fffa..760068c 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 fec0c94..197f03a 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<object, object>((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 4d08840..e667637 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 e3b3d9d..5f5a347 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<TypeConvertKey>
{
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 bf03713..52345e4 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 d67734d..6d43f65 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<TKey, TValue> : IDictionary<TKey, TValue>, IWrappedDictionary
{
+#if !(NETFX_CORE)
private readonly IDictionary _dictionary;
+#endif
private readonly IDictionary<TKey, TValue> _genericDictionary;
private object _syncRoot;
+#if !(NETFX_CORE)
public DictionaryWrapper(IDictionary dictionary)
{
ValidationUtils.ArgumentNotNull(dictionary, "dictionary");
_dictionary = dictionary;
}
+#endif
public DictionaryWrapper(IDictionary<TKey, TValue> 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<TKey> Keys
{
get
{
- if (_genericDictionary != null)
- return _genericDictionary.Keys;
- else
+#if !NETFX_CORE
+ if (_dictionary != null)
return _dictionary.Keys.Cast<TKey>().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<TValue> Values
{
get
{
- if (_genericDictionary != null)
- return _genericDictionary.Values;
- else
+#if !NETFX_CORE
+ if (_dictionary != null)
return _dictionary.Values.Cast<TValue>().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<TKey, TValue> 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<TKey, TValue> 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<TKey, TValue>[] 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, TValue>((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<TKey, TValue> 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<KeyValuePair<TKey, TValue>> GetEnumerator()
{
- if (_genericDictionary != null)
- return _genericDictionary.GetEnumerator();
- else
+#if !NETFX_CORE
+ if (_dictionary != null)
return _dictionary.Cast<DictionaryEntry>().Select(de => new KeyValuePair<TKey, TValue>((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<TEnumeratorKey, TEnumeratorValue> : IDictionaryEnumerator
@@ -291,10 +377,21 @@ namespace Newtonsoft.Json.Utilities
IDictionaryEnumerator IDictionary.GetEnumerator()
{
- if (_genericDictionary != null)
+#if !NETFX_CORE
+ if (_dictionary != null)
+ return _dictionary.GetEnumerator();
+ else
+#endif
return new DictionaryEnumerator<TKey, TValue>(_genericDictionary.GetEnumerator());
+ }
+
+#if !NETFX_CORE
+ bool IDictionary.Contains(object key)
+ {
+ if (_genericDictionary != null)
+ return _genericDictionary.ContainsKey((TKey)key);
else
- return _dictionary.GetEnumerator();
+ 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<TKey, TValue>[])array, index);
- else
+#if !NETFX_CORE
+ if (_dictionary != null)
_dictionary.CopyTo(array, index);
+ else
+#endif
+ _genericDictionary.CopyTo((KeyValuePair<TKey, TValue>[])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 bd61026..5565f2d 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<MethodInfo>()
.Any(info =>
// check that the method overrides the original on DynamicObjectProxy
- info.DeclaringType != typeof(DynamicProxy<T>) &&
- info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy<T>));
+ info.DeclaringType != typeof(DynamicProxy<T>)
+ // todo - find out whether there is a way to do this in winrt
+#if !NETFX_CORE
+ && info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy<T>)
+#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 eaf7d3c..e6b9270 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<T> CreateDefaultConstructor<T>(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 7899509..5882bd6 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<Type> 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<MethodInfo> 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 1d904f2..57e034f 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<object> GetValues(Type enumType)
{
- if (!enumType.IsEnum)
+ if (!enumType.IsEnum())
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum.");
List<object> values = new List<object>();
@@ -123,7 +123,7 @@ namespace Newtonsoft.Json.Utilities
public static IList<string> GetNames(Type enumType)
{
- if (!enumType.IsEnum)
+ if (!enumType.IsEnum())
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum.");
List<string> values = new List<string>();
diff --git a/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs b/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs
index c508fc4..1739d12 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 c96be70..f83e316 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 be3f467..2764cab 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);
}
/// <summary>
@@ -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
/// </returns>
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
/// </returns>
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<T>(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<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute
+ {
+ object provider = attributeProvider.UnderlyingObject;
+
+ if (provider is Type)
+ return ((Type)provider).GetTypeInfo().GetCustomAttributes<T>(inherit).ToArray();
+
+ if (provider is Assembly)
+ return ((Assembly)provider).GetCustomAttributes<T>().ToArray();
+
+ if (provider is MemberInfo)
+ return ((MemberInfo)provider).GetCustomAttributes<T>(inherit).ToArray();
+
+ if (provider is Module)
+ return ((Module)provider).GetCustomAttributes<T>().ToArray();
+
+ if (provider is ParameterInfo)
+ return ((ParameterInfo)provider).GetCustomAttributes<T>(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<Type>(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<MemberInfo> fieldInfos = new List<MemberInfo>(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<FieldInfo>();
}
@@ -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<MemberInfo> 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 e6cd6c6..91cd3c8 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 0000000..7d761f9
--- /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<Type> 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<MemberInfo> 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<Type> parameterTypes)
+ {
+ return type.GetMethod(null, parameterTypes);
+ }
+
+ public static MethodInfo GetMethod(this Type type, string name, IList<Type> parameterTypes)
+ {
+ return type.GetMethod(name, DefaultFlags, null, parameterTypes, null);
+ }
+
+ public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags, object placeHolder1, IList<Type> 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<ConstructorInfo> GetConstructors(this Type type)
+ {
+ return type.GetConstructors(DefaultFlags);
+ }
+
+ public static IEnumerable<ConstructorInfo> GetConstructors(this Type type, BindingFlags bindingFlags)
+ {
+ return type.GetConstructors(bindingFlags, null);
+ }
+
+ private static IEnumerable<ConstructorInfo> GetConstructors(this Type type, BindingFlags bindingFlags, IList<Type> 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<Type> parameterTypes)
+ {
+ return type.GetConstructor(DefaultFlags, null, parameterTypes, null);
+ }
+
+ public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object placeholder1, IList<Type> 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<PropertyInfo> GetProperties(this Type type, BindingFlags bindingFlags)
+ {
+ return type.GetTypeInfo().GetPropertiesRecursive().Where(p => TestAccessibility(p, bindingFlags));
+ }
+
+ private static IList<MemberInfo> GetMembersRecursive(this TypeInfo type)
+ {
+ TypeInfo t = type;
+ IList<MemberInfo> members = new List<MemberInfo>();
+ 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<PropertyInfo> GetPropertiesRecursive(this TypeInfo type)
+ {
+ TypeInfo t = type;
+ IList<PropertyInfo> properties = new List<PropertyInfo>();
+ 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<FieldInfo> GetFieldsRecursive(this TypeInfo type)
+ {
+ TypeInfo t = type;
+ IList<FieldInfo> fields = new List<FieldInfo>();
+ 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<MethodInfo> 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<FieldInfo> GetFields(this Type type)
+ {
+ return type.GetFields(DefaultFlags);
+ }
+
+ public static IEnumerable<FieldInfo> 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<Type> GetInterfaces(this Type type)
+ {
+ return type.GetTypeInfo().ImplementedInterfaces;
+ }
+
+ public static IEnumerable<MethodInfo> 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<Type> 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<MethodInfo> 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 47e724e..4e905c6 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);
}