Skip to content

Commit

Permalink
Merge pull request #718 from SteveDunn/stj-namespace-bug-717
Browse files Browse the repository at this point in the history
Fix: System.Text.Json factories fail to generate if assembly name has hyphens
  • Loading branch information
SteveDunn authored Dec 2, 2024
2 parents 5d1e289 + 65e3da9 commit 8356bd6
Show file tree
Hide file tree
Showing 15 changed files with 1,595 additions and 59 deletions.
6 changes: 5 additions & 1 deletion docs/site/Writerside/topics/tutorials/Using-with-JSON.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,13 @@ var json = JsonSerializer.Serialize(weather, ctx.Weather);
Weather w2 = JsonSerializer.Deserialize(json, ctx.Weather)!;
```
<note>
The namespace used to generate the factory is based on the project name. If the project name contains illegal characters, such as commas, hyphens, or dots, they are replaced with underscores.
</note>
The STJ converter factory is generated automatically if referencing the new STJ types in the `System.Text.Json.Serialization` namespace.
You can turn this off via the `SystemTextJsonConverterFactoryGeneration` flag in config (either globally, or per value object)
You can turn this off via the `SystemTextJsonConverterFactoryGeneration` flag in config (either globally or per value object)
## Summary
Expand Down
2 changes: 1 addition & 1 deletion samples/WebApplication/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
// the following extension method is available if you specify `GenerateSwashbuckleMappingExtensionMethod` - as shown above

opt.MapVogenTypesInWebApplication();
opt.MapVogenTypesInWebApplicationShared();
opt.MapVogenTypesInWebApplication_Shared();

// the following schema filter is generated if you specify GenerateSwashbuckleSchemaFilter as shown above
// opt.SchemaFilter<MyVogenSchemaFilter>();
Expand Down
6 changes: 3 additions & 3 deletions src/Vogen/GenerateCodeForBsonSerializers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,12 @@ public static void TryRegister() { }

string ClassNameForRegistering()
{
var assemblyName = new SanitizedAssemblyName(compilation.AssemblyName);
string projectName = ProjectName.FromAssemblyName(compilation.AssemblyName ?? "").Value;

string s = "BsonSerializationRegister";
if(assemblyName.Value.Length > 0)
if(projectName.Length > 0)
{
s = $"{s}For{assemblyName}";
s = $"{s}For{projectName}";
}

return s;
Expand Down
7 changes: 4 additions & 3 deletions src/Vogen/GenerateCodeForSystemTextJsonConverterFactories.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Vogen.Types;

namespace Vogen;

Expand All @@ -27,10 +28,10 @@ public static void WriteIfNeeded(VogenConfiguration? globalConfig,


var entries = workItems.Where(i => i.Config.Conversions.HasFlag(Conversions.SystemTextJson)).Select(BuildEntry);

var fullNamespace = ProjectName.FromAssemblyName(compilation.Assembly.Name);

var fullNamespace = compilation.Assembly.Name;

var ns = string.IsNullOrEmpty(fullNamespace) ? string.Empty : $"namespace {fullNamespace};";
var ns = $"namespace {fullNamespace};";

string source =
$$"""
Expand Down
12 changes: 9 additions & 3 deletions src/Vogen/Types/ProjectName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@ internal class ProjectName
{
private ProjectName(string value) => Value = value;

/// <summary>
/// Replaces [., -] with [_] for use as type type names etc.
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
public static ProjectName FromAssemblyName(string assemblyName)
{
assemblyName = assemblyName.Replace(".", "");
assemblyName = assemblyName.Replace(",", "");
assemblyName = assemblyName.Replace(" ", "");
assemblyName = assemblyName.Replace(".", "_");
assemblyName = assemblyName.Replace(",", "_");
assemblyName = assemblyName.Replace(" ", "_");
assemblyName = assemblyName.Replace("-", "_");

return new(assemblyName);
}
Expand Down
19 changes: 0 additions & 19 deletions src/Vogen/Types/SanitizedAssemblyName.cs

This file was deleted.

12 changes: 10 additions & 2 deletions tests/Shared/ProjectBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public sealed class ProjectBuilder
private TargetFramework? _targetFramework;
private bool _excludeStj;
private LanguageVersion _languageVersion = LanguageVersion.Default;
private string _assemblyName = "generator";

public ProjectBuilder WithTargetFramework(TargetFramework targetFramework)
{
Expand Down Expand Up @@ -273,6 +274,13 @@ public ProjectBuilder WithUserSource(string userSource)
return this;
}

public ProjectBuilder WithAssemblyName(string assemblyName)
{
_assemblyName = assemblyName;

return this;
}

public ProjectBuilder WithNugetPackages(IEnumerable<NuGetPackage> packages)
{
foreach (var nuGetPackage in packages)
Expand Down Expand Up @@ -322,8 +330,8 @@ internal static class IsExternalInit {}
options = options.WithSpecificDiagnosticOptions(diagnostics);

var compilation = CSharpCompilation.Create(
assemblyName: "generator",
syntaxTrees: new[] { usersSyntaxTree, isExternalInitSyntaxTree },
assemblyName: _assemblyName,
syntaxTrees: [usersSyntaxTree, isExternalInitSyntaxTree],
_references,
options);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Threading.Tasks;
using Vogen;

namespace SnapshotTests.BugFixes;

// See https://github.com/SteveDunn/Vogen/issues/717
public class Bug717_Stj_does_not_escape_dashed_namespace
{
[Fact]
public async Task Test()
{
var source = """
using System;
using Vogen;
using System.Text.Json;
namespace My_Namespace;
[ValueObject(typeof(Guid))]
public partial struct Vo;
""";

await new SnapshotRunner<ValueObjectGenerator>()
.WithAssemblyName("MY-PROJECT")
.WithSource(source)
.IgnoreInitialCompilationErrors()
.RunOnAllFrameworks();
}
}
Loading

0 comments on commit 8356bd6

Please sign in to comment.