Type or namespace SigninManager<> could not be found Identity 3.1.1 Mediatr 8.0.0 - asp.net-core

I am trying to implement Identity using the Mediatr library and pattern...
The code i am using did work in dotnetcore 2.x and identity 2.2 but is broken in dotnetcore 3.x and identity 3.1.1...
My Application class library is netstandard2.1 and hase the following dependencies set.
<PackageReference Include="FluentValidation.AspNetCore" Version="8.6.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
I have my request handler like so;
public class Handler : IRequestHandler<Query, AppUser>
{
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager;
public Handler(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public async Task<AppUser> Handle(Query request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
{
throw new Exception("Unauthorized");
}
// var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
var result = await _userManager.CheckPasswordAsync(user, request.Password);
if (result)
{
return user;
}
throw new Exception("Unauthorized");
}
}
The issue I am having here is that I cannot resolve SignInManager anymore and I am not sure why. I cannot find much info about any of the breaking changes around this between identity versions either.
Where has the SignInManager gone? I thought UserManager were in the same namespace and UserManager resolves just fine. Super confused right now, as you can see, i am about ready to cheat my way out but it doesn't sit right with me.
With the same dependencies in my API project I can reference SignInManager with the same namespace and i can use it to sign in directly in the controller. How can i decouple this in to a Mediatr Handler?

Starting with version 3.0, ASP.NET Core is no longer fully distributed through NuGet. Instead, it is shipped as part of the .NET Core runtime as a shared framework. Only optional packages, like the Microsoft.AspNetCore.Identity.EntityFrameworkCore are still distributed through NuGet. However, those packages do not have transient dependencies defined which will automatically work, so you will still need to properly reference this shared framework in order to use these types.
In order to do this, you will need to switch your project to target netcoreapp3.1 since ASP.NET Core only runs on .NET Core and won’t work with .NET Standard.
Once you have done that, you can reference the shared framework using a framework reference. So your project file should look like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="8.6.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
</ItemGroup>
</Project>

Related

Problem Reading Embedded Resource With ASP.NET Core 3.1 in Console App

I'm failing at being able to read embedded resources in ASP.NET Core 3.1. Specifically, I'm following the example in the docs here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-3.1
I've updated my csproj file to the following adding the <GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="Data\sessions.json" />
<EmbeddedResource Include="Data\speakers.json" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EFLib\EFLib.csproj" />
<ProjectReference Include="..\RepositoryLib\RepositoryLib.csproj" />
<ProjectReference Include="..\SeedDataLib\SeedDataLib.csproj" />
</ItemGroup>
</Project>
I have console app as follows and I get the error below when I run it.
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var manifestEmbeddedProvider =
new ManifestEmbeddedFileProvider(typeof(Program).Assembly); // ERROR HERE
{"Could not load the embedded file manifest 'Microsoft.Extensions.FileProviders.Embedded.Manifest.xml' for assembly 'TestConsoleApp'."}
I'm basically trying to do what I use to do in ASP.NET Core 2 which was this and it's not working.
var assembly = Assembly.GetEntryAssembly();
string[] resources = assembly.GetManifestResourceNames(); // debugging purposes only to get list of embedded resources
I faced the same issue you described. Make sure that you added the following package reference to the .csproj where embedded resources are declared. Once I added it to my project and rebuilt the solution, it started working.
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="3.1.0" />
</ItemGroup>

Could not load the embedded file manifest 'Microsoft.Extensions.FileProviders.Embedded.Manifest.xml' ASP.NET Core 3.0

I have an asp.net core 3.0 website and I am trying to use FileProvider. I created the below based on an example, but I keep getting the error
InvalidOperationException: Could not load the embedded file manifest 'Microsoft.Extensions.FileProviders.Embedded.Manifest.xml' for assembly 'Test'.
Below is my startup class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using IntranetPages.Shared;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
namespace Test
{
public class Startup
{
private readonly IWebHostEnvironment _env;
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddTransient<IClaimsTransformation, CustomClaimsTransformer>();
services.AddSingleton<IAuthorizationHandler, CheckGroupHandler>();
var physicalProvider = _env.ContentRootFileProvider;
var manifestEmbeddedProvider =
new ManifestEmbeddedFileProvider(typeof(Program).Assembly);
var compositeProvider =
new CompositeFileProvider(physicalProvider, manifestEmbeddedProvider);
services.AddSingleton<IFileProvider>(compositeProvider);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
}
}
}
What am I missing? I tried installing the NuGet packages, but it made no difference.
If you're migrating from ASP.NET-Core 2.x to 3.x, since ASP.NET-Core 3.0 and above, Microsoft.NET.Sdk.Web MSBuild SDK doesn't automatically include Microsoft.Extensions.FileProviders.Embedded NuGet package anymore.
Microsoft.Extensions.FileProviders.Embedded needs to be added explicitly.
<Project Sdk="Microsoft.NET.Sdk.Web">
...
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="3.0.3" />
<!-- Or use version 3.1.2 for ASP.NET-Core 3.1 -->
</ItemGroup>
...
</Project>
For those not migrating from 2.x to 3.x, don't forget to also add the following to your .csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
...
<PropertyGroup>
<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
</PropertyGroup>
...
<ItemGroup>
<EmbeddedResource Include="..." /> <!-- Add your directories and/or files here. -->
</ItemGroup>
...
</Project>
You also need to specify the files to embed with <EmbeddedResource> in csproj file
<ItemGroup>
<EmbeddedResource Include="your file" />
</ItemGroup>
Use glob patterns to specify one or more files to embed into the assembly.
To generate a manifest of the embedded files:
Add the Microsoft.Extensions.FileProviders.Embedded NuGet package to
your project.
Set the property to true. Specify the
files to embed with :
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resource.txt" />
</ItemGroup>
</Project>
Use glob patterns to specify one or more files to embed into the
assembly.

