In some solutions I use direct references to internal projects during development and switch to nuget references for release. However, adding 30+ projects to new solutions manually is a tedious task.
I was wondering whether there is a quicker way to do this. With projects it's pretty easy because you just copy/paste the xml but solution files are not that easy to edit but maybe there is some trick?
You can use the dotnet CLI.
For Linux:
dotnet sln MySolution.sln add **/*.csproj
For Windows PowerShell:
dotnet sln MySolution.sln add (Get-ChildItem -Recurse *.csproj)
I've done some reaserch on the visualstudio extensibility based on #JamesFaix link and I managed to put together this small piece of code:
using System;
using System.IO;
using System.Linq;
using EnvDTE;
using EnvDTE80;
class Program
{
static void Main(string[] args)
{
// VS2019
var dteType = Type.GetTypeFromProgID("VisualStudio.DTE.16.0", true);
var dte = (EnvDTE.DTE)System.Activator.CreateInstance(dteType);
var sln = (SolutionClass)dte.Solution;
// Solution to add projects to
sln.Open(#"C:\Projects\MyProject\MySolution.sln");
// Projects should be added to the "lib" solution-folder.
var lib = FindSolutionFolderOrCreate(sln, "lib");
// These projects should be added.
var projectPaths = new[]
{
#"C:\Projects\MyLibs\Lib1.csproj",
#"C:\Projects\MyLibs\Lib2.csproj"
};
foreach (var path in projectPaths)
{
var name = Path.GetFileNameWithoutExtension(path);
// If project not already in the solution-folder then add it.
if(!(lib.Parent.ProjectItems.Cast<ProjectItem>().Any(pi => pi.Name == name)))
{
lib.AddFromFile(path);
}
}
dte.Solution.Close(true);
}
private static SolutionFolder FindSolutionFolderOrCreate(SolutionClass sln, string folderName)
{
foreach (var x in sln.Projects)
{
if (x is Project p && p.Name.Equals(folderName, StringComparison.OrdinalIgnoreCase))
{
return (SolutionFolder)p.Object;
}
}
var proj = (sln as Solution2).AddSolutionFolder(folderName);
return (SolutionFolder)proj.Object;
}
}
*.csproj file of this utility:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<!--<TargetFramework>netcoreapp2.2</TargetFramework>-->
<TargetFramework>net47</TargetFramework>
<EnableUnmanagedDebugging>true</EnableUnmanagedDebugging>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Reference Include="EnvDTE">
<HintPath>..\..\..\..\..\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies\envdte.dll</HintPath>
</Reference>
<Reference Include="EnvDTE80">
<HintPath>..\..\..\..\..\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies\envdte80.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
I'm using net47 here because netcoreapp doesn't allow you to debug COM objects which makes it really a painful experience.
You'll also need references to the two EnvDTE files.
Related
I'm doing a C# source generator and I want the developer to influence the output of the generated types based on a class with a specified interface that he will implement.
The interface is declared in a project called Core.dll.
namespace Core
{
public interface ITask
{
void Run();
}
}
The source generator gets called, compiles the class implementing the interface and executes a method.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using DynamicCompilationNetStandard2._0;
namespace Generator;
[Generator]
public partial class Generator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var classDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (x, _) => x is ClassDeclarationSyntax c,
transform: static (ctx, _) => (ClassDeclarationSyntax)ctx.Node)
.Where(x => x is not null);
var compilationAndClasses = context.CompilationProvider.Combine(classDeclarations.Collect());
context.RegisterSourceOutput(compilationAndClasses, static (spc, source) => Execute(source.Item1, source.Item2, spc));
}
private static void Execute(Compilation compilation, ImmutableArray<ClassDeclarationSyntax> classes, SourceProductionContext context)
{
if (classes.IsDefaultOrEmpty)
{
return;
}
try
{
var source = """
using System;
using Core;
namespace Consumer
{
public class MyTask : ITask
{
public void Run()
{
Console.WriteLine("Finished");
}
}
}
""";
Executor.Execute(source);
}
catch (Exception ex)
{
throw;
}
}
}
The executor class dynamically compiles the class and runs it.
using Basic.Reference.Assemblies;
using Core;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.IO;
using System.Reflection;
namespace DynamicCompilationNetStandard2._0
{
public static class Executor
{
public static void Execute(string source)
{
var syntaxTree = SyntaxFactory.ParseSyntaxTree(source);
var compilation = CSharpCompilation.Create(assemblyName: Path.GetRandomFileName())
.WithReferenceAssemblies(ReferenceAssemblyKind.NetStandard20)
.AddReferences(
MetadataReference.CreateFromFile(typeof(ITask).Assembly.Location))
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddSyntaxTrees(syntaxTree);
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (!result.Success)
{
throw new Exception(result.ToString());
}
ms.Seek(0, SeekOrigin.Begin);
var assembly = Assembly.Load(ms.ToArray());
try
{
var types = assembly.GetTypes();
}
catch (Exception ex)
{
throw;
}
dynamic task = assembly.CreateInstance("Consumer.MyTask");
task.Run();
}
}
}
}
All the framework references are correctly loaded using reference assemblies by using the nuget package Basic.Reference.Assemblies. The only one not loading is my library Core.dll but it is added as a reference to the CSharpCompilation. When I read the FusionLogs, it's like Roslyn can't load a Dll outside of it's folder.
=== Pre-bind state information ===
LOG: DisplayName = Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
(Fully-specified)
LOG: Appbase = file:///G:/Program Files/Microsoft Visual Studio/2022/Preview/MSBuild/Current/Bin/Roslyn/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: G:\Program Files\Microsoft Visual Studio\2022\Preview\MSBuild\Current\Bin\Roslyn\csc.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///G:/Program Files/Microsoft Visual Studio/2022/Preview/MSBuild/Current/Bin/Roslyn/Core.DLL.
LOG: Attempting download of new URL file:///G:/Program Files/Microsoft Visual Studio/2022/Preview/MSBuild/Current/Bin/Roslyn/Core/Core.DLL.
LOG: Attempting download of new URL file:///G:/Program Files/Microsoft Visual Studio/2022/Preview/MSBuild/Current/Bin/Roslyn/Core.EXE.
LOG: Attempting download of new URL file:///G:/Program Files/Microsoft Visual Studio/2022/Preview/MSBuild/Current/Bin/Roslyn/Core/Core.EXE.
To verify that everything else is good, I created a console app in .Net 7 executing the same code and it works!
using DynamicCompilationNetStandard2._0;
var source = """
using System;
using Core;
namespace Consumer
{
public class MyTask : ITask
{
public void Run()
{
Console.WriteLine("Finished");
}
}
}
""";
Executor.Execute(source);
If I put Core.dll manually inside the G:/Program Files/Microsoft Visual Studio/2022/Preview/MSBuild/Current/Bin/Roslyn folder, it works with the source generator but I don't want the developer to copy the file manually.
The question is, how can I make it work with a source generator? It is only a simple Dll to load.
The sources are ready to debug with the source generator. https://github.com/adampaquette/DynamicCompilationTests
Make sure to have the component .NET Compiler Platform SDK installed in VS2022.
Thanks!
Update
Here is the Generator.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
<IsRoslynComponent>true</IsRoslynComponent>
<PreserveCompilationContext>true</PreserveCompilationContext>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies" Version="1.4.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.4.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="4.4.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" />
<ProjectReference Include="..\DynamicCompilationNetStandard2.0\DynamicCompilationNetStandard2.0.csproj" />
</ItemGroup>
</Project>
Edit
One fix was to resolve the DLL inside the no context context for the debug to work but when compiling a consumer project the DLL is not found.
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
private Assembly? CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) =>
args.Name == "FluentType.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
? AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName == args.Name)
: null;
Assuming your source generator will be packaged in a nuget package, you will have to manually add all assemblies that the source generator uses to the package.
This means the package needs to contain all assemblies in the transitive closure of the source generator's dependencies.
The only exceptions are the target framework assemblies and certain assemblies that will be provided by the roslyn environment at source generation runtime, like System.Collections.Immutable.
Be aware that the latter can differ depending on compilation environment.
Compiling in Visual Studio will run the .NET Framework version of MSBuild.
Compiling via dotnet CLI will run the .NET Core version of MSBuild.
Those are different applications running in different runtimes and will cause different assemblies and/or different assembly versions to be available. If you want your source generator to work for both Visual Studio and the dotnet CLI you need to be careful here.
I once wrote a source generator as a PoC and ran into similar problems.
You can find it at https://github.com/shuebner/XsdToSource. Maybe it can help you as a reference.
Other helpful resources include
https://www.meziantou.net/packaging-a-roslyn-analyzer-with-nuget-dependencies.htm
https://natemcmaster.com/blog/2017/07/05/msbuild-task-in-nuget/ (this is about MSBuild tasks, but explains some ways in which the MSBuild runtime environments differs)
How should a single-file .Net Core 3.0 Web API application be configured to look for the appsettings.json file that is in the same directory that the single-file application is built to?
After running
dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
The directory looks like this:
XX/XX/XXXX XX:XX PM <DIR> .
XX/XX/XXXX XX:XX PM <DIR> ..
XX/XX/XXXX XX:XX PM 134 appsettings.json
XX/XX/XXXX XX:XX PM 92,899,983 APPNAME.exe
XX/XX/XXXX XX:XX PM 541 web.config
3 File(s) 92,900,658 bytes
However, attempting to run APPNAME.exe results in the following error
An exception occurred, System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\Users\USERNAME\AppData\Local\Temp\.net\APPNAME\kyl3yc02.5zs\appsettings.json'.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.HandleException(ExceptionDispatchInfo info)
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
...
I tried solutions from a similar, but distinct question, as well as other Stack Overflow questions.
I attempted to pass the following to SetBasePath()
Directory.GetCurrentDirectory()
environment.ContentRootPath
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
Each led to the same error.
The root of the issue is that the PublishSingleFile binary is unzipped and run from a temp directory.
In the case of this single file app, the location it was looking appsettings.json was the following directory:
C:\Users\USERNAME\AppData\Local\Temp\.net\APPNAME\kyl3yc02.5zs
All of the above methods point to the place that the file is unzipped to, which is different than the place it was run from.
I found an issue on GitHub here titled PublishSingleFile excluding appsettings not working as expected.
That pointed to another issue here titled single file publish: AppContext.BaseDirectory doesn't point to apphost directory
In it, a solution was to try Process.GetCurrentProcess().MainModule.FileName
The following code configured the application to look at the directory that the single-executable application was run from, rather than the place that the binaries were extracted to.
config.SetBasePath(GetBasePath());
config.AddJsonFile("appsettings.json", false);
The GetBasePath() implementation:
private string GetBasePath()
{
using var processModule = Process.GetCurrentProcess().MainModule;
return Path.GetDirectoryName(processModule?.FileName);
}
If you're okay with having files used at runtime outside of the executable, then you could just flag the files you want outside, in csproj. This method allows for live changes and such in a known location.
<ItemGroup>
<None Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</None>
<None Include="appsettings.Development.json;appsettings.QA.json;appsettings.Production.json;">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
<DependentUpon>appsettings.json</DependentUpon>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</None>
</ItemGroup>
<ItemGroup>
<None Include="Views\Test.cshtml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</None>
</ItemGroup>
If this is not acceptable, and must have ONLY a single file, I pass the single-file-extracted path as the root path in my host setup. This allows configuration, and razor (which I add after), to find its files as normal.
// when using single file exe, the hosts config loader defaults to GetCurrentDirectory
// which is where the exe is, not where the bundle (with appsettings) has been extracted.
// when running in debug (from output folder) there is effectively no difference
var realPath = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
var host = Host.CreateDefaultBuilder(args).UseContentRoot(realPath);
Note, to truly make a single file, and no PDB, you'll also need:
<DebugType>None</DebugType>
My application is on .NET Core 3.1, is published as a single file and runs as a Windows Service (which may or may not have an impact on the issue).
The proposed solution with Process.GetCurrentProcess().MainModule.FileName as the content root works for me, but only if I set the content root in the right place:
This works:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseContentRoot(...);
webBuilder.UseStartup<Startup>();
});
This does not work:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseContentRoot(...)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
this is the "piggy back" answer(s) area.
First, upvote the above answer by "RS" that I reference in this answer. That was the magic.
Short answer is "use RS's answer AND set that value in all the right places.". I show the 2 places to SET the values below.
My specific ADDITION (not mentioned anywhere else) is:
IConfigurationBuilder builder = new ConfigurationBuilder()
/* IMPORTANT line below */
.SetBasePath(realPath)
Longer answer is:
I needed the above answers AND I have some additions.
In my output (i'll show code later), here is the difference between the 2 answers above.
GetBasePath='/mybuilddir/myOut'
realPath='/var/tmp/.net/MyCompany.MyExamples.WorkerServiceExampleOne.ConsoleOne/jhvc5zwc.g25'
where '/mybuilddir/myOut' was the location here I published my single file..in my docker definition file.
GetBasePath did NOT work when using PublishSingleFile
"realPath" was the way I finally got it to work. Aka, the answer above. : How can I get my .NET Core 3 single file app to find the appsettings.json file?
and when you see the value of "realPath"...then it all makes sense. the singleFile is being extracted ~somewhere....and RS figured out the magic sauce on where that extraction place is.
I will show my entire Program.cs, that will give context to everything.
Note, I had to set "realPath" in TWO places.
I marked the important things with
/* IMPORTANT
Full code below, which (again) borrows from RS's answer : How can I get my .NET Core 3 single file app to find the appsettings.json file?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
namespace MyCompany.MyExamples.WorkerServiceExampleOne.ConsoleOne
{
public static class Program
{
public static async Task<int> Main(string[] args)
{
/* easy concrete logger that uses a file for demos */
Serilog.ILogger lgr = new Serilog.LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("MyCompany.MyExamples.WorkerServiceExampleOne.ConsoleOne.log.txt", rollingInterval: Serilog.RollingInterval.Day)
.CreateLogger();
try
{
/* look at the Project-Properties/Debug(Tab) for this environment variable */
string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
Console.WriteLine(string.Format("ASPNETCORE_ENVIRONMENT='{0}'", environmentName));
Console.WriteLine(string.Empty);
string basePath = Directory.GetCurrentDirectory();
basePath = GetBasePath();
Console.WriteLine(string.Format("GetBasePath='{0}'", basePath));
Console.WriteLine(string.Empty);
// when using single file exe, the hosts config loader defaults to GetCurrentDirectory
// which is where the exe is, not where the bundle (with appsettings) has been extracted.
// when running in debug (from output folder) there is effectively no difference
/* IMPORTANT 3 lines below */
string realPath = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
Console.WriteLine(string.Format("realPath='{0}'", realPath));
Console.WriteLine(string.Empty);
IConfigurationBuilder builder = new ConfigurationBuilder()
/* IMPORTANT line below */
.SetBasePath(realPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", true, true)
.AddEnvironmentVariables();
IConfigurationRoot configuration = builder.Build();
IHost host = Host.CreateDefaultBuilder(args)
/* IMPORTANT line below */
.UseContentRoot(realPath)
.UseSystemd()
.ConfigureServices((hostContext, services) => AppendDi(services, configuration, lgr)).Build();
await host.StartAsync();
await host.WaitForShutdownAsync();
}
catch (Exception ex)
{
string flattenMsg = GenerateFullFlatMessage(ex, true);
Console.WriteLine(flattenMsg);
}
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
return 0;
}
private static string GetBasePath()
{
using var processModule = System.Diagnostics.Process.GetCurrentProcess().MainModule;
return Path.GetDirectoryName(processModule?.FileName);
}
private static string GenerateFullFlatMessage(Exception ex)
{
return GenerateFullFlatMessage(ex, false);
}
private static void AppendDi(IServiceCollection servColl, IConfiguration configuration, Serilog.ILogger lgr)
{
servColl
.AddSingleton(lgr)
.AddLogging();
servColl.AddHostedService<TimedHostedService>(); /* from https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio and/or https://github.com/dotnet/AspNetCore.Docs/blob/master/aspnetcore/fundamentals/host/hosted-services/samples/3.x/BackgroundTasksSample/Services/TimedHostedService.cs */
servColl.AddLogging(blder =>
{
blder.AddConsole().SetMinimumLevel(LogLevel.Trace);
blder.SetMinimumLevel(LogLevel.Trace);
blder.AddSerilog(logger: lgr, dispose: true);
});
Console.WriteLine("Using UseInMemoryDatabase");
servColl.AddDbContext<WorkerServiceExampleOneDbContext>(options => options.UseInMemoryDatabase(databaseName: "WorkerServiceExampleOneInMemoryDatabase"));
}
private static string GenerateFullFlatMessage(Exception ex, bool showStackTrace)
{
string returnValue;
StringBuilder sb = new StringBuilder();
Exception nestedEx = ex;
while (nestedEx != null)
{
if (!string.IsNullOrEmpty(nestedEx.Message))
{
sb.Append(nestedEx.Message + System.Environment.NewLine);
}
if (showStackTrace && !string.IsNullOrEmpty(nestedEx.StackTrace))
{
sb.Append(nestedEx.StackTrace + System.Environment.NewLine);
}
if (ex is AggregateException)
{
AggregateException ae = ex as AggregateException;
foreach (Exception aeflatEx in ae.Flatten().InnerExceptions)
{
if (!string.IsNullOrEmpty(aeflatEx.Message))
{
sb.Append(aeflatEx.Message + System.Environment.NewLine);
}
if (showStackTrace && !string.IsNullOrEmpty(aeflatEx.StackTrace))
{
sb.Append(aeflatEx.StackTrace + System.Environment.NewLine);
}
}
}
nestedEx = nestedEx.InnerException;
}
returnValue = sb.ToString();
return returnValue;
}
}
}
and my toplayer csproj contents:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<!-- allows one line of code to get a txt file logger #simple #notForProduction -->
<PackageReference Include="Serilog" Version="2.9.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="3.1.6" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
and my docker file for kicks:
# See https://hub.docker.com/_/microsoft-dotnet-core-sdk/
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS buildImage
WORKDIR /mybuilddir
# Copy sln and csprojs and restore as distinct layers
COPY ./src/Solutions/MyCompany.MyExamples.WorkerServiceExampleOne.sln ./src/Solutions/
COPY ./src/ConsoleOne/*.csproj ./src/ConsoleOne/
RUN dotnet restore ./src/Solutions/MyCompany.MyExamples.WorkerServiceExampleOne.sln
COPY ./src ./src
RUN dotnet publish "./src/ConsoleOne/MyCompany.MyExamples.WorkerServiceExampleOne.ConsoleOne.csproj" -c Release -o myOut -r linux-x64 /p:PublishSingleFile=true /p:DebugType=None --framework netcoreapp3.1
# See https://hub.docker.com/_/microsoft-dotnet-core-runtime/
FROM mcr.microsoft.com/dotnet/core/runtime:3.1 AS runtime
WORKDIR /myrundir
COPY --from=buildImage /mybuilddir/myOut ./
# this line is wrong for PublishSingleFile ### ENTRYPOINT ["dotnet", "MyCompany.MyExamples.WorkerServiceExampleOne.ConsoleOne.dll"]
#below is probably right...i was still working on this at time of posting this answer
./myOut/MyCompany.MyExamples.WorkerServiceExampleOne.ConsoleOne
I want to get the value of the element <Location>SourceFiles/ConnectionStrings.json</Location> that is child of <PropertyGroup /> using C#. This is located at the .csproj file for a .NET Core 2 classlib project. The structure is as follow:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<Location>SharedSettingsProvider.SourceFiles/ConnectionStrings.json</Location>
</PropertyGroup>
Which class can I use from .NET Core libraries to achieve this? (not .NET framework)
Update 1:
I want to read the value when the application (that this .csproj file builds) runs. Both before and after deployment.
Thanks
As has been discussed in comments, csproj content only controls predefined build tasks and aren't available at run-time.
But msbuild is flexible and other methods could be used to persist some values to be available at run time.
One possible approach is to create a custom assembly attribute:
[System.AttributeUsage(System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
sealed class ConfigurationLocationAttribute : System.Attribute
{
public string ConfigurationLocation { get; }
public ConfigurationLocationAttribute(string configurationLocation)
{
this.ConfigurationLocation = configurationLocation;
}
}
which can then be used in the auto-generated assembly attributes from inside the csproj file:
<PropertyGroup>
<ConfigurationLocation>https://my-config.service/customer2.json</ConfigurationLocation>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="An.Example.ConfigurationLocationAttribute">
<_Parameter1>"$(ConfigurationLocation)"</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
And then used at run time in code:
static void Main(string[] args)
{
var configurationLocation = Assembly.GetEntryAssembly()
.GetCustomAttribute<ConfigurationLocationAttribute>()
.ConfigurationLocation;
Console.WriteLine($"Should get config from {configurationLocation}");
}
I am trying to make a simple WinForm tool to assist with code generation, and I was wondering if it was possible to get the Assembly of one project into a different one that presides in a different solution. I want the form to show all of the classes and then properties for each class, and the easiest/best way I can think of doing that is like:
private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
}
If the user selects a .csproj file, is it possible to get the Assembly? Or is there a different way to get the classes/properties without recursively searching the project folder and parsing the files?
The csproj file will contain the assembly name and the output directory.
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<AssemblyName>MyAppAssemblyNameOnly</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
</PropertyGroup>
</Project>
You'll have to add .dll suffix to it to get the actual file name.
The Output Path can be found in the different Configuration <PropertyGroup> nodes.
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
There's a couple of problems I can think of right off the bat.
The DLL may not be built and so it won't exist.
There are many different configurations with there being Debug and Release by default. You'll have to decide which one to look for.
For ease, you may just want to make the user feed you a DLL if the project is not part of the solution and you don't actually need anything else.
You can also look into Roslyn and parse the files with Roslyn to get you all of the information you need too.
Here's an example straight from their page. Seems super simple and straightforward. Kind of larger than I want, but don't want to just give a single link-only suggestion.
class Program
{
static void Main(string[] args)
{
SyntaxTree tree = CSharpSyntaxTree.ParseText(
#"using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
var firstMember = root.Members[0];
var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember;
var programDeclaration = (ClassDeclarationSyntax)helloWorldDeclaration.Members[0];
var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[0];
var argsParameter = mainDeclaration.ParameterList.Parameters[0];
}
}
I have an odd solution where I need one of the projects to "compile" files in another one.
The compiler (showing here a minimal example) is as follows (MSBuild custom task):
public class MyCompileTask : Task
{
[Required]
public ITaskItem[] InputFiles { get; set; }
[Output]
public ITaskItem[] OutputFiles { get; set; }
public override bool Execute()
{
var generatedFileNames = new List<string>();
foreach (var inputFile in this.InputFiles)
{
var inputFileName = inputFile.ItemSpec;
var outputFileName = Path.ChangeExtension(inputFileName, ".res.txt");
var source = File.ReadAllText(inputFileName);
var compiled = source.ToUpper();
File.WriteAllText(outputFileName, compiled + "\n\n" + DateTime.Now);
generatedFileNames.Add(outputFileName);
}
this.OutputFiles = generatedFileNames.Select(name => new TaskItem(name)).ToArray();
return true;
}
}
As you see, it only uppercases the content of the input files.
This was project A - the "compiler" library.
Project B, for now the main application, has a file "lorem.txt" that needs to be "compiled" into "lorem.res.txt" and put as an EmbeddedResource in B.exe/B.dll.
In B.csproj I added the following:
<PropertyGroup>
<CoreCompileDependsOn>$(CoreCompileDependsOn);InvokeMyCompile</CoreCompileDependsOn>
</PropertyGroup>
<UsingTask TaskName="MyCompiler.MyCompileTask" AssemblyFile="$(MSBuildProjectDirectory)\..\MyCompiler\bin\$(Configuration)\MyCompiler.dll" />
<Target Name="MyCompile" Inputs="lorem.txt" Outputs="lorem.res.txt">
<MyCompileTask InputFiles="lorem.txt">
<Output TaskParameter="OutputFiles" PropertyName="OutputFiles" />
</MyCompileTask>
</Target>
<Target Name="InvokeMyCompile" Inputs="lorem.txt" Outputs="lorem.res.txt">
<Exec Command=""$(MSBuildBinPath)\MSBuild.exe" /t:MyCompile "$(ProjectDir)$(ProjectFileName)"" />
</Target>
(The 2 layers of targets and an explicit msbuild.exe invocation is a workaround to another problem. In fact, much of this example is stolen from that Q.)
The most important part works, i.e. when I change lorem.txt and build, lorem.res.txt gets regenerated.
However:
When lorem.res.txt is physically deleted, a build does nothing (says it's up-to-date) until I actually refresh the project in VS. So, MSBuild does not "know" that lorem.res.txt is actually required to build the project.
More importantly, when I change anything in project A, project B recompiles but does not re-run the compilation lorem.txt -> lorem.res.txt. So MSBuild does not "know" that the transformation is dependent on another project.
How can I declare these dependencies in the csproj file?
Bonus question: how to mark the output file (lorem.res.txt) as a generated EmbeddedResource so I don't have to track it in VS but it's still put into the assembly?
•When lorem.res.txt is physically deleted, a build does nothing (says it's up-to-date) until I actually refresh the project in VS. So, MSBuild does not "know" that lorem.res.txt is actually required to build the project.
I create a demo and reproduce your issue on my side, you could use msbuild command line to avoid it.
•More importantly, when I change anything in project A, project B recompiles but does not re-run the compilation lorem.txt -> lorem.res.txt. So MSBuild does not "know" that the transformation is dependent on another project.
Because the custom task reference the DLL file, when change anything in project A, you need to rebuild project to generate newer DLL file.
Bonus question: how to mark the output file (lorem.res.txt) as a generated EmbeddedResource so I don't have to track it in VS but it's still put into the assembly?
You can add custom ItemGroup in BeforeBuild target to achieve it.
<Target Name="BeforeBuild" DependsOnTargets="MyCompile">
<ItemGroup>
<Content Include="lorem.res.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Target>