Skip to content
Draft
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
83 changes: 73 additions & 10 deletions src/IntelliTect.Coalesce.CodeGeneration.Api/Generators/ClassDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using IntelliTect.Coalesce.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;

namespace IntelliTect.Coalesce.CodeGeneration.Api.Generators;
Expand Down Expand Up @@ -36,6 +37,7 @@ public override void BuildOutput(CSharpCodeBuilder b)
"IntelliTect.Coalesce.Mapping",
"IntelliTect.Coalesce.Models",
"System",
"System.Collections.Immutable",
"System.Linq",
"System.Collections.Generic",
"System.Security.Claims",
Expand All @@ -46,6 +48,8 @@ public override void BuildOutput(CSharpCodeBuilder b)
b.Line($"using {ns};");
}

b.Line();
b.Line("#pragma warning disable CS0618");
b.Line();

using (b.Block($"namespace {DtoNamespace}"))
Expand All @@ -54,6 +58,9 @@ public override void BuildOutput(CSharpCodeBuilder b)
b.Line();
WriteResponseDto(b);
}

b.Line();
b.Line("#pragma warning restore CS0618");
}

private void WriteParameterDto(CSharpCodeBuilder b)
Expand Down Expand Up @@ -328,7 +335,7 @@ private void WriteResponseDto(CSharpCodeBuilder b)
b.DocComment("Map from the domain object to the properties of the current DTO instance.");
using (b.Block($"public void MapFrom({Model.FullyQualifiedName} obj, IMappingContext context, IncludeTree tree = null)"))
{
b.Line("if (obj == null) return;");
b.Line("if (obj is null) return;");

var derivedTypes = Model.ClientDerivedTypes.ToList();
if (derivedTypes.Any())
Expand Down Expand Up @@ -459,18 +466,13 @@ private IEnumerable<string> GetPropertySetterConditional(
string setter;
if (property.Type.IsDictionary)
{
// Dictionaries aren't officially supported by Coalesce.
// This only supports dictionaries of types that require no type mapping.
// This is only a stop-gap to bridge apparent functionality that existed in 2.x versions
// of Coalesce where Dictionaries apparently "accidentally" worked to a limited extent.
// There is no frontend support at all.
setter = $"{name}?.ToDictionary(k => k.Key, v => v.Value)";
setter = DictionaryDtoToModelExpression(property.Type, name);
}
else if (property.Object != null)
{
if (property.Type.IsCollection)
{
setter = $"{name}?.Select(f => f.MapToNew(context)).{(property.Type.IsArray ? "ToArray" : "ToList")}()";
setter = $"{name}?.Select(f => f.MapToNew(context)).{CollectionMaterializerForModel(property.Type)}()";
}
else if (modelVar != null)
{
Expand All @@ -484,7 +486,7 @@ private IEnumerable<string> GetPropertySetterConditional(
else if (!property.Type.IsArray && property.Type.IsA(typeof(IList<>)))
{
// Lists of scalar values, whose DTO properties will be ICollection<>, preventing direct assignment.
setter = $"{name}?.ToList()";
setter = $"{name}?.{CollectionMaterializerForModel(property.Type)}()";
}
else
{
Expand Down Expand Up @@ -515,7 +517,11 @@ string mapCall() => property.Object.IsCustomDto
? "" // If we hang an IClassDto off an external type, or another IClassDto, no mapping needed - it is already the desired type.
: $".MapToDto<{property.Object.FullyQualifiedName}, {property.Object.ResponseDtoTypeName}>(context, tree?[nameof({dtoVar}.{name})])";

if (property.Type.IsCollection)
if (property.Type.IsDictionary)
{
setter = $"{dtoVar}.{name} = {DictionaryModelToDtoExpression(property.Type, $"obj.{name}")};";
}
else if (property.Type.IsCollection)
{
if (property.Object != null)
{
Expand Down Expand Up @@ -615,4 +621,61 @@ string mapCall() => property.Object.IsCustomDto
var statement = GetPropertySetterConditional(property, property.SecurityInfo.Read, "obj");
return (statement, setter);
}

private static bool IsImmutableDictionary(TypeViewModel type) =>
type.IsA(typeof(IImmutableDictionary<,>)) || type.IsA(typeof(ImmutableDictionary<,>));

private static bool IsImmutableList(TypeViewModel type) =>
type.IsA(typeof(IImmutableList<>)) || type.IsA(typeof(ImmutableList<>));

private static string CollectionMaterializerForModel(TypeViewModel type) =>
type.IsArray ? "ToArray" : IsImmutableList(type) ? "ToImmutableList" : "ToList";

private string DictionaryDtoToModelExpression(TypeViewModel type, string sourceExpression)
{
var args = type.GenericArgumentsFor(typeof(IDictionary<,>))
?? throw new InvalidOperationException($"Dictionary type '{type}' is missing generic arguments.");

return $"{sourceExpression}?.{(IsImmutableDictionary(type) ? "ToImmutableDictionary" : "ToDictionary")}(k => k.Key, v => {DictionaryValueDtoToModelExpression(args[1], "v.Value")})";
}

private string DictionaryValueDtoToModelExpression(TypeViewModel type, string sourceExpression)
{
if (type.IsDictionary)
{
return DictionaryDtoToModelExpression(type, sourceExpression);
}

var pureType = type.PureType;
if (pureType.ClassViewModel is not null)
{
return $"{sourceExpression}?.MapToNew(context)";
}

return sourceExpression;
}

private string DictionaryModelToDtoExpression(TypeViewModel type, string sourceExpression)
{
var args = type.GenericArgumentsFor(typeof(IDictionary<,>))
?? throw new InvalidOperationException($"Dictionary type '{type}' is missing generic arguments.");

return $"{sourceExpression}?.ToDictionary(k => k.Key, v => {DictionaryValueModelToDtoExpression(args[1], "v.Value")})";
}

private string DictionaryValueModelToDtoExpression(TypeViewModel type, string sourceExpression)
{
if (type.IsDictionary)
{
return $"({type.NullableTypeForDto(isInput: false, dtoNamespace: DtoNamespace)}){DictionaryModelToDtoExpression(type, sourceExpression)}";
}

var pureType = type.PureType;
if (pureType.ClassViewModel is { } model)
{
return $"{sourceExpression}.MapToDto<{model.FullyQualifiedName}, {model.ResponseDtoTypeName}>(context)";
}

return sourceExpression;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ internal sealed class ProjectAssemblyTypeResolver
public ProjectAssemblyTypeResolver(MsBuildProjectContext projectContext)
{
_assemblyPath = projectContext.AssemblyFullPath;
_loadContext = new ProjectAssemblyLoadContext(projectContext.AssemblyFullPath, projectContext.TargetDirectory);
_loadContext = new ProjectAssemblyLoadContext(
projectContext.AssemblyFullPath,
projectContext.TargetDirectory,
projectContext.ResolvedReferences);
_rootAssembly = new Lazy<Assembly>(() => _loadContext.LoadFromAssemblyPath(projectContext.AssemblyFullPath));
_defaultContextAssembly = new Lazy<Assembly?>(TryLoadIntoDefaultContext);
}
Expand Down Expand Up @@ -88,17 +91,29 @@ private sealed class ProjectAssemblyLoadContext : AssemblyLoadContext
private readonly AssemblyDependencyResolver _resolver;
private readonly IReadOnlyDictionary<string, string> _referencePaths;

public ProjectAssemblyLoadContext(string assemblyPath, string targetDirectory)
public ProjectAssemblyLoadContext(string assemblyPath, string targetDirectory, IEnumerable<string> resolvedReferences)
: base($"CoalesceProject:{Path.GetFileNameWithoutExtension(assemblyPath)}", isCollectible: false)
{
_resolver = new AssemblyDependencyResolver(assemblyPath);
_referencePaths = Directory
.EnumerateFiles(targetDirectory, "*.dll", SearchOption.TopDirectoryOnly)
.Concat(resolvedReferences.Where(IsRuntimeAssemblyPath))
.Where(File.Exists)
.GroupBy(path => Path.GetFileNameWithoutExtension(path), StringComparer.OrdinalIgnoreCase)
.ToDictionary(group => group.Key, group => group.First(), StringComparer.OrdinalIgnoreCase);
}

private static bool IsRuntimeAssemblyPath(string path)
{
if (!path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
return false;
}

var pathSegments = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
return !pathSegments.Contains("ref", StringComparer.OrdinalIgnoreCase);
}

protected override Assembly? Load(AssemblyName assemblyName)
{
var defaultAssembly = AssemblyLoadContext.Default.Assemblies
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.DotNet.Cli.Utils" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration" />
</ItemGroup>
</Project>
Loading