How to stop Ninject from overriding custom DataAnnotationsModelValidatorProvider? - asp.net-mvc-3

I have a custom DataAnnotationsModelValidatorProvider for doing model validation in a more dynamic way then just adding attributes. I tried to add my provide to the global.asax.cs like so:
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new AttributeValidatorProvider());
But once I load my form, I get an error saying "Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required".
According to a comment on this blog, this is because Ninject is overriding custom validator providers.
I'm fairly new to MVC and I can't seem to find a way to tell Ninject to accept my custom providers as well, how would I go about fixing this problem?
For the record: I do not wish to use Fluentvalidation.net, I want to stick with the default MVC validations (for the most part).

There is another way (works in MVC 4 for sure):
Find your class which inherit IdependencyResolver interface and add to constructor _kernel.Unbind<ModelValidatorProvider>(); - you just unbind ninject validator and there should be no colission with default validator.
In my case my constructor looks like this:
public NinjectDependencyResolver()
{
_kernel = new StandardKernel();
_kernel.Unbind<ModelValidatorProvider>();
AddBindings();
}

Change the registration of the provider to
Rebind<ModelValidatorProvider>().To<AttributeValidatorProvider>();

Related

What is the IShouldNormalize's alternative in Abp.io?

I have a project, that created in Abp.io framework. I before used ASP.NET Boilerplate framework and ASP.NET Boilerplate has IShouldNormalize interface for normalize request's input. But I don't find IShouldNormalize's alternative in Abp.io
What is the IShouldNormalize's alternative in Abp.io ?
No alternative. You can use IValidatableObject for validation and
simple normalization. You can add your own method and call in the
application service.
But we suggest you to make it in your application service method
explicitly
https://github.com/abpframework/abp/issues/1908
You can use the IValidatableObject for validation and normalization for your needs.
IValidatableObject has just a method named Validate you can define your normalization rules in here, that you normally do in the Normalize method of theIShouldNormalize interface.

how to implement spring support for custom template engine?

