Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,14 @@
[IDE0160] Convert to block scoped namespace
[IDE0260] Use pattern matching
[IDE0290] Use primary constructor
[IDE0300] Collection initialization can be simplified
[IDE0301] Collection initialization can be simplified
[IDE0305] Collection initialization can be simplified
[IDE1005] Delegate invocation can be simplified
[CA1200] Avoid using cref tags with a prefix
[CA1510] Use 'ArgumentNullException.ThrowIfNull' instead of explicitly throwing a new exception instance
[CA1716] rename parameter property so that it no longer conflicts with the reserved language keyword
[CA1720] Identifier 'xxx' contains type name
[CA2263] Prefer the generic overload 'System.Enum.GetValues<TEnum>()'
-->
<NoWarn>$(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;IDE0300;IDE0301;IDE0305;IDE1005;CA1200;CA1510;CA1716;CA1720;CA2263</NoWarn>
<NoWarn>$(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</NoWarn>
</PropertyGroup>

</Project>
2 changes: 1 addition & 1 deletion src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
};

Expand All @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2016,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");
Expand Down Expand Up @@ -2093,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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static string GenerateJsonConvertersArrayCode(CSharpGeneratorSettings set

private static List<string> GetJsonConverters(CSharpGeneratorSettings settings, IEnumerable<string>? additionalJsonConverters)
{
return (settings.JsonConverters ?? Array.Empty<string>()).Concat(additionalJsonConverters ?? Array.Empty<string>()).ToList();
return [.. settings.JsonConverters ?? [], .. additionalJsonConverters ?? []];
}

private static string GenerateForJsonLibrary(CSharpGeneratorSettings settings, List<string> jsonConverters, bool hasJsonConverters)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ namespace NJsonSchema.CodeGeneration.CSharp
/// <summary>Generates the property name for a given CSharp <see cref="JsonSchemaProperty"/>.</summary>
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 = ['*', ':', '-', '#', '&'];

/// <summary>Generates the property name.</summary>
/// <param name="property">The property.</param>
Expand Down
6 changes: 3 additions & 3 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ namespace NJsonSchema.CodeGeneration.CSharp
public class CSharpValueGenerator : ValueGeneratorBase
{
private readonly CSharpGeneratorSettings _settings;
private readonly List<string> _typesWithStringConstructor = new List<string>()
{
private readonly List<string> _typesWithStringConstructor =
[
"System.Guid",
"System.Uri"
};
];

/// <summary>Initializes a new instance of the <see cref="CSharpValueGenerator" /> class.</summary>
/// <param name="settings">The settings.</param>
Expand Down
7 changes: 4 additions & 3 deletions src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class SubClass2 : SubClass

public static Type[] GetTypes()
{
return new Type[] { typeof(SubClass3) };
return [typeof(SubClass3)];
}
}

Expand Down Expand Up @@ -88,11 +88,11 @@ public async Task When_JsonInheritanceConverter_is_used_then_inheritance_is_corr
{
Foo = "foo",
Bar = "bar",
SubElements = new List<SubClass>
{
SubElements =
[
new SubClass1 { Prop1 = "x" },
new SubClass3 { Prop2 = "x", Prop3 = "y"}
}
new SubClass3 { Prop2 = "x", Prop3 = "y" }
]
}
};

Expand Down Expand Up @@ -120,11 +120,11 @@ public async Task When_serializer_setting_is_changed_then_converter_uses_correct
{
Foo = "foo",
Bar = "bar",
SubElements = new List<SubClass>
{
SubElements =
[
new SubClass1 { Prop1 = "x" },
new SubClass3 { Prop2 = "x", Prop3 = "y"}
}
new SubClass3 { Prop2 = "x", Prop3 = "y" }
]
}
};

Expand Down Expand Up @@ -193,7 +193,7 @@ public async Task JsonInheritanceConverter_is_thread_safe()
}

//// Act
await Task.WhenAll(tasks.ToArray());
await Task.WhenAll([.. tasks]);

//// Assert
// No exceptions
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public void CanGetFriendlyErrorSuggestingUsingElsif()
{
TemplateDirectory = "Templates"
};
var templateFactory = new DefaultTemplateFactory(settings, Array.Empty<Assembly>());
var templateFactory = new DefaultTemplateFactory(settings, []);
var template1 = templateFactory.CreateTemplate("csharp", "elseif", new object());

// Act
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -131,7 +131,7 @@ protected transformOptions(options: RequestInit): Promise<RequestInit> {
}";

