ronantakizawa/codereview-bench huggingface dataset:
Repository: dotnet/aspnetcore
File: src/Middleware/RequestDecompression/src/RequestDecompressionMiddleware.cs (C#)

Code before:
    /// <summary>
    /// Invoke the middleware.
    /// </summary>
    /// <param name="context">The <see cref="HttpContext"/>.</param>
    /// <returns>A task that represents the execution of this middleware.</returns>
    public Task Invoke(HttpContext context)
    {
        var decompressionStream = _provider.GetDecompressionStream(context);
        if (decompressionStream is null)
        {
            return _next(context);
        }

        return InvokeCore(context, decompressionStream);
    }

    private async Task InvokeCore(HttpContext context, Stream decompressionStream)
    {
        var request = context.Request.Body;
        try
        {
            var sizeLimit =
                context.GetEndpoint()?.Metadata?.GetMetadata<IRequestSizeLimitMetadata>()?.MaxRequestBodySize
                    ?? context.Features.Get<IHttpMaxRequestBodySizeFeature>()?.MaxRequestBodySize;

            context.Request.Body = new SizeLimitedStream(decompressionStream, sizeLimit, (long totalBytesRead, long sizeLimit) => throw new BadHttpRequestException(
                    $"The decompressed request body is larger than the request body size limit {sizeLimit}.",
                    StatusCodes.Status413PayloadTooLarge));
            await _next(context);
        }
        finally
        {
            context.Request.Body = request;
            await decompressionStream.DisposeAsync();
        }
    }
}


Review comment (suggestion):
```suggestion
            context.Request.Body = new SizeLimitedStream(decompressionStream, sizeLimit, static (long sizeLimit) => throw new BadHttpRequestException(
```

Code after:
    /// <summary>
    /// Invoke the middleware.
    /// </summary>
    /// <param name="context">The <see cref="HttpContext"/>.</param>
    /// <returns>A task that represents the execution of this middleware.</returns>
    public Task Invoke(HttpContext context)
    {
        var decompressionStream = _provider.GetDecompressionStream(context);
        if (decompressionStream is null)
        {
            return _next(context);
        }

        return InvokeCore(context, decompressionStream);
    }

    private async Task InvokeCore(HttpContext context, Stream decompressionStream)
    {
        var request = context.Request.Body;
        try
        {
            var sizeLimit =
                context.GetEndpoint()?.Metadata?.GetMetadata<IRequestSizeLimitMetadata>()?.MaxRequestBodySize
                    ?? context.Features.Get<IHttpMaxRequestBodySizeFeature>()?.MaxRequestBodySize;

            context.Request.Body = new SizeLimitedStream(decompressionStream, sizeLimit, static (long sizeLimit) => throw new BadHttpRequestException(
                    $"The decompressed request body is larger than the request body size limit {sizeLimit}.",
                    StatusCodes.Status413PayloadTooLarge));
            await _next(context);
        }
        finally
        {
            context.Request.Body = request;
            await decompressionStream.DisposeAsync();
        }
    }
}
Repository: dotnet/aspnetcore
File: src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Program.cs (C#)

Code before:
#if (IndividualLocalAuth)
#if (UseServer)
using Microsoft.AspNetCore.Components.Authorization;
#endif
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
#endif
#if (UseWebAssembly && SampleContent)
using BlazorWeb_CSharp.Client.Pages;
#endif
using BlazorWeb_CSharp.Components;
#if (IndividualLocalAuth)
using BlazorWeb_CSharp.Components.Account;
using BlazorWeb_CSharp.Data;
#endif

System.AppContext.SetSwitch("Microsoft.AspNetCore.Components.Endpoints.NavigationManager.DisableThrowNavigationException", true);

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
#if (!UseServer && !UseWebAssembly)
builder.Services.AddRazorComponents();
#else
builder.Services.AddRazorComponents()
    #if (UseServer && UseWebAssembly && IndividualLocalAuth)
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents()
    .AddAuthenticationStateSerialization();
    #elif (UseServer && UseWebAssembly)
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();
    #elif (UseServer)
    .AddInteractiveServerComponents();
    #elif (UseWebAssembly && IndividualLocalAuth)
    .AddInteractiveWebAssemblyComponents()
    .AddAuthenticationStateSerialization();
    #elif (UseWebAssembly)
    .AddInteractiveWebAssemblyComponents();
    #endif
#endif


Review comment (suggestion):
Precisely being able to put a `Directory.build.props` and defining it there is what I was going for with avoiding this

Code after:
#if (IndividualLocalAuth)
#if (UseServer)
using Microsoft.AspNetCore.Components.Authorization;
#endif
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
#endif
#if (UseWebAssembly && SampleContent)
using BlazorWeb_CSharp.Client.Pages;
#endif
using BlazorWeb_CSharp.Components;
#if (IndividualLocalAuth)
using BlazorWeb_CSharp.Components.Account;
using BlazorWeb_CSharp.Data;
#endif

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
#if (!UseServer && !UseWebAssembly)
builder.Services.AddRazorComponents();
#else
builder.Services.AddRazorComponents()
    #if (UseServer && UseWebAssembly && IndividualLocalAuth)
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents()
    .AddAuthenticationStateSerialization();
    #elif (UseServer && UseWebAssembly)
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();
    #elif (UseServer)
    .AddInteractiveServerComponents();
    #elif (UseWebAssembly && IndividualLocalAuth)
    .AddInteractiveWebAssemblyComponents()
    .AddAuthenticationStateSerialization();
    #elif (UseWebAssembly)
    .AddInteractiveWebAssemblyComponents();
    #endif
#endif

#if (IndividualLocalAuth)
builder.Services.AddCascadingAuthenticationState();
Repository: dotnet/aspnetcore
File: src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs (C#)

Code before:
        }

        return marker;
    }

    private ComponentMarkerKey GenerateMarkerKey(int sequence, object? componentKey)
    {
        var componentTypeNameHash = _componentTypeNameHashCache.GetOrAdd(_componentType, TypeNameHash.Compute);
        var sequenceString = sequence.ToString(CultureInfo.InvariantCulture);

        var locationHash = $"{componentTypeNameHash}:{sequenceString}";
        var formattedComponentKey = (componentKey as IFormattable)?.ToString(null, CultureInfo.InvariantCulture) ?? string.Empty;

        return new()
        {
            LocationHash = locationHash,
            FormattedComponentKey = formattedComponentKey,
        };
    }

    /// <summary>
    /// Gets the ComponentMarkerKey for this boundary if it has been computed.
    /// This is used for state persistence across render modes.
    /// </summary>
    /// <returns>The ComponentMarkerKey if available, null otherwise.</returns>
    internal ComponentMarkerKey? GetComponentMarkerKey(int sequence, object? componentKey)
    {
        return _markerKey ??= GenerateMarkerKey(sequence, componentKey);
    }
}


