diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f062ef79d..16c4e934e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,7 +5,7 @@ # # - To turn off auto-generation set: # -# [GitHubActions (AutoGenerate = false)] +# [CustomGitHubActions (AutoGenerate = false)] # # - To trigger manual generation invoke: # @@ -33,6 +33,10 @@ jobs: name: windows-latest runs-on: windows-latest steps: + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 9.0 - uses: actions/checkout@v4 - name: 'Cache: .nuke/temp, ~/.nuget/packages' uses: actions/cache@v4 @@ -48,6 +52,7 @@ jobs: MYGET_API_KEY: ${{ secrets.MYGET_API_KEY }} - name: 'Publish: artifacts' uses: actions/upload-artifact@v4 + if: runner.os == 'Windows' with: name: artifacts path: artifacts @@ -55,6 +60,10 @@ jobs: name: ubuntu-latest runs-on: ubuntu-latest steps: + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 9.0 - uses: actions/checkout@v4 - name: 'Cache: .nuke/temp, ~/.nuget/packages' uses: actions/cache@v4 @@ -70,6 +79,7 @@ jobs: MYGET_API_KEY: ${{ secrets.MYGET_API_KEY }} - name: 'Publish: artifacts' uses: actions/upload-artifact@v4 + if: runner.os == 'Windows' with: name: artifacts path: artifacts diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 8e993f88d..41f2b2ff2 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -5,7 +5,7 @@ # # - To turn off auto-generation set: # -# [GitHubActions (AutoGenerate = false)] +# [CustomGitHubActions (AutoGenerate = false)] # # - To trigger manual generation invoke: # @@ -34,6 +34,10 @@ jobs: name: windows-latest runs-on: windows-latest steps: + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 9.0 - uses: actions/checkout@v4 - name: 'Cache: .nuke/temp, ~/.nuget/packages' uses: actions/cache@v4 @@ -48,6 +52,10 @@ jobs: name: ubuntu-latest runs-on: ubuntu-latest steps: + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 9.0 - uses: actions/checkout@v4 - name: 'Cache: .nuke/temp, ~/.nuget/packages' uses: actions/cache@v4 diff --git a/Directory.Build.props b/Directory.Build.props index ccc140a26..5c13ae385 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -33,12 +33,40 @@ latest-Recommended true - $(NoWarn);CA1200;CA1510;CA1716;CA1720 + $(NoWarn);IDE0005;IDE0008;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0057;IDE0059;IDE0060;IDE0074;IDE0078;IDE0083;IDE0090;IDE0100;IDE0130;IDE0160;IDE0260;IDE0290;IDE1005;CA1200;CA1510;CA1716;CA1720;CA2263 diff --git a/build/Build.CI.GitHubActions.cs b/build/Build.CI.GitHubActions.cs index 8591806a3..3daec2eef 100644 --- a/build/Build.CI.GitHubActions.cs +++ b/build/Build.CI.GitHubActions.cs @@ -1,6 +1,10 @@ +using System.Collections.Generic; using Nuke.Common.CI.GitHubActions; +using Nuke.Common.CI.GitHubActions.Configuration; +using Nuke.Common.Execution; +using Nuke.Common.Utilities; -[GitHubActions( +[CustomGitHubActions( "pr", GitHubActionsImage.WindowsLatest, GitHubActionsImage.UbuntuLatest, @@ -12,7 +16,7 @@ CacheKeyFiles = ["global.json", "src/**/*.csproj", "src/**/package.json"], ConcurrencyCancelInProgress = true) ] -[GitHubActions( +[CustomGitHubActions( "build", GitHubActionsImage.WindowsLatest, GitHubActionsImage.UbuntuLatest, @@ -21,8 +25,60 @@ OnPushIncludePaths = ["**/*.*"], OnPushExcludePaths = ["**/*.md"], PublishArtifacts = true, + PublishCondition = "runner.os == 'Windows'", InvokedTargets = [nameof(Compile), nameof(Test), nameof(Pack), nameof(Publish)], ImportSecrets = ["NUGET_API_KEY", "MYGET_API_KEY"], CacheKeyFiles = ["global.json", "src/**/*.csproj", "src/**/package.json"]) ] public partial class Build; + +class CustomGitHubActionsAttribute : GitHubActionsAttribute +{ + public CustomGitHubActionsAttribute(string name, GitHubActionsImage image, params GitHubActionsImage[] images) : base(name, image, images) + { + } + + protected override GitHubActionsJob GetJobs(GitHubActionsImage image, IReadOnlyCollection relevantTargets) + { + var job = base.GetJobs(image, relevantTargets); + + var newSteps = new List(job.Steps); + + // only need to list the ones that are missing from default image + newSteps.Insert(0, new GitHubActionsSetupDotNetStep(["9.0"])); + + job.Steps = newSteps.ToArray(); + return job; + } +} + +class GitHubActionsSetupDotNetStep : GitHubActionsStep +{ + public GitHubActionsSetupDotNetStep(string[] versions) + { + Versions = versions; + } + + string[] Versions { get; } + + public override void Write(CustomFileWriter writer) + { + writer.WriteLine("- uses: actions/setup-dotnet@v4"); + + using (writer.Indent()) + { + writer.WriteLine("with:"); + using (writer.Indent()) + { + writer.WriteLine("dotnet-version: |"); + using (writer.Indent()) + { + foreach (var version in Versions) + { + writer.WriteLine(version); + } + } + } + } + } +} \ No newline at end of file diff --git a/build/_build.csproj b/build/_build.csproj index d8b48b5fd..48b0b7dfe 100644 --- a/build/_build.csproj +++ b/build/_build.csproj @@ -22,6 +22,7 @@ + diff --git a/global.json b/global.json index 989a69caf..f15a95928 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "8.0.100", + "version": "9.0.100", "rollForward": "latestMinor" } } \ No newline at end of file diff --git a/src/NJsonSchema.Benchmark/Program.cs b/src/NJsonSchema.Benchmark/Program.cs index 2bf2ba8aa..1dd3a424d 100644 --- a/src/NJsonSchema.Benchmark/Program.cs +++ b/src/NJsonSchema.Benchmark/Program.cs @@ -10,7 +10,9 @@ public static void Main(string[] args) BenchmarkDotNet.Running.BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).RunAllJoined(); } +#pragma warning disable IDE0051 private static void RunCsharpBenchmark() +#pragma warning restore IDE0051 { var benchmark = new CsharpGeneratorBenchmark(); benchmark.Setup().GetAwaiter().GetResult(); diff --git a/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs b/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs index b9ab6021d..2006f8e90 100644 --- a/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs +++ b/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs @@ -61,7 +61,7 @@ public class WritingInstrument { public static Type[] GetKnownTypes() { - return new[] { typeof(Pen), typeof(Pencil) }; + return [typeof(Pen), typeof(Pencil)]; } public string Baz { get; set; } diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs index 4301c355d..4244eec55 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs @@ -30,7 +30,7 @@ public void When_using_NewtonsoftJson_with_JsonConverters_GenerateJsonSerializer var settings = new CSharpGeneratorSettings { JsonLibrary = CSharpJsonLibrary.NewtonsoftJson, - JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" } + JsonConverters = ["CustomConverter1", "CustomConverter2"] }; //// Act @@ -68,7 +68,7 @@ public void When_using_NewtonsoftJson_with_HandleReferences_and_JsonConverters_a { JsonLibrary = CSharpJsonLibrary.NewtonsoftJson, HandleReferences = true, - JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" }, + JsonConverters = ["CustomConverter1", "CustomConverter2"], JsonSerializerSettingsTransformationMethod = "TestJsonSerializerSettingsTransformationMethod", }; @@ -88,7 +88,7 @@ public void When_using_SystemTextJson_with_JsonConverters_GenerateJsonConverters var settings = new CSharpGeneratorSettings { JsonLibrary = CSharpJsonLibrary.SystemTextJson, - JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" } + JsonConverters = ["CustomConverter1", "CustomConverter2"] }; //// Act @@ -107,7 +107,7 @@ public void When_using_NewtonsoftJson_with_JsonConverters_GenerateJsonConverters var settings = new CSharpGeneratorSettings { JsonLibrary = CSharpJsonLibrary.NewtonsoftJson, - JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" } + JsonConverters = ["CustomConverter1", "CustomConverter2"] }; //// Act diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs index d1eb0b828..129d132bc 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs @@ -91,8 +91,10 @@ public async Task When_generating_CSharp_code_then_default_value_generates_expec }"); //// Act - var settings = new CSharpGeneratorSettings(); - settings.GenerateDefaultValues = true; + var settings = new CSharpGeneratorSettings + { + GenerateDefaultValues = true + }; var generator = new CSharpGenerator(document, settings); var code = generator.GenerateFile(); @@ -117,8 +119,10 @@ public async Task When_generating_CSharp_code_then_default_value_with_decimal_ge }"); //// Act - var settings = new CSharpGeneratorSettings(); - settings.GenerateDefaultValues = true; + var settings = new CSharpGeneratorSettings + { + GenerateDefaultValues = true + }; var generator = new CSharpGenerator(document, settings); var code = generator.GenerateFile(); @@ -149,8 +153,10 @@ public async Task When_generating_CSharp_code_then_default_value_of_dictionary_w }"); // Act - var settings = new CSharpGeneratorSettings(); - settings.GenerateDefaultValues = true; + var settings = new CSharpGeneratorSettings + { + GenerateDefaultValues = true + }; var generator = new CSharpGenerator(document, settings); var code = generator.GenerateFile(); @@ -181,8 +187,10 @@ public async Task When_generating_CSharp_code_then_default_value_of_array_of_arr }"); // Act - var settings = new CSharpGeneratorSettings(); - settings.GenerateDefaultValues = true; + var settings = new CSharpGeneratorSettings + { + GenerateDefaultValues = true + }; var generator = new CSharpGenerator(document, settings); var code = generator.GenerateFile(); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs index cd5fb9798..8bac3428a 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs @@ -66,14 +66,15 @@ public async Task When_code_is_generated_then_toolchain_version_is_printed() AssertCompile(output); } - class CustomPropertyNameGenerator : IPropertyNameGenerator + private class CustomPropertyNameGenerator : IPropertyNameGenerator { public string Generate(JsonSchemaProperty property) { return "MyCustom" + ConversionUtilities.ConvertToUpperCamelCase(property.Name, true); } } - class CustomTypeNameGenerator : ITypeNameGenerator + + private class CustomTypeNameGenerator : ITypeNameGenerator { public string Generate(JsonSchema schema, string typeNameHint, IEnumerable reservedTypeNames) { @@ -134,10 +135,12 @@ public async Task When_property_name_is_created_by_custom_fun_then_attribute_is_ //// Arrange var schema = NewtonsoftJsonSchemaGenerator.FromType(); var schemaData = schema.ToJson(); - var settings = new CSharpGeneratorSettings(); + var settings = new CSharpGeneratorSettings + { + TypeNameGenerator = new CustomTypeNameGenerator(), + PropertyNameGenerator = new CustomPropertyNameGenerator() + }; - settings.TypeNameGenerator = new CustomTypeNameGenerator(); - settings.PropertyNameGenerator = new CustomPropertyNameGenerator(); var generator = new CSharpGenerator(schema, settings); //// Act @@ -454,8 +457,10 @@ private static async Task CreateGeneratorAsync() { var schema = NewtonsoftJsonSchemaGenerator.FromType(); var schemaData = schema.ToJson(); - var settings = new CSharpGeneratorSettings(); - settings.Namespace = "MyNamespace"; + var settings = new CSharpGeneratorSettings + { + Namespace = "MyNamespace" + }; var generator = new CSharpGenerator(schema, settings); return generator; } @@ -664,11 +669,16 @@ public async Task When_patternProperties_is_set_with_string_value_type_then_corr public void When_object_has_generic_name_then_it_is_transformed() { //// Arrange - var schema = new JsonSchema(); - schema.Type = JsonObjectType.Object; - schema.Properties["foo"] = new JsonSchemaProperty + var schema = new JsonSchema { - Type = JsonObjectType.Number + Type = JsonObjectType.Object, + Properties = + { + ["foo"] = new JsonSchemaProperty + { + Type = JsonObjectType.Number + } + } }; //// Act @@ -2006,7 +2016,7 @@ public static Person FromJson(string data) var generator = await CreateGeneratorAsync(); generator.Settings.JsonLibrary = CSharpJsonLibrary.SystemTextJson; generator.Settings.GenerateJsonMethods = true; - generator.Settings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" }; + generator.Settings.JsonConverters = ["CustomConverter1", "CustomConverter2"]; //// Act var output = generator.GenerateFile("MyClass"); @@ -2083,7 +2093,7 @@ public static Person FromJson(string data) var generator = await CreateGeneratorAsync(); generator.Settings.JsonLibrary = CSharpJsonLibrary.NewtonsoftJson; generator.Settings.GenerateJsonMethods = true; - generator.Settings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" }; + generator.Settings.JsonConverters = ["CustomConverter1", "CustomConverter2"]; //// Act var output = generator.GenerateFile("MyClass"); diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs index de2fd2574..0174b18e7 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs @@ -144,7 +144,7 @@ private static void RenamePropertyWithSameNameAsClass(string typeName, IEnumerab number++; } - propertyWithSameNameAsClass.PropertyName = propertyWithSameNameAsClass.PropertyName + number; + propertyWithSameNameAsClass.PropertyName += number; } } diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs index 3f8e30e6d..67c265f3c 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs @@ -50,10 +50,9 @@ public CSharpGeneratorSettings() ValueGenerator = new CSharpValueGenerator(this); PropertyNameGenerator = new CSharpPropertyNameGenerator(); - TemplateFactory = new DefaultTemplateFactory(this, new Assembly[] - { + TemplateFactory = new DefaultTemplateFactory(this, [ typeof(CSharpGeneratorSettings).GetTypeInfo().Assembly - }); + ]); InlineNamedArrays = false; InlineNamedDictionaries = false; diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs index 815d8dd68..a3c3baa6e 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs @@ -40,7 +40,7 @@ public static string GenerateJsonConvertersArrayCode(CSharpGeneratorSettings set private static List GetJsonConverters(CSharpGeneratorSettings settings, IEnumerable? additionalJsonConverters) { - return (settings.JsonConverters ?? Array.Empty()).Concat(additionalJsonConverters ?? Array.Empty()).ToList(); + return [.. settings.JsonConverters ?? [], .. additionalJsonConverters ?? []]; } private static string GenerateForJsonLibrary(CSharpGeneratorSettings settings, List jsonConverters, bool hasJsonConverters) diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs index 2a42c6df8..0496cfed9 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs @@ -11,8 +11,9 @@ namespace NJsonSchema.CodeGeneration.CSharp /// Generates the property name for a given CSharp . public sealed class CSharpPropertyNameGenerator : IPropertyNameGenerator { - private static readonly char[] _reservedFirstPassChars = { '"', '\'', '@', '?', '!', '$', '[', ']', '(', ')', '.', '=', '+', '|' }; - private static readonly char[] _reservedSecondPassChars = { '*', ':', '-', '#', '&' }; + private static readonly char[] _reservedFirstPassChars = ['"', '\'', '@', '?', '!', '$', '[', ']', '(', ')', '.', '=', '+', '|' + ]; + private static readonly char[] _reservedSecondPassChars = ['*', ':', '-', '#', '&']; /// Generates the property name. /// The property. diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs index 5f329158e..4d7f369da 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs @@ -268,7 +268,9 @@ private string ResolveNumber(JsonSchema schema, bool isNullable) }; if (string.IsNullOrWhiteSpace(numberType)) + { numberType = "double"; + } return isNullable ? numberType + "?" : numberType; } diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs index 07356edf9..04fb5a1b2 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs @@ -17,11 +17,11 @@ namespace NJsonSchema.CodeGeneration.CSharp public class CSharpValueGenerator : ValueGeneratorBase { private readonly CSharpGeneratorSettings _settings; - private readonly List _typesWithStringConstructor = new List() - { + private readonly List _typesWithStringConstructor = + [ "System.Guid", "System.Uri" - }; + ]; /// Initializes a new instance of the class. /// The settings. diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs index 0855e9936..83d6bd0b0 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs @@ -168,7 +168,7 @@ private static bool TryGetInt64(object value, out long valueInt64) } else { - valueInt64 = default(long); + valueInt64 = default; return false; } } diff --git a/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj b/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj index 468231bfe..512925763 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj +++ b/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj @@ -2,7 +2,6 @@ netstandard2.0;net462 - bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml diff --git a/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs b/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs index fafb47efa..4a219de1e 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs @@ -44,7 +44,7 @@ public async Task When_string_and_integer_enum_used_then_two_enums_are_generated var code = generator.GenerateFile("MyClass"); //// Assert - Assert.Equal(3, code.Split(new[] { "export enum " }, StringSplitOptions.None).Count()); // two found + Assert.Equal(3, code.Split(["export enum "], StringSplitOptions.None).Count()); // two found } [Fact] @@ -104,8 +104,9 @@ public async Task When_string_and_integer_enum_used_then_one_enum_is_generated_i Assert.Contains("public enum Bar2\n", code); Assert.Contains(" B = 5,", code); // B must be 5 even if B = 1 is first defined - Assert.Equal(3, code.Split(new[] { "public enum " }, StringSplitOptions.None).Count()); // two found (one string and one integer based enum) - Assert.Equal(3, code.Split(new[] { "[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]" }, StringSplitOptions.None).Count()); // two found + Assert.Equal(3, code.Split(["public enum "], StringSplitOptions.None).Count()); // two found (one string and one integer based enum) + Assert.Equal(3, code.Split( + ["[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]"], StringSplitOptions.None).Count()); // two found } [Fact] diff --git a/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs b/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs index f93750e43..56c0f6a31 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs @@ -55,7 +55,7 @@ public class SubClass2 : SubClass public static Type[] GetTypes() { - return new Type[] { typeof(SubClass3) }; + return [typeof(SubClass3)]; } } @@ -88,11 +88,11 @@ public async Task When_JsonInheritanceConverter_is_used_then_inheritance_is_corr { Foo = "foo", Bar = "bar", - SubElements = new List - { + SubElements = + [ new SubClass1 { Prop1 = "x" }, - new SubClass3 { Prop2 = "x", Prop3 = "y"} - } + new SubClass3 { Prop2 = "x", Prop3 = "y" } + ] } }; @@ -120,11 +120,11 @@ public async Task When_serializer_setting_is_changed_then_converter_uses_correct { Foo = "foo", Bar = "bar", - SubElements = new List - { + SubElements = + [ new SubClass1 { Prop1 = "x" }, - new SubClass3 { Prop2 = "x", Prop3 = "y"} - } + new SubClass3 { Prop2 = "x", Prop3 = "y" } + ] } }; @@ -189,14 +189,11 @@ public async Task JsonInheritanceConverter_is_thread_safe() var tasks = new List(); for (int i = 0; i < 100; i++) { - tasks.Add(Task.Run(async () => - { - await When_JsonInheritanceConverter_is_used_then_inheritance_is_correctly_serialized_and_deserialized(); - })); + tasks.Add(Task.Run(When_JsonInheritanceConverter_is_used_then_inheritance_is_correctly_serialized_and_deserialized)); } //// Act - await Task.WhenAll(tasks.ToArray()); + await Task.WhenAll([.. tasks]); //// Assert // No exceptions @@ -300,12 +297,7 @@ public async Task Subtypes_are_serialized_with_correct_discriminator() var code = generator.GenerateFile(); var assembly = Compile(code); - var type = assembly.GetType("foo.Foo"); - if (type == null) - { - throw new Exception("Foo not found in " + String.Join(", ", assembly.GetTypes().Select(t => t.Name))); - } - + var type = assembly.GetType("foo.Foo") ?? throw new Exception("Foo not found in " + String.Join(", ", assembly.GetTypes().Select(t => t.Name))); var bar = JsonConvert.DeserializeObject(@"{""discriminator"":""bar""}", type); //// Assert @@ -331,19 +323,17 @@ private Assembly Compile(string code) MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Linq.Expressions.dll"), MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Runtime.Extensions.dll")); - using (var stream = new MemoryStream()) - { - var result = compilation.Emit(stream); - - if (!result.Success) - { - throw new Exception(String.Join(", ", result.Diagnostics - .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error) - .Select(d => d.Location.GetLineSpan().StartLinePosition + " - " + d.GetMessage())) + "\n" + code); - } + using var stream = new MemoryStream(); + var result = compilation.Emit(stream); - return Assembly.Load(stream.GetBuffer()); + if (!result.Success) + { + throw new Exception(String.Join(", ", result.Diagnostics + .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error) + .Select(d => d.Location.GetLineSpan().StartLinePosition + " - " + d.GetMessage())) + "\n" + code); } + + return Assembly.Load(stream.GetBuffer()); } } } diff --git a/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs b/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs index 37097d1ea..d341ef0e2 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs @@ -75,11 +75,11 @@ public void CanGetFriendlyErrorSuggestingUsingElsif() { TemplateDirectory = "Templates" }; - var templateFactory = new DefaultTemplateFactory(settings, Array.Empty()); + var templateFactory = new DefaultTemplateFactory(settings, []); var template1 = templateFactory.CreateTemplate("csharp", "elseif", new object()); // Act - var ex = Assert.Throws(() => template1.Render()); + var ex = Assert.Throws(template1.Render); // Assert Assert.Contains(", did you use 'elseif' instead of correct 'elsif'?", ex.Message); diff --git a/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj b/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj index cd1ef8ba1..a565cdf18 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj +++ b/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj @@ -3,7 +3,7 @@ net8.0;net472 false - $(NoWarn),1998,1591,618 + $(NoWarn),1998,1591,618,IDE1006 disable false diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs index 31c7da35b..3543fa461 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs @@ -57,7 +57,7 @@ public void When_extension_code_is_processed_then_code_and_classes_are_correctly var code = Code; //// Act - var extensionCode = new TypeScriptExtensionCode(code, new[] { "Foo", "Bar" }, new [] { "BaseClass" }); + var extensionCode = new TypeScriptExtensionCode(code, ["Foo", "Bar"], ["BaseClass"]); //// Assert Assert.True(extensionCode.ExtensionClasses.ContainsKey("Foo")); @@ -103,7 +103,7 @@ public async Task When_classes_have_extension_code_then_class_body_is_copied() //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { - ExtendedClasses = new[] { "Foo", "Bar" }, + ExtendedClasses = ["Foo", "Bar"], ExtensionCode = Code }); var code = generator.GenerateFile(); @@ -131,7 +131,7 @@ protected transformOptions(options: RequestInit): Promise { }"; //// Act - var extensionCode = new TypeScriptExtensionCode(code, Array.Empty(), new[] { "UseHttpCookiesForApi" }); + var extensionCode = new TypeScriptExtensionCode(code, [], ["UseHttpCookiesForApi"]); //// Assert Assert.Empty(extensionCode.ExtensionClasses); diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs index 7ca7f63bd..715a5557a 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs @@ -360,7 +360,7 @@ export class ExceptionBase extends generated.ExceptionBase { var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { ExtensionCode = extensionCode, - ExtendedClasses = new[] { "ExceptionBase" }, + ExtendedClasses = ["ExceptionBase"], }); //// Act diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj b/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj index 5227ca505..5f20732fa 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj +++ b/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj @@ -4,10 +4,6 @@ netstandard2.0;net462 - - bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml - - diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs index f6f5c9a0b..5c476c94f 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs @@ -53,8 +53,7 @@ public TypeScriptGenerator(object rootObject, TypeScriptGeneratorSettings settin /// The code. public override IEnumerable GenerateTypes() { - _extensionCode = _extensionCode ?? - new TypeScriptExtensionCode(Settings.ExtensionCode, Settings.ExtendedClasses); + _extensionCode ??= new TypeScriptExtensionCode(Settings.ExtensionCode, Settings.ExtendedClasses); return GenerateTypes(_extensionCode); } diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs index c627f1788..753832235 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs @@ -34,13 +34,12 @@ public TypeScriptGeneratorSettings() ValueGenerator = new TypeScriptValueGenerator(this); PropertyNameGenerator = new TypeScriptPropertyNameGenerator(); - TemplateFactory = new DefaultTemplateFactory(this, new Assembly[] - { + TemplateFactory = new DefaultTemplateFactory(this, [ typeof(TypeScriptGeneratorSettings).GetTypeInfo().Assembly - }); + ]); - ClassTypes = Array.Empty(); - ExtendedClasses = Array.Empty(); + ClassTypes = []; + ExtendedClasses = []; InlineNamedDictionaries = false; GenerateTypeCheckFunctions = false; diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs index 6f92c8e84..3ae5ff610 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs @@ -14,8 +14,8 @@ namespace NJsonSchema.CodeGeneration.TypeScript /// Generates the property name for a given TypeScript . public sealed class TypeScriptPropertyNameGenerator : IPropertyNameGenerator { - private static readonly char[] _reservedFirstPassChars = { '"', '@', '?', '.', '=', '+' }; - private static readonly char[] _reservedSecondPassChars = { '*', ':', '-' }; + private static readonly char[] _reservedFirstPassChars = ['"', '@', '?', '.', '=', '+']; + private static readonly char[] _reservedSecondPassChars = ['*', ':', '-']; /// Gets or sets the reserved names. public HashSet ReservedPropertyNames { get; set; } = new(StringComparer.Ordinal) { "constructor", "init", "fromJS", "toJSON" }; diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs index b61f02fd2..d400ae8db 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs @@ -310,7 +310,7 @@ private string ResolveArrayOrTuple(JsonSchema schema, string? typeNameHint, bool if (Settings.UseLeafType) { var itemTypes = Resolve(schema.Item, true, typeNameHint) // TODO: Make typeNameHint singular if possible - .Split(new[] { UnionPipe }, StringSplitOptions.RemoveEmptyEntries) + .Split([UnionPipe], StringSplitOptions.RemoveEmptyEntries) .Select(x => GetNullableItemType(schema, prefix + x)) .ToList(); diff --git a/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs b/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs index e53f6f4e3..56519326c 100644 --- a/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs +++ b/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs @@ -31,7 +31,7 @@ public static IEnumerable OrderByBaseDependency(this IEnumerable(results); // we need new list to iterate as we modify the original - var resultIterator = results as List ?? newResults.ToList(); + var resultIterator = results as List ?? [.. newResults]; foreach (var result in resultIterator) { if (!string.IsNullOrEmpty(GetActualBaseName(result.BaseTypeName))) diff --git a/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs b/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs index 1b08ecc9b..c89009fba 100644 --- a/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs +++ b/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs @@ -20,7 +20,7 @@ public CodeGeneratorSettingsBase() #pragma warning restore CS8618 { GenerateDefaultValues = true; - ExcludedTypeNames = Array.Empty(); + ExcludedTypeNames = []; } /// Gets or sets the schema type (default: JsonSchema). diff --git a/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs b/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs index 2f71e31be..75ee4db90 100644 --- a/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs +++ b/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs @@ -14,8 +14,7 @@ namespace NJsonSchema.CodeGeneration /// The default enumeration name generator. public class DefaultEnumNameGenerator : IEnumNameGenerator { - private readonly static Regex _invalidNameCharactersPattern = new Regex(@"[^\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]"); - private const string _defaultReplacementCharacter = "_"; + private static readonly Regex _invalidNameCharactersPattern = new Regex(@"[^\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]"); /// Generates the enumeration name/key of the given enumeration entry. /// The index of the enumeration value (check and ). diff --git a/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs b/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs index 9ded5c121..6206b7ce9 100644 --- a/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs +++ b/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs @@ -49,7 +49,7 @@ public ITemplate CreateTemplate(string language, string template, object model) return new LiquidTemplate( language, template, - (lang, name) => GetLiquidTemplate(lang, name), + GetLiquidTemplate, model, GetToolchainVersion(), _settings); @@ -91,10 +91,8 @@ protected virtual string GetEmbeddedLiquidTemplate(string language, string templ var resource = assembly.GetManifestResourceStream(resourceName); if (resource != null) { - using (var reader = new StreamReader(resource)) - { - return reader.ReadToEnd(); - } + using var reader = new StreamReader(resource); + return reader.ReadToEnd(); } throw new InvalidOperationException("Could not load template '" + template + "' for language '" + language + "'."); diff --git a/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs b/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs index c8d370aeb..a3048079b 100644 --- a/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs +++ b/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs @@ -16,7 +16,7 @@ public abstract class TypeResolverBase { private readonly CodeGeneratorSettingsBase _settings; internal readonly Dictionary _generatedTypeNames = new(); - private readonly HashSet _reservedTypeNames = new(); + private readonly HashSet _reservedTypeNames = []; /// Initializes a new instance of the class. /// The settings. diff --git a/src/NJsonSchema.Demo.Performance/Program.cs b/src/NJsonSchema.Demo.Performance/Program.cs index 1a83f85c8..65ccdf31a 100644 --- a/src/NJsonSchema.Demo.Performance/Program.cs +++ b/src/NJsonSchema.Demo.Performance/Program.cs @@ -62,7 +62,7 @@ public class WritingInstrument { public static Type[] GetKnownTypes() { - return new[] { typeof(Pen), typeof(Pencil) }; + return [typeof(Pen), typeof(Pencil)]; } public string Baz { get; set; } diff --git a/src/NJsonSchema.Demo/Program.cs b/src/NJsonSchema.Demo/Program.cs index 800f745cf..a5593010d 100644 --- a/src/NJsonSchema.Demo/Program.cs +++ b/src/NJsonSchema.Demo/Program.cs @@ -10,7 +10,7 @@ namespace NJsonSchema.Demo { public class Program { - static void Main(string[] args) + private static void Main(string[] args) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { diff --git a/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs b/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs index e68a8a3ea..edc0e6bc9 100644 --- a/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs +++ b/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs @@ -106,14 +106,13 @@ public override bool CanConvert(Type objectType) return null; } - var newSerializer = new JsonSerializer(); - newSerializer.ContractResolver = (IContractResolver)Activator.CreateInstance(serializer.ContractResolver.GetType()); + var newSerializer = new JsonSerializer + { + ContractResolver = (IContractResolver)Activator.CreateInstance(serializer.ContractResolver.GetType()) + }; var field = JsonExceptionConverter.GetField(typeof(DefaultContractResolver), "_sharedCache"); - if (field != null) - { - field.SetValue(newSerializer.ContractResolver, false); - } + field?.SetValue(newSerializer.ContractResolver, false); dynamic resolver = newSerializer.ContractResolver; if (newSerializer.ContractResolver.GetType().GetRuntimeProperty("IgnoreSerializableAttribute") != null) @@ -126,8 +125,7 @@ public override bool CanConvert(Type objectType) resolver.IgnoreSerializableInterface = true; } - JToken? token; - if (jObject.TryGetValue("discriminator", StringComparison.OrdinalIgnoreCase, out token)) + if (jObject.TryGetValue("discriminator", StringComparison.OrdinalIgnoreCase, out JToken? token)) { var discriminator = token.Value(); if (objectType.Name.Equals(discriminator, StringComparison.Ordinal) == false) @@ -175,10 +173,7 @@ public override bool CanConvert(Type objectType) else { field = JsonExceptionConverter.GetField(objectType, "_" + fieldNameSuffix); - if (field != null) - { - field.SetValue(value, propertyValue); - } + field?.SetValue(value, propertyValue); } } } @@ -205,10 +200,8 @@ public override bool CanConvert(Type objectType) } - private static readonly HashSet ignoredExceptionProperties = new() - { - "Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult" - }; + private static readonly HashSet ignoredExceptionProperties = + ["Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult"]; private static Dictionary GetExceptionProperties(Type exceptionType) { diff --git a/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs b/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs index aff50579c..dd9bbe644 100644 --- a/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs +++ b/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs @@ -268,7 +268,7 @@ protected virtual Type GetDiscriminatorType(JObject jObject, Type objectType, st var method = type.GetRuntimeMethod((string)attribute.MethodName, Type.EmptyTypes); if (method != null) { - var types = (System.Collections.Generic.IEnumerable)method.Invoke(null, Array.Empty()); + var types = (System.Collections.Generic.IEnumerable)method.Invoke(null, []); foreach (var knownType in types) { if (knownType.Name == discriminator) diff --git a/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonReflectionService.cs b/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonReflectionService.cs index 56bb7d58c..c01f44218 100644 --- a/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonReflectionService.cs +++ b/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonReflectionService.cs @@ -65,7 +65,7 @@ public override bool IsStringEnum(ContextualType contextualType, NewtonsoftJsonS converters.Add(new StringEnumConverter()); } - return x => JsonConvert.DeserializeObject(JsonConvert.SerializeObject(x, Formatting.None, converters.ToArray())); + return x => JsonConvert.DeserializeObject(JsonConvert.SerializeObject(x, Formatting.None, [.. converters])); } /// diff --git a/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonSchemaGeneratorSettings.cs b/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonSchemaGeneratorSettings.cs index dbab76a38..de1d80653 100644 --- a/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonSchemaGeneratorSettings.cs +++ b/src/NJsonSchema.NewtonsoftJson/Generation/NewtonsoftJsonSchemaGeneratorSettings.cs @@ -18,7 +18,7 @@ namespace NJsonSchema.NewtonsoftJson.Generation /// public class NewtonsoftJsonSchemaGeneratorSettings : JsonSchemaGeneratorSettings { - private Dictionary _cachedContracts = new Dictionary(); + private readonly Dictionary _cachedContracts = new(); private JsonSerializerSettings _serializerSettings; diff --git a/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs b/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs index 33012ea4d..3f5a2b2fc 100644 --- a/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs @@ -112,7 +112,7 @@ public SimpleClass(decimal number) public async Task When_multipleOf_is_fraction_then_it_is_validated_correctly() { //// Arrange - List testClasses = new List(); + List testClasses = []; for (int i = 0; i < 100; i++) { testClasses.Add(new SimpleClass((decimal)(0.1 * i))); diff --git a/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs b/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs index 5faa0f813..0b4755ee7 100644 --- a/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs @@ -32,9 +32,9 @@ public async Task When_property_is_JArray_then_schema_with_any_array_is_generate #nullable enable public class ClassWithArrayOfNullable { - public string?[] Array { get; set; } = new string?[0]; + public string?[] Array { get; set; } = []; - public List List { get; set; } = new List(); + public List List { get; set; } = []; } #nullable restore diff --git a/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs b/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs index 602f2d127..c1bc79318 100644 --- a/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs +++ b/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs @@ -68,10 +68,15 @@ protected override JsonContract CreateContract(Type objectType) return contract; } - static HashSet _systemConverters = new HashSet(new[] { - "System.ComponentModel.ComponentConverter", - "System.ComponentModel.ReferenceConverter", - "System.ComponentModel.CollectionConverter" }); + static HashSet _systemConverters = + [ + ..new[] + { + "System.ComponentModel.ComponentConverter", + "System.ComponentModel.ReferenceConverter", + "System.ComponentModel.CollectionConverter" + } + ]; public static bool CanNonSystemTypeDescriptorConvertString(Type type) { diff --git a/src/NJsonSchema.Tests/Generation/EnumTests.cs b/src/NJsonSchema.Tests/Generation/EnumTests.cs index 12682fcdb..f6816a336 100644 --- a/src/NJsonSchema.Tests/Generation/EnumTests.cs +++ b/src/NJsonSchema.Tests/Generation/EnumTests.cs @@ -46,8 +46,8 @@ public async Task When_enum_is_used_multiple_times_in_array_then_it_is_always_re var json = schema.ToJson(); // Assert - Assert.True(json.Split(new[] { "x-enumNames" }, StringSplitOptions.None).Length == 2); // enum is defined only once - Assert.True(json.Split(new[] { "\"$ref\": \"#/definitions/MetadataSchemaType\"" }, StringSplitOptions.None).Length == 3); // both classes reference the enum + Assert.True(json.Split(["x-enumNames"], StringSplitOptions.None).Length == 2); // enum is defined only once + Assert.True(json.Split(["\"$ref\": \"#/definitions/MetadataSchemaType\""], StringSplitOptions.None).Length == 3); // both classes reference the enum } public class ContainerWithEnumDictionary diff --git a/src/NJsonSchema.Tests/Generation/InheritanceTests.cs b/src/NJsonSchema.Tests/Generation/InheritanceTests.cs index 144bca65d..3f7ace08f 100644 --- a/src/NJsonSchema.Tests/Generation/InheritanceTests.cs +++ b/src/NJsonSchema.Tests/Generation/InheritanceTests.cs @@ -277,10 +277,10 @@ public async Task When_deserializing_object_with_inheritance_then_correct_type_i /// Act var vm = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { - Converters = new[] - { + Converters = + [ new JsonInheritanceConverter(typeof(CommonThingBase), "discriminator") - } + ] }); /// Assert diff --git a/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs b/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs index 187af502d..7cd0fe6bf 100644 --- a/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs @@ -40,7 +40,7 @@ public class WritingInstrument { public static Type[] GetKnownTypes() { - return new[] { typeof(Pen), typeof(Pencil) }; + return [typeof(Pen), typeof(Pencil)]; } public string Baz { get; set; } diff --git a/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs b/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs index 08419926f..873ce0e93 100644 --- a/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs +++ b/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs @@ -42,11 +42,11 @@ public class WithXmlAttribute private static WithoutXmlAttributesDefined Data => new WithoutXmlAttributesDefined() { Foo = "stringvalue", - StringArray = new[] { "S1" }, - IntArray = new[] { 1 }, - DoubleArray = new double[] { 1 }, - DecimalArray = new decimal[] { 1 }, - InternalItem = new[] { new WithoutXmlAttributeItem() { Name = "Test" } }, + StringArray = ["S1"], + IntArray = [1], + DoubleArray = [1], + DecimalArray = [1], + InternalItem = [new WithoutXmlAttributeItem() { Name = "Test" }], ShouldBeThisPropertyName = new WithXmlAttribute() { Name = "Test2" } }; @@ -273,11 +273,11 @@ public class WithXmlAttributeProperty { Foo = "stringvalue", MightBeAAttribute = "stringvalue", - StringArray = new[] { "S1" }, - TheInts = new[] { 1 }, - InternalItems = new[] { new WithXmlAttributeItem() { Name = "Test" } }, + StringArray = ["S1"], + TheInts = [1], + InternalItems = [new WithXmlAttributeItem() { Name = "Test" }], ReferenceProperty = new WithXmlAttributeProperty() { Name = "Test" }, - ExternalItems2 = new[] { new WithXmlAttributeItem2() { Name = "Test" } }, + ExternalItems2 = [new WithXmlAttributeItem2() { Name = "Test" }], }; public static string CreateTestXml() diff --git a/src/NJsonSchema.Tests/Validation/CustomValidationTests.cs b/src/NJsonSchema.Tests/Validation/CustomValidationTests.cs index 495375434..bb62721c0 100644 --- a/src/NJsonSchema.Tests/Validation/CustomValidationTests.cs +++ b/src/NJsonSchema.Tests/Validation/CustomValidationTests.cs @@ -33,9 +33,10 @@ public void When_format_date_time_correct_with_custom_validator_passed_then_no_e private class CustomDateTimeFormatValidator : IFormatValidator { - private readonly string[] _acceptableFormats = { + private readonly string[] _acceptableFormats = + [ "yyyy'-'MM'-'dd HH':'mm':'ss':'ff" - }; + ]; /// /// Gets the format attributes value. diff --git a/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs b/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs index 78976a636..e085280ae 100644 --- a/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs @@ -58,7 +58,7 @@ public void Validation_should_succeed_if_string_is_base64_formatted_with_trailin Format = "base64" }; - var value = Convert.ToBase64String(new byte[] { 101, 22, 87, 25 }); + var value = Convert.ToBase64String([101, 22, 87, 25]); var token = new JValue(value); //// Act @@ -78,7 +78,7 @@ public void Validation_should_succeed_if_string_is_byte_formatted_with_trailing_ Format = JsonFormatStrings.Byte }; - var value = Convert.ToBase64String(new byte[] { 101, 22, 87, 25 }); + var value = Convert.ToBase64String([101, 22, 87, 25]); var token = new JValue(value); //// Act @@ -98,7 +98,7 @@ public void Validation_should_succeed_if_string_is_base64_formatted_without_trai Format = "base64" }; - var value = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + var value = Convert.ToBase64String([1, 2, 3]); var token = new JValue(value); //// Act @@ -118,7 +118,7 @@ public void Validation_should_succeed_if_string_is_byte_formatted_without_traili Format = JsonFormatStrings.Byte }; - var value = Convert.ToBase64String(new byte[] { 1, 2, 3 }); + var value = Convert.ToBase64String([1, 2, 3]); var token = new JValue(value); //// Act diff --git a/src/NJsonSchema.Yaml.Tests/References/YamlReferencesTests.cs b/src/NJsonSchema.Yaml.Tests/References/YamlReferencesTests.cs index 610400d0f..11cc4e1ed 100644 --- a/src/NJsonSchema.Yaml.Tests/References/YamlReferencesTests.cs +++ b/src/NJsonSchema.Yaml.Tests/References/YamlReferencesTests.cs @@ -94,7 +94,7 @@ public async Task When_yaml_OpenAPI_spec_has_relative_external_schema_refs_in_su var schema = OK.Content["application/json"]; JsonSchemaProperty items = schema.Schema.ActualSchema.ActualProperties["items"]; var innerProperties = items.Item.ActualSchema.ActualProperties; - string[] expectedProperties = new string[] { "id", "systemName", "name", "smallImageID", "helpText" }; + string[] expectedProperties = ["id", "systemName", "name", "smallImageID", "helpText"]; foreach (string property in expectedProperties) { diff --git a/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs b/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs index 0b95cede8..6b24b52d7 100644 --- a/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs +++ b/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs @@ -28,8 +28,10 @@ public JsonAndYamlReferenceResolver(JsonSchemaAppender schemaAppender) /// The factory. public static Func CreateJsonAndYamlReferenceResolverFactory(ITypeNameGenerator typeNameGenerator) { - JsonReferenceResolver ReferenceResolverFactory(JsonSchema schema) => - new JsonAndYamlReferenceResolver(new JsonSchemaAppender(schema, typeNameGenerator)); + JsonReferenceResolver ReferenceResolverFactory(JsonSchema schema) + { + return new JsonAndYamlReferenceResolver(new JsonSchemaAppender(schema, typeNameGenerator)); + } return ReferenceResolverFactory; } diff --git a/src/NJsonSchema/Collections/ObservableDictionary.cs b/src/NJsonSchema/Collections/ObservableDictionary.cs index ce3315004..b93e82ebf 100644 --- a/src/NJsonSchema/Collections/ObservableDictionary.cs +++ b/src/NJsonSchema/Collections/ObservableDictionary.cs @@ -107,8 +107,7 @@ public void AddRange(IDictionary items) /// If true and key already exists then an exception is thrown. private void Insert(TKey key, TValue? value, bool add) { - TValue? item; - if (_dictionary.TryGetValue(key, out item)) + if (_dictionary.TryGetValue(key, out TValue? item)) { if (add) { @@ -216,9 +215,6 @@ public bool Remove(TKey key) throw new ArgumentNullException(nameof(key)); } - TValue? value; - _dictionary.TryGetValue(key, out value); - var removed = _dictionary.Remove(key); if (removed) { diff --git a/src/NJsonSchema/CompilerFeatures.cs b/src/NJsonSchema/CompilerFeatures.cs index d0b78f8b1..581104987 100644 --- a/src/NJsonSchema/CompilerFeatures.cs +++ b/src/NJsonSchema/CompilerFeatures.cs @@ -205,7 +205,7 @@ sealed class MemberNotNullAttribute : Attribute /// /// The field or property member that is promised to be not-null. /// - public MemberNotNullAttribute(string member) => Members = new[] { member }; + public MemberNotNullAttribute(string member) => Members = [member]; /// Initializes the attribute with the list of field and property members. /// @@ -236,7 +236,7 @@ sealed class MemberNotNullWhenAttribute : Attribute public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; - Members = new[] { member }; + Members = [member]; } /// Initializes the attribute with the specified return value condition and list of field and property members. diff --git a/src/NJsonSchema/ConversionUtilities.cs b/src/NJsonSchema/ConversionUtilities.cs index ec61f5474..35ab5fa97 100644 --- a/src/NJsonSchema/ConversionUtilities.cs +++ b/src/NJsonSchema/ConversionUtilities.cs @@ -162,7 +162,7 @@ public static string ConvertToCamelCase(string input) } - private static readonly char[] _whiteSpaceChars = { '\n', '\r', '\t', ' ' }; + private static readonly char[] _whiteSpaceChars = ['\n', '\r', '\t', ' ']; /// Trims white spaces from the text. /// The text. @@ -172,7 +172,7 @@ public static string TrimWhiteSpaces(string? text) return text?.Trim(_whiteSpaceChars) ?? string.Empty; } - private static readonly char[] _lineBreakTrimChars = { '\n', '\t', ' ' }; + private static readonly char[] _lineBreakTrimChars = ['\n', '\t', ' ']; /// Removes the line breaks from the text. /// The text. diff --git a/src/NJsonSchema/Converters/JsonInheritanceConverter.cs b/src/NJsonSchema/Converters/JsonInheritanceConverter.cs index bd356b81e..8951b303d 100644 --- a/src/NJsonSchema/Converters/JsonInheritanceConverter.cs +++ b/src/NJsonSchema/Converters/JsonInheritanceConverter.cs @@ -188,7 +188,7 @@ protected virtual Type GetDiscriminatorType(JsonElement jObject, Type objectType var method = type.GetRuntimeMethod((string)attribute.MethodName, Type.EmptyTypes); if (method != null) { - if (method.Invoke(null, Array.Empty()) is IEnumerable types) + if (method.Invoke(null, []) is IEnumerable types) { foreach (var knownType in types) { diff --git a/src/NJsonSchema/DefaultTypeNameGenerator.cs b/src/NJsonSchema/DefaultTypeNameGenerator.cs index cd29eae0a..33049d39d 100644 --- a/src/NJsonSchema/DefaultTypeNameGenerator.cs +++ b/src/NJsonSchema/DefaultTypeNameGenerator.cs @@ -17,10 +17,10 @@ namespace NJsonSchema /// Converts the last part of the full type name to upper case. public class DefaultTypeNameGenerator : ITypeNameGenerator { - private static readonly char[] TypeNameHintCleanupChars = { '[', ']', '<', '>', ',', ' ' }; + private static readonly char[] TypeNameHintCleanupChars = ['[', ']', '<', '>', ',', ' ']; private readonly Dictionary _typeNameMappings = new(); - private string[] _reservedTypeNames = { "object" }; + private string[] _reservedTypeNames = ["object"]; // TODO: Expose as options to UI and cmd line? diff --git a/src/NJsonSchema/Generation/JsonSchemaGenerator.cs b/src/NJsonSchema/Generation/JsonSchemaGenerator.cs index 92bf90463..44a43742b 100644 --- a/src/NJsonSchema/Generation/JsonSchemaGenerator.cs +++ b/src/NJsonSchema/Generation/JsonSchemaGenerator.cs @@ -270,7 +270,7 @@ public virtual TSchemaType GenerateWithReferenceAndNullability( } else { - schema.Type = schema.Type | JsonObjectType.Null; + schema.Type |= JsonObjectType.Null; } } else if (Settings.SchemaType == SchemaType.OpenApi3 || Settings.GenerateCustomNullableProperties) @@ -577,7 +577,7 @@ protected virtual void GenerateObject(JsonSchema schema, JsonTypeDescription typ { if (type == typeof(Exception)) { - return new[] { "InnerException", "Message", "Source", "StackTrace" }; + return ["InnerException", "Message", "Source", "StackTrace"]; } return null; diff --git a/src/NJsonSchema/Generation/JsonSchemaGeneratorSettings.cs b/src/NJsonSchema/Generation/JsonSchemaGeneratorSettings.cs index 63519b068..4b50cb3c3 100644 --- a/src/NJsonSchema/Generation/JsonSchemaGeneratorSettings.cs +++ b/src/NJsonSchema/Generation/JsonSchemaGeneratorSettings.cs @@ -36,7 +36,7 @@ public JsonSchemaGeneratorSettings(IReflectionService reflectionService) TypeNameGenerator = new DefaultTypeNameGenerator(); SchemaNameGenerator = new DefaultSchemaNameGenerator(); - ExcludedTypeNames = Array.Empty(); + ExcludedTypeNames = []; UseXmlDocumentation = true; ResolveExternalXmlDocumentation = true; diff --git a/src/NJsonSchema/Infrastructure/DynamicApis.cs b/src/NJsonSchema/Infrastructure/DynamicApis.cs index c14933be9..85c84c9b4 100644 --- a/src/NJsonSchema/Infrastructure/DynamicApis.cs +++ b/src/NJsonSchema/Infrastructure/DynamicApis.cs @@ -51,20 +51,18 @@ public static async Task HttpGetAsync(string url, CancellationToken canc throw new NotSupportedException("The System.Net.Http.HttpClient API is not available on this platform."); } - using (dynamic handler = (IDisposable)Activator.CreateInstance(HttpClientHandlerType!)!) - using (dynamic client = (IDisposable)Activator.CreateInstance(HttpClientType!, new[] { handler })!) - { - handler.UseDefaultCredentials = true; - - // enable all decompression methods - var calculatedAllValue = GenerateAllDecompressionMethodsEnumValue(); - var allDecompressionMethodsValue = Enum.ToObject(DecompressionMethodsType!, calculatedAllValue); - handler.AutomaticDecompression = (dynamic)allDecompressionMethodsValue; - - var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false); - response.EnsureSuccessStatusCode(); - return await response.Content.ReadAsStringAsync().ConfigureAwait(false); - } + using dynamic handler = (IDisposable)Activator.CreateInstance(HttpClientHandlerType!)!; + using dynamic client = (IDisposable)Activator.CreateInstance(HttpClientType!, [handler])!; + handler.UseDefaultCredentials = true; + + // enable all decompression methods + var calculatedAllValue = GenerateAllDecompressionMethodsEnumValue(); + var allDecompressionMethodsValue = Enum.ToObject(DecompressionMethodsType!, calculatedAllValue); + handler.AutomaticDecompression = (dynamic)allDecompressionMethodsValue; + + var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsStringAsync().ConfigureAwait(false); } // see https://learn.microsoft.com/en-us/dotnet/api/system.net.decompressionmethods?view=net-7.0 @@ -121,8 +119,6 @@ public static string HandleSubdirectoryRelativeReferences(string fullPath, strin if (Directory.Exists(fileDir)) { var fileName = Path.GetFileName(fullPath); - var pathPieces = fullPath.Replace("\\", "/").Split('/'); - var subDirPiece = pathPieces[pathPieces.Length - 2]; foreach (var subDir in Directory.GetDirectories(fileDir)) { var expectedFile = Path.Combine(subDir, fileName); diff --git a/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs b/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs index 405f630a7..d7a5919e8 100644 --- a/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs +++ b/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs @@ -34,7 +34,7 @@ public void IgnoreProperty(Type type, params string[] jsonPropertyNames) { if (!_ignores.TryGetValue(type.FullName!, out HashSet? value)) { - value = new HashSet(); + value = []; _ignores[type.FullName!] = value; } diff --git a/src/NJsonSchema/Infrastructure/TypeExtensions.cs b/src/NJsonSchema/Infrastructure/TypeExtensions.cs index 749a70baa..bad553547 100644 --- a/src/NJsonSchema/Infrastructure/TypeExtensions.cs +++ b/src/NJsonSchema/Infrastructure/TypeExtensions.cs @@ -19,8 +19,8 @@ namespace NJsonSchema.Infrastructure /// Provides extension methods for reading contextual type names and descriptions. public static class TypeExtensions { - private static ReaderWriterLockSlim _namesLock = new ReaderWriterLockSlim(); - private static Dictionary _names = new Dictionary(); + private static readonly ReaderWriterLockSlim _namesLock = new(); + private static readonly Dictionary _names = new(); /// Gets the name of the property for JSON serialization. /// The name. diff --git a/src/NJsonSchema/JsonPathUtilities.cs b/src/NJsonSchema/JsonPathUtilities.cs index e83462399..b027dc922 100644 --- a/src/NJsonSchema/JsonPathUtilities.cs +++ b/src/NJsonSchema/JsonPathUtilities.cs @@ -59,7 +59,7 @@ public static class JsonPathUtilities } var mappings = searchedObjects.ToDictionary(o => o, o => (string?)null); - FindJsonPaths(rootObject, mappings, "#", new HashSet(), contractResolver); + FindJsonPaths(rootObject, mappings, "#", [], contractResolver); if (mappings.Any(p => p.Value == null)) { diff --git a/src/NJsonSchema/JsonReferenceResolver.cs b/src/NJsonSchema/JsonReferenceResolver.cs index 40945342f..3f783cb53 100644 --- a/src/NJsonSchema/JsonReferenceResolver.cs +++ b/src/NJsonSchema/JsonReferenceResolver.cs @@ -40,8 +40,10 @@ public JsonReferenceResolver(JsonSchemaAppender schemaAppender) /// The factory. public static Func CreateJsonReferenceResolverFactory(ITypeNameGenerator typeNameGenerator) { - JsonReferenceResolver ReferenceResolverFactory(JsonSchema schema) => - new JsonReferenceResolver(new JsonSchemaAppender(schema, typeNameGenerator)); + JsonReferenceResolver ReferenceResolverFactory(JsonSchema schema) + { + return new JsonReferenceResolver(new JsonSchemaAppender(schema, typeNameGenerator)); + } return ReferenceResolverFactory; } @@ -99,16 +101,13 @@ private static string UnescapeReferenceSegment(string segment) public virtual IJsonReference ResolveDocumentReference(object rootObject, string jsonPath, Type targetType, IContractResolver contractResolver) { var allSegments = jsonPath.Split('/').Skip(1).ToList(); - for (int i = 0; i < allSegments.Count; i++) + for (var i = 0; i < allSegments.Count; i++) { allSegments[i] = UnescapeReferenceSegment(allSegments[i]); } - var schema = ResolveDocumentReference(rootObject, allSegments, targetType, contractResolver, new HashSet()); - if (schema == null) - { - throw new InvalidOperationException("Could not resolve the path '" + jsonPath + "'."); - } + var schema = ResolveDocumentReference(rootObject, allSegments, targetType, contractResolver, []) + ?? throw new InvalidOperationException($"Could not resolve the path '{jsonPath}'."); return schema; } @@ -299,8 +298,7 @@ private async Task ResolveUrlReferenceWithAlreadyResolvedCheckAs } else if (obj is IEnumerable) { - int index; - if (int.TryParse(firstSegment, out index)) + if (int.TryParse(firstSegment, out var index)) { var enumerable = ((IEnumerable)obj).Cast().ToArray(); if (enumerable.Length > index) diff --git a/src/NJsonSchema/JsonSchema.Reference.cs b/src/NJsonSchema/JsonSchema.Reference.cs index ee89538bd..7ebe8de7d 100644 --- a/src/NJsonSchema/JsonSchema.Reference.cs +++ b/src/NJsonSchema/JsonSchema.Reference.cs @@ -20,7 +20,7 @@ public partial class JsonSchema : JsonReferenceBase, IJsonReference /// Cyclic references detected. /// The schema reference path has not been resolved. [JsonIgnore] - public virtual JsonSchema ActualSchema => GetActualSchema(new List()); + public virtual JsonSchema ActualSchema => GetActualSchema([]); /// Gets the type actual schema (e.g. the shared schema of a property, parameter, etc.). /// Cyclic references detected. @@ -113,7 +113,7 @@ static void ThrowInvalidOperationException(string message) private JsonSchema? GetActualSchemaReferences(List checkedSchemas) { - checkedSchemas ??= new List(); + checkedSchemas ??= []; checkedSchemas.Add(this); if (HasAllOfSchemaReference) diff --git a/src/NJsonSchema/JsonSchema.Serialization.cs b/src/NJsonSchema/JsonSchema.Serialization.cs index ebdae8757..1c4ed931e 100644 --- a/src/NJsonSchema/JsonSchema.Serialization.cs +++ b/src/NJsonSchema/JsonSchema.Serialization.cs @@ -291,7 +291,7 @@ internal object? ItemsRaw { if (value is JArray) { - Items = new ObservableCollection(((JArray)value).Select(t => FromJsonWithCurrentSettings(t))); + Items = new ObservableCollection(((JArray)value).Select(FromJsonWithCurrentSettings)); } else if (value != null) { diff --git a/src/NJsonSchema/JsonSchema.cs b/src/NJsonSchema/JsonSchema.cs index 6a8b718eb..fd31ec1f8 100644 --- a/src/NJsonSchema/JsonSchema.cs +++ b/src/NJsonSchema/JsonSchema.cs @@ -30,7 +30,8 @@ namespace NJsonSchema /// A base class for describing a JSON schema. public partial class JsonSchema : IDocumentPathProvider { - internal static readonly HashSet JsonSchemaPropertiesCache = new HashSet(typeof(JsonSchema).GetContextualProperties().Select(p => p.Name).ToArray()); + internal static readonly HashSet JsonSchemaPropertiesCache = + [..typeof(JsonSchema).GetContextualProperties().Select(p => p.Name).ToArray()]; private const SchemaType SerializationSchemaType = SchemaType.JsonSchema; @@ -314,7 +315,7 @@ public IReadOnlyCollection AllInheritedSchemas new List { this.InheritedSchema } : new List(); - return inheritedSchema.Concat(inheritedSchema.SelectMany(s => s.AllInheritedSchemas)).ToList(); + return [.. inheritedSchema, .. inheritedSchema.SelectMany(s => s.AllInheritedSchemas)]; } } @@ -1075,7 +1076,7 @@ private void Initialize() if (EnumerationNames == null) { - EnumerationNames = new Collection(); + EnumerationNames = []; } } #pragma warning restore CS8774 diff --git a/src/NJsonSchema/NJsonSchema.csproj b/src/NJsonSchema/NJsonSchema.csproj index b334b4535..cd90198ba 100644 --- a/src/NJsonSchema/NJsonSchema.csproj +++ b/src/NJsonSchema/NJsonSchema.csproj @@ -1,7 +1,7 @@  - net6.0;netstandard2.0;net462 + net8.0;netstandard2.0;net462 @@ -17,7 +17,7 @@ - + diff --git a/src/NJsonSchema/OpenApiDiscriminator.cs b/src/NJsonSchema/OpenApiDiscriminator.cs index 40e782615..f57b44e54 100644 --- a/src/NJsonSchema/OpenApiDiscriminator.cs +++ b/src/NJsonSchema/OpenApiDiscriminator.cs @@ -37,11 +37,11 @@ public class OpenApiDiscriminator public void AddMapping(Type type, JsonSchema schema) { var getDiscriminatorValueMethod = JsonInheritanceConverter?.GetType() - .GetRuntimeMethod("GetDiscriminatorValue", new Type[] { typeof(Type) }); + .GetRuntimeMethod("GetDiscriminatorValue", [typeof(Type)]); if (getDiscriminatorValueMethod != null) { - var discriminatorValue = (string)getDiscriminatorValueMethod.Invoke(JsonInheritanceConverter, new[] { type } )!; + var discriminatorValue = (string)getDiscriminatorValueMethod.Invoke(JsonInheritanceConverter, [type])!; Mapping[discriminatorValue] = new JsonSchema { Reference = schema.ActualSchema }; } else diff --git a/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs b/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs index 22f4add90..b544c9150 100644 --- a/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs +++ b/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs @@ -15,7 +15,8 @@ namespace NJsonSchema.Validation.FormatValidators /// Validator for DateTime format. public class DateTimeFormatValidator : IFormatValidator { - private readonly string[] _acceptableFormats = new [] { + private readonly string[] _acceptableFormats = + [ "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK", "yyyy-MM-dd' 'HH:mm:ss.FFFFFFFK", "yyyy-MM-dd'T'HH:mm:ssK", @@ -31,7 +32,7 @@ public class DateTimeFormatValidator : IFormatValidator "yyyyMMdd", "yyyy-MM", "yyyy" - }; + ]; /// Gets the format attribute's value. public string Format { get; } = JsonFormatStrings.DateTime; diff --git a/src/NJsonSchema/Validation/JsonSchemaValidator.cs b/src/NJsonSchema/Validation/JsonSchemaValidator.cs index 1eef4442b..0b2d6e009 100644 --- a/src/NJsonSchema/Validation/JsonSchemaValidator.cs +++ b/src/NJsonSchema/Validation/JsonSchemaValidator.cs @@ -49,15 +49,13 @@ public JsonSchemaValidator(JsonSchemaValidatorSettings? settings) /// The list of validation errors. public ICollection Validate(string jsonData, JsonSchema schema, SchemaType schemaType = SchemaType.JsonSchema) { - using (var reader = new StringReader(jsonData)) - using (var jsonReader = new JsonTextReader(reader) + using var reader = new StringReader(jsonData); + using var jsonReader = new JsonTextReader(reader) { DateParseHandling = DateParseHandling.None - }) - { - var jsonObject = JToken.ReadFrom(jsonReader); - return Validate(jsonObject, schema, schemaType); - } + }; + var jsonObject = JToken.ReadFrom(jsonReader); + return Validate(jsonObject, schema, schemaType); } /// Validates the given JSON token. @@ -417,7 +415,7 @@ private static string GetPropertyPath(string propertyPath, string propertyName) return !string.IsNullOrEmpty(propertyPath) ? propertyPath + "." + propertyName : propertyName; } - private static void ValidateMaxProperties(JToken token, IList properties, JsonSchema schema, string? propertyName, string propertyPath, List errors) + private static void ValidateMaxProperties(JToken token, List properties, JsonSchema schema, string? propertyName, string propertyPath, List errors) { if (schema.MaxProperties > 0 && properties.Count > schema.MaxProperties) { @@ -425,7 +423,7 @@ private static void ValidateMaxProperties(JToken token, IList propert } } - private static void ValidateMinProperties(JToken token, IList properties, JsonSchema schema, string? propertyName, string propertyPath, List errors) + private static void ValidateMinProperties(JToken token, List properties, JsonSchema schema, string? propertyName, string propertyPath, List errors) { if (schema.MinProperties > 0 && properties.Count < schema.MinProperties) { diff --git a/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs b/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs index 361e91a1e..9ff4c5c9c 100644 --- a/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs +++ b/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs @@ -12,8 +12,8 @@ public class JsonSchemaValidatorSettings public StringComparer PropertyStringComparer { get; set; } = StringComparer.Ordinal; /// Gets or sets the format validators. - public IEnumerable FormatValidators { get; set; } = new IFormatValidator[] - { + public IEnumerable FormatValidators { get; set; } = + [ new DateTimeFormatValidator(), new DateFormatValidator(), new EmailFormatValidator(), @@ -27,7 +27,7 @@ public class JsonSchemaValidatorSettings new ByteFormatValidator(), new Base64FormatValidator(), new UuidFormatValidator() - }; + ]; /// /// Adds a custom format validator to the array. @@ -37,7 +37,7 @@ public void AddCustomFormatValidator(IFormatValidator formatValidator) { FormatValidators = this .FormatValidators - .Union(new[] { formatValidator }) + .Union([formatValidator]) .ToArray(); } }