From ab512f60d22134b1810cc6eb8131ca9540f9f2f0 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Sun, 2 Apr 2017 19:09:18 +1200 Subject: [PATCH 01/15] starting migration. it's not looking good. --- Manatee.Json-Core/Class1.cs | 8 ++++++++ Manatee.Json.sln | 16 +++++++-------- Manatee.Json/Manatee.Json-3.5.project.json | 14 ------------- Manatee.Json/Manatee.Json-4.0.project.json | 14 ------------- Manatee.Json/Manatee.Json-4.5.project.json | 15 -------------- Manatee.Json/Manatee.Json-Core.csproj | 19 ++++++++++++++++++ Manatee.Json/Manatee.Json-Core.xproj | 26 ------------------------- Manatee.Json/Manatee.Json-Core.xproj.user | 6 ------ Manatee.Json/Manatee.Json-Portable.project.json | 14 ------------- Manatee.Json/project.json | 18 ----------------- 10 files changed, 35 insertions(+), 115 deletions(-) create mode 100644 Manatee.Json-Core/Class1.cs delete mode 100644 Manatee.Json/Manatee.Json-3.5.project.json delete mode 100644 Manatee.Json/Manatee.Json-4.0.project.json delete mode 100644 Manatee.Json/Manatee.Json-4.5.project.json create mode 100644 Manatee.Json/Manatee.Json-Core.csproj delete mode 100644 Manatee.Json/Manatee.Json-Core.xproj delete mode 100644 Manatee.Json/Manatee.Json-Core.xproj.user delete mode 100644 Manatee.Json/Manatee.Json-Portable.project.json delete mode 100644 Manatee.Json/project.json diff --git a/Manatee.Json-Core/Class1.cs b/Manatee.Json-Core/Class1.cs new file mode 100644 index 0000000..4643189 --- /dev/null +++ b/Manatee.Json-Core/Class1.cs @@ -0,0 +1,8 @@ +using System; + +namespace Manatee.Json_Core +{ + public class Class1 + { + } +} diff --git a/Manatee.Json.sln b/Manatee.Json.sln index f2f5e63..44e0149 100644 --- a/Manatee.Json.sln +++ b/Manatee.Json.sln @@ -1,12 +1,12 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 +# Visual Studio 15 +VisualStudioVersion = 15.0.26228.12 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-4.5", "Manatee.Json\Manatee.Json-4.5.csproj", "{6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}" ProjectSection(ProjectDependencies) = postProject + {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60} = {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60} {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E} = {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E} - {A83D9791-01A7-4031-886E-995B7A1320D1} = {A83D9791-01A7-4031-886E-995B7A1320D1} {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA} = {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA} {B0A832B8-06B7-4494-8416-FABE755F621F} = {B0A832B8-06B7-4494-8416-FABE755F621F} EndProjectSection @@ -28,7 +28,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-4.0", "Manatee EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-Portable", "Manatee.Json\Manatee.Json-Portable.csproj", "{B0A832B8-06B7-4494-8416-FABE755F621F}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Manatee.Json-Core", "Manatee.Json\Manatee.Json-Core.xproj", "{A83D9791-01A7-4031-886E-995B7A1320D1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Manatee.Json-Core", "Manatee.Json\Manatee.Json-Core.csproj", "{A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -55,10 +55,10 @@ Global {B0A832B8-06B7-4494-8416-FABE755F621F}.Debug|Any CPU.Build.0 = Debug|Any CPU {B0A832B8-06B7-4494-8416-FABE755F621F}.Release|Any CPU.ActiveCfg = Release|Any CPU {B0A832B8-06B7-4494-8416-FABE755F621F}.Release|Any CPU.Build.0 = Release|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Release|Any CPU.Build.0 = Release|Any CPU + {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Manatee.Json/Manatee.Json-3.5.project.json b/Manatee.Json/Manatee.Json-3.5.project.json deleted file mode 100644 index a0fb47c..0000000 --- a/Manatee.Json/Manatee.Json-3.5.project.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "frameworks": { - ".NETFramework,Version=v3.5,Profile=Client": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/Manatee.Json-4.0.project.json b/Manatee.Json/Manatee.Json-4.0.project.json deleted file mode 100644 index 565cf90..0000000 --- a/Manatee.Json/Manatee.Json-4.0.project.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "frameworks": { - ".NETFramework,Version=v4.0,Profile=Client": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/Manatee.Json-4.5.project.json b/Manatee.Json/Manatee.Json-4.5.project.json deleted file mode 100644 index b39c42f..0000000 --- a/Manatee.Json/Manatee.Json-4.5.project.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "frameworks": { - ".NETFramework,Version=v4.0": {}, - ".NETFramework,Version=v4.5": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/Manatee.Json-Core.csproj b/Manatee.Json/Manatee.Json-Core.csproj new file mode 100644 index 0000000..5acde30 --- /dev/null +++ b/Manatee.Json/Manatee.Json-Core.csproj @@ -0,0 +1,19 @@ + + + + netcoreapp1.1 + Manatee.Json + Manatee.Json + Manatee.Json + Manatee.Json + Provides an intuitive approach to building JSON structures. + 6.0.0 + True + Manatee.Json.snk + + + + + + + \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Core.xproj b/Manatee.Json/Manatee.Json-Core.xproj deleted file mode 100644 index 85ea3f4..0000000 --- a/Manatee.Json/Manatee.Json-Core.xproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - a83d9791-01a7-4031-886e-995b7a1320d1 - Manatee.Json - .\obj - .\bin\ - v4.5.2 - - - 2.0 - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Core.xproj.user b/Manatee.Json/Manatee.Json-Core.xproj.user deleted file mode 100644 index c99c608..0000000 --- a/Manatee.Json/Manatee.Json-Core.xproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - Start - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Portable.project.json b/Manatee.Json/Manatee.Json-Portable.project.json deleted file mode 100644 index 6782e01..0000000 --- a/Manatee.Json/Manatee.Json-Portable.project.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "frameworks": { - ".NETPortable,Version=v4.5,Profile=Profile111": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/project.json b/Manatee.Json/project.json deleted file mode 100644 index 0d06306..0000000 --- a/Manatee.Json/project.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "dependencies": { - "NETStandard.Library": "1.6.1" - }, - "frameworks": { - "netstandard1.6": { - "buildOptions": { - "define": [ "TRACE", "CORE", "JETBRAINS_ANNOTATIONS" ] - }, - "imports": "dnxcore50" - } - }, - "buildOptions": { - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} From 170f6a94ba6095025c4b95e76d39a862ed1fd464 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 13 Jun 2017 12:09:33 +1200 Subject: [PATCH 02/15] removed all project types. replaced with .net-standard-1.1. test project build fails. --- Json-Schema-Test-Suite | 2 +- Manatee.Json-Core/Class1.cs | 8 - Manatee.Json-Portable/Manatee.Json.csproj | 7 + Manatee.Json.Tests/Manatee.Json.Tests.csproj | 6 +- Manatee.Json.sln | 36 +- Manatee.Json/DescriptionAttribute.cs | 4 +- Manatee.Json/Internal/CompatibilityExtensions.cs | 77 +--- Manatee.Json/Internal/GeneralExtensions.cs | 6 +- Manatee.Json/JsonSyntaxException.cs | 3 - Manatee.Json/JsonValue.cs | 2 +- Manatee.Json/JsonValueIncorrectTypeException.cs | 3 - Manatee.Json/Manatee.Json-3.5.csproj | 311 --------------- Manatee.Json/Manatee.Json-4.0.csproj | 312 --------------- Manatee.Json/Manatee.Json-4.5.csproj | 440 --------------------- Manatee.Json/Manatee.Json-4.5.csproj.user | 6 - Manatee.Json/Manatee.Json-Core.csproj | 19 - Manatee.Json/Manatee.Json-Portable.csproj | 311 --------------- Manatee.Json/Manatee.Json.csproj | 29 ++ Manatee.Json/Parsing/JsonParser.cs | 7 +- .../Parsing/JsonPathExpressionParser.cs | 7 +- .../Translation/ExpressionTranslator.cs | 3 +- Manatee.Json/Path/JsonPathSyntaxException.cs | 3 - Manatee.Json/Path/Operators/NameOperator.cs | 2 +- Manatee.Json/Path/Parsing/JsonPathParser.cs | 7 +- Manatee.Json/Path/Parsing/PathParsingExtensions.cs | 5 +- .../Path/SearchParameters/NameSearchParameter.cs | 2 +- Manatee.Json/Properties/AssemblyInfo.cs | 37 +- Manatee.Json/Schema/AdditionalItems.cs | 3 - Manatee.Json/Schema/AdditionalProperties.cs | 3 - Manatee.Json/Schema/JsonSchemaOptions.cs | 6 - Manatee.Json/Schema/JsonSchemaTypeDefinition.cs | 3 - .../JsonSchemaPropertyValidatorFactory.cs | 11 +- .../SerializationDelegateProviderBase.cs | 13 - .../Serialization/Internal/ConstructorResolver.cs | 7 +- .../Serialization/Internal/SerializerCache.cs | 10 +- .../Serialization/Internal/SerializerFactory.cs | 8 +- .../Serialization/Internal/SerializerMethodPair.cs | 5 +- .../Internal/Serializers/EnumNameSerializer.cs | 9 +- .../Internal/Serializers/ReflectionCache.cs | 32 +- .../Serialization/Internal/TemplateGenerator.cs | 18 +- .../Serialization/Internal/TypeGenerator.cs | 7 +- .../JsonSerializationAbstractionMap.cs | 6 +- .../Serialization/JsonSerializationTypeRegistry.cs | 16 +- .../TypeDoesNotContainPropertyException.cs | 3 - .../Serialization/TypeRegistrationException.cs | 3 - Manatee.Json/XmlExtensions.cs | 2 +- Wiki | 2 +- 47 files changed, 113 insertions(+), 1709 deletions(-) delete mode 100644 Manatee.Json-Core/Class1.cs create mode 100644 Manatee.Json-Portable/Manatee.Json.csproj delete mode 100644 Manatee.Json/Manatee.Json-3.5.csproj delete mode 100644 Manatee.Json/Manatee.Json-4.0.csproj delete mode 100644 Manatee.Json/Manatee.Json-4.5.csproj delete mode 100644 Manatee.Json/Manatee.Json-4.5.csproj.user delete mode 100644 Manatee.Json/Manatee.Json-Core.csproj delete mode 100644 Manatee.Json/Manatee.Json-Portable.csproj create mode 100644 Manatee.Json/Manatee.Json.csproj diff --git a/Json-Schema-Test-Suite b/Json-Schema-Test-Suite index 5fb3d9f..67c7b4d 160000 --- a/Json-Schema-Test-Suite +++ b/Json-Schema-Test-Suite @@ -1 +1 @@ -Subproject commit 5fb3d9f1a1c4136f544fbd0029942ea559732f8e +Subproject commit 67c7b4dc84c783d204e0c3a9324a63f3f7d9444d diff --git a/Manatee.Json-Core/Class1.cs b/Manatee.Json-Core/Class1.cs deleted file mode 100644 index 4643189..0000000 --- a/Manatee.Json-Core/Class1.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System; - -namespace Manatee.Json_Core -{ - public class Class1 - { - } -} diff --git a/Manatee.Json-Portable/Manatee.Json.csproj b/Manatee.Json-Portable/Manatee.Json.csproj new file mode 100644 index 0000000..1536775 --- /dev/null +++ b/Manatee.Json-Portable/Manatee.Json.csproj @@ -0,0 +1,7 @@ + + + + netstandard1.0 + + + \ No newline at end of file diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj b/Manatee.Json.Tests/Manatee.Json.Tests.csproj index 6c0219b..b64f6b1 100644 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj +++ b/Manatee.Json.Tests/Manatee.Json.Tests.csproj @@ -165,9 +165,9 @@ - - {6adf0bcf-4e46-4605-a784-51ea6dac81c7} - Manatee.Json-4.5 + + {b0a832b8-06b7-4494-8416-fabe755f621f} + Manatee.Json diff --git a/Manatee.Json.sln b/Manatee.Json.sln index b8c5764..af27fea 100644 --- a/Manatee.Json.sln +++ b/Manatee.Json.sln @@ -1,10 +1,8 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26228.12 +VisualStudioVersion = 15.0.26430.13 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-4.5", "Manatee.Json\Manatee.Json-4.5.csproj", "{6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8C148909-BDAD-45A5-9BFA-63DBD47290B9}" ProjectSection(SolutionItems) = preProject LICENSE-2.0.txt = LICENSE-2.0.txt @@ -16,13 +14,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests", "Manat EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{6E84846A-D11A-4B3F-9588-C815FB0A22C5}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-3.5", "Manatee.Json\Manatee.Json-3.5.csproj", "{FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-4.0", "Manatee.Json\Manatee.Json-4.0.csproj", "{67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-Portable", "Manatee.Json\Manatee.Json-Portable.csproj", "{B0A832B8-06B7-4494-8416-FABE755F621F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Manatee.Json-Core", "Manatee.Json\Manatee.Json-Core.csproj", "{A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Manatee.Json", "Manatee.Json\Manatee.Json.csproj", "{7548217B-8C18-4CA5-A248-59889EF93CF5}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -30,29 +22,13 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Release|Any CPU.Build.0 = Release|Any CPU {E74B7538-5E17-43C7-925B-33784945312E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E74B7538-5E17-43C7-925B-33784945312E}.Debug|Any CPU.Build.0 = Debug|Any CPU {E74B7538-5E17-43C7-925B-33784945312E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Release|Any CPU.Build.0 = Release|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Release|Any CPU.Build.0 = Release|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Release|Any CPU.Build.0 = Release|Any CPU - {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A6003C19-EB21-4CF1-82B7-F4CEEF8EEC60}.Release|Any CPU.Build.0 = Release|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Manatee.Json/DescriptionAttribute.cs b/Manatee.Json/DescriptionAttribute.cs index efd0ce0..254f9e7 100644 --- a/Manatee.Json/DescriptionAttribute.cs +++ b/Manatee.Json/DescriptionAttribute.cs @@ -1,5 +1,4 @@ -#if IOS || CORE -using System; +using System; namespace Manatee.Json { @@ -23,4 +22,3 @@ public DescriptionAttribute(string description) } } } -#endif diff --git a/Manatee.Json/Internal/CompatibilityExtensions.cs b/Manatee.Json/Internal/CompatibilityExtensions.cs index d167cb5..8b86382 100644 --- a/Manatee.Json/Internal/CompatibilityExtensions.cs +++ b/Manatee.Json/Internal/CompatibilityExtensions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; @@ -8,25 +7,16 @@ namespace Manatee.Json.Internal { internal static class CompatibilityExtensions { - //[MethodImpl(MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullOrWhiteSpace(this string value) { -#if NET35 - return string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()); -#else return string.IsNullOrWhiteSpace(value); -#endif } - //[MethodImpl(MethodImplOptions.AggressiveInlining)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string Join(this IEnumerable segments, string separator) { -#if NET35 - return string.Join(separator, segments.Select(s => s.ToString()).ToArray()); -#else return string.Join(separator, segments); -#endif } -#if IOS || CORE [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TypeInfo TypeInfo(this Type type) { @@ -37,69 +27,6 @@ public static Type[] GetTypeArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } -#else - //[MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Type TypeInfo(this Type type) - { - return type; - } - //[MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Type[] GetTypeArguments(this Type type) - { - return type.GetGenericArguments(); - } -#endif -#if IOS - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Any(this string value, Func predicate) - { - return value.ToCharArray().Any(predicate); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable TakeWhile(this string value, Func predicate) - { - return value.ToCharArray().TakeWhile(predicate); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Contains(this string value, char c) - { - return value.ToCharArray().Contains(c); - } - public static IEnumerable GetInterfaces(this TypeInfo type) - { - return type.ImplementedInterfaces; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsAssignableFrom(this Type derivedType, Type baseType) - { - return derivedType.TypeInfo().IsAssignableFrom(baseType.TypeInfo()); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetMethod(this Type type, string name) - { - return type.TypeInfo().GetDeclaredMethod(name); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MemberInfo[] GetMember(this TypeInfo typeInfo, string name) - { - return typeInfo.DeclaredMembers.Where(m => m.Name == name).ToArray(); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetSetMethod(this PropertyInfo property) - { - return property.SetMethod; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetGetMethod(this PropertyInfo property) - { - return property.GetMethod; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable GetTypes(this Assembly assembly) - { - return assembly.ExportedTypes; - } -#endif #if CORE [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAssignableFrom(this Type derivedType, Type baseType) diff --git a/Manatee.Json/Internal/GeneralExtensions.cs b/Manatee.Json/Internal/GeneralExtensions.cs index 69a1542..3d18afd 100644 --- a/Manatee.Json/Internal/GeneralExtensions.cs +++ b/Manatee.Json/Internal/GeneralExtensions.cs @@ -210,7 +210,7 @@ public static string SkipWhiteSpace(this StreamReader stream, out char ch) public static bool InheritsFrom(this Type tDerived, Type tBase) { if (tDerived.IsSubtypeOf(tBase)) return true; - var interfaces = tDerived.TypeInfo().GetInterfaces().Select(i => i.TypeInfo().IsGenericType ? i.GetGenericTypeDefinition() : i); + var interfaces = tDerived.TypeInfo().ImplementedInterfaces.Select(i => i.TypeInfo().IsGenericType ? i.GetGenericTypeDefinition() : i); return interfaces.Contains(tBase); } private static bool IsSubtypeOf(this Type tDerived, Type tBase) @@ -231,11 +231,7 @@ public static int GetCollectionHashCode(this IEnumerable collection) } public static int GetCollectionHashCode(this IEnumerable> collection) { -#if IOS || CORE return collection.OrderBy(kvp => kvp.Key, StringComparer.Ordinal) -#else - return collection.OrderBy(kvp => kvp.Key, StringComparer.InvariantCulture) -#endif .Aggregate(0, (current, kvp) => { unchecked diff --git a/Manatee.Json/JsonSyntaxException.cs b/Manatee.Json/JsonSyntaxException.cs index dff9805..2dd31af 100644 --- a/Manatee.Json/JsonSyntaxException.cs +++ b/Manatee.Json/JsonSyntaxException.cs @@ -32,9 +32,6 @@ namespace Manatee.Json /// /// Thrown when an input string contains a syntax error while parsing a , , or . /// -#if !IOS && !CORE - [Serializable] -#endif public class JsonSyntaxException : Exception { private readonly string _path; diff --git a/Manatee.Json/JsonValue.cs b/Manatee.Json/JsonValue.cs index ba41ee6..d6809af 100644 --- a/Manatee.Json/JsonValue.cs +++ b/Manatee.Json/JsonValue.cs @@ -338,7 +338,7 @@ public static JsonValue Parse(string source) { if (source == null) throw new ArgumentNullException(nameof(source)); - if (source.IsNullOrWhiteSpace()) + if (string.IsNullOrWhiteSpace(source)) throw new ArgumentException("Source string contains no data."); return JsonParser.Parse(source); } diff --git a/Manatee.Json/JsonValueIncorrectTypeException.cs b/Manatee.Json/JsonValueIncorrectTypeException.cs index 3e880e0..d1a266d 100644 --- a/Manatee.Json/JsonValueIncorrectTypeException.cs +++ b/Manatee.Json/JsonValueIncorrectTypeException.cs @@ -28,9 +28,6 @@ namespace Manatee.Json /// /// Thrown when a value is accessed via the incorrect type accessor. /// -#if !IOS && !CORE - [Serializable] -#endif public class JsonValueIncorrectTypeException : InvalidOperationException { /// diff --git a/Manatee.Json/Manatee.Json-3.5.csproj b/Manatee.Json/Manatee.Json-3.5.csproj deleted file mode 100644 index c59e816..0000000 --- a/Manatee.Json/Manatee.Json-3.5.csproj +++ /dev/null @@ -1,311 +0,0 @@ - - - - - Debug - AnyCPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA} - Library - Properties - Manatee.Json - Manatee.Json - v3.5 - 512 - Client - - - true - full - false - bin\Debug-3.5\ - TRACE;DEBUG;NET35, JETBRAINS_ANNOTATIONS - prompt - 4 - true - - - pdbonly - true - bin\Release-3.5\ - TRACE;NET35, JETBRAINS_ANNOTATIONS - prompt - 4 - bin\Release-3.5\Manatee.Json.XML - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-4.0.csproj b/Manatee.Json/Manatee.Json-4.0.csproj deleted file mode 100644 index 9e1c5ce..0000000 --- a/Manatee.Json/Manatee.Json-4.0.csproj +++ /dev/null @@ -1,312 +0,0 @@ - - - - - Debug - AnyCPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E} - Library - Properties - Manatee.Json - Manatee.Json - v4.0 - 512 - Client - - - true - full - false - bin\Debug-4.0\ - TRACE;DEBUG;NET4, JETBRAINS_ANNOTATIONS - prompt - 4 - true - - - pdbonly - true - bin\Release-4.0\ - TRACE;NET4, JETBRAINS_ANNOTATIONS - prompt - 4 - bin\Release-4.0\Manatee.Json.xml - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-4.5.csproj b/Manatee.Json/Manatee.Json-4.5.csproj deleted file mode 100644 index cb8d35e..0000000 --- a/Manatee.Json/Manatee.Json-4.5.csproj +++ /dev/null @@ -1,440 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7} - Library - Properties - Manatee.Json - Manatee.Json - 512 - - ..\ - true - - - v4.5 - true - full - false - bin\Debug-4.5\ - TRACE;DEBUG;NET45, JETBRAINS_ANNOTATIONS - prompt - 4 - - - false - true - - - true - - - Manatee.Json.snk - - - - - - bin\Release-4.5\ - TRACE;NET45, JETBRAINS_ANNOTATIONS - bin\Release-4.5\Manatee.Json.XML - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-4.5.csproj.user b/Manatee.Json/Manatee.Json-4.5.csproj.user deleted file mode 100644 index 07dbd5b..0000000 --- a/Manatee.Json/Manatee.Json-4.5.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - ProjectFiles - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Core.csproj b/Manatee.Json/Manatee.Json-Core.csproj deleted file mode 100644 index 5acde30..0000000 --- a/Manatee.Json/Manatee.Json-Core.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - netcoreapp1.1 - Manatee.Json - Manatee.Json - Manatee.Json - Manatee.Json - Provides an intuitive approach to building JSON structures. - 6.0.0 - True - Manatee.Json.snk - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Portable.csproj b/Manatee.Json/Manatee.Json-Portable.csproj deleted file mode 100644 index 8249230..0000000 --- a/Manatee.Json/Manatee.Json-Portable.csproj +++ /dev/null @@ -1,311 +0,0 @@ - - - - - 10.0 - Debug - AnyCPU - {B0A832B8-06B7-4494-8416-FABE755F621F} - Library - Properties - Manatee.Json - Manatee.Json - en-US - 512 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Profile111 - v4.5 - - - - - true - full - false - bin\Debug-Portable\ - TRACE;DEBUG;IOS, JETBRAINS_ANNOTATIONS - prompt - 4 - - - pdbonly - true - bin\Release-Portable\ - TRACE;IOS, JETBRAINS_ANNOTATIONS - prompt - 4 - bin\Release-Portable\Manatee.Json.XML - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj new file mode 100644 index 0000000..66c518b --- /dev/null +++ b/Manatee.Json/Manatee.Json.csproj @@ -0,0 +1,29 @@ + + + + netstandard1.1 + True + Provides an intuitive approach to building JSON structures. + 6.0.0 + Copyright © 2016 Little Crab Solutions + https://github.com/gregsdennis/Manatee.Json/blob/master/LICENSE.txt + https://github.com/gregsdennis/Manatee.Json + https://bytebucket.org/gregsdennis/manatee.json/wiki/Resources/Manatee-Json-Logo.png + + json manatee parser serializer jsonpath jsonschema transform path schema linq-to-json + v6.0.0 +Added DocumentPath to IJsonSchema. +BUG FIX: Schema now properly resolve referenced schema relative to document path instead of application's current directory. (#50) +Removed JsonSchemaFactory.Load(string filename) in favor of . + +Note: As a consequence of removing JsonSchemaFactory.Load(string filename), you'll need to resolve the full file name (using System.IO.Path.GetFullPath()) before passing it into JsonSchemaRegistry.Get(string uri). + + True + Manatee.Json.snk + + + + + + + \ No newline at end of file diff --git a/Manatee.Json/Parsing/JsonParser.cs b/Manatee.Json/Parsing/JsonParser.cs index 9def488..36130fd 100644 --- a/Manatee.Json/Parsing/JsonParser.cs +++ b/Manatee.Json/Parsing/JsonParser.cs @@ -35,9 +35,10 @@ internal static class JsonParser static JsonParser() { - Parsers = typeof(JsonParser).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonParser).IsAssignableFrom(t) && t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + Parsers = typeof(JsonParser).TypeInfo().Assembly.DefinedTypes + // TODO: optimize + .Where(t => typeof(IJsonParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } diff --git a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs index 9431dd9..77bb326 100644 --- a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs +++ b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs @@ -34,9 +34,10 @@ internal static class JsonPathExpressionParser static JsonPathExpressionParser() { - Parsers = typeof(JsonPathExpressionParser).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonPathExpressionParser).IsAssignableFrom(t) && t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + Parsers = typeof(JsonPathExpressionParser).TypeInfo().Assembly.DefinedTypes + // TODO: optimize + .Where(t => typeof(IJsonPathExpressionParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } diff --git a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs index 7e7582c..b2482f6 100644 --- a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs @@ -199,7 +199,8 @@ private static IExpressionTranslator GetMemberTranslator(Expression exp) public static ExpressionTreeNode TranslateNode(Expression source) { var type = source.GetType(); - var expressionKey = Translators.Keys.FirstOrDefault(t => t.IsAssignableFrom(type)); + // TODO: optimize + var expressionKey = Translators.Keys.FirstOrDefault(t => t.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())); if (expressionKey != null) { var translator = Translators[expressionKey](source); diff --git a/Manatee.Json/Path/JsonPathSyntaxException.cs b/Manatee.Json/Path/JsonPathSyntaxException.cs index 151b48d..5565a0f 100644 --- a/Manatee.Json/Path/JsonPathSyntaxException.cs +++ b/Manatee.Json/Path/JsonPathSyntaxException.cs @@ -30,9 +30,6 @@ namespace Manatee.Json.Path /// /// Thrown when an input string contains a syntax error while parsing a . /// -#if !IOS && !CORE - [Serializable] -#endif public class JsonPathSyntaxException : Exception { private readonly bool _isExpression; diff --git a/Manatee.Json/Path/Operators/NameOperator.cs b/Manatee.Json/Path/Operators/NameOperator.cs index 1c7ce6a..db788bc 100644 --- a/Manatee.Json/Path/Operators/NameOperator.cs +++ b/Manatee.Json/Path/Operators/NameOperator.cs @@ -44,7 +44,7 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) } public override string ToString() { - return Name.Any(c => !char.IsLetterOrDigit(c)) || Name.IsNullOrWhiteSpace() + return Name.Cast().Any(c => !char.IsLetterOrDigit(c)) || Name.IsNullOrWhiteSpace() ? $".'{Name}'" : $".{Name}"; } diff --git a/Manatee.Json/Path/Parsing/JsonPathParser.cs b/Manatee.Json/Path/Parsing/JsonPathParser.cs index b1f9674..658cd5f 100644 --- a/Manatee.Json/Path/Parsing/JsonPathParser.cs +++ b/Manatee.Json/Path/Parsing/JsonPathParser.cs @@ -34,9 +34,10 @@ internal static class JsonPathParser static JsonPathParser() { - Parsers = typeof(JsonPathParser).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonPathParser).IsAssignableFrom(t) && t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + Parsers = typeof(JsonPathParser).TypeInfo().Assembly.DefinedTypes + // TODO: optimize + .Where(t => typeof(IJsonPathParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } diff --git a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs index 2fe6ccc..7c5ab7c 100644 --- a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs +++ b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs @@ -192,7 +192,7 @@ private static string GetSlice(this string source, ref int index, out Slice slic public static string GetInt(string source, ref int index, out int? number) { int value; - var text = new string(source.Substring(index).TakeWhile(c => char.IsDigit(c) || c == '-').ToArray()); + var text = new string(source.Substring(index).Cast().TakeWhile(c => char.IsDigit(c) || c == '-').ToArray()); if (text.Length == 0 && source[index].In(':', ',', ']')) { number = null; @@ -218,7 +218,8 @@ public static string GetInt(string source, ref int index, out int? number) public static string GetNumber(this string source, ref int index, out double? number) { double value; - var text = new string(source.Substring(index).TakeWhile(c => NumberChars.Contains(c)).ToArray()); + // TODO: optimize + var text = new string(source.Substring(index).Cast().TakeWhile(c => NumberChars.Cast().Contains(c)).ToArray()); if (text.Length == 0 && source[index].In(':', ',', ']')) { number = null; diff --git a/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs b/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs index b0980e7..11e5ae1 100644 --- a/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs +++ b/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs @@ -57,7 +57,7 @@ public IEnumerable Find(IEnumerable json, JsonValue root) } public override string ToString() { - return _name.Any(c => !char.IsLetterOrDigit(c)) || _name.IsNullOrWhiteSpace() + return _name.Cast().Any(c => !char.IsLetterOrDigit(c)) || _name.IsNullOrWhiteSpace() ? $"'{_name}'" : _name; } diff --git a/Manatee.Json/Properties/AssemblyInfo.cs b/Manatee.Json/Properties/AssemblyInfo.cs index 555ee76..024bab6 100644 --- a/Manatee.Json/Properties/AssemblyInfo.cs +++ b/Manatee.Json/Properties/AssemblyInfo.cs @@ -1,38 +1,3 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Manatee.Json")] -[assembly: AssemblyDescription("Provides an intuitive approach to building JSON structures.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Little Crab Solutions")] -[assembly: AssemblyProduct("Manatee.Json")] -[assembly: AssemblyCopyright("Copyright © 2016 Little Crab Solutions")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("effb4352-e82d-445c-ba56-99a6d5ceb8b8")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("6.0.0.0")] -[assembly: AssemblyFileVersion("6.0.0")] +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Manatee.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100bbe54aad91e473ca58d56672e66770435869a2388ac5a077457bf23b0872f5d656414709391f78751fd762ec25132d42ad60e319b821e37357964ac194b31a52e1d9772c507aed15527ff41564fdf85c7a90b09b7f8c8c321daf05404e7ccdaee0b5808db8aaa0ac2e8e3065509b5f1c75c4d1de5ceed995ae83fd36d10e8be0")] diff --git a/Manatee.Json/Schema/AdditionalItems.cs b/Manatee.Json/Schema/AdditionalItems.cs index ae5e84c..e24cea2 100644 --- a/Manatee.Json/Schema/AdditionalItems.cs +++ b/Manatee.Json/Schema/AdditionalItems.cs @@ -22,9 +22,6 @@ ***************************************************************************************/ using System; -#if !IOS && !CORE -using System.Data; -#endif using Manatee.Json.Serialization; namespace Manatee.Json.Schema diff --git a/Manatee.Json/Schema/AdditionalProperties.cs b/Manatee.Json/Schema/AdditionalProperties.cs index 0c82fb2..83286a6 100644 --- a/Manatee.Json/Schema/AdditionalProperties.cs +++ b/Manatee.Json/Schema/AdditionalProperties.cs @@ -22,9 +22,6 @@ ***************************************************************************************/ using System; -#if !IOS && !CORE -using System.Data; -#endif using Manatee.Json.Serialization; namespace Manatee.Json.Schema diff --git a/Manatee.Json/Schema/JsonSchemaOptions.cs b/Manatee.Json/Schema/JsonSchemaOptions.cs index c5ce045..e706ad3 100644 --- a/Manatee.Json/Schema/JsonSchemaOptions.cs +++ b/Manatee.Json/Schema/JsonSchemaOptions.cs @@ -22,9 +22,7 @@ ***************************************************************************************/ using System; using System.Net; -#if IOS || CORE using System.Net.Http; -#endif using System.Text; namespace Manatee.Json.Schema @@ -41,11 +39,7 @@ public static class JsonSchemaOptions /// public static Func Download { -#if IOS || CORE get { return _download ?? (_download = uri => new HttpClient().GetStringAsync(uri).Result); } -#else - get { return _download ?? (_download = uri => new WebClient {Encoding = Encoding.UTF8}.DownloadString(uri)); } -#endif set { _download = value; } } diff --git a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs index 2b2ce72..bd2c5c4 100644 --- a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs @@ -23,9 +23,6 @@ using System; using System.Collections.Generic; -#if !IOS && !CORE -using System.Data; -#endif using System.Linq; using Manatee.Json.Internal; using Manatee.Json.Serialization; diff --git a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs index 86f189b..553c435 100644 --- a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs +++ b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs @@ -34,11 +34,12 @@ internal static class JsonSchemaPropertyValidatorFactory static JsonSchemaPropertyValidatorFactory() { - AllValidators = typeof(IJsonSchemaPropertyValidator).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonSchemaPropertyValidator).IsAssignableFrom(t) && - !t.TypeInfo().IsAbstract && - t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + AllValidators = typeof(IJsonSchemaPropertyValidator).TypeInfo().Assembly.DefinedTypes + // TODO: optimize + .Where(t => typeof(IJsonSchemaPropertyValidator).GetTypeInfo().IsAssignableFrom(t) && + !t.IsAbstract && + t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs index 72319bf..1bc4cf0 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs @@ -33,13 +33,8 @@ internal abstract class SerializationDelegateProviderBase : ISerializationDelega protected SerializationDelegateProviderBase() { -#if !IOS - _encodeMethod = GetType().GetMethod("Encode", BindingFlags.NonPublic | BindingFlags.Static); - _decodeMethod = GetType().GetMethod("Decode", BindingFlags.NonPublic | BindingFlags.Static); -#else _encodeMethod = GetType().TypeInfo().GetDeclaredMethod("Encode"); _decodeMethod = GetType().TypeInfo().GetDeclaredMethod("Decode"); -#endif } public abstract bool CanHandle(Type type); @@ -49,11 +44,7 @@ public JsonSerializationTypeRegistry.ToJsonDelegate GetEncoder() var toJson = _encodeMethod; if (toJson.IsGenericMethod) toJson = toJson.MakeGenericMethod(typeArguments); -#if IOS || CORE return (JsonSerializationTypeRegistry.ToJsonDelegate) toJson.CreateDelegate(typeof (JsonSerializationTypeRegistry.ToJsonDelegate), toJson); -#else - return (JsonSerializationTypeRegistry.ToJsonDelegate) Delegate.CreateDelegate(typeof (JsonSerializationTypeRegistry.ToJsonDelegate), toJson); -#endif } public JsonSerializationTypeRegistry.FromJsonDelegate GetDecoder() { @@ -61,11 +52,7 @@ public JsonSerializationTypeRegistry.FromJsonDelegate GetDecoder() var fromJson = _decodeMethod; if (fromJson.IsGenericMethod) fromJson = fromJson.MakeGenericMethod(typeArguments); -#if IOS || CORE return (JsonSerializationTypeRegistry.FromJsonDelegate) fromJson.CreateDelegate(typeof(JsonSerializationTypeRegistry.FromJsonDelegate), fromJson); -#else - return (JsonSerializationTypeRegistry.FromJsonDelegate) Delegate.CreateDelegate(typeof (JsonSerializationTypeRegistry.FromJsonDelegate), fromJson); -#endif } protected virtual Type[] GetTypeArguments(Type type) diff --git a/Manatee.Json/Serialization/Internal/ConstructorResolver.cs b/Manatee.Json/Serialization/Internal/ConstructorResolver.cs index b0a431e..b983aaa 100644 --- a/Manatee.Json/Serialization/Internal/ConstructorResolver.cs +++ b/Manatee.Json/Serialization/Internal/ConstructorResolver.cs @@ -23,7 +23,6 @@ using System; using System.Linq; -using System.Reflection; using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal @@ -38,17 +37,13 @@ public object Resolve(Type type) { try { -#if IOS var constructors = type.TypeInfo().DeclaredConstructors.ToList(); -#else - var constructors = type.TypeInfo().GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).ToList(); -#endif if (!constructors.Any()) return Activator.CreateInstance(type); var parameterless = constructors.FirstOrDefault(c => !c.GetParameters().Any()); if (parameterless != null) return parameterless.Invoke(null); - var constructor = constructors.OrderBy(c => c.GetParameters().Count()).First(); + var constructor = constructors.OrderBy(c => c.GetParameters().Length).First(); var parameters = constructor.GetParameters().Select(p => Resolve(p.ParameterType)).ToArray(); return constructor.Invoke(parameters); } diff --git a/Manatee.Json/Serialization/Internal/SerializerCache.cs b/Manatee.Json/Serialization/Internal/SerializerCache.cs index ddcdb1e..489be76 100644 --- a/Manatee.Json/Serialization/Internal/SerializerCache.cs +++ b/Manatee.Json/Serialization/Internal/SerializerCache.cs @@ -22,22 +22,18 @@ ***************************************************************************************/ using System; -#if !NET35 && !IOS -using Dictionary = System.Collections.Concurrent.ConcurrentDictionary; -#else -using Dictionary = System.Collections.Generic.Dictionary; -#endif +using System.Collections.Generic; using System.Reflection; namespace Manatee.Json.Serialization.Internal { internal static class SerializerCache { - private static readonly Dictionary _cache; + private static readonly Dictionary _cache; static SerializerCache() { - _cache = new Dictionary(); + _cache = new Dictionary(); } public static MethodInfo GetSerializeMethod(Type type) diff --git a/Manatee.Json/Serialization/Internal/SerializerFactory.cs b/Manatee.Json/Serialization/Internal/SerializerFactory.cs index 2b2e9a8..9ad546e 100644 --- a/Manatee.Json/Serialization/Internal/SerializerFactory.cs +++ b/Manatee.Json/Serialization/Internal/SerializerFactory.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; +using System.Reflection; using Manatee.Json.Internal; using Manatee.Json.Schema; using Manatee.Json.Serialization.Internal.Serializers; @@ -76,13 +77,14 @@ public static ISerializer GetSerializer(JsonSerializerOptions options, JsonVa { var type = typeof (T); var typeToSerialize = JsonSerializationAbstractionMap.GetMap(type); - if (typeof (IJsonSchema).IsAssignableFrom(typeToSerialize)) + // TODO: optimize + if (typeof (IJsonSchema).GetTypeInfo().IsAssignableFrom(typeToSerialize.GetTypeInfo())) return BuildSerializer(_schemaSerializer); if (JsonSerializationTypeRegistry.IsRegistered(typeToSerialize)) return BuildSerializer(_registeredObjectSerializer); - if (typeof (IJsonSerializable).IsAssignableFrom(typeToSerialize)) + if (typeof (IJsonSerializable).GetTypeInfo().IsAssignableFrom(typeToSerialize.GetTypeInfo())) return BuildSerializer(_jsonSerializableSerializer); - if (typeof (Enum).IsAssignableFrom(typeToSerialize)) + if (typeof (Enum).GetTypeInfo().IsAssignableFrom(typeToSerialize.GetTypeInfo())) { if (json != null) { diff --git a/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs b/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs index a06df67..d4596b9 100644 --- a/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs +++ b/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs @@ -23,7 +23,6 @@ using System; using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal { @@ -40,12 +39,12 @@ public SerializerMethodPair(Type type) private static MethodInfo GetTypedSerializeMethod(Type type) { - return typeof(JsonSerializer).GetMethod("Serialize") + return typeof(JsonSerializer).GetTypeInfo().GetDeclaredMethod("Serialize") .MakeGenericMethod(type); } private static MethodInfo GetTypedDeserializeMethod(Type type) { - return typeof(JsonSerializer).GetMethod("Deserialize") + return typeof(JsonSerializer).GetTypeInfo().GetDeclaredMethod("Deserialize") .MakeGenericMethod(type); } } diff --git a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs index c19e23a..6baf44e 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs @@ -57,13 +57,8 @@ public T Deserialize(JsonValue json, JsonSerializer serializer) { EnsureDescriptions(); var options = serializer.Options.CaseSensitiveDeserialization -#if IOS || CORE ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; -#else - ? StringComparison.InvariantCultureIgnoreCase - : StringComparison.InvariantCulture; -#endif var entry = _descriptions[typeof (T)].FirstOrDefault(d => string.Equals(d.String, json.String, options)); if (entry == null) { @@ -87,8 +82,8 @@ private static void EnsureDescriptions() private static string GetDescription(string name) { var type = typeof (T); - var memInfo = type.TypeInfo().GetMember(name); - var attributes = memInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false); + var memInfo = type.GetTypeInfo().GetDeclaredField(name); + var attributes = memInfo.GetCustomAttributes(typeof (DescriptionAttribute), false); return attributes.Any() ? ((DescriptionAttribute)attributes.First()).Description : name; } private static string BuildFlagsValues(T obj, string separator) diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index 70705d2..61b3b8c 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -91,12 +91,12 @@ private static ReflectionInfo InitializeInstanceCache(Type type) ReflectionInfo info; if (!_instanceCache.TryGetValue(type, out info)) { - var read = GetInstanceProperties(type).Where(p => p.GetSetMethod() == null) - .Where(p => p.GetGetMethod() != null) + var read = GetInstanceProperties(type).Where(p => p.SetMethod == null) + .Where(p => p.GetMethod != null) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); - var readWrite = GetInstanceProperties(type).Where(p => p.GetSetMethod() != null) - .Where(p => p.GetGetMethod() != null) + var readWrite = GetInstanceProperties(type).Where(p => p.SetMethod != null) + .Where(p => p.GetMethod != null) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); var fields = GetInstanceFields(type).Where(p => !p.IsInitOnly) @@ -111,12 +111,12 @@ private static ReflectionInfo InitializeStaticCache(Type type) ReflectionInfo info; if (!_staticCache.TryGetValue(type, out info)) { - var read = GetStaticProperties(type).Where(p => p.GetSetMethod() == null) - .Where(p => p.GetGetMethod() != null) + var read = GetStaticProperties(type).Where(p => p.SetMethod == null) + .Where(p => p.GetMethod != null) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); - var readWrite = GetStaticProperties(type).Where(p => p.GetSetMethod() != null) - .Where(p => p.GetGetMethod() != null) + var readWrite = GetStaticProperties(type).Where(p => p.SetMethod != null) + .Where(p => p.GetMethod != null) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); var fields = GetStaticFields(type).Where(p => !p.IsInitOnly) @@ -134,35 +134,19 @@ private static SerializationInfo BuildSerializationInfo(MemberInfo info) } private static IEnumerable GetInstanceProperties(Type type) { -#if IOS return type.TypeInfo().DeclaredProperties.Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); -#else - return type.TypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public); -#endif } private static IEnumerable GetStaticProperties(Type type) { -#if IOS return type.TypeInfo().DeclaredProperties.Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); -#else - return type.TypeInfo().GetProperties(BindingFlags.Static | BindingFlags.Public); -#endif } private static IEnumerable GetInstanceFields(Type type) { -#if IOS return type.TypeInfo().DeclaredFields.Where(f => !f.IsStatic && f.IsPublic); -#else - return type.TypeInfo().GetFields(BindingFlags.Instance | BindingFlags.Public); -#endif } private static IEnumerable GetStaticFields(Type type) { -#if IOS return type.TypeInfo().DeclaredFields.Where(f => f.IsStatic && f.IsPublic); -#else - return type.TypeInfo().GetFields(BindingFlags.Static | BindingFlags.Public); -#endif } } } \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs index b07154c..dce5be1 100644 --- a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs @@ -41,11 +41,7 @@ internal static class TemplateGenerator static TemplateGenerator() { -#if IOS - _buildMethod = typeof(TemplateGenerator).GetMethod("BuildInstance"); -#else - _buildMethod = typeof(TemplateGenerator).TypeInfo().GetMethod("BuildInstance", BindingFlags.Static | BindingFlags.NonPublic); -#endif + _buildMethod = typeof(TemplateGenerator).GetTypeInfo().GetDeclaredMethod("BuildInstance"); _buildMethods = new Dictionary(); _defaultInstances = new Dictionary { @@ -105,13 +101,9 @@ private static void FillProperties(T instance, JsonSerializerOptions options) { var type = typeof (T); -#if IOS var properties = type.TypeInfo().DeclaredProperties -#else - var properties = type.TypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public) -#endif - .Where(p => p.GetSetMethod() != null) - .Where(p => p.GetGetMethod() != null) + .Where(p => p.SetMethod != null) + .Where(p => p.GetMethod != null) .Where(p => !p.GetCustomAttributes(typeof (JsonIgnoreAttribute), true).Any()); foreach (var propertyInfo in properties) { @@ -124,11 +116,7 @@ private static void FillProperties(T instance, JsonSerializerOptions options) } private static void FillFields(T instance, JsonSerializerOptions options) { -#if IOS var fields = typeof (T).TypeInfo().DeclaredFields -#else - var fields = typeof (T).TypeInfo().GetFields(BindingFlags.Instance | BindingFlags.Public) -#endif .Where(p => !p.IsInitOnly) .Where(p => !p.GetCustomAttributes(typeof (JsonIgnoreAttribute), true).Any()); foreach (var fieldInfo in fields) diff --git a/Manatee.Json/Serialization/Internal/TypeGenerator.cs b/Manatee.Json/Serialization/Internal/TypeGenerator.cs index 8b3971c..1ff6f56 100644 --- a/Manatee.Json/Serialization/Internal/TypeGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TypeGenerator.cs @@ -21,7 +21,7 @@ ***************************************************************************************/ -#if !IOS && !CORE +#if !NETSTANDARD1_1 using System; using System.Collections.Generic; @@ -46,13 +46,8 @@ static TypeGenerator() var assemblyName = new AssemblyName(AssemblyName); // Note: To debug IL generation, please use the following line with your own test path. Also need to uncomment the Save() call in the Generate() method. //_assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, @"E:\Projects\Manatee.Json\Manatee.Json.Tests\bin\Debug\"); -#if NET35 - _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); - _moduleBuilder = _assemblyBuilder.DefineDynamicModule(AssemblyName); -#else _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(AssemblyName, AssemblyName + ".dll"); -#endif _cache = new Dictionary(); } diff --git a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs index cce1000..04e7e0f 100644 --- a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs +++ b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs @@ -146,8 +146,8 @@ internal static T CreateInstance(JsonValue json, IResolver resolver) return (T) resolver.Resolve(tConcrete); } -#if !IOS && !CORE - if (type.IsInterface) +#if !NETSTANDARD1_1 + if (type.GetTypeInfo().IsInterface) return TypeGenerator.Generate(); #endif } @@ -176,7 +176,7 @@ private static void MapBaseTypes(Type tAbstract, Type tConcrete, bool overwrite) _registry[tBase] = tConcrete; } MapBaseTypes(tBase, tConcrete, overwrite); - foreach (var tInterface in tAbstract.TypeInfo().GetInterfaces()) + foreach (var tInterface in tAbstract.TypeInfo().ImplementedInterfaces) { if (overwrite || !_registry.ContainsKey(tInterface)) { diff --git a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs index e5e2a16..c43cb09 100644 --- a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs +++ b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs @@ -63,20 +63,16 @@ public static class JsonSerializationTypeRegistry static JsonSerializationTypeRegistry() { - _delegateProviders = typeof(JsonSerializationTypeRegistry).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(ISerializationDelegateProvider).IsAssignableFrom(t) && - !t.TypeInfo().IsAbstract && - t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + _delegateProviders = typeof(JsonSerializationTypeRegistry).TypeInfo().Assembly.DefinedTypes + .Where(t => typeof(ISerializationDelegateProvider).GetTypeInfo().IsAssignableFrom(t) && + !t.IsAbstract && + t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); _toJsonConverters = new Dictionary(); _fromJsonConverters = new Dictionary(); -#if IOS - _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetMethod("RegisterProviderDelegates"); -#else - _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetMethod("RegisterProviderDelegates", BindingFlags.Static | BindingFlags.NonPublic); -#endif + _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetTypeInfo().GetDeclaredMethod("RegisterProviderDelegates"); } /// diff --git a/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs b/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs index a75d415..7679e99 100644 --- a/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs +++ b/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs @@ -31,9 +31,6 @@ namespace Manatee.Json.Serialization /// Optionally thrown when deserializing and the JSON structure contains property names /// which are not valid for the type requested. /// -#if !IOS && !CORE - [Serializable] -#endif public class TypeDoesNotContainPropertyException : Exception { /// diff --git a/Manatee.Json/Serialization/TypeRegistrationException.cs b/Manatee.Json/Serialization/TypeRegistrationException.cs index 763ff1e..3a3d1fd 100644 --- a/Manatee.Json/Serialization/TypeRegistrationException.cs +++ b/Manatee.Json/Serialization/TypeRegistrationException.cs @@ -30,9 +30,6 @@ namespace Manatee.Json.Serialization /// Thrown when /// is passed one method and a null. /// -#if !IOS && !CORE - [Serializable] -#endif public class TypeRegistrationException : Exception { /// diff --git a/Manatee.Json/XmlExtensions.cs b/Manatee.Json/XmlExtensions.cs index a8ed3aa..246c562 100644 --- a/Manatee.Json/XmlExtensions.cs +++ b/Manatee.Json/XmlExtensions.cs @@ -280,7 +280,7 @@ private static XName GetXName(string key) return name; } -#if !IOS && !CORE +#if !NETSTANDARD1_1 /// /// Converts an to an . /// diff --git a/Wiki b/Wiki index 3537c0e..b06e173 160000 --- a/Wiki +++ b/Wiki @@ -1 +1 @@ -Subproject commit 3537c0e7c780be8cbab689bd0972d3a7db272d54 +Subproject commit b06e173b927c852984a1a16b94b6e263cd3cf2f1 From e0dc4a88dc7a7c1e812b4c9fd7169599396dfe71 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 13 Jun 2017 13:12:16 +1200 Subject: [PATCH 03/15] fixed test project referencing issue. some tests are failing. --- Manatee.Json.Tests/Manatee.Json.Tests.csproj | 2 +- Manatee.Json/Manatee.Json.csproj | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj b/Manatee.Json.Tests/Manatee.Json.Tests.csproj index b64f6b1..694f576 100644 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj +++ b/Manatee.Json.Tests/Manatee.Json.Tests.csproj @@ -166,7 +166,7 @@ - {b0a832b8-06b7-4494-8416-fabe755f621f} + {7548217b-8c18-4ca5-a248-59889ef93cf5} Manatee.Json diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj index 66c518b..4c1126f 100644 --- a/Manatee.Json/Manatee.Json.csproj +++ b/Manatee.Json/Manatee.Json.csproj @@ -1,7 +1,7 @@  - netstandard1.1 + netstandard1.1;net45 True Provides an intuitive approach to building JSON structures. 6.0.0 @@ -17,13 +17,23 @@ BUG FIX: Schema now properly resolve referenced schema relative to document path Removed JsonSchemaFactory.Load(string filename) in favor of . Note: As a consequence of removing JsonSchemaFactory.Load(string filename), you'll need to resolve the full file name (using System.IO.Path.GetFullPath()) before passing it into JsonSchemaRegistry.Get(string uri). - + True Manatee.Json.snk - + + .NETStandard + + - + + + .NETFramework + + + + + \ No newline at end of file From ec563d97c1291d84e34d780e433bc0a769333792 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 13 Jun 2017 14:28:22 +1200 Subject: [PATCH 04/15] merged from master --- Manatee.Json.sln.DotSettings.user | 4 +- Manatee.Json/Manatee.Json.csproj | 24 +++++++++--- Manatee.Json/Parsing/JsonParser.cs | 1 - .../Parsing/JsonPathExpressionParser.cs | 1 - Manatee.Json/Path/Parsing/JsonPathParser.cs | 2 +- Manatee.Json/Path/Parsing/PathParsingExtensions.cs | 1 - .../JsonSchemaPropertyValidatorFactory.cs | 2 +- Manatee.Json/project.nuspec | 45 ---------------------- 8 files changed, 22 insertions(+), 58 deletions(-) delete mode 100644 Manatee.Json/project.nuspec diff --git a/Manatee.Json.sln.DotSettings.user b/Manatee.Json.sln.DotSettings.user index 900e72b..9ce5a53 100644 --- a/Manatee.Json.sln.DotSettings.user +++ b/Manatee.Json.sln.DotSettings.user @@ -9,10 +9,10 @@ True - (Doc Ln 24 Col 13) + (Doc Ln 47 Col 13) 6ADF0BCF-4E46-4605-A784-51EA6DAC81C7/d:Path/d:Expressions/f:IsLessThanExpression.cs NumberedBookmarkManager True - (Doc Ln 186 Col 20) + (Doc Ln 210 Col 20) 6ADF0BCF-4E46-4605-A784-51EA6DAC81C7/d:Serialization/d:Internal/d:Serializers/f:AutoSerializer.cs NumberedBookmarkManager \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj index 4c1126f..4ad8c2f 100644 --- a/Manatee.Json/Manatee.Json.csproj +++ b/Manatee.Json/Manatee.Json.csproj @@ -4,22 +4,34 @@ netstandard1.1;net45 True Provides an intuitive approach to building JSON structures. - 6.0.0 + 6.0.3 Copyright © 2016 Little Crab Solutions https://github.com/gregsdennis/Manatee.Json/blob/master/LICENSE.txt https://github.com/gregsdennis/Manatee.Json https://bytebucket.org/gregsdennis/manatee.json/wiki/Resources/Manatee-Json-Logo.png json manatee parser serializer jsonpath jsonschema transform path schema linq-to-json - v6.0.0 + v6.0.3 +Schema passes latest version of JSON Schema Test Suite. (#63) + +v6.0.2 +BUG FIX: Referenced schema not loaded. (#58) + +v6.0.1.1 +Repackaged + +v6.0.1 +Updated equality logic to further unify .Net-null and JSON-null. Please read Equality Comparisons section of Usage wiki page. +BUG FIX: Vague error messaging when validating schema. (#55) + +v6.0.0 Added DocumentPath to IJsonSchema. BUG FIX: Schema now properly resolve referenced schema relative to document path instead of application's current directory. (#50) -Removed JsonSchemaFactory.Load(string filename) in favor of . - -Note: As a consequence of removing JsonSchemaFactory.Load(string filename), you'll need to resolve the full file name (using System.IO.Path.GetFullPath()) before passing it into JsonSchemaRegistry.Get(string uri). - +Removed JsonSchemaFactory.Load(string filename) in favor of JsonSchemaRegistry.Get(string uri). + True Manatee.Json.snk + 6.0.3.0 diff --git a/Manatee.Json/Parsing/JsonParser.cs b/Manatee.Json/Parsing/JsonParser.cs index f5d4a1b..92f4590 100644 --- a/Manatee.Json/Parsing/JsonParser.cs +++ b/Manatee.Json/Parsing/JsonParser.cs @@ -14,7 +14,6 @@ internal static class JsonParser static JsonParser() { Parsers = typeof(JsonParser).TypeInfo().Assembly.DefinedTypes - // TODO: optimize .Where(t => typeof(IJsonParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() diff --git a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs index 90a199f..8ed1be5 100644 --- a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs +++ b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs @@ -13,7 +13,6 @@ internal static class JsonPathExpressionParser static JsonPathExpressionParser() { Parsers = typeof(JsonPathExpressionParser).TypeInfo().Assembly.DefinedTypes - // TODO: optimize .Where(t => typeof(IJsonPathExpressionParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() diff --git a/Manatee.Json/Path/Parsing/JsonPathParser.cs b/Manatee.Json/Path/Parsing/JsonPathParser.cs index fb5b0d1..6f61994 100644 --- a/Manatee.Json/Path/Parsing/JsonPathParser.cs +++ b/Manatee.Json/Path/Parsing/JsonPathParser.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using Manatee.Json.Internal; namespace Manatee.Json.Path.Parsing @@ -12,7 +13,6 @@ internal static class JsonPathParser static JsonPathParser() { Parsers = typeof(JsonPathParser).TypeInfo().Assembly.DefinedTypes - // TODO: optimize .Where(t => typeof(IJsonPathParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() diff --git a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs index aac82a8..ee36736 100644 --- a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs +++ b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs @@ -196,7 +196,6 @@ public static string GetInt(string source, ref int index, out int? number) public static string GetNumber(this string source, ref int index, out double? number) { double value; - // TODO: optimize var text = new string(source.Substring(index).Cast().TakeWhile(c => NumberChars.Cast().Contains(c)).ToArray()); if (text.Length == 0 && source[index].In(':', ',', ']')) { diff --git a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs index eac17a7..80792e0 100644 --- a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs +++ b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using Manatee.Json.Internal; namespace Manatee.Json.Schema.Validators @@ -12,7 +13,6 @@ internal static class JsonSchemaPropertyValidatorFactory static JsonSchemaPropertyValidatorFactory() { AllValidators = typeof(IJsonSchemaPropertyValidator).TypeInfo().Assembly.DefinedTypes - // TODO: optimize .Where(t => typeof(IJsonSchemaPropertyValidator).GetTypeInfo().IsAssignableFrom(t) && !t.IsAbstract && t.IsClass) diff --git a/Manatee.Json/project.nuspec b/Manatee.Json/project.nuspec deleted file mode 100644 index 54d1b54..0000000 --- a/Manatee.Json/project.nuspec +++ /dev/null @@ -1,45 +0,0 @@ - - - - Manatee.Json - 6.0.3 - - A fully object-oriented approach to JSON manipulation, validation, and serialization that focuses on modeling the JSON structure rather than mere string parsing. - - gregsdennis - Copyright © 2016 Little Crab Solutions - https://www.github.com/gregsdennis/manatee.json - https://github.com/gregsdennis/Manatee.Json/blob/master/LICENSE.txt - https://bytebucket.org/gregsdennis/manatee.json/wiki/Resources/Manatee-Json-Logo.png - - v6.0.3 - Schema passes latest version of JSON Schema Test Suite. (#63) - - v6.0.2 - BUG FIX: Referenced schema not loaded. (#58) - - v6.0.1.1 - Repackaged - - v6.0.1 - Updated equality logic to further unify .Net-null and JSON-null. Please read Equality Comparisons section of Usage wiki page. - BUG FIX: Vague error messaging when validating schema. (#55) - - v6.0.0 - Added DocumentPath to IJsonSchema. - BUG FIX: Schema now properly resolve referenced schema relative to document path instead of application's current directory. (#50) - Removed JsonSchemaFactory.Load(string filename) in favor of JsonSchemaRegistry.Get(string uri). - - json manatee parser serializer jsonpath jsonschema transform path schema linq-to-json - - - - - - - - - - - - \ No newline at end of file From 7c79c0e5945f80d848161c259b269de2fd2a032a Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 13 Jun 2017 21:25:49 +1200 Subject: [PATCH 05/15] upgraded to netstandard1.3 and net46 to support file downloads --- Manatee.Json.Tests/Manatee.Json.Tests.csproj | 19 +++++++++++++++++-- Manatee.Json.Tests/packages.config | 8 ++++++++ Manatee.Json.sln.DotSettings.user | 2 +- Manatee.Json/Manatee.Json.csproj | 12 ++++++------ Manatee.Json/Schema/JsonSchemaOptions.cs | 21 ++++++++++++++++++--- .../Serialization/Internal/TypeGenerator.cs | 2 +- .../JsonSerializationAbstractionMap.cs | 2 +- Manatee.Json/XmlExtensions.cs | 2 +- 8 files changed, 53 insertions(+), 15 deletions(-) create mode 100644 Manatee.Json.Tests/packages.config diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj b/Manatee.Json.Tests/Manatee.Json.Tests.csproj index 96b56a5..c7bce9f 100644 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj +++ b/Manatee.Json.Tests/Manatee.Json.Tests.csproj @@ -11,7 +11,7 @@ Properties Manatee.Json.Tests Manatee.Json.Tests - v4.5 + v4.6 512 {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -59,9 +59,23 @@ - + + ..\packages\System.Net.Http.4.3.2\lib\net46\System.Net.Http.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net46\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net46\System.Security.Cryptography.X509Certificates.dll + @@ -128,6 +142,7 @@ Always + PreserveNewest diff --git a/Manatee.Json.Tests/packages.config b/Manatee.Json.Tests/packages.config new file mode 100644 index 0000000..eb95af3 --- /dev/null +++ b/Manatee.Json.Tests/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Manatee.Json.sln.DotSettings.user b/Manatee.Json.sln.DotSettings.user index 9ce5a53..58f206f 100644 --- a/Manatee.Json.sln.DotSettings.user +++ b/Manatee.Json.sln.DotSettings.user @@ -1,5 +1,5 @@  - SOLUTION + 0 diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj index 4ad8c2f..12d1775 100644 --- a/Manatee.Json/Manatee.Json.csproj +++ b/Manatee.Json/Manatee.Json.csproj @@ -1,7 +1,7 @@  - netstandard1.1;net45 + netstandard1.3;net46 True Provides an intuitive approach to building JSON structures. 6.0.3 @@ -37,15 +37,15 @@ Removed JsonSchemaFactory.Load(string filename) in favor of JsonSchemaRegistry.G .NETStandard - - - - + .NETFramework - + + + + \ No newline at end of file diff --git a/Manatee.Json/Schema/JsonSchemaOptions.cs b/Manatee.Json/Schema/JsonSchemaOptions.cs index c8391a1..e540733 100644 --- a/Manatee.Json/Schema/JsonSchemaOptions.cs +++ b/Manatee.Json/Schema/JsonSchemaOptions.cs @@ -1,7 +1,6 @@ using System; -using System.Net; +using System.IO; using System.Net.Http; -using System.Text; namespace Manatee.Json.Schema { @@ -17,7 +16,7 @@ public static class JsonSchemaOptions /// public static Func Download { - get { return _download ?? (_download = uri => new HttpClient().GetStringAsync(uri).Result); } + get { return _download ?? (_download = _BasicDownload); } set { _download = value; } } @@ -33,5 +32,21 @@ static JsonSchemaOptions() { ValidateFormat = true; } + + private static string _BasicDownload(string path) + { + var uri = new Uri(path); + + switch (uri.Scheme) + { + case "http": + case "https:": + return new HttpClient().GetStringAsync(uri).Result; + case "file": + return File.ReadAllText(uri.AbsolutePath); + default: + throw new Exception(); + } + } } } diff --git a/Manatee.Json/Serialization/Internal/TypeGenerator.cs b/Manatee.Json/Serialization/Internal/TypeGenerator.cs index c0cea0a..3a06171 100644 --- a/Manatee.Json/Serialization/Internal/TypeGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TypeGenerator.cs @@ -1,4 +1,4 @@ -#if !NETSTANDARD1_1 +#if !NETSTANDARD1_3 using System; using System.Collections.Generic; diff --git a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs index edcabbf..2d2399d 100644 --- a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs +++ b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs @@ -123,7 +123,7 @@ internal static T CreateInstance(JsonValue json, IResolver resolver) return (T) resolver.Resolve(tConcrete); } -#if !NETSTANDARD1_1 +#if !NETSTANDARD1_3 if (type.GetTypeInfo().IsInterface) return TypeGenerator.Generate(); #endif diff --git a/Manatee.Json/XmlExtensions.cs b/Manatee.Json/XmlExtensions.cs index e6c04df..2183d82 100644 --- a/Manatee.Json/XmlExtensions.cs +++ b/Manatee.Json/XmlExtensions.cs @@ -257,7 +257,7 @@ private static XName GetXName(string key) return name; } -#if !NETSTANDARD1_1 +#if !NETSTANDARD1_3 /// /// Converts an to an . /// From 4f61a3a3a7bc636281d3b62a91cd598b8ad15821 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 13 Jun 2017 22:39:44 +1200 Subject: [PATCH 06/15] fixed file path issue. --- Manatee.Json/Schema/JsonSchemaOptions.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Manatee.Json/Schema/JsonSchemaOptions.cs b/Manatee.Json/Schema/JsonSchemaOptions.cs index e540733..05de557 100644 --- a/Manatee.Json/Schema/JsonSchemaOptions.cs +++ b/Manatee.Json/Schema/JsonSchemaOptions.cs @@ -43,7 +43,8 @@ private static string _BasicDownload(string path) case "https:": return new HttpClient().GetStringAsync(uri).Result; case "file": - return File.ReadAllText(uri.AbsolutePath); + var filename = Uri.UnescapeDataString(uri.AbsolutePath); + return File.ReadAllText(filename); default: throw new Exception(); } From 7232dc030c8a6f9ceff058f2f73b95be854e8249 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 13 Jun 2017 22:54:25 +1200 Subject: [PATCH 07/15] property reflection fixed --- .../SerializationDelegateProviderBase.cs | 4 ++-- .../Internal/Serializers/ReflectionCache.cs | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs index 27ac04f..4e413f2 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs @@ -22,7 +22,7 @@ public JsonSerializationTypeRegistry.ToJsonDelegate GetEncoder() var toJson = _encodeMethod; if (toJson.IsGenericMethod) toJson = toJson.MakeGenericMethod(typeArguments); - return (JsonSerializationTypeRegistry.ToJsonDelegate) toJson.CreateDelegate(typeof (JsonSerializationTypeRegistry.ToJsonDelegate), toJson); + return (JsonSerializationTypeRegistry.ToJsonDelegate) toJson.CreateDelegate(typeof (JsonSerializationTypeRegistry.ToJsonDelegate), null); } public JsonSerializationTypeRegistry.FromJsonDelegate GetDecoder() { @@ -30,7 +30,7 @@ public JsonSerializationTypeRegistry.FromJsonDelegate GetDecoder() var fromJson = _decodeMethod; if (fromJson.IsGenericMethod) fromJson = fromJson.MakeGenericMethod(typeArguments); - return (JsonSerializationTypeRegistry.FromJsonDelegate) fromJson.CreateDelegate(typeof(JsonSerializationTypeRegistry.FromJsonDelegate), fromJson); + return (JsonSerializationTypeRegistry.FromJsonDelegate) fromJson.CreateDelegate(typeof(JsonSerializationTypeRegistry.FromJsonDelegate), null); } protected virtual Type[] GetTypeArguments(Type type) diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index 64ddc51..9bb7a34 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -68,12 +68,12 @@ private static ReflectionInfo InitializeInstanceCache(Type type) ReflectionInfo info; if (!_instanceCache.TryGetValue(type, out info)) { - var read = GetInstanceProperties(type).Where(p => p.SetMethod == null) - .Where(p => p.GetMethod != null) + var read = GetInstanceProperties(type).Where(p => !p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); - var readWrite = GetInstanceProperties(type).Where(p => p.SetMethod != null) - .Where(p => p.GetMethod != null) + var readWrite = GetInstanceProperties(type).Where(p => p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); var fields = GetInstanceFields(type).Where(p => !p.IsInitOnly) @@ -88,12 +88,12 @@ private static ReflectionInfo InitializeStaticCache(Type type) ReflectionInfo info; if (!_staticCache.TryGetValue(type, out info)) { - var read = GetStaticProperties(type).Where(p => p.SetMethod == null) - .Where(p => p.GetMethod != null) + var read = GetStaticProperties(type).Where(p => !p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); - var readWrite = GetStaticProperties(type).Where(p => p.SetMethod != null) - .Where(p => p.GetMethod != null) + var readWrite = GetStaticProperties(type).Where(p => p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) .Select(BuildSerializationInfo); var fields = GetStaticFields(type).Where(p => !p.IsInitOnly) From 511cebc2827ef5f614c261237b8c460662050139 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 13 Jun 2017 23:32:10 +1200 Subject: [PATCH 08/15] some minor code edits. build script updated to use VS2017. still need to test on myget --- Manatee.Json-Portable/Manatee.Json.csproj | 7 -- Manatee.Json/Internal/CompatibilityExtensions.cs | 18 +---- Manatee.Json/Internal/GeneralExtensions.cs | 10 ++- Manatee.Json/Internal/JsonPathInput.cs | 42 ----------- Manatee.Json/Manatee.Json.csproj | 28 +++----- .../Internal/Serializers/ReflectionCache.cs | 82 ++++++++++++++-------- Manatee.Json/UriExtensions.cs | 8 --- build.bat | 4 +- 8 files changed, 67 insertions(+), 132 deletions(-) delete mode 100644 Manatee.Json-Portable/Manatee.Json.csproj delete mode 100644 Manatee.Json/Internal/JsonPathInput.cs diff --git a/Manatee.Json-Portable/Manatee.Json.csproj b/Manatee.Json-Portable/Manatee.Json.csproj deleted file mode 100644 index 1536775..0000000 --- a/Manatee.Json-Portable/Manatee.Json.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netstandard1.0 - - - \ No newline at end of file diff --git a/Manatee.Json/Internal/CompatibilityExtensions.cs b/Manatee.Json/Internal/CompatibilityExtensions.cs index 8b86382..4a49983 100644 --- a/Manatee.Json/Internal/CompatibilityExtensions.cs +++ b/Manatee.Json/Internal/CompatibilityExtensions.cs @@ -5,6 +5,7 @@ namespace Manatee.Json.Internal { + [Obsolete] internal static class CompatibilityExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -27,22 +28,5 @@ public static Type[] GetTypeArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } -#if CORE - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsAssignableFrom(this Type derivedType, Type baseType) - { - return derivedType.TypeInfo().IsAssignableFrom(baseType); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetMethod(this Type type, string name, BindingFlags flags = BindingFlags.Default) - { - return type.TypeInfo().GetMethod(name, flags); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetMethod(this Type type, string name, Type[] typeParams) - { - return type.TypeInfo().GetMethod(name, typeParams); - } -#endif } } diff --git a/Manatee.Json/Internal/GeneralExtensions.cs b/Manatee.Json/Internal/GeneralExtensions.cs index 91e9798..c7f09d5 100644 --- a/Manatee.Json/Internal/GeneralExtensions.cs +++ b/Manatee.Json/Internal/GeneralExtensions.cs @@ -3,8 +3,6 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Internal { @@ -122,14 +120,14 @@ public static string InsertEscapeSequences(this string source) } if (replace != null) { - source = Replace(source, index, count, replace); + source = _Replace(source, index, count, replace); index++; } index++; } return source; } - private static string Replace(string source, int index, int count, string content) + private static string _Replace(string source, int index, int count, string content) { // I've checked both of these methods with ILSpy. They occur in external methods, so // we're not going to do much better than this. @@ -186,11 +184,11 @@ public static string SkipWhiteSpace(this StreamReader stream, out char ch) // Note: These methods assume that if a generic type is passed, the type is open. public static bool InheritsFrom(this Type tDerived, Type tBase) { - if (tDerived.IsSubtypeOf(tBase)) return true; + if (tDerived._IsSubtypeOf(tBase)) return true; var interfaces = tDerived.TypeInfo().ImplementedInterfaces.Select(i => i.TypeInfo().IsGenericType ? i.GetGenericTypeDefinition() : i); return interfaces.Contains(tBase); } - private static bool IsSubtypeOf(this Type tDerived, Type tBase) + private static bool _IsSubtypeOf(this Type tDerived, Type tBase) { var currentType = tDerived.TypeInfo().BaseType; while (currentType != null) diff --git a/Manatee.Json/Internal/JsonPathInput.cs b/Manatee.Json/Internal/JsonPathInput.cs deleted file mode 100644 index c52db5a..0000000 --- a/Manatee.Json/Internal/JsonPathInput.cs +++ /dev/null @@ -1,42 +0,0 @@ -/*************************************************************************************** - - Copyright 2016 Greg Dennis - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - File Name: JsonPathInput.cs - Namespace: Manatee.Json.Internal - Class Name: JsonPathInput - Purpose: Enumerates input types for JSON Paths. - -***************************************************************************************/ - -namespace Manatee.Json.Internal -{ - internal enum JsonPathInput - { - Dollar, - Current, - OpenBracket, - CloseBracket, - Period, - Star, - OpenParenth, - Question, - Number, - Letter, - Colon, - Comma, - End - } -} \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj index 12d1775..c2207e2 100644 --- a/Manatee.Json/Manatee.Json.csproj +++ b/Manatee.Json/Manatee.Json.csproj @@ -4,34 +4,24 @@ netstandard1.3;net46 True Provides an intuitive approach to building JSON structures. - 6.0.3 - Copyright © 2016 Little Crab Solutions + 7.0.0 + Copyright © 2017 Little Crab Solutions https://github.com/gregsdennis/Manatee.Json/blob/master/LICENSE.txt https://github.com/gregsdennis/Manatee.Json https://bytebucket.org/gregsdennis/manatee.json/wiki/Resources/Manatee-Json-Logo.png json manatee parser serializer jsonpath jsonschema transform path schema linq-to-json - v6.0.3 -Schema passes latest version of JSON Schema Test Suite. (#63) - -v6.0.2 -BUG FIX: Referenced schema not loaded. (#58) - -v6.0.1.1 -Repackaged + v7.0.0 +BREAKING CHANGE: Frameworks below 4.6 are no longer supported. +Updated to multi-targeted NetStandard1.3 & NetFramework4.6. -v6.0.1 -Updated equality logic to further unify .Net-null and JSON-null. Please read Equality Comparisons section of Usage wiki page. -BUG FIX: Vague error messaging when validating schema. (#55) - -v6.0.0 -Added DocumentPath to IJsonSchema. -BUG FIX: Schema now properly resolve referenced schema relative to document path instead of application's current directory. (#50) -Removed JsonSchemaFactory.Load(string filename) in favor of JsonSchemaRegistry.Get(string uri). +v6.0.3 +Schema passes latest version of JSON Schema Test Suite. (#63) True Manatee.Json.snk - 6.0.3.0 + 7.0.0.0 + 7.0.0.0 diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index 9bb7a34..2c07d9f 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -33,22 +33,22 @@ static ReflectionCache() public static IEnumerable GetMembers(Type type, PropertySelectionStrategy propertyTypes, bool includeFields) { - var info = InitializeInstanceCache(type); - var members = GetProperties(info, propertyTypes); + var info = _InitializeInstanceCache(type); + var members = _GetProperties(info, propertyTypes); if (includeFields) - members = members.Concat(GetFields(info)); + members = members.Concat(_GetFields(info)); return members; } public static IEnumerable GetTypeMembers(Type type, PropertySelectionStrategy propertyTypes, bool includeFields) { - var info = InitializeStaticCache(type); - var members = GetProperties(info, propertyTypes); + var info = _InitializeStaticCache(type); + var members = _GetProperties(info, propertyTypes); if (includeFields) - members = members.Concat(GetFields(info)); + members = members.Concat(_GetFields(info)); return members; } - private static IEnumerable GetProperties(ReflectionInfo info, PropertySelectionStrategy propertyTypes) + private static IEnumerable _GetProperties(ReflectionInfo info, PropertySelectionStrategy propertyTypes) { var properties = new List(); if ((propertyTypes & PropertySelectionStrategy.ReadWriteOnly) != 0) @@ -57,73 +57,93 @@ private static IEnumerable GetProperties(ReflectionInfo info, properties.AddRange(info.ReadOnlyProperties); return properties; } - private static IEnumerable GetFields(ReflectionInfo info) + private static IEnumerable _GetFields(ReflectionInfo info) { var fields = new List(); fields.AddRange(info.Fields); return fields; } - private static ReflectionInfo InitializeInstanceCache(Type type) + private static ReflectionInfo _InitializeInstanceCache(Type type) { ReflectionInfo info; if (!_instanceCache.TryGetValue(type, out info)) { - var read = GetInstanceProperties(type).Where(p => !p.SetMethod.IsPublic) + var read = _GetInstanceProperties(type).Where(p => !p.SetMethod.IsPublic) .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var readWrite = GetInstanceProperties(type).Where(p => p.SetMethod.IsPublic) + .Select(_BuildSerializationInfo); + var readWrite = _GetInstanceProperties(type).Where(p => p.SetMethod.IsPublic) .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var fields = GetInstanceFields(type).Where(p => !p.IsInitOnly) + .Select(_BuildSerializationInfo); + var fields = _GetInstanceFields(type).Where(p => !p.IsInitOnly) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); + .Select(_BuildSerializationInfo); _instanceCache[type] = info = new ReflectionInfo(read, readWrite, fields); } return info; } - private static ReflectionInfo InitializeStaticCache(Type type) + private static ReflectionInfo _InitializeStaticCache(Type type) { ReflectionInfo info; if (!_staticCache.TryGetValue(type, out info)) { - var read = GetStaticProperties(type).Where(p => !p.SetMethod.IsPublic) + var read = _GetStaticProperties(type).Where(p => !p.SetMethod.IsPublic) .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var readWrite = GetStaticProperties(type).Where(p => p.SetMethod.IsPublic) + .Select(_BuildSerializationInfo); + var readWrite = _GetStaticProperties(type).Where(p => p.SetMethod.IsPublic) .Where(p => p.GetMethod.IsPublic) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var fields = GetStaticFields(type).Where(p => !p.IsInitOnly) + .Select(_BuildSerializationInfo); + var fields = _GetStaticFields(type).Where(p => !p.IsInitOnly) .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); + .Select(_BuildSerializationInfo); _staticCache[type] = info = new ReflectionInfo(read, readWrite, fields); } return info; } - private static SerializationInfo BuildSerializationInfo(MemberInfo info) + private static SerializationInfo _BuildSerializationInfo(MemberInfo info) { var mapper = (JsonMapToAttribute) info.GetCustomAttributes(typeof(JsonMapToAttribute), false).FirstOrDefault(); var name = mapper == null ? info.Name : mapper.MapToKey; return new SerializationInfo(info, name); } - private static IEnumerable GetInstanceProperties(Type type) + private static IEnumerable _GetInstanceProperties(this Type type) { - return type.TypeInfo().DeclaredProperties.Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); + return type.TypeInfo()._GetAllProperties().Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } - private static IEnumerable GetStaticProperties(Type type) + private static IEnumerable _GetStaticProperties(this Type type) { - return type.TypeInfo().DeclaredProperties.Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); + return type.TypeInfo()._GetAllProperties().Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } - private static IEnumerable GetInstanceFields(Type type) + private static IEnumerable _GetInstanceFields(this Type type) { - return type.TypeInfo().DeclaredFields.Where(f => !f.IsStatic && f.IsPublic); + return type.TypeInfo()._GetAllFields().Where(f => !f.IsStatic && f.IsPublic); } - private static IEnumerable GetStaticFields(Type type) + private static IEnumerable _GetStaticFields(this Type type) { - return type.TypeInfo().DeclaredFields.Where(f => f.IsStatic && f.IsPublic); + return type.TypeInfo()._GetAllFields().Where(f => f.IsStatic && f.IsPublic); + } + private static IEnumerable _GetAllProperties(this TypeInfo type) + { + var properties = new List(); + while (type != null) + { + properties.AddRange(type.DeclaredProperties); + type = type.BaseType?.GetTypeInfo(); + } + return properties; + } + private static IEnumerable _GetAllFields(this TypeInfo type) + { + var fields = new List(); + while (type != null) + { + fields.AddRange(type.DeclaredFields); + type = type.BaseType?.GetTypeInfo(); + } + return fields; } } } \ No newline at end of file diff --git a/Manatee.Json/UriExtensions.cs b/Manatee.Json/UriExtensions.cs index 7d12b52..2691d42 100644 --- a/Manatee.Json/UriExtensions.cs +++ b/Manatee.Json/UriExtensions.cs @@ -25,14 +25,6 @@ public static Uri GetParentUri(this Uri uri) var path = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length); return new Uri(path); - - string url = uri.ToString(); - int index = url.Length - 1; - if (url[index] == '/') - index--; - while (url[index] != '/') - index--; - return new Uri(url.Substring(0, index + 1)); } } } diff --git a/build.bat b/build.bat index 82e1e1a..eaa65f7 100644 --- a/build.bat +++ b/build.bat @@ -8,8 +8,8 @@ if "%config%" == "" ( REM Build dotnet restore -"%programfiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe" Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false +"%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe" Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false REM Package -powershell .\Manatee.Json\nuget.ps1 -nuspecfile .\Manatee.Json\project.nuspec \ No newline at end of file +"%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe" Manatee.Json.sln /t:pack /p:Configuration=Release \ No newline at end of file From 411e3f44a0547b78cf03de02a01734b5512f9a3d Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Wed, 14 Jun 2017 00:42:57 +1200 Subject: [PATCH 09/15] removed compatibility extensions --- Manatee.Json/Internal/CompatibilityExtensions.cs | 32 ------------ Manatee.Json/Internal/GeneralExtensions.cs | 23 ++++----- Manatee.Json/Parsing/JsonParser.cs | 2 +- Manatee.Json/Path/ArrayParameters/SliceQuery.cs | 2 +- .../Parsing/JsonPathExpressionParser.cs | 2 +- .../Translation/ExpressionTranslator.cs | 4 +- Manatee.Json/Path/JsonPath.cs | 2 +- Manatee.Json/Path/Operators/NameOperator.cs | 2 +- Manatee.Json/Path/Parsing/JsonPathParser.cs | 2 +- .../Path/SearchParameters/NameSearchParameter.cs | 2 +- Manatee.Json/Schema/JsonSchema.cs | 14 +++--- .../Schema/JsonSchemaPropertyDefinition.cs | 3 +- Manatee.Json/Schema/JsonSchemaReference.cs | 11 ++-- Manatee.Json/Schema/JsonSchemaRegistry.cs | 9 ++-- Manatee.Json/Schema/JsonSchemaTypeDefinition.cs | 5 +- Manatee.Json/Schema/PropertyDependency.cs | 2 +- Manatee.Json/Schema/SchemaDependency.cs | 3 +- Manatee.Json/Schema/SchemaValidationError.cs | 5 +- .../JsonSchemaPropertyValidatorFactory.cs | 2 +- .../DictionarySerializationDelegateProvider.cs | 4 +- .../ListSerializationDelegateProvider.cs | 4 +- .../NullableSerializationDelegateProvider.cs | 4 +- .../QueueSerializationDelegateProvider.cs | 4 +- .../SerializationDelegateProviderBase.cs | 4 +- .../StackSerializationDelegateProvider.cs | 4 +- .../Serialization/Internal/ConstructorResolver.cs | 4 +- .../Serialization/Internal/SerializerFactory.cs | 8 +-- .../Internal/Serializers/AutoSerializer.cs | 4 +- .../Internal/Serializers/EnumNameSerializer.cs | 4 +- .../Internal/Serializers/ReflectionCache.cs | 8 +-- .../Serialization/Internal/TemplateGenerator.cs | 6 +-- .../JsonSerializationAbstractionMap.cs | 20 ++++---- .../Serialization/JsonSerializationTypeRegistry.cs | 4 +- Manatee.Json/Transform/JsonTransformer.cs | 37 +++++++------- Manatee.Json/XmlExtensions.cs | 58 +++++++++++----------- 35 files changed, 129 insertions(+), 175 deletions(-) delete mode 100644 Manatee.Json/Internal/CompatibilityExtensions.cs diff --git a/Manatee.Json/Internal/CompatibilityExtensions.cs b/Manatee.Json/Internal/CompatibilityExtensions.cs deleted file mode 100644 index 4a49983..0000000 --- a/Manatee.Json/Internal/CompatibilityExtensions.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Manatee.Json.Internal -{ - [Obsolete] - internal static class CompatibilityExtensions - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsNullOrWhiteSpace(this string value) - { - return string.IsNullOrWhiteSpace(value); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static string Join(this IEnumerable segments, string separator) - { - return string.Join(separator, segments); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TypeInfo TypeInfo(this Type type) - { - return type.GetTypeInfo(); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Type[] GetTypeArguments(this Type type) - { - return type.GetTypeInfo().GenericTypeArguments; - } - } -} diff --git a/Manatee.Json/Internal/GeneralExtensions.cs b/Manatee.Json/Internal/GeneralExtensions.cs index c7f09d5..2b20ac1 100644 --- a/Manatee.Json/Internal/GeneralExtensions.cs +++ b/Manatee.Json/Internal/GeneralExtensions.cs @@ -3,6 +3,8 @@ using System.Globalization; using System.IO; using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; namespace Manatee.Json.Internal { @@ -185,18 +187,18 @@ public static string SkipWhiteSpace(this StreamReader stream, out char ch) public static bool InheritsFrom(this Type tDerived, Type tBase) { if (tDerived._IsSubtypeOf(tBase)) return true; - var interfaces = tDerived.TypeInfo().ImplementedInterfaces.Select(i => i.TypeInfo().IsGenericType ? i.GetGenericTypeDefinition() : i); + var interfaces = tDerived.GetTypeInfo().ImplementedInterfaces.Select(i => i.GetTypeInfo().IsGenericType ? i.GetGenericTypeDefinition() : i); return interfaces.Contains(tBase); } private static bool _IsSubtypeOf(this Type tDerived, Type tBase) { - var currentType = tDerived.TypeInfo().BaseType; + var currentType = tDerived.GetTypeInfo().BaseType; while (currentType != null) { - if (currentType.TypeInfo().IsGenericType) + if (currentType.GetTypeInfo().IsGenericType) currentType = currentType.GetGenericTypeDefinition(); if (currentType == tBase) return true; - currentType = currentType.TypeInfo().BaseType; + currentType = currentType.GetTypeInfo().BaseType; } return false; } @@ -250,17 +252,10 @@ public static bool IsNumber(this object value) value is long || value is ulong; } - public static Uri GetBase(this Uri uri) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Type[] GetTypeArguments(this Type type) { - Uri previous = uri; - do - { - uri = previous; - previous = uri.GetParentUri(); - } while (uri != previous); - - return uri; + return type.GetTypeInfo().GenericTypeArguments; } - } } \ No newline at end of file diff --git a/Manatee.Json/Parsing/JsonParser.cs b/Manatee.Json/Parsing/JsonParser.cs index 92f4590..8cca3b3 100644 --- a/Manatee.Json/Parsing/JsonParser.cs +++ b/Manatee.Json/Parsing/JsonParser.cs @@ -13,7 +13,7 @@ internal static class JsonParser static JsonParser() { - Parsers = typeof(JsonParser).TypeInfo().Assembly.DefinedTypes + Parsers = typeof(JsonParser).GetTypeInfo().Assembly.DefinedTypes .Where(t => typeof(IJsonParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() diff --git a/Manatee.Json/Path/ArrayParameters/SliceQuery.cs b/Manatee.Json/Path/ArrayParameters/SliceQuery.cs index be2a817..fccaf3a 100644 --- a/Manatee.Json/Path/ArrayParameters/SliceQuery.cs +++ b/Manatee.Json/Path/ArrayParameters/SliceQuery.cs @@ -21,7 +21,7 @@ public IEnumerable Find(JsonArray json, JsonValue root) } public override string ToString() { - return Slices.Join(","); + return string.Join(",", Slices); } public bool Equals(SliceQuery other) { diff --git a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs index 8ed1be5..871aa33 100644 --- a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs +++ b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs @@ -12,7 +12,7 @@ internal static class JsonPathExpressionParser static JsonPathExpressionParser() { - Parsers = typeof(JsonPathExpressionParser).TypeInfo().Assembly.DefinedTypes + Parsers = typeof(JsonPathExpressionParser).GetTypeInfo().Assembly.DefinedTypes .Where(t => typeof(IJsonPathExpressionParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() diff --git a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs index f43f9ba..ca1ac4b 100644 --- a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs @@ -176,8 +176,8 @@ private static IExpressionTranslator GetMemberTranslator(Expression exp) public static ExpressionTreeNode TranslateNode(Expression source) { var type = source.GetType(); - // TODO: optimize - var expressionKey = Translators.Keys.FirstOrDefault(t => t.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())); + var typeInfo = type.GetTypeInfo(); + var expressionKey = Translators.Keys.FirstOrDefault(t => t.GetTypeInfo().IsAssignableFrom(typeInfo)); if (expressionKey != null) { var translator = Translators[expressionKey](source); diff --git a/Manatee.Json/Path/JsonPath.cs b/Manatee.Json/Path/JsonPath.cs index 8f985d3..79fb183 100644 --- a/Manatee.Json/Path/JsonPath.cs +++ b/Manatee.Json/Path/JsonPath.cs @@ -74,7 +74,7 @@ public override int GetHashCode() internal string GetRawString() { - return Operators.Select(o => o.ToString()).Join(string.Empty); + return string.Join(string.Empty, Operators.Select(o => o.ToString())); } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Operators/NameOperator.cs b/Manatee.Json/Path/Operators/NameOperator.cs index 7c5269a..9c2a64d 100644 --- a/Manatee.Json/Path/Operators/NameOperator.cs +++ b/Manatee.Json/Path/Operators/NameOperator.cs @@ -21,7 +21,7 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) } public override string ToString() { - return Name.Cast().Any(c => !char.IsLetterOrDigit(c)) || Name.IsNullOrWhiteSpace() + return Name.Any(c => !char.IsLetterOrDigit(c)) || string.IsNullOrWhiteSpace(Name) ? $".'{Name}'" : $".{Name}"; } diff --git a/Manatee.Json/Path/Parsing/JsonPathParser.cs b/Manatee.Json/Path/Parsing/JsonPathParser.cs index 6f61994..f1759c7 100644 --- a/Manatee.Json/Path/Parsing/JsonPathParser.cs +++ b/Manatee.Json/Path/Parsing/JsonPathParser.cs @@ -12,7 +12,7 @@ internal static class JsonPathParser static JsonPathParser() { - Parsers = typeof(JsonPathParser).TypeInfo().Assembly.DefinedTypes + Parsers = typeof(JsonPathParser).GetTypeInfo().Assembly.DefinedTypes .Where(t => typeof(IJsonPathParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() diff --git a/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs b/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs index d190cfe..358442d 100644 --- a/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs +++ b/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs @@ -35,7 +35,7 @@ public IEnumerable Find(IEnumerable json, JsonValue root) } public override string ToString() { - return _name.Cast().Any(c => !char.IsLetterOrDigit(c)) || _name.IsNullOrWhiteSpace() + return _name.Any(c => !char.IsLetterOrDigit(c)) || string.IsNullOrWhiteSpace(_name) ? $"'{_name}'" : _name; } diff --git a/Manatee.Json/Schema/JsonSchema.cs b/Manatee.Json/Schema/JsonSchema.cs index 986ef95..67daabc 100644 --- a/Manatee.Json/Schema/JsonSchema.cs +++ b/Manatee.Json/Schema/JsonSchema.cs @@ -360,7 +360,7 @@ public string Id get { return _id; } set { - if (!value.IsNullOrWhiteSpace() && !StringFormat.Uri.Validate(value)) + if (!string.IsNullOrWhiteSpace(value) && !StringFormat.Uri.Validate(value)) throw new ArgumentOutOfRangeException(nameof(Id), "'id' property must be a well-formed URI."); _id = value; } @@ -376,7 +376,7 @@ public string Schema get { return _schema; } set { - if (!value.IsNullOrWhiteSpace() && !StringFormat.Uri.Validate(value)) + if (!string.IsNullOrWhiteSpace(value) && !StringFormat.Uri.Validate(value)) throw new ArgumentOutOfRangeException(nameof(Schema), "'$schema' property must be a well-formed URI."); _schema = value; } @@ -548,7 +548,7 @@ public virtual void FromJson(JsonValue json, JsonSerializer serializer) Id = obj.TryGetString("id"); Uri uri; var uriFolder = DocumentPath?.OriginalString.EndsWith("/") ?? true ? DocumentPath : DocumentPath?.GetParentUri(); - if (!Id.IsNullOrWhiteSpace() && + if (!string.IsNullOrWhiteSpace(Id) && (Uri.TryCreate(Id, UriKind.Absolute, out uri) || Uri.TryCreate(uriFolder + Id, UriKind.Absolute, out uri))) { DocumentPath = uri; @@ -661,7 +661,7 @@ public virtual void FromJson(JsonValue json, JsonSerializer serializer) { case JsonValueType.String: // string implies primitive type - Type = GetPrimitiveDefinition(typeEntry.String); + Type = _GetPrimitiveDefinition(typeEntry.String); break; case JsonValueType.Array: // array implies "oneOf" several primitive types @@ -699,9 +699,9 @@ public virtual JsonValue ToJson(JsonSerializer serializer) requiredProperties = Properties.Where(p => p.IsRequired).Select(p => p.Name).ToList(); var json = new JsonObject(); if (Id != null) json["id"] = Id; - if (!Schema.IsNullOrWhiteSpace()) json["$schema"] = Schema; + if (!string.IsNullOrWhiteSpace(Schema)) json["$schema"] = Schema; if (Title != null) json["title"] = Title; - if (!Description.IsNullOrWhiteSpace()) json["description"] = Description; + if (!string.IsNullOrWhiteSpace(Description)) json["description"] = Description; if (Default != null) json["default"] = Default; if (MultipleOf.HasValue) json["multipleOf"] = MultipleOf; if (Maximum.HasValue) json["maximum"] = Maximum; @@ -865,7 +865,7 @@ public override int GetHashCode() } } - private static JsonSchemaTypeDefinition GetPrimitiveDefinition(string type) + private static JsonSchemaTypeDefinition _GetPrimitiveDefinition(string type) { switch (type) { diff --git a/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs b/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs index 68750e8..ba72123 100644 --- a/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using Manatee.Json.Internal; using Manatee.Json.Serialization; namespace Manatee.Json.Schema @@ -35,7 +34,7 @@ public class JsonSchemaPropertyDefinition : IJsonSerializable, IEquatableThrown if is null, empty, or whitespace. public JsonSchemaPropertyDefinition(string name) { - if (name.IsNullOrWhiteSpace()) + if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); Name = name; diff --git a/Manatee.Json/Schema/JsonSchemaReference.cs b/Manatee.Json/Schema/JsonSchemaReference.cs index 4a6cb34..34f023f 100644 --- a/Manatee.Json/Schema/JsonSchemaReference.cs +++ b/Manatee.Json/Schema/JsonSchemaReference.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; -using Manatee.Json.Internal; -using Manatee.Json.Path; using Manatee.Json.Serialization; namespace Manatee.Json.Schema @@ -42,7 +39,7 @@ public class JsonSchemaReference : JsonSchema /// Thrown when is nulll, empty, or whitespace. public JsonSchemaReference(string reference) { - if (reference.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(reference)); + if (string.IsNullOrWhiteSpace(reference)) throw new ArgumentNullException(nameof(reference)); Reference = reference; } /// @@ -111,10 +108,10 @@ public override int GetHashCode() private JsonValue _Resolve(JsonValue root) { var referenceParts = Reference.Split(new[] { '#' }, StringSplitOptions.None); - var address = referenceParts[0].IsNullOrWhiteSpace() ? DocumentPath?.OriginalString : referenceParts[0]; + var address = string.IsNullOrWhiteSpace(referenceParts[0]) ? DocumentPath?.OriginalString : referenceParts[0]; var fragment = referenceParts.Length > 1 ? referenceParts[1] : string.Empty; var jValue = root; - if (!address.IsNullOrWhiteSpace()) + if (!string.IsNullOrWhiteSpace(address)) { Uri absolute; if (!Uri.TryCreate(address, UriKind.Absolute, out absolute)) @@ -132,7 +129,7 @@ private JsonValue _Resolve(JsonValue root) if (jValue == null) return root; if (jValue == _rootJson) throw new ArgumentException("Cannot use a root reference as the base schema."); - Resolved = _ResolveLocalReference(jValue, fragment, address.IsNullOrWhiteSpace() ? null : new Uri(address)); + Resolved = _ResolveLocalReference(jValue, fragment, string.IsNullOrWhiteSpace(address) ? null : new Uri(address)); return jValue; } private static IJsonSchema _ResolveLocalReference(JsonValue root, string path, Uri documentPath) diff --git a/Manatee.Json/Schema/JsonSchemaRegistry.cs b/Manatee.Json/Schema/JsonSchemaRegistry.cs index c8807dd..ea85232 100644 --- a/Manatee.Json/Schema/JsonSchemaRegistry.cs +++ b/Manatee.Json/Schema/JsonSchemaRegistry.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -43,7 +42,7 @@ public static IJsonSchema Get(string uri) if (!validation.Valid) { - var errors = validation.Errors.Select(e => e.Message).Join(Environment.NewLine); + var errors = string.Join(Environment.NewLine, validation.Errors.Select(e => e.Message)); throw new ArgumentException($"The given path does not contain a valid schema. Errors: \n{errors}"); } @@ -59,7 +58,7 @@ public static IJsonSchema Get(string uri) /// public static void Register(JsonSchema schema) { - if (schema.Id.IsNullOrWhiteSpace()) return; + if (string.IsNullOrWhiteSpace(schema.Id)) return; lock (_schemaLookup) { _schemaLookup[schema.DocumentPath.ToString()] = schema; @@ -71,7 +70,7 @@ public static void Register(JsonSchema schema) /// public static void Unregister(JsonSchema schema) { - if (schema.Id.IsNullOrWhiteSpace()) return; + if (string.IsNullOrWhiteSpace(schema.Id)) return; lock (_schemaLookup) { _schemaLookup.Remove(schema.Id); @@ -83,7 +82,7 @@ public static void Unregister(JsonSchema schema) /// public static void Unregister(string uri) { - if (uri.IsNullOrWhiteSpace()) return; + if (string.IsNullOrWhiteSpace(uri)) return; lock (_schemaLookup) { _schemaLookup.Remove(uri); diff --git a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs index 3b0fd37..f4c761a 100644 --- a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs @@ -98,8 +98,7 @@ static JsonSchemaTypeDefinition() /// Thrown if is null, empty, or whitespace. public JsonSchemaTypeDefinition(string name) { - if (name.IsNullOrWhiteSpace()) - throw new ArgumentNullException(nameof(name)); + if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); Name = name; } @@ -133,7 +132,7 @@ public virtual void FromJson(JsonValue json, JsonSerializer serializer) /// 2 public override string ToString() { - if (!Name.IsNullOrWhiteSpace()) return Name; + if (!string.IsNullOrWhiteSpace(Name)) return Name; return ToJson(null).ToString(); } diff --git a/Manatee.Json/Schema/PropertyDependency.cs b/Manatee.Json/Schema/PropertyDependency.cs index db6dc05..a905af6 100644 --- a/Manatee.Json/Schema/PropertyDependency.cs +++ b/Manatee.Json/Schema/PropertyDependency.cs @@ -25,7 +25,7 @@ public class PropertyDependency : IJsonSchemaDependency public PropertyDependency(string propertyName, IEnumerable dependencies) { if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); - if (propertyName.IsNullOrWhiteSpace()) throw new ArgumentException("Must provide a property name."); + if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentException("Must provide a property name."); if (dependencies == null) throw new ArgumentNullException(nameof(dependencies)); if (!dependencies.Any()) throw new ArgumentException("Cannot create property dependency on no properties."); diff --git a/Manatee.Json/Schema/SchemaDependency.cs b/Manatee.Json/Schema/SchemaDependency.cs index 036fe71..6b453c3 100644 --- a/Manatee.Json/Schema/SchemaDependency.cs +++ b/Manatee.Json/Schema/SchemaDependency.cs @@ -1,5 +1,4 @@ using System; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -24,7 +23,7 @@ public SchemaDependency(string propertyName, IJsonSchema schema) { _schema = schema; if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); - if (propertyName.IsNullOrWhiteSpace()) throw new ArgumentException("Must provide a property name."); + if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentException("Must provide a property name."); PropertyName = propertyName; } diff --git a/Manatee.Json/Schema/SchemaValidationError.cs b/Manatee.Json/Schema/SchemaValidationError.cs index d24940b..f115112 100644 --- a/Manatee.Json/Schema/SchemaValidationError.cs +++ b/Manatee.Json/Schema/SchemaValidationError.cs @@ -1,5 +1,4 @@ using System; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -25,7 +24,7 @@ internal SchemaValidationError(string propertyName, string message) internal SchemaValidationError PrependPropertyName(string parent) { - if (PropertyName.IsNullOrWhiteSpace()) + if (string.IsNullOrWhiteSpace(PropertyName)) PropertyName = parent; else PropertyName = parent + (PropertyName[0] == '[' ? string.Empty : ".") + PropertyName; @@ -41,7 +40,7 @@ internal SchemaValidationError PrependPropertyName(string parent) /// 2 public override string ToString() { - return PropertyName.IsNullOrWhiteSpace() + return string.IsNullOrWhiteSpace(PropertyName) ? Message : $"Property: {PropertyName} - {Message}"; } diff --git a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs index 80792e0..6d41d79 100644 --- a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs +++ b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs @@ -12,7 +12,7 @@ internal static class JsonSchemaPropertyValidatorFactory static JsonSchemaPropertyValidatorFactory() { - AllValidators = typeof(IJsonSchemaPropertyValidator).TypeInfo().Assembly.DefinedTypes + AllValidators = typeof(IJsonSchemaPropertyValidator).GetTypeInfo().Assembly.DefinedTypes .Where(t => typeof(IJsonSchemaPropertyValidator).GetTypeInfo().IsAssignableFrom(t) && !t.IsAbstract && t.IsClass) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs index b24744c..13c7aa0 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,7 +9,7 @@ internal class DictionarySerializationDelegateProvider : SerializationDelegatePr { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>); } private static JsonValue Encode(Dictionary dict, JsonSerializer serializer) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs index 7be61a6..fc30086 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,7 +9,7 @@ internal class ListSerializationDelegateProvider : SerializationDelegateProvider { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); } private static JsonValue Encode(List list, JsonSerializer serializer) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs index 1cd3ec2..3b8bbc4 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs @@ -1,5 +1,5 @@ using System; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -7,7 +7,7 @@ internal class NullableSerializationDelegateProvider : SerializationDelegateProv { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } private static JsonValue Encode(T? nullable, JsonSerializer serializer) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs index 18ca92a..34db6d2 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,7 +9,7 @@ internal class QueueSerializationDelegateProvider : SerializationDelegateProvide { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Queue<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Queue<>); } private static JsonValue Encode(Queue queue, JsonSerializer serializer) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs index 4e413f2..5b79b67 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs @@ -11,8 +11,8 @@ internal abstract class SerializationDelegateProviderBase : ISerializationDelega protected SerializationDelegateProviderBase() { - _encodeMethod = GetType().TypeInfo().GetDeclaredMethod("Encode"); - _decodeMethod = GetType().TypeInfo().GetDeclaredMethod("Decode"); + _encodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("Encode"); + _decodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("Decode"); } public abstract bool CanHandle(Type type); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs index dfabab3..2eda461 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,7 +9,7 @@ internal class StackSerializationDelegateProvider : SerializationDelegateProvide { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); } private static JsonValue Encode(Stack stack, JsonSerializer serializer) diff --git a/Manatee.Json/Serialization/Internal/ConstructorResolver.cs b/Manatee.Json/Serialization/Internal/ConstructorResolver.cs index 9abe562..fe2fea0 100644 --- a/Manatee.Json/Serialization/Internal/ConstructorResolver.cs +++ b/Manatee.Json/Serialization/Internal/ConstructorResolver.cs @@ -1,6 +1,6 @@ using System; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal { @@ -14,7 +14,7 @@ public object Resolve(Type type) { try { - var constructors = type.TypeInfo().DeclaredConstructors.ToList(); + var constructors = type.GetTypeInfo().DeclaredConstructors.ToList(); if (!constructors.Any()) return Activator.CreateInstance(type); var parameterless = constructors.FirstOrDefault(c => !c.GetParameters().Any()); diff --git a/Manatee.Json/Serialization/Internal/SerializerFactory.cs b/Manatee.Json/Serialization/Internal/SerializerFactory.cs index c105d97..b128c8a 100644 --- a/Manatee.Json/Serialization/Internal/SerializerFactory.cs +++ b/Manatee.Json/Serialization/Internal/SerializerFactory.cs @@ -54,14 +54,14 @@ public static ISerializer GetSerializer(JsonSerializerOptions options, JsonVa { var type = typeof (T); var typeToSerialize = JsonSerializationAbstractionMap.GetMap(type); - // TODO: optimize - if (typeof (IJsonSchema).GetTypeInfo().IsAssignableFrom(typeToSerialize.GetTypeInfo())) + var typeInfo = typeToSerialize.GetTypeInfo(); + if (typeof (IJsonSchema).GetTypeInfo().IsAssignableFrom(typeInfo)) return BuildSerializer(_schemaSerializer); if (JsonSerializationTypeRegistry.IsRegistered(typeToSerialize)) return BuildSerializer(_registeredObjectSerializer); - if (typeof (IJsonSerializable).GetTypeInfo().IsAssignableFrom(typeToSerialize.GetTypeInfo())) + if (typeof (IJsonSerializable).GetTypeInfo().IsAssignableFrom(typeInfo)) return BuildSerializer(_jsonSerializableSerializer); - if (typeof (Enum).GetTypeInfo().IsAssignableFrom(typeToSerialize.GetTypeInfo())) + if (typeof (Enum).GetTypeInfo().IsAssignableFrom(typeInfo)) { if (json != null) { diff --git a/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs index 872754b..c0de1af 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs @@ -15,7 +15,7 @@ public JsonValue Serialize(T obj, JsonSerializer serializer) var json = new JsonObject(); var type = typeof (T); if ((serializer.Options.TypeNameSerializationBehavior != TypeNameSerializationBehavior.Never) && - (type.TypeInfo().IsAbstract || type.TypeInfo().IsInterface || (serializer.Options.TypeNameSerializationBehavior == TypeNameSerializationBehavior.Always))) + (type.GetTypeInfo().IsAbstract || type.GetTypeInfo().IsInterface || (serializer.Options.TypeNameSerializationBehavior == TypeNameSerializationBehavior.Always))) { type = obj.GetType(); json.Add(Constants.TypeKey, type.AssemblyQualifiedName); @@ -231,7 +231,7 @@ private static Type GetElementType(Type collectionType) { if (collectionType.IsArray) return collectionType.GetElementType(); - if (collectionType.TypeInfo().IsGenericType && collectionType.GetGenericTypeDefinition().InheritsFrom(typeof(IEnumerable<>))) + if (collectionType.GetTypeInfo().IsGenericType && collectionType.GetGenericTypeDefinition().InheritsFrom(typeof(IEnumerable<>))) return collectionType.GetTypeArguments().First(); return typeof (object); } diff --git a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs index e518419..81166c7 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs @@ -22,7 +22,7 @@ private class Description public JsonValue Serialize(T obj, JsonSerializer serializer) { EnsureDescriptions(); - var attributes = typeof (T).TypeInfo().GetCustomAttributes(typeof (FlagsAttribute), false); + var attributes = typeof (T).GetTypeInfo().GetCustomAttributes(typeof (FlagsAttribute), false); if (!attributes.Any()) { var entry = _descriptions[typeof (T)].FirstOrDefault(d => Equals(d.Value, obj)); @@ -79,7 +79,7 @@ private static string BuildFlagsValues(T obj, string separator) } index--; } - return names.Join(separator); + return string.Join(separator, names); } } } \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index 2c07d9f..9058a67 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -111,19 +111,19 @@ private static SerializationInfo _BuildSerializationInfo(MemberInfo info) } private static IEnumerable _GetInstanceProperties(this Type type) { - return type.TypeInfo()._GetAllProperties().Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); + return type.GetTypeInfo()._GetAllProperties().Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } private static IEnumerable _GetStaticProperties(this Type type) { - return type.TypeInfo()._GetAllProperties().Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); + return type.GetTypeInfo()._GetAllProperties().Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } private static IEnumerable _GetInstanceFields(this Type type) { - return type.TypeInfo()._GetAllFields().Where(f => !f.IsStatic && f.IsPublic); + return type.GetTypeInfo()._GetAllFields().Where(f => !f.IsStatic && f.IsPublic); } private static IEnumerable _GetStaticFields(this Type type) { - return type.TypeInfo()._GetAllFields().Where(f => f.IsStatic && f.IsPublic); + return type.GetTypeInfo()._GetAllFields().Where(f => f.IsStatic && f.IsPublic); } private static IEnumerable _GetAllProperties(this TypeInfo type) { diff --git a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs index d7c1f7c..9ef98fa 100644 --- a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs @@ -55,7 +55,7 @@ private static T BuildInstance(JsonSerializerOptions options) _generatedTypes.Add(type); T instance; - if (type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { var valueType = type.GetTypeArguments().First(); var buildMethod = GetBuildMethod(valueType); @@ -78,7 +78,7 @@ private static void FillProperties(T instance, JsonSerializerOptions options) { var type = typeof (T); - var properties = type.TypeInfo().DeclaredProperties + var properties = type.GetTypeInfo().DeclaredProperties .Where(p => p.SetMethod != null) .Where(p => p.GetMethod != null) .Where(p => !p.GetCustomAttributes(typeof (JsonIgnoreAttribute), true).Any()); @@ -93,7 +93,7 @@ private static void FillProperties(T instance, JsonSerializerOptions options) } private static void FillFields(T instance, JsonSerializerOptions options) { - var fields = typeof (T).TypeInfo().DeclaredFields + var fields = typeof (T).GetTypeInfo().DeclaredFields .Where(p => !p.IsInitOnly) .Where(p => !p.GetCustomAttributes(typeof (JsonIgnoreAttribute), true).Any()); foreach (var fieldInfo in fields) diff --git a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs index 2d2399d..0005562 100644 --- a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs +++ b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs @@ -31,7 +31,7 @@ static JsonSerializationAbstractionMap() public static void Map(MapBaseAbstractionBehavior mappingBehavior = MapBaseAbstractionBehavior.Unmapped) where TConcrete : TAbstract, new() { - if (typeof(TConcrete).TypeInfo().IsAbstract || typeof(TConcrete).TypeInfo().IsInterface) + if (typeof(TConcrete).GetTypeInfo().IsAbstract || typeof(TConcrete).GetTypeInfo().IsInterface) throw new JsonTypeMapException(); var tAbstract = typeof (TAbstract); var tConcrete = typeof (TConcrete); @@ -48,7 +48,7 @@ static JsonSerializationAbstractionMap() /// from . public static void MapGeneric(Type tAbstract, Type tConcrete, MapBaseAbstractionBehavior mappingBehavior = MapBaseAbstractionBehavior.Unmapped) { - if (tConcrete.TypeInfo().IsAbstract || tConcrete.TypeInfo().IsInterface) + if (tConcrete.GetTypeInfo().IsAbstract || tConcrete.GetTypeInfo().IsInterface) throw new JsonTypeMapException(tAbstract, tConcrete); if (!tConcrete.InheritsFrom(tAbstract)) throw new JsonTypeMapException(tAbstract, tConcrete); @@ -81,14 +81,14 @@ public static void RemoveMap(bool removeRelated = true) /// The mapped type if a mapping exists; otherwise the abstraction type. public static Type GetMap(Type type) { - if (!type.TypeInfo().IsAbstract && !type.TypeInfo().IsInterface) return type; + if (!type.GetTypeInfo().IsAbstract && !type.GetTypeInfo().IsInterface) return type; Type tConcrete; if (_registry.TryGetValue(type, out tConcrete)) return tConcrete; - if (type.TypeInfo().IsGenericType) + if (type.GetTypeInfo().IsGenericType) { var genericDefinition = type.GetGenericTypeDefinition(); - var genericMatches = _registry.Where(t => t.Key.TypeInfo().IsGenericTypeDefinition && t.Key.GetGenericTypeDefinition() == genericDefinition).ToList(); + var genericMatches = _registry.Where(t => t.Key.GetTypeInfo().IsGenericTypeDefinition && t.Key.GetGenericTypeDefinition() == genericDefinition).ToList(); if (genericMatches.Any()) { var typeArguments = type.GetTypeArguments(); @@ -101,7 +101,7 @@ public static Type GetMap(Type type) internal static T CreateInstance(JsonValue json, IResolver resolver) { var type = typeof (T); - if (type.TypeInfo().IsAbstract || type.TypeInfo().IsInterface || type.TypeInfo().IsGenericType) + if (type.GetTypeInfo().IsAbstract || type.GetTypeInfo().IsInterface || type.GetTypeInfo().IsGenericType) { if ((json != null) && (json.Type == JsonValueType.Object) && (json.Object.ContainsKey(Constants.TypeKey))) { @@ -111,14 +111,14 @@ internal static T CreateInstance(JsonValue json, IResolver resolver) Type tConcrete; if (!_registry.TryGetValue(type, out tConcrete)) { - if (type.TypeInfo().IsGenericType) + if (type.GetTypeInfo().IsGenericType) type = type.GetGenericTypeDefinition(); _registry.TryGetValue(type, out tConcrete); } if (tConcrete != null) { - if (tConcrete.TypeInfo().IsGenericTypeDefinition) + if (tConcrete.GetTypeInfo().IsGenericTypeDefinition) tConcrete = tConcrete.MakeGenericType(typeof(T).GetTypeArguments()); return (T) resolver.Resolve(tConcrete); } @@ -147,13 +147,13 @@ private static void MapTypes(Type tAbstract, Type tConcrete, MapBaseAbstractionB private static void MapBaseTypes(Type tAbstract, Type tConcrete, bool overwrite) { if (tAbstract == null) return; - var tBase = tAbstract.TypeInfo().BaseType; + var tBase = tAbstract.GetTypeInfo().BaseType; if ((tBase != null) && (overwrite || !_registry.ContainsKey(tBase))) { _registry[tBase] = tConcrete; } MapBaseTypes(tBase, tConcrete, overwrite); - foreach (var tInterface in tAbstract.TypeInfo().ImplementedInterfaces) + foreach (var tInterface in tAbstract.GetTypeInfo().ImplementedInterfaces) { if (overwrite || !_registry.ContainsKey(tInterface)) { diff --git a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs index 66edb40..498b07e 100644 --- a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs +++ b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs @@ -39,7 +39,7 @@ public static class JsonSerializationTypeRegistry static JsonSerializationTypeRegistry() { - _delegateProviders = typeof(JsonSerializationTypeRegistry).TypeInfo().Assembly.DefinedTypes + _delegateProviders = typeof(JsonSerializationTypeRegistry).GetTypeInfo().Assembly.DefinedTypes .Where(t => typeof(ISerializationDelegateProvider).GetTypeInfo().IsAssignableFrom(t) && !t.IsAbstract && t.IsClass) @@ -91,7 +91,7 @@ public static bool IsRegistered() public static bool IsRegistered(Type type) { if (_toJsonConverters.ContainsKey(type)) return true; - if (type.TypeInfo().IsGenericTypeDefinition) return false; + if (type.GetTypeInfo().IsGenericTypeDefinition) return false; var delegateProvider = _delegateProviders.FirstOrDefault(p => p.CanHandle(type)); if (delegateProvider == null) return false; diff --git a/Manatee.Json/Transform/JsonTransformer.cs b/Manatee.Json/Transform/JsonTransformer.cs index e493b52..7719c25 100644 --- a/Manatee.Json/Transform/JsonTransformer.cs +++ b/Manatee.Json/Transform/JsonTransformer.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using Manatee.Json.Internal; using Manatee.Json.Path; namespace Manatee.Json.Transform @@ -18,10 +17,10 @@ public static class JsonTransformer /// The transformed JSON. public static JsonValue Transform(this JsonValue source, JsonValue template) { - return Transform(source, source, template, -1); + return _Transform(source, source, template, -1); } - private static JsonValue Transform(this JsonValue source, JsonValue localSource, JsonValue template, int index) + private static JsonValue _Transform(this JsonValue source, JsonValue localSource, JsonValue template, int index) { switch (template.Type) { @@ -30,51 +29,51 @@ private static JsonValue Transform(this JsonValue source, JsonValue localSource, case JsonValueType.Null: return template; case JsonValueType.String: - return TransformString(source, localSource, template.String, index); + return _TransformString(source, localSource, template.String, index); case JsonValueType.Object: - return TransformObject(source, localSource, template.Object, index); + return _TransformObject(source, localSource, template.Object, index); case JsonValueType.Array: - return TransformArray(source, localSource, template.Array, index); + return _TransformArray(source, localSource, template.Array, index); default: throw new ArgumentOutOfRangeException(); } } - private static JsonValue TransformObject(JsonValue source, JsonValue localSource, JsonObject template, int index) + private static JsonValue _TransformObject(JsonValue source, JsonValue localSource, JsonObject template, int index) { var obj = new JsonObject(); foreach (var property in template) { - obj[property.Key] = Transform(source, localSource, property.Value, index); + obj[property.Key] = _Transform(source, localSource, property.Value, index); } return obj; } - private static JsonValue TransformArray(JsonValue source, JsonValue localSource, JsonArray template, int index) + private static JsonValue _TransformArray(JsonValue source, JsonValue localSource, JsonArray template, int index) { if (template.Count != 2 || template[0].Type != JsonValueType.String) - return TransformArrayElements(source, localSource, template, index); - var path = TryGetPath(template[0].String); + return _TransformArrayElements(source, localSource, template, index); + var path = _TryGetPath(template[0].String); if (path == null) - return TransformArrayElements(source, localSource, template, index); + return _TransformArrayElements(source, localSource, template, index); var items = path.Evaluate(source); - return new JsonArray(items.Select((item, i) => Transform(source, item, template[1], i))); + return new JsonArray(items.Select((item, i) => _Transform(source, item, template[1], i))); } - private static JsonValue TransformArrayElements(JsonValue source, JsonValue localSource, JsonArray array, int index) + private static JsonValue _TransformArrayElements(JsonValue source, JsonValue localSource, JsonArray array, int index) { - return new JsonArray(array.Select(jv => Transform(source, localSource, jv, index))); + return new JsonArray(array.Select(jv => _Transform(source, localSource, jv, index))); } - private static JsonValue TransformString(JsonValue source, JsonValue localSource, string template, int index) + private static JsonValue _TransformString(JsonValue source, JsonValue localSource, string template, int index) { - var path = TryGetPath(template); + var path = _TryGetPath(template); if (path == null) return template; var pathIsLocal = template[0] == '@'; var items = path.Evaluate(pathIsLocal ? localSource : source); return items.Count == 1 ? items[0] : (index == -1 ? items : items[index]); } - private static JsonPath TryGetPath(string text) + private static JsonPath _TryGetPath(string text) { - if (text.IsNullOrWhiteSpace()) return null; + if (string.IsNullOrWhiteSpace(text)) return null; if (text[0] == '@') text = "$" + text.Substring(1); try diff --git a/Manatee.Json/XmlExtensions.cs b/Manatee.Json/XmlExtensions.cs index 2183d82..7355603 100644 --- a/Manatee.Json/XmlExtensions.cs +++ b/Manatee.Json/XmlExtensions.cs @@ -32,9 +32,9 @@ public static class XmlExtensions /// and is not a non-empty . public static XElement ToXElement(this JsonValue json, string key) { - if (key.IsNullOrWhiteSpace() && (json.Type != JsonValueType.Object)) + if (string.IsNullOrWhiteSpace(key) && json.Type != JsonValueType.Object) throw new ArgumentException(EncodingWithoutKeyError); - var name = GetXName(key); + var name = _GetXName(key); XElement xml; switch (json.Type) { @@ -42,7 +42,7 @@ public static XElement ToXElement(this JsonValue json, string key) return new XElement(name, json.Number); case JsonValueType.String: xml = new XElement(name, json.String); - if (RequiresTypeAttribute(json.String)) + if (_RequiresTypeAttribute(json.String)) xml.SetAttributeValue(TypeAttribute, "String"); return xml; case JsonValueType.Boolean: @@ -59,20 +59,20 @@ public static XElement ToXElement(this JsonValue json, string key) foreach (var kvp in json.Object) { var element = kvp.Value.ToXElement(kvp.Key); - if ((kvp.Value.Type == JsonValueType.Array) && !ContainsAttributeList(kvp.Value.Array)) + if ((kvp.Value.Type == JsonValueType.Array) && !_ContainsAttributeList(kvp.Value.Array)) xml.Add(element.Elements()); else xml.Add(element); } return xml; case JsonValueType.Array: - if (ContainsAttributeList(json.Array)) + if (_ContainsAttributeList(json.Array)) { var attributeNames = json.Array[0].Object; var attributes = new List(); foreach(var attributeName in attributeNames) { - var localName = GetXName(attributeName.Key.Substring(1)); + var localName = _GetXName(attributeName.Key.Substring(1)); var attribute = new XAttribute(localName, attributeName.Value.ToXElement(key).Value); if (attribute.IsNamespaceDeclaration) XmlNamespaceRegistry.Instance.Register(attribute.Name.LocalName,attribute.Value); @@ -129,7 +129,7 @@ public static XElement ToXElement(this JsonValue json, string key) /// The representation of the . public static JsonValue ToJson(this XElement xElement) { - return new JsonObject {{GetNamespaceForElement(xElement) + xElement.Name.LocalName, GetValue(xElement)}}; + return new JsonObject {{_GetNamespaceForElement(xElement) + xElement.Name.LocalName, _GetValue(xElement)}}; } /// /// Converts an to a . @@ -143,15 +143,15 @@ public static JsonValue ToJson(this IEnumerable xElements) foreach (var xElement in xElements) { XmlNamespaceRegistry.Instance.RegisterElement(xElement); - var name = GetNamespaceForElement(xElement) + xElement.Name.LocalName; - var newValue = GetValue(xElement); + var name = _GetNamespaceForElement(xElement) + xElement.Name.LocalName; + var newValue = _GetValue(xElement); if (json.ContainsKey(name)) { var item = json[name]; var nestAttribute = xElement.Attribute(NestAttribute); - if ((nestAttribute != null) && (nestAttribute.Value.ToLower() == "true")) + if (nestAttribute != null && nestAttribute.Value.ToLower() == "true") { - if ((newValue.Object.Count > 1) || ((newValue.Object.Count != 0) && (newValue.Object.Keys.ElementAt(0) != name))) + if (newValue.Object.Count > 1 || newValue.Object.Count != 0 && newValue.Object.Keys.ElementAt(0) != name) throw new XmlException(DecodingNestedArrayWithMismatchedKeysError); newValue = newValue.Object[name].Type == JsonValueType.Array ? newValue.Object[name] @@ -171,40 +171,40 @@ public static JsonValue ToJson(this IEnumerable xElements) return json; } - private static bool RequiresTypeAttribute(string value) + private static bool _RequiresTypeAttribute(string value) { double d; var s = value.ToLower(); - return (s == "true") || (s == "false") || (s == "null") || double.TryParse(s, out d); + return s == "true" || s == "false" || s == "null" || double.TryParse(s, out d); } - private static JsonValue GetValue(XElement xElement) + private static JsonValue _GetValue(XElement xElement) { var typeAttribute = xElement.Attribute(TypeAttribute); if (xElement.HasElements) - return AttachAttributes(xElement.Elements().ToJson(), xElement); - if (string.IsNullOrEmpty(xElement.Value) && (typeAttribute == null)) - return AttachAttributes(JsonValue.Null, xElement); + return _AttachAttributes(xElement.Elements().ToJson(), xElement); + if (string.IsNullOrEmpty(xElement.Value) && typeAttribute == null) + return _AttachAttributes(JsonValue.Null, xElement); var value = xElement.Value; - if ((typeAttribute != null) && (typeAttribute.Value.ToLower() == "string")) - return AttachAttributes(value, xElement); - return AttachAttributes(ParseValue(value), xElement); + if (typeAttribute != null && typeAttribute.Value.ToLower() == "string") + return _AttachAttributes(value, xElement); + return _AttachAttributes(_ParseValue(value), xElement); } - private static JsonValue AttachAttributes(JsonValue json, XElement xElement) + private static JsonValue _AttachAttributes(JsonValue json, XElement xElement) { - var attributes = xElement.Attributes().Where(a => (a.Name != NestAttribute) && (a.Name != TypeAttribute)).ToList(); + var attributes = xElement.Attributes().Where(a => (a.Name != NestAttribute) && a.Name != TypeAttribute).ToList(); if (attributes.Count == 0) return json; var obj = new JsonObject(); foreach (var xAttribute in attributes) { - var name = xAttribute.IsNamespaceDeclaration && (xAttribute.Name.LocalName != XmlNamespaceAttribute) + var name = xAttribute.IsNamespaceDeclaration && xAttribute.Name.LocalName != XmlNamespaceAttribute ? $"{XmlNamespaceAttribute}:{xAttribute.Name.LocalName}" - : GetNamespaceForElement(xElement, xAttribute.Name.NamespaceName) + xAttribute.Name.LocalName; - obj.Add($"-{name}", ParseValue(xAttribute.Value)); + : _GetNamespaceForElement(xElement, xAttribute.Name.NamespaceName) + xAttribute.Name.LocalName; + obj.Add($"-{name}", _ParseValue(xAttribute.Value)); } return new JsonArray { obj, json }; } - private static JsonValue ParseValue(string value) + private static JsonValue _ParseValue(string value) { bool b; if (bool.TryParse(value, out b)) @@ -214,13 +214,13 @@ private static JsonValue ParseValue(string value) return d; return value; } - private static bool ContainsAttributeList(JsonArray json) + private static bool _ContainsAttributeList(JsonArray json) { if (json.Count != 2) return false; if (json[0].Type != JsonValueType.Object) return false; return json[0].Object.Keys.All(key => key[0] == '-'); } - private static string GetNamespaceForElement(XElement xElement, string space = null) + private static string _GetNamespaceForElement(XElement xElement, string space = null) { var search = space ?? xElement.Name.NamespaceName; if (string.IsNullOrEmpty(search)) return string.Empty; @@ -238,7 +238,7 @@ private static string GetNamespaceForElement(XElement xElement, string space = n } return string.Empty; } - private static XName GetXName(string key) + private static XName _GetXName(string key) { if (key == null) return null; if (!key.Contains(":") && (key != XmlNamespaceAttribute)) return key; From 113632ed958af862c33cbae4481ac47622db0929 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Wed, 14 Jun 2017 00:55:41 +1200 Subject: [PATCH 10/15] minor edits --- .../Serialization/Internal/TypeGeneratorTest.cs | 4 ---- .../Serialization/JsonSerializerTest.cs | 15 +++++------- Manatee.Json.sln.DotSettings | 2 +- Manatee.Json.sln.DotSettings.user | 3 +++ Manatee.Json/Manatee.Json.csproj | 3 +++ .../Internal/Serializers/ReflectionCache.cs | 1 - Manatee.Json/nuget.ps1 | 27 ---------------------- 7 files changed, 13 insertions(+), 42 deletions(-) delete mode 100644 Manatee.Json/nuget.ps1 diff --git a/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs b/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs index b99b7a4..31256a2 100644 --- a/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs +++ b/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs @@ -3,8 +3,6 @@ using Manatee.Json.Tests.Test_References; using Microsoft.VisualStudio.TestTools.UnitTesting; -#if !IOS - namespace Manatee.Json.Tests.Serialization.Internal { [TestClass] @@ -58,5 +56,3 @@ public void CacheTypes_Success() } } } - -#endif \ No newline at end of file diff --git a/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs b/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs index ada198c..7cb82d3 100644 --- a/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs @@ -291,9 +291,6 @@ public void AbstractClass_Successful() Assert.AreEqual(expected, actual); } [TestMethod] -#if IOS - [Ignore] -#endif public void Interface_Successful() { var serializer = new JsonSerializer(); @@ -338,7 +335,7 @@ public void IJsonSerializable_Successful() Assert.AreEqual(expected, actual); } [TestMethod] - public void Array_Successfull() + public void Array_Successful() { var serializer = new JsonSerializer(); var list = new[] {4, 3, 5, 6}; @@ -347,7 +344,7 @@ public void Array_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void List_Successfull() + public void List_Successful() { var serializer = new JsonSerializer(); var list = new List {4, 3, 5, 6}; @@ -356,7 +353,7 @@ public void List_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void IEnumerable_Successfull() + public void IEnumerable_Successful() { var serializer = new JsonSerializer(); JsonSerializationAbstractionMap.MapGeneric(typeof (IEnumerable<>), typeof (List<>)); @@ -381,7 +378,7 @@ public void Dictionary_Successful() Assert.AreEqual(expected, actual); } [TestMethod] - public void Queue_Successfull() + public void Queue_Successful() { var serializer = new JsonSerializer(); var queue = new Queue(); @@ -394,7 +391,7 @@ public void Queue_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void Stack_Successfull() + public void Stack_Successful() { var serializer = new JsonSerializer(); var stack = new Stack(); @@ -407,7 +404,7 @@ public void Stack_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void SerializeType_Successfull() + public void SerializeType_Successful() { var serializer = new JsonSerializer(); ObjectWithBasicProps.StaticStringProp = "staticStringValue"; diff --git a/Manatee.Json.sln.DotSettings b/Manatee.Json.sln.DotSettings index 1237c76..18d2ca7 100644 --- a/Manatee.Json.sln.DotSettings +++ b/Manatee.Json.sln.DotSettings @@ -24,4 +24,4 @@ True True True - <data><IncludeFilters /><ExcludeFilters><Filter ModuleMask="Manatee.Json" ModuleVersionMask="*" ClassMask="Manatee.Json.Path.JsonPathRoot" FunctionMask="*" IsEnabled="True" /></ExcludeFilters></data> \ No newline at end of file + <data><IncludeFilters /><ExcludeFilters><Filter ModuleMask="Manatee.Json" ModuleVersionMask="*" ClassMask="Manatee.Json.Path.JsonPathRoot" FunctionMask="*" IsEnabled="True" /><Filter ModuleMask="Manatee.Json.Tests" ModuleVersionMask="*" ClassMask="*" FunctionMask="*" IsEnabled="True" /></ExcludeFilters></data> \ No newline at end of file diff --git a/Manatee.Json.sln.DotSettings.user b/Manatee.Json.sln.DotSettings.user index 58f206f..f47061f 100644 --- a/Manatee.Json.sln.DotSettings.user +++ b/Manatee.Json.sln.DotSettings.user @@ -1,4 +1,7 @@  + True + 2017.1.2 + C:\Users\gregd\AppData\Local\Temp\ssm.Zytokuc.tmp 0 diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj index c2207e2..cc1b4da 100644 --- a/Manatee.Json/Manatee.Json.csproj +++ b/Manatee.Json/Manatee.Json.csproj @@ -36,6 +36,9 @@ Schema passes latest version of JSON Schema Test Suite. (#63) + + + \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index 9058a67..ec163d7 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal.Serializers { diff --git a/Manatee.Json/nuget.ps1 b/Manatee.Json/nuget.ps1 deleted file mode 100644 index 5304dc9..0000000 --- a/Manatee.Json/nuget.ps1 +++ /dev/null @@ -1,27 +0,0 @@ -param([String]$nuspecfile) - -Write-Output "Post-build running..." - -if (!(Test-Path -path $nuspecfile)) { - Write-Output "Cannot find project/nuspec file '$nuspecfile'" - return 1 -} - -$nuget_exe = ".\.tools\nuget.exe" -$release_dir = ".\.release" - -if (!(Test-Path -path ".\.tools")){ - mkdir ".\.tools" -} - -if (!(Test-Path -path $nuget_exe)) { - Write-Output "Attempting to download nuget.exe" - $sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" - Invoke-WebRequest $sourceNugetExe -OutFile $nuget_exe -} - -Write-Output "Building project file '$nuspecfile'" - -& $nuget_exe pack "$nuspecfile" -NonInteractive -properties Configuration=Release -outputdirectory $release_dir - -exit $LASTEXITCODE \ No newline at end of file From 116640a7cc26793e4be0fcb7c5b89ad4917d49e8 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Thu, 15 Jun 2017 10:03:17 +1200 Subject: [PATCH 11/15] updated type generation --- .../Manatee.Json.Tests.Console.csproj | 12 ++ Manatee.Json.Tests.Console/Program.cs | 40 +++++++ Manatee.Json.sln | 7 ++ Manatee.Json/Internal/GeneralExtensions.cs | 24 ++-- Manatee.Json/Manatee.Json.csproj | 2 + .../Internal/Serializers/ReflectionCache.cs | 15 +-- .../Serialization/Internal/TypeGenerator.cs | 133 +++++++++++---------- .../JsonSerializationAbstractionMap.cs | 2 - 8 files changed, 149 insertions(+), 86 deletions(-) create mode 100644 Manatee.Json.Tests.Console/Manatee.Json.Tests.Console.csproj create mode 100644 Manatee.Json.Tests.Console/Program.cs diff --git a/Manatee.Json.Tests.Console/Manatee.Json.Tests.Console.csproj b/Manatee.Json.Tests.Console/Manatee.Json.Tests.Console.csproj new file mode 100644 index 0000000..a2e2743 --- /dev/null +++ b/Manatee.Json.Tests.Console/Manatee.Json.Tests.Console.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp1.1 + + + + + + + \ No newline at end of file diff --git a/Manatee.Json.Tests.Console/Program.cs b/Manatee.Json.Tests.Console/Program.cs new file mode 100644 index 0000000..33af0af --- /dev/null +++ b/Manatee.Json.Tests.Console/Program.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; +using Manatee.Json.Serialization; + +//[assembly:InternalsVisibleTo("Manatee.Json.DynamicTypes")] + +namespace Manatee.Json.Tests.Console +{ + class Program + { + static void Main(string[] args) + { + var json = new JsonObject + { + ["test1"] = 1, + ["test2"] = "hello" + }; + var serializer = new JsonSerializer(); + var obj = serializer.Deserialize(json); + + System.Console.WriteLine(obj.Test1); + System.Console.WriteLine(obj.Test2); + + System.Console.ReadLine(); + } + } + + internal interface ITest + { + [JsonMapTo("test1")] + int Test1 { get; set; } + [JsonMapTo("test2")] + string Test2 { get; set; } + + event EventHandler SomethingHappened; + + void Action(object withParameter); + int Function(string withParameter); + } +} \ No newline at end of file diff --git a/Manatee.Json.sln b/Manatee.Json.sln index af27fea..228257e 100644 --- a/Manatee.Json.sln +++ b/Manatee.Json.sln @@ -16,6 +16,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{6E84846A EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Manatee.Json", "Manatee.Json\Manatee.Json.csproj", "{7548217B-8C18-4CA5-A248-59889EF93CF5}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests.Console", "Manatee.Json.Tests.Console\Manatee.Json.Tests.Console.csproj", "{861C40FB-5D2E-4051-A1F0-D9B9C5D74794}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -29,12 +31,17 @@ Global {7548217B-8C18-4CA5-A248-59889EF93CF5}.Debug|Any CPU.Build.0 = Debug|Any CPU {7548217B-8C18-4CA5-A248-59889EF93CF5}.Release|Any CPU.ActiveCfg = Release|Any CPU {7548217B-8C18-4CA5-A248-59889EF93CF5}.Release|Any CPU.Build.0 = Release|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Debug|Any CPU.Build.0 = Debug|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.ActiveCfg = Release|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {E74B7538-5E17-43C7-925B-33784945312E} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = Json.vsmdi diff --git a/Manatee.Json/Internal/GeneralExtensions.cs b/Manatee.Json/Internal/GeneralExtensions.cs index 2b20ac1..bbb858f 100644 --- a/Manatee.Json/Internal/GeneralExtensions.cs +++ b/Manatee.Json/Internal/GeneralExtensions.cs @@ -10,9 +10,9 @@ namespace Manatee.Json.Internal { internal static class GeneralExtensions { - private static readonly IEnumerable AvailableChars = Enumerable.Range(ushort.MinValue, ushort.MaxValue) + private static readonly IEnumerable AvailableChars = Enumerable.Range(UInt16.MinValue, UInt16.MaxValue) .Select(n => (char)n) - .Where(c => !char.IsControl(c)); + .Where(c => !Char.IsControl(c)); public static bool In(this T value, params T[] collection) { @@ -58,14 +58,14 @@ public static string EvaluateEscapeSequences(this string source, out string resu break; case 'u': length = 6; - var hex = int.Parse(source.Substring(i + 2, 4), NumberStyles.HexNumber); + var hex = Int32.Parse(source.Substring(i + 2, 4), NumberStyles.HexNumber); if (source.Substring(i + 6, 2) == "\\u") { - var hex2 = int.Parse(source.Substring(i + 8, 4), NumberStyles.HexNumber); + var hex2 = Int32.Parse(source.Substring(i + 8, 4), NumberStyles.HexNumber); hex = (hex - 0xD800)*0x400 + (hex2 - 0xDC00)%0x400 + 0x10000; length += 6; } - source = source.Substring(0, i) + char.ConvertFromUtf32(hex) + source.Substring(i + length); + source = source.Substring(0, i) + Char.ConvertFromUtf32(hex) + source.Substring(i + length); length = 2; // unicode pairs are 2 chars in .Net strings. break; default: @@ -145,7 +145,7 @@ public static string SkipWhiteSpace(this string source, ref int index, int lengt var c = source[index]; while (index < length) { - if (!char.IsWhiteSpace(c)) break; + if (!Char.IsWhiteSpace(c)) break; index++; if (index >= length) { @@ -172,7 +172,7 @@ public static string SkipWhiteSpace(this StreamReader stream, out char ch) ch = (char) stream.Peek(); while (!stream.EndOfStream) { - if (!char.IsWhiteSpace(ch)) break; + if (!Char.IsWhiteSpace(ch)) break; stream.Read(); ch = (char) stream.Peek(); } @@ -257,5 +257,15 @@ public static Type[] GetTypeArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } + public static IEnumerable GetAllProperties(this TypeInfo type) + { + var properties = new List(); + while (type != null) + { + properties.AddRange(type.DeclaredProperties); + type = type.BaseType?.GetTypeInfo(); + } + return properties; + } } } \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj index cc1b4da..0113395 100644 --- a/Manatee.Json/Manatee.Json.csproj +++ b/Manatee.Json/Manatee.Json.csproj @@ -40,5 +40,7 @@ Schema passes latest version of JSON Schema Test Suite. (#63) + + \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index ec163d7..744d336 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal.Serializers { @@ -110,11 +111,11 @@ private static SerializationInfo _BuildSerializationInfo(MemberInfo info) } private static IEnumerable _GetInstanceProperties(this Type type) { - return type.GetTypeInfo()._GetAllProperties().Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); + return type.GetTypeInfo().GetAllProperties().Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } private static IEnumerable _GetStaticProperties(this Type type) { - return type.GetTypeInfo()._GetAllProperties().Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); + return type.GetTypeInfo().GetAllProperties().Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } private static IEnumerable _GetInstanceFields(this Type type) { @@ -124,16 +125,6 @@ private static IEnumerable _GetStaticFields(this Type type) { return type.GetTypeInfo()._GetAllFields().Where(f => f.IsStatic && f.IsPublic); } - private static IEnumerable _GetAllProperties(this TypeInfo type) - { - var properties = new List(); - while (type != null) - { - properties.AddRange(type.DeclaredProperties); - type = type.BaseType?.GetTypeInfo(); - } - return properties; - } private static IEnumerable _GetAllFields(this TypeInfo type) { var fields = new List(); diff --git a/Manatee.Json/Serialization/Internal/TypeGenerator.cs b/Manatee.Json/Serialization/Internal/TypeGenerator.cs index 3a06171..1fccff8 100644 --- a/Manatee.Json/Serialization/Internal/TypeGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TypeGenerator.cs @@ -1,76 +1,81 @@ -#if !NETSTANDARD1_3 - -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; +using System.Runtime.CompilerServices; using System.Threading; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal { internal static class TypeGenerator { - private const string AssemblyName = "Manatee.Json.DynamicTypes"; + public const string AssemblyName = "Manatee.Json.DynamicTypes"; private static readonly AssemblyBuilder _assemblyBuilder; private static readonly ModuleBuilder _moduleBuilder; - private static readonly Dictionary _cache; + private static readonly Dictionary _cache; static TypeGenerator() { var assemblyName = new AssemblyName(AssemblyName); - // Note: To debug IL generation, please use the following line with your own test path. Also need to uncomment the Save() call in the Generate() method. - //_assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, @"E:\Projects\Manatee.Json\Manatee.Json.Tests\bin\Debug\"); - _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect); - _moduleBuilder = _assemblyBuilder.DefineDynamicModule(AssemblyName, AssemblyName + ".dll"); - _cache = new Dictionary(); + _assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect); + _moduleBuilder = _assemblyBuilder.DefineDynamicModule(AssemblyName + ".dll"); + _cache = new Dictionary(); } public static T Generate() { var type = typeof (T); - Type concreteType; + TypeInfo concreteType; if (!_cache.TryGetValue(type, out concreteType)) { - if (!type.IsInterface) - throw new ArgumentException($"Type generation only works for interface types. Type '{type}' is not valid."); - var typeBuilder = CreateType(type); - ImplementProperties(typeBuilder); - ImplementMethods(typeBuilder); - ImplementEvents(typeBuilder); - concreteType = typeBuilder.CreateType(); + var typeInfo = type.GetTypeInfo(); + if (!typeInfo.IsInterface) + throw new ArgumentException($"Type generation only works for interface types. Type '{type}' is not an interface."); + if (!typeInfo.IsPublic) + { + var assembly = typeInfo.Assembly; + var internalsVisible = assembly.GetCustomAttributes() + .Any(a => a.AssemblyName == AssemblyName); + if (!internalsVisible) + throw new ArgumentException($"Type generation only works for accessible interface types. Type '{type}' is not accessible. " + + $"If possible, make the type public or add '[assembly:InternalsVisibleTo(\"{AssemblyName}\")] " + + $"to assembly '{assembly.FullName}'."); + } + var typeBuilder = _CreateTypeBuilder(type); + _ImplementProperties(typeBuilder); + _ImplementMethods(typeBuilder); + _ImplementEvents(typeBuilder); + concreteType = typeBuilder.CreateTypeInfo(); _cache.Add(type, concreteType); - // Note: To debug IL generation, please uncomment the following line. Also need to use the first _assemblyBuilder assignment in the static constructor. - //_assemblyBuilder.Save(@"Manatee.Json.DynamicTypes.dll"); } - return (T) ConstructInstance(concreteType); + return (T) _ConstructInstance(concreteType.AsType()); } - private static TypeBuilder CreateType(Type type) + private static TypeBuilder _CreateTypeBuilder(Type type) { var typeBuilder = _moduleBuilder.DefineType("Concrete" + type.Name, TypeAttributes.Public); typeBuilder.AddInterfaceImplementation(type); return typeBuilder; } - private static void ImplementProperties(TypeBuilder builder) + private static void _ImplementProperties(TypeBuilder builder) { var interfaceType = typeof (T); - var properties = GetAllProperties(interfaceType); + var properties = _GetAllProperties(interfaceType); foreach (var propertyInfo in properties) { - ImplementSingleProperty(builder, propertyInfo); + _ImplementSingleProperty(builder, propertyInfo); } } - private static IEnumerable GetAllProperties(Type type) + private static IEnumerable _GetAllProperties(Type type) { - var methods = new List(type.GetProperties().Where(m => !m.IsSpecialName)); - var interfaceTypes = type.GetInterfaces(); - methods.AddRange(interfaceTypes.SelectMany(GetAllProperties)); + var methods = new List(type.GetTypeInfo().DeclaredProperties.Where(m => !m.IsSpecialName)); + var interfaceTypes = type.GetTypeInfo().ImplementedInterfaces; + methods.AddRange(interfaceTypes.SelectMany(_GetAllProperties)); return methods; } - private static void ImplementSingleProperty(TypeBuilder builder, PropertyInfo propertyInfo) + private static void _ImplementSingleProperty(TypeBuilder builder, PropertyInfo propertyInfo) { const MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual; @@ -80,17 +85,17 @@ private static void ImplementSingleProperty(TypeBuilder builder, PropertyInfo pr MethodBuilder methodBuilder; if (propertyInfo.CanRead) { - methodBuilder = builder.DefineMethod(propertyInfo.GetGetMethod().Name, methodAttr, propertyInfo.PropertyType, indexers); + methodBuilder = builder.DefineMethod(propertyInfo.GetMethod.Name, methodAttr, propertyInfo.PropertyType, indexers); var il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, fieldBuilder); il.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, propertyInfo.GetGetMethod()); + builder.DefineMethodOverride(methodBuilder, propertyInfo.GetMethod); } if (propertyInfo.CanWrite) { - methodBuilder = builder.DefineMethod(propertyInfo.GetGetMethod().Name, methodAttr, null, + methodBuilder = builder.DefineMethod(propertyInfo.GetMethod.Name, methodAttr, null, indexers.Union(new[] {propertyInfo.PropertyType}).ToArray()); var il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); @@ -98,26 +103,26 @@ private static void ImplementSingleProperty(TypeBuilder builder, PropertyInfo pr il.Emit(OpCodes.Stfld, fieldBuilder); il.Emit(OpCodes.Ret); propertyBuilder.SetSetMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, propertyInfo.GetSetMethod()); + builder.DefineMethodOverride(methodBuilder, propertyInfo.SetMethod); } } - private static void ImplementMethods(TypeBuilder builder) + private static void _ImplementMethods(TypeBuilder builder) { var interfaceType = typeof(T); - var methods = GetAllMethods(interfaceType); + var methods = _GetAllMethods(interfaceType); foreach (var methodInfo in methods) { - ImplementSingleMethod(builder, methodInfo); + _ImplementSingleMethod(builder, methodInfo); } } - private static IEnumerable GetAllMethods(Type type) + private static IEnumerable _GetAllMethods(Type type) { - var methods = new List(type.GetMethods().Where(m => !m.IsSpecialName)); - var interfaceTypes = type.GetInterfaces(); - methods.AddRange(interfaceTypes.SelectMany(GetAllMethods)); + var methods = new List(type.GetTypeInfo().DeclaredMethods.Where(m => !m.IsSpecialName)); + var interfaceTypes = type.GetTypeInfo().ImplementedInterfaces; + methods.AddRange(interfaceTypes.SelectMany(_GetAllMethods)); return methods; } - private static void ImplementSingleMethod(TypeBuilder builder, MethodInfo methodInfo) + private static void _ImplementSingleMethod(TypeBuilder builder, MethodInfo methodInfo) { const MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Final; var types = methodInfo.GetParameters().Select(p => p.ParameterType).ToArray(); @@ -130,10 +135,10 @@ private static void ImplementSingleMethod(TypeBuilder builder, MethodInfo method foreach (var typeParameter in typeParameters) { var genericParameter = genericParameters.Single(p => p.Name == typeParameter.Name); - var constraints = genericParameter.GetGenericParameterConstraints(); + var constraints = genericParameter.GetTypeInfo().GetGenericParameterConstraints(); foreach (var constraint in constraints) { - if (constraint.IsInterface) typeParameter.SetInterfaceConstraints(constraint); + if (constraint.GetTypeInfo().IsInterface) typeParameter.SetInterfaceConstraints(constraint); else typeParameter.SetBaseTypeConstraint(constraint); } } @@ -147,36 +152,36 @@ private static void ImplementSingleMethod(TypeBuilder builder, MethodInfo method il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); } - private static void ImplementEvents(TypeBuilder builder) + private static void _ImplementEvents(TypeBuilder builder) { var interfaceType = typeof(T); - var events = GetAllEvents(interfaceType); + var events = _GetAllEvents(interfaceType); foreach (var eventInfo in events) { - ImplementSingleEvent(builder, eventInfo); + _ImplementSingleEvent(builder, eventInfo); } } - private static IEnumerable GetAllEvents(Type type) + private static IEnumerable _GetAllEvents(Type type) { - var events = new List(type.GetEvents()); - var interfaceTypes = type.GetInterfaces(); - events.AddRange(interfaceTypes.SelectMany(GetAllEvents)); + var events = new List(type.GetTypeInfo().DeclaredEvents); + var interfaceTypes = type.GetTypeInfo().ImplementedInterfaces; + events.AddRange(interfaceTypes.SelectMany(_GetAllEvents)); return events; } - private static void ImplementSingleEvent(TypeBuilder builder, EventInfo eventInfo) + private static void _ImplementSingleEvent(TypeBuilder builder, EventInfo eventInfo) { const MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Final; var fieldBuilder = builder.DefineField("_" + eventInfo.Name, eventInfo.EventHandlerType, FieldAttributes.Private); var eventBuilder = builder.DefineEvent(eventInfo.Name, EventAttributes.None, eventInfo.EventHandlerType); - var methodBuilder = builder.DefineMethod(eventInfo.GetAddMethod().Name, methodAttr, null, + var methodBuilder = builder.DefineMethod(eventInfo.AddMethod.Name, methodAttr, null, new[] {eventInfo.EventHandlerType}); - var combineMethod = typeof (Delegate).GetMethod("Combine", new[] {typeof (Delegate), typeof (Delegate)}); - var removeMethod = typeof (Delegate).GetMethod("Remove", new[] {typeof (Delegate), typeof (Delegate)}); - var compareExchangeMethod = typeof (Interlocked).GetMethods() - .Single(m => (m.Name == "CompareExchange") && m.IsGenericMethod) - .MakeGenericMethod(eventInfo.EventHandlerType); + var combineMethod = typeof (Delegate).GetRuntimeMethod("Combine", new[] {typeof (Delegate), typeof (Delegate)}); + var removeMethod = typeof (Delegate).GetRuntimeMethod("Remove", new[] {typeof (Delegate), typeof (Delegate)}); + var compareExchangeMethod = typeof(Interlocked).GetTypeInfo().DeclaredMethods + .Single(m => m.Name == "CompareExchange" && m.IsGenericMethod) + .MakeGenericMethod(eventInfo.EventHandlerType); var il = methodBuilder.GetILGenerator(); il.DeclareLocal(eventInfo.EventHandlerType); il.DeclareLocal(eventInfo.EventHandlerType); @@ -210,9 +215,9 @@ private static void ImplementSingleEvent(TypeBuilder builder, EventInfo eventInf il.Emit(OpCodes.Brtrue_S, label); il.Emit(OpCodes.Ret); eventBuilder.SetAddOnMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, eventInfo.GetAddMethod()); + builder.DefineMethodOverride(methodBuilder, eventInfo.AddMethod); - methodBuilder = builder.DefineMethod(eventInfo.GetRemoveMethod().Name, methodAttr, null, new[] {eventInfo.EventHandlerType}); + methodBuilder = builder.DefineMethod(eventInfo.RemoveMethod.Name, methodAttr, null, new[] {eventInfo.EventHandlerType}); il = methodBuilder.GetILGenerator(); il.DeclareLocal(eventInfo.EventHandlerType); il.DeclareLocal(eventInfo.EventHandlerType); @@ -246,13 +251,11 @@ private static void ImplementSingleEvent(TypeBuilder builder, EventInfo eventInf il.Emit(OpCodes.Brtrue_S, label); il.Emit(OpCodes.Ret); eventBuilder.SetRemoveOnMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, eventInfo.GetRemoveMethod()); + builder.DefineMethodOverride(methodBuilder, eventInfo.RemoveMethod); } - private static object ConstructInstance(Type type) + private static object _ConstructInstance(Type type) { return Activator.CreateInstance(type, null); } } } - -#endif \ No newline at end of file diff --git a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs index 0005562..0784c66 100644 --- a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs +++ b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs @@ -123,10 +123,8 @@ internal static T CreateInstance(JsonValue json, IResolver resolver) return (T) resolver.Resolve(tConcrete); } -#if !NETSTANDARD1_3 if (type.GetTypeInfo().IsInterface) return TypeGenerator.Generate(); -#endif } return resolver.Resolve(); } From d87799844eb235b7104159fb6b7163e5e16a337b Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Thu, 15 Jun 2017 16:09:54 +1200 Subject: [PATCH 12/15] fixed some issues with test project file --- Manatee.Json.Tests/Manatee.Json.Tests.csproj | 17 ----------------- Manatee.Json.Tests/Manatee.Json.Tests.csproj.user | 6 ------ Manatee.Json.Tests/packages.config | 8 -------- Manatee.Json.sln.DotSettings.user | 6 +++--- 4 files changed, 3 insertions(+), 34 deletions(-) delete mode 100644 Manatee.Json.Tests/Manatee.Json.Tests.csproj.user delete mode 100644 Manatee.Json.Tests/packages.config diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj b/Manatee.Json.Tests/Manatee.Json.Tests.csproj index c7bce9f..474b179 100644 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj +++ b/Manatee.Json.Tests/Manatee.Json.Tests.csproj @@ -59,23 +59,7 @@ - - ..\packages\System.Net.Http.4.3.2\lib\net46\System.Net.Http.dll - - - - ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net46\System.Security.Cryptography.Algorithms.dll - - - ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - - - ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll - - - ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net46\System.Security.Cryptography.X509Certificates.dll - @@ -142,7 +126,6 @@ Always - PreserveNewest diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj.user b/Manatee.Json.Tests/Manatee.Json.Tests.csproj.user deleted file mode 100644 index 76fe5a5..0000000 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - ProjectFiles - - \ No newline at end of file diff --git a/Manatee.Json.Tests/packages.config b/Manatee.Json.Tests/packages.config deleted file mode 100644 index eb95af3..0000000 --- a/Manatee.Json.Tests/packages.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json.sln.DotSettings.user b/Manatee.Json.sln.DotSettings.user index f47061f..83059b6 100644 --- a/Manatee.Json.sln.DotSettings.user +++ b/Manatee.Json.sln.DotSettings.user @@ -1,7 +1,7 @@  - True - 2017.1.2 - C:\Users\gregd\AppData\Local\Temp\ssm.Zytokuc.tmp + + + 0 From 92a50bdfeb3855321f83a58cb847508e48f598ff Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Sat, 17 Jun 2017 21:47:41 +1200 Subject: [PATCH 13/15] updated to c# 7 language features --- Manatee.Json.Tests/LinqExtensionsTest.cs | 7 +- Manatee.Json.Tests/Manatee.Json.Tests.csproj | 1 + .../Test References/ObjectWithBasicProps.cs | 6 +- Manatee.Json.sln.DotSettings.user | 1 + Manatee.Json/DescriptionAttribute.cs | 24 --- Manatee.Json/Internal/GeneralExtensions.cs | 224 +-------------------- Manatee.Json/Internal/LinqExtensions.cs | 26 +++ Manatee.Json/Internal/ReflectionExtensions.cs | 46 +++++ Manatee.Json/Internal/StringExtensions.cs | 172 ++++++++++++++++ Manatee.Json/Internal/XmlNamespaceRegistry.cs | 9 +- Manatee.Json/JsonArray.cs | 5 +- Manatee.Json/JsonObjectExtensions.cs | 10 +- Manatee.Json/JsonSyntaxException.cs | 8 +- Manatee.Json/JsonValue.cs | 1 - Manatee.Json/LinqExtensions.cs | 10 +- Manatee.Json/Manatee.Json.csproj | 10 +- Manatee.Json/Parsing/ArrayParser.cs | 12 +- Manatee.Json/Parsing/BoolParser.cs | 2 +- Manatee.Json/Parsing/JsonParser.cs | 12 +- Manatee.Json/Parsing/NullParser.cs | 4 +- Manatee.Json/Parsing/NumberParser.cs | 10 +- Manatee.Json/Parsing/ObjectParser.cs | 12 +- Manatee.Json/Parsing/StringParser.cs | 6 +- Manatee.Json/Path/ArrayParameters/SliceQuery.cs | 2 - .../Path/Expressions/ArrayIndexExpression.cs | 6 +- .../Path/Expressions/ConversionExpression.cs | 8 +- Manatee.Json/Path/Expressions/Expression.cs | 12 +- Manatee.Json/Path/Expressions/IndexOfExpression.cs | 4 +- .../Path/Expressions/IsGreaterThanExpression.cs | 3 +- Manatee.Json/Path/Expressions/LengthExpression.cs | 2 +- Manatee.Json/Path/Expressions/NameExpresssion.cs | 6 +- .../Parsing/JsonPathExpressionParser.cs | 39 ++-- .../Expressions/Parsing/PathExpressionParser.cs | 6 +- .../Translation/AddExpressionTranslator.cs | 8 +- .../Translation/AndExpressionTranslator.cs | 8 +- .../Translation/ExpressionTranslator.cs | 20 +- .../Translation/FieldExpressionTranslator.cs | 10 +- .../Translation/HasPropertyExpressionTranslator.cs | 3 +- .../Translation/IsEqualExpressionTranslator.cs | 8 +- Manatee.Json/Path/Expressions/ValueComparer.cs | 50 ++--- Manatee.Json/Path/JsonPathWith.cs | 46 ----- Manatee.Json/Path/Operators/ArrayOperator.cs | 2 +- Manatee.Json/Path/Operators/NameOperator.cs | 2 +- Manatee.Json/Path/Operators/WildCardOperator.cs | 2 +- .../Path/Parsing/ExpressionFilterParser.cs | 6 +- Manatee.Json/Path/Parsing/ExpressionIndexParser.cs | 6 +- Manatee.Json/Path/Parsing/IndexedArrayParser.cs | 6 +- Manatee.Json/Path/Parsing/JsonPathParser.cs | 6 +- Manatee.Json/Path/Parsing/PathParsingExtensions.cs | 47 ++--- .../Path/Parsing/SearchIndexedArrayParser.cs | 5 +- Manatee.Json/Path/Parsing/SearchParser.cs | 3 +- Manatee.Json/Path/Parsing/StartParser.cs | 3 +- Manatee.Json/Path/Slice.cs | 6 +- Manatee.Json/Schema/AdditionalItems.cs | 3 +- Manatee.Json/Schema/JsonSchema.cs | 6 +- Manatee.Json/Schema/JsonSchemaFactory.cs | 3 +- .../Schema/JsonSchemaMultiTypeDefinition.cs | 19 +- Manatee.Json/Schema/JsonSchemaReference.cs | 12 +- Manatee.Json/Schema/JsonSchemaTypeDefinition.cs | 1 - Manatee.Json/Schema/PropertyDependency.cs | 1 - .../JsonSchemaPropertyValidatorFactory.cs | 1 - .../MaxPropertySchemaPropertyValidator.cs | 6 +- .../Validators/MinItemsSchemaPropertyValidator.cs | 6 +- .../Validators/MinLengthSchemaPropertyValidator.cs | 2 +- .../MinPropertiesSchemaPropertyValidator.cs | 6 +- .../MultipleOfSchemaPropertyValidator.cs | 6 +- .../Validators/NotSchemaPropertyValidator.cs | 6 +- .../Validators/PatternSchemaPropertyValidator.cs | 6 +- .../UniqueItemsSchemaPropertyValidator.cs | 6 +- .../ArraySerializationDelegateProvider.cs | 4 +- .../DateTimeSerializationDelegateProvider.cs | 4 +- .../DictionarySerializationDelegateProvider.cs | 4 +- .../GuidSerializationDelegateProvider.cs | 4 +- .../ListSerializationDelegateProvider.cs | 4 +- .../NullableSerializationDelegateProvider.cs | 4 +- .../QueueSerializationDelegateProvider.cs | 4 +- .../SerializationDelegateProviderBase.cs | 4 +- .../StackSerializationDelegateProvider.cs | 4 +- .../TimeSpanSerializationDelegateProvider.cs | 4 +- .../Serialization/Internal/SerializerCache.cs | 6 +- .../Serialization/Internal/SerializerFactory.cs | 20 +- .../Serialization/Internal/SerializerMethodPair.cs | 12 +- .../Internal/Serializers/AutoSerializer.cs | 58 +++--- .../Internal/Serializers/DefaultValueSerializer.cs | 5 +- .../Internal/Serializers/EnumNameSerializer.cs | 23 +-- .../Internal/Serializers/NumericSerializer.cs | 2 +- .../Internal/Serializers/ReflectionCache.cs | 38 ++-- .../Serialization/Internal/TemplateGenerator.cs | 19 +- .../Serialization/Internal/TypeGenerator.cs | 9 +- .../JsonSerializationAbstractionMap.cs | 29 ++- .../Serialization/JsonSerializationTypeRegistry.cs | 12 +- Manatee.Json/Serialization/JsonSerializer.cs | 2 - .../Serialization/TypeRegistrationException.cs | 2 +- Manatee.Json/XmlExtensions.cs | 40 +--- 94 files changed, 609 insertions(+), 751 deletions(-) delete mode 100644 Manatee.Json/DescriptionAttribute.cs create mode 100644 Manatee.Json/Internal/LinqExtensions.cs create mode 100644 Manatee.Json/Internal/ReflectionExtensions.cs create mode 100644 Manatee.Json/Internal/StringExtensions.cs diff --git a/Manatee.Json.Tests/LinqExtensionsTest.cs b/Manatee.Json.Tests/LinqExtensionsTest.cs index 37d7560..a4611c8 100644 --- a/Manatee.Json.Tests/LinqExtensionsTest.cs +++ b/Manatee.Json.Tests/LinqExtensionsTest.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Manatee.Json.Serialization; using Manatee.Json.Tests.Test_References; @@ -172,13 +173,13 @@ public void FromJson_SerializableArray_ReturnsArray() Assert.IsTrue(expected.SequenceEqual(actual)); } [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] public void FromJson_NullSerializableArray_ReturnsNull() { var serializer = new JsonSerializer(); var json = (JsonArray)null; var expected = (IEnumerable)null; - var actual = json.FromJson(serializer); - Assert.AreEqual(expected, actual); + var actual = json.FromJson(serializer).ToList(); } [TestMethod] public void FromJson_SerializableObject_ReturnsObject() diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj b/Manatee.Json.Tests/Manatee.Json.Tests.csproj index 474b179..ebe1a67 100644 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj +++ b/Manatee.Json.Tests/Manatee.Json.Tests.csproj @@ -52,6 +52,7 @@ False + 3.5 diff --git a/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs b/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs index a2bb730..c591e8d 100644 --- a/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs +++ b/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs @@ -1,5 +1,5 @@ using System; -using System.ComponentModel; +using System.ComponentModel.DataAnnotations; using Manatee.Json.Serialization; namespace Manatee.Json.Tests.Test_References @@ -90,7 +90,7 @@ public enum TestEnum { None, BasicEnumValue, - [Description("enum_value_with_description")] + [Display(Description = "enum_value_with_description")] EnumValueWithDescription } @@ -99,7 +99,7 @@ public enum FlagsEnum { None = 0, BasicEnumValue = 1, - [Description("enum_value_with_description")] + [Display(Description = "enum_value_with_description")] EnumValueWithDescription = 2 } // ReSharper restore UnusedAutoPropertyAccessor.Local diff --git a/Manatee.Json.sln.DotSettings.user b/Manatee.Json.sln.DotSettings.user index 83059b6..db3369a 100644 --- a/Manatee.Json.sln.DotSettings.user +++ b/Manatee.Json.sln.DotSettings.user @@ -1,4 +1,5 @@  + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> diff --git a/Manatee.Json/DescriptionAttribute.cs b/Manatee.Json/DescriptionAttribute.cs deleted file mode 100644 index 254f9e7..0000000 --- a/Manatee.Json/DescriptionAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace Manatee.Json -{ - /// - /// - /// - [AttributeUsage(AttributeTargets.All)] - public class DescriptionAttribute : Attribute - { - /// - /// Gets the description. - /// - public string Description { get; } - - /// - /// Creates a new instance of the class. - /// - public DescriptionAttribute(string description) - { - Description = description; - } - } -} diff --git a/Manatee.Json/Internal/GeneralExtensions.cs b/Manatee.Json/Internal/GeneralExtensions.cs index bbb858f..5a9f43c 100644 --- a/Manatee.Json/Internal/GeneralExtensions.cs +++ b/Manatee.Json/Internal/GeneralExtensions.cs @@ -1,207 +1,23 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.IO; using System.Linq; -using System.Reflection; using System.Runtime.CompilerServices; namespace Manatee.Json.Internal { internal static class GeneralExtensions { - private static readonly IEnumerable AvailableChars = Enumerable.Range(UInt16.MinValue, UInt16.MaxValue) - .Select(n => (char)n) - .Where(c => !Char.IsControl(c)); - + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool In(this T value, params T[] collection) { return collection.Contains(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInt(this double value) { return Math.Ceiling(value) == Math.Floor(value); } - public static IEnumerable NotNull(this IEnumerable items) - where T : class - { - return items.Where(i => i != null); - } - public static string EvaluateEscapeSequences(this string source, out string result) - { - var i = 0; - while (i < source.Length) - { - var length = 1; - if (source[i] == '\\') - switch (source[i + 1]) - { - case '"': - case '/': - case '\\': - source = source.Remove(i, 1); - break; - case 'b': - source = source.Substring(0, i) + '\b' + source.Substring(i + length + 1); - break; - case 'f': - source = source.Substring(0, i) + '\f' + source.Substring(i + length + 1); - break; - case 'n': - source = source.Substring(0, i) + '\n' + source.Substring(i + length + 1); - break; - case 'r': - source = source.Substring(0, i) + '\r' + source.Substring(i + length + 1); - break; - case 't': - source = source.Substring(0, i) + '\t' + source.Substring(i + length + 1); - break; - case 'u': - length = 6; - var hex = Int32.Parse(source.Substring(i + 2, 4), NumberStyles.HexNumber); - if (source.Substring(i + 6, 2) == "\\u") - { - var hex2 = Int32.Parse(source.Substring(i + 8, 4), NumberStyles.HexNumber); - hex = (hex - 0xD800)*0x400 + (hex2 - 0xDC00)%0x400 + 0x10000; - length += 6; - } - source = source.Substring(0, i) + Char.ConvertFromUtf32(hex) + source.Substring(i + length); - length = 2; // unicode pairs are 2 chars in .Net strings. - break; - default: - result = source; - return $"Invalid escape sequence: '\\{source[i + 1]}'."; - } - i += length; - } - result = source; - return null; - } - public static string InsertEscapeSequences(this string source) - { - var index = 0; - while (index < source.Length) - { - var count = 0; - string replace = null; - switch (source[index]) - { - case '"': - case '\\': - source = source.Insert(index, "\\"); - index++; - break; - case '\b': - count = 1; - replace = "\\b"; - break; - case '\f': - count = 1; - replace = "\\f"; - break; - case '\n': - count = 1; - replace = "\\n"; - break; - case '\r': - count = 1; - replace = "\\r"; - break; - case '\t': - count = 1; - replace = "\\t"; - break; - default: - if (!AvailableChars.Contains(source[index])) - { - var hex = Convert.ToInt16(source[index]).ToString("X4"); - source = source.Substring(0, index) + "\\u" + hex + source.Substring(index + 1); - index += 5; - } - break; - } - if (replace != null) - { - source = _Replace(source, index, count, replace); - index++; - } - index++; - } - return source; - } - private static string _Replace(string source, int index, int count, string content) - { - // I've checked both of these methods with ILSpy. They occur in external methods, so - // we're not going to do much better than this. - return source.Remove(index, count).Insert(index, content); - } - public static string SkipWhiteSpace(this string source, ref int index, int length, out char ch) - { - if (index >= length) - { - ch = default(char); - return "Unexpected end of input."; - } - var c = source[index]; - while (index < length) - { - if (!Char.IsWhiteSpace(c)) break; - index++; - if (index >= length) - { - ch = default(char); - return "Unexpected end of input."; - } - c = source[index]; - } - if (index >= length) - { - ch = default(char); - return "Unexpected end of input."; - } - ch = c; - return null; - } - public static string SkipWhiteSpace(this StreamReader stream, out char ch) - { - if (stream.EndOfStream) - { - ch = default(char); - return "Unexpected end of input."; - } - ch = (char) stream.Peek(); - while (!stream.EndOfStream) - { - if (!Char.IsWhiteSpace(ch)) break; - stream.Read(); - ch = (char) stream.Peek(); - } - if (stream.EndOfStream) - { - ch = default(char); - return "Unexpected end of input."; - } - return null; - } - // Note: These methods assume that if a generic type is passed, the type is open. - public static bool InheritsFrom(this Type tDerived, Type tBase) - { - if (tDerived._IsSubtypeOf(tBase)) return true; - var interfaces = tDerived.GetTypeInfo().ImplementedInterfaces.Select(i => i.GetTypeInfo().IsGenericType ? i.GetGenericTypeDefinition() : i); - return interfaces.Contains(tBase); - } - private static bool _IsSubtypeOf(this Type tDerived, Type tBase) - { - var currentType = tDerived.GetTypeInfo().BaseType; - while (currentType != null) - { - if (currentType.GetTypeInfo().IsGenericType) - currentType = currentType.GetGenericTypeDefinition(); - if (currentType == tBase) return true; - currentType = currentType.GetTypeInfo().BaseType; - } - return false; - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetCollectionHashCode(this IEnumerable collection) { return collection.Aggregate(0, (current, obj) => unchecked(current * 397) ^ obj.GetHashCode()); @@ -219,27 +35,18 @@ public static int GetCollectionHashCode(this IEnumerable(this IEnumerable a, IEnumerable b) - { - if (a == null && b != null) return false; - if (a != null && b == null) return false; - if (a == null) return true; - - var listA = a.ToList(); - var listB = b.ToList(); - return listA.Count == listB.Count && listA.All(item => listB.Contains(item)); - } public static JsonValue AsJsonValue(this object value) { - if (value is JsonValue) return (JsonValue) value; - if (value is JsonArray) return (JsonArray) value; - if (value is JsonObject) return (JsonObject) value; - if (value is string) return (string) value; + if (value is JsonValue jsonValue) return jsonValue; + if (value is JsonArray jsonArray) return jsonArray; + if (value is JsonObject jsonObject) return jsonObject; + if (value is string s) return s; if (value is bool) return (bool) value; if (value.IsNumber()) return Convert.ToDouble(value); return null; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNumber(this object value) { return value is double || @@ -252,20 +59,5 @@ public static bool IsNumber(this object value) value is long || value is ulong; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Type[] GetTypeArguments(this Type type) - { - return type.GetTypeInfo().GenericTypeArguments; - } - public static IEnumerable GetAllProperties(this TypeInfo type) - { - var properties = new List(); - while (type != null) - { - properties.AddRange(type.DeclaredProperties); - type = type.BaseType?.GetTypeInfo(); - } - return properties; - } } } \ No newline at end of file diff --git a/Manatee.Json/Internal/LinqExtensions.cs b/Manatee.Json/Internal/LinqExtensions.cs new file mode 100644 index 0000000..275c64e --- /dev/null +++ b/Manatee.Json/Internal/LinqExtensions.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Manatee.Json.Internal +{ + internal static class LinqExtensions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable WhereNotNull(this IEnumerable items) + where T : class + { + return items.Where(i => i != null); + } + public static bool ContentsEqual(this IEnumerable a, IEnumerable b) + { + if (a == null && b != null) return false; + if (a != null && b == null) return false; + if (a == null) return true; + + var listA = a.ToList(); + var listB = b.ToList(); + return listA.Count == listB.Count && listA.All(item => listB.Contains(item)); + } + } +} \ No newline at end of file diff --git a/Manatee.Json/Internal/ReflectionExtensions.cs b/Manatee.Json/Internal/ReflectionExtensions.cs new file mode 100644 index 0000000..d8be6db --- /dev/null +++ b/Manatee.Json/Internal/ReflectionExtensions.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Manatee.Json.Internal +{ + internal static class ReflectionExtensions + { + // Note: These methods assume that if a generic type is passed, the type is open. + public static bool InheritsFrom(this Type tDerived, Type tBase) + { + if (tDerived._IsSubtypeOf(tBase)) return true; + var interfaces = tDerived.GetTypeInfo().ImplementedInterfaces.Select(i => IntrospectionExtensions.GetTypeInfo(i).IsGenericType ? i.GetGenericTypeDefinition() : i); + return interfaces.Contains(tBase); + } + private static bool _IsSubtypeOf(this Type tDerived, Type tBase) + { + var currentType = tDerived.GetTypeInfo().BaseType; + while (currentType != null) + { + if (currentType.GetTypeInfo().IsGenericType) + currentType = currentType.GetGenericTypeDefinition(); + if (currentType == tBase) return true; + currentType = currentType.GetTypeInfo().BaseType; + } + return false; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Type[] GetTypeArguments(this Type type) + { + return type.GetTypeInfo().GenericTypeArguments; + } + public static IEnumerable GetAllProperties(this TypeInfo type) + { + var properties = new List(); + while (type != null) + { + properties.AddRange(type.DeclaredProperties); + type = type.BaseType?.GetTypeInfo(); + } + return properties; + } + } +} \ No newline at end of file diff --git a/Manatee.Json/Internal/StringExtensions.cs b/Manatee.Json/Internal/StringExtensions.cs new file mode 100644 index 0000000..005a4be --- /dev/null +++ b/Manatee.Json/Internal/StringExtensions.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; + +namespace Manatee.Json.Internal +{ + internal static class StringExtensions + { + private static readonly IEnumerable AvailableChars = Enumerable.Range(UInt16.MinValue, UInt16.MaxValue) + .Select(n => (char) n) + .Where(c => !Char.IsControl(c)); + + public static string EvaluateEscapeSequences(this string source, out string result) + { + var i = 0; + while (i < source.Length) + { + var length = 1; + if (source[i] == '\\') + switch (source[i + 1]) + { + case '"': + case '/': + case '\\': + source = source.Remove(i, 1); + break; + case 'b': + source = source.Substring(0, i) + '\b' + source.Substring(i + length + 1); + break; + case 'f': + source = source.Substring(0, i) + '\f' + source.Substring(i + length + 1); + break; + case 'n': + source = source.Substring(0, i) + '\n' + source.Substring(i + length + 1); + break; + case 'r': + source = source.Substring(0, i) + '\r' + source.Substring(i + length + 1); + break; + case 't': + source = source.Substring(0, i) + '\t' + source.Substring(i + length + 1); + break; + case 'u': + length = 6; + var hex = Int32.Parse(source.Substring(i + 2, 4), NumberStyles.HexNumber); + if (source.Substring(i + 6, 2) == "\\u") + { + var hex2 = Int32.Parse(source.Substring(i + 8, 4), NumberStyles.HexNumber); + hex = (hex - 0xD800) * 0x400 + (hex2 - 0xDC00) % 0x400 + 0x10000; + length += 6; + } + source = source.Substring(0, i) + Char.ConvertFromUtf32(hex) + source.Substring(i + length); + length = 2; // unicode pairs are 2 chars in .Net strings. + break; + default: + result = source; + return $"Invalid escape sequence: '\\{source[i + 1]}'."; + } + i += length; + } + result = source; + return null; + } + public static string InsertEscapeSequences(this string source) + { + var index = 0; + while (index < source.Length) + { + var count = 0; + string replace = null; + switch (source[index]) + { + case '"': + case '\\': + source = source.Insert(index, "\\"); + index++; + break; + case '\b': + count = 1; + replace = "\\b"; + break; + case '\f': + count = 1; + replace = "\\f"; + break; + case '\n': + count = 1; + replace = "\\n"; + break; + case '\r': + count = 1; + replace = "\\r"; + break; + case '\t': + count = 1; + replace = "\\t"; + break; + default: + if (!Enumerable.Contains(AvailableChars, source[index])) + { + var hex = Convert.ToInt16(source[index]).ToString("X4"); + source = source.Substring(0, index) + "\\u" + hex + source.Substring(index + 1); + index += 5; + } + break; + } + if (replace != null) + { + source = _Replace(source, index, count, replace); + index++; + } + index++; + } + return source; + } + private static string _Replace(string source, int index, int count, string content) + { + // I've checked both of these methods with ILSpy. They occur in external methods, so + // we're not going to do much better than this. + return source.Remove(index, count).Insert(index, content); + } + public static string SkipWhiteSpace(this string source, ref int index, int length, out char ch) + { + if (index >= length) + { + ch = default(char); + return "Unexpected end of input."; + } + var c = source[index]; + while (index < length) + { + if (!Char.IsWhiteSpace(c)) break; + index++; + if (index >= length) + { + ch = default(char); + return "Unexpected end of input."; + } + c = source[index]; + } + if (index >= length) + { + ch = default(char); + return "Unexpected end of input."; + } + ch = c; + return null; + } + public static string SkipWhiteSpace(this StreamReader stream, out char ch) + { + if (stream.EndOfStream) + { + ch = default(char); + return "Unexpected end of input."; + } + ch = (char) stream.Peek(); + while (!stream.EndOfStream) + { + if (!Char.IsWhiteSpace(ch)) break; + stream.Read(); + ch = (char) stream.Peek(); + } + if (stream.EndOfStream) + { + ch = default(char); + return "Unexpected end of input."; + } + return null; + } + } +} \ No newline at end of file diff --git a/Manatee.Json/Internal/XmlNamespaceRegistry.cs b/Manatee.Json/Internal/XmlNamespaceRegistry.cs index 3d5ce79..019234e 100644 --- a/Manatee.Json/Internal/XmlNamespaceRegistry.cs +++ b/Manatee.Json/Internal/XmlNamespaceRegistry.cs @@ -34,8 +34,7 @@ public void UnRegisterElement(XElement element) } public bool ElementDefinesNamespace(XElement element, string space) { - List entry; - return _registry.TryGetValue(element, out entry) && entry.Any(pair => pair.Namespace == space); + return _registry.TryGetValue(element, out List entry) && entry.Any(pair => pair.Namespace == space); } public string GetLabel(XElement element, string space) { @@ -44,8 +43,7 @@ public string GetLabel(XElement element, string space) public void Register(string label, string space) { - Stack entry; - if (!_stack.TryGetValue(label, out entry)) + if (!_stack.TryGetValue(label, out Stack entry)) { entry = new Stack(); _stack.Add(label, entry); @@ -60,8 +58,7 @@ public void Unregister(string label) } public string GetNamespace(string label) { - Stack entry; - if (!_stack.TryGetValue(label, out entry)) return null; + if (!_stack.TryGetValue(label, out Stack entry)) return null; return _stack.TryGetValue(label, out entry) && entry.Count != 0 ? entry.Peek() : null; } } diff --git a/Manatee.Json/JsonArray.cs b/Manatee.Json/JsonArray.cs index 0915766..1f047ca 100644 --- a/Manatee.Json/JsonArray.cs +++ b/Manatee.Json/JsonArray.cs @@ -24,10 +24,7 @@ public class JsonArray : List /// /// public JsonArray(IEnumerable collection) - : base(collection) - { - - } + : base(collection) { } /// /// Creates a string representation of the JSON data. diff --git a/Manatee.Json/JsonObjectExtensions.cs b/Manatee.Json/JsonObjectExtensions.cs index 191b43b..606e7ef 100644 --- a/Manatee.Json/JsonObjectExtensions.cs +++ b/Manatee.Json/JsonObjectExtensions.cs @@ -15,7 +15,7 @@ public static class JsonObjectExtensions /// A or null if the key is not found or is not a public static string TryGetString(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.String) ? obj[key].String : null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.String ? obj[key].String : null; } /// /// Returns a or null if the key is not found or is not a double. @@ -25,7 +25,7 @@ public static string TryGetString(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static double? TryGetNumber(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Number) ? obj[key].Number : (double?)null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Number ? obj[key].Number : (double?)null; } /// /// Returns a or null if the key is not found or is not a . @@ -35,7 +35,7 @@ public static string TryGetString(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static bool? TryGetBoolean(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Boolean) ? obj[key].Boolean : (bool?)null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Boolean ? obj[key].Boolean : (bool?)null; } /// /// Returns a or null if the key is not found or is not a . @@ -45,7 +45,7 @@ public static string TryGetString(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static JsonArray TryGetArray(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Array) ? obj[key].Array : null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Array ? obj[key].Array : null; } /// /// Returns a or null if the key is not found or is not a . @@ -55,7 +55,7 @@ public static JsonArray TryGetArray(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static JsonObject TryGetObject(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Object) ? obj[key].Object : null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Object ? obj[key].Object : null; } } } diff --git a/Manatee.Json/JsonSyntaxException.cs b/Manatee.Json/JsonSyntaxException.cs index 175270c..e136766 100644 --- a/Manatee.Json/JsonSyntaxException.cs +++ b/Manatee.Json/JsonSyntaxException.cs @@ -29,10 +29,10 @@ public class JsonSyntaxException : Exception internal JsonSyntaxException(string message, JsonValue value) : base(message) { - _path = BuildPath(value); + _path = _BuildPath(value); } - private static string BuildPath(JsonValue value) + private static string _BuildPath(JsonValue value) { if (value == null) return string.Empty; switch (value.Type) @@ -41,12 +41,12 @@ private static string BuildPath(JsonValue value) if (!value.Object.Any()) return string.Empty; var pair = value.Object.Last(); var key = pair.Key; - return $".{key}{BuildPath(pair.Value)}"; + return $".{key}{_BuildPath(pair.Value)}"; case JsonValueType.Array: if (!value.Array.Any()) return string.Empty; var item = value.Array.Last(); var index = value.Array.Count - 1; - return $"[{index}]{BuildPath(item)}"; + return $"[{index}]{_BuildPath(item)}"; default: return string.Empty; } diff --git a/Manatee.Json/JsonValue.cs b/Manatee.Json/JsonValue.cs index a2b5d7b..f493dff 100644 --- a/Manatee.Json/JsonValue.cs +++ b/Manatee.Json/JsonValue.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.Globalization; using System.IO; using Manatee.Json.Internal; diff --git a/Manatee.Json/LinqExtensions.cs b/Manatee.Json/LinqExtensions.cs index 98c8fd5..89bdf96 100644 --- a/Manatee.Json/LinqExtensions.cs +++ b/Manatee.Json/LinqExtensions.cs @@ -3,8 +3,6 @@ using System.Linq; using Manatee.Json.Serialization; -//using Manatee.Json.Serialization; - namespace Manatee.Json { /// @@ -168,15 +166,14 @@ public static JsonObject ToJson(this IEnumerable> res public static IEnumerable FromJson(this IEnumerable json, JsonSerializer serializer) where T : IJsonSerializable, new() { - if (json == null) return null; - var list = new List(); + if (json == null) throw new ArgumentNullException(nameof(json)); + foreach (var value in json) { T item = new T(); item.FromJson(value, serializer); - list.Add(item); + yield return item; } - return list; } /// /// Deserializes a to its equivalent object. @@ -190,6 +187,7 @@ public static T FromJson(this JsonObject json, JsonSerializer serializer) where T : IJsonSerializable, new() { if (json == null) return default(T); + T obj = new T(); obj.FromJson(json, serializer); return obj; diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj index 0113395..7a7599c 100644 --- a/Manatee.Json/Manatee.Json.csproj +++ b/Manatee.Json/Manatee.Json.csproj @@ -35,12 +35,16 @@ Schema passes latest version of JSON Schema Test Suite. (#63) + + + + + + - - - + \ No newline at end of file diff --git a/Manatee.Json/Parsing/ArrayParser.cs b/Manatee.Json/Parsing/ArrayParser.cs index 3913629..bf31ec4 100644 --- a/Manatee.Json/Parsing/ArrayParser.cs +++ b/Manatee.Json/Parsing/ArrayParser.cs @@ -17,8 +17,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a index++; while (index < length) { - char c; - var message = source.SkipWhiteSpace(ref index, length, out c); + var message = source.SkipWhiteSpace(ref index, length, out char c); if (message != null) return message; // check for empty array if (c == ']') @@ -29,8 +28,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a } else return "Expected value."; // get value - JsonValue item; - message = JsonParser.Parse(source, ref index, out item); + message = JsonParser.Parse(source, ref index, out JsonValue item); array.Add(item); if (message != null) return message; message = source.SkipWhiteSpace(ref index, length, out c); @@ -52,8 +50,7 @@ public string TryParse(StreamReader stream, out JsonValue value) while (!stream.EndOfStream) { stream.Read(); // waste the '[' or ',' - char c; - var message = stream.SkipWhiteSpace(out c); + var message = stream.SkipWhiteSpace(out char c); if (message != null) return message; // check for empty array if (c == ']') @@ -64,8 +61,7 @@ public string TryParse(StreamReader stream, out JsonValue value) } else return "Expected value."; // get value - JsonValue item; - message = JsonParser.Parse(stream, out item); + message = JsonParser.Parse(stream, out JsonValue item); array.Add(item); if (message != null) return message; message = stream.SkipWhiteSpace(out c); diff --git a/Manatee.Json/Parsing/BoolParser.cs b/Manatee.Json/Parsing/BoolParser.cs index 808de58..41fd8b3 100644 --- a/Manatee.Json/Parsing/BoolParser.cs +++ b/Manatee.Json/Parsing/BoolParser.cs @@ -25,7 +25,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a count = 5; } count = Math.Min(count, source.Length - index); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { buffer[i] = source[index + i]; } diff --git a/Manatee.Json/Parsing/JsonParser.cs b/Manatee.Json/Parsing/JsonParser.cs index 8cca3b3..332f879 100644 --- a/Manatee.Json/Parsing/JsonParser.cs +++ b/Manatee.Json/Parsing/JsonParser.cs @@ -23,16 +23,14 @@ static JsonParser() public static JsonValue Parse(string source) { var index = 0; - JsonValue value; - var errorMessage = Parse(source, ref index, out value); + var errorMessage = Parse(source, ref index, out JsonValue value); if (errorMessage != null) throw new JsonSyntaxException(errorMessage, value); return value; } public static JsonValue Parse(StreamReader stream) { - JsonValue value; - var errorMessage = Parse(stream, out value); + var errorMessage = Parse(stream, out JsonValue value); if (errorMessage != null) throw new JsonSyntaxException(errorMessage, value); return value; @@ -40,8 +38,7 @@ public static JsonValue Parse(StreamReader stream) public static string Parse(string source, ref int index, out JsonValue value, bool allowExtraChars = false) { var length = source.Length; - char c; - var errorMessage = source.SkipWhiteSpace(ref index, length, out c); + var errorMessage = source.SkipWhiteSpace(ref index, length, out char c); if (errorMessage != null) { value = null; @@ -58,8 +55,7 @@ public static string Parse(string source, ref int index, out JsonValue value, bo } public static string Parse(StreamReader stream, out JsonValue value) { - char c; - var errorMessage = stream.SkipWhiteSpace(out c); + var errorMessage = stream.SkipWhiteSpace(out char c); if (errorMessage != null) { value = null; diff --git a/Manatee.Json/Parsing/NullParser.cs b/Manatee.Json/Parsing/NullParser.cs index 3d5118c..ff706fc 100644 --- a/Manatee.Json/Parsing/NullParser.cs +++ b/Manatee.Json/Parsing/NullParser.cs @@ -12,7 +12,7 @@ public bool Handles(char c) public string TryParse(string source, ref int index, out JsonValue value, bool allowExtraChars) { var buffer = new char[4]; - for (int i = 0; i < 4 && index + i < source.Length; i++) + for (var i = 0; i < 4 && index + i < source.Length; i++) { buffer[i] = source[index + i]; } @@ -29,7 +29,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a public string TryParse(StreamReader stream, out JsonValue value) { var buffer = new char[4]; - for (int i = 0; i < 4 && !stream.EndOfStream; i++) + for (var i = 0; i < 4 && !stream.EndOfStream; i++) { buffer[i] = (char) stream.Read(); } diff --git a/Manatee.Json/Parsing/NumberParser.cs b/Manatee.Json/Parsing/NumberParser.cs index 390f1eb..416939f 100644 --- a/Manatee.Json/Parsing/NumberParser.cs +++ b/Manatee.Json/Parsing/NumberParser.cs @@ -20,7 +20,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; var buffer = new char[bufferLength]; - int bufferIndex = 0; + var bufferIndex = 0; var sourceLength = source.Length; while (index < sourceLength) { @@ -46,9 +46,8 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a index++; bufferIndex++; } - double dbl; var result = new string(buffer, 0, bufferIndex); - if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out dbl)) + if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out double dbl)) { value = null; return $"Value not recognized: '{result}'"; @@ -61,7 +60,7 @@ public string TryParse(StreamReader stream, out JsonValue value) var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; var buffer = new char[bufferLength]; - int bufferIndex = 0; + var bufferIndex = 0; while (!stream.EndOfStream) { if (bufferIndex == bufferLength) @@ -84,9 +83,8 @@ public string TryParse(StreamReader stream, out JsonValue value) buffer[bufferIndex] = c; bufferIndex++; } - double dbl; var result = new string(buffer, 0, bufferIndex); - if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out dbl)) + if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out double dbl)) { value = null; return $"Value not recognized: '{result}'"; diff --git a/Manatee.Json/Parsing/ObjectParser.cs b/Manatee.Json/Parsing/ObjectParser.cs index 5a2380e..bb8faa5 100644 --- a/Manatee.Json/Parsing/ObjectParser.cs +++ b/Manatee.Json/Parsing/ObjectParser.cs @@ -17,8 +17,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a index++; while (index < length) { - char c; - var message = source.SkipWhiteSpace(ref index, length, out c); + var message = source.SkipWhiteSpace(ref index, length, out char c); if (message != null) return message; // check for empty object if (c == '}') @@ -32,8 +31,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a message = source.SkipWhiteSpace(ref index, length, out c); if (message != null) return message; if (c != '\"') return "Expected key."; - JsonValue item; - message = JsonParser.Parse(source, ref index, out item); + message = JsonParser.Parse(source, ref index, out JsonValue item); if (message != null) return message; var key = item.String; // check for colon @@ -68,8 +66,7 @@ public string TryParse(StreamReader stream, out JsonValue value) while (!stream.EndOfStream) { stream.Read(); // waste the '{' or ',' - char c; - var message = stream.SkipWhiteSpace(out c); + var message = stream.SkipWhiteSpace(out char c); if (message != null) return message; // check for empty object if (c == '}') @@ -83,8 +80,7 @@ public string TryParse(StreamReader stream, out JsonValue value) message = stream.SkipWhiteSpace(out c); if (message != null) return message; if (c != '\"') return "Expected key."; - JsonValue item; - message = JsonParser.Parse(stream, out item); + message = JsonParser.Parse(stream, out JsonValue item); if (message != null) return message; var key = item.String; // check for colon diff --git a/Manatee.Json/Parsing/StringParser.cs b/Manatee.Json/Parsing/StringParser.cs index e62707a..eae1aa0 100644 --- a/Manatee.Json/Parsing/StringParser.cs +++ b/Manatee.Json/Parsing/StringParser.cs @@ -50,8 +50,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a return "Could not find end of string value."; } var result = new string(buffer, 0, bufferIndex); - string escaped; - var errorMessage = result.EvaluateEscapeSequences(out escaped); + var errorMessage = result.EvaluateEscapeSequences(out string escaped); value = escaped; return errorMessage; } @@ -91,8 +90,7 @@ public string TryParse(StreamReader stream, out JsonValue value) return "Could not find end of string value."; } var result = new string(buffer, 0, bufferIndex); - string escaped; - var errorMessage = result.EvaluateEscapeSequences(out escaped); + var errorMessage = result.EvaluateEscapeSequences(out string escaped); value = escaped; return errorMessage; } diff --git a/Manatee.Json/Path/ArrayParameters/SliceQuery.cs b/Manatee.Json/Path/ArrayParameters/SliceQuery.cs index fccaf3a..f20e6cf 100644 --- a/Manatee.Json/Path/ArrayParameters/SliceQuery.cs +++ b/Manatee.Json/Path/ArrayParameters/SliceQuery.cs @@ -10,8 +10,6 @@ internal class SliceQuery : IJsonPathArrayQuery, IEquatable internal IEnumerable Slices { get; } public SliceQuery(params Slice[] slices) - : this((IEnumerable) slices) {} - public SliceQuery(IEnumerable slices) { Slices = slices.ToList(); } diff --git a/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs b/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs index 769e327..5455208 100644 --- a/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs +++ b/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs @@ -20,7 +20,7 @@ public override object Evaluate(T json, JsonValue root) if (results.Count > 1) throw new InvalidOperationException($"Path '{Path}' returned more than one result on value '{value}'"); var result = results.FirstOrDefault(); - var index = GetIndex(); + var index = _GetIndex(); if (result != null && index >= 0) { if (result.Type == JsonValueType.Array && index < result.Array.Count) @@ -33,7 +33,7 @@ public override object Evaluate(T json, JsonValue root) public override string ToString() { var path = Path == null ? string.Empty : Path.GetRawString(); - return string.Format(IsLocal ? "@{0}[{1}]" : "${0}[{1}]", path, GetIndex()); + return string.Format(IsLocal ? "@{0}[{1}]" : "${0}[{1}]", path, _GetIndex()); } public bool Equals(ArrayIndexExpression other) { @@ -58,7 +58,7 @@ public override int GetHashCode() } } - private int GetIndex() + private int _GetIndex() { var value = IndexExpression?.Evaluate(default(T), null); if (value != null) return (int) value; diff --git a/Manatee.Json/Path/Expressions/ConversionExpression.cs b/Manatee.Json/Path/Expressions/ConversionExpression.cs index c41b67d..0693cf8 100644 --- a/Manatee.Json/Path/Expressions/ConversionExpression.cs +++ b/Manatee.Json/Path/Expressions/ConversionExpression.cs @@ -13,7 +13,7 @@ internal class ConversionExpression : ExpressionTreeNode, IEquatable 1) throw new InvalidOperationException($"Path '{Path}' returned more than one result on value '{value}'"); var result = results.FirstOrDefault(); - var parameter = GetParameter(); + var parameter = _GetParameter(); return result != null && result.Type == JsonValueType.Array && parameter != null ? result.Array.IndexOf(parameter) : (object)null; @@ -52,7 +52,7 @@ public override int GetHashCode() } } - private JsonValue GetParameter() + private JsonValue _GetParameter() { var value = ParameterExpression?.Evaluate(null, null); if (value != null) diff --git a/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs b/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs index 57c9305..df3159c 100644 --- a/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs +++ b/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs @@ -24,8 +24,7 @@ public bool Equals(IsGreaterThanExpression other) } public override bool Equals(object obj) { - if (obj.GetType() != this.GetType()) return false; - return Equals((IsGreaterThanExpression) obj); + return Equals(obj as IsGreaterThanExpression); } public override int GetHashCode() { diff --git a/Manatee.Json/Path/Expressions/LengthExpression.cs b/Manatee.Json/Path/Expressions/LengthExpression.cs index 7f2ac49..7185db8 100644 --- a/Manatee.Json/Path/Expressions/LengthExpression.cs +++ b/Manatee.Json/Path/Expressions/LengthExpression.cs @@ -19,7 +19,7 @@ public override object Evaluate(T json, JsonValue root) if (array == null) { var value = json as JsonValue; - if (value.Type == JsonValueType.Array) + if (value?.Type == JsonValueType.Array) array = value.Array; } if (array == null) return null; diff --git a/Manatee.Json/Path/Expressions/NameExpresssion.cs b/Manatee.Json/Path/Expressions/NameExpresssion.cs index fe36471..c3f77fb 100644 --- a/Manatee.Json/Path/Expressions/NameExpresssion.cs +++ b/Manatee.Json/Path/Expressions/NameExpresssion.cs @@ -20,7 +20,7 @@ public override object Evaluate(T json, JsonValue root) if (results.Count > 1) throw new InvalidOperationException($"Path '{Path}' returned more than one result on value '{value}'"); var result = results.FirstOrDefault(); - var name = GetName(); + var name = _GetName(); return result != null && result.Type == JsonValueType.Object && result.Object.ContainsKey(name) ? result.Object[name].GetValue() : null; @@ -28,10 +28,10 @@ public override object Evaluate(T json, JsonValue root) public override string ToString() { var path = Path == null ? string.Empty : Path.GetRawString(); - return string.Format(IsLocal ? "@{0}.{1}" : "${0}.{1}", path, GetName()); + return string.Format(IsLocal ? "@{0}.{1}" : "${0}.{1}", path, _GetName()); } - private string GetName() + private string _GetName() { var value = NameExp?.Evaluate(default(T), null); if (value != null) diff --git a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs index 871aa33..6d7911e 100644 --- a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs +++ b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs @@ -21,8 +21,7 @@ static JsonPathExpressionParser() public static string Parse(string source, ref int index, out Expression expr) { - ExpressionTreeNode root; - var error = Parse(source, ref index, out root); + var error = Parse(source, ref index, out ExpressionTreeNode root); if (error != null) { expr = null; @@ -45,8 +44,7 @@ public static string Parse(string source, ref int index, out ExpressionTree root = null; do { - char c; - var errorMessage = source.SkipWhiteSpace(ref index, length, out c); + var errorMessage = source.SkipWhiteSpace(ref index, length, out char c); if (errorMessage != null) return errorMessage; var substring = source.Substring(index); var parser = Parsers.FirstOrDefault(p => p.Handles(substring)); @@ -58,46 +56,43 @@ public static string Parse(string source, ref int index, out ExpressionTree } while (index < length && node != null); root = nodes.Count == 1 - ? CheckNode(nodes[0], null) - : BuildTree(nodes); + ? _CheckNode(nodes[0], null) + : _BuildTree(nodes); return null; } - private static ExpressionTreeNode BuildTree(List> nodes) + private static ExpressionTreeNode _BuildTree(List> nodes) { if (!nodes.Any()) return null; var minPriority = nodes.Min(n => n.Priority); var root = nodes.Last(n => n.Priority == minPriority); - var branch = root as ExpressionTreeBranch; - if (branch != null && branch.Right == null && branch.Left == null) + if (root is ExpressionTreeBranch branch && branch.Right == null && branch.Left == null) { var split = nodes.LastIndexOf(root); var left = nodes.Take(split).ToList(); var right = nodes.Skip(split + 1).ToList(); - branch.Left = CheckNode(BuildTree(left), branch); - branch.Right = CheckNode(BuildTree(right), branch); + branch.Left = _CheckNode(_BuildTree(left), branch); + branch.Right = _CheckNode(_BuildTree(right), branch); } - var not = root as NotExpression; - if (not != null) + if (root is NotExpression not) { var split = nodes.IndexOf(root); var right = nodes.Skip(split + 1).FirstOrDefault(); - not.Root = CheckNode(right, null); + not.Root = _CheckNode(right, null); } return root; } - private static ExpressionTreeNode CheckNode(ExpressionTreeNode node, ExpressionTreeBranch root) + private static ExpressionTreeNode _CheckNode(ExpressionTreeNode node, ExpressionTreeBranch root) { - var named = node as NameExpression; - if (named != null && (root == null || root.Priority == 0)) + if (node is NameExpression named && (root == null || root.Priority == 0)) { return new HasPropertyExpression - { - Path = named.Path, - IsLocal = named.IsLocal, - Name = named.Name - }; + { + Path = named.Path, + IsLocal = named.IsLocal, + Name = named.Name + }; } return node; } diff --git a/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs b/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs index 1f8e19c..98d2241 100644 --- a/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs +++ b/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs @@ -17,8 +17,7 @@ public bool Handles(string input) public string TryParse(string source, ref int index, out ExpressionTreeNode node) { var isLocal = source[index] == '@'; - JsonPath path; - var error = JsonPathParser.Parse(source, ref index, out path); + var error = JsonPathParser.Parse(source, ref index, out JsonPath path); // Swallow this error from the path parser and assume the path just ended. // If it's really a syntax error, the expression parser should catch it. if (error != null && error != "Unrecognized JSON Path element.") @@ -35,14 +34,13 @@ public string TryParse(string source, ref int index, out ExpressionTreeNode Translate(Expression body) if (add == null) throw new InvalidOperationException(); return new AddExpression - { - Left = ExpressionTranslator.TranslateNode(add.Left), - Right = ExpressionTranslator.TranslateNode(add.Right) - }; + { + Left = ExpressionTranslator.TranslateNode(add.Left), + Right = ExpressionTranslator.TranslateNode(add.Right) + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs index efccbf7..d7d98f2 100644 --- a/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs @@ -11,10 +11,10 @@ public ExpressionTreeNode Translate(Expression body) if (and == null) throw new InvalidOperationException(); return new AndExpression - { - Left = ExpressionTranslator.TranslateNode(and.Left), - Right = ExpressionTranslator.TranslateNode(and.Right) - }; + { + Left = ExpressionTranslator.TranslateNode(and.Left), + Right = ExpressionTranslator.TranslateNode(and.Right) + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs index ca1ac4b..bc774d8 100644 --- a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs @@ -12,14 +12,14 @@ internal static class ExpressionTranslator private static readonly Dictionary> Translators = new Dictionary> { - {typeof(ConstantExpression), GetValueTranslator}, - {typeof(BinaryExpression), e => GetNodeTypeBasedTranslator(e.NodeType)}, - {typeof(UnaryExpression), e => GetNodeTypeBasedTranslator(e.NodeType)}, - {typeof(MethodCallExpression), GetMethodCallTranslator}, - {typeof(MemberExpression), GetMemberTranslator}, + {typeof(ConstantExpression), _GetValueTranslator}, + {typeof(BinaryExpression), e => _GetNodeTypeBasedTranslator(e.NodeType)}, + {typeof(UnaryExpression), e => _GetNodeTypeBasedTranslator(e.NodeType)}, + {typeof(MethodCallExpression), _GetMethodCallTranslator}, + {typeof(MemberExpression), _GetMemberTranslator}, }; - private static IExpressionTranslator GetValueTranslator(Expression e) + private static IExpressionTranslator _GetValueTranslator(Expression e) { var type = e.Type; if (type == typeof(bool)) @@ -34,7 +34,7 @@ private static IExpressionTranslator GetValueTranslator(Expression e) return new NullValueExpressionTranslator(); throw new NotSupportedException($"Values of type '{type}' are not supported."); } - private static IExpressionTranslator GetNodeTypeBasedTranslator(ExpressionType type) + private static IExpressionTranslator _GetNodeTypeBasedTranslator(ExpressionType type) { switch (type) { @@ -102,7 +102,6 @@ private static IExpressionTranslator GetNodeTypeBasedTranslator(ExpressionType t case ExpressionType.RightShift: case ExpressionType.TypeAs: case ExpressionType.TypeIs: -#if NET4 || NET45 case ExpressionType.Assign: case ExpressionType.Block: case ExpressionType.DebugInfo: @@ -142,12 +141,11 @@ private static IExpressionTranslator GetNodeTypeBasedTranslator(ExpressionType t case ExpressionType.OnesComplement: case ExpressionType.IsTrue: case ExpressionType.IsFalse: -#endif break; } throw new NotSupportedException($"Expression type '{type}' is not supported."); } - private static IExpressionTranslator GetMethodCallTranslator(Expression exp) + private static IExpressionTranslator _GetMethodCallTranslator(Expression exp) { var method = (MethodCallExpression) exp; switch (method.Method.Name) @@ -165,7 +163,7 @@ private static IExpressionTranslator GetMethodCallTranslator(Expression exp) } throw new NotSupportedException($"The method '{method.Method.Name}' is not supported."); } - private static IExpressionTranslator GetMemberTranslator(Expression exp) + private static IExpressionTranslator _GetMemberTranslator(Expression exp) { var member = (MemberExpression) exp; if (member.Member is FieldInfo && member.Expression is ConstantExpression) diff --git a/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs index 28abb7b..ed94a35 100644 --- a/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs @@ -7,12 +7,12 @@ internal class FieldExpressionTranslator : IExpressionTranslator { public ExpressionTreeNode Translate(Expression body) { - var member = (MemberExpression)body; + var member = (MemberExpression) body; return new FieldExpression - { - Field = (FieldInfo)member.Member, - Source = ((ConstantExpression)member.Expression).Value - }; + { + Field = (FieldInfo) member.Member, + Source = ((ConstantExpression) member.Expression).Value + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs index 2062f58..27bf556 100644 --- a/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs @@ -8,7 +8,6 @@ internal class HasPropertyExpressionTranslator : PathExpressionTranslator { public override ExpressionTreeNode Translate(Expression body) { - bool isLocal; var method = body as MethodCallExpression; if (method == null) throw new InvalidOperationException(); @@ -17,7 +16,7 @@ public override ExpressionTreeNode Translate(Expression body) throw new NotSupportedException("Only constant string arguments are supported in HasProperty()"); return new HasPropertyExpression { - Path = BuildPath(method, out isLocal), + Path = BuildPath(method, out bool isLocal), IsLocal = isLocal, Name = parameter.Value.ToString() }; diff --git a/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs index 17f81c8..9e12963 100644 --- a/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs @@ -11,10 +11,10 @@ public ExpressionTreeNode Translate(Expression body) if (equal == null) throw new InvalidOperationException(); return new IsEqualExpression - { - Left = ExpressionTranslator.TranslateNode(equal.Left), - Right = ExpressionTranslator.TranslateNode(equal.Right) - }; + { + Left = ExpressionTranslator.TranslateNode(equal.Left), + Right = ExpressionTranslator.TranslateNode(equal.Right) + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/ValueComparer.cs b/Manatee.Json/Path/Expressions/ValueComparer.cs index ec10fcd..63ac4b1 100644 --- a/Manatee.Json/Path/Expressions/ValueComparer.cs +++ b/Manatee.Json/Path/Expressions/ValueComparer.cs @@ -7,40 +7,40 @@ internal static class ValueComparer { public static bool Equal(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) == 0; - var bleft = TryGetBoolean(a); - var bright = TryGetBoolean(b); + var bleft = _TryGetBoolean(a); + var bright = _TryGetBoolean(b); if (bleft != null && bright != null) return bleft == bright; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft == dright; return false; } public static bool LessThan(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) < 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft < dright; return false; } public static bool GreaterThan(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) > 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft > dright; return false; @@ -48,35 +48,35 @@ public static bool GreaterThan(object a, object b) public static bool LessThanEqual(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) <= 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft <= dright; return false; } public static bool GreaterThanEqual(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) >= 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft >= dright; return false; } - private static string TryGetString(object value) + private static string _TryGetString(object value) { var jv = value as JsonValue; return jv != null && jv.Type == JsonValueType.String ? jv.String : value as string; } - private static double? TryGetNumber(object value) + private static double? _TryGetNumber(object value) { var jv = value as JsonValue; if (jv != null && jv.Type == JsonValueType.Number) return jv.Number; @@ -84,7 +84,7 @@ private static string TryGetString(object value) // at this point, we have no idea what this is. return null; } - private static bool? TryGetBoolean(object value) + private static bool? _TryGetBoolean(object value) { var jv = value as JsonValue; return jv != null && jv.Type == JsonValueType.Boolean ? jv.Boolean : value as bool?; diff --git a/Manatee.Json/Path/JsonPathWith.cs b/Manatee.Json/Path/JsonPathWith.cs index 572e8d4..5f2a2c0 100644 --- a/Manatee.Json/Path/JsonPathWith.cs +++ b/Manatee.Json/Path/JsonPathWith.cs @@ -96,21 +96,6 @@ public static JsonPath SearchArray(params Slice[] slices) return path; } /// - /// Appends a by specifying a series of array indicies using array slice notation. - /// - /// The start index of the s to include. - /// The end index of the s to include. - /// The index interval of the s to include. - /// The new . - /// The format for the array slice is [start:end:step]. All parameters are individually optional, - /// however either the start or end must be defines. Negative values for start and end indicate that the - /// iterator should begin counting from the end of the array. - [Obsolete("Use the SearchArray(params Slice[]) overload instead.")] - public static JsonPath SearchArraySlice(int? start, int? end, int? step = null) - { - return SearchArray(new Slice(start, end, step)); - } - /// /// Appends a by specifying an expression which evaluates to the index to include. /// /// The expression. @@ -146,21 +131,6 @@ public static JsonPath Array(params Slice[] slices) return path; } /// - /// Appends a by specifying a series of array indicies using array slice notation. - /// - /// The start index of the s to include. - /// The end index of the s to include. - /// The index interval of the s to include. - /// The new . - /// The format for the array slice is [start:end:step]. All parameters are individually optional, - /// however either the start or end must be defines. Negative values for start and end indicate that the - /// iterator should begin counting from the end of the array. - [Obsolete("Use the Array(params Slice[]) overload instead.")] - public static JsonPath ArraySlice(int? start, int? end, int? step = null) - { - return Array(new Slice(start, end, step)); - } - /// /// Appends a by specifying an expression which evaluates to the index to include. /// /// The expression. @@ -333,22 +303,6 @@ public static JsonPath Array(this JsonPath path, params Slice[] slices) return newPath; } /// - /// Appends a by specifying a series of array indicies using array slice notation. - /// - /// The to extend. - /// The start index of the s to include. - /// The end index of the s to include. - /// The index interval of the s to include. - /// The new . - /// The format for the array slice is [start:end:step]. All parameters are individually optional, - /// however either the start or end must be defines. Negative values for start and end indicate that the - /// iterator should begin counting from the end of the array. - [Obsolete("Use the Array(this JsonPath, params Slice[]) overload instead.")] - public static JsonPath ArraySlice(this JsonPath path, int? start, int? end, int? step = null) - { - return path.Array(new Slice(start, end, step)); - } - /// /// Appends a by specifying an expression which evaluates to the index to include. /// /// The to extend. diff --git a/Manatee.Json/Path/Operators/ArrayOperator.cs b/Manatee.Json/Path/Operators/ArrayOperator.cs index dbf2a8c..770fc2e 100644 --- a/Manatee.Json/Path/Operators/ArrayOperator.cs +++ b/Manatee.Json/Path/Operators/ArrayOperator.cs @@ -20,7 +20,7 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) : v.Type == JsonValueType.Object ? Query.Find(v.Object.Values.ToJson(), root) : Enumerable.Empty()) - .NotNull()); + .WhereNotNull()); } public override string ToString() diff --git a/Manatee.Json/Path/Operators/NameOperator.cs b/Manatee.Json/Path/Operators/NameOperator.cs index 9c2a64d..d391f36 100644 --- a/Manatee.Json/Path/Operators/NameOperator.cs +++ b/Manatee.Json/Path/Operators/NameOperator.cs @@ -17,7 +17,7 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) { return new JsonArray(json.Select(v => v.Type == JsonValueType.Object && v.Object.ContainsKey(Name) ? v.Object[Name] - : null).NotNull()); + : null).WhereNotNull()); } public override string ToString() { diff --git a/Manatee.Json/Path/Operators/WildCardOperator.cs b/Manatee.Json/Path/Operators/WildCardOperator.cs index 99866f8..b545c51 100644 --- a/Manatee.Json/Path/Operators/WildCardOperator.cs +++ b/Manatee.Json/Path/Operators/WildCardOperator.cs @@ -27,7 +27,7 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) default: return Enumerable.Empty(); } - }).NotNull()); + }).WhereNotNull()); } public override string ToString() { diff --git a/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs b/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs index 536e65f..9101d43 100644 --- a/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs +++ b/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs @@ -20,10 +20,8 @@ public string TryParse(string source, ref int index, ref JsonPath path) if (error != null) return error; - if (index >= source.Length) - return "Unexpected end of input."; - if (source[index] != ']') - return "Expected ']'"; + if (index >= source.Length) return "Unexpected end of input."; + if (source[index] != ']') return "Expected ']'"; index++; path.Operators.Add(new ArrayOperator(new FilterExpressionQuery(expression))); return null; diff --git a/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs b/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs index 60f4e85..ed9e058 100644 --- a/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs +++ b/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs @@ -20,10 +20,8 @@ public string TryParse(string source, ref int index, ref JsonPath path) if (error != null) return error; - if (index >= source.Length) - return "Unexpected end of input."; - if (source[index] != ']') - return "Expected ']'"; + if (index >= source.Length) return "Unexpected end of input."; + if (source[index] != ']') return "Expected ']'"; index++; path.Operators.Add(new ArrayOperator(new IndexExpressionQuery(expression))); return null; diff --git a/Manatee.Json/Path/Parsing/IndexedArrayParser.cs b/Manatee.Json/Path/Parsing/IndexedArrayParser.cs index ef53884..dad5820 100644 --- a/Manatee.Json/Path/Parsing/IndexedArrayParser.cs +++ b/Manatee.Json/Path/Parsing/IndexedArrayParser.cs @@ -12,11 +12,9 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path == null) - return "Start token not found."; + if (path == null) return "Start token not found."; - IList slices; - var error = source.GetSlices(ref index, out slices); + var error = source.GetSlices(ref index, out IList slices); if (error != null) return error; path = path.Array(slices.ToArray()); diff --git a/Manatee.Json/Path/Parsing/JsonPathParser.cs b/Manatee.Json/Path/Parsing/JsonPathParser.cs index f1759c7..1b65358 100644 --- a/Manatee.Json/Path/Parsing/JsonPathParser.cs +++ b/Manatee.Json/Path/Parsing/JsonPathParser.cs @@ -22,8 +22,7 @@ static JsonPathParser() public static JsonPath Parse(string source) { var index = 0; - JsonPath path; - var errorMessage = Parse(source, ref index, out path); + var errorMessage = Parse(source, ref index, out JsonPath path); if (errorMessage != null) throw new JsonPathSyntaxException(path, errorMessage); return path; @@ -34,8 +33,7 @@ public static string Parse(string source, ref int index, out JsonPath path) path = null; while(index < length) { - char c; - var errorMessage = source.SkipWhiteSpace(ref index, length, out c); + var errorMessage = source.SkipWhiteSpace(ref index, length, out char c); if (errorMessage != null) return errorMessage; var substring = source.Substring(index); var parser = Parsers.FirstOrDefault(p => p.Handles(substring)); diff --git a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs index ee36736..3c4f5f8 100644 --- a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs +++ b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs @@ -14,11 +14,11 @@ internal static class PathParsingExtensions public static string GetKey(this string source, ref int index, out string key) { return source[index].In('"', '\'') - ? GetQuotedKey(source, ref index, out key) - : GetBasicKey(source, ref index, out key); + ? _GetQuotedKey(source, ref index, out key) + : _GetBasicKey(source, ref index, out key); } - private static string GetBasicKey(string source, ref int index, out string key) + private static string _GetBasicKey(string source, ref int index, out string key) { var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; @@ -59,7 +59,7 @@ private static string GetBasicKey(string source, ref int index, out string key) return null; } - private static string GetQuotedKey(string source, ref int index, out string key) + private static string _GetQuotedKey(string source, ref int index, out string key) { var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; @@ -98,8 +98,7 @@ private static string GetQuotedKey(string source, ref int index, out string key) return "Could not find end of string value."; } var result = new string(buffer, 0, bufferIndex); - string escaped; - var errorMessage = result.EvaluateEscapeSequences(out escaped); + var errorMessage = result.EvaluateEscapeSequences(out string escaped); key = escaped; return errorMessage; } @@ -116,49 +115,43 @@ public static string GetSlices(this string source, ref int index, out IList= source.Length) - return "Expected ':', ',', or ']'."; + if (index >= source.Length) return "Expected ':', ',', or ']'."; if (n1.HasValue && source[index].In(',', ']')) { slice = new Slice(n1.Value); return null; } - if (source[index] != ':') - return "Expected ':', ',', or ']'."; + if (source[index] != ':') return "Expected ':', ',', or ']'."; index++; - error = GetInt(source, ref index, out n2); + error = _GetInt(source, ref index, out int? n2); if (error != null) return error; if (source[index].In(',', ']')) { slice = new Slice(n1, n2); return null; } - if (source[index] != ':') - return "Expected ':', ',', or ']'."; + if (source[index] != ':') return "Expected ':', ',', or ']'."; index++; - error = GetInt(source, ref index, out n3); + error = _GetInt(source, ref index, out int? n3); if (error != null) return error; if (source[index].In(',', ']')) { @@ -167,16 +160,15 @@ private static string GetSlice(this string source, ref int index, out Slice slic } return "Expected ',' or ']'."; } - public static string GetInt(string source, ref int index, out int? number) + private static string _GetInt(string source, ref int index, out int? number) { - int value; - var text = new string(source.Substring(index).Cast().TakeWhile(c => char.IsDigit(c) || c == '-').ToArray()); + var text = new string(source.Substring(index).TakeWhile(c => char.IsDigit(c) || c == '-').ToArray()); if (text.Length == 0 && source[index].In(':', ',', ']')) { number = null; return null; } - if (!int.TryParse(text, out value)) + if (!int.TryParse(text, out int value)) { number = null; return "Expected number."; @@ -195,14 +187,13 @@ public static string GetInt(string source, ref int index, out int? number) public static string GetNumber(this string source, ref int index, out double? number) { - double value; - var text = new string(source.Substring(index).Cast().TakeWhile(c => NumberChars.Cast().Contains(c)).ToArray()); + var text = new string(source.Substring(index).TakeWhile(c => NumberChars.Contains(c)).ToArray()); if (text.Length == 0 && source[index].In(':', ',', ']')) { number = null; return null; } - if (!double.TryParse(text, out value)) + if (!double.TryParse(text, out double value)) { number = null; return "Expected number."; diff --git a/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs b/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs index a24811b..3e894d7 100644 --- a/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs +++ b/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs @@ -12,12 +12,11 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path == null) - return "Start token not found."; + if (path == null) return "Start token not found."; index += 2; IList slices; - string error = source.GetSlices(ref index, out slices); + var error = source.GetSlices(ref index, out slices); if (error != null) return error; path = path.SearchArray(slices.ToArray()); diff --git a/Manatee.Json/Path/Parsing/SearchParser.cs b/Manatee.Json/Path/Parsing/SearchParser.cs index 94b8b9e..ac68bfc 100644 --- a/Manatee.Json/Path/Parsing/SearchParser.cs +++ b/Manatee.Json/Path/Parsing/SearchParser.cs @@ -10,8 +10,7 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path == null) - return "Start token not found."; + if (path == null) return "Start token not found."; index += 2; diff --git a/Manatee.Json/Path/Parsing/StartParser.cs b/Manatee.Json/Path/Parsing/StartParser.cs index ab3f39d..60dec6d 100644 --- a/Manatee.Json/Path/Parsing/StartParser.cs +++ b/Manatee.Json/Path/Parsing/StartParser.cs @@ -8,8 +8,7 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path != null) - return "Start token not valid in the middle of path."; + if (path != null) return "Start token not valid in the middle of path."; path = new JsonPath(); index++; diff --git a/Manatee.Json/Path/Slice.cs b/Manatee.Json/Path/Slice.cs index ce27123..e5c28e4 100644 --- a/Manatee.Json/Path/Slice.cs +++ b/Manatee.Json/Path/Slice.cs @@ -99,8 +99,8 @@ internal IEnumerable Find(JsonArray json, JsonValue root) : new[] { json[Index.Value] }; } - var start = ResolveIndex(_start ?? 0, json.Count); - var end = ResolveIndex(_end ?? json.Count, json.Count); + var start = _ResolveIndex(_start ?? 0, json.Count); + var end = _ResolveIndex(_end ?? json.Count, json.Count); var step = Math.Max(_step ?? 1, 1); var index = start; @@ -113,7 +113,7 @@ internal IEnumerable Find(JsonArray json, JsonValue root) return list; } - private static int ResolveIndex(int index, int count) + private static int _ResolveIndex(int index, int count) { return index < 0 ? count + index : index; } diff --git a/Manatee.Json/Schema/AdditionalItems.cs b/Manatee.Json/Schema/AdditionalItems.cs index 6b8e8a3..973a0d1 100644 --- a/Manatee.Json/Schema/AdditionalItems.cs +++ b/Manatee.Json/Schema/AdditionalItems.cs @@ -65,8 +65,7 @@ public bool Equals(AdditionalItems other) /// The object to compare with the current object. 2 public override bool Equals(object obj) { - if (obj.GetType() != GetType()) return false; - return Equals(obj as AdditionalItems); + return obj.GetType() == GetType() && Equals(obj as AdditionalItems); } /// /// Serves as a hash function for a particular type. diff --git a/Manatee.Json/Schema/JsonSchema.cs b/Manatee.Json/Schema/JsonSchema.cs index 67daabc..ee95376 100644 --- a/Manatee.Json/Schema/JsonSchema.cs +++ b/Manatee.Json/Schema/JsonSchema.cs @@ -546,10 +546,9 @@ public virtual void FromJson(JsonValue json, JsonSerializer serializer) { var obj = json.Object; Id = obj.TryGetString("id"); - Uri uri; var uriFolder = DocumentPath?.OriginalString.EndsWith("/") ?? true ? DocumentPath : DocumentPath?.GetParentUri(); if (!string.IsNullOrWhiteSpace(Id) && - (Uri.TryCreate(Id, UriKind.Absolute, out uri) || Uri.TryCreate(uriFolder + Id, UriKind.Absolute, out uri))) + (Uri.TryCreate(Id, UriKind.Absolute, out Uri uri) || Uri.TryCreate(uriFolder + Id, UriKind.Absolute, out uri))) { DocumentPath = uri; JsonSchemaRegistry.Register(this); @@ -716,8 +715,7 @@ public virtual JsonValue ToJson(JsonSerializer serializer) if (Items != null) { var items = Items as JsonSchema; - var type = items?.Type as JsonSchemaMultiTypeDefinition; - if (type != null && !type.IsPrimitive) + if (items?.Type is JsonSchemaMultiTypeDefinition type && !type.IsPrimitive) json["items"] = items.Type.ToJson(serializer); else json["items"] = Items.ToJson(serializer); diff --git a/Manatee.Json/Schema/JsonSchemaFactory.cs b/Manatee.Json/Schema/JsonSchemaFactory.cs index cba0f3d..8579877 100644 --- a/Manatee.Json/Schema/JsonSchemaFactory.cs +++ b/Manatee.Json/Schema/JsonSchemaFactory.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -64,6 +63,7 @@ public static IJsonSchema FromJson(JsonValue json, Uri documentPath = null) return schema; } +#if !NETSTANDARD1_3 /// /// Builds a implementation which can validate JSON for a given type. /// @@ -131,5 +131,6 @@ private static IJsonSchema GetBasicSchema(Type type) return new JsonSchema {Type = JsonSchemaTypeDefinition.Number}; return null; } +#endif } } \ No newline at end of file diff --git a/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs b/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs index f5c32e4..12ef141 100644 --- a/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs @@ -12,9 +12,8 @@ namespace Manatee.Json.Schema public class JsonSchemaMultiTypeDefinition : JsonSchemaTypeDefinition { private readonly bool _nonPrimitiveAllowed; - private IEnumerable _definitions; - internal IEnumerable Defintions => _definitions; + internal IEnumerable Defintions { get; private set; } internal bool IsPrimitive => !_nonPrimitiveAllowed; /// @@ -23,12 +22,12 @@ public class JsonSchemaMultiTypeDefinition : JsonSchemaTypeDefinition public JsonSchemaMultiTypeDefinition(params JsonSchemaTypeDefinition[] definitions) : this(false) { - _definitions = definitions.ToList(); + Defintions = definitions.ToList(); - if (_definitions.Except(PrimitiveDefinitions).Any()) + if (Defintions.Except(PrimitiveDefinitions).Any()) throw new InvalidOperationException("Only primitive types are allowed in type collections."); - Definition = new JsonSchema { OneOf = _definitions.Select(d => d.Definition) }; + Definition = new JsonSchema { OneOf = Defintions.Select(d => d.Definition) }; } internal JsonSchemaMultiTypeDefinition(bool nonPrimitiveAllowed) { @@ -44,7 +43,7 @@ internal JsonSchemaMultiTypeDefinition(bool nonPrimitiveAllowed) public override void FromJson(JsonValue json, JsonSerializer serializer) { var typeEntry = json.Array; - _definitions = typeEntry.Select(jv => + Defintions = typeEntry.Select(jv => { if (_nonPrimitiveAllowed) return new JsonSchemaTypeDefinition(JsonSchemaFactory.FromJson(jv)); var definition = PrimitiveDefinitions.FirstOrDefault(p => p.Name == jv.String); @@ -53,7 +52,7 @@ public override void FromJson(JsonValue json, JsonSerializer serializer) return definition; }).ToList(); - Definition = new JsonSchema {OneOf = _definitions.Select(d => d.Definition)}; } + Definition = new JsonSchema {OneOf = Defintions.Select(d => d.Definition)}; } /// /// Converts an object to a . /// @@ -62,7 +61,7 @@ public override void FromJson(JsonValue json, JsonSerializer serializer) /// The representation of the object. public override JsonValue ToJson(JsonSerializer serializer) { - return _definitions.ToJson(serializer); + return Defintions.ToJson(serializer); } /// /// Determines whether the specified is equal to the current . @@ -89,13 +88,13 @@ public override int GetHashCode() { unchecked { - return (base.GetHashCode()*397) ^ (_definitions?.GetCollectionHashCode() ?? 0); + return (base.GetHashCode()*397) ^ (Defintions?.GetCollectionHashCode() ?? 0); } } private bool Equals(JsonSchemaMultiTypeDefinition other) { - return base.Equals(other) && _definitions.ContentsEqual(other._definitions); + return base.Equals(other) && Defintions.ContentsEqual(other.Defintions); } } } \ No newline at end of file diff --git a/Manatee.Json/Schema/JsonSchemaReference.cs b/Manatee.Json/Schema/JsonSchemaReference.cs index 34f023f..1dfb7ea 100644 --- a/Manatee.Json/Schema/JsonSchemaReference.cs +++ b/Manatee.Json/Schema/JsonSchemaReference.cs @@ -113,8 +113,7 @@ private JsonValue _Resolve(JsonValue root) var jValue = root; if (!string.IsNullOrWhiteSpace(address)) { - Uri absolute; - if (!Uri.TryCreate(address, UriKind.Absolute, out absolute)) + if (!Uri.TryCreate(address, UriKind.Absolute, out Uri absolute)) { address = Id + address; } @@ -143,11 +142,9 @@ private static IJsonSchema _ResolveLocalReference(JsonValue root, string path, U if (value.Type == JsonValueType.Object) { if (!value.Object.ContainsKey(unescaped)) return null; - JsonValue id; - if (value.Object.TryGetValue("id", out id)) + if (value.Object.TryGetValue("id", out JsonValue id)) { - Uri uri; - documentPath = Uri.TryCreate(id.String, UriKind.Absolute, out uri) + documentPath = Uri.TryCreate(id.String, UriKind.Absolute, out Uri uri) ? uri : new Uri(documentPath, id.String); } @@ -155,8 +152,7 @@ private static IJsonSchema _ResolveLocalReference(JsonValue root, string path, U } else if (value.Type == JsonValueType.Array) { - int index; - if (!int.TryParse(unescaped, out index) || index >= value.Array.Count) return null; + if (!int.TryParse(unescaped, out int index) || index >= value.Array.Count) return null; value = value.Array[index]; } } diff --git a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs index f4c761a..acd7e3d 100644 --- a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; using Manatee.Json.Serialization; namespace Manatee.Json.Schema diff --git a/Manatee.Json/Schema/PropertyDependency.cs b/Manatee.Json/Schema/PropertyDependency.cs index a905af6..5ad8347 100644 --- a/Manatee.Json/Schema/PropertyDependency.cs +++ b/Manatee.Json/Schema/PropertyDependency.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { diff --git a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs index 6d41d79..a4e3f70 100644 --- a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs +++ b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Schema.Validators { diff --git a/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs index d68a3a9..e7ab7d0 100644 --- a/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Object.Count > schema.MaxProperties) - return new SchemaValidationResults(string.Empty, $"Expected: <= {schema.MaxProperties} properties; Actual: {json.Object.Count} properties."); - return new SchemaValidationResults(); + return json.Object.Count > schema.MaxProperties + ? new SchemaValidationResults(string.Empty, $"Expected: <= {schema.MaxProperties} properties; Actual: {json.Object.Count} properties.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs index 070fb62..6fffc08 100644 --- a/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Array.Count < schema.MinItems) - return new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinItems} items; Actual: {json.Array.Count} items."); - return new SchemaValidationResults(); + return json.Array.Count < schema.MinItems + ? new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinItems} items; Actual: {json.Array.Count} items.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs index 7fbf0c8..243882c 100644 --- a/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs @@ -11,7 +11,7 @@ public bool Applies(JsonSchema schema, JsonValue json) public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { var length = new StringInfo(json.String).LengthInTextElements; - if (schema.MinLength.HasValue && (length < schema.MinLength)) + if (schema.MinLength.HasValue && length < schema.MinLength) return new SchemaValidationResults(string.Empty, $"Expected: length >= {schema.MinLength}; Actual: {length}."); return new SchemaValidationResults(); } diff --git a/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs index c79e667..8a44b0b 100644 --- a/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Object.Count < schema.MinProperties) - return new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinProperties} items; Actual: {json.Object.Count} items."); - return new SchemaValidationResults(); + return json.Object.Count < schema.MinProperties + ? new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinProperties} items; Actual: {json.Object.Count} items.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs index aede343..3762e70 100644 --- a/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if ((decimal) json.Number%(decimal) schema.MultipleOf.Value != 0) - return new SchemaValidationResults(string.Empty, $"Expected: {json.Number}%{schema.MultipleOf}=0; Actual: {json.Number%schema.MultipleOf}."); - return new SchemaValidationResults(); + return (decimal) json.Number % (decimal?) schema.MultipleOf != 0 + ? new SchemaValidationResults(string.Empty, $"Expected: {json.Number}%{schema.MultipleOf}=0; Actual: {json.Number % schema.MultipleOf}.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs index d41fb1f..f417304 100644 --- a/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs @@ -9,9 +9,9 @@ public bool Applies(JsonSchema schema, JsonValue json) public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { var results = schema.Not.Validate(json, root); - if (results.Valid) - return new SchemaValidationResults(string.Empty, "Expected schema to be invalid, but was valid."); - return new SchemaValidationResults(); + return results.Valid + ? new SchemaValidationResults(string.Empty, "Expected schema to be invalid, but was valid.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs index 947dfac..9016224 100644 --- a/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs @@ -10,9 +10,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (!Regex.IsMatch(json.String, schema.Pattern)) - return new SchemaValidationResults(string.Empty, $"Value [{json.String}] does not match required Regex pattern [{schema.Pattern}]."); - return new SchemaValidationResults(); + return Regex.IsMatch(json.String, schema.Pattern) + ? new SchemaValidationResults() + : new SchemaValidationResults(string.Empty, $"Value [{json.String}] does not match required Regex pattern [{schema.Pattern}]."); } } } diff --git a/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs index 3a9a128..18bc1d1 100644 --- a/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs @@ -10,9 +10,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Array.Count != json.Array.Distinct().Count()) - return new SchemaValidationResults(string.Empty, "Expected unique items; Duplicates were found."); - return new SchemaValidationResults(); + return json.Array.Count != json.Array.Distinct().Count() + ? new SchemaValidationResults(string.Empty, "Expected unique items; Duplicates were found.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs index dd60c52..7b894e0 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs @@ -16,13 +16,13 @@ protected override Type[] GetTypeArguments(Type type) return new[] { type.GetElementType() }; } - private static JsonValue Encode(T[] array, JsonSerializer serializer) + private static JsonValue _Encode(T[] array, JsonSerializer serializer) { var json = new JsonArray(); json.AddRange(array.Select(serializer.Serialize)); return json; } - private static T[] Decode(JsonValue json, JsonSerializer serializer) + private static T[] _Decode(JsonValue json, JsonSerializer serializer) { var list = new List(); list.AddRange(json.Array.Select(serializer.Deserialize)); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs index 3b9fe12..09f359f 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs @@ -10,7 +10,7 @@ public override bool CanHandle(Type type) return type == typeof(DateTime); } - private static JsonValue Encode(DateTime dt, JsonSerializer serializer) + private static JsonValue _Encode(DateTime dt, JsonSerializer serializer) { if (serializer.Options == null) return dt.ToString(); @@ -28,7 +28,7 @@ private static JsonValue Encode(DateTime dt, JsonSerializer serializer) throw new ArgumentOutOfRangeException(); } } - private static DateTime Decode(JsonValue json, JsonSerializer serializer) + private static DateTime _Decode(JsonValue json, JsonSerializer serializer) { if (serializer.Options == null) return DateTime.Parse(json.String); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs index 13c7aa0..8cd8640 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs @@ -12,7 +12,7 @@ public override bool CanHandle(Type type) return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>); } - private static JsonValue Encode(Dictionary dict, JsonSerializer serializer) + private static JsonValue _Encode(Dictionary dict, JsonSerializer serializer) { var array = new JsonArray(); array.AddRange(dict.Select(item => (JsonValue)(new JsonObject @@ -22,7 +22,7 @@ public override bool CanHandle(Type type) }))); return array; } - private static Dictionary Decode(JsonValue json, JsonSerializer serializer) + private static Dictionary _Decode(JsonValue json, JsonSerializer serializer) { return json.Array.ToDictionary(jv => serializer.Deserialize(jv.Object["Key"]), jv => serializer.Deserialize(jv.Object["Value"])); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs index 2e98a3b..26ef21b 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs @@ -9,11 +9,11 @@ public override bool CanHandle(Type type) return type == typeof(Guid); } - private static JsonValue Encode(Guid guid, JsonSerializer serializer) + private static JsonValue _Encode(Guid guid, JsonSerializer serializer) { return guid.ToString(); } - private static Guid Decode(JsonValue json, JsonSerializer serializer) + private static Guid _Decode(JsonValue json, JsonSerializer serializer) { return json.Type == JsonValueType.String ? new Guid(json.String) : default(Guid); } diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs index fc30086..c97ed16 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs @@ -12,13 +12,13 @@ public override bool CanHandle(Type type) return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); } - private static JsonValue Encode(List list, JsonSerializer serializer) + private static JsonValue _Encode(List list, JsonSerializer serializer) { var array = new JsonArray(); array.AddRange(list.Select(serializer.Serialize)); return array; } - private static List Decode(JsonValue json, JsonSerializer serializer) + private static List _Decode(JsonValue json, JsonSerializer serializer) { var list = new List(); list.AddRange(json.Array.Select(serializer.Deserialize)); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs index 3b8bbc4..008d0ce 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs @@ -10,7 +10,7 @@ public override bool CanHandle(Type type) return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } - private static JsonValue Encode(T? nullable, JsonSerializer serializer) + private static JsonValue _Encode(T? nullable, JsonSerializer serializer) where T : struct { if (!nullable.HasValue) return JsonValue.Null; @@ -20,7 +20,7 @@ private static JsonValue Encode(T? nullable, JsonSerializer serializer) serializer.Options.EncodeDefaultValues = encodeDefaultValues; return json; } - private static T? Decode(JsonValue json, JsonSerializer serializer) + private static T? _Decode(JsonValue json, JsonSerializer serializer) where T : struct { if (json == JsonValue.Null) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs index 34db6d2..6596fb3 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs @@ -12,7 +12,7 @@ public override bool CanHandle(Type type) return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Queue<>); } - private static JsonValue Encode(Queue queue, JsonSerializer serializer) + private static JsonValue _Encode(Queue queue, JsonSerializer serializer) { var array = new JsonArray(); for (int i = 0; i < queue.Count; i++) @@ -21,7 +21,7 @@ private static JsonValue Encode(Queue queue, JsonSerializer serializer) } return array; } - private static Queue Decode(JsonValue json, JsonSerializer serializer) + private static Queue _Decode(JsonValue json, JsonSerializer serializer) { var queue = new Queue(); for (int i = 0; i < json.Array.Count; i++) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs index 5b79b67..d867d4b 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs @@ -11,8 +11,8 @@ internal abstract class SerializationDelegateProviderBase : ISerializationDelega protected SerializationDelegateProviderBase() { - _encodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("Encode"); - _decodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("Decode"); + _encodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("_Encode"); + _decodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("_Decode"); } public abstract bool CanHandle(Type type); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs index 2eda461..2991b6e 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs @@ -12,7 +12,7 @@ public override bool CanHandle(Type type) return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); } - private static JsonValue Encode(Stack stack, JsonSerializer serializer) + private static JsonValue _Encode(Stack stack, JsonSerializer serializer) { var array = new JsonArray(); for (int i = 0; i < stack.Count; i++) @@ -21,7 +21,7 @@ private static JsonValue Encode(Stack stack, JsonSerializer serializer) } return array; } - private static Stack Decode(JsonValue json, JsonSerializer serializer) + private static Stack _Decode(JsonValue json, JsonSerializer serializer) { var stack = new Stack(); for (int i = 0; i < json.Array.Count; i++) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs index 158df07..62a1585 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs @@ -9,11 +9,11 @@ public override bool CanHandle(Type type) return type == typeof(TimeSpan); } - private static JsonValue Encode(TimeSpan ts, JsonSerializer serializer) + private static JsonValue _Encode(TimeSpan ts, JsonSerializer serializer) { return ts.ToString(); } - private static TimeSpan Decode(JsonValue json, JsonSerializer serializer) + private static TimeSpan _Decode(JsonValue json, JsonSerializer serializer) { return json.Type == JsonValueType.String ? TimeSpan.Parse(json.String) : default(TimeSpan); } diff --git a/Manatee.Json/Serialization/Internal/SerializerCache.cs b/Manatee.Json/Serialization/Internal/SerializerCache.cs index ab5447c..37679b2 100644 --- a/Manatee.Json/Serialization/Internal/SerializerCache.cs +++ b/Manatee.Json/Serialization/Internal/SerializerCache.cs @@ -15,17 +15,17 @@ static SerializerCache() public static MethodInfo GetSerializeMethod(Type type) { - var pair = EnsureMethodPair(type); + var pair = _EnsureMethodPair(type); return pair.Serializer; } public static MethodInfo GetDeserializeMethod(Type type) { - var pair = EnsureMethodPair(type); + var pair = _EnsureMethodPair(type); return pair.Deserializer; } - private static SerializerMethodPair EnsureMethodPair(Type type) + private static SerializerMethodPair _EnsureMethodPair(Type type) { SerializerMethodPair pair; if (!_cache.TryGetValue(type, out pair)) diff --git a/Manatee.Json/Serialization/Internal/SerializerFactory.cs b/Manatee.Json/Serialization/Internal/SerializerFactory.cs index b128c8a..10bfb83 100644 --- a/Manatee.Json/Serialization/Internal/SerializerFactory.cs +++ b/Manatee.Json/Serialization/Internal/SerializerFactory.cs @@ -56,41 +56,41 @@ public static ISerializer GetSerializer(JsonSerializerOptions options, JsonVa var typeToSerialize = JsonSerializationAbstractionMap.GetMap(type); var typeInfo = typeToSerialize.GetTypeInfo(); if (typeof (IJsonSchema).GetTypeInfo().IsAssignableFrom(typeInfo)) - return BuildSerializer(_schemaSerializer); + return _BuildSerializer(_schemaSerializer); if (JsonSerializationTypeRegistry.IsRegistered(typeToSerialize)) - return BuildSerializer(_registeredObjectSerializer); + return _BuildSerializer(_registeredObjectSerializer); if (typeof (IJsonSerializable).GetTypeInfo().IsAssignableFrom(typeInfo)) - return BuildSerializer(_jsonSerializableSerializer); + return _BuildSerializer(_jsonSerializableSerializer); if (typeof (Enum).GetTypeInfo().IsAssignableFrom(typeInfo)) { if (json != null) { if (json.Type == JsonValueType.Number) - return BuildSerializer(_enumValueSerializer); + return _BuildSerializer(_enumValueSerializer); if (json.Type == JsonValueType.String) - return BuildSerializer(_enumNameSerializer); + return _BuildSerializer(_enumNameSerializer); } switch (options.EnumSerializationFormat) { case EnumSerializationFormat.AsInteger: - return BuildSerializer(_enumValueSerializer); + return _BuildSerializer(_enumValueSerializer); case EnumSerializationFormat.AsName: - return BuildSerializer(_enumNameSerializer); + return _BuildSerializer(_enumNameSerializer); default: throw new ArgumentOutOfRangeException(); } } ISerializer serializer; if (_library.TryGetValue(typeToSerialize, out serializer)) - return BuildSerializer(serializer); - return BuildSerializer(_autoSerializer); + return _BuildSerializer(serializer); + return _BuildSerializer(_autoSerializer); } public static ITypeSerializer GetTypeSerializer(JsonSerializerOptions options) { return _autoSerializer; } - private static ISerializer BuildSerializer(ISerializer innerSerializer) + private static ISerializer _BuildSerializer(ISerializer innerSerializer) { return new DefaultValueSerializer(new ReferencingSerializer(innerSerializer)); } diff --git a/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs b/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs index cf023e4..03f2555 100644 --- a/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs +++ b/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs @@ -5,21 +5,21 @@ namespace Manatee.Json.Serialization.Internal { internal class SerializerMethodPair { - public MethodInfo Serializer { get; private set; } - public MethodInfo Deserializer { get; private set; } + public MethodInfo Serializer { get; } + public MethodInfo Deserializer { get; } public SerializerMethodPair(Type type) { - Serializer = GetTypedSerializeMethod(type); - Deserializer = GetTypedDeserializeMethod(type); + Serializer = _GetTypedSerializeMethod(type); + Deserializer = _GetTypedDeserializeMethod(type); } - private static MethodInfo GetTypedSerializeMethod(Type type) + private static MethodInfo _GetTypedSerializeMethod(Type type) { return typeof(JsonSerializer).GetTypeInfo().GetDeclaredMethod("Serialize") .MakeGenericMethod(type); } - private static MethodInfo GetTypedDeserializeMethod(Type type) + private static MethodInfo _GetTypedDeserializeMethod(Type type) { return typeof(JsonSerializer).GetTypeInfo().GetDeclaredMethod("Deserialize") .MakeGenericMethod(type); diff --git a/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs index c0de1af..adffcbe 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs @@ -21,8 +21,8 @@ public JsonValue Serialize(T obj, JsonSerializer serializer) json.Add(Constants.TypeKey, type.AssemblyQualifiedName); } var propertyList = ReflectionCache.GetMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = SerializeValues(obj, serializer, propertyList); - ConstructJsonObject(json, map); + var map = _SerializeValues(obj, serializer, propertyList); + _ConstructJsonObject(json, map); return json.Count == 0 ? JsonValue.Null : json; } public JsonValue SerializeType(JsonSerializer serializer) @@ -30,8 +30,8 @@ public JsonValue SerializeType(JsonSerializer serializer) var json = new JsonObject(); var type = typeof (T); var propertyList = ReflectionCache.GetTypeMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = SerializeTypeValues(serializer, propertyList); - ConstructJsonObject(json, map); + var map = _SerializeTypeValues(serializer, propertyList); + _ConstructJsonObject(json, map); return json.Count == 0 ? JsonValue.Null : json; } public T Deserialize(JsonValue json, JsonSerializer serializer) @@ -39,30 +39,29 @@ public T Deserialize(JsonValue json, JsonSerializer serializer) var obj = JsonSerializationAbstractionMap.CreateInstance(json, serializer.Options.Resolver); var type = obj.GetType(); var propertyList = ReflectionCache.GetMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = DeserializeValues(obj, json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); + var map = _DeserializeValues(obj, json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); if ((json.Object.Count > 0) && (serializer.Options.InvalidPropertyKeyBehavior == InvalidPropertyKeyBehavior.ThrowException)) throw new TypeDoesNotContainPropertyException(type, json); - AssignObjectProperties(obj, map); + _AssignObjectProperties(obj, map); return obj; } public void DeserializeType(JsonValue json, JsonSerializer serializer) { var type = typeof (T); var propertyList = ReflectionCache.GetTypeMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = DeserializeTypeValues(json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); + var map = _DeserializeTypeValues(json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); if ((json.Object.Count > 0) && (serializer.Options.InvalidPropertyKeyBehavior == InvalidPropertyKeyBehavior.ThrowException)) throw new TypeDoesNotContainPropertyException(type, json); - AssignObjectProperties(null, map); + _AssignObjectProperties(null, map); } - private static Dictionary SerializeValues(T obj, JsonSerializer serializer, IEnumerable properties) + private static Dictionary _SerializeValues(T obj, JsonSerializer serializer, IEnumerable properties) { var dict = new Dictionary(); foreach (var property in properties) { object value; Type type; - var propertyInfo = property.MemberInfo as PropertyInfo; - if (propertyInfo != null) + if (property.MemberInfo is PropertyInfo propertyInfo) { if (propertyInfo.GetIndexParameters().Any()) continue; value = propertyInfo.GetValue(obj, null); @@ -71,7 +70,7 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) } else { - var fieldInfo = (FieldInfo) property.MemberInfo; + var fieldInfo = (FieldInfo)property.MemberInfo; value = fieldInfo.GetValue(obj); if (value == null && !serializer.Options.EncodeDefaultValues) continue; type = fieldInfo.FieldType; @@ -85,22 +84,21 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) if ((json == JsonValue.Null) && !serializer.Options.EncodeDefaultValues) continue; if (serializer.Options.IncludeContentSample && json.Type == JsonValueType.Array) { - AddSample(type, json.Array, serializer); + _AddSample(type, json.Array, serializer); } dict.Add(property, json); } return dict; } - private static Dictionary SerializeTypeValues(JsonSerializer serializer, IEnumerable properties) + private static Dictionary _SerializeTypeValues(JsonSerializer serializer, IEnumerable properties) { var dict = new Dictionary(); foreach (var memberInfo in properties) { object value; Type type; - var propertyInfo = memberInfo.MemberInfo as PropertyInfo; - if (propertyInfo != null) + if (memberInfo.MemberInfo is PropertyInfo propertyInfo) { if (propertyInfo.GetIndexParameters().Any()) continue; value = propertyInfo.GetValue(null, null); @@ -109,7 +107,7 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) } else { - var fieldInfo = (FieldInfo) memberInfo.MemberInfo; + var fieldInfo = (FieldInfo)memberInfo.MemberInfo; value = fieldInfo.GetValue(null); if (value == null) continue; type = fieldInfo.FieldType; @@ -121,14 +119,14 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) } return dict; } - private static void ConstructJsonObject(JsonObject json, Dictionary memberMap) + private static void _ConstructJsonObject(JsonObject json, Dictionary memberMap) { foreach (var memberInfo in memberMap.Keys) { json.Add(memberInfo.SerializationName, memberMap[memberInfo]); } } - private static Dictionary DeserializeValues(T obj, JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) + private static Dictionary _DeserializeValues(T obj, JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) { var dict = new Dictionary(); foreach (var memberInfo in members) @@ -141,10 +139,10 @@ private static void ConstructJsonObject(JsonObject json, Dictionary DeserializeTypeValues(JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) + private static Dictionary _DeserializeTypeValues(JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) { var dict = new Dictionary(); foreach (var memberInfo in members) @@ -208,7 +206,7 @@ private static void ConstructJsonObject(JsonObject json, Dictionary memberMap) + private static void _AssignObjectProperties(object obj, Dictionary memberMap) { foreach (var entry in memberMap) { @@ -219,15 +217,15 @@ private static void AssignObjectProperties(object obj, Dictionary(T obj, JsonSerializer serializer) } public T Deserialize(JsonValue json, JsonSerializer serializer) { - if (json.Type == JsonValueType.Null) return default(T); - return _innerSerializer.Deserialize(json, serializer); + return json.Type == JsonValueType.Null + ? default(T) + : _innerSerializer.Deserialize(json, serializer); } } } \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs index 81166c7..cf30bed 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; -using System.ComponentModel; +using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal.Serializers { @@ -21,18 +20,18 @@ private class Description public JsonValue Serialize(T obj, JsonSerializer serializer) { - EnsureDescriptions(); + _EnsureDescriptions(); var attributes = typeof (T).GetTypeInfo().GetCustomAttributes(typeof (FlagsAttribute), false); if (!attributes.Any()) { var entry = _descriptions[typeof (T)].FirstOrDefault(d => Equals(d.Value, obj)); return entry == null ? obj.ToString() : entry.String; } - return BuildFlagsValues(obj, serializer.Options.FlagsEnumSeparator); + return _BuildFlagsValues(obj, serializer.Options.FlagsEnumSeparator); } public T Deserialize(JsonValue json, JsonSerializer serializer) { - EnsureDescriptions(); + _EnsureDescriptions(); var options = serializer.Options.CaseSensitiveDeserialization ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; @@ -44,7 +43,7 @@ public T Deserialize(JsonValue json, JsonSerializer serializer) return (T) entry.Value; } - private static void EnsureDescriptions() + private static void _EnsureDescriptions() { lock (_descriptions) { @@ -52,18 +51,18 @@ private static void EnsureDescriptions() if (_descriptions.ContainsKey(type)) return; var names = Enum.GetValues(type).Cast(); - var descriptions = names.Select(n => new Description { Value = n, String = GetDescription(n.ToString()) }).ToList(); + var descriptions = names.Select(n => new Description { Value = n, String = _GetDescription(n.ToString()) }).ToList(); _descriptions.Add(type, descriptions); } } - private static string GetDescription(string name) + private static string _GetDescription(string name) { - var type = typeof (T); + var type = typeof(T); var memInfo = type.GetTypeInfo().GetDeclaredField(name); - var attributes = memInfo.GetCustomAttributes(typeof (DescriptionAttribute), false); - return attributes.Any() ? ((DescriptionAttribute)attributes.First()).Description : name; + var attributes = memInfo.GetCustomAttributes(typeof(DisplayAttribute), false); + return attributes.Any() ? ((DisplayAttribute) attributes.First()).Description : name; } - private static string BuildFlagsValues(T obj, string separator) + private static string _BuildFlagsValues(T obj, string separator) { var descriptions = _descriptions[typeof (T)]; var value = Convert.ToInt64(obj); diff --git a/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs index e3f7877..2a5b97c 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs @@ -8,7 +8,7 @@ internal class NumericSerializer : ISerializer public JsonValue Serialize(T obj, JsonSerializer serializer) { - double value = Convert.ToDouble(obj); + var value = Convert.ToDouble(obj); return value; } public T Deserialize(JsonValue json, JsonSerializer serializer) diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index 744d336..838bac5 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -65,40 +65,38 @@ private static IEnumerable _GetFields(ReflectionInfo info) } private static ReflectionInfo _InitializeInstanceCache(Type type) { - ReflectionInfo info; - if (!_instanceCache.TryGetValue(type, out info)) + if (!_instanceCache.TryGetValue(type, out ReflectionInfo info)) { var read = _GetInstanceProperties(type).Where(p => !p.SetMethod.IsPublic) - .Where(p => p.GetMethod.IsPublic) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(_BuildSerializationInfo); + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); var readWrite = _GetInstanceProperties(type).Where(p => p.SetMethod.IsPublic) - .Where(p => p.GetMethod.IsPublic) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(_BuildSerializationInfo); + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); var fields = _GetInstanceFields(type).Where(p => !p.IsInitOnly) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(_BuildSerializationInfo); + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); _instanceCache[type] = info = new ReflectionInfo(read, readWrite, fields); } return info; } private static ReflectionInfo _InitializeStaticCache(Type type) { - ReflectionInfo info; - if (!_staticCache.TryGetValue(type, out info)) + if (!_staticCache.TryGetValue(type, out ReflectionInfo info)) { var read = _GetStaticProperties(type).Where(p => !p.SetMethod.IsPublic) - .Where(p => p.GetMethod.IsPublic) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(_BuildSerializationInfo); + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); var readWrite = _GetStaticProperties(type).Where(p => p.SetMethod.IsPublic) - .Where(p => p.GetMethod.IsPublic) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(_BuildSerializationInfo); + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); var fields = _GetStaticFields(type).Where(p => !p.IsInitOnly) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(_BuildSerializationInfo); + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); _staticCache[type] = info = new ReflectionInfo(read, readWrite, fields); } return info; diff --git a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs index 9ef98fa..8bd1703 100644 --- a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs @@ -34,7 +34,7 @@ public static JsonValue FromType(JsonSerializer serializer) serializer.Options.IncludeContentSample = true; _generatedTypes = new List(); - var instance = BuildInstance(serializer.Options); + var instance = _BuildInstance(serializer.Options); var json = serializer.Serialize(instance); @@ -43,7 +43,7 @@ public static JsonValue FromType(JsonSerializer serializer) return json; } - private static T BuildInstance(JsonSerializerOptions options) + private static T _BuildInstance(JsonSerializerOptions options) { var type = typeof (T); @@ -65,16 +65,16 @@ private static T BuildInstance(JsonSerializerOptions options) else { instance = JsonSerializationAbstractionMap.CreateInstance(null, options.Resolver); - FillProperties(instance, options); + _FillProperties(instance, options); if (options.AutoSerializeFields) - FillFields(instance, options); + _FillFields(instance, options); } _defaultInstances[type] = instance; return instance; } - private static void FillProperties(T instance, JsonSerializerOptions options) + private static void _FillProperties(T instance, JsonSerializerOptions options) { var type = typeof (T); @@ -87,11 +87,11 @@ private static void FillProperties(T instance, JsonSerializerOptions options) var propertyType = propertyInfo.PropertyType; var indexParameters = propertyInfo.GetIndexParameters().ToList(); if (indexParameters.Any()) continue; - var value = GetValue(options, propertyType); + var value = _GetValue(options, propertyType); propertyInfo.SetValue(instance, value, null); } } - private static void FillFields(T instance, JsonSerializerOptions options) + private static void _FillFields(T instance, JsonSerializerOptions options) { var fields = typeof (T).GetTypeInfo().DeclaredFields .Where(p => !p.IsInitOnly) @@ -104,7 +104,7 @@ private static void FillFields(T instance, JsonSerializerOptions options) fieldInfo.SetValue(instance, value); } } - private static object GetValue(JsonSerializerOptions options, Type propertyType) + private static object _GetValue(JsonSerializerOptions options, Type propertyType) { var buildMethod = GetBuildMethod(propertyType); var value = buildMethod.Invoke(null, new object[] {options}); @@ -112,8 +112,7 @@ private static object GetValue(JsonSerializerOptions options, Type propertyType) } internal static MethodInfo GetBuildMethod(Type type) { - MethodInfo methodInfo; - if (!_buildMethods.TryGetValue(type, out methodInfo)) + if (!_buildMethods.TryGetValue(type, out MethodInfo methodInfo)) { methodInfo = _buildMethod.MakeGenericMethod(type); _buildMethods[type] = methodInfo; diff --git a/Manatee.Json/Serialization/Internal/TypeGenerator.cs b/Manatee.Json/Serialization/Internal/TypeGenerator.cs index 1fccff8..45780ee 100644 --- a/Manatee.Json/Serialization/Internal/TypeGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TypeGenerator.cs @@ -10,7 +10,7 @@ namespace Manatee.Json.Serialization.Internal { internal static class TypeGenerator { - public const string AssemblyName = "Manatee.Json.DynamicTypes"; + private const string AssemblyName = "Manatee.Json.DynamicTypes"; private static readonly AssemblyBuilder _assemblyBuilder; private static readonly ModuleBuilder _moduleBuilder; @@ -27,8 +27,7 @@ static TypeGenerator() public static T Generate() { var type = typeof (T); - TypeInfo concreteType; - if (!_cache.TryGetValue(type, out concreteType)) + if (!_cache.TryGetValue(type, out TypeInfo concreteType)) { var typeInfo = type.GetTypeInfo(); if (!typeInfo.IsInterface) @@ -40,8 +39,8 @@ public static T Generate() .Any(a => a.AssemblyName == AssemblyName); if (!internalsVisible) throw new ArgumentException($"Type generation only works for accessible interface types. Type '{type}' is not accessible. " + - $"If possible, make the type public or add '[assembly:InternalsVisibleTo(\"{AssemblyName}\")] " + - $"to assembly '{assembly.FullName}'."); + $"If possible, make the type public or add '[assembly:InternalsVisibleTo(\"{AssemblyName}\")] " + + $"to assembly '{assembly.FullName}'."); } var typeBuilder = _CreateTypeBuilder(type); _ImplementProperties(typeBuilder); diff --git a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs index 0784c66..fda7945 100644 --- a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs +++ b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs @@ -35,7 +35,7 @@ static JsonSerializationAbstractionMap() throw new JsonTypeMapException(); var tAbstract = typeof (TAbstract); var tConcrete = typeof (TConcrete); - MapTypes(tAbstract, tConcrete, mappingBehavior); + _MapTypes(tAbstract, tConcrete, mappingBehavior); } /// /// Applies a mapping from an open generic abstraction to an open generic concrete type. @@ -52,7 +52,7 @@ public static void MapGeneric(Type tAbstract, Type tConcrete, MapBaseAbstraction throw new JsonTypeMapException(tAbstract, tConcrete); if (!tConcrete.InheritsFrom(tAbstract)) throw new JsonTypeMapException(tAbstract, tConcrete); - MapTypes(tAbstract, tConcrete, mappingBehavior); + _MapTypes(tAbstract, tConcrete, mappingBehavior); } /// /// Removes a previously-assigned mapping. @@ -62,8 +62,7 @@ public static void MapGeneric(Type tAbstract, Type tConcrete, MapBaseAbstraction public static void RemoveMap(bool removeRelated = true) { var tAbstract = typeof (TAbstract); - Type tConcrete; - if (!_registry.TryGetValue(tAbstract, out tConcrete)) return; + if (!_registry.TryGetValue(tAbstract, out Type tConcrete)) return; _registry.Remove(tAbstract); if (!removeRelated) return; @@ -82,8 +81,7 @@ public static void RemoveMap(bool removeRelated = true) public static Type GetMap(Type type) { if (!type.GetTypeInfo().IsAbstract && !type.GetTypeInfo().IsInterface) return type; - Type tConcrete; - if (_registry.TryGetValue(type, out tConcrete)) return tConcrete; + if (_registry.TryGetValue(type, out Type tConcrete)) return tConcrete; if (type.GetTypeInfo().IsGenericType) { @@ -108,8 +106,7 @@ internal static T CreateInstance(JsonValue json, IResolver resolver) var concrete = Type.GetType(json.Object[Constants.TypeKey].String); return (T) resolver.Resolve(concrete); } - Type tConcrete; - if (!_registry.TryGetValue(type, out tConcrete)) + if (!_registry.TryGetValue(type, out Type tConcrete)) { if (type.GetTypeInfo().IsGenericType) type = type.GetGenericTypeDefinition(); @@ -129,35 +126,33 @@ internal static T CreateInstance(JsonValue json, IResolver resolver) return resolver.Resolve(); } - private static void MapTypes(Type tAbstract, Type tConcrete, MapBaseAbstractionBehavior mappingBehavior) + private static void _MapTypes(Type tAbstract, Type tConcrete, MapBaseAbstractionBehavior mappingBehavior) { _registry[tAbstract] = tConcrete; switch (mappingBehavior) { case MapBaseAbstractionBehavior.Unmapped: - MapBaseTypes(tAbstract, tConcrete, false); + _MapBaseTypes(tAbstract, tConcrete, false); break; case MapBaseAbstractionBehavior.Override: - MapBaseTypes(tAbstract, tConcrete, true); + _MapBaseTypes(tAbstract, tConcrete, true); break; } } - private static void MapBaseTypes(Type tAbstract, Type tConcrete, bool overwrite) + private static void _MapBaseTypes(Type tAbstract, Type tConcrete, bool overwrite) { if (tAbstract == null) return; var tBase = tAbstract.GetTypeInfo().BaseType; - if ((tBase != null) && (overwrite || !_registry.ContainsKey(tBase))) - { + if (tBase != null && (overwrite || !_registry.ContainsKey(tBase))) _registry[tBase] = tConcrete; - } - MapBaseTypes(tBase, tConcrete, overwrite); + _MapBaseTypes(tBase, tConcrete, overwrite); foreach (var tInterface in tAbstract.GetTypeInfo().ImplementedInterfaces) { if (overwrite || !_registry.ContainsKey(tInterface)) { _registry[tInterface] = tConcrete; } - MapBaseTypes(tInterface, tConcrete, overwrite); + _MapBaseTypes(tInterface, tConcrete, overwrite); } } } diff --git a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs index 498b07e..3ae049b 100644 --- a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs +++ b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs @@ -48,7 +48,7 @@ static JsonSerializationTypeRegistry() .ToList(); _toJsonConverters = new Dictionary(); _fromJsonConverters = new Dictionary(); - _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetTypeInfo().GetDeclaredMethod("RegisterProviderDelegates"); + _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetTypeInfo().GetDeclaredMethod("_RegisterProviderDelegates"); } /// @@ -103,7 +103,7 @@ public static bool IsRegistered(Type type) internal static void Encode(this JsonSerializer serializer, T obj, out JsonValue json) { - var converter = GetToJsonConverter(); + var converter = _GetToJsonConverter(); if (converter == null) { json = null; @@ -116,7 +116,7 @@ internal static void Encode(this JsonSerializer serializer, T obj, out JsonVa } internal static void Decode(this JsonSerializer serializer, JsonValue json, out T obj) { - var converter = GetFromJsonConverter(); + var converter = _GetFromJsonConverter(); if (converter == null) { obj = default(T); @@ -128,18 +128,18 @@ internal static void Decode(this JsonSerializer serializer, JsonValue json, o } } - private static Delegate GetToJsonConverter() + private static Delegate _GetToJsonConverter() { var type = JsonSerializationAbstractionMap.GetMap(typeof(T)); return _toJsonConverters.ContainsKey(type) ? _toJsonConverters[type] : null; } - private static FromJsonDelegate GetFromJsonConverter() + private static FromJsonDelegate _GetFromJsonConverter() { var type = JsonSerializationAbstractionMap.GetMap(typeof (T)); return _fromJsonConverters.ContainsKey(type) ? (FromJsonDelegate) _fromJsonConverters[type] : null; } // ReSharper disable once UnusedMember.Local - private static void RegisterProviderDelegates(ISerializationDelegateProvider provider) + private static void _RegisterProviderDelegates(ISerializationDelegateProvider provider) { var type = typeof (T); _toJsonConverters[type] = provider.GetEncoder(); diff --git a/Manatee.Json/Serialization/JsonSerializer.cs b/Manatee.Json/Serialization/JsonSerializer.cs index 970cdaf..20b0e3c 100644 --- a/Manatee.Json/Serialization/JsonSerializer.cs +++ b/Manatee.Json/Serialization/JsonSerializer.cs @@ -20,7 +20,6 @@ public JsonSerializerOptions Options } internal SerializationPairCache SerializationMap { get; } = new SerializationPairCache(); - #region Public Methods /// /// Serializes an object to a JSON structure. /// @@ -92,6 +91,5 @@ public void DeserializeType(JsonValue json) var serializer = SerializerFactory.GetTypeSerializer(Options); serializer.DeserializeType(json, this); } - #endregion } } diff --git a/Manatee.Json/Serialization/TypeRegistrationException.cs b/Manatee.Json/Serialization/TypeRegistrationException.cs index 9243ab3..b5468e0 100644 --- a/Manatee.Json/Serialization/TypeRegistrationException.cs +++ b/Manatee.Json/Serialization/TypeRegistrationException.cs @@ -11,7 +11,7 @@ public class TypeRegistrationException : Exception /// /// Gets the type. /// - public Type Type { get; private set; } + public Type Type { get; } /// /// Initializes a new instance of the class. diff --git a/Manatee.Json/XmlExtensions.cs b/Manatee.Json/XmlExtensions.cs index 7355603..208669d 100644 --- a/Manatee.Json/XmlExtensions.cs +++ b/Manatee.Json/XmlExtensions.cs @@ -173,9 +173,8 @@ public static JsonValue ToJson(this IEnumerable xElements) private static bool _RequiresTypeAttribute(string value) { - double d; var s = value.ToLower(); - return s == "true" || s == "false" || s == "null" || double.TryParse(s, out d); + return s == "true" || s == "false" || s == "null" || double.TryParse(s, out double _); } private static JsonValue _GetValue(XElement xElement) { @@ -206,8 +205,7 @@ private static JsonValue _AttachAttributes(JsonValue json, XElement xElement) } private static JsonValue _ParseValue(string value) { - bool b; - if (bool.TryParse(value, out b)) + if (bool.TryParse(value, out bool b)) return b; double d; if (double.TryParse(value, out d)) @@ -256,37 +254,5 @@ private static XName _GetXName(string key) } return name; } - -#if !NETSTANDARD1_3 - /// - /// Converts an to an . - /// - /// An . - /// The construct of the . - /// Provided for convenience. - public static XElement ToXElement(this XmlNode node) - { - var xDoc = new XDocument(); - using (var xmlWriter = xDoc.CreateWriter()) - node.WriteTo(xmlWriter); - return xDoc.Root; - } - /// - /// Converts an to an . - /// - /// An . - /// The construct of the . - /// Provided for convenience. - public static XmlNode ToXmlNode(this XElement element) - { - using (var xmlReader = element.CreateReader()) - { - var xmlDoc = new XmlDocument(); - xmlDoc.Load(xmlReader); - return xmlDoc; - } - } - -#endif - } + } } From 02cbf8b97703c9e23b2519cc632c1d1645a63292 Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Sat, 17 Jun 2017 22:06:07 +1200 Subject: [PATCH 14/15] added performance tests to solution. having issues running them. --- .../Manatee.Json.Performance.csproj | 108 -------- Manatee.Json.Performance/Manatee.Json.snk | Bin 596 -> 0 bytes .../Properties/AssemblyInfo.cs | 36 --- .../Associate.cs | 96 +++---- .../Associates.json | 84 +++---- .../DeserializeTest.cs | 275 ++++++++++----------- .../Manatee.Json.Tests.Performance.csproj | 81 ++++++ .../ParseTest.cs | 74 +++--- .../Properties/AssemblyInfo.cs | 20 ++ Manatee.Json.Tests.Performance/packages.config | 6 + Manatee.Json.sln | 7 + 11 files changed, 378 insertions(+), 409 deletions(-) delete mode 100644 Manatee.Json.Performance/Manatee.Json.Performance.csproj delete mode 100644 Manatee.Json.Performance/Manatee.Json.snk delete mode 100644 Manatee.Json.Performance/Properties/AssemblyInfo.cs rename {Manatee.Json.Performance => Manatee.Json.Tests.Performance}/Associate.cs (92%) rename {Manatee.Json.Performance => Manatee.Json.Tests.Performance}/Associates.json (93%) rename {Manatee.Json.Performance => Manatee.Json.Tests.Performance}/DeserializeTest.cs (96%) create mode 100644 Manatee.Json.Tests.Performance/Manatee.Json.Tests.Performance.csproj rename {Manatee.Json.Performance => Manatee.Json.Tests.Performance}/ParseTest.cs (92%) create mode 100644 Manatee.Json.Tests.Performance/Properties/AssemblyInfo.cs create mode 100644 Manatee.Json.Tests.Performance/packages.config diff --git a/Manatee.Json.Performance/Manatee.Json.Performance.csproj b/Manatee.Json.Performance/Manatee.Json.Performance.csproj deleted file mode 100644 index d6f7360..0000000 --- a/Manatee.Json.Performance/Manatee.Json.Performance.csproj +++ /dev/null @@ -1,108 +0,0 @@ - - - - Debug - AnyCPU - {2F8A54FB-B395-4BE4-9DF8-D9A13BF1D4F5} - Library - Properties - Manatee.Json.Performance - Manatee.Json.Performance - v4.5 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages - False - UnitTest - - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - Always - - - - - - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7} - Manatee.Json-4.5 - - - - - - - False - - - False - - - False - - - False - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - \ No newline at end of file diff --git a/Manatee.Json.Performance/Manatee.Json.snk b/Manatee.Json.Performance/Manatee.Json.snk deleted file mode 100644 index da49a45c3ca97b2de2ac2320c77b986596047a2b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50098IlmVB;CMA>(sbmP)~tvl>$2*>@~ZdhHcbfAke( z{rFsZkg%J7jEpiJuLVF(e9f-lwSbMds-Ubcjxc3Vn_nDt#L?bd?%9>DgZ(zq4vXOZ z;unhp{01=SoNHKTDbmq zVY%LNP4D_$f}2Gkq*784IOnI>H_ziiTm9J%Jr7*({o}$)!bC7+YC=}AaO6Rafd+5K z*-NmE8B*$zj`+SbyQFD>Ot3@SKBS4S;Ql18L=^Q06+X(_`O5-=Fi@2QI3O4%4}tj- zVfy4~D=sMP!~z%>=;dVR2Qa+pno!|3c&kvJHy*@%6eas?zU~n~U?WBf(xWyW7o; zCVid$>KJ*M0*+i!;L#1}6SoMlZn7>sZ4M{+-aV?xKg`qc*7Jq!0er)t3$~!p>hml+ zx^GQ2UfUSw9JpBo)(bH9-N-u`0h)(xf4{4mKjKig;BuuOpK4hnS|GL;0X^W~lF~{K iwVEA}`oSv`K7x$QOwRdeD?Z#4T_9_%fXtz}nWZdNu^(js diff --git a/Manatee.Json.Performance/Properties/AssemblyInfo.cs b/Manatee.Json.Performance/Properties/AssemblyInfo.cs deleted file mode 100644 index a166f0e..0000000 --- a/Manatee.Json.Performance/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Manatee.Json.Performance")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("GameStop, Inc.")] -[assembly: AssemblyProduct("Manatee.Json.Performance")] -[assembly: AssemblyCopyright("Copyright © GameStop, Inc. 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("de798abf-79b3-4295-9a1a-d18b3894e8ef")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Manatee.Json.Performance/Associate.cs b/Manatee.Json.Tests.Performance/Associate.cs similarity index 92% rename from Manatee.Json.Performance/Associate.cs rename to Manatee.Json.Tests.Performance/Associate.cs index 6787942..c0639f5 100644 --- a/Manatee.Json.Performance/Associate.cs +++ b/Manatee.Json.Tests.Performance/Associate.cs @@ -1,48 +1,48 @@ -using Manatee.Json.Serialization; - -namespace Manatee.Json.Performance -{ - public class Associate - { - public string Id { get; set; } - - public string FamilyName { get; set; } - - public string GivenName { get; set; } - - public override string ToString() - { - return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); - } - } - - public class SerializableAssociate : IJsonSerializable - { - public string Id { get; set; } - - public string FamilyName { get; set; } - - public string GivenName { get; set; } - - public void FromJson(JsonValue json, JsonSerializer serializer) - { - Id = json.Object["id"].String; - FamilyName = json.Object["familyName"].String; - GivenName = json.Object["givenName"].String; - } - public JsonValue ToJson(JsonSerializer serializer) - { - var obj = new JsonObject - { - {"id", Id}, - {"familyName", FamilyName}, - {"givenName", GivenName}, - }; - return obj; - } - public override string ToString() - { - return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); - } - } -} +using Manatee.Json.Serialization; + +namespace Manatee.Json.Tests.Performance +{ + public class Associate + { + public string Id { get; set; } + + public string FamilyName { get; set; } + + public string GivenName { get; set; } + + public override string ToString() + { + return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); + } + } + + public class SerializableAssociate : IJsonSerializable + { + public string Id { get; set; } + + public string FamilyName { get; set; } + + public string GivenName { get; set; } + + public void FromJson(JsonValue json, JsonSerializer serializer) + { + Id = json.Object["id"].String; + FamilyName = json.Object["familyName"].String; + GivenName = json.Object["givenName"].String; + } + public JsonValue ToJson(JsonSerializer serializer) + { + var obj = new JsonObject + { + {"id", Id}, + {"familyName", FamilyName}, + {"givenName", GivenName}, + }; + return obj; + } + public override string ToString() + { + return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); + } + } +} diff --git a/Manatee.Json.Performance/Associates.json b/Manatee.Json.Tests.Performance/Associates.json similarity index 93% rename from Manatee.Json.Performance/Associates.json rename to Manatee.Json.Tests.Performance/Associates.json index 4edf3c4..13e9f28 100644 --- a/Manatee.Json.Performance/Associates.json +++ b/Manatee.Json.Tests.Performance/Associates.json @@ -1,43 +1,43 @@ -[ - { - "id": "123456", - "familyName": "User", - "givenName": "POS" - }, - { - "id": "234567", - "familyName": "MUNIZ", - "givenName": "D" - - }, - { - "id": "345678", - "familyName": "Medina", - "givenName": "John" - }, - { - "id": "456789", - "familyName": "Trott", - "givenName": "Stephanie" - }, - { - "id": "987654", - "familyName": "Gutierrez", - "givenName": "Adrian" - }, - { - "id": "876543", - "familyName": "Himmelheber", - "givenName": "Devin" - }, - { - "id": "765432", - "familyName": "Burriss", - "givenName": "Charles" - }, - { - "id": "654321", - "familyName": "Williams", - "givenName": "Nic" - } +[ + { + "id": "123456", + "familyName": "User", + "givenName": "POS" + }, + { + "id": "234567", + "familyName": "MUNIZ", + "givenName": "D" + + }, + { + "id": "345678", + "familyName": "Medina", + "givenName": "John" + }, + { + "id": "456789", + "familyName": "Trott", + "givenName": "Stephanie" + }, + { + "id": "987654", + "familyName": "Gutierrez", + "givenName": "Adrian" + }, + { + "id": "876543", + "familyName": "Himmelheber", + "givenName": "Devin" + }, + { + "id": "765432", + "familyName": "Burriss", + "givenName": "Charles" + }, + { + "id": "654321", + "familyName": "Williams", + "givenName": "Nic" + } ] \ No newline at end of file diff --git a/Manatee.Json.Performance/DeserializeTest.cs b/Manatee.Json.Tests.Performance/DeserializeTest.cs similarity index 96% rename from Manatee.Json.Performance/DeserializeTest.cs rename to Manatee.Json.Tests.Performance/DeserializeTest.cs index df62f78..f615622 100644 --- a/Manatee.Json.Performance/DeserializeTest.cs +++ b/Manatee.Json.Tests.Performance/DeserializeTest.cs @@ -1,138 +1,137 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using Manatee.Json.Serialization; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; -using JsonSerializer = Manatee.Json.Serialization.JsonSerializer; - -namespace Manatee.Json.Performance -{ - [TestClass] - [DeploymentItem("Associates.json")] - public class DeserializeTest - { - [TestMethod] - public void Performance_FullAutoSerialize_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0280016"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - var start = DateTime.Now; - var json = JsonValue.Parse(content); - var obj = serializer.Deserialize>(json); - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - start = DateTime.Now; - obj = JsonConvert.DeserializeObject>(content); - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - } - [TestMethod] - public void Performance_FullAutoSerialize_10000() - { - Console.WriteLine("Time To Beat: 00:00:01.6560947"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - var json = JsonValue.Parse(content); - obj = serializer.Deserialize>(json); - } - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - obj = JsonConvert.DeserializeObject>(content); - } - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - } - [TestMethod] - public void Performance_FullIJsonSerialize_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0230013"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - var start = DateTime.Now; - var json = JsonValue.Parse(content); - var obj = serializer.Deserialize>(json); - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - foreach (var serializableAssociate in obj) - { - Console.WriteLine("\t{0}", serializableAssociate); - } - start = DateTime.Now; - var obj2 = JsonConvert.DeserializeObject>(content); - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - foreach (var serializableAssociate in obj2) - { - Console.WriteLine("\t{0}", serializableAssociate); - } - } - [TestMethod] - public void Performance_FullIJsonSerialize_10000() - { - Console.WriteLine("Time To Beat: 00:00:00.6080608"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - var json = JsonValue.Parse(content); - obj = serializer.Deserialize>(json); - } - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - obj = JsonConvert.DeserializeObject>(content); - } - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - } - [TestMethod] - public void Performance_IJsonSerializeOnly_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0120012"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var json = JsonValue.Parse(content); - var start = DateTime.Now; - obj = serializer.Deserialize>(json); - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - } - [TestMethod] - public void Performance_IJsonSerializeOnly_10000() - { - Console.WriteLine("Time To Beat: 00:00:00.2130213"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var json = JsonValue.Parse(content); - var start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - obj = serializer.Deserialize>(json); - } - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using Manatee.Json.Serialization; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; +using JsonSerializer = Manatee.Json.Serialization.JsonSerializer; + +namespace Manatee.Json.Tests.Performance +{ + [TestClass] + [DeploymentItem("Associates.json")] + public class DeserializeTest + { + [TestMethod] + public void Performance_FullAutoSerialize_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0280016"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + var start = DateTime.Now; + var json = JsonValue.Parse(content); + var obj = serializer.Deserialize>(json); + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + start = DateTime.Now; + obj = JsonConvert.DeserializeObject>(content); + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + } + [TestMethod] + public void Performance_FullAutoSerialize_10000() + { + Console.WriteLine("Time To Beat: 00:00:01.6560947"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + var json = JsonValue.Parse(content); + obj = serializer.Deserialize>(json); + } + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + obj = JsonConvert.DeserializeObject>(content); + } + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + } + [TestMethod] + public void Performance_FullIJsonSerialize_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0230013"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + var start = DateTime.Now; + var json = JsonValue.Parse(content); + var obj = serializer.Deserialize>(json); + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + foreach (var serializableAssociate in obj) + { + Console.WriteLine("\t{0}", serializableAssociate); + } + start = DateTime.Now; + var obj2 = JsonConvert.DeserializeObject>(content); + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + foreach (var serializableAssociate in obj2) + { + Console.WriteLine("\t{0}", serializableAssociate); + } + } + [TestMethod] + public void Performance_FullIJsonSerialize_10000() + { + Console.WriteLine("Time To Beat: 00:00:00.6080608"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + var json = JsonValue.Parse(content); + obj = serializer.Deserialize>(json); + } + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + obj = JsonConvert.DeserializeObject>(content); + } + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + } + [TestMethod] + public void Performance_IJsonSerializeOnly_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0120012"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var json = JsonValue.Parse(content); + var start = DateTime.Now; + obj = serializer.Deserialize>(json); + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + } + [TestMethod] + public void Performance_IJsonSerializeOnly_10000() + { + Console.WriteLine("Time To Beat: 00:00:00.2130213"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var json = JsonValue.Parse(content); + var start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + obj = serializer.Deserialize>(json); + } + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + } + } +} diff --git a/Manatee.Json.Tests.Performance/Manatee.Json.Tests.Performance.csproj b/Manatee.Json.Tests.Performance/Manatee.Json.Tests.Performance.csproj new file mode 100644 index 0000000..2b09692 --- /dev/null +++ b/Manatee.Json.Tests.Performance/Manatee.Json.Tests.Performance.csproj @@ -0,0 +1,81 @@ + + + + + Debug + AnyCPU + {36A1A51A-B8AF-4492-828A-73390286D2F4} + Library + Properties + Manatee.Json.Tests.Performance + Manatee.Json.Tests.Performance + v4.6 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll + + + ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + + ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + + + + Always + + + + + + {7548217b-8c18-4ca5-a248-59889ef93cf5} + Manatee.Json + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/Manatee.Json.Performance/ParseTest.cs b/Manatee.Json.Tests.Performance/ParseTest.cs similarity index 92% rename from Manatee.Json.Performance/ParseTest.cs rename to Manatee.Json.Tests.Performance/ParseTest.cs index bf0cf8e..a307f05 100644 --- a/Manatee.Json.Performance/ParseTest.cs +++ b/Manatee.Json.Tests.Performance/ParseTest.cs @@ -1,38 +1,38 @@ -using System; -using System.IO; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Manatee.Json.Performance -{ - [TestClass] - [DeploymentItem("Associates.json")] - public class ParseTest - { - [TestMethod] - public void Performance_Parse_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0110006"); - var content = File.ReadAllText("Associates.json"); - var start = DateTime.Now; - var json = JsonValue.Parse(content); - var end = DateTime.Now; - Console.WriteLine(json); - Console.WriteLine(end - start); - } - [TestMethod] - public void Performance_Parse_10000() - { - Console.WriteLine("Time To Beat: 00:00:00.3410196"); - var content = File.ReadAllText("Associates.json"); - var start = DateTime.Now; - JsonValue json = null; - for (int i = 0; i < 10000; i++) - { - json = JsonValue.Parse(content); - } - var end = DateTime.Now; - Console.WriteLine(json); - Console.WriteLine(end - start); - } - } +using System; +using System.IO; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Manatee.Json.Tests.Performance +{ + [TestClass] + [DeploymentItem("Associates.json")] + public class ParseTest + { + [TestMethod] + public void Performance_Parse_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0110006"); + var content = File.ReadAllText("Associates.json"); + var start = DateTime.Now; + var json = JsonValue.Parse(content); + var end = DateTime.Now; + Console.WriteLine(json); + Console.WriteLine(end - start); + } + [TestMethod] + public void Performance_Parse_10000() + { + Console.WriteLine("Time To Beat: 00:00:00.3410196"); + var content = File.ReadAllText("Associates.json"); + var start = DateTime.Now; + JsonValue json = null; + for (int i = 0; i < 10000; i++) + { + json = JsonValue.Parse(content); + } + var end = DateTime.Now; + Console.WriteLine(json); + Console.WriteLine(end - start); + } + } } \ No newline at end of file diff --git a/Manatee.Json.Tests.Performance/Properties/AssemblyInfo.cs b/Manatee.Json.Tests.Performance/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a2366bc --- /dev/null +++ b/Manatee.Json.Tests.Performance/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Manatee.Json.Tests.Performance")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Manatee.Json.Tests.Performance")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] + +[assembly: Guid("36a1a51a-b8af-4492-828a-73390286d2f4")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Manatee.Json.Tests.Performance/packages.config b/Manatee.Json.Tests.Performance/packages.config new file mode 100644 index 0000000..4d73a3f --- /dev/null +++ b/Manatee.Json.Tests.Performance/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Manatee.Json.sln b/Manatee.Json.sln index 228257e..0bcc123 100644 --- a/Manatee.Json.sln +++ b/Manatee.Json.sln @@ -18,6 +18,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Manatee.Json", "Manatee.Jso EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests.Console", "Manatee.Json.Tests.Console\Manatee.Json.Tests.Console.csproj", "{861C40FB-5D2E-4051-A1F0-D9B9C5D74794}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests.Performance", "Manatee.Json.Tests.Performance\Manatee.Json.Tests.Performance.csproj", "{36A1A51A-B8AF-4492-828A-73390286D2F4}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -35,6 +37,10 @@ Global {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Debug|Any CPU.Build.0 = Debug|Any CPU {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.ActiveCfg = Release|Any CPU {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.Build.0 = Release|Any CPU + {36A1A51A-B8AF-4492-828A-73390286D2F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {36A1A51A-B8AF-4492-828A-73390286D2F4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {36A1A51A-B8AF-4492-828A-73390286D2F4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {36A1A51A-B8AF-4492-828A-73390286D2F4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -42,6 +48,7 @@ Global GlobalSection(NestedProjects) = preSolution {E74B7538-5E17-43C7-925B-33784945312E} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} {861C40FB-5D2E-4051-A1F0-D9B9C5D74794} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} + {36A1A51A-B8AF-4492-828A-73390286D2F4} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = Json.vsmdi From 307516115473c1760014fcf5c368f08d825df0fd Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Sat, 17 Jun 2017 23:00:21 +1200 Subject: [PATCH 15/15] removed performance project --- Manatee.Json.sln | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Manatee.Json.sln b/Manatee.Json.sln index 0bcc123..228257e 100644 --- a/Manatee.Json.sln +++ b/Manatee.Json.sln @@ -18,8 +18,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Manatee.Json", "Manatee.Jso EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests.Console", "Manatee.Json.Tests.Console\Manatee.Json.Tests.Console.csproj", "{861C40FB-5D2E-4051-A1F0-D9B9C5D74794}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests.Performance", "Manatee.Json.Tests.Performance\Manatee.Json.Tests.Performance.csproj", "{36A1A51A-B8AF-4492-828A-73390286D2F4}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -37,10 +35,6 @@ Global {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Debug|Any CPU.Build.0 = Debug|Any CPU {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.ActiveCfg = Release|Any CPU {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.Build.0 = Release|Any CPU - {36A1A51A-B8AF-4492-828A-73390286D2F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {36A1A51A-B8AF-4492-828A-73390286D2F4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {36A1A51A-B8AF-4492-828A-73390286D2F4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {36A1A51A-B8AF-4492-828A-73390286D2F4}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -48,7 +42,6 @@ Global GlobalSection(NestedProjects) = preSolution {E74B7538-5E17-43C7-925B-33784945312E} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} {861C40FB-5D2E-4051-A1F0-D9B9C5D74794} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} - {36A1A51A-B8AF-4492-828A-73390286D2F4} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = Json.vsmdi