How to register validators from more than one assembly in FluentValidation? - fluentvalidation

I have FluentValidators in more than one assembly. In prior versions of FluentValidation, I was able to register like this:
services.AddMvc()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyOne>())
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyTwo>());
But, this now results in the following error:
Exception thrown: 'System.InvalidOperationException' in System.Linq.dll
An exception of type 'System.InvalidOperationException' occurred in System.Linq.dll but was not handled in user code
Sequence contains more than one matching element
Is this no longer allowed? If not, what is the proper way to do this?

I got the same error after upgrading FluentValidation.AspNetCore from 7.2.1 to 7.4.0 (as well as upgrading to ASP.NET Core 2.0).
I solved it by only calling .AddFluentValidaton(...) once, like this:
services.AddMvc()
.AddFluentValidation(fv => {
fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyOne>());
fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyTwo>());
});

This is the correct syntax to add as many assemblies as possible.
services
.AddMvc()
.AddFluentValidation(fv => {
fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyOne>();
fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyTwo>();
fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyThree>();
});

Related

Disable or Mock a background service in xunit .net core

I have this line of code in my startup.cs in my project
services.AddHostedService<AkkaService>(sp => (AkkaService)sp.GetRequiredService<IEasyProcessor>());
I need to disable this line when I run my tests .I don't want use environment variable .I just need to mock or disable this service .
I Mock this service in my test solution like this :
Mock<IEasyProcessor> easyprocessor= new Mock<IEasyProcessor>();
services.AddScoped<IEasyProcessor>(processor =>{ return easyprocessor.Object; });
But I get this error :
System.InvalidCastException: 'Unable to cast object of type 'Castle.Proxies.IEasyProcessorProxy' to type 'easy.api.Akka.AkkaService'.'

JsonApiDotNetCore 4.0 has removed BuildResourceGraph from JsonApiOptions. What is the replacement?

I am migrating from .NET Core 2.2 to 3.1. In doing so, I have updated the JsonApiDotNetCore package from 3.1 to 4.0.0 alpha 4.
In 2.2, I used JsonApiDotNetCore 3.1 and was using BuildResourceGraph to add any JSON API resources to the resource graph. Code below:
IMvcCoreBuilder objMvcCoreBuilder = null;
objServices.AddJsonApi((objOptions) =>
{
objOptions.BuildResourceGraph((objBuilder) =>
{
objBuilder
.AddResource<Register>("registers")
.AddResource<Client>("clients")
;
});
}, objMvcCoreBuilder);
But, I get the following error:
'JsonApiOptions' does not contain a definition for
'BuildResourceGraph' and no accessible extension method
'BuildResourceGraph' accepting a first argument of type
'JsonApiOptions' could be found (are you missing a using directive or
an assembly reference?)
What is the replacement for BuildResourceGraph?
After digging through the JsonApiOptions.cs commit history on Git, I found the change:
IMvcCoreBuilder objMvcCoreBuilder = null;
objServices.AddJsonApi(
options => options.Namespace = "api/v1",
resources: resources =>
resources
.AddResource<Register>("registers")
.AddResource<Client>("clients")
,
mvcBuilder: objMvcCoreBuilder
);
Go down to the /NoEntityFrameworkExample/Startup.cs file and you will see the diff that shows the change. Other than that, there is only a cryptic mention to renaming BuildResourceManager in the change log notes at the top of the site.
https://github.com/json-api-dotnet/JsonApiDotNetCore/commit/7b8250bf5b9e64b91d8fa0357e915a1121eb6081#diff-d56ca61ff20d8be0b7cb20c9fd106d9f
The revised version of the file is here:
https://github.com/json-api-dotnet/JsonApiDotNetCore/blob/7b8250bf5b9e64b91d8fa0357e915a1121eb6081/src/Examples/NoEntityFrameworkExample/Startup.cs

Send exception for UNIQUE constraint to UI in .NET core

