Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ public class ModelBindingTests : IDisposable

private bool hasDisposed;

private JsonSerializerSettings options = new();

[TestInitialize]
public void TestInitialize()
{
var options = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
options.Converters.AddExtendableEnums();
this.options = options;
}

~ModelBindingTests()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing).
Expand All @@ -37,7 +50,7 @@ public async Task BindTheExtendableEnumCorrectlyGivenIntBasedValue()
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(true);
var book = JsonConvert.DeserializeObject<SampleBook>(responseContent);
var book = JsonConvert.DeserializeObject<SampleBook>(responseContent, this.options);

Assert.AreEqual(SampleStatus.Deleted, book?.Status);
}
Expand All @@ -59,7 +72,7 @@ public async Task BindTheExtendableEnumCorrectlyGivenNonExistentIntBasedValue()
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(true);
var book = JsonConvert.DeserializeObject<SampleBook>(responseContent);
var book = JsonConvert.DeserializeObject<SampleBook>(responseContent, this.options);

Assert.IsNull(book?.Status);
}
Expand All @@ -82,7 +95,7 @@ public async Task BindTheExtendableEnumCorrectlyGivenNullIntBasedValue()
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(true);
var book = JsonConvert.DeserializeObject<SampleBook>(responseContent);
var book = JsonConvert.DeserializeObject<SampleBook>(responseContent, this.options);

Assert.IsNull(book?.Status);
}
Expand All @@ -105,7 +118,7 @@ public async Task BindTheExtendableEnumCorrectlyGivenStringBasedValue()
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(true);
var book = JsonConvert.DeserializeObject<SampleBookByStringStatus>(responseContent);
var book = JsonConvert.DeserializeObject<SampleBookByStringStatus>(responseContent, this.options);

Assert.AreEqual(SampleStatusByString.Deleted, book?.Status);
}
Expand Down
14 changes: 10 additions & 4 deletions ExtendableEnums.Microsoft.AspNetCore/ExtendableEnumBinder.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using System;
using System.Threading.Tasks;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;

namespace ExtendableEnums.Microsoft.AspNetCore;

Expand All @@ -10,6 +8,13 @@ namespace ExtendableEnums.Microsoft.AspNetCore;
/// </summary>
public class ExtendableEnumBinder : IModelBinder
{
private JsonSerializerOptions jsonSerializerOptions;

public ExtendableEnumBinder(JsonSerializerOptions jsonSerializerOptions)
{
this.jsonSerializerOptions = jsonSerializerOptions;
}

/// <summary>
/// Attempts to bind a model.
/// </summary>
Expand Down Expand Up @@ -37,7 +42,8 @@ public Task BindModelAsync(ModelBindingContext bindingContext)
return Task.CompletedTask;
}

var result = JsonConvert.DeserializeObject($"'{valueProviderResult.FirstValue}'", bindingContext.ModelType);
var json = $"{{\"value\":\"{valueProviderResult.FirstValue}\"}}";
var result = JsonSerializer.Deserialize(json, returnType: bindingContext.ModelType, options: this.jsonSerializerOptions);

bindingContext.Result = ModelBindingResult.Success(result);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace ExtendableEnums.Microsoft.AspNetCore;

Expand All @@ -22,7 +24,8 @@ public class ExtendableEnumModelBinderProvider : IModelBinderProvider

if (context.Metadata.ModelType.IsExtendableEnum())
{
return new ExtendableEnumBinder();
var options = context.Services.GetRequiredService<IOptions<JsonOptions>>().Value;
return new ExtendableEnumBinder(options.JsonSerializerOptions);
}

return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,6 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ExtendableEnums\ExtendableEnums.csproj" />
<ProjectReference Include="..\ExtendableEnums.Serialization.System.Text.Json\ExtendableEnums.Serialization.System.Text.Json.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Collections;
using Newtonsoft.Json;
using ExtendableEnums;

namespace ExtendableEnums.Serialization.Newtonsoft;
namespace Newtonsoft.Json;

/// <summary>
/// Converts <see cref="ExtendableEnumDictionary{TKey, TValue}"/> objects to and from JSON.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Diagnostics;
using System.Globalization;
using ExtendableEnums.Internals;
using Newtonsoft.Json;
using ExtendableEnums;
using Newtonsoft.Json.Internals;

namespace ExtendableEnums.Serialization.Newtonsoft;
namespace Newtonsoft.Json;

/// <summary>
/// Converts ExtendableEnum objects to and from JSON.
Expand All @@ -17,7 +17,34 @@ public class ExtendableEnumJsonConverter : JsonConverter
/// <returns><c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.</returns>
public override bool CanConvert(Type objectType)
{
return true;
if (objectType is null)
{
throw new ArgumentNullException(nameof(objectType));
}

return IsExtendableEnum(objectType);
}

