Incremental source generator not called in production build context - c#

Given a working source generator and a working test project for the generator.
Generator
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<IncludeBuildOutput>false</IncludeBuildOutput>
</PropertyGroup>
[...]
<ItemGroup>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.0.1" />
</ItemGroup>
<ItemGroup Condition="!$(DefineConstants.Contains('NET5_0_OR_GREATER'))">
<PackageReference Include="System.Memory" Version="4.5.4" />
</ItemGroup>
[...]
</Project>
namespace Rustic.DataEnumGen;
[Generator(LanguageNames.CSharp)]
[CLSCompliant(false)]
public class DataEnumGen : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterPostInitializationOutput(ctx => ctx.AddSource($"{GenInfo.DataEnumSymbol}.g.cs", SourceText.From(GenInfo.DataEnumSyntax, Encoding.UTF8)));
var enumDecls = context.SyntaxProvider.CreateSyntaxProvider(
static (s, _) => IsEnumDecl(s),
static (ctx, _) => CollectTreeInfo(ctx))
.Where(static m => m.HasValue)
.Select(static (m, _) => m!.Value);
var compilationEnumDeclUnion = context.CompilationProvider.Combine(enumDecls.Collect());
context.RegisterSourceOutput(compilationEnumDeclUnion, static (spc, source) => Generate(source.Right, spc));
}
private static bool IsEnumDecl(SyntaxNode node)
{
return node is EnumDeclarationSyntax;
}
private static GenInfo? CollectTreeInfo(GeneratorSyntaxContext context)
{
[...]
}
private static EnumDeclInfo CollectEnumDeclInfo(GeneratorSyntaxContext context, EnumMemberDeclarationSyntax memberDecl)
{
[...]
}
private static void Generate(ImmutableArray<GenInfo> members, SourceProductionContext context)
{
if (members.IsDefaultOrEmpty)
{
return;
}
foreach (var info in members.Distinct())
{
SrcBuilder text = new(2048);
GenInfo.Generate(text, in info);
context.AddSource($"{info.EnumName}Value.g.cs", SourceText.From(text.ToString(), Encoding.UTF8));
}
}
}
Test project
namespace Rustic.DataEnumGen.Tests;
[TestFixture]
public class GeneratorTests
{
private readonly StreamWriter _writer;
public GeneratorTests()
{
_writer = new StreamWriter($"GeneratorTests-{typeof(string).Assembly.ImageRuntimeVersion}.log", true);
_writer.AutoFlush = true;
Logger = new Logger(nameof(GeneratorTests), InternalTraceLevel.Debug, _writer);
}
~GeneratorTests()
{
_writer.Dispose();
}
internal Logger Logger { get; }
[Test]
public void SimpleGeneratorTest()
{
// Create the 'input' compilation that the generator will act on
Compilation inputCompilation = CreateCompilation(#"
using System;
using System.ComponentModel;
using Rustic;
namespace Rustic.DataEnumGen.Tests.TestAssembly
{
using static DummyValue;
public enum Dummy : byte
{
[Description(""The default value."")]
Default = 0,
[Rustic.DataEnum(typeof((int, int)))]
Minimum = 1,
[Rustic.DataEnum(typeof((long, long)))]
Maximum = 2,
}
public enum NoAttr
{
[Description(""This is a description."")]
This,
Is,
Sparta,
}
[Flags]
public enum NoFlags : byte
{
Flag = 1 << 0,
Enums = 1 << 1,
Are = 1 << 2,
Not = 1 << 3,
Supported = 1 << 4,
}
public static class Program
{
public static void Main()
{
DummyValue empty = default!;
DummyValue default = Default();
DummyValue min = Minimum((12, 43));
DummyValue min = Maximum((12, 43));
}
}
}
");
const int TEST_SOURCES_LEN = 1;
const int GEN_SOURCES_LEN = 3; // Attribute + Dummy + NoAttr
DataEnumGen generator = new();
GeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
driver = driver.RunGeneratorsAndUpdateCompilation(inputCompilation, out var outputCompilation, out var diagnostics);
[...Validation...]
}
private void Logging(Compilation comp, ImmutableArray<Diagnostic> diagnostics)
{
foreach (var diag in diagnostics)
{
Logger.Debug("Initial diagnostics {0}", diag.ToString());
}
foreach (var tree in comp.SyntaxTrees)
{
Logger.Debug("SyntaxTree\nName=\"{0}\",\nText=\"{1}\"", tree.FilePath, tree.ToString());
}
var d = comp.GetDiagnostics();
foreach (var diag in d)
{
Logger.Debug("Diagnostics {0}", diag.ToString());
}
}
private static Compilation CreateCompilation(string source)
=> CSharpCompilation.Create("compilation",
new[] { CSharpSyntaxTree.ParseText(source) },
new[]
{
MetadataReference.CreateFromFile(typeof(System.String).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.ComponentModel.DescriptionAttribute).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(ReadOnlySpan<char>).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.Collections.Generic.List<char>).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.CompilerServices.MethodImplAttribute).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.ISerializable).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.InteropServices.StructLayoutAttribute).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(#"C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App\6.0.1\System.Runtime.dll"),
},
new CSharpCompilationOptions(OutputKind.ConsoleApplication));
}
The test runs without error, the types and methods are generated correctly.
But I absolutely hate writing tests in plain text, plus executing the tests like so doesnt yield test coverage or unit test cases, so I want to write a production test for the source generator. As per usual I create a .Run.Tests project and add the Rustic.DataEnumGen nuget project as an analyzer. Like so
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48;net50;net60</TargetFrameworks>
<LangVersion>10.0</LangVersion>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AltCover" Version="8.2.835" />
<PackageReference Include="bogus" Version="33.0.2" />
<PackageReference Include="fluentassertions" Version="5.10.3" />
<PackageReference Include="NUnit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Rustic.DataEnumGen" Version="0.5.0" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
</Project>
using System;
using System.ComponentModel;
using NUnit.Framework;
using Rustic;
namespace Rustic.DataEnumGen.Run.Tests
{
using static DummyValue;
public enum Dummy : byte
{
[Description("The default value.")]
Default = 0,
[DataEnum(typeof((int, int)))]
Minimum = 1,
[DataEnum(typeof((long, long)))]
Maximum = 2,
}
public enum NoAttr
{
[Description("This is a description.")]
This,
Is,
Sparta,
}
[Flags]
public enum NoFlags : byte
{
Flag = 1 << 0,
Enums = 1 << 1,
Are = 1 << 2,
Not = 1 << 3,
Supported = 1 << 4,
}
[TestFixture]
public static class DataEnumRunTests
{
[Test]
public static void TestFactory()
{
DummyValue empty = default!;
DummyValue default = Default();
DummyValue min = Minimum((12, 43));
DummyValue min = Maximum((12, 43));
}
[Test]
public static void TestImplicitEnumCast()
{
Dummy default = Default();
Dummy min = Minimum((12, 43));
Dummy min = Maximum((12, 43));
}
}
}
This is the exact same code as in the previous test, but wrapped in a TestFixture instead of a console application. So I build the project with the analyzer, so that the DataEnumAttribute generated and then add the code above. But the code does not compile, because the type DataEnum or DataEnumAttribute does not exist.
First I thought that I needed to (I) ReferenceOutputAssembly, but that didn't change anything either, then I tried combinations of removing OutputItemType="Analyzer" and hoping that would result in the analyzer being called; nothing helped.
I conclude, that in this example the imported source generator, the very same that works in the first test case with the plain text compilation, is not executed before building the project, because if that was the case then type that is always added by the generator would be available in the project, and I would see some Rusic.*.g.cs in the obj/ directory. That is not the case.
So maybe the generator is not packed in the nuget package? As you can see the analyzer is being packed. Maybe I need to IncludeBuildOutput aswell? Nope not working either.
Now my question is why that is the case? Is there some specific thing, some specific attribute, I need to pay attention to when importing IIncrementalGenerator into a project compared to ISourceGenerator, because using an ISourceGenerator in a project works in the exact same way?
Is there anything else I might try to get the incremental source generator to work, or should I just revert to using a regular source generator?
References to good articles help as well, because there is effectively no doc to be found. When working I referenced most of Andrew Lock`s source generator related articles, specifically this one.
I tested this mit net 6.0.101 and a build of 6.0.2xx from like a week ago.

Related

MissingMethodException in Integration test with sqlite

I have the following exception:
I was using .NET 6 (I still had the error) and thought that it could be some conflict with the nugets I am using in my solution. It turns out that even after updating to .NET 7 the error persists when I run the test. For testing I'm using MSTest Framework and using an inmemory database (sqlite) to make integration tests. The error is happening when executing the line await context.Database.EnsureCreatedAsync();. The test classes are the following:
public class SQLiteDatabaseContextFactory : IDisposable
{
private DbConnection _connection;
private DbContextOptions<DataContext> CreateOptions()
{
return new DbContextOptionsBuilder<DataContext>()
.UseSqlite(_connection).Options;
}
public DataContext CreateContext()
{
if (_connection == null)
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
var options = CreateOptions();
using var context = new DataContext(options);
context.Database.EnsureCreated();
}
return new DataContext(CreateOptions());
}
public void Dispose()
{
if (_connection != null)
{
_connection.Dispose();
_connection = null;
}
}
}
And:
[TestClass]
public class SQLiteIntegrationTests
{
[TestMethod]
public async Task TestMethod_UsingSqliteInMemoryProvider_Success()
{
using var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<DataContext>()
.UseSqlite(connection) // Set the connection explicitly, so it won't be closed automatically by EF
.Options;
// Create the dabase schema
// You can use MigrateAsync if you use Migrations
using (var context = new DataContext(options))
{
//await context.Database.MigrateAsync();
await context.Database.EnsureCreatedAsync();
} // The connection is not closed, so the database still exists
using (var context = new DataContext(options))
{
var user = new ManualClassifier()
{
FirstName = "First",
LastName = "Last",
Email = "example#gmail.com",
Username = "firstlast123",
PasswordHash = "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf",
PasswordSalt = "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf"
};
context.ManualClassifiers.Add(user);
await context.SaveChangesAsync();
}
using (var context = new DataContext(options))
{
var count = await context.ManualClassifiers.CountAsync();
Assert.AreEqual(1, count);
var u = await context.ManualClassifiers.FirstOrDefaultAsync(user => user.Email == "example#gmail.com");
Assert.IsNotNull(u);
}
}
}
EDIT: The full error is the following:
The .csproj of the project where I'm running the tests:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.13" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VSC.Repo\VSC.Repo.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.1" />
<PackageReference Include="coverlet.collector" Version="1.3.0" />
</ItemGroup>
</Project>
Dbcontext class library .csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />
</ItemGroup>
</Project>
Any help figuring what is happening would be much appreciated. I honestly have no clue what is causing this.
Looks a lot like package version mismatch (in my practice it is the most common source of such errors). Update Microsoft.EntityFrameworkCore.Sqlite to the latest 7th version (my guess is that EF project uses that version) to match major version of EF Core packages in the tested solution.

Incremental Source Generator generated code passed compilation with syntax error

I made a Incremental Source Generator:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<IsRoslynComponent>true</IsRoslynComponent>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis" Version="4.2.0" />
<PackageReference Include="System.Text.Json" Version="6.0.0" />
</ItemGroup>
</Project>
It generates code that has an obvious syntax error
[Generator]
public class SourceGenerator : IIncrementalGenerator {
public void Initialize(IncrementalGeneratorInitializationContext context) {
context.RegisterSourceOutput(context.AdditionalTextsProvider, static (context, name) => {
string sourceCode = $#"
public class {"AAA"}{{
{{
}}
";
context.AddSource("AAA" + ".g.cs", sourceCode);
});
}
After building the solution for the first time and errors were expected. I restarted Visual Studio. I can see following code was generated:
public class AAA{
{
}
When viewing this AAA.g.cs, the text editor didn't highlight the fault of less closing braket.
Then I build the solution for the second time. It was succeeded. How can this be possible?

NET 5 error when adding migration on Entity Framework Core

I'm setting up a new project with Entity Framework Core 5 and Postgres. All my project and my context are in the same project.
When adding a migration, I'm getting this error:
/src/Api.csproj : error MSB4057: The target "GetEFProjectMetadata" does not exist in the project. Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
EF Core version: 5.0.1
Target framework: net5.0
These are all the commands I tried:
dotnet ef migrations add NewMigration
dotnet ef migrations add NewMigration --msbuildprojectextensionspath
dotnet ef migrations add NewMigration -p ".\src\Api.csproj"
dotnet ef migrations add NewMigration -p ".\src\Api.csproj" --msbuildprojectextensionspath*
I have tried a lot of options I found on the internet, but none worked.
if i add -v , the last lines are:
Using project '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj'.
Using startup project '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj'.
Writing '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/obj/Api.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpbscOwZ.tmp /verbosity:quiet /nologo /media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj
/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj : error MSB4057: O destino "GetEFProjectMetadata" não existe no projeto.
Microsoft.EntityFrameworkCore.Tools.CommandException: Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
at Microsoft.EntityFrameworkCore.Tools.Project.FromFile(String file, String buildExtensionsDir, String framework, String configuration, String runtime)
at Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute(String[] _)
at Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.<Configure>b__0(String[] args)
at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
Api.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<DocumentationFile>bin\Debug\net5.0\comments.xml</DocumentationFile>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<noWarn>1591;1572;1573</noWarn>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
<CodeAnalysisRuleSet>../roslynator.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="9.4.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="9.4.0" />
<PackageReference Include="Mapster" Version="7.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
<PackageReference Include="Scrutor" Version="3.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.1" />
<PackageReference Include="jaeger" Version="0.4.2" />
<PackageReference Include="OpenTracing.Contrib.NetCore" Version="0.7.1" />
<PackageReference Include="RestSharp" Version="106.2.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.OpenApi" Version="1.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="5.6.3" />
</ItemGroup>
<ItemGroup>
<None Include="*.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="Always" />
<None Include="Locales\**\*.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="Always" />
</ItemGroup>
</Project>
Program.cs:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace Linear.Service_Name.Api
{
public static class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
}
}
Startup.cs:
using Linear.Service_Name.DataBase.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApiController]
namespace Linear.Service_Name.Api
{
public class Startup
{
private IWebHostEnvironment _environment { get; }
public Startup(IConfiguration _, IWebHostEnvironment environment)
{
_environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Context>(opt => opt
.UseNpgsql(EnvVariables.LINEAR_API_DOMAIN_NAME_DB_CONNECTION_STRING)
);
services.AddCommonsServices<Context>(new CommonServices
{
Env = _environment,
ConnectionString = EnvVariables.LINEAR_API_DOMAIN_NAME_DB_CONNECTION_STRING,
Assembly = Assembly.GetExecutingAssembly(),
Swagger = new CommonServices.SwaggerSettings{
Version = "v1",
Title = "Service_Name",
Description = "API REST do Módulo de " + ("Service_Name").ToUpper()
+ " da solução SG Web."
}
});
}
public void Configure(IApplicationBuilder app)
{
app.UserCommonsMiddlewares(new CommonMiddlewares
{
Env = _environment,
PathBase = EnvVariables.LINEAR_API_SERVICE_NAME_BASE_PATH,
Swagger = new CommonMiddlewares.SwaggerSettings
{
Version = "v1",
Title = "Service_Name"
}
});
}
}
}
Context.cs:
using Linear.Infrastructure.Data.Audit;
using Linear.Infrastructure.Data.MultiTenancy;
using Microsoft.EntityFrameworkCore;
namespace Linear.Service_Name.DataBase.Entities
{
public class Context : DbContext
{
public virtual DbSet<Sample_NamesEntity> Sample_Names { get; set; }
private readonly IAuditEntity _auditEntity;
private readonly IMultiTenancy _multiTenancy;
public Context(DbContextOptions<Context> options, IAuditEntity auditEntity,
IMultiTenancy multiTenancy)
: base(options)
{
_auditEntity = auditEntity;
_multiTenancy = multiTenancy;
}
#region Métodos Protegidos
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.ApplyConfigurationsFromAssembly(typeof(Context).Assembly);
#endregion
#region Métodos Públicos
public override int SaveChanges()
{
_multiTenancy.OnSaveChanges(this);
_auditEntity.OnSaveChanges(this);
return base.SaveChanges();
}
public int SaveChangesWithoutMultiTenancy()
{
_auditEntity.OnSaveChanges(this);
return base.SaveChanges();
}
public int SaveChangesWithoutMultiTenancyAndAudit() => base.SaveChanges();
#endregion
}
}
Project link to download:
https://drive.google.com/file/d/1YWlm_teyGMjJe193AwrFqe3VAeVVKWLq/view?usp=sharing
I've been stuck with this problem for over 3 hours, tried a lot of suggestions on internet and still no sucess, i appreciate if i have some help.
After doing some research, it seems that there is a problem with projects with docker integration and the EF Core tooling.
I have downloaded your code and this is the content of your Directory.Build.props
<Project>
<PropertyGroup>
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/obj/**/*</DefaultItemExcludes>
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/bin/**/*</DefaultItemExcludes>
</PropertyGroup>
<PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' == 'true'">
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/container/</BaseIntermediateOutputPath>
<BaseOutputPath>$(MSBuildProjectDirectory)/bin/container/</BaseOutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' != 'true'">
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/local/</BaseIntermediateOutputPath>
<BaseOutputPath>$(MSBuildProjectDirectory)/bin/local/</BaseOutputPath>
</PropertyGroup>
</Project>
According to #bricelam in this issue the root of the problem lies here:
Changing BaseIntermediateOutputPath from its default when not running inside a
container breaks the EF Core tooling experience (*)
Since your BaseIntermediateOutputPath was changed from its default to obj/local when running outside the docker container, what you need to do is let the EF Core CLI know where to find that folder. You can accomplish that by using the --msbuildprojectextensionspath parameter. In your case, it would like like this (as suggested here):
dotnet ef migrations add NewMigration --msbuildprojectextensionspath obj/local
If you are still unable to make it work, you could follow the discussion in this other issue. In there, it was suggested that another possible fix is to change a bit your Directory.Build.props and *.csproj files so that the latter looks like the following:
<Project> <!-- Note: No Sdk="" here. -->
<PropertyGroup>
<!-- Don't use $(Configuration) since it isn't set yet. -->
<MSBuildProjectExtensionsPath>$(MSBuildProjectDirectory)\_intermediate_\</MSBuildProjectExtensionsPath>
</PropertyGroup>
<!-- MSBuildProjectExtensionsPath must be set before this gets imported. Directory.Build.props is too late. -->
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
<!-- (Project content goes here) -->
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
</Project>

Edit and Continue doesn't work with Roslyn compiled class library

Background
I'm trying to get Edit and Continue to work with a class library I'm compiling at runtime using Roslyn. This is for adding modding support to a game I'm developing.
Breakdown of problem
I have one class library project (A) with source files (.cs)
I have another console application project (B) in another solution that does the following:
Compiles all of project A's source files
Emits a dll and pdb
Loads the emitted dll and pdb via an assembly context
Calls a static method defined within project B
My desire is to be able to attach a debugger to a running process of project B in an instance of VS with project A loaded and be able to break, edit project A's code, and continue with my changes being executed
Currently, I am only able to break and continue
Any edits lead to the following notification:
This source file has changed. It no longer matches the version of the file used to build the application being debugged.
Source
Project A: DebuggableClassLibrary.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
Project A: Test.cs
using System;
namespace DebuggableClassLibrary
{
public class Test
{
public static int Ct = 0;
public static void SayHello()
{
Ct++;
Console.WriteLine("Hello World");
}
}
}
Project B: DynamicLoading.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" />
</ItemGroup>
</Project>
Project B: Program.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
namespace DynamicLoading
{
class Program
{
static void Main(string[] args)
{
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location),
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)
};
var files = Directory.GetFiles(#"C:\Users\mrbri\source\repos\DebuggableClassLibrary\DebuggableClassLibrary", "*.cs");
var assemblyName = "DebuggableClassLibrary.dll";
var debug = true;
var allowUnsafe = false;
var outputDirectory = #"C:\Users\mrbri\Documents\Test";
var preprocessorSymbols = debug ? new string[] { "DEBUG" } : new string[] { };
var parseOptions = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: preprocessorSymbols);
var compilation = CSharpCompilation.Create(
assemblyName: assemblyName,
syntaxTrees: files.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, f, Encoding.UTF8)),
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
optimizationLevel: debug ? OptimizationLevel.Debug : OptimizationLevel.Release,
allowUnsafe: allowUnsafe
));
var pePath = Path.Combine(outputDirectory, assemblyName);
var pdbPath = Path.Combine(outputDirectory, Path.ChangeExtension(assemblyName, ".pdb"));
using (var peStream = new FileStream(pePath, FileMode.Create))
using (var pdbStream = new FileStream(pdbPath, FileMode.Create))
{
var results = compilation.Emit(
peStream: peStream,
pdbStream: pdbStream,
options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)
);
}
var assemblyLoadContext = new SimpleUnloadableAssemblyLoadContext();
var assembly = assemblyLoadContext.LoadFromStream(File.OpenRead(pePath), File.OpenRead(pdbPath));
var type = assembly.GetTypes().First();
var method = type.GetMethod("SayHello");
while (true)
{
method.Invoke(null, null);
}
}
}
internal class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
public SimpleUnloadableAssemblyLoadContext(): base(true) { }
protected override Assembly Load(AssemblyName assemblyName) => null;
}
}
Attempts at solutions and observations
Compiling project A manually through VS and loading the generated pdb and dll exactly as I do for the Roslyn compiled one does allow for Edit and Continue
Comparing project A's dlls generated via Roslyn and VS in JetBrains dotPeek did yield some interesting differences that stem from the compilation time generated .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs that I do not include when I compile in project B
Going through the trouble of compiling project A via a MSBuildWorkspace Project did not allow Edit and Continue, although did include .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs
Alternatives
I am open to Roslyn alternatives/wrappers that do have Edit and Continue support.
Edit and Continue does not support this scenario. The project for the library being edited needs to be loaded in VS (in the current solution) and the program needs to be launched with the debugger attached.

How to set the culture in a dotnetcore xunit test

I have the following unit test that I'm porting from a .Net Framework library to .Net core xunint test library. The project the unit test needs to be added to is
https://github.com/dotliquid/dotliquid
and is being added to the selected file as show here
The unit test I'm trying to add is
[Test]
public void ParsingWithCommaDecimalSeparatorShouldWork()
{
var ci = new CultureInfo(CultureInfo.CurrentCulture.Name)
{
NumberFormat =
{
NumberDecimalSeparator = ","
, NumberGroupSeparator = "."
}
};
Thread.CurrentThread.CurrentCulture = ci;
var t = Template.Parse("{{2.5}}");
var result = t.Render( new Hash(), CultureInfo.InvariantCulture );
Assert.AreEqual( result, "2.5" );
}
However the test fails to compile in dotnet core.
Severity Code Description Project File Line Suppression State
Error CS1061 'Thread' does not contain a definition for
'CurrentCulture' and no extension method 'CurrentCulture' accepting a
first argument of type 'Thread' could be found (are you missing a
using directive or an assembly
reference?) DotLiquid.Tests(net451) C:\Users\phelan\workspace\dotliquid\src\DotLiquid.Tests\OutputTests.cs 113 N/A
I need to have different unit tests with different cultures. I would like to create an XUnit theory where each instance passes in a different culture for the unit test to verify against. How is this done in .NetCore?
I looked at some of the dotnet source and I found this.
CultureInfo.DefaultThreadCurrentCulture = ci;
Basically it looks like you can set the default thread current culture from a static property of CultureInfo rather than from Thread.CurrentThread
poking around a bit more I found this
public CultureInfo CurrentCulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return CultureInfo.CurrentCulture;
}
set
{
Contract.EndContractBlock();
// If you add more pre-conditions to this method, check to see if you also need to
// add them to CultureInfo.DefaultThreadCurrentCulture.set.
if (m_CurrentCulture == null && m_CurrentUICulture == null)
nativeInitCultureAccessors();
CultureInfo.CurrentCulture = value;
}
}
This is in Thread.cs. So you can set the CultureInfo.CurrentCulture property explicitly.
example:
CultureInfo.CurrentCulture = new CultureInfo("en-GB"); ;
Assert.Equal("£1,000.00", String.Format("{0:C}", 1000));
CultureInfo.CurrentCulture = new CultureInfo("en-US"); ;
Assert.Equal("$1,000.00", String.Format("{0:C}", 1000));
csproj file for unit test project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<IsPackable>false</IsPackable>
<ApplicationIcon />
<OutputType>Library</OutputType>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0-preview-20170425-07" />
<PackageReference Include="xunit" Version="2.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
</ItemGroup>
</Project>
The solution is to set
CultureInfo.DefaultThreadCurrentCulture = ci;
and then spin up a new thread. This will set the current culture for the next thread. The final test case is.
[Test]
public void ParsingWithCommaDecimalSeparatorShouldWork()
{
var ci = new CultureInfo(CultureInfo.CurrentCulture.Name)
{
NumberFormat =
{
NumberDecimalSeparator = ","
, NumberGroupSeparator = "."
}
};
CultureInfo.DefaultThreadCurrentCulture = ci;
var result = "";
var thread = new Thread
( delegate()
{
Console.WriteLine(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
Console.WriteLine(CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator);
var t = Template.Parse("{{2.5}}");
result = t.Render(new Hash(), CultureInfo.InvariantCulture);
} );
thread.Start();
thread.Join();
Assert.AreEqual(result, "2.5");
}
which is a bit messy but get the job done.

Categories