Could not find 'UserSecretsIdAttribute' on assembly 'ef' - asp.net-core

I am using ASP.NET Core 1.1 and I have the following on startup:
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddUserSecrets();
I am using csproj file instead of JSON where I added:
<PropertyGroup>
<UserSecretsId>8844d677-223b-4527-a648-387a65933d55</UserSecretsId>
</PropertyGroup>
But when I run the command:
dotnet ef migrations add "InitialCommit"
I get the error:
An error occurred while calling method 'ConfigureServices' on startup class 'Startup'. Consider using IDbContextFactory to override the initialization of the DbContext at design-time. Could not find 'UserSecretsIdAttribute' on assembly 'ef, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"
Any idea why?

You have run into this issue: https://github.com/aspnet/Configuration/issues/543
The solution is to change your call .AddUserSecrets() to .AddUserSecrets(Assembly assembly)
See this announcement about how deprecating project.json required a breaking change to user secrets: https://github.com/aspnet/Announcements/issues/209

I had this issue also. My solution was to install the nuget package Microsoft.Extensions.Configuration.UserSecrets.

It finally worked for me when I changed a version of package in .csproj:
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.2" />
to:
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />

Related

The "TransformAppSettings" task failed unexpectedly

I have a .NET Core 3 Blazor (server side) application which I recently upgraded to .NET Core 3.0.1 preview 6 version from the preview 5 version. When I build and run it locally, it works fine; but when trying to publish it to a file system folder (in Framework-Dependent mode), it throws this error:
C:\Program Files\dotnet\sdk\3.0.100-preview6-012264\Sdks\Microsoft.NET.Sdk.Publish\targets\TransformTargets\Microsoft.NET.Sdk.Publish.TransformFiles.targets(192,5): Error MSB4018: 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()
It's perhaps worth mentioning that this error didn't occur in the preview 5 version. Also, I use Visual Studio Enterprise 2019 (Windows).
Things I've tried so far: (with no luck)
Clean/Rebuild solution
Reinstall .NET Core 3 preview 6 SDK
Add Newtonsoft.Json package via Nuget
Search for related issues raised by the community on github
.csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<LangVersion>7.3</LangVersion>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.1.0" />
<PackageReference Include="MatBlazor" Version="1.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="SqlTableDependency" Version="8.5.3" />
<PackageReference Include="System.DirectoryServices" Version="4.5.0" />
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="4.5.0" />
<PackageReference Include="Telerik.UI.for.Blazor" Version="1.1.1" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\images\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\{path to project file}" />
</ItemGroup>
</Project>
In my case, I edit the publish configuration and turned off the Database -> Use this connection at runtime. Then I could publish without this error, however, I had to manually edit the web.config and make the following changes.
modules="AspNetCorModuleV2" had to become modules="AspNetCodeModule"
hostingModel="InProcess" had to become hostingModel="OutOfProcess"
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" /> had to become value="Production"
These changes were already in my own directories web.config, but they didn't seem to get propagated in the publish anymore.
I had this same error and was able to fix it by editing the .pubxml.user file.
When the error occurred, my publish settings didn't have the "Use this connection at runtime" selected, nor were any database migrations checked. But when I looked in the pubxml.user file and it turns out there was a reference to a non-existent database that wasn't showing up in the Publish Settings UI. I removed that and it solved the problem.
All I did was uncheck the "Use this connection string at runtime" database option, since my azure server will that set that anyway it shouldn't be an issue.
I have the same issue
Same Question on Stack Overflow
Though i have managed to publish my project via powershell commands
dotnet publish --configuration Release --framework netcoreapp2.2
Try it, I hope it will help...
I know this has been resolved for you. But in my own case.
IDE: Visual Studio 2017 Enterprise
Publish Profile: Folder
Follow this step:
Change the build option to the environment you want to publish for
(Test, Staging, Release or Production) and clean the solution.
Open your project folder and delete the bin and obj folders.
Restart Visual Studio
After restarting VS, delete the publish profile and re-create the profile
This should fix it as it did for me. After which I was able to publish comfortably.
I hope this helps.
My issue was resolved when I
checked "Use this connection string at runtime"
unchecked the "Default connection string"
If you are publishing to a local file System. Check whether the folder has required read/write permission for Visual Studio to copy the published files.

What is the default version of the nuget package when referenced with PackageReference in .NET Core project?

I am trying to learn and understand nuget and msbuild in .NET Core by examining and manually editing project files (.csproj in .NET Core 2.2).
So when I create WebApi project, the .csproj file looks like this:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
</ItemGroup>
</Project>
Notice that there is no Version attribute specified for the first PackageReference.
Now if I specify it to be the latest stable version 2.2.3 like this:
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.3" />
I get build warning NETSDK1071 which says:
A PackageReference to 'Microsoft.AspNetCore.App' specified a Version
of 2.2.3. Specifying the version of this package is not recommended.
For more information, see https://aka.ms/sdkimplicitrefs
This warning is not shown when Version attribute is omitted so I was wondering how is nuget package Version resolved when not set explicitly?
Also, how does dotnet build knows which version of a nuget package is recommended with the current project settings?
From the link in the warning, you can learn that it is not a regular package, but Meta-package.
It's mean that this package depends on your TargetFramework, and this is mean that when you target to a specific framework that installed in your machine (as SDK), the package will be taken from the specific SDK.

how to setup EFcore database first in separate class library in ASP.NET Core MVC application?