private static bool IsExtendableEnum(Type objectType)
{
if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ExtendableEnumBase<,>))
{
return true;
}

// traverse type hierarchy
var baseType = objectType.BaseType;
while (baseType != null)
{
if (baseType.IsGenericType && baseType.GetGenericTypeDefinition() == typeof(ExtendableEnumBase<,>))
{
return true;
}

baseType = baseType.BaseType;
}

return false;
}

/// <summary>
Expand Down Expand Up @@ -45,7 +72,13 @@ public override bool CanConvert(Type objectType)
throw new ArgumentNullException(nameof(serializer));
}

var valueType = objectType.GetExtendableEnumArgs()[1];
var enumArgs = objectType.GetExtendableEnumArgs();
if (enumArgs.Length < 2)
{
return null;
}

var valueType = enumArgs[1];

var rawValue = reader.Value;
if (rawValue is null)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>13.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<ApplicationVersion>9.1</ApplicationVersion>
<ApplicationRevision>0</ApplicationRevision>
<Version>9.1</Version>
<PackageProjectUrl>https://github.com/kyleherzog/ExtendableEnums</PackageProjectUrl>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>Enum Enumeration Extendable Class</PackageTags>
<RepositoryUrl>https://github.com/kyleherzog/ExtendableEnums</RepositoryUrl>
<Authors>Kyle Herzog</Authors>
<Description>A .NET Standard library that provides extendable class based enums.</Description>
<RootNamespace>Newtonsoft.Json</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.3.0.106239">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.406">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageReference Include="Text.Analyzers" Version="3.3.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ExtendableEnums\ExtendableEnums.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Collections.Concurrent;
using System.Reflection;

namespace ExtendableEnums.Internals;
namespace Newtonsoft.Json.Internals;

internal static class Methods
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace Newtonsoft.Json;

public static class JsonSerializerSettingsExtensions
{
/// <summary>
/// Adds custom converters required for serializing and deserializing extendable enums
/// to the specified list of JSON converters.
/// </summary>
/// <example>
/// Example usage:
/// <code>
/// var settings = new JsonSerializerSettings
/// {
/// Formatting = Formatting.Indented
/// };
///
/// // Add the custom converters
/// settings.Converters.AddExtendableEnums();
///
/// var json = JsonConvert.SerializeObject(yourObject, settings);
/// var obj = JsonConvert.DeserializeObject&lt;YourType&gt;(json, settings);
/// </code>
/// </example>
public static void AddExtendableEnums(this IList<JsonConverter> converters)
{
converters.Add(new ExtendableEnumJsonConverter());
converters.Add(new ExtendableEnumDictionaryJsonConverter());
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ExtendableEnums.Serialization.SystemText;
namespace ExtendableEnums.Serialization.System.Text.Json;

/// <summary>
/// Converts ExtendableEnum objects to and from JSON.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
using ExtendableEnums.Internals;
using ExtendableEnums.Serialization.System.Text.Json.Internals;

namespace ExtendableEnums.Serialization.SystemText;
namespace ExtendableEnums.Serialization.System.Text.Json;

/// <summary>
/// Converts ExtendableEnum objects to and from JSON.
Expand Down Expand Up @@ -90,10 +90,8 @@ public override void Write(Utf8JsonWriter writer, TEnumeration value, JsonSerial
{
return Activator.CreateInstance(t);
}
else
{
return null;
}

return null;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>13.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<ApplicationVersion>9.1</ApplicationVersion>
<ApplicationRevision>0</ApplicationRevision>
<Version>9.1</Version>
<PackageProjectUrl>https://github.com/kyleherzog/ExtendableEnums</PackageProjectUrl>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>Enum Enumeration Extendable Class</PackageTags>
<RepositoryUrl>https://github.com/kyleherzog/ExtendableEnums</RepositoryUrl>
<Authors>Kyle Herzog</Authors>
<Description>A .NET Standard library that provides extendable class based enums.</Description>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.3.0.106239">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.406">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageReference Include="System.Text.Json" Version="9.0.0" />
<PackageReference Include="Text.Analyzers" Version="3.3.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ExtendableEnums\ExtendableEnums.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Collections.Concurrent;
using System.Reflection;

namespace ExtendableEnums.Serialization.System.Text.Json.Internals;

internal static class Methods
{
private static readonly ConcurrentDictionary<Type, MethodInfo> parseValueOrCreateMethodCache = new();

internal static MethodInfo GetParseValueOrCreate(Type type)
{
return parseValueOrCreateMethodCache.GetOrAdd(type, t => t.GetMethod("ParseValueOrCreate", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy));
}
}
Loading