When a unique constraint exception occurs, how do I message the UI in .NET Core; I want to return JSON, not MVC/Razor approach.
I think you have been looking at my article Catching Bad Data in Entity Framework. In there I describe a way to catch a SQL error and turn it into a validation error for EF Core.
UPDATE
In answer to your follow on questions I can point you to the code associated with the book I am writing, Entity Framework Core in Action. In this I built a method called SaveChangesSqlCheck, which contains the code to check for sql errors. You would use this method instead of calling SaveChanges, and it will return a ValidationResult.
My book has associated git repository where I have unit tests for just about everything I show in the book. Below are links to a unit test to see how you call SaveChangesSqlCheck, and then the SaveChangesSqlCheck code itself.
Unit test: https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/Test/UnitTests/DataLayer/Ch10_CatchSqlError.cs#L59-L89
The SaveChangesSqlCheck code: https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/DataLayer/EfCode/SaveChangesSqlCheck.cs
The method that catches the Unique error: https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/DataLayer/EfCode/SqlErrorFormatters.cs
Note: you need to format the unique constraint name in a special way - see https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/Test/Chapter10Listings/EfCode/Configuration/MyUniqueConfig.cs for an example.
If you plan to use the code shown in the article then all you need to do is use JsonConvert.SerializeObject(errors) to turn that into json. I have included some code so you can see what the json output would look like.
var error = new ValidationResult("error message");
var jsonList = JsonConvert.SerializeObject(error,
new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented });
The json output of this would be
{
"MemberNames": [],
"ErrorMessage": "error message"
}
I hope that helps.

Identity error when to ASP.NET Core MVC RC2 upgrading from RC1

I have from my RC1 version:
services.AddIdentity<User, Role>(options =>
{
// configure identity options
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 3;
options.User.AllowedUserNameCharacters = null;
})
.AddEntityFrameworkStores<JobsDbContext, int>()
.AddUserStore<UserStore<User, Role, JobsDbContext, int>>()
.AddRoleStore<RoleStore<Role, JobsDbContext, int>>()
.AddDefaultTokenProviders();
and I am getting an error on the first line specifically this part of the line:
AddIdentity<User, Role>
The error is:
The call is ambiguous between the following methods or properties: 'Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionExtensions.AddIdentity(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)' and 'Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionExtensions.AddIdentity(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)' JobsLedger..NETCoreApp,Version=v1.0 C:\Users\simon\DEV\JobsLedger-RC2-FIrstAttempt\src\JobsLedger\Startup.cs 64 Active
I know this is bleeding edge but if there is anybody out there who might have an idea on this I am all ears..
Please check the other answers on StackOverflow, there is a dozen of question asking the exact same thing.
Your issue is that you mix RC1 and RC2 libraries. This won't work! All of stack libraries (ASP.NET/MVC/EF/Identity) have to be 1.0.0-rc2-final, not 1.0.0-rc2-* or rc1. Read the annoncements, they have all the breaking changes in them.
Often outdated package name is an issue (i.e. Microsoft.AspNet.Mvc is outdated and you have to use Microsoft.AspNetCore.Mvc, as the first one will drag old dependencies.
Also some of your other dependencies (i.e. Swashbuckle.Swagger etc.) may still reference old rc1 libraries. They all need to be upgraded to the latest rc2 builds.
The error message you are getting is because two assemblies with different name are referenced and both have the same extension method in the same namespace so the compiler doesn't know which one to choose.

TaskEx.WhenAll and Exceptions

I'm constrained to using the .NET 4.0 framework and Async CTP Extensions to do something like the following:
var dataTasks = _tasks.Select(t => t.GetData(keys));
var results = TaskEx.WhenAll(dataTasks).Result.ToList();
where _tasks is a list of objects that each provide a GetData method that returns a Task<Data>.
My problem is that one of the dataTasks is throwing an exception and tanking the whole. I'd like to be able to inspect the results of each dataTask and check the results, logging any exception and then continuing on with any valid results. I'm unsure now to go about it though. Any help would be greatly appreciated.
One way to do this would be to use a trivial ContinueWith() to change a potentially faulting Task<T> into a successful Task<Task<T>>. If you then use WhenAll().Result on that (or await WhenAll()), you'll get Task<T>[], which is exactly what you need:
var dataTasks = _tasks.Select(t => t.GetData(keys).ContinueWith(c => c));
Task<T>[] results = Task.WhenAll(dataTasks).Result;
TaskEx.WhenAll(dataTasks) is your combined task. It might be faulted.
When calling Result this cause the exception to be thrown. So don't do that. Examine the Exception or IsFaulted properties.