Review comment (suggestion):
I don't agree. It returns `_markerKey` if it's not null, otherwise it calls `GenerateMarkerKey` that always returns `ComponentMarkerKey` (not nullable).

```suggestion
    internal ComponentMarkerKey GetComponentMarkerKey(int sequence, object? componentKey)
```

Code after:
        }

        return marker;
    }

    private ComponentMarkerKey GenerateMarkerKey(int sequence, object? componentKey)
    {
        var componentTypeNameHash = _componentTypeNameHashCache.GetOrAdd(_componentType, TypeNameHash.Compute);
        var sequenceString = sequence.ToString(CultureInfo.InvariantCulture);

        var locationHash = $"{componentTypeNameHash}:{sequenceString}";
        var formattedComponentKey = (componentKey as IFormattable)?.ToString(null, CultureInfo.InvariantCulture) ?? string.Empty;

        return new()
        {
            LocationHash = locationHash,
            FormattedComponentKey = formattedComponentKey,
        };
    }

    /// <summary>
    /// Gets the ComponentMarkerKey for this boundary if it has been computed.
    /// This is used for state persistence across render modes.
    /// </summary>
    /// <returns>The ComponentMarkerKey if available, null otherwise.</returns>
    internal ComponentMarkerKey GetComponentMarkerKey(int sequence, object? componentKey)
    {
        return _markerKey ??= GenerateMarkerKey(sequence, componentKey);
    }
}
Repository: dotnet/aspnetcore
File: src/Http/Authentication.Core/test/TokenExtensionTests.cs (C#)

Code before:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Security.Claims;
using static Microsoft.AspNetCore.Authentication.Core.Test.AuthenticationPropertiesTests;

namespace Microsoft.AspNetCore.Authentication.Core.Test;

public class TokenExtensionTests
{
    [Fact]
    public void CanStoreMultipleTokens()
    {
        var props = new AuthenticationProperties();
        var tokens = new List<AuthenticationToken>();
        var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
        var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
        var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
        tokens.Add(tok1);
        tokens.Add(tok2);
        tokens.Add(tok3);
        props.StoreTokens(tokens);

        Assert.Equal("1", props.GetTokenValue("One"));
        Assert.Equal("2", props.GetTokenValue("Two"));
        Assert.Equal("3", props.GetTokenValue("Three"));
        Assert.Equal(3, props.GetTokens().Count());
    }

    [Fact]

Review comment (security):
```suggestion
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
```

Code after:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Authentication.Core.Test;

public class TokenExtensionTests
{
    [Fact]
    public void CanStoreMultipleTokens()
    {
        var props = new AuthenticationProperties();
        var tokens = new List<AuthenticationToken>();
        var tok1 = new AuthenticationToken { Name = "One", Value = "1" };
        var tok2 = new AuthenticationToken { Name = "Two", Value = "2" };
        var tok3 = new AuthenticationToken { Name = "Three", Value = "3" };
        tokens.Add(tok1);
        tokens.Add(tok2);
        tokens.Add(tok3);
        props.StoreTokens(tokens);

        Assert.Equal("1", props.GetTokenValue("One"));
        Assert.Equal("2", props.GetTokenValue("Two"));
        Assert.Equal("3", props.GetTokenValue("Three"));
        Assert.Equal(3, props.GetTokens().Count());
    }

    [Fact]
    public void SubsequentStoreTokenDeletesPreviousTokens()
Repository: dotnet/aspnetcore
File: src/Components/Components/src/IPersistentComponentStateSerializer.cs (C#)

Code before:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;

namespace Microsoft.AspNetCore.Components;

/// <summary>
/// Provides custom serialization logic for persistent component state values.
/// </summary>
internal interface IPersistentComponentStateSerializer
{
    /// <summary>
    /// Serializes the provided <paramref name="value"/> and writes it to the <paramref name="writer"/>.
    /// </summary>
    /// <param name="type">The type of the value to serialize.</param>
    /// <param name="value">The value to serialize.</param>
    /// <param name="writer">The buffer writer to write the serialized data to.</param>
    /// <returns>A task that represents the asynchronous serialization operation.</returns>
    Task PersistAsync(Type type, object value, IBufferWriter<byte> writer);

    /// <summary>
    /// Deserializes a value from the provided <paramref name="data"/>.
    /// This method must be synchronous to avoid UI tearing during component state restoration.
    /// </summary>
    /// <param name="type">The type of the value to deserialize.</param>
    /// <param name="data">The serialized data to deserialize.</param>
    /// <returns>The deserialized value.</returns>
    object Restore(Type type, ReadOnlySequence<byte> data);
}

Review comment (suggestion):
Remove the comments from all the non public types and members

Code after:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;

namespace Microsoft.AspNetCore.Components;

internal interface IPersistentComponentStateSerializer
{
    void Persist(Type type, object value, IBufferWriter<byte> writer);
    object Restore(Type type, ReadOnlySequence<byte> data);
}
Repository: dotnet/aspnetcore
File: src/Components/Components/src/OwningComponentBase.cs (C#)

Code before:

            _scope ??= ScopeFactory.CreateAsyncScope();
            return _scope.Value.ServiceProvider;
        }
    }

    /// <summary>
    /// Releases the service scope used by the component.
    /// </summary>
    void IDisposable.Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Asynchronously releases the service scope used by the component.
    /// </summary>
    /// <returns>A task that represents the asynchronous dispose operation.</returns>
    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore().ConfigureAwait(false);

        Dispose(disposing: false);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Releases the service scope used by the component.
    /// </summary>
    /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
    protected virtual void Dispose(bool disposing)
    {
        if (!IsDisposed)
        {
            if (disposing)
            {
                if (_scope.HasValue)
                {
                    if (_scope.Value is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }
                    _scope = null;
                }
            }
            IsDisposed = true;
        }
    }

    /// <summary>

Review comment (refactor):
Move this block below `protected virtual void Dispose(bool disposing)` so that Dispose(bool disposing) remains below Dispose and DisposeAsyncCore is right below DisposeAsync

Code after:

            _scope ??= ScopeFactory.CreateAsyncScope();
            return _scope.Value.ServiceProvider;
        }
    }

    /// <inhertidoc />
    void IDisposable.Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Releases the service scope used by the component.
    /// </summary>
    /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
    protected virtual void Dispose(bool disposing)
    {
        if (!IsDisposed)
        {
            if (disposing && _scope.HasValue && _scope.Value is IDisposable disposable)
            {
                disposable.Dispose();
                _scope = null;
            }

            IsDisposed = true;
        }
    }

    /// <inhertidoc />
    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        await DisposeAsyncCore().ConfigureAwait(false);

        Dispose(disposing: false);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// Asynchronously releases the service scope used by the component.
    /// </summary>
    /// <returns>A task that represents the asynchronous dispose operation.</returns>
    protected virtual async ValueTask DisposeAsyncCore()
    {
        if (!IsDisposed && _scope.HasValue)
        {
            await _scope.Value.DisposeAsync().ConfigureAwait(false);
            _scope = null;
        }
Repository: dotnet/aspnetcore
File: src/Mvc/Mvc.Core/src/Infrastructure/ActionContextAccessor.cs (C#)

Code before:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#nullable enable

using System.Diagnostics.CodeAnalysis;

namespace Microsoft.AspNetCore.Mvc.Infrastructure;

/// <summary>
/// Type that provides access to an <see cref="ActionContext"/>.
/// </summary>
[Obsolete("ActionContextAccessor is obsolete. Use IHttpContextAccessor instead and access the endpoint information from HttpContext.GetEndpoint(). This type will be removed in a future version.", DiagnosticId = "ASPDEPR004")]
public class ActionContextAccessor : IActionContextAccessor
{
    internal static readonly IActionContextAccessor Null = new NullActionContextAccessor();

    private static readonly AsyncLocal<ActionContext> _storage = new AsyncLocal<ActionContext>();

    /// <inheritdoc/>
    [DisallowNull]
    public ActionContext? ActionContext
    {
        get { return _storage.Value; }
        set { _storage.Value = value; }
    }

    private sealed class NullActionContextAccessor : IActionContextAccessor
    {
        public ActionContext? ActionContext
        {
            get => null;
            set { }
        }
    }
}


Review comment (suggestion):
```suggestion
[Obsolete("ActionContextAccessor is obsolete and will be removed in a future version. For more information, visit https://aka.ms/aspnet/deprecate/006.", DiagnosticId = "ASPDEPR006")]
```

Code after:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#nullable enable

using System.Diagnostics.CodeAnalysis;

namespace Microsoft.AspNetCore.Mvc.Infrastructure;

/// <summary>
/// Type that provides access to an <see cref="ActionContext"/>.
/// </summary>
[Obsolete("ActionContextAccessor is obsolete and will be removed in a future version. For more information, visit https://aka.ms/aspnet/deprecate/006.", DiagnosticId = "ASPDEPR006")]
public class ActionContextAccessor : IActionContextAccessor
{
    internal static readonly IActionContextAccessor Null = new NullActionContextAccessor();

    private static readonly AsyncLocal<ActionContext> _storage = new AsyncLocal<ActionContext>();

    /// <inheritdoc/>
    [DisallowNull]
    public ActionContext? ActionContext
    {
        get { return _storage.Value; }
        set { _storage.Value = value; }
    }

    private sealed class NullActionContextAccessor : IActionContextAccessor
    {
        public ActionContext? ActionContext
        {
            get => null;
            set { }
        }
    }
}
Repository: dotnet/aspnetcore
File: src/Framework/AspNetCoreAnalyzers/test/SourceGenerators/PublicTopLevelProgramGeneratorTests.cs (C#)

Code before:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using VerifyCS = Microsoft.AspNetCore.Analyzers.Verifiers.CSharpSourceGeneratorVerifier<Microsoft.AspNetCore.SourceGenerators.PublicProgramSourceGenerator>;

namespace Microsoft.AspNetCore.SourceGenerators.Tests;

public class PublicTopLevelProgramGeneratorTests
{
    private const string ExpectedGeneratedSource = """
// <auto-generated />
/// <summary>
/// Auto-generated public partial Program class for top-level statement apps
/// </summary>
public partial class Program { }
""";

    [Fact]
    public async Task GeneratesSource_ProgramWithTopLevelStatements()
    {
        var source = """
using Microsoft.AspNetCore.Builder;

var app = WebApplication.Create();

app.MapGet("/", () => "Hello, World!");

app.Run();
""";

        await VerifyCS.VerifyAsync(source, "PublicTopLevelProgram.Generated.g.cs", ExpectedGeneratedSource);
    }

    // The compiler synthesizes a Program class in the global namespace due to top-level statements
    // The Foo.Program class is completely unrelated to the entry point and is just as any regular type
    // Hence, we will expect to see the source generated in these scenarios
    [Theory]
    [InlineData("public partial class Program { }")]

Review comment (suggestion):
```suggestion
/// Auto-generated public partial Program class for top-level statement apps.
```

Code after:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using VerifyCS = Microsoft.AspNetCore.Analyzers.Verifiers.CSharpSourceGeneratorVerifier<Microsoft.AspNetCore.SourceGenerators.PublicProgramSourceGenerator>;

namespace Microsoft.AspNetCore.SourceGenerators.Tests;

public class PublicTopLevelProgramGeneratorTests
{
    private const string ExpectedGeneratedSource = """
// <auto-generated />
/// <summary>
/// Auto-generated public partial Program class for top-level statement apps.
/// </summary>
public partial class Program { }
""";

    [Fact]
    public async Task GeneratesSource_ProgramWithTopLevelStatements()
    {
        var source = """
using Microsoft.AspNetCore.Builder;

var app = WebApplication.Create();

app.MapGet("/", () => "Hello, World!");

app.Run();
""";

        await VerifyCS.VerifyAsync(source, "PublicTopLevelProgram.Generated.g.cs", ExpectedGeneratedSource);
    }

    // The compiler synthesizes a Program class in the global namespace due to top-level statements
    // The Foo.Program class is completely unrelated to the entry point and is just as any regular type
    // Hence, we will expect to see the source generated in these scenarios
    [Theory]
    [InlineData("public partial class Program { }")]