Skip to content

[Blazor] SupplyParameterFromForm dictionary support #48565

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 7, 2023
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

// Uses a concrete type that implements IDictionary<TKey, TValue> as a buffer.
internal sealed class DictionaryBufferAdapter<TDictionaryType, TKey, TValue>
: IDictionaryBufferAdapter<TDictionaryType, TDictionaryType, TKey, TValue>
where TDictionaryType : IDictionary<TKey, TValue>, new()
where TKey : IParsable<TKey>
{
public static TDictionaryType Add(ref TDictionaryType buffer, TKey key, TValue value)
{
buffer.Add(key, value);
return buffer;
}

public static TDictionaryType CreateBuffer() => new TDictionaryType();

public static TDictionaryType ToResult(TDictionaryType buffer) => buffer;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

// Adapts a concrete dictionary type into an interface.
internal sealed class DictionaryStaticCastAdapter<TDictionaryInterface, TDictionaryImplementation, TDictionaryAdapter, TBuffer, TKey, TValue>
: IDictionaryBufferAdapter<TDictionaryInterface, TBuffer, TKey, TValue>
where TDictionaryAdapter : IDictionaryBufferAdapter<TDictionaryImplementation, TBuffer, TKey, TValue>
where TDictionaryImplementation : TDictionaryInterface
where TKey : IParsable<TKey>
{
public static TBuffer CreateBuffer() => TDictionaryAdapter.CreateBuffer();

public static TBuffer Add(ref TBuffer buffer, TKey key, TValue element) => TDictionaryAdapter.Add(ref buffer, key, element);

public static TDictionaryInterface ToResult(TBuffer buffer) => TDictionaryAdapter.ToResult(buffer);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

// Interface for constructing a dictionary like instance using the
// dictionary converter.
// This interface abstracts over the different ways of constructing a dictionary.
// For example, Immutable types use a builder as a buffer, while other types
// use an instance of the dictionary itself as a buffer.
internal interface IDictionaryBufferAdapter<TDictionary, TBuffer, TKey, TValue>
where TKey : IParsable<TKey>
{
public static abstract TBuffer CreateBuffer();

public static abstract TBuffer Add(ref TBuffer buffer, TKey key, TValue value);

public static abstract TDictionary ToResult(TBuffer buffer);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

internal sealed class ImmutableDictionaryBufferAdapter<TKey, TValue>
: IDictionaryBufferAdapter<ImmutableDictionary<TKey, TValue>, ImmutableDictionary<TKey, TValue>.Builder, TKey, TValue>
where TKey : IParsable<TKey>
{
public static ImmutableDictionary<TKey, TValue>.Builder Add(ref ImmutableDictionary<TKey, TValue>.Builder buffer, TKey key, TValue value)
{
buffer.Add(key, value);
return buffer;
}

public static ImmutableDictionary<TKey, TValue>.Builder CreateBuffer() => ImmutableDictionary.CreateBuilder<TKey, TValue>();

public static ImmutableDictionary<TKey, TValue> ToResult(ImmutableDictionary<TKey, TValue>.Builder buffer) => buffer.ToImmutable();

internal static DictionaryConverter<IImmutableDictionary<TKey, TValue>> CreateInterfaceConverter(FormDataConverter<TValue> valueTypeConverter)
{
return new DictionaryConverter<IImmutableDictionary<TKey, TValue>,
DictionaryStaticCastAdapter<
IImmutableDictionary<TKey, TValue>,
ImmutableDictionary<TKey, TValue>,
ImmutableDictionaryBufferAdapter<TKey, TValue>,
ImmutableDictionary<TKey, TValue>.Builder,
TKey,
TValue>,
ImmutableDictionary<TKey, TValue>.Builder,
TKey,
TValue>(valueTypeConverter);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

internal sealed class ImmutableSortedDictionaryBufferAdapter<TKey, TValue>
: IDictionaryBufferAdapter<ImmutableSortedDictionary<TKey, TValue>, ImmutableSortedDictionary<TKey, TValue>.Builder, TKey, TValue>
where TKey : IParsable<TKey>
{
public static ImmutableSortedDictionary<TKey, TValue>.Builder Add(ref ImmutableSortedDictionary<TKey, TValue>.Builder buffer, TKey key, TValue value)
{
buffer.Add(key, value);
return buffer;
}

public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuffer() => ImmutableSortedDictionary.CreateBuilder<TKey, TValue>();

public static ImmutableSortedDictionary<TKey, TValue> ToResult(ImmutableSortedDictionary<TKey, TValue>.Builder buffer) => buffer.ToImmutable();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.ObjectModel;

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

internal sealed class ReadOnlyDictionaryBufferAdapter<TKey, TValue>
: IDictionaryBufferAdapter<ReadOnlyDictionary<TKey, TValue>, Dictionary<TKey, TValue>, TKey, TValue>
where TKey : IParsable<TKey>
{
public static Dictionary<TKey, TValue> Add(ref Dictionary<TKey, TValue> buffer, TKey key, TValue value)
{
buffer.Add(key, value);
return buffer;
}

public static Dictionary<TKey, TValue> CreateBuffer() =>
new Dictionary<TKey, TValue>();

public static ReadOnlyDictionary<TKey, TValue> ToResult(Dictionary<TKey, TValue> buffer) =>
new ReadOnlyDictionary<TKey, TValue>(buffer);

internal static DictionaryConverter<IReadOnlyDictionary<TKey, TValue>> CreateInterfaceConverter(FormDataConverter<TValue> valueTypeConverter)
{
return new DictionaryConverter<IReadOnlyDictionary<TKey, TValue>,
DictionaryStaticCastAdapter<
IReadOnlyDictionary<TKey, TValue>,
ReadOnlyDictionary<TKey, TValue>,
ReadOnlyDictionaryBufferAdapter<TKey, TValue>,
Dictionary<TKey, TValue>,
TKey,
TValue>,
Dictionary<TKey, TValue>,
TKey,
TValue>(valueTypeConverter);
}

internal static DictionaryConverter<ReadOnlyDictionary<TKey, TValue>> CreateConverter(FormDataConverter<TValue> valueTypeConverter)
{
return new DictionaryConverter<ReadOnlyDictionary<TKey, TValue>,
ReadOnlyDictionaryBufferAdapter<TKey, TValue>,
Dictionary<TKey, TValue>,
TKey,
TValue>(valueTypeConverter);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

internal abstract class DictionaryConverter<TDictionary> : FormDataConverter<TDictionary>
{
}

internal sealed class DictionaryConverter<TDictionary, TDictionaryPolicy, TBuffer, TKey, TValue> : DictionaryConverter<TDictionary>
where TKey : IParsable<TKey>
where TDictionaryPolicy : IDictionaryBufferAdapter<TDictionary, TBuffer, TKey, TValue>
{
private readonly FormDataConverter<TValue> _valueConverter;

public DictionaryConverter(FormDataConverter<TValue> elementConverter)
{
ArgumentNullException.ThrowIfNull(elementConverter);

_valueConverter = elementConverter;
}

internal override bool TryRead(
ref FormDataReader context,
Type type,
FormDataMapperOptions options,
[NotNullWhen(true)] out TDictionary? result,
out bool found)
{
TValue currentValue;
TBuffer buffer;
bool foundCurrentValue;
bool currentElementSuccess;
bool succeded = true;

found = context.GetKeys().GetEnumerator().MoveNext();
if (!found)
{
result = default!;
return true;
}

buffer = TDictionaryPolicy.CreateBuffer();

// We can't precompute dictionary anyKeys ahead of time,
// so the moment we find a dictionary, we request the list of anyKeys
// for the current location, which will involve parsing the form data anyKeys
// and building a tree of anyKeys.
var keyCount = 0;
var maxCollectionSize = options.MaxCollectionSize;

foreach (var key in context.GetKeys())
{
context.PushPrefix(key);
currentElementSuccess = _valueConverter.TryRead(ref context, typeof(TValue), options, out currentValue!, out foundCurrentValue);
context.PopPrefix(key);

if (!TKey.TryParse(key[1..^1], CultureInfo.InvariantCulture, out var keyValue))
{
succeded = false;
// Will report an error about unparsable key here.

// Continue trying to bind the rest of the dictionary.
continue;
}

TDictionaryPolicy.Add(ref buffer, keyValue!, currentValue);
keyCount++;
if (keyCount == maxCollectionSize)
{
succeded = false;
break;
}
}

result = TDictionaryPolicy.ToResult(buffer);
return succeded;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,20 @@ internal class CollectionConverterFactory : IFormDataConverterFactory
public bool CanConvert(Type type, FormDataMapperOptions options)
{
var enumerable = ClosedGenericMatcher.ExtractGenericInterface(type, typeof(IEnumerable<>));
if (enumerable == null && !type.IsArray && type.GetArrayRank() != 1)
if (enumerable == null && !(type.IsArray && type.GetArrayRank() == 1))
{
return false;
}

var element = enumerable != null ? enumerable.GetGenericArguments()[0] : type.GetElementType()!;

return options.HasConverter(element);
if (Activator.CreateInstance(typeof(TypedCollectionConverterFactory<,>)
.MakeGenericType(type, element!)) is not IFormDataConverterFactory factory)
{
return false;
}

return factory.CanConvert(type, options);
}

public FormDataConverter CreateConverter(Type type, FormDataMapperOptions options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

internal sealed class CollectionLikeTypedCollectionConverterFactory<TCollection, TElement>
internal class ConcreteTypeCollectionConverterFactory<TCollection, TElement>
: IFormDataConverterFactory
{
public static readonly CollectionLikeTypedCollectionConverterFactory<TCollection, TElement> Instance =
public static readonly ConcreteTypeCollectionConverterFactory<TCollection, TElement> Instance =
new();

public bool CanConvert(Type _, FormDataMapperOptions options) => true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ var _ when type.IsAssignableTo(typeof(ImmutableStack<TElement>)) =>
// Some of the types above implement ICollection<T>, but do so in a very inneficient way, so we want to
// use special converters for them.
var _ when type.IsAssignableTo(typeof(ICollection<TElement>))
=> CollectionLikeTypedCollectionConverterFactory<TCollection, TElement>.Instance.CreateConverter(typeof(TCollection), options),
=> ConcreteTypeCollectionConverterFactory<TCollection, TElement>.Instance.CreateConverter(typeof(TCollection), options),
_ => throw new InvalidOperationException($"Unable to create converter for '{typeof(TCollection).FullName}'.")
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Components.Endpoints.Binding;

internal sealed class ConcreteTypeDictionaryConverterFactory<TDictionary, TKey, TValue> : IFormDataConverterFactory
where TKey : IParsable<TKey>
{
public static readonly ConcreteTypeDictionaryConverterFactory<TDictionary, TKey, TValue> Instance = new();

public bool CanConvert(Type type, FormDataMapperOptions options) => true;

public FormDataConverter CreateConverter(Type type, FormDataMapperOptions options)
{
// Resolve the element type converter
var keyConverter = options.ResolveConverter<TKey>() ??
throw new InvalidOperationException($"Unable to create converter for '{typeof(TDictionary).FullName}'.");

var valueConverter = options.ResolveConverter<TValue>() ??
throw new InvalidOperationException($"Unable to create converter for '{typeof(TDictionary).FullName}'.");

var customFactory = Activator.CreateInstance(typeof(CustomDictionaryConverterFactory<>)
.MakeGenericType(typeof(TDictionary), typeof(TKey), typeof(TValue), typeof(TDictionary))) as CustomDictionaryConverterFactory;

if (customFactory == null)
{
throw new InvalidOperationException($"Unable to create converter for type '{typeof(TDictionary).FullName}'.");
}

return customFactory.CreateConverter(keyConverter, valueConverter);
}

private abstract class CustomDictionaryConverterFactory
{
public abstract FormDataConverter CreateConverter(FormDataConverter<TKey> keyConverter, FormDataConverter<TValue> valueConverter);
}

private class CustomDictionaryConverterFactory<TCustomDictionary> : CustomDictionaryConverterFactory
where TCustomDictionary : TDictionary, IDictionary<TKey, TValue>, new()
{
public override FormDataConverter CreateConverter(FormDataConverter<TKey> keyConverter, FormDataConverter<TValue> valueConverter)
{
return new DictionaryConverter<
TCustomDictionary,
DictionaryBufferAdapter<TCustomDictionary, TKey, TValue>,
TCustomDictionary,
TKey,
TValue>(valueConverter);
}
}
}
Loading