How to inject dependencies used for validation in .NET MVC3? - asp.net-mvc-3

We have quite a few validation methods that need to access repositories / database to do their work. So far we have been using the service locator pattern (albeit sparingly) to accomplish this in custom ValidationAttributes:
public override bool IsValid(object value)
{
// use custom service locator in our app's infrastructure
var repos = DependencyInjector.Current.GetService<IXyzRepository>();
...
}
I know this is :( upon as an anti-pattern, and we would like to use a more correct approach. We use unity, and I read this post that says to use a build-up method. However the link in the accepted answer says that the documentation is outdated (retired content).
The solution does not need to use a validation attribute, I suppose it could use IValidatableObject, however the problem remains: how to inject the dependency into the model. Do we need a custom model binder to do this?
Another solution would be to perform the validation in the controller, where dependency injection is easy. To me this feels cluttered though. I would like the model to be validated by the time it gets to the action method.
Also we sometimes use [RemoteAttribute] to perform some of these validations on the client. Currently those methods construct a viewmodel and delegate validation to the model by using the static Validator.TryValidateObject method.
How have you accomplished validation that requires an injected dependency to do its work, without using the SL anti-pattern?

How have you accomplished validation that requires an injected
dependency to do its work, without using the SL anti-pattern?
I use FluentValidation.NET to perform validation in my applications. It allows me to inject dependencies into my validators. It has a really nice integration with ASP.NET MVC. It also supports automatic client side validation for the standard rules just the same way as data annotations using jquery unobtrusive validate:
NotNull/NotEmpty
Matches (regex)
InclusiveBetween (range)
CreditCard
Email
EqualTo (cross-property equality comparison)
Length
I have never used data annotations to perform validation. They are absolutely useless when you need to handle some more complex validation scenarios where you need to validate dependent properties and even use some service. I put complex in italics in the previous sentence because, I don't think that validating that one of the 2 properties is required is a really complex validation scenario and yet, just checkout the amount of infrastructure crap you have to write in order to implement it using data annotations. Looking at this code you no longer know what you are validating.

Inject your validation into your Model.
Validation Attributes can become awkward to work with when your validation stories become more complex. Yuck!
I like to use Entity Framework with Code First. I have full control of my model at that point. I also use FluentValidation like #Darin Dimitrov and I really like its ease of use and simple syntax.
Here’s how you put it together.
I assume you have assembly with your interfaces or contracts.
This will be the base interface for your models…
using System.ComponentModel;
using FluentValidation.Results;
public interface IAbstractBase : IDataErrorInfo
{
bool IsValid { get; }
ValidationResult SelfValidate();
}
and its counterpart in your business layer looks like this…
using System;
using System.Linq;
using FluentValidation.Results;
using Contracts;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public abstract class AbstractBase : IAbstractBase
{
#region IDataErrorInfo
public abstract ValidationResult SelfValidate();
[NotMapped]
public bool IsValid
{
get
{
return SelfValidate().IsValid;
}
}
[NotMapped]
public string Error
{
get
{
var results = SelfValidate().Errors.Select(s => string.Format("● {0}{1}", s.ErrorMessage, Environment.NewLine)).ToArray();
return string.Join("", results);
}
}
[NotMapped]
public IList<ValidationFailure> Errors
{
get
{
var results = SelfValidate().Errors;
return results;
}
}
[NotMapped]
public string this[string columnName]
{
get
{
var validationResults = SelfValidate();
if (validationResults == null) return string.Empty;
var columnResults = validationResults.Errors.FirstOrDefault(x => string.Compare(x.PropertyName, columnName, true) == 0);
return columnResults != null ? columnResults.ErrorMessage : string.Empty;
}
}
#endregion
}
This is your base class for your models. Make sure you implement the abstract method in your models. It should look like this.
public class MyModel : AbstractBase, IMyModel
{
private AbstractValidator<IMyModelValidator> _myModelValidator;
public MyModel():this(new MyModelValidator()){};
public MyModel(AbstractValidator<IMyModelValidator> myModelValidator){
_myModelValidator = myModelValidator;
};
public int MyModelId { get; set; }
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
public override ValidationResult SelfValidate()
{
return _myModelValidator.Validate(this);
}
}
Your validator class will look something like this.
public class MyModelValidator : AbstractValidator<IMyModelValidator>
{
private IMyModelProvider _myModelProvider;
public MyModelValidator(IMyModelProvider myModelProvider){ _myModelProvider = myModelProvider;};
private void SetRules()
{
RuleFor(x => x.Name).NotEmpty().WithMessage("Please specify a project name.");
RuleFor(x => x.Name.Length).LessThanOrEqualTo(100).WithMessage("The project name must be less than or equal to 100 characters.");
}
public override ValidationResult Validate(IMyModel instance)
{
SetRules();
return base.Validate(instance);
}
}
Pass your validation results from your Model to your view in your Controller using the following call in your controller.
TryValidateModel(your model here);
After you call this in your controller call your model.IsValid property.
Make sure you register everything and you should be good to go. I assume you can fill in the missing pieces.
The big picture looks like this:

Related

Injecting Non-User-Submitted Data For Use During Validation

From what I can tell, ASP.Net Core performs model state validation before calling the relevant controller action method. This means that code in the action method isn't given an opportunity to add data to the model before it is validated.
What is the ASP.Net Core way of giving a view model access to additional, non-user-submitted data prior to validation?
Example
What I'm trying to do (doesn't work).
The view model's Validate method expects data to be in ValidOptions. However, since validation occurs before the controller can set this property, validation causes the view model to throw an ArgumentNullException.
// From the Controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Process([Bind("SelectedId")]ViewModels.Import details)
{
// data needed for validation
details.ValidOptions = await service.ImportTypes.ToListAsync();
if (ModelState.ValidationState != ModelValidationState.Valid) {
// ...
}
}
// From ViewModels.Import
public IEnumerable<Option> ValidOptions { get; set; }
public int SelectdId {get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// throws ArgumentNullException because ValidOptions hasn't been set when this is executed
var option = ValidOptions.Single(t => t.Id == SelectdId);
//...
}
Probably many ways to skin a cat here. But the easiest for you is probably custom model binders. It's a way to "supplement" or change the binding of your model before it hits the controller. I will say that some see it as extremely bad practice to call an external service/repository at the point of model binding, but it does work and can come in handy.
You need to implement a class that inherits from IModelBinder.
public class MyViewModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
//Bind here. Including calling external services if you want.
}
}
Then you need to implement a provider, this essentially says "when" to bind.
public class MyViewModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(MyViewModel))
return new MyViewModelBinder();
return null;
}
}
In your configure method of your startup.cs, you need to add the provider to the ModelBinderProviders list.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(config =>
config.ModelBinderProviders.Add(new MyViewModelBinderProvider())
);
}
Further Documentation :
http://dotnetcoretutorials.com/2016/12/28/custom-model-binders-asp-net-core/
http://intellitect.com/custom-model-binding-in-asp-net-core-1-0/
I don't think the official documentation has an article on custom model binders yet unfortunately.

