Custom DataAnnotations with RIA Services - data-annotations

This is a word of warning more than a question, if you are using RIAServices with Custom ValidatorAttributes.
Here is the Senario, I was creating a custom DataAnnotation that would validate a property based on whether or not a possible series of other properties had been set, such as; if Prop1 was 100 then Prop2, Prop3, or Prop4 could not be 0 one of them had to be set. I am also using RIA Services so I created the ValidatorAttribute my .shared.cs file. After writing all the tests for the helper CannotBeZeroIf class, I began to add the attributes to the Model Class. This is of course when thing started to go very wrong. RIA Services began to throw up during the CodeGen, with a NullReferenceException.
CreateRiaClientFilesTask -> NullReferenceException
It turns out to be linked to the fact that I was using the validator's constructor to pass in the values to the class. By switching to using ObjectInitialization syntax, everything was fixed.
The Answer appears to be use ObjectInitializer syntax when dealing with RIA Services and Custom DataAnnotation Validators.

The Answer appears to be use ObjectInitializer syntax when dealing with RIA Services and Custom DataAnnotation Validators (that was easier than I thought! ;-)

Related

Throwing exceptions in getters and setters

I was wondering what the best practice is for model validation when it comes to using getters and setters. Specifically, I have nullable fields in my model that, in some use cases, should not have null values when accessed. In those cases, I would like to throw an exception from the getter, but is that an accepted practice?
This could also be the case if I received a value in a setter that was not valid.
Alternatively from throwing exceptions, I'm aware of MVC attributes that you can use to decorate fields, but have not used them very much for model validation. In the "This value shouldn't be null in my getter" scenario, is there an appropriate attribute I could use?
Also, if throwing exceptions in getters and setters is accepted, is there a recommended exception to throw, i.e. ValueNotValidException (if that were real)?
If you are going to use the object as a ViewModel you can annotate it with a [NotNullValidator] given by the Microsoft's Enterprise Library, as well as a bunch of others that give extra functionality like Regex validation, ranges, IgnoreNulls, type, etc, as shown here. It is also possible using this library to create custom validators, based on this step-by-step guide, which you can use to annotate your ViewModel.
Otherwise you are left with the more traditional MVC Data Annotation Attributes, like [Required].
You should use the standard Data Validation Attributes to validate the model. If the value is required - use [Required].
http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
if (ModelState.IsValid)
{
...
}
Less code maintain and improved readability.

How do I resolve Dependency Injection in MVC Filter attributes

I have a custom attribute class derived from AuthorizationAttribute, which performs custom security on controller actions. The OnAuthorizationCore method depends on various other components (e.g. DAL) in order to ajudicate whether a user can invoke an action.
I'm using Autofac for dependency injection. The ExtensibleActionInvoker claims to be able to perform property injection on action filters. Setting an attribute's properties at runtime (which seems like a bad idea) will work in a simple unit test, but in a busy, multi-threaded web server it's bound to go wrong, and so this idea seems like an anti-pattern. Hence this question:
If my AuthorizationAttribute depends on other components in order to work correctly, what it the right [architecture] pattern in order to achieve this?
i.e. AuthorizationAttribute depends on IUserRepository... how should this relationship be resolved?
The ExtensibleActionInvoker claims to be able to perform property injection on action filters.
Correct - but don't confuse action filters with the attributes that might not implement them. The cleanest way to approach this in ASP.NET MVC is to split responsibilities, even though the MVC framework allows you to combine them.
E.g., use a pair of classes - an attribute class that holds data only:
// Just a regular old attribute with data values
class SomeAttribute : Attribute { ... }
And a filter that has dependencies injected:
// Gets dependencies injected
class SomeFilter : IActionFilter { ... }
SomeFilter just uses the typical approach of getting the SomeAttribute attribute from the controller or action method via GetCustomAttributes() to do whatever work is needed.
You can then use ExtensibleActionInvoker to wire up the filter:
builder.RegisterControllers(...).InjectActionInvoker();
builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
builder.RegisterType<SomeFilter>().As<IActionFilter>();
It might be a little more code than you'd write using the attribute-as-filter approach, but the quality of the code will be better in the long run (e.g. by avoiding the limitations of attributes and the awkwardness of the Service Locator solutions.)
I would seem that the easiest way to achieve this is to bite the bullet and accept a dependency on autofac itself. While a dependency on the IoC is in itself an anti-pattern, it's somewhat more pallatable. You can implement a property as follows:
public class UserAuthorizeAttribute : AuthorizeAttribute
{
public IUserRepository CurrentUserService
{
get
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
return cp.RequestLifetime.Resolve<IUserRepository>();
}
}
}
...
There's no straight-forward way to do this prior to MVC2. There is an interesting technique detailed here: http://www.mattlong.com.au/?p=154. I'd suggest using the Common Service Locator to abstract over this and locate your DI container.
If you're using MVC 3 then you can use MVC Service Location
Constructor injection seems to be impossible w/o changing way of filter registration.
Even in Asp.Net Mvc3:
One place where dependency injection has been difficult in the past is inside the filter attributes themselves. Because the .NET framework runtime is actually responsible for creating these attribute instances, we cannot use a traditional dependency injection strategy.
So - next best thing is property injection (Mvc3 provides some support for that out of the box).
Here's a how to for doing that manually.
I personally use MvcExtensions. I'm fine with registering them in different way. Here's usage.
Another thing You might want to investigate is MvcTurbine project. In contrast to MvcExtensions project which is more general - MvcTurbine is primarily for providing dependency injection support.

