ronantakizawa/codereview-bench huggingface dataset:
Repository: dotnet/runtime
File: src/mono/wasm/testassets/BlazorWebWasm/BlazorWebWasm/Program.cs (C#)

Code before:
    requestLogs.Add(logEntry);
});

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();

app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents<App>()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(BlazorWebWasm.Client._Imports).Assembly);

app.MapGet("/request-logs", () => requestLogs);
app.MapDelete("/request-logs", () => requestLogs.Clear());

app.Run();


Review comment (bug):
The Clear() method on the requestLogs list is not thread-safe. If Clear() is called while another request is adding an entry, it can cause race conditions or collection modified exceptions. Use a thread-safe approach such as replacing the list with a new instance or using a concurrent collection with proper clearing logic.

Code after:
    );
    lock (requestLogsLock)
    {
        requestLogs.Add(logEntry);
    }
});

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();

app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents<App>()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(BlazorWebWasm.Client._Imports).Assembly);

app.MapGet("/request-logs", () =>
{
    lock (requestLogsLock)
    {
        return requestLogs.ToList();
    }
});
app.MapDelete("/request-logs", () =>
{
    lock (requestLogsLock)
    {
        requestLogs.Clear();
    }
});

app.Run();
Repository: dotnet/runtime
File: src/mono/wasm/Wasm.Build.Tests/Blazor/BlazorWebWasmLogClient.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;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace Wasm.Build.Tests.Blazor;

/// <summary>
/// Client for interacting with the request log API exposed by the BlazorWebWasm test server app.
/// </summary>
internal class BlazorWebWasmLogClient
{
    private readonly HttpClient _httpClient;

    public BlazorWebWasmLogClient(string baseUrl)
    {
        _httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
    }

    /// <summary>
    /// Retrieves logs for requests processed by the server since the last call to ClearRequestLogsAsync.
    /// </summary>
    public async Task<BlazorWebWasmRequestLog[]> GetRequestLogsAsync()
    {
        var response = await _httpClient.GetAsync("request-logs");
        response.EnsureSuccessStatusCode();
        var logs = await response.Content.ReadFromJsonAsync<BlazorWebWasmRequestLog[]>();
        return logs;
    }

    public async Task ClearRequestLogsAsync()
    {
        var response = await _httpClient.DeleteAsync("request-logs");
        response.EnsureSuccessStatusCode();
    }
}


Review comment (suggestion):
BlazorWebWasmLogClient creates an HttpClient in its constructor but never disposes it. This can lead to resource leaks, especially socket exhaustion. The class should implement IDisposable to properly dispose of the HttpClient, or consider using a shared HttpClient instance.

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;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace Wasm.Build.Tests.Blazor;

/// <summary>
/// Client for interacting with the request log API exposed by the BlazorWebWasm test server app.
/// </summary>
internal class BlazorWebWasmLogClient : IDisposable
{
    private readonly HttpClient _httpClient;

    public BlazorWebWasmLogClient(string baseUrl)
    {
        _httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
    }

    /// <summary>
    /// Retrieves logs for requests processed by the server since the last call to ClearRequestLogsAsync.
    /// </summary>
    public async Task<BlazorWebWasmRequestLog[]> GetRequestLogsAsync()
    {
        var response = await _httpClient.GetAsync("request-logs");
        response.EnsureSuccessStatusCode();
        var logs = await response.Content.ReadFromJsonAsync<BlazorWebWasmRequestLog[]>() ?? [];
        return logs;
    }