Where to validate DTO

I am writing a Webservice which sends and receives DTO's
A DTO might look like this(in this example its C#)
[Serializable]
public class GetCardStatusRequest : RequestBase
{
public GetCardStatusRequest()
{
}
public String CardId { get; set; }
}
when receiving such a request DTO I want to validate that the CardId is for example not empty.
So I currently have a validation class
internal class Validation
{
internal static bool IsValidGetGiftCardStatusRequest(GetCardStatusRequest getCardStatusRequest)
{
return getCardStatusRequest.CardId != null && !string.IsNullOrEmpty(getCardStatusRequest.CardId);
}
}
There are more "complex" DTO's so I wanted to place the validation logic somewhere to ensure that the incoming requests are valid before mapping them to the business objects.
My question is where should I place the validation logic and how should I do it ? I currently have this class with only static methods which seem wrong to me.
Should this validation be placed in the service layer ?
I feel quite close with this logic above, but nevertheless it seems not correct.

Doctrine: Validate Model Data using Annotations

In doctrine, is there a way that I could validate model data using annotations? Like the bellow example in c#
public class ProductMD {
[StringLength(50),Required]
public object Name { get; set; }
[StringLength(15)]
public object Color { get; set; }
[Range(0, 9999)]
public object Weight { get; set; }
}
So when the property Name is empty then it will give you error.
Unfortunately, starting from Doctrine2 there is no validation component integrated into the ORM itself anymore.
If, for example, you're using Doctrine2 with Symfony2, you can take advantage of the validation framework component by using #Assert annotations in the Doctrine entities.
If you don't use any framework, or if the framework you use does not provide a validation component, you can always use Doctrine's lifecycle callbacks to provide custom validation in #PrePersist and #PreUpdate (for more information, take a look here). In this case, there's more manual work to be done but it still sounds like a reasonable solution.

How do I use asp.net MVC Scaffolder with a context that is two subclasses down from dbcontext

I have a standard model set.
I have a base context class that inherits from dbcontext to add some features I needed.
public class MyContext : DbContext
{
public void MyFeature() {
}
}
I then have my actual Data Context:
public class DataContext : MyContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
I want to use the scaffolder built in when you create a controller, but I get an error "Unsupported Context Type"
If I change the datacontext to just inherit from dbcontext directly it works, but at this point I have alot of stuff that uses the added features, so changing the inheritance cant be done without commenting out all that stuff. And I have of course simplified down the features, it is actually quite alot of stuff, so adding it directly into the datacontext would be alot of work, plus the scaffolder should be smart enough to see that the datacontext is a dbcontext.
How can I use the scaffolder with my datacontext?
Why don't you use Composition?
If your feature really is just needed as lets say a few methods needed in those objects I would put those methods in a separate class called ContextDetails - something along those lines and have DataContext contain a ContextDetails like so:
//Changed MyContext to ContextDetails
public class ContextDetails
{
public void MyFeature()
{
//Do something
}
}
public class DataContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public ContextDetails DbDetails { get; set; }
}
And if the ContextDetails object needs information about the DataContext/DbContext it's in pass the DataContext/DbContext into a method or even the constructor.
If you don't like Composition for this problem maybe you want to use an Interface. If that's the case check out http://www.codeproject.com/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C
The context class must inherit from System.Data.EntityDbContext which provides facilities for querying and working with entity data as objects
The best reason I could find for why the inheritance is not working in your example.
EDIT:
I read my answer and realized DBDetails might not be the best name but you get the idea. Extract the implementation and use it as a separate entity. Good luck!
i think first you should install entity framework 4.0 then i think definitely it's working please try this.

