Visual Studio cannot publish - c#

I tried this with a new project just to confirm that I have not made any errors, but Visual Studio 2019 won't publish any dot net core project. Below is the error I am getting... Any help would be much appreciated...
Severity Code Description Project File Line Suppression State
Error The "TransformAppSettings" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
File name: 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
at Microsoft.NET.Sdk.Publish.Tasks.AppSettingsTransform.UpdateDestinationConnectionStringEntries(String destinationAppSettingsFilePath, ITaskItem[] destinationConnectionStrings)
at Microsoft.NET.Sdk.Publish.Tasks.TransformAppSettings.TransformAppSettingsInternal()
at Microsoft.NET.Sdk.Publish.Tasks.TransformAppSettings.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext()
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog]. ProjectNameX 0
Here is my project file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<UserSecretsId>aspnet-ProjectNameX-A0D4A38F-C3FA-4FD3-8EBC-0F2201FBCD57</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>..\..\..</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0-preview6.19307.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview6.19307.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0-preview6.19307.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-preview6.19304.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0-preview6.19304.10" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.7.12" />
</ItemGroup>
While digging into visual studio folders, I found this...

Please check if Newtonsoft.Jsonis referenced in your solution. It seems solution is not able to find it.
Below link shows how to add it.
https://learn.microsoft.com/en-us/nuget/quickstart/install-and-use-a-package-in-visual-studio

Can you try publishing using a different Visual Studio 2019 instance? Not with the preview version of course.

The error has nothing to do with your project. The error message "clearly" says that Microsoft.NET.Sdk.Publish.Tasks.TransformAppSettings.TransformAppSettingsInternal() tried to access Newtonsoft.Json. This is obviously not your code.
I find this very strange, as Microsoft.NET.Sdk.Publish.Tasks.dll exists in the same directory as Newtonsoft.Json.dll (check c:\program files\dotnet\sdk), and it should have been compiled against the same version that ships. You can confirm using something like ILSpy to see what the assembly version of Newtonsoft.Json is and what assembly reference the publish tasks dll has. You can also better understand the paths and dlls that .NET used to try to load the dll, and why any dll with a matching filename was not used, using Fusion Logs. But I'm not going to write a tutorial on using Fusion Logs here.
In any case, understanding why it's happening won't help you solve it. All you can really do is make sure you're using the latest SDK, install the newest version if not, and if the problem still exists using the Visual Studio "report a problem" tool to let the .NET Core team know about this.

I faced similar issue.
In package manager console execute: Update-Package –reinstall Newtonsoft.Json

Though you haven't added package reference in .csproj. Open the project.assets.json file in your obj folder and search for Newtonsoft.Json you would find the real version you refer to.
So just check if binding redirect can help. If not, check if this issue persists if you create a new .net core empty web-app. Then publish it to locate the issue according to the result whether it succeeds or not.

Related

Custom msbuild task tries to load dependency with wrong version

I have custom publish process which firstly merges some assemblies into one via ILRepack, then performs some other steps and finally cleans up publish directory - removes merged dependencies from APP_NAME.deps.json, relevant assemblies and symbol files.
In order to implement the last step, I've created a NuGet package with a custom MsBuild task.
According to Nate's blog post, I've set PrivateAssets="All" in order to ship all task's dependencies within the package:
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="2019.1.3" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="15.9.20" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Update="#(PackageReference)" PrivateAssets="All" />
</ItemGroup>
Package layout looks like:
Suddenly, during publish, this step fails with error:
task failed unexpectedly. Could not load file or assembly
'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=30ad4fe6b2a6aeed'. Could not find or load a specific
file. (0x80131621)
I can't understand why task tries to load version 12.0.0.0 while I have Newtonsoft.Json 12.0.2 (as specified in PackageReference).
Thank you for any help!
Updated:
According to this msbuild spec currently MSBuild tasks have serious limitations:
Tasks in MSBuild are dynamically loaded assemblies with potentially separate and colliding dependency trees. Currently MSBuild on .NET Core has no isolation between tasks and as such only one version of any given assembly can be loaded. Prime example of this is Newtonsoft.Json which has multiple versions, but all the tasks must agree on it to work.
As Lex Li mentioned in the comment, 12.0.2 is the NuGet package version which corresponds to the 12.0.0.0 assembly version. So the system attempts to load the right version of the assembly.
According to task-isolation-and-dependencies.md, related issue etc. custom MsBuild tasks have serious limitations.
MsBuild itself includes a dependency on Newtonsoft.Json 11.0.1, so custom tasks can't load any other version of this dependency.
Workarounds:
Use the same dependency version as MsBuild. I guess this approach is fragile and should not be used.
Create and package console application instead of a custom MsBuild task. I've chosen this approach because it is easily extensible and allows us to use any dependency version. Nate's blog post gives an overview of the approach.
As Martin Ullrich mentioned in the comment, we could use task with isolation boundaries. ContextAwareTask.cs demonstrates the approach.

