FluentValidation.AspNetCore is not working in Class Library - fluentvalidation

I am using library "FluentValidation.AspNetCore": "6.4.0-beta3" in .netcore WebApi in a project. You can see the project structure below. Library is working fine if i place the CurrencyDTO.cscode in section 2 (Project FH.WebAPI) and if the same code placed in section 1 (Class Library DTO) its not working. And requirement is that i have to place code in Class library FH.Common. Is there any work around.I have search but didn't find any thing
Project Structure
CurrencyDTO.cs
[Validator(typeof(CurrencyDTOValidator))]
public class CurrencyDTO
{
public int Id { get { return CurrencyId; } }
public int CurrencyId { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
}
public class CurrencyDTOValidator : AbstractValidator<CurrencyDTO>
{
public CurrencyDTOValidator()
{
RuleFor(x => x.Name).NotEmpty().NotNull().WithMessage("The currency 'Name' is required.")
.Length(0, 250).WithMessage("The currency 'Name' cannot be more than 250 characters.");
RuleFor(x => x.Symbol).NotEmpty().WithMessage("The currency Symbol is required.");
}
}
Library Configuration
Step 1) . Add in project.json
{
"dependencies": {
"Autofac": "4.3.0",
"Autofac.Extensions.DependencyInjection": "4.0.0",
"AutoMapper": "5.2.0",
"EntityFramework": "6.1.3",
"FH.Business": "1.0.0-*",
"FH.Common": "1.0.0-*",
"JWT": "1.4.1-beta",
"Microsoft.AspNet.Http.Extensions": "1.0.0-rc1-final",
"Microsoft.AspNet.WebApi.Client": "5.2.3",
"Microsoft.AspNet.WebApi.Core": "5.2.3",
"Microsoft.AspNetCore.Authentication.JwtBearer": "1.1.0",
"Microsoft.AspNetCore.Diagnostics": "1.1.0",
"Microsoft.AspNetCore.Mvc": "1.1.1",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
},
//other libraries..
"FluentValidation.AspNetCore": "6.4.0-beta3" //<------Here
},
"tools": {
"BundlerMinifier.Core": "2.0.238",
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"net461": {
"frameworkAssemblies": {
"System.Drawing": "4.0.0.0"
}
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"publishOptions": {
"include": [
"wwwroot",
"Views",
"Areas/**/*.cshtml",
"appsettings.json",
"web.config"
]
},
"scripts": {
"prepublish": [ "bower install", "dotnet bundle" ],
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
Step 2). In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(options => { }).AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
// Other code..
}
Used in Controller
[HttpPost]
[Route("CreateCurrency")]
public IActionResult CreateCurrency([FromBody] CurrencyDTO model)
{
if (!ModelState.IsValid) //<----Validate here
{
return new BadRequestObjectResult(ModelState);
}
//Other Code..
}

The problem was in a registration line in startup.csand thank to #JeremySkinner who have suggested me the right way and i am quoting his answer here.
My mistake
services.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
Replace
RegisterValidatorsFromAssemblyContaining<Startup>()
with
RegisterValidatorsFromAssemblyContaining<CurrencyDTOValidator>()
Actual link to the Issue
Link Description
Above link is the answers posted #JeremySkinner

Related

Asp.net Core EF options.UseInMemoryDatabase System.TypeLoadException

I used EF in Asp.net Core, but got below error in below code:
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options)
: base(options)
{
}
public DbSet<TodoItem> TodoItems { get; set; }
}
Error Message:
An exception of type 'System.TypeLoadException' occurred in
Microsoft.EntityFrameworkCore.dll but was not handled in user code
Additional information: Could not load type
'Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionExtensions'
from assembly 'Microsoft.Extensions.DependencyInjection.Abstractions,
Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
Here is my Project.json
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Logging.Console": "1.0.0",
//Dependence for MVC
"Microsoft.AspNetCore.Mvc": "1.1.1",
"Microsoft.AspNetCore.StaticFiles": "1.1.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
"Microsoft.Extensions.Configuration.Json": "1.1.0",
//Dependence for EF
"Microsoft.EntityFrameworkCore": "1.1.0",
"Microsoft.EntityFrameworkCore.InMemory": "1.0.0-rc2-final"
//Dependence for EF with SQL, this is avalible under VS 2017 RC
//"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
//Entity Framework commands to maintain the database
//"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview4-final"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
//used for Razor pages which are compiled at runtime,and the compiler needs access to reference assemblies,
//to make sure it compiles correctly
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"web.config"
]
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
Any help would be appreciated.
Reards,
Edward
After trying, I changed "1.0.0-rc2-final" to "1.1.0" which I already have tried, but I found there is an warning, "Dependency conflict. CoreMVCWebAPI 1.0.0 expected Microsoft.EntityFrameworkCore.InMemory >= 1.1.0 but received 1.0.0-rc2-final", after install this package manually instead of only changing project.json, it works now.
Install-Package Microsoft.EntityFrameworkCore.InMemory
I just wanted to add that I had to restart VS2017 before the package restore was recognised. Prior to that I was getting an error
DbContextOptionsBuilder does not contain a definition for
UseInMemoryDatabase() ...
I hope this saves you time.

