How do I port the following code to .NET Core?
AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName(
Guid.NewGuid().ToString()),
AssemblyBuilderAccess.RunAndSave);
Is it possible?
Add this to your project.json:
"dependencies": {
"System.Reflection.Emit": "4.0.1"
},
and use:
AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()),
AssemblyBuilderAccess.Run);
AssemblyBuilderAccess.RunAndSave is not supported at the moment - link to source.
For new .csproj projects, use:
<ItemGroup>
<PackageReference Include="System.Reflection.Emit" Version="4.3.0" />
</ItemGroup>
Related
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>
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>
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.
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();
}
}
}
I've selected "Xml documentation file" in my ASP.NET Core MVC application and it displays "bin\Debug\net452\MyProject.xml" as output folder. The problem is that this file doesn't exist in publish folder. Do I need to someting additional to include it? Using .NET Core 1.0-RC4 and VS.NET 2017 RC4 (new csproject format).
If you're using project.json then you can control the files and folders that are both included and excluded by the publish process:
"publishOptions": {
"include": [
"wwwroot",
"appsettings.json",
"appsettings.*.json",
"web.config"
],
"exclude": [
"wwwroot/less"
]
}
For .csproj based projects here is a good resource for replicating old project.json settings in XML, for example:
<ItemGroup>
<Compile Include="..\Shared\*.cs" Exclude="..\Shared\Not\*.cs" />
<EmbeddedResource Include="..\Shared\*.resx" />
<Content Include="Views\**\*" PackagePath="%(Identity)" />
<None Include="some/path/in/project.txt" Pack="true" PackagePath="in/package.txt" />
<None Include="notes.txt" CopyToOutputDirectory="Always" />
<!-- CopyToOutputDirectory = { Always, PreserveNewest, Never } -->
<Content Include="files\**\*" CopyToPublishDirectory="PreserveNewest" />
<None Include="publishnotes.txt" CopyToPublishDirectory="Always" />
<!-- CopyToPublishDirectory = { Always, PreserveNewest, Never } -->
</ItemGroup>
Apparently this is not implemented in with dotnet publish but will be in the near future: https://github.com/dotnet/sdk/issues/795
The project.json file should have the "xmlDoc": true under "buildOptions":
{
"buildOptions": {
"xmlDoc": true
}
}
If you have documentation in your code like this:
/// <summary>
/// Documentation for FooClass
/// </summary>
public static class FooClass
{
// ...
}
Then you should have an xml file in your output that looks like this:
<doc>
<assembly>
<name>Foo.Bar</name>
</assembly>
<members>
<member name="T:Foo.Bar.FooClass">
<summary>
Documentation for FooClass
</summary>
</member>
</members>
</doc>
Tested on 1.1.2
ResolvedFileToPublish is the Item that publish uses to know which files to put in the publish folder. The Include is the file's source, and the RelativePath is where inside the publish folder the file should be placed.
ComputeFilesToPublish is exactly as its name implies - it is the Target that gathers all the files to be published.
<Target Name="CopyDocumentationFile"
AfterTargets="ComputeFilesToPublish">
<ItemGroup>
<ResolvedFileToPublish Include="#(FinalDocFile)"
RelativePath="#(FinalDocFile->'%(Filename)%(Extension)')" />
</ItemGroup>
</Target>
Just add this target to your .csproj and make sure that
GenerateDocumentationFile is set to true
<GenerateDocumentationFile>true</GenerateDocumentationFile>
https://github.com/dotnet/sdk/issues/795#issuecomment-289782712
In Asp.net Core, if you are having trouble setting DocumentationFile to work, we can do that by setting GenerateDocumentationFile property in .csproj:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>