.NET Framework dll Could not load file or assembly 'Newtonsoft.Json....'

I am creating a c# .net framework library (.dll) that will act as a plugin for another piece of software. I want to use the Newtonsoft.json library but when the I call the json library I get the classic "FileNotFoundException":
Could not load file or assembly 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
The .dll is definitely being copied to the directory I am trying to run the plugin from. A lot of others have had this issue and I have tried everything I've seen (updating, reinstalling, etc.) but no luck yet. Because this is a class library I do not have an "app.config" file to play with binding redirects, so I haven't been able to try that.
I have very basic code right now, this package is the only external reference I am using. I've only been working on this today, only ever trying with Newtonsoft.Json version 12.0.2. It is weird to me that it appears VS is looking for 12.0.0.0, however. This is not an option to download. Similarly, I've tried downgrading to version 11.0.2, and then it gives me the same error saying it can't find version 11.0.0.0.
Even though your project may not have an .app config, you can still view the package references by unloading your project and viewing the .csproj file.
To try and force a direct reference to Newtonsoft.Json 12.0.2, you can add this snippet
<ItemGroup>
<PackageReference Include="Newtonsoft.Json">
<Version>12.0.2</Version>
</PackageReference>
</ItemGroup>
I would recommend removing any other references in your .csproj for Newtonsoft.Json as well

Assembly conflicts after NuGet update

I have a .Net Framework 4.7.1 Web Forms app and .Net Framework 4.7.1. WebJob, both running on Azure AppService.
Since updating via Nuget WebJob packages from 2.0.0 to 2.2.0 a number of dependency issues occurred.
First one comes up at runtime:
System.IO.FileLoadException : Could not load file or assembly 'System.Net.Http, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference
Second one shows during compilation:
Consider app.config remapping of assembly for a number of assemblies like System.Net.Http, System.Net.Sockets, System.IO.Compression, etc.
To solve this, advised by number of sources and compiler warning I have added
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
This has allowed for WebJob execution but still compiler shows warning on assembly remapping.
I have seen more issues regarding assembly conflicts since as I believe .Net Standard.
Can you please explain to me
1. What is going on with assemblies and why I need to turn on Binding Redirects?
2. Why this does not solve the second issue?
Thank you.
What is going on with assemblies and why I need to turn on Binding Redirects?
It requires assembly binding redirects that need to be generated during the build process. And after you add this to your webjobs, it will add assembly into bin folder when you build.
Why this does not solve the second issue?
It seems that it is a VS issue, you could solve it by click Migrate packages.config to PackageReference in your webjob References. Add the following .csproj in your webjobs and compiled.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net461</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs" Version="2.2.0" />
</ItemGroup>
</Project>
For more details, you could refer to this issue.

Roslyn analyzer missing assembly warning

