How to fix NuGet package Razor runtime compilation Error? - c#

After reading through several answers (.NET Core 3.0 - Preview 2 - Razor views don't automatically recompile on change) that recomend installing Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package to get back runtime compilation, I tried the suggested solutions but the project gets the following error message simply by installing the package without even using AddRazorRuntimeCompilation():
The project "project name" must provide a value for configuration
double clicking in the error leads to the following path:
C:\Users....nuget\packages\microsoft.aspnetcore.razor.design\2.2.0\build\netstandard2.0\Microsoft.AspNetCore.Razor.Design.CodeGeneration.targets
But there is no indication as to what is wrong with this file

Add <RazorCompileOnBuild>false</RazorCompileOnBuild> to your .csproj file. That should allow you to build the project.
You also might need <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish> for publishing to a server.
See example below:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
...
<RazorCompileOnBuild>false</RazorCompileOnBuild>
<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
...
</PropertyGroup>
Found this property from this answer on a related question.

Related

MSBuild Conditional PackageReference based on .Net TargetFramework

INTRODUCTION
I am building a class library which could be used by some legacy applications targetting .Net Framework 4.0 and new applications targetting .Net Framework 4.6.1
I am adding some database/Hibernate new code in the class library that requires .Net Framework 4.6.1. This new code is incompatible with .Net Framework 4.0 because the nuGet package FluentNHibernate 3.1.0 requires .Net Framework 4.6.1 and up. And legacy application does not require this functionnality.
WHAT I AM TRYING TO ACHIEVE
I am attempting to conditionnaly build the class library so one code base and the master git branch can be used to build a version compatible for either one or the other application.
So far, I have been able to:
Define a constant indicating the target framework (FWK40)
for use within .cs code to adjust code to target framework
Conditionally define the targetted framework (TargetFrameworkVersion)
Exclude files from build when not under the right TargetFrameworkVersion
Here is what the .CSPROJ looks so far (emphasis for the relevant adjustments):
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug.Net40|AnyCPU'">
<!-- Set target framework here -->
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug.Net40\</OutputPath>
<!-- Define Build-time constant here -->
<DefineConstants Condition=" '$(TargetFrameworkVersion)' == 'v4.0'" >FWK40</DefineConstants>
</PropertyGroup>
<ItemGroup>
<-- Conditionally include .cs files here -->
<Compile Include="Database\GeneralSQL.cs" Condition="'$(TargetFrameworkVersion)' != 'v4.0'" />
<Compile Include="Database\NamingStrategy.cs" Condition="'$(TargetFrameworkVersion)' != 'v4.0'" />
<ItemGroup>
<ItemGroup>
<-- In THEORY conditionally include PackageReference here -->
<PackageReference Include="FluentNHibernate" Condition="'$(TargetFramework)' != 'net40'" >
<Version>3.1.0</Version>
</PackageReference>
</ItemGroup>
THE RESULT SO FAR
What is happenning, is I am getting a nuGet error saying:
NU1202: Package FluentNHibernate 3.1.0 is not compatible with net40 (.NETFramework,Version=v4.0). Package FluentNHibernate 3.1.0 supports:
Failed to restore C:\_projets\repos\TestSolution\TestLibrary\TestLibrary.csproj (in 19 ms).
NuGet package restore failed. Please see Error List window for detailed warnings and errors.
Not withstanding this error, the assemblies all are generated properly, the DLL Class Library itself, as well as an EXE Console application using that class library AND so far they run properly.
THE PROBLEM
I haven't been able to conditionnaly include nuGet a PackageReference.
AND The nuGet error still causes MSBuild.exe to fail, which prevents the CI/CD pipeline to work properly..
WHAT I HAVE TRIED
I have tried many many ways to get rid of nuget NU1202 error message.
#1 I have tried initially with other conditions based on $(TargetFrameworkVersion) which works througout the .csproj but to no avail.
#2 According to official documentation, nuGet ReferencePackage only supports conditions based on $(TargetFramework) adding-a-packagereference-condition as shown in the sample .csproj above. YET THIS STILL DOES NOT WORK.
I haven't been able to figure out so far what exactly the Property TargetFramework looks like. I ran MSBUILD.EXE in Verbosity level diagnostics, which dumps all the Properties, but TargetFramework wasn't listed (while others were)
I have tried to "reverse" the condition == 'net461' so that if the expected value is incorrect, it won't be included and the error would disappear => no effect, errors still there
#3 I have tried to define myself the TargetFramework property
<!-- Set target framework here -->
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFramework>net40</TargetFramework>
The outcome would be much worse!
Visual Studio did not like it, the "Configuration Manager" broke down
it would not allow to set a specific Configuration for a project.
changing from Debug.Net40 to any other configuration (or loading the project) would show a nasty error message
Current solution contains incorrect configuration mappings. It may cause projects to not work properly
And the csproj was definitely not loaded properly either and project would be skip the build step.
WHERE I AM AT NOW
I am really stuck! Can't seem to find a way to make this work.
I would hate to have to have a branch master40 and a branch master just to handle this.
I would hate to have to have two csproj different files, unless I can somehow manage to share/include one into the other AND Visual Studio would not complain
The really really right thing would be to make the conditions on the ReferencePackage to actually work as intended.
What you want is multi-targeting.
The documentation you link seems to be only applicable for SDK-style projects.
AFAIK, multi-targeting is not available with the legacy-style project format.
I suggest migrating to the SDK-style project format.
A lot of things are much simpler there, not to mention better documented.
You can use a tool to do this, like hvanbakel/CsprojToVs2017 or dotnet/try-convert. Don't be fooled by its name and wrong usage of terminology.
(since this is also mixed up on SO all the time: yes, you can use the SDK-style format with .NET Framework TFMs; SDK-style has nothing to do with either TFM or Visual Studio version, but only with minimum required MSBuild version).
Once you have done that for your particular project, the documentation for multi-targeting applies and you can use Condition on $(TargetFramework) just like you have already done, in both your PackageReference and the Compile item group and pretty much anywhere you want.

Debugging .net core 3.1 library code published on github private nuget repository is broken?

In the last few days I've battled against an issue with debugging nuget packages that I still wasn't able to solve the way I want.
All this has been tested with visual studio 2022, updated to the latest version available.
We have a .NET 3.1 library published on github (private package).
We consume such library in many .NET 3.1 WebAPI backends that we develop.
We need to be able to debug such library.
GitHUB doesn't seem to support symbol servers at the moment, so I thought we had these 2 possibilities:
embed the pdb in the dll: this seemed the most straightforward solution and was the first I tried. By doing so on the core library, when we import that in a .NET webapi project and inspect the "modules" window, we can see that symbols for the dll have been loaded correctly; symbol file column reads: "OurLibrary.dll (embedded)"
include the pdb in the nupkg and then add a piece of code (found here https://github.com/dotnet/sdk/issues/1458#issuecomment-420456386) in the .csproj of consuming .NET webapi project that ensures that the dll pdb, contained in the nuget package, is copied to the bin folder. Also in this case, inspecting the modules window, it looks that the symbols have been loaded from metadata (which I guess is the pdb file itself).
STILL, in both cases, if the project is running, when I try to set a breakpoint in the Startup.cs file of the consuming WebAPI project, and step into an IServiceCollection extension method, which is defined in the library, I'm able to do so, but many symbols used in that file (referring to PUBLIC types defined in the library, or from the framework itself) are white, and I can't explore them by doing "go to definintion".
Instead, if I try to peek at the source code of the extension method mentioned before, when the project is not running, I'm able to peek at code by doing "go to definition" without issues. So, I set a breakpoint..
Then, when I launch the project:
you can see that it's a different "SessionFactory" file, and all the symbols have become white. If I try to go back to the original file (with all the types correctly resolved by intellisense), and set a breakpoint inside it, visual studio automatically switches to the other file (with "broken" intellisense) and sets the breakpoint there, which is very frustrating..
At the moment the only solution that really behaves the way I want requires me to remove the library nuget package from the project and reference the library as an "Existing project" inside the solution. By doing so everything works perfectly (of course, now library source code is part of the project) but of course seems wrong / time consuming / error prone.
Somebody is able to shed some light on what is going on? Thanks
EDIT: FURTHER DETAILS FOR USER #Transformer
I tried your suggestion to include the supplied code in .csproj of both the library and the consuming application:
By doing so in the library .csproj, it contains these settings related to PDB generation, in a property group:
<EmbedAllSources>true</EmbedAllSources>
<DebugSymbols>true</DebugSymbols>
<DebugType>portable</DebugType>
<AllowedReferenceRelatedFileExtensions>.pdb</AllowedReferenceRelatedFileExtensions>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
It also includes this, outside of the property group:
<Target Name="AddReferenceRelatedPathsToCopyLocal" AfterTargets="ResolveAssemblyReferences">
<ItemGroup>
<ReferenceCopyLocalPaths Include="#(_ReferenceRelatedPaths)" />
</ItemGroup>
</Target>
Unfortunately, by doing so, the pdb doesn't seem to be included in the nupkg. Instead, if I add the following (a setting I've already found in the past):
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
then the pdb is included in nupkg, but still, I experience the same debugging problem in the consuming library, even if I add the code you supplied to the consuming library as well...any other idea?
Thanks a lot for your kind help
The issue is probably because the nuget packages are built with Release configuration which optimizes out the symbols. One way you can debug the package itself is if you open the project (from which you deploy the nuget), build it with Debug configuration, then copy the dll and pdb file into the bin\Debug\ folder of your consumer app. Then start the consumer app with no debugger attached, after it starts, you can attach your nuget project to that process, and your nuget code breakpoints will be hit.
Hello, from what I can see - that's because the embedded files are not copied to local, please try this in your cs.proj file and paste your comments
<PropertyGroup>
<AllowedReferenceRelatedFileExtensions>.pdb</AllowedReferenceRelatedFileExtensions>
</PropertyGroup>
<Target Name="AddReferenceRelatedPathsToCopyLocal" AfterTargets="ResolveAssemblyReferences">
<ItemGroup>
<ReferenceCopyLocalPaths Include="#(_ReferenceRelatedPaths)" />
</ItemGroup>
</Target>
Question from Carlo Arnaboldi : Where does this go?
Update: These are settings that go into the .proj file.
You you to do this in your nuget pacakge && your consuming project to see the pdb for symbol debugging
Also delete you old pdbs - exist visual studio/code and then delete the bin and obj folders

Multi target net frameworks conflicts

I have a Nuget package project that targets framework netcoreapp2.2. I'm trying to use it for an application that contains other projects targeting frameworks netstandard2.0;netcoreapp3.1.
This is what I currently have in the .csproj for that
<PropertyGroup>
<TargetFrameworks>netcoreapp2.2;netstandard2.0;netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework) '=='netcoreapp2.2'">
( ........ )
In the classes I get the conflicts I'm using the conditional directive
##if true
1. But I'm getting compile errors because some of the extensions I'm using here are not available in one of the frameworks above.
*[Solved] I get this error:
Error CS0006 Metadata file 'C:\Users\user\source\repos\workspace\project\bin\Debug\netstandard2.0\project.dll' could not be found project.Test (netcoreapp2.2)
Is there any way I can target multiple frameworks to be able to download the NuGet package in the other projects?
Any ideas for a better approach?
Thanks
Update:
Error #2 The file project.dll didn't exist. It wasn't autogenerated by rebuilding the project. Adding the file manually solved it.