I have a DB and I want to add a separate class library for entity framework to access my data but when I run scaffold command it makes a DB model in my web application.
You should select your Data project as default project in package manager console.
Be careful, you have ef core references in data.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<RuntimeFrameworkVersion>2.0.5</RuntimeFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0-preview3-35497" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.0-preview3-35497" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.0-preview3-35497" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.0-preview3-35497"/>
<PackageReference Include="System.Data.Common" Version="4.2.1" />
</ItemGroup>
</Project>
I realized that there are some errors in ClassLibrary projects. You can take a look at them:
https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet#targeting-class-library-projects-is-not-supported
https://github.com/dotnet/cli/issues/8735
https://github.com/aspnet/EntityFrameworkCore/issues/10298
#ibrahimozgon's answer is right and helped me. However, I encountered a few errors in the DbContext class on the way which he didn't mention how to solve:
'EntityTypeBuilder' does not contain a definition for 'ToTable' and no accessible extension method 'ToTable' accepting a first argument of type 'EntityTypeBuilder' could be found (are you missing a using directive or an assembly reference?
and
'KeyBuilder' does not contain a definition for 'ForSqlServerIsClustered' and no accessible extension method 'ForSqlServerIsClustered' accepting a first argument of type 'KeyBuilder' could be found (are you missing a using directive or an assembly reference?
To resolve these errors in DbContext class, open up package manager console again and select the default project to be the class library. Enter these commands one by one:
- Install package: Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.4 (or whichever latest version)
- Install package: Install-Package Microsoft.EntityFrameworkCore.Relational -Version 2.2.4 (or whichever latest version)
- If errors persist try: Install-Package or Update-Package Microsoft.EntityFrameworkCore.Tools (or whichever latest version)

EntityFrameworkCore 2.x and PrivateAsset="All"

I'm building an .NetCoreApp1.1 webapi. We have the typical business and data layer assemblies broken out. When we added EntityFrameworkCore 2.x to the data access project, I was able to test functionality that went across projects. But the webapi stopped working! We were no longer able to start the app. program.cs-main failed with the exception:
System.MissingMethodException: "Method not found: 'System.IServiceProvider >MicrosoftExtensions.DependencyInjection.ServiceCollectionContainerBuilderExtens>ions.BuildServiceProvider...'
Articles indicated a package type mismatch but I couldn't find anything out of place. The EntityFrameworkcore in the data layer was suspect since it was version 2.0.0-preview1-final. In VS2017 there is a new feature to mark packages as private to the assembly. This made sense to do this with EF in the data layer so I opened the project and marked them PrivateAsset="All"
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0-preview1-final" **PrivateAssets="All"** />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0-preview1-final" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0-preview1-final" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="2.0.0-preview1-final" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0-preview1-final" PrivateAssets="All" />
<PackageReference Include="WindowsAzure.Storage" Version="8.1.4" />
</ItemGroup>
This solved my problem. I was able to rebuild and run the webapi application. But, now my test failed with:
Message: Test method
ACMEAppTests.AppTests_FileManagerSave.FileManager_SaveFile threw exception: >System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
This makes no sense. The assembly is there. So it seems I can't get both applications working at the same time. The errors make no sense to me. There seems to be little information on the PrivateAsset="All" feature for packages. I found this description:
Tip
A private package reference (PrivateAssets="All") means this dependency is local to the current project. For example, if Project A has a build only dependency and Project B depends on A, dotnet restore will not add A's build-only dependencies into Project B.
reference
.Net Command Line Tools
How to resolve this? Figure out why the webapi stopped working (Method not found) or debug the missing assembly reference that isn't, from what I can tell, missing?
All help appreciated.
You can't mix ASP.NET Core 1.1 with EF Core 2.0. They share some common dependencies (e.g. Logging, DependencyInjection, etc.) which means all your Microsoft.* package versions need to more-or-less align.
See the documentation about PrivateAssets. Adding PrivateAssets="All" prevents your data layer's dependencies from propagating into your app. Hence, you get could not load assembly errors.

.NET Core how to test with net461 and xunit

dotnet new xunit ->
dotnet restore ->
dotnet test
Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1,7148 Seconds.
.csproj; change target framework to net461:
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="xunit" Version="2.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
</ItemGroup>
</Project>
then
dotnet restore ->
dotnet test
Starting test execution, please wait...
No test is available in C:\Projects\testing\bin\Debug\net461\testing.dll. Make sure that installed test discoverers & executors, platform & framework version sett
ings are appropriate and try again.
How am I supposed to test net461-projects with xunit?
I already have a big project I've upgraded from .NET Core 1.0, and testing worked fine before the upgrade, so changing test framework would require some work.
Update
As it turns out, this is probably not related to xunit and testing - ASP.NET Core projects targeting net461 won't run at all on my machine anymore, neither through VS or from cmd.
The project I am trying to run is an new empty web project from the VS template. The csproj looks like this:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
<RuntimeIdentifier>win7-x86</RuntimeIdentifier>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
</ItemGroup>
</Project>
The error I get is this:
dotnet run
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AspNetCore.Hosting, Version=1.1.1.0, Culture=neutral, PublicKeyTo
ken=adb9793829ddae60' or one of its dependencies. The system cannot find the file specified.
at WebApplication2.Program.Main(String[] args)
I have tried removing all traces of Visual Studio and .NET Core from my machine and reinstalling them, but the error is the same.
There is an issue with runtime identifier inference and how the test sdk works.
Try adding this to your <PropertyGroup> (assuming you're on a 64 bit windows):
<RuntimeIdentifier>win7-x64</RuntimeIdentifier>
you could also add
<OutputType>Exe</OutputType>
which would turn your class library project into an exe but this should work around the issue.
Yeah, I've experienced the same issue. Not sure if Microsoft already has a fix available, but it seems that some packages of ASP.NET Core 1.1.x are targeting NetStandard Library 1.6.1, which is not compatible with .NET Framework... See the matrix on MS website here: https://learn.microsoft.com/en-us/dotnet/articles/standard/library#net-platforms-support
We've decided to stick to ASP.NET Core 1.0.x for now.