.Net Core 2.1 System.IO.FileSystem.DriveInfo - asp.net-core

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();
}
}
}

Related

Type or namespace SigninManager<> could not be found Identity 3.1.1 Mediatr 8.0.0

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>

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.

MSBuildWorkspace cannot compile project with <ProjectReference> to another project

Note I've also asked this question (with reproduction code) on Roslyn's GitHub
Create a new solution with 2 projects (CoreLibrary and DownstreamLibrary).
Add a project reference from DownstreamLibrary to CoreLibrary.
Run the following code and note that DownstreamLibrary no longer compiles.
Note that I've tried net461, netcoreapp2.1 and netstandard2.0 as target frameworks for the projects - same problem each time.
static async Task Main(string[] args)
{
MSBuildLocator.RegisterDefaults();
using (var workspace = MSBuildWorkspace.Create())
{
workspace.WorkspaceFailed += (sender, workspaceFailedArgs) => WriteLine(workspaceFailedArgs.Diagnostic.Message);
var solution = await workspace.OpenSolutionAsync(#"c:\source\ForRoslynTest\ForRoslynTest.sln");
WriteLine($"Loaded solution {solution.FilePath}");
var projectTree = workspace.CurrentSolution.GetProjectDependencyGraph();
foreach (var projectId in projectTree.GetTopologicallySortedProjects())
{
await CompileProject(workspace.CurrentSolution.GetProject(projectId));
}
}
}
private static async Task CompileProject(Project project)
{
WriteLine($"Compiling {project.Name}. It has {project.MetadataReferences.Count} metadata references.");
var compilation = await project.GetCompilationAsync();
var errors = compilation.GetDiagnostics().Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error);
if (errors.Any())
{
WriteLine($"COMPILATION ERROR: {compilation.AssemblyName}: {errors.Count()} compilation errors: \n\t{string.Join("\n\t", errors.Where(e => false).Select(e => e.ToString()))}");
}
else
{
WriteLine($"Project {project.Name} compiled with no errors");
}
}
You will receive the following output:
Msbuild failed when processing the file 'c:\source\ForRoslynTest\DownstreamLibrary\DownstreamLibrary.csproj' with message: C:\Program Files\dotnet\sdk\2.1.602\Microsoft.Common.CurrentVersion.targets: (1548, 5): The "Microsoft.Build.Tasks.ResolveNonMSBuildProjectOutput" task could not be loaded from the assembly Microsoft.Build.Tasks.Core, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
Found project reference without a matching metadata reference: c:\source\ForRoslynTest\CoreLibrary\CoreLibrary.csproj
Loaded solution c:\source\ForRoslynTest\ForRoslynTest.sln
Compiling CoreLibrary. It has 113 metadata references.
Project CoreLibrary compiled with no errors
Compiling DownstreamLibrary. It has 0 metadata references.
COMPILATION ERROR: DownstreamLibrary: 3 compilation errors:
c:\source\ForRoslynTest\DownstreamLibrary\Class1.cs(1,7): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
c:\source\ForRoslynTest\DownstreamLibrary\Class1.cs(5,18): error CS0518: Predefined type 'System.Object' is not defined or imported
c:\source\ForRoslynTest\DownstreamLibrary\Class1.cs(5,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments
So my question is how do I fix the above errors and get DownstreamLibrary to compile?
EDIT
I'm 99% sure the underlying cause is this error
The "Microsoft.Build.Tasks.ResolveNonMSBuildProjectOutput" task could not be loaded from the assembly Microsoft.Build.Tasks.Core, Version=15.1.0.0
I've confirmed with procmon that it's loading the following DLL (C:\Program Files\dotnet\sdk\2.1.602\Microsoft.Build.Tasks.Core.dll) which I've confirmed with ILSpy DOESN'T have the ResolveNonMSBuildProjectOutput task in it. Older versions of this DLL did have this task.
I found a manual workaround to this WorkspaceFailed error:
[Failure] Msbuild failed when processing the with message: The "Microsoft.Build.Tasks.ResolveNonMSBuildProjectOutput" task could not be loaded from the assembly Microsoft.Build.Tasks.Core, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
There were a few resolution steps:
following https://github.com/microsoft/msbuild/issues/4770 I updated VS 2019 from 16.2 to 16.5.3... This didn't fix my bug, but it's worth documenting I did this.
I upgraded my Microsoft.Build.* and Microsoft.CodeAnalysis dependencies to latest, THIS DIDN'T FIX THINGS YET, same bug.
I navigated to C:\Program Files\dotnet\sdk which previously had a few directories:
1.0.0/ 1.0.0-rc4-004771/ 2.0.3/ 2.1.505/
1.0.0-preview1-002702/ 1.0.3/ 2.1.202/ 3.1.100/
1.0.0-preview2-003121/ 1.0.4/ 2.1.4/ 3.1.201/
1.0.0-preview4-004233/ 1.1.0/ 2.1.502/ NuGetFallbackFolder/
I renamed this to sdk_o and created a new folder C:\Program Files\dotnet\sdk, copying in only 3.1.201/
Success! This error was gone, but running my roslyn app then resulted in some error like (paths stripped)
[Failure] Msbuild failed when processing the file with message The "ProcessFrameworkReferences" task failed unexpectedly. System.IO.FileNotFoundException: Could not load file or assembly 'NuGet.Frameworks, Version=5.5.0.4, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified. File name: 'NuGet.Frameworks, Version=5.5.0.4, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
Solved this one by adding NuGet.ProjectModel 5.5.1 to my project, the csproj now has the following package references:
<ItemGroup>
<PackageReference Include="Microsoft.Build" Version="16.5.0" ExcludeAssets="runtime" />
<PackageReference Include="Microsoft.Build.Framework" Version="16.5.0" ExcludeAssets="runtime" />
<PackageReference Include="Microsoft.Build.Locator" Version="1.2.6" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="16.5.0" ExcludeAssets="runtime" />
<PackageReference Include="Microsoft.CodeAnalysis" Version="3.5.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.5.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="3.5.0" />
<PackageReference Include="NuGet.ProjectModel" Version="5.5.1" />
</ItemGroup>
No more WorkspaceFailed events for this code:
Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults();
var workspace = MSBuildWorkspace.Create();
workspace.WorkspaceFailed += (s, e) => { Console.WriteLine(e.Diagnostic); };
var project = await workspace.OpenProjectAsync(#"C:/path/to.csproj");
The csproj I'm loading with Roslyn looks as follows:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<OutputType>Library</OutputType>
<ApplicationIcon />
<StartupObject />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\dependencies\some.csproj" />
</ItemGroup>
</Project>

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.