    public async Task ClearRequestLogsAsync()
    {
        var response = await _httpClient.DeleteAsync("request-logs");
        response.EnsureSuccessStatusCode();
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}
Repository: dotnet/runtime
File: src/mono/wasm/Wasm.Build.Tests/Blazor/BlazorWebWasmLogClient.cs (C#)

Code before:
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace Wasm.Build.Tests.Blazor;

/// <summary>
/// Client for interacting with the request log API exposed by the BlazorWebWasm test server app.
/// </summary>
internal class BlazorWebWasmLogClient
{
    private readonly HttpClient _httpClient;

    public BlazorWebWasmLogClient(string baseUrl)
    {
        _httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
    }

    /// <summary>
    /// Retrieves logs for requests processed by the server since the last call to ClearRequestLogsAsync.
    /// </summary>
    public async Task<BlazorWebWasmRequestLog[]> GetRequestLogsAsync()
    {
        var response = await _httpClient.GetAsync("request-logs");
        response.EnsureSuccessStatusCode();
        var logs = await response.Content.ReadFromJsonAsync<BlazorWebWasmRequestLog[]>();
        return logs;
    }

    public async Task ClearRequestLogsAsync()
    {
        var response = await _httpClient.DeleteAsync("request-logs");
        response.EnsureSuccessStatusCode();
    }
}


Review comment (suggestion):
ReadFromJsonAsync can return null if the response content is empty or invalid JSON. Since nullable is enabled in this file, the return type should be BlazorWebWasmRequestLog[]? and null should be checked before returning, or a null-forgiving operator should be used if null is truly impossible in this context.
```suggestion
        var logs = await response.Content.ReadFromJsonAsync<BlazorWebWasmRequestLog[]>() ?? Array.Empty<BlazorWebWasmRequestLog>();
```

Code after:
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace Wasm.Build.Tests.Blazor;

/// <summary>
/// Client for interacting with the request log API exposed by the BlazorWebWasm test server app.
/// </summary>
internal class BlazorWebWasmLogClient : IDisposable
{
    private readonly HttpClient _httpClient;

    public BlazorWebWasmLogClient(string baseUrl)
    {
        _httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
    }

    /// <summary>
    /// Retrieves logs for requests processed by the server since the last call to ClearRequestLogsAsync.
    /// </summary>
    public async Task<BlazorWebWasmRequestLog[]> GetRequestLogsAsync()
    {
        var response = await _httpClient.GetAsync("request-logs");
        response.EnsureSuccessStatusCode();
        var logs = await response.Content.ReadFromJsonAsync<BlazorWebWasmRequestLog[]>() ?? [];
        return logs;
    }

    public async Task ClearRequestLogsAsync()
    {
        var response = await _httpClient.DeleteAsync("request-logs");
        response.EnsureSuccessStatusCode();
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}
Repository: dotnet/runtime
File: src/mono/wasm/testassets/BlazorWebWasm/BlazorWebWasm/Program.cs (C#)

Code before:
using BlazorWebWasm.Client.Pages;
using BlazorWebWasm.Components;
using Microsoft.AspNetCore.HttpLogging;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveWebAssemblyComponents();

var app = builder.Build();

var requestLogs = new List<BlazorWebWasmRequestLog>();

app.Use(async (context, next) =>
{
    await next.Invoke();
    var logEntry = new BlazorWebWasmRequestLog(
        DateTime.Now,
        context.Request.Method,
        context.Request.Path,
        context.Response.StatusCode
    );
    requestLogs.Add(logEntry);
});

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();

app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents<App>()

Review comment (suggestion):
DateTime.Now should be replaced with DateTime.UtcNow for consistency and to avoid timezone-related issues. Using UTC time is a best practice for logging and timestamps that may be compared or aggregated across different timezones.
```suggestion
        DateTime.UtcNow,
```

Code after:
using BlazorWebWasm.Client.Pages;
using BlazorWebWasm.Components;
using Microsoft.AspNetCore.HttpLogging;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveWebAssemblyComponents();

var app = builder.Build();

var requestLogs = new List<BlazorWebWasmRequestLog>();
var requestLogsLock = new Lock();

app.Use(async (context, next) =>
{
    await next.Invoke();
    var logEntry = new BlazorWebWasmRequestLog(
        DateTime.UtcNow,
        context.Request.Method,
        context.Request.Path,
        context.Response.StatusCode
    );
    lock (requestLogsLock)
    {
        requestLogs.Add(logEntry);
    }
});

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();
Repository: dotnet/runtime
File: src/libraries/Common/src/Interop/Unix/System.Native/Interop.IsATty.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;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

internal static partial class Interop
{
    internal static partial class Sys
    {
        [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_IsATty", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static partial bool IsATty(SafeFileHandle fd);

        [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_IsATty", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static partial bool IsATty(IntPtr fd);
    }
}


Review comment (suggestion):
@copilot The caller of this method does not check for errors. `SetLastError = true` should not be needed.

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;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class Sys
    {
        [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_IsATty")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static partial bool IsATty(IntPtr fd);
    }
}
Repository: dotnet/runtime
File: src/libraries/System.Private.CoreLib/src/System/IO/File.Windows.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.Win32.SafeHandles;

namespace System.IO
{
    public static partial class File
    {
        private static SafeFileHandle OpenNullHandleCore()
        {
            // Open the NUL device on Windows with read/write access, async support, and no inheritance
            return SafeFileHandle.Open("NUL", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, FileOptions.Asynchronous, preallocationSize: 0);
        }

        private static UnixFileMode GetUnixFileModeCore(string path)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);

        private static UnixFileMode GetUnixFileModeCore(SafeFileHandle fileHandle)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);

        private static void SetUnixFileModeCore(string path, UnixFileMode mode)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);

        private static void SetUnixFileModeCore(SafeFileHandle fileHandle, UnixFileMode mode)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);
    }
}


Review comment (suggestion):
This handle will be often used for Process STD IN/OUT/ERR that are not expected to be async.

```suggestion
            return SafeFileHandle.Open("NUL", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, FileOptions.None, preallocationSize: 0);
```

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 Microsoft.Win32.SafeHandles;

namespace System.IO
{
    public static partial class File
    {
        private const string NullDevicePath = "NUL";

        private static UnixFileMode GetUnixFileModeCore(string path)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);

        private static UnixFileMode GetUnixFileModeCore(SafeFileHandle fileHandle)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);

        private static void SetUnixFileModeCore(string path, UnixFileMode mode)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);