Grails internals : Auto mapping and Domain object creation

I am trying to make a taglib to represent an object (to read and display at the UI). When creating an object (save method in the controller), I see the domain class and association are created by the auto assignment of parameter
def Book = new Book(params)
It also maps complex types (for eg: joda time). I wonder about the naming convention necessary to facilitate this mapping. Out of curiosity, can someone also point where in the grails source code I could see how grails handles this mapping. I'm still learning Spring and probably this would be a good exercise.
Thanks,
Babu.
AFAIK the naming conventions are rather straightforward. If there's a field params.foo and the object you are binding to has a field foo, it will bind the value, assuming the type conversion works properly. If there's a params.bar.id set with an Long value and your object has a complex property of type Bar, it will lookup this instance and inject it.
If you need more control over the binding process, you might want to use bindData.
If you are interested into the details of the binding process, have a look at Java's PropertyEditor as this is what is being used in the background. I wrote a blog post on how to create and register PropertyEditors a while ago, maybe it helps you getting started with that stuff.

Finding target of LinFu proxy object

This is pretty much a duplicate question but instead of using Castle Dynamic Proxy I'm using LinFu Getting underlying type of a proxy object
I'm using automapper to create proxies of interfaces that I'm sending to my viewmodel in Asp.net MVC. My problem is from what I can tell that MVC's default MetadataProvider find the properties and metadata by calling .GetType() on the model.
So what happens is EditorFor() and DisplayFor() templates don't generate any fields. What I need to do is find the proxy target type and then generate my templates. I know I can just parse the name and use GetType( "thename" ) but was wondering if there was an easy way.
LinFu.DynamicProxy doesn't directly expose the underlying object of a proxy. It simply redirects each method call to an IInterceptor implementation instance. In order to access the underlying object, you'll have to figure out whether or not the current interceptor instance actually has a target class instance, or not.
If you're working with AutoMapper, AFAIK, they use LinFu.DynamicObject to do a lot of the duck taping, and calling GetType() on a dynamic type generated by LinFu.DynamicObject won't even get you the actual type in your domain model--it will just get you an object that has been literally duck-taped together by LinFu itself.
get latest AutoMapper - it uses Castle Dynamic Proxy, and you already know how to get this from there :)

Asp.Net MVC - Mapping Data Objects to View Model

Our current MVC project is set up to have ViewModels that encapsulate the data from the repository and pass it to the view.
When doing the mapping (In the controller) from Data Object to View model what is the best way to achieve this?
I've seen AutoMapper (http://www.codeplex.com/AutoMapper), but wondered if there was an out of the box solution?
AutoMapper seems to be the accepted (by many) solution.
And I would say, there's no such thing as "out of the box" solution in the MVC world - unlike in Ruby on Rails, for example. Framework is highly extensible but is very thin at the same time, so in lots of areas you have to invent your own "opinionated" way of doing things. Just an example of your situation, I personally have my view models:
Declare static ConfigureAutoMapper()
Have either optional Setup(realmodel) method or optional constructor
ViewModel(destinationViewModelType) is used on actions, and it performs conversion automatically - creating view model, calling Setup or Constructor, or invoking AutoMapper
ViewModel maps are created with predefined ConstructUsing that uses IoC container to instantiate so that view models gets their IoC dependencies if needed
None of the above exist in MVC out of the box. I'd say that MVC only supports ViewData-like usage "out of the box".

Resources