Skip to content

Allow same type names in different namespaces in validator generator #62050

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
merged 1 commit into from
May 21, 2025
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 @@ -7,15 +7,13 @@
using System.Text;
using Microsoft.CodeAnalysis.CSharp;
using System.IO;
using System.Text.RegularExpressions;

namespace Microsoft.AspNetCore.Http.ValidationsGenerator;

public sealed partial class ValidationsGenerator : IIncrementalGenerator
{
public static string GeneratedCodeConstructor => $@"global::System.CodeDom.Compiler.GeneratedCodeAttribute(""{typeof(ValidationsGenerator).Assembly.FullName}"", ""{typeof(ValidationsGenerator).Assembly.GetName().Version}"")";
public static string GeneratedCodeAttribute => $"[{GeneratedCodeConstructor}]";
private static readonly Regex InvalidNameCharsRegex = new("[^0-9A-Za-z_]", RegexOptions.Compiled);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love that we can get rid of this now! 😄


internal static void Emit(SourceProductionContext context, (InterceptableLocation? AddValidation, ImmutableArray<ValidatableType> ValidatableTypes) emitInputs)
{
Expand Down Expand Up @@ -102,8 +100,6 @@ public bool TryGetValidatableParameterInfo(global::System.Reflection.ParameterIn
validatableInfo = null;
return false;
}

{{EmitCreateMethods(validatableTypes)}}
}

{{GeneratedCodeAttribute}}
Expand Down Expand Up @@ -186,24 +182,9 @@ private static string EmitTypeChecks(ImmutableArray<ValidatableType> validatable
var typeName = validatableType.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
cw.WriteLine($"if (type == typeof({typeName}))");
cw.StartBlock();
cw.WriteLine($"validatableInfo = Create{SanitizeTypeName(validatableType.Type.MetadataName)}();");
cw.WriteLine("return true;");
cw.EndBlock();
}
return sw.ToString();
}

private static string EmitCreateMethods(ImmutableArray<ValidatableType> validatableTypes)
{
var sw = new StringWriter();
var cw = new CodeWriter(sw, baseIndent: 2);
foreach (var validatableType in validatableTypes)
{
cw.WriteLine($@"private ValidatableTypeInfo Create{SanitizeTypeName(validatableType.Type.MetadataName)}()");
cw.StartBlock();
cw.WriteLine("return new GeneratedValidatableTypeInfo(");
cw.WriteLine($"validatableInfo = new GeneratedValidatableTypeInfo(");
cw.Indent++;
cw.WriteLine($"type: typeof({validatableType.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}),");
cw.WriteLine($"type: typeof({typeName}),");
if (validatableType.Members.IsDefaultOrEmpty)
{
cw.WriteLine("members: []");
Expand All @@ -221,6 +202,7 @@ private static string EmitCreateMethods(ImmutableArray<ValidatableType> validata
}
cw.Indent--;
cw.WriteLine(");");
cw.WriteLine("return true;");
cw.EndBlock();
}
return sw.ToString();
Expand All @@ -237,10 +219,4 @@ private static void EmitValidatableMemberForCreate(ValidatableProperty member, C
cw.Indent--;
cw.WriteLine("),");
}

private static string SanitizeTypeName(string typeName)
{
// Replace invalid characters with underscores
return InvalidNameCharsRegex.Replace(typeName, "_");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Http.ValidationsGenerator.Tests;

public partial class ValidationsGeneratorTests : ValidationsGeneratorTestBase
{
[Fact]
public async Task CanValidateMultipleNamespaces()
{
// Arrange
var source = """
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Validation;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder();

builder.Services.AddValidation();

var app = builder.Build();

app.MapPost("/namespace-one", (NamespaceOne.Type obj) => Results.Ok("Passed"));
app.MapPost("/namespace-two", (NamespaceTwo.Type obj) => Results.Ok("Passed"));

app.Run();

namespace NamespaceOne {
public class Type
{
[StringLength(10)]
public string StringWithLength { get; set; } = string.Empty;
}
}

namespace NamespaceTwo {
public class Type
{
[StringLength(20)]
public string StringWithLength { get; set; } = string.Empty;
}
}
""";
await Verify(source, out var compilation);
await VerifyEndpoint(compilation, "/namespace-one", async (endpoint, serviceProvider) =>
{
await InvalidStringWithLengthProducesError(endpoint);
await ValidInputProducesNoWarnings(endpoint);

async Task InvalidStringWithLengthProducesError(Endpoint endpoint)
{
var payload = """
{
"StringWithLength": "abcdefghijk"
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);

await endpoint.RequestDelegate(context);

var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("StringWithLength", kvp.Key);
Assert.Equal("The field StringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
});
}

async Task ValidInputProducesNoWarnings(Endpoint endpoint)
{
var payload = """
{
"StringWithLength": "abc"
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);
await endpoint.RequestDelegate(context);

Assert.Equal(200, context.Response.StatusCode);
}
});
await VerifyEndpoint(compilation, "/namespace-two", async (endpoint, serviceProvider) =>
{
await InvalidStringWithLengthProducesError(endpoint);
await ValidInputProducesNoWarnings(endpoint);

async Task InvalidStringWithLengthProducesError(Endpoint endpoint)
{
var payload = """
{
"StringWithLength": "abcdefghijklmnopqrstu"
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);

await endpoint.RequestDelegate(context);

var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("StringWithLength", kvp.Key);
Assert.Equal("The field StringWithLength must be a string with a maximum length of 20.", kvp.Value.Single());
});
}

async Task ValidInputProducesNoWarnings(Endpoint endpoint)
{
var payload = """
{
"StringWithLength": "abcdefghijk"
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);
await endpoint.RequestDelegate(context);

Assert.Equal(200, context.Response.StatusCode);
}
});
}
}
Loading
Loading