After creating a Roslyn analyzer package targeting .Net Standard 2.0, when I reference the package in another project, I receive the following error:
'C:\Users\username.nuget\packages\analyzer4\1.0.0.1\analyzers\dotnet\cs\Analyzer4.dll' depends on 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.
A repro of the project using the Analyzer is here. This repro is a vanilla .Net Core 2.0 console app with a reference to the analyzer and no other code whatsoever. The analyzer itself was built simply by creating the default Analyzer project in Visual Studio, changing it so that it targets netstandard2.0 instead of netstandard1.3, and then building in release mode to generate the .nupkg file. The analyzer does work properly, as the repro demonstrates, but the warning is generated.
There are discussions of this warning at various places on Github, such as here, but in those cases, the analyzer author had deliberately stripped out some local library code. In this case, the analyzer does not reference any other library.
I am not clear on what exactly it means to add an analyzer as an "analyzer reference" rather than just a regular project reference. I did try changing
<PackageReference Include="Analyzer4" Version="1.0.0.1" />
to
<Analyzer Include="..\LocalPackages\Analyzer4.1.0.0.1.nupkg" />
but that resulted in another error message ("PE image doesn't contain managed metadata").
Can anyone explain what this error means and ideally how to fix it?
Some background on this issue is here. When an analyzer depends on another assembly, then both must be listed as analyzers, but there is generally an exception for the core system assemblies. Unfortunately, it does not appear that .Net standard 2.0 has yet been added to the exceptions list; presumably, that will occur at some point in the future. I was able to make code changes to target the analyzer to .Net Standard 1.3 instead, thus avoiding the warning.
This problem will also arise when adding other assemblies (such as Newtonsoft.Json) into your analyzer. One solution to this is simply not to do so; for example, StyleCop eliminated its dependence on Newtonsoft.Json and simply includes the code for LightJson directly in its assembly. Other solutions might be (1) to manually copy the dll you are depending on (taking it from your packages folder if necessary) into the .nupkg file, recognizing that .nupkg is really just a .zip file; or (2) to use a tool like ILMerge to merge the dependency into your DLL. I have not yet experimented with these approaches, so if someone else can produce a step-by-step explanation of how to integrate this into a build for an analyzer, I will mark that as a correct answer.
You can use the approach in the Source Generators Cookbook (Thanks to #mbabramo for the link!).
<ItemGroup>
<PackageReference Include="Analyzer4" Version="1.0.0.1" />
</ItemGroup>
Becomes:
<ItemGroup>
<PackageReference Include="Analyzer4" Version="1.0.0.1" PrivateAssets="all" GeneratePathProperty="true" />
<None Include="$(PkgAnalyzer4)\lib\netstandard2.0\*.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>
This should add the package dlls into your analyzer's folder, and it should work.

NuGet package (.NET Standard 2.x) breaking ASP.NET MVC5 application (.NET full framework)

(updated - see below)
I have an ASP.NET MVC5 application (multiple Assemblies) all addressing the .NET Full Framework 4.7.1
I recently added a (private) NuGet package that we built using .NET Standard 2. From Quickstart: Create and publish a package using Visual Studio (.NET Framework):
Unless you have a reason to choose otherwise, .NET Standard is the preferred target for NuGet packages, as it provides compatibility with the widest range of consuming projects.
Since then, things just haven't been the same.....there are a list of errors that I mention below, but I suspect they're all symptoms of the same issue (discussed at the end).
Please note: I'm using Visual Studio 15.7.1, and all NuGet packages use the package.config manage format rather than PackageReference.
First problem
Method not found:
'System.Collections.ObjectModel.Collection`1
System.Web.Http.HttpConfiguration.get_MessageHandlers()'
My guess here is that there's a .NET Standard version of System.Web.Http that doesn't have this method, and my application has chosen to address this rather than the 4.7.1 framework.
I partially fixed this by adding the following to my web.config file:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="B03F5F7F11D50A3A" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
I say "partially" fixed it, this fixes the problem when run in my DEV environment (with Visual Studio) but when published to our QA environment, the issue remains. Any ideas on how to fix this?
Note: The MVC project's reference to System.Net.Http exists in the following path (it is NOT a NuGet package):
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net471\lib\System.Net.Http.dll
Second problem
Two of the Assemblies are involved with pulling data from various web-sources (WCF, web-api, web-service). When compiling these in RELEASE mode (where I have code analysis etc turned on) I get the following error reported:
An attempt was made to load an assembly with an incorrect format:
C:\Program Files (x86)\Reference
Assemblies\Microsoft\Framework.NETFramework\v4.7.1\Facades\System.IO.Compression.ZipFile.dll. {Name
of the assembly} {Path to the assembly}\SGEN
I found one post had the following suggestion:
Another suggestion I saw (which didn’t help me at all), was to disable
the project from creating a serialization assembly. Follow these
steps to do that (it may or may not help, but it’s worth a try):
In Solution Explorer, right click on the project that has the error and go to Properties.
In the Build tab, scroll to the very bottom and change Generate
Serialization Assembly to Off
I tried this and yes, it worked for me. However, these are the two projects that are serializing objects to send to these various web sources, so the last thing I want to be doing is un-optimizing serialization within my application...
Any suggestions on what might be wrong, or how I should best proceed?
UPDATE 14-May-2018
I found a great article from Scot Hanselman regarding NuGet packages which states:
As Oren wisely says:
"Using .NET Standard requires you to use PackageReference to eliminate
the pain of “lots of packages” as well as properly handle transitive
dependencies. While you may be able to use .NET Standard without
PackageReference, I wouldn’t recommend it."
However, there's a catch.... In Visual Studio, there is now an easy way to migrate an assembly from the older package.config to PackageReference as detailed in this link, but that article clearly states:
Note that the migrator does not presently support C++, JavaScript, and ASP.NET (.NET Framework) projects.
And when attempting this, the migration tool duly notified me that for the NuGet packages Microsoft.AspNet.Mvc and Microsoft.AspNet.WebPages:
"content" assets are not available when the package is installed after the migration
UPDATE 23-May-2018 I found several other people are experiencing a similar issue. From GitHub: .NET 4.6.1/.NET Standard 2.0 build with SGen fails #1630. Their "solution" was again to disable the serialization (see above) which would ruin performance on my application.
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
Conclusion?
So, am I right to conclude that to consume a .NET Standard 2.x NuGet package in a .NET FullFramework application, I need to use PackageReference rather than package.config and this is currently not possible with AspNet.MVC applications? In other words, it's not currently possible.
I've got this problem with .Net Framework 4.8 application and System.Buffers assembly incorrect format
The MarkKharitonov advice has solved the error. With Directory.Build.targets file I can built a project without any problem.
<Project>
<ItemGroup>
<ReflectionOnlyAssemblyNames Include="Microsoft.Bcl.AsyncInterfaces"/>
<ReflectionOnlyAssemblyNames Include="System.Buffers"/>
<ReflectionOnlyAssemblyNames Include="System.Numerics.Vectors"/>
<ReflectionOnlyAssemblyNames Include="System.Runtime.CompilerServices.Unsafe"/>
</ItemGroup>
<Target Name="RemoveDesignTimeFacadesBeforeSGen" BeforeTargets="GenerateSerializationAssemblies">
<ItemGroup>
<_ReflectionOnlyAssembly_Names Include="#(_ReferencePath_Names)"
Condition="'#(ReflectionOnlyAssemblyNames)' == '#(_ReferencePath_Names)' And '%(Identity)' != ''"/>
</ItemGroup>
<ItemGroup>
<ReferencePath Remove="#(_DesignTimeFacadeAssemblies_Names->'%(OriginalIdentity)')" />
<ReferencePath Remove="#(_ReflectionOnlyAssembly_Names->'%(OriginalIdentity)')" />
</ItemGroup>
<Message Importance="normal" Text="Removing DesignTimeFacades from ReferencePath before running SGen." />
</Target>
<Target Name="ReAddDesignTimeFacadesBeforeSGen" AfterTargets="GenerateSerializationAssemblies">
<ItemGroup>
<ReferencePath Include="#(_DesignTimeFacadeAssemblies_Names->'%(OriginalIdentity)')" />
<ReferencePath Include="#(_ReflectionOnlyAssembly_Names->'%(OriginalIdentity)')" />
</ItemGroup>
<Message Importance="normal" Text="Adding back DesignTimeFacades from ReferencePath now that SGen has run." />
</Target>
</Project>

Categories

Resources