Metadatatypes with self-validation using validation application block

Is it possible to use the selfvalidation attribute with my validations located in a metadatatype? I'm using Enterprise Library 5's Validation Application Block.
As I explained in my other answer, this isn't supported out of the box. However, this can be achieved by hooking into the framework using depedency injection and replace the existing AttributeValidatorFactory implementation. I written a post on my weblog on how to do this: Mixing Validation Application Block With DataAnnotation: What About SelfValidation?
I hope this helps.
This is currently not supported (out of the box) by VAB. Look for instance at this thread at the EntLib forum. I think the main reason this is not supported is because you can't simply place the [SelfValidation] method on the meta data type and expect this to work. Reason it won't work is because self validation methods will typically validate instance members of the type. The signature of the self validation method does not contain the actual object to validate.
A simple work around is call into the meta data type from the entity. For instance:
[MetadataType(typeof(InvoiceMetaData))]
[HasSelfValidation]
public partial class Invoice
{
public string Name{ get; set; }
public int Price { get; set; }
[SelfValidation]
public void CustomValidate(ValidationResults results)
{
// Call into the meta data class
InvoiceMetaData.Validate(this, results);
}
}
public class InvoiceMetaData
{
[StringLengthValidator(1, 10, Tag = "Name")]
string Name { get; set; }
[RangeValidator(0, RangeBoundaryType.Inclusive, 0,
RangeBoundaryType.Ignore, Tag = "Price")]
int Price { get; set; }
public static void CustomValidate(Invoice instance,
ValidationResults results)
{
results.AddResult(new ValidationResult("ErrorMessage1",
instance, "", "", null));
}
}
This of course isn't a very clean solution. VAB however is very extendable and version 5.0 only got better. If you want you can swap existing AttributeValidationFactory and replace it with a version that is able to do this. It won't be easy though.
Cheers

Resources