I've decided to use custom template engine with Spring MVC framework.
my templates implemented in java and have method for rendering into String:
public String render(Map context);
how to configure spring to make them available in Controller beans as views, for example like:
ModelAndView modelAndView = new ModelAndView("activationPage"); // - view name which will actually be java class name reference.
modelAndView.addObject("validationResult", validationResult);
return modelAndView;
Model will be passed as context in code connecting spring and my template engine.
You need to implement org.springframework.web.servlet.View (which should be easy, you already have something very similar to the render method it needs), as well as org.springframework.web.servlet.ViewResolver, which maps the view names (e.g. "activationPage") on your custom views.
Once you have that, drop a bean of your ViewResolver class into the context, and (unless you've done something else that gets in the way) it should automatically be picked up by Spring and should just work. if you have other ViewResolvers already in there, they may get into a fight over who gets to resolve the view, in which case ask a new question.
Hi I am the author of Rythm template engine, about half year ago I am having the same requirement like you. What I did is to read the source code of Velocity and Freemarker view of SpringFramework. And then create the Rythm view for spring following their approach.
It's easy to follow something that is already there, and it makes your implementation in good quality to follow the official module. Good luck on you :-)

Does ASP.NET web API support IValidatableObject?

I have a view model that implements IValidatableObject and also has several validation attributes. When I attempt to call an action on my ApiController, only the attribute validation is performed. Does ASP.NET Web API not support IValidatableObject? What's the alternative for complex validation that cannot be represented by a single attribute?
Edit: Somewhere along the line, I must have fudged something up. The validation mysteriously started working as expected. Looks like IValidatableObject is definitely supported by default.
With Web API 2.1 (Microsoft.AspNet.WebApi nuget 5.1.x), I experienced IValidatableObject's Validate method not being called if any of the validation attributes are invalid. Hence, all validation attributes that have been applied to your class's properties must first pass as valid before that class's Validate method will be called.
If, for example, you have a property with the RequiredAttribute and you do not put a value in that field, your implementation of IValidatableObject's Validate method will not be called. Although not technically a bug, I expected the Validate method to be called every time I validate.
Not yet tried IValidatableObject on webapi, but it should be supported according to the documentation the Validation provider for DataAnnotations (DataAnnotationsModelValidatorProvider) provide also IValidatableObject validation. See here: http://msdn.microsoft.com/en-us/library/system.web.http.validation.providers(v=vs.108)
Anyway, you can use also Object level ValidationAttribute that you can use to decorated a class...It is not so easy as IValidatableObject, but should work.
As of now, IValidatableObject is supported.

IModelBinder with DataAnnotation Support

We have to use a custom ModelBinder that implements IModelBinder. We cannot directly change this code at all. It currently doesn't have support for updating ModelState from the DataAnnotations of the model passed in. We want to subclass the ModelBinder and add that support. What do we need to do to add that support so it works like DefaultModelBinder works with DataAnnotations?

MVC3 Action Filter Using Database (EF 4.1 DBContext, Ninject)

I'm trying to setup an 'Authorization' Filter on an Action, creating my own ActionFilterAttribute where I do a database lookup to determine if a user has access to a certain resource.
On my class inheriting from ActionFilterAttribute, I have created an Injected(Ninject) property to hold the service that I am using for the database access. I have a parameterless constructor so that I can use this as an attribute on my actions. In the 'OnActionExecuting' Method, I am able to gain access to the Injected property (it's not null), but the base DBCotext that it is using is closed.
This working fine, up until the RTM of MVC3, where the Release Notes stated:
Breaking Changes:
In previous versions of ASP.NET MVC, action filters are create per
request except in a few cases. This
behavior was never a guaranteed
behavior but merely an implementation
detail and the contract for filters
was to consider them stateless. In
ASP.NET MVC 3, filters are cached more
aggressively. Therefore, any custom
action filters which improperly store
instance state might be broken.
The first time I use this filter, it works as expected, but if I refresh the page or another user access this filter, I get the error:
The operation cannot be completed
because the DbContext has been
disposed.
which is what I guess I should expect given the breaking changes notes.
My question is this, what would be the preferred/recommended way of accomplishing what I need to do? Should this be in an ActionFilterAttribute, or should this 'authorization' be done somewhere else?
I'd do authentication in Application_AuthenticateRequest and authorization in your attribute using Thread.CurrentPrincipal, but your method should work too. You just need to count with fact that DbContext will be different for each request but your attribute won't. Something like this should do the trick (I'm assuming you are using DependencyResolver):
public class MyMightyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var context = (DbContext)DependencyResolver.Current.GetService(typeof(DbContext))
// authenticate, authorize, whatever
base.OnActionExecuting(filterContext);
}
}
I have been battling with this for a while and finally solved my problem. So here is my solution in the hope it may help someone else.
The setup:
1. I have an MVC3 project, a custom action filter that accesses the db using EF5 via a business service.
2. I use Unity and unity.MVC to resolve my dependencies on a per request basis.
3. I use property injection into my custom Action filter, as it has a parameterless constructor.
The result.
Dependency injection works correctly for all the services used by actions, my EF DbContext is correctly disposed of at the end of each request.
The Problem
Although my property dependency is resolved in my custom action filter, it contains a stale instance of my DbContext (e.g. it seems to have been cached from the previous request)
As mentioned in previous posts, MVC3 is more aggressive with filter caching and the state of a filter cannot be relied on. So the suggestion was to resolve the dependency in the OnActionExecuting method. So I removed my injected property and did just that called resolve on my unity container. However I still got a stale version of the DbContext. Any changes in the DB were correctly queried in my main actions, but the custom action filter didn’t pick them up.
The solution.
Unity.MVC Manages per-request lifetime by using child containers and disposing these at the end of each request. By resolving my dependency’s in the action filter from my unity container I was resolving from the parent container which is not disposed of on each request.
So rather than
IoC.Instance.CurrentContainer.Resolve<IService>();
I used this to obtain an instance of the child container rather than parent.
var childContainer = HttpContext.Current.Items["perRequestContainer"] as IUnityContainer;
var service = childContainer.Resolve<IServcie>();
I'm sure there must be a clean way to achive the same result, so please add suggestions.
Ok slight refinement to allow my unit test to inject a mock of the service.
1. remove the dependency resolve from the the OnActionexecuting and add two constructors.
public MyCustomActionfilter() : this(((IUnityContainer)HttpContext.Current.Items["perRequestContainer"].Resolve<IService>())
and
public MyCustomActionfilter(IService service)
{
this.service = service;
}
Now the constructor resolves your service and stores it as a private readonly. This can now be consumed in your OnActionExecutng function. Unit tests can now call the second constructor and inject a mock.

Resources