//// Act
var extensionCode = new TypeScriptExtensionCode(code, Array.Empty<string>(), new[] { "UseHttpCookiesForApi" });
var extensionCode = new TypeScriptExtensionCode(code, [], ["UseHttpCookiesForApi"]);

//// Assert
Assert.Empty(extensionCode.ExtensionClasses);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
ExtendedClasses = Array.Empty<string>();
ClassTypes = [];
ExtendedClasses = [];

InlineNamedDictionaries = false;
GenerateTypeCheckFunctions = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ namespace NJsonSchema.CodeGeneration.TypeScript
/// <summary>Generates the property name for a given TypeScript <see cref="JsonSchemaProperty"/>.</summary>
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 = ['*', ':', '-'];

/// <summary>Gets or sets the reserved names.</summary>
public HashSet<string> ReservedPropertyNames { get; set; } = new(StringComparer.Ordinal) { "constructor", "init", "fromJS", "toJSON" };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static IEnumerable<CodeArtifact> OrderByBaseDependency(this IEnumerable<C
var newResults = new List<CodeArtifact>(results);

// we need new list to iterate as we modify the original
var resultIterator = results as List<CodeArtifact> ?? newResults.ToList();
var resultIterator = results as List<CodeArtifact> ?? [.. newResults];
foreach (var result in resultIterator)
{
if (!string.IsNullOrEmpty(GetActualBaseName(result.BaseTypeName)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public CodeGeneratorSettingsBase()
#pragma warning restore CS8618
{
GenerateDefaultValues = true;
ExcludedTypeNames = Array.Empty<string>();
ExcludedTypeNames = [];
}

/// <summary>Gets or sets the schema type (default: JsonSchema).</summary>
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema.CodeGeneration/TypeResolverBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public abstract class TypeResolverBase
{
private readonly CodeGeneratorSettingsBase _settings;
internal readonly Dictionary<JsonSchema, string> _generatedTypeNames = new();
private readonly HashSet<string> _reservedTypeNames = new();
private readonly HashSet<string> _reservedTypeNames = [];

/// <summary>Initializes a new instance of the <see cref="TypeResolverBase" /> class.</summary>
/// <param name="settings">The settings.</param>
Expand Down
2 changes: 1 addition & 1 deletion src/NJsonSchema.Demo.Performance/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,8 @@ public override bool CanConvert(Type objectType)
}


private static readonly HashSet<string> ignoredExceptionProperties = new()
{
"Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult"
};
private static readonly HashSet<string> ignoredExceptionProperties =
["Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult"];

private static Dictionary<PropertyInfo, string> GetExceptionProperties(Type exceptionType)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Type>)method.Invoke(null, Array.Empty<object>());
var types = (System.Collections.Generic.IEnumerable<Type>)method.Invoke(null, []);
foreach (var knownType in types)
{
if (knownType.Name == discriminator)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public override bool IsStringEnum(ContextualType contextualType, NewtonsoftJsonS
converters.Add(new StringEnumConverter());
}

return x => JsonConvert.DeserializeObject<string?>(JsonConvert.SerializeObject(x, Formatting.None, converters.ToArray()));
return x => JsonConvert.DeserializeObject<string?>(JsonConvert.SerializeObject(x, Formatting.None, [.. converters]));
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public SimpleClass(decimal number)
public async Task When_multipleOf_is_fraction_then_it_is_validated_correctly()
{
//// Arrange
List<SimpleClass> testClasses = new List<SimpleClass>();
List<SimpleClass> testClasses = [];
for (int i = 0; i < 100; i++)
{
testClasses.Add(new SimpleClass((decimal)(0.1 * i)));
Expand Down
4 changes: 2 additions & 2 deletions src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string?> List { get; set; } = new List<string?>();
public List<string?> List { get; set; } = [];
}
#nullable restore

Expand Down
13 changes: 9 additions & 4 deletions src/NJsonSchema.Tests/Generation/ContractResolverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,15 @@ protected override JsonContract CreateContract(Type objectType)
return contract;
}

static HashSet<string> _systemConverters = new HashSet<string>(new[] {
"System.ComponentModel.ComponentConverter",
"System.ComponentModel.ReferenceConverter",
"System.ComponentModel.CollectionConverter" });
static HashSet<string> _systemConverters =
[
..new[]
{
"System.ComponentModel.ComponentConverter",
"System.ComponentModel.ReferenceConverter",
"System.ComponentModel.CollectionConverter"
}
];

public static bool CanNonSystemTypeDescriptorConvertString(Type type)
{
Expand Down
Loading