Skip to content
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

Support new Options attributes in the Runtime #90275

Merged
merged 2 commits into from
Aug 10, 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
Expand Up @@ -2,9 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Microsoft.Extensions.Options
{
Expand Down Expand Up @@ -52,19 +56,81 @@ public ValidateOptionsResult Validate(string? name, TOptions options)
ThrowHelper.ThrowIfNull(options);

var validationResults = new List<ValidationResult>();
if (Validator.TryValidateObject(options, new ValidationContext(options), validationResults, validateAllProperties: true))
HashSet<object>? visited = null;
List<string>? errors = null;

if (TryValidateOptions(options, options.GetType().Name, validationResults, ref errors, ref visited))
{
return ValidateOptionsResult.Success;
}

string typeName = options.GetType().Name;
var errors = new List<string>();
foreach (ValidationResult result in validationResults)
Debug.Assert(errors is not null && errors.Count > 0);

return ValidateOptionsResult.Fail(errors);
}

[RequiresUnreferencedCode("This method on this type will walk through all properties of the passed in options object, and its type cannot be " +
"statically analyzed so its members may be trimmed.")]
private static bool TryValidateOptions(object options, string qualifiedName, List<ValidationResult> results, ref List<string>? errors, ref HashSet<object>? visited)
{
Debug.Assert(options is not null);

if (visited is not null && visited.Contains(options))
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
{
errors.Add($"DataAnnotation validation failed for '{typeName}' members: '{string.Join(",", result.MemberNames)}' with the error: '{result.ErrorMessage}'.");
return true;
}

return ValidateOptionsResult.Fail(errors);
results.Clear();

bool res = Validator.TryValidateObject(options, new ValidationContext(options), results, validateAllProperties: true);
if (!res)
{
errors ??= new List<string>();

foreach (ValidationResult result in results!)
{
errors.Add($"DataAnnotation validation failed for '{qualifiedName}' members: '{string.Join(",", result.MemberNames)}' with the error: '{result.ErrorMessage}'.");
}
}

foreach (PropertyInfo propertyInfo in options.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetMethod is null)
{
continue;
}

object? value = propertyInfo!.GetValue(options);

if (value is null)
{
continue;
}

if (propertyInfo.GetCustomAttribute<ValidateObjectMembersAttribute>() is not null)
{
visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance);
visited.Add(options);

results ??= new List<ValidationResult>();
tarekgh marked this conversation as resolved.
Show resolved Hide resolved
res = TryValidateOptions(value, $"{qualifiedName}.{propertyInfo.Name}", results, ref errors, ref visited) && res;
}
else if (value is IEnumerable enumerable &&
propertyInfo.GetCustomAttribute<ValidateEnumeratedItemsAttribute>() is not null)
{
visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance);
visited.Add(options);
results ??= new List<ValidationResult>();

int index = 0;
foreach (object item in enumerable)
{
res = TryValidateOptions(item, $"{qualifiedName}.{propertyInfo.Name}[{index++}]", results, ref errors, ref visited) && res;
}
}
}

return res;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
</ItemGroup>

<ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">
<Compile Include="$(CoreLibSharedDir)System\Collections\Generic\ReferenceEqualityComparer.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\RequiresUnreferencedCodeAttribute.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\DynamicallyAccessedMemberTypes.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\DynamicallyAccessedMembersAttribute.cs" />
Expand Down
5 changes: 4 additions & 1 deletion src/libraries/Microsoft.Extensions.Options/gen/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ private List<ValidatedMember> GetMembersToValidate(ITypeSymbol modelType, bool s
var memberInfo = GetMemberInfo(member, speculate, location, validatorType);
if (memberInfo is not null)
{
if (member.DeclaredAccessibility != Accessibility.Public && member.DeclaredAccessibility != Accessibility.Internal)
if (member.DeclaredAccessibility != Accessibility.Public)
{
Diag(DiagDescriptors.MemberIsInaccessible, member.Locations.First(), member.Name);
continue;
Expand All @@ -297,6 +297,8 @@ private List<ValidatedMember> GetMembersToValidate(ITypeSymbol modelType, bool s
case IPropertySymbol prop:
memberType = prop.Type;
break;

/* The runtime doesn't support fields validation yet. If we allow that in the future, we need to add the following code back.
case IFieldSymbol field:
if (field.AssociatedSymbol is not null)
{
Expand All @@ -306,6 +308,7 @@ private List<ValidatedMember> GetMembersToValidate(ITypeSymbol modelType, bool s

memberType = field.Type;
break;
*/
default:
// we only care about properties and fields
return null;
Expand Down
Loading
Loading