Skip to content

Commit

Permalink
Support new Options attributes in the Runtime (dotnet#90275)
Browse files Browse the repository at this point in the history
  • Loading branch information
tarekgh authored Aug 10, 2023
1 parent 867e185 commit bc43b7e
Show file tree
Hide file tree
Showing 16 changed files with 414 additions and 433 deletions.
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))
{
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>();
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

0 comments on commit bc43b7e

Please sign in to comment.