Visual Studio not copying dependencies | Could not load file or assembly

I'm writing a class library to abstract our company's Database functions, but when the code gets to instantiating one of my database objects we get a:
FileNotFound Exception:
Could not load file or assembly 'MySql.Data,
Version=8.0.13.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or
one of its dependencies. The system cannot find the file specified.
The MySql.Data Dependencies as stated on the website are:
.NETStandard 2.0 Google.Protobuf (>= 3.5.1)
System.Configuration.ConfigurationManager (>= 4.4.1)
System.Security.Permissions (>= 4.4.1)
System.Text.Encoding.CodePages (>= 4.4.0)
But all of them are installed automatically.
The NuGet package is MySql.Data (8.0.13) (which installs successfully)
Project is a .NET Standard 2.0 class library
There are no compile errors or even warnings; just the above error at run-time.
Have looked through Could not load file or assembly or one of its dependencies which advises checking where the dependencies are not being found - so I did - but it doesn't say how to fix the missing reference when you've found where it is?
Using Process Monitor I was able to find the failed CreateFile operation DLL calls, referencing ...\TestingGUI\bin\Debug\MySql.Data\MySql.Data.dll which, manually checking, is not there.
The project that runs is a WinForms app that references another .NET Standard class library (essentially a middleman) which then references the database library which depends on MySql.Data.
Doing a search in the whole solution directory, there are no MySql.Data.dll files, especially after a full solution build.
Here is my csproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<RootNamespace>App1.Database</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MySql.Data" Version="8.0.13" />
</ItemGroup>
</Project>
So, who's a .NET Wizard?
UPDATE:
So it turns out the code works fine when run from a .Net Core console app, but only has the error when referenced from a .NET app (specifically winforms). So I've given up having a GUI for now and am just using a .NET Core console app. I thought .NET Standard was compatible with everything, but maybe not? Anyway, I will keep my question here for anyone else having troubles.
UPDATE 2:
Thanks to #Itay Podhajcer's answer we managed to get it working with .NET Winforms by also including the NuGet package there.
I remember encountering the same issue, I think it was related to the new nuget referencing model.
Try adding the missing nuget package directly to the WinForms project.Far from ideal solution, but it should work.
Hope it helps!
Visual Studio not copying dependencies | Could not load file or assembly
It seems the dependencies and assembly are not copied to the output folder. You can check the thread for some more details:
PackageReference is missing copy files to output feature
To resolve this issue, you can try to following workaround:
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
Hope this helps.