UseStaticFiles() throws error "Connection refused"

I have problem with serving static file in asp.net core. I am really new to it. Just followed a tutorial from pluralsight and stuck here.
I have added index.html in wwwroot folder, and added dependencies for static file in Json, but still does not seems to work. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace TheWorld
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
// app.Run(async (context) =>
// {
// await context.Response.WriteAsync("Hello World!");
// });
}
}
}
And this is my project.json
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"web.config"
]
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
In order for your Web app to serve a default page without the user having to fully qualify the URI, call the UseDefaultFiles extension method from Startup.Configure as follows.
public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
}
UseDefaultFiles must be called before UseStaticFiles to serve the default file.
Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files#serving-default-files

Could not load file or assembly mscorlib

I'm new in NetCore and I try to load a dll dynamically with this code :
public void LoadDll()
{
try
{
var dllPath = #"C:\Temp\dynamic.dll";
var asl = new AssemblyLoader();
var asm = asl.LoadFromAssemblyPath(dllPath);
var type = asm.GetType("MyNamespace.MyClass");
dynamicInstance = Activator.CreateInstance(type);
}
catch (Exception ex)
{
}
}
public class AssemblyLoader : AssemblyLoadContext
{
// Not exactly sure about this
protected override Assembly Load(AssemblyName assemblyName)
{
var deps = DependencyContext.Default;
var res = deps.CompileLibraries.Where(d => d.Name.Contains(assemblyName.Name)).ToList();
var assembly = Assembly.Load(new AssemblyName(res.First().Name));
return assembly;
}
}
When I call asm.GetType method a exception is thrown :
"Could not load file or assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. An operation is not legal in the current state. (Exception from HRESULT: 0x80131509)" Source : System.Private.CoreLib
Here is my project.json :
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.Routing": "1.0.1",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config"
]
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
Can someone help me ?
SThis is a very common problem. As of .NET Core 1.1 you cannot load libraries built for the .NET Framework (they are mscorlib based) but only ones which are build using PCL.
Check the assembly you try to load.
.NET Core 2.0 will address this topic.

Is NodaTime compatible with NetCoreApp 1.0?

I have dotnet core app that I'm working on that is cross-platform. I wanted to use Noda as a utility in my project but get the following error even tho I have nodatime defined as a dependency in my project:
System.IO.FileNotFoundException: Could not load file or assembly 'NodaTimestrong text, Version=2.0.0.0, Culture=neutral, PublicKeyToken=4226afe0d9b296d1'. The system cannot find the file specified.
File name: 'NodaTime, Version=2.0.0.0, Culture=neutral, PublicKeyToken=4226afe0d9b296d1'
at project.ef.CalendarHelper.ValidateTimeZone(String timezoneTypeName)
at project.ef.CalendarHelper.
Here are the project config files:
API PROJECT
{
"buildOptions": {
"preserveCompilationContext": true,
"emitEntryPoint": true,
"warningsAsErrors": true,
"debugType": "portable",
"copyToOutput": {
"include": [
"config.json",
"Certificate.pfx"
]
}
},
"dependencies": {
"AspNet.Security.OAuth.Introspection": "1.0.0-alpha2-final",
"AspNet.Security.OAuth.Validation": "1.0.0-alpha2-final",
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Mvc.Formatters.Json": "1.0.0",
"Microsoft.AspNetCore.Mvc.Cors": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.EntityFrameworkCore.Design": {
"type": "build",
"version": "1.0.0-preview2-final"
},
"Microsoft.NETCore.App": "1.0.0",
"project.ef": "1.0.0-*"
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [ "portable-dnxcore50+net45+win8+wp8+wpa81" ]
}
},
"publishOptions": {
"include": [
"config.json"
]
},
"runtimes": {
"win10-x64": {},
"osx.10.11-x64": {},
"ubuntu.14.04-x64": {}
}
}
EF PROJECT
{
"dependencies": {
"NETStandard.Library": "1.6.0",
"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.1",
"Npgsql.EntityFrameworkCore.PostgreSQL.Design": "1.0.1",
"project.Internal.ERP": "1.1.0-*",
"project.models": "1.0.0-*",
"NodaTime": "2.0.0-alpha-*"
},
"frameworks": {
"netstandard1.6": {
"imports": [
"dnxcore50",
"portable-net451+win8"
]
}
}
}
Noda Time 1.x only targets PCLs. You may be able to get it to work with netcoreapp1.0, but I'm not going to guarantee it.
But Noda Time 2.0 targets netstandard1.1, so should be fine. That's only available as an alpha release right now, but it works fine:
project.json contents:
{
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"NodaTime": "2.0.0-alpha20160729"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
}
}
}
}
Program.cs contents:
using System;
using NodaTime;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(SystemClock.Instance.GetCurrentInstant());
}
}
That runs with no problems.

