Skip to content

Use System.Linq in fewer places #31199

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
5 commits merged into from
Apr 24, 2021
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
19 changes: 14 additions & 5 deletions src/Components/Authorization/src/AttributeAuthorizeDataCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;

namespace Microsoft.AspNetCore.Components.Authorization
Expand All @@ -29,13 +29,22 @@ private static IAuthorizeData[] ComputeAuthorizeDataForType(Type type)
{
// Allow Anonymous skips all authorization
var allAttributes = type.GetCustomAttributes(inherit: true);
if (allAttributes.OfType<IAllowAnonymous>().Any())
List<IAuthorizeData> authorizeDatas = null;
for (var i = 0; i < allAttributes.Length; i++)
{
return null;
if (allAttributes[i] is IAllowAnonymous)
{
return null;
}

if (allAttributes[i] is IAuthorizeData authorizeData)
{
authorizeDatas ??= new();
authorizeDatas.Add(authorizeData);
}
}

var authorizeDataAttributes = allAttributes.OfType<IAuthorizeData>().ToArray();
return authorizeDataAttributes.Length > 0 ? authorizeDataAttributes : null;
return authorizeDatas?.ToArray();
}
}
}
26 changes: 16 additions & 10 deletions src/Components/Components/src/ComponentFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Components.Reflection;
using static Microsoft.AspNetCore.Internal.LinkerFlags;
Expand Down Expand Up @@ -56,16 +56,22 @@ private void PerformPropertyInjection(IServiceProvider serviceProvider, ICompone
private Action<IServiceProvider, IComponent> CreateInitializer([DynamicallyAccessedMembers(Component)] Type type)
{
// Do all the reflection up front
var injectableProperties =
MemberAssignment.GetPropertiesIncludingInherited(type, _injectablePropertyBindingFlags)
.Where(p => p.IsDefined(typeof(InjectAttribute)));
List<(string name, Type propertyType, PropertySetter setter)>? injectables = null;
foreach (var property in MemberAssignment.GetPropertiesIncludingInherited(type, _injectablePropertyBindingFlags))
{
if (!property.IsDefined(typeof(InjectAttribute)))
{
continue;
}

var injectables = injectableProperties.Select(property =>
(
propertyName: property.Name,
propertyType: property.PropertyType,
setter: new PropertySetter(type, property)
)).ToArray();
injectables ??= new();
injectables.Add((property.Name, property.PropertyType, new PropertySetter(type, property)));
}

if (injectables is null)
{
return static (_, _) => { };
}

return Initialize;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.Extensions.Logging;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@
<argument>ILLink</argument>
<argument>IL2026</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Components.RouteTableFactory.GetRouteableComponents(System.Collections.Generic.IEnumerable{System.Reflection.Assembly})</property>
<property name="Target">M:Microsoft.AspNetCore.Components.RouteTableFactory.&lt;GetRouteableComponents&gt;g__GetRouteableComponents|3_0(System.Collections.Generic.List{System.Type},System.Reflection.Assembly)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2062</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Components.RouteTableFactory.Create(System.Collections.Generic.Dictionary{System.Type,System.String[]})</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
Expand Down Expand Up @@ -51,21 +57,21 @@
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2072</argument>
<argument>IL2077</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Components.RouteTableFactory.Create(System.Collections.Generic.Dictionary{System.Type,System.String[]})</property>
<property name="Target">M:Microsoft.AspNetCore.Components.ComponentFactory.CreateInitializer(System.Type)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2077</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Components.ComponentFactory.CreateInitializer(System.Type)</property>
<property name="Target">M:Microsoft.AspNetCore.Components.LayoutView.&lt;&gt;c__DisplayClass13_0.&lt;WrapInLayout&gt;g__Render|0(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder)</property>
</attribute>
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2077</argument>
<argument>IL2080</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Components.LayoutView.&lt;&gt;c__DisplayClass13_0.&lt;WrapInLayout&gt;g__Render|0(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder)</property>
<property name="Target">M:Microsoft.AspNetCore.Components.Reflection.MemberAssignment.&lt;GetPropertiesIncludingInherited&gt;d__0.MoveNext</property>
</attribute>
</assembly>
</linker>
20 changes: 11 additions & 9 deletions src/Components/Components/src/Reflection/ComponentProperties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using static Microsoft.AspNetCore.Internal.LinkerFlags;

Expand Down Expand Up @@ -215,19 +214,22 @@ private static void ThrowForCaptureUnmatchedValuesConflict(Type targetType, stri
throw new InvalidOperationException(
$"The property '{parameterName}' on component type '{targetType.FullName}' cannot be set explicitly " +
$"when also used to capture unmatched values. Unmatched values:" + Environment.NewLine +
string.Join(Environment.NewLine, unmatched.Keys.OrderBy(k => k)));
string.Join(Environment.NewLine, unmatched.Keys));
}

[DoesNotReturn]
private static void ThrowForMultipleCaptureUnmatchedValuesParameters([DynamicallyAccessedMembers(Component)] Type targetType)
{
// We don't care about perf here, we want to report an accurate and useful error.
var propertyNames = targetType
.GetProperties(_bindablePropertyFlags)
.Where(p => p.GetCustomAttribute<ParameterAttribute>()?.CaptureUnmatchedValues == true)
.Select(p => p.Name)
.OrderBy(p => p)
.ToArray();
var propertyNames = new List<string>();
foreach (var property in targetType.GetProperties(_bindablePropertyFlags))
{
if (property.GetCustomAttribute<ParameterAttribute>()?.CaptureUnmatchedValues == true)
{
propertyNames.Add(property.Name);
}
}

propertyNames.Sort(StringComparer.Ordinal);

throw new InvalidOperationException(
$"Multiple properties were found on component type '{targetType.FullName}' with " +
Expand Down
63 changes: 50 additions & 13 deletions src/Components/Components/src/Reflection/MemberAssignment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using static Microsoft.AspNetCore.Internal.LinkerFlags;

namespace Microsoft.AspNetCore.Components.Reflection
Expand All @@ -16,35 +16,72 @@ public static IEnumerable<PropertyInfo> GetPropertiesIncludingInherited(
[DynamicallyAccessedMembers(Component)] Type type,
BindingFlags bindingFlags)
{
var dictionary = new Dictionary<string, List<PropertyInfo>>();
var dictionary = new Dictionary<string, object>(StringComparer.Ordinal);

Type? currentType = type;

while (currentType != null)
{
var properties = currentType.GetProperties(bindingFlags | BindingFlags.DeclaredOnly);
var properties = currentType.GetProperties(bindingFlags | BindingFlags.DeclaredOnly);
foreach (var property in properties)
{
if (!dictionary.TryGetValue(property.Name, out var others))
{
others = new List<PropertyInfo>();
dictionary.Add(property.Name, others);
dictionary.Add(property.Name, property);
}

if (others.Any(other => other.GetMethod?.GetBaseDefinition() == property.GetMethod?.GetBaseDefinition()))
else if (!IsInheritedProperty(property, others))
{
// This is an inheritance case. We can safely ignore the value of property since
// we have seen a more derived value.
continue;
List<PropertyInfo> many;
if (others is PropertyInfo single)
{
many = new List<PropertyInfo> { single };
dictionary[property.Name] = many;
}
else
{
many = (List<PropertyInfo>)others;
}
many.Add(property);
}

others.Add(property);
}

currentType = currentType.BaseType;
}

return dictionary.Values.SelectMany(p => p);
foreach (var item in dictionary)
{
if (item.Value is PropertyInfo property)
{
yield return property;
continue;
}

var list = (List<PropertyInfo>)item.Value;
var count = list.Count;
for (var i = 0; i < count; i++)
{
yield return list[i];
}
}
}

private static bool IsInheritedProperty(PropertyInfo property, object others)
{
if (others is PropertyInfo single)
{
return single.GetMethod?.GetBaseDefinition() == property.GetMethod?.GetBaseDefinition();
}

var many = (List<PropertyInfo>)others;
foreach (var other in CollectionsMarshal.AsSpan(many))
{
if (other.GetMethod?.GetBaseDefinition() == property.GetMethod?.GetBaseDefinition())
{
return true;
}
}

return false;
}
}
}
8 changes: 4 additions & 4 deletions src/Components/Components/src/Routing/RouteEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Components.Routing
[DebuggerDisplay("Handler = {Handler}, Template = {Template}")]
internal class RouteEntry
{
public RouteEntry(RouteTemplate template, [DynamicallyAccessedMembers(Component)] Type handler, string[] unusedRouteParameterNames)
public RouteEntry(RouteTemplate template, [DynamicallyAccessedMembers(Component)] Type handler, List<string>? unusedRouteParameterNames)
{
Template = template;
UnusedRouteParameterNames = unusedRouteParameterNames;
Expand All @@ -23,7 +23,7 @@ public RouteEntry(RouteTemplate template, [DynamicallyAccessedMembers(Component)

public RouteTemplate Template { get; }

public string[] UnusedRouteParameterNames { get; }
public List<string>? UnusedRouteParameterNames { get; }

[DynamicallyAccessedMembers(Component)]
public Type Handler { get; }
Expand Down Expand Up @@ -113,10 +113,10 @@ internal void Match(RouteContext context)
parameters ??= new Dictionary<string, object>(StringComparer.Ordinal);
AddDefaultValues(parameters, templateIndex, Template.Segments);
}
if (UnusedRouteParameterNames?.Length > 0)
if (UnusedRouteParameterNames?.Count > 0)
{
parameters ??= new Dictionary<string, object>(StringComparer.Ordinal);
for (var i = 0; i < UnusedRouteParameterNames.Length; i++)
for (var i = 0; i < UnusedRouteParameterNames.Count; i++)
{
parameters[UnusedRouteParameterNames[i]] = null;
}
Expand Down
64 changes: 64 additions & 0 deletions src/Components/Components/src/Routing/RouteKey.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Reflection;

namespace Microsoft.AspNetCore.Components.Routing
{
internal readonly struct RouteKey : IEquatable<RouteKey>
{
public readonly Assembly? AppAssembly;
public readonly HashSet<Assembly>? AdditionalAssemblies;

public RouteKey(Assembly appAssembly, IEnumerable<Assembly> additionalAssemblies)
{
AppAssembly = appAssembly;
AdditionalAssemblies = additionalAssemblies is null ? null : new HashSet<Assembly>(additionalAssemblies);
}

public override bool Equals(object? obj)
{
return obj is RouteKey other && Equals(other);
}

public bool Equals(RouteKey other)
{
if (!Equals(AppAssembly, other.AppAssembly))
{
return false;
}

if (AdditionalAssemblies is null && other.AdditionalAssemblies is null)
{
return true;
}

if (AdditionalAssemblies is null || other.AdditionalAssemblies is null)
{
return false;
}

return AdditionalAssemblies.Count == other.AdditionalAssemblies.Count &&
AdditionalAssemblies.SetEquals(other.AdditionalAssemblies);
}

public override int GetHashCode()
{
if (AppAssembly is null)
{
return 0;
}

if (AdditionalAssemblies is null)
{
return AppAssembly.GetHashCode();
}

// Producing a hash code that includes individual assemblies requires it to have a stable order.
// We'll avoid the cost of sorting and simply include the number of assemblies instead.
return HashCode.Combine(AppAssembly, AdditionalAssemblies.Count);
}
}
}
Loading