Assets file obj\project.assets.json doesn't have a target - VS2017

Using Visual Studio 2017, AspNetCore 1.1.2
All of a sudden I am getting following error when I am trying to publish (Release build) any project in the solution:
Assets file 'C:\example\obj\project.assets.json' doesn't have a target for
'.NETFramework,Version=v4.5.2/win7-x86'. Ensure that restore has run
and that you have included 'net452' in the TargetFrameworks for your
project. You may also need to include 'win7-x86' in your project's
RuntimeIdentifiers.
Have checked in the project.assets.json files, I have:
"targets": {
".NETFramework,Version=v4.5.2": {
and
"runtimes": {
"win7-x86": {
"#import": []
}
In the *.csproj files I have:
<PropertyGroup>
<TargetFramework>net452</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
Have made no changes to config in the projects. Only thing is that I have updated VS2017 to latest version today, 15.6.3. Could this cause issue?
According to the Microsoft blog (which, bizarrely, my account doesn't have permissions to post in), this isn't a bug, and is entirely caused by ReSharper. If you disable this, the problem goes away.
Errr, one problem: I'm getting this error, and I don't have ReSharper.
After a lot of hunting around, I found the reason I was getting the error on my .NET Core project which had been upgraded from 1.0 to 2.1.
When running my project in Debug or Release mode, everything worked fine, but when I tried to publish to Azure, I got that error:
Assets file '(mikesproject)\obj\project.assets.json' doesn't have a target for '.NETCoreApp,Version=v2.0'. Ensure that restore has run and that you have included 'netcoreapp2.0' in the TargetFrameworks for your project.
Although I had updated the version of .NET Core to 2.1 in Project\Properties and upgraded the various nuget packages, there was one place which hadn't picked up this change... the Publish Profile file.
I needed to go into the Properties\PublishProfiles folder in my solution, open up the .pubxml file relating to the way I was publishing to Azure, and change this setting from netcoreapp2.0 to netcoreapp2.1:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
. . .
<TargetFramework>netcoreapp2.0</TargetFramework>
. . .
</PropertyGroup>
</Project>
Ridiculous, hey?
I do wish Microsoft error messages gave some clue as to the source of problems like this.
Restarting Visual Studio solved the error for me.
Right click on the project file, and click unload. Then right click on the project and reload.
Had this error in similar situation. This has helped me: Link
This is my property group in *.csproj file of my .net core 3.0 project:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp3.0</TargetFrameworks>
<RuntimeIdentifier>win-x64</RuntimeIdentifier> <----- SOLVES IT. Mandatory Line
</PropertyGroup>
Migrating from nuget 5.4 to nuget 5.8 solve the problem on my devops build server
Delete the publish profile you created and create a new one. The wizard will put in the correct targetframe work for you and publish again. It should solve the problem.
If your build script starts with a dotnet restore and ends with a dotnet publish --no-restore, you must make sure that they both include the same --runtime parameter.
Restarting Visual Studio or unloading/reloading the project didn't work for me, but deleting the "obj" folder and then rebuilding seems to have fixed the issue.
For me the problem ended up being that one of my NuGet feeds was down, so a package was not getting updated properly. It wasn't until I ran a NuGet package restore directly on the solution that I saw any error messages related to my NuGet feed being down.
You should try all the other solutions here first. Failing that you can try what eventually unblocked me when none of these did. I ran into this problem when porting a Jenkins build to an Azure DevOps pipeline on a pool of agents. It took about 60 builds before I tried every other possibility. I found out that needed to do two things:
Ensure the tooling was consistent for this specific project
Use a nuget restore friendly with the version of MSBuild used after finding out that mattered yet I couldn't use the proposed workaround for just updated nuget tooling.
The versions I needed to use are likely different than yours.
1:
call choco install windows-adk-all --version=10.0.15063.0 --force
call choco install windows-sdk-10.1 --version=10.1.15063.468 --force
2:
call MSBuild -t:restore Solution.sln
call MSBuild Solution.sln /t:rebuild;pack /p:Configuration=Release /p:Platform="Any CPU"
I got this error when upgrading a web project from netcoreapp3.1 to net5.0.
One of the answers here pointed me in the right direction:
The publish profile still had netcoreapp3.1 as target framework. Edited the publish profile and changed target framework to net5.0 and it worked.
(Visual Studio 16.8)
For me it was the happening because I had migrated my project from .net5.0 to .net6.0 and the problem was caused when I was publishing the project while debugging worked fine.
Checking the publishing profile showed that it had a configuration for .net5.0 in it:
Changing the existing .net core version with the desired one resolved the issue:
Or you can directly change it by going into the publishing profile .pubxml file under Properties > PublishingProfiles directory.
To me, the error was caused because of an existing global.json file in the solution level folder, pointing to a different .NET version.
Removing that file (or changing its SDK version) resolved the problem
Upgrading NuGet version from 5.5.1 to 5.8.0 fixed the issue.
I had similar issue, when I installed a new sdk version.
Exception was:
Severity Code Description Project File Line Suppression State Error NETSDK1005
Assets file '.. \RazorPages\obj\project.assets.json' doesn't have a target for
'netcoreapp3.1'. Ensure that restore has run and that you have included 'netcoreapp3.1'
in the TargetFrameworks for your project. RazorPages
C:\Program Files\dotnet\sdk\5.0.102\Sdks\Microsoft.NET.Sdk
\targets\Microsoft.PackageDependencyResolution.targets 241
Solution was to select again the target version of the project.
right click on solution
Properties\Application Tab
Change Target framework version to something different and change it back.
Running dotnet restore --packages .nuget in the project directory fixed the issues for me.
A colleague ran into this after upgrading an application from dotnet core 1.1 to dotnet core 2.1. He properly updated all the targetFramework references within the various csproj files, and had no issues on his local development machine. However, we run Azure DevOps Server and build agents on-premises, so the build agent was reporting this error after a pull request build was executed.
The dotnet clean task was throwing an error because of the new targeted framework. dotnet clean uses the same targets as build, publish, etc, so after a change in target frameworks the dotnet restore must happen before the dotnet clean to update the dependent files. In hindsight this makes sense because you want to restore dependencies to the proper target framework before you do any building or deploying.
This may only affect projects with upgraded target frameworks but I have not tested it.
Receiving similar error for 'netcoreapp3.1' when building using command line. It turned out to be an MsBuild switch that caused the issue. Specifically speaking:
/p:TargetFramework="netcoreapp3.1"
Removed the switch and the error was fixed.
In my case updating visual studio 2019 to the latest version, fixed the issue.
In my case, if you have TargetFrameworks and TargetFramework together in the csrpoj file, remove TargetFramework will solve the problem.
edit it from:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461;</TargetFrameworks>
<TargetFramework>net461</TargetFramework><!--remove this line-->
</PropertyGroup>
</Project>
to
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461;</TargetFrameworks>
</PropertyGroup>
</Project>
From my experience if you have dependencies in your solution built using "ProjectSection(ProjectDependencies) = postProject"
then in this case dotnet build goes nuts.
I ran into the NETSDK1047 when playing around with Docker in a brand new dotnet project created using dotnet new worker and the docker file from dotnet-docker samples.
❯ docker build -t dockertest .
output elided...
/usr/share/dotnet/sdk/6.0.300/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(267,5): error NETSDK1047: Assets file '/source/obj/project.assets.json' doesn't have a target for 'net6.0/linux-musl-x64'. Ensure that restore has run and that you have included 'net6.0' in the TargetFrameworks for your project. You may also need to include 'linux-musl-x64' in your project's RuntimeIdentifiers. [/source/dockertest.csproj]
The command '/bin/sh -c dotnet publish -c release -o /app -r linux-musl-x64 --self-contained true --no-restore /p:PublishTrimmed=true /p:PublishReadyToRun=true /p:PublishSingleFile=true' returned a non-zero code: 1
dockertest on  main [✘] via .NET v6.0.202 🎯 net6.0
❯
The issue was because I forgot to add a .dockerignore file ignoring the bin and obj directories.
I only realized why because I tried different Dockerfiles from the dotnet-docker repo and got a different error which has this same resolution. I'll try to make a PR to the docs of NETSDK1047 to add this resolution. edit: link to PR https://github.com/dotnet/docs/pull/29530
Had the same problem, for me it was that I had a space before my TargetFramework
<TargetFramework> net6.0</TargetFramework>
I upgraded from netstandard to net6.0, when publishing had to change TargetFramework to net6.0
On my end I had this issue with net6.0 at build time, even before trying to publish. Even if everything was pointing to csproj and it had all the right TargetFramework, the issue was that our repo had a Nuget.Config at it's root and it included a configuration for a local disk Nuget Repo of another programmer. I disabled the Nuget.Config file and I was able to build the project. It was probably unable to restore the Nuget Packages but the error message was misleading.
clean cache and restart VS then it worked for me.

Categories