Reference a NET461 DLL model type from ASP.NET Core View

I have a new ASP.NET Core RC2 built as follows:
Model stored in DLL library of .NET Framework 461
Web is MVC Core 1.0 Full Framework - not based on core framework
when reference the model type in the DLL library and run the project, i got the following error:
An error occurred during the compilation of a resource required to
process this request. Please review the following specific error
details and modify your source code appropriately. Generated Code The
type or namespace name 'Data' does not exist in the namespace
'ADMA.EWRS' (are you missing an assembly reference?)
23. public class _Views_Murad_Index_cshtml : Microsoft.AspNetCore.Mvc.Razor.RazorPage>
The type or namespace name 'Data' does not exist in the namespace
'ADMA.EWRS' (are you missing an assembly reference?)
39. public Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper>
Html { get; private set; } An error occurred during the compilation of
a resource required to process this request. Please review the
following specific error details and modify your source code
appropriately. Generated Code The type or namespace name 'Data' does
not exist in the namespace 'ADMA.EWRS' (are you missing an assembly
reference?)
23. public class _Views_Murad_Index_cshtml : Microsoft.AspNetCore.Mvc.Razor.RazorPage>
The type or namespace name 'Data' does not exist in the namespace
'ADMA.EWRS' (are you missing an assembly reference?)
39. public Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper>
Html { get; private set; }
Config Project.json as follow :
{
"dependencies": {
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview1-final",
"type": "build"
},
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
"Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc2-final",
"Microsoft.AspNetCore.Authorization": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Authentication": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Session": "1.0.0-rc2-final",
"ADMA.EWRS.Web.Security": "1.0.0-*"
},
"tools": {
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview1-final",
"imports": "portable-net45+win8+dnxcore50"
},
"Microsoft.AspNetCore.Server.IISIntegration.Tools": {
"version": "1.0.0-preview1-final",
"imports": "portable-net45+win8+dnxcore50"
}
},
"frameworks": {
"net461": {
"dependencies": {
"ADMA.EWRS.BizDomain": {
"target": "project"
},
"ADMA.EWRS.Data.Models": {
"target": "project"
}
}
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"publishOptions": {
"include": [
"wwwroot",
"Views",
"appsettings.json",
"web.config"
]
},
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ],
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
Solution Explorer
X Project
Solved after Adding Razor Options as in below code :
services.AddMvc().// Murad Add this for RC2, remove it if release 1.0 after June
AddRazorOptions(options =>
{
var previous = options.CompilationCallback;
options.CompilationCallback = context =>
{
previous?.Invoke(context);
context.Compilation = context.Compilation.AddReferences(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(ADMA.EWRS.Data.Models.Murad).Assembly.Location));
};
});
//var myAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(x => Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(x.Location)).ToList();
//services.Configure((Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions options) =>
//{
// var previous = options.CompilationCallback;
// options.CompilationCallback = (context) =>
// {
// previous?.Invoke(context);
// context.Compilation = context.Compilation.AddReferences(myAssemblies);
// };
//});
Check
https://github.com/aspnet/Mvc/issues/4686