How to check environment from a class library not using any form of DI

We are using Entity Framework to scaffold classes from the database as the DBA creates the database and we can't use code first.
When scaffolding it creates a DbContext class and populates the onconfiguring method with the connection string hard coded into that class, we have a partial class that overrides the onconfiguring and attempts to look at the environment and return different connection string based on the environment. However in the partial class we haven't been able to access the environment like you can from a controller.
How would I check the current environment in the DAL layer being generated from the EF Core scaffold command. We have no problem getting the scaffold command itself to read different connection strings but it needs to happen in the DAL itself so we can just deploy to live without having to rescaffold first with a new connection string.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Core" Version="1.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
<PackageReference Include="Xero.Api.SDK.Core" Version="1.1.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Hosting">
<HintPath>..\..\..\Program Files (x86)\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.hosting\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Hosting.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Abstractions">
<HintPath>..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.abstractions\2.0.1\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Hosting">
<HintPath>..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.hosting\2.2.0\lib\netstandard2.0\Microsoft.Extensions.Hosting.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
You need inject both the DbContextOptions and IHostingEnvironment .
Try the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using App.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting; // this is required
using System.ComponentModel.DataAnnotations.Schema;
// ...
public class AppDbContext : IdentityDbContext<IdentityUser>
{
public AppDbContext (DbContextOptions<AppDbContext> options,IHostingEnvironment env)
: base(options)
{
this._env = env;
}
[NotMapped]
private IHostingEnvironment _env;
protected override void OnModelCreating(ModelBuilder builder){
base.OnModelCreating(builder);
System.Console.WriteLine("*********************");
System.Console.WriteLine(this._env.EnvironmentName);
System.Console.WriteLine("*********************");
}
// your entities generated by scaffolding
public DbSet<App.Models.XModel> XModel { get; set; }
}

.Net Core 2.1 System.IO.FileSystem.DriveInfo

I have a .NET Core 2.1 console app using Visual Studio 2017 Preview 4
I can't seem to get System.IO.FileSystem into my project. I need to access TotalFreeSpace
I do:
dotnet add package System.IO.FileSystem.DriveInfo
which succeeds without erros
in my .csproj file I have:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.2" />
<PackageReference Include="System.Diagnostics.PerformanceCounter" Version="4.5.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="1.0.0" />
<PackageReference Include="System.IO.FileSystem.DriveInfo" Version="4.3.1" />
I then clean and rebuild fine.
However in my source code if I then try:
using System.IO.FileSystem.DriveInfo;
I get:
Error CS0234 The type or namespace name 'FileSystem' does not exist in the namespace 'System.IO' (are you missing an assembly reference?)
How can I solve this ? what else can I try ?
I just needed:
using System.IO;
then
var drives=DriveInfo.GetDrives();
The full sample for completeness.
using System.IO;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
DriveInfo dr = new DriveInfo("C");
Console.WriteLine(dr.TotalFreeSpace);
Console.ReadKey();
}
}
}

Why is the first space lost in the ouput from this very basic AspNetCore program

I was following along with Scott and Naggaga on the "Introduction to ASP.NET Core with VS 2017" and got to the very first web page. And the html in the response is missing the first space. So I get "HelloBrave New World!".
I cannot think why this is happening - there is only 45 lines in the whole thing...
supermva.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
Program.cs:
using Microsoft.AspNetCore.Hosting;
namespace supermva
{
class Program
{
static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
namespace supermva
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(context =>
{
return context.Response.WriteAsync("Hello Brave New World!");
});
}
}
}
The answer is, of course, nothing is wrong with the program. (Stupid question)
If I use Firefox or Chrome, the text is shown fine.
Only with Edge does the first space disappear. Because I use LastPass in Edge and LastPass did the mangling.