        private static void SetUnixFileModeCore(SafeFileHandle fileHandle, UnixFileMode mode)
            => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode);
    }
}
Repository: dotnet/runtime
File: src/libraries/System.Private.CoreLib/src/System/IO/File.Unix.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.Win32.SafeHandles;

namespace System.IO
{
    public static partial class File
    {
        private static SafeFileHandle OpenNullHandleCore()
        {
            // Open /dev/null on Unix with read/write access, async support, and CLOEXEC (no inheritance)
            return SafeFileHandle.Open("/dev/null", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, FileOptions.Asynchronous, preallocationSize: 0);
        }

        private static UnixFileMode GetUnixFileModeCore(string path)
            => FileSystem.GetUnixFileMode(Path.GetFullPath(path));

        private static UnixFileMode GetUnixFileModeCore(SafeFileHandle fileHandle)
            => FileSystem.GetUnixFileMode(fileHandle);

        private static void SetUnixFileModeCore(string path, UnixFileMode mode)
            => FileSystem.SetUnixFileMode(Path.GetFullPath(path), mode);

        private static void SetUnixFileModeCore(SafeFileHandle fileHandle, UnixFileMode mode)
            => FileSystem.SetUnixFileMode(fileHandle, mode);
    }
}


Review comment (suggestion):
```suggestion
            return SafeFileHandle.Open("/dev/null", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, FileOptions.None, preallocationSize: 0);
```

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 Microsoft.Win32.SafeHandles;

namespace System.IO
{
    public static partial class File
    {
        private const string NullDevicePath = "/dev/null";

        private static UnixFileMode GetUnixFileModeCore(string path)
            => FileSystem.GetUnixFileMode(Path.GetFullPath(path));

        private static UnixFileMode GetUnixFileModeCore(SafeFileHandle fileHandle)
            => FileSystem.GetUnixFileMode(fileHandle);

        private static void SetUnixFileModeCore(string path, UnixFileMode mode)
            => FileSystem.SetUnixFileMode(Path.GetFullPath(path), mode);

        private static void SetUnixFileModeCore(SafeFileHandle fileHandle, UnixFileMode mode)
            => FileSystem.SetUnixFileMode(fileHandle, mode);
    }
}
Repository: dotnet/runtime
File: src/libraries/System.Private.CoreLib/src/System/Guid.Unix.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.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace System
{
    public partial struct Guid
    {
        // Batch size for cached GUID generation. Chosen to balance memory usage vs syscall overhead.
        // 64 GUIDs = 1024 bytes, which provides good amortization of the syscall cost while
        // keeping memory footprint reasonable for thread-local storage.
        private const int GuidCacheBatchSize = 64;

        [ThreadStatic]
        private static Guid[]? t_guidCache;

        [ThreadStatic]
        private static int t_guidCacheIndex;

        // This will create a new random guid based on the https://www.ietf.org/rfc/rfc4122.txt
        public static unsafe Guid NewGuid()
        {
#if !TARGET_WASI
            // Use thread-local caching to amortize the cost of secure random byte generation.
            // This significantly improves performance on Linux where the getrandom/urandom syscall
            // overhead is much higher than Windows' BCryptGenRandom.

            Guid[]? cache = t_guidCache;

Review comment (suggestion):
`System.Runtime.InteropServices` does not appear to be used in this file anymore; consider removing this `using` to avoid an unnecessary import and keep the file consistent with the usual style of only including needed namespaces.
```suggestion

```

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.Runtime.CompilerServices;

namespace System
{
    public partial struct Guid
    {
        // This will create a new random guid based on the https://www.ietf.org/rfc/rfc4122.txt
        public static unsafe Guid NewGuid()
        {
            Guid g;
#if !TARGET_WASI
            // Guid.NewGuid is often used as a cheap source of random data that are sometimes used for security purposes.
            // Windows implementation uses secure RNG to implement it. We use secure RNG for Unix too to avoid subtle security
            // vulnerabilities in applications that depend on it. See https://github.com/dotnet/runtime/issues/42752 for details.
            Interop.GetCryptographicallySecureRandomBytes((byte*)&g, sizeof(Guid));
#else
            // TODOWASI: crypto secure random bytes
            Interop.GetRandomBytes((byte*)&g, sizeof(Guid));
#endif

            // Modify bits indicating the type of the GUID

            unchecked
            {
                // time_hi_and_version
                Unsafe.AsRef(in g._c) = (short)((g._c & ~VersionMask) | Version4Value);
                // clock_seq_hi_and_reserved
Repository: dotnet/runtime
File: src/libraries/System.IO.Hashing/src/System/IO/Hashing/Adler32.cs (C#)

Code before:
        private const int NMax = 5552;   // NMax is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1

        private static uint Update(uint adler, ReadOnlySpan<byte> buf)
        {
            if (buf.IsEmpty)
            {
                return 1u;
            }

            uint s1 = adler & 0xFFFF;
            uint s2 = (adler >> 16) & 0xFFFF;
            while (buf.Length > 0)
            {
                int k = buf.Length < NMax ? buf.Length : NMax;
                for (int i = 0; i < k; i++)
                {
                    s1 += buf[i];
                    s2 += s1;
                }
                s1 %= Base;
                s2 %= Base;
#if NETSTANDARD2_0 || NETFRAMEWORK
                buf = buf.Slice(k);
#else
                buf = buf[k..];
#endif
            }

            return (s2 << 16) | s1;
        }
    }
}


Review comment (suggestion):
```suggestion
                buf = buf.Slice(k);
```

Even if one generally likes the compressed syntax better, it's made worse by being in a \#if... so just use the pattern that works everywhere, since they're identical in the end.

Code after:
            if (buf.IsEmpty)
            {
                return adler;
            }

            return UpdateScalar(adler, buf);
        }

        private static uint UpdateScalar(uint adler, ReadOnlySpan<byte> buf)
        {
            const uint Base = 65521; // largest prime smaller than 65536
            const int NMax = 5552; // NMax is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1

            uint s1 = adler & 0xFFFF;
            uint s2 = (adler >> 16) & 0xFFFF;
            while (buf.Length > 0)
            {
                int k = buf.Length < NMax ? buf.Length : NMax;
                foreach (byte b in buf.Slice(0, k))
                {
                    s1 += b;
                    s2 += s1;
                }
                s1 %= Base;
                s2 %= Base;
                buf = buf.Slice(k);
            }

            return (s2 << 16) | s1;
        }
    }
}