ChameleonForms 1.0 Released

I’m incredibly excited and proud to finally announce the release of 1.0 of the ChameleonForms library I’ve been working on with Matt Davies. My blog has been fairly quiet the last couple of months while I’ve poured time and energy in finally getting ChameleonForms to 1.0.

WOOOOOOOOOOOOOOOO

(Apologies; I’m releasing months of built-up anticipation and excitement here).

I’m biased of course, but I think this library is amazing to use and results in immensely more maintainable form generation code when using ASP.NET MVC. It extends on the knowledge that MVC developers would have in generating forms using the (already pretty awesome) built-in stuff, but adds the things I think are missing. For me, this library epitomises over 7 years of exploration in the best way to do web-based forms and I’m excited to be able to share the beginnings of my current vision via this library.

What is ChameleonForms?

In short, ChameleonForms takes away the pain and repetition of building forms with ASP.NET MVC by following a philosophy of:

  • Model-driven defaults (e.g. enum is drop-down, [DataType(DataType.Password)] is password textbox)
  • DRY up your forms – your forms will be quicker to write and easier to maintain and you won’t get stuck writing the same form boilerplate markup form after form after form
  • Consistent – consistency of the API and form structure within your forms and consistency across all forms in your site via templating
  • Declarative syntax – specify how the form is structured rather than worrying about the boilerplate HTML markup of the form; this has the same beneficial effect as separating HTML markup and CSS
  • Beautiful, terse, fluent APIs – it’s a pleasure to read and write the code
  • Extensible and flexible core – you can extend or completely change anything you want at any layer of ChameleonForms and you can drop out to plain HTML at any point in your form for those moments where pre-prepared field types and templates just don’t cut it

More info.

What are the big improvements in 1.0?

We’ve been releasing pretty often so that depends on what version you are currently using, but these are the most important things:

  • Extensive usage across a number of production websites – we are happy that this library is mature, stable and ready for prime-time
  • Twitter Bootstrap 3 Template out-of-the-box supported by a NuGet package to get you up and running faster – this is HUGE for a number of reasons:
    • Bootstrap is pretty darn popular right now so this is immediately useful to a lot of people
    • In creating this template we had to do some pretty sophisticated changes to allow the template to drive a lot of changes unobtrusively to the form structure you are adding in your views – this is great because it means it’s really easy for you to create your own form templates and accomplish similarly complex transformations of your form markup
    • The ASP.NET MVC templates that come with Visual Studio 2013 come with Bootstrap by default now – and boy do they have gross repetitive boilerplate in them, which you can clean right up using this library
    • The vision that we have for this library is coming to fruition, which is personally gratifying – this is a beautiful demonstration of being able to declaratively specify the structure of your form and then completely change the markup/template of your form across a whole application with a single line of code when it changes
  • Really comprehensive documentation of everything in the library – we’ve spent many hours writing up the documentation – the idea was to make it comprehensive, but accessible/terse; hopefully we’ve met that goal!
  • Really solid code coverage to help prevent regressions or breaking changes as well as some refactorings that give us a solid codebase to continue with the other features we want to add – hopefully this can support us into the future with minimal breaking changes

How can I get it?

Checkout the GitHub release or go to NuGet.

Versioning

From this point on we are following semver thanks to the GitHubFlowVersion project. The fourth number in the NuGet version number is actually build metadata.

Borderlands 2 here I come!

Over a year ago now (yes it’s been a long journey – our first NuGet package was published on November 1, 2012) Matt Davies and I made an agreement to each other that neither of us would play the recently released Borderlands 2 game (we were both huge fans of Borderlands so this was a big deal) until we released 1.0 of ChameleonForms so that we would remain focussed on it and not get distracted. Now, while we both didn’t realise that it would take this long and while the last couple of months have seemed like forever (I’m pretty sure we had a phone conversation at least once a week where one of us would say “dude, we are sooooo close to 1.0 and BORDERLANDS 2!”) we are both incredibly proud of the library and are happy with what we’ve managed to get into 1.0.

Needless to say, we will probably be taking a break from open source for a few weekends to play Borderlands 2 🙂

We hope you enjoy using the library!

As usual hit us up with issues and pull requests on GitHub – they make our day 🙂

Resolving request-scoped objects into a singleton with Autofac

This week I had an issue raised on my Github site for examples of unobtrusive validation with ASP.NET MVC. The person that raised the issue was having a problem where they wanted their fluent validation modules to be singleton, but they wanted to inject a factory that can be invoked to return a request-scoped object (in this case some sort of database store). Inevitably they came across the “No scope with a Tag matching ‘AutofacWebRequest’ is visible from the scope in which the instance was requested” error.

I’ve blogged previously about a technique for using DependencyResolver.Current and being able to unit test it for similar situations. It’s not a great solution, but it does work and at least it can be unit tested.

Low and behold though, thanks to the power of the Internet, the person that raised the issue asked a question on StackOverflow and got a really elegant solution for how to inject factories in a singleton that will correctly resolve request-scoped objects. I’m pretty excited about it so I thought I’d give it more exposure by doing this blog post.

This is the technique in all it’s glory (I’ve renamed the method name slightly to make it more readable):

public Func<T> HttpRequestScopedFactoryFor<T>()
{
    return () => DependencyResolver.Current.GetService<T>();
}

...

builder.RegisterType<SomeRequestScopedComponent>().As<ISomeRequestScopedComponent>().InstancePerHttpRequest();
builder.RegisterInstance(HttpRequestScopedFactoryFor<ISomeRequestScopedComponent>()); // this is the magic bit

This will then allow you to do something like this:

builder.RegisterType<SomeSingletonType>().As<ISomeSingletonType>().SingleInstance();

...

public class SomeSingletonType
{
    private readonly Func<ISomeRequestScopedComponent> _someRequestScopedComponentFactory;

    public SomeSingletonType(Func<ISomeRequestScopedComponent> someRequestScopedComponentFactory())
    {
        _someRequestScopedComponentFactory = someRequestScopedComponentFactory;
    }

    public void SomeMethod() {
        var requestScopedComponent = _requestScopedComponentFactory();
        ...
    }
}

Nice and even easier to unit test than using DependencyResolver.Current directly!

Big thanks to @thardy and @felix.

Unobtrusive Validation in ASP.NET MVC 3 and 4

Most things that can be done to reduce the amount of code that you need to write to get the same outcome (keeping in mind that you still need code to be easily readable/understandable for maintainability reasons) is great. The less code you have the less change of a bug, the less code to maintain, the less code that needs to be modified to add a new feature and the easier (hopefully) the overall solution is to understand.

In particular, if plumbing code that doesn’t actually serve any purpose other than to join the useful bits of code can be negated then that will usually significantly increase readability and maintainability of code. It’s also this sort of boring, monotonous code that often contains little errors that get missed because of the blight of CPDD (copy-paste-driven-development) where you copy a few lines of code, plonk them somewhere else and then change a couple of the class names or magic strings around. Inevitably you will miss one of two of the references and this is often combined with the fact that this type of code is likely not tested (depending on how strict your testing regime is).

Thus, one of the things that my team and I have put energy into over the last year and a half while we progress on our ASP.NET MVC journey is how to reduce this type of code. The first technique that springs to mind to combat this type of plumbing code is convention over configuration and to that end we have come up with unobtrusive techniques for model binding and validation that make heavy use of our dependency injection framework (Autofac). While the techniques I’ll demonstrate make use of Autofac, I imagine similar techniques can be used for the other frameworks.

Example code

This post is accompanied by some example code.

Data type validation

The DefaultModelBinder class that comes with MVC is pretty magical; it managed to parse the various values from the various scopes submitted with a request e.g. get and post values, etc. by name to your (potentially nested)  view model by name and pops any validation errors that it encounters in the Model State for you. Then a simple call to ModelState.IsValid in your controller will tell you if the view model was ok! This includes things like putting your data type as int and checking the input the user submitted was an integer and the same for any primitive types or enumerations! Furthermore, any custom types you define can have validation logic associated with them that will get automatically triggered (see my blog post for an example; look at the code for the custom type).

Thus, if you are taking user input in a controller action you will likely want code like this:

        public ActionResult SomeAction(SomeViewModel vm)
        {
            if (!ModelState.IsValid)
                return View(vm);

            // todo: Perform the action
        }

System.ComponentModel.DataAnnotations

By default in MVC you are given a number of unobtrusive validation options from the System.ComponentModel.DataAnnotations namespace, you can see the list of classes included on MSDN, but here is a quick rundown of the notable ones:

  • [DataType(DataType.Something)] – by default doesn’t actually perform any (server-side) validation, although you can use this to perform custom validation. It’s mostly used to provide metadata for UI controls to affect the display of the data. This is one of the confusing things about the DataAnnotations namespace – you would reasonably expect that this attribute would perform validation on first inspection!
  • [Display(“Label text”)] – Override the label text, although if you use this for every field because the default display of the field name when there is multiple words in camel case is ugly then you might want to define a custom metadata provider instead.
  • [Range(min, max)] – Specify a numerical range
  • [RegularExpression(regex)] – Specify a regex the data has to conform to
  • [Required] – enough said, although one thing to note is that non-nullable types like int, double etc. are implicitly required so the omission (or inclusion) of this attribute will have no effect. If you want to have an int that isn’t required make the type int? (or Nullable<int> if you like typing).
  • [StringLength(MinimumLength = minLength, MaximumLength = maxLength)] – Specify a min and/or max character length for a string

It should be noted that you are given the option of overriding the default error message for any of these attributes.

Data Annotations Extensions

The default set of unobtrusive data validation annotations can be extended with a much more useful set of validations via the Data Annotations Extensions project, which includes server- and client-side validation for:

  • Credit cards
  • Dates
  • Digits
  • Emails
  • Cross-property equality
  • File extensions
  • Digits and other numerical validations
  • Urls
  • Years

It’s pretty easy to get up and running with them too via NuGet:

Install-Package DataAnnotationsExtensions.MVC3

Custom Validation

Sometimes simply validating that the data type and format of your view model properties just isn’t enough, what if you want to validate that a URL returns a 200 OK, or that the username the user provided isn’t already in your database?

In this instance we need to turn to performing custom validation. There are a number of ways this could be done:

  1. Put custom validation code directly in your controller after checking ModelState.IsValid
    • Tedious and awful separation of concerns, plus we will still need to use model state (if you want errors to propagate to the UI via Html.ValidationMessageFor(…) or similar) and thus have a second call to check ModelState.IsValid
  2. Wrap the custom validation code into a helper or extension method and calling it from the controller after checking ModelState
    • More reusable if you use the view model multiple times and makes the controller action easier to test and understand, still tedious though
  3. Use one of the custom validation approaches to call the validation code
    • Even better separation of concerns since the model errors will now appear in model state when the controller action is called, but still reasonably tedious
  4. Use a validation library to take away the tedium (my favourite is Fluent Validation)
    • Getting there, but the amount of code to write increased :(…
  5. Use an MVC ModelValidatorProvider and reflection to unobtrusively apply the validation using the default model binder without having to implement IValidatableObject for every view model
    • Almost there, we still have to statically call DependencyResolver.Current to get any database repositories or similar, which is painful to test
    • In my case I’m using the MVC integration that the FluentValidation library provides to automatically pick up the correct validator, but you could obviously write your own ModelValidatorProvider, for this to work it simply requires that you add the [Validator(typeof(ValidatorClass)] attribute on your view models
  6. Integrate with your DI framework to inject dependencies to the unobtrusively called validator
    • Perfect!
    • Props to my Senior Developer Matthew Davies for coming up with this technique

I’ve ordered the list above in pretty much the order of approaches that we went through to get to where we are now. I’ve included a comparison of the different approaches in the Github repo for this blog post. Note that I’ve bundled all the code for each approach into a region when in reality the validation classes should be separated, but it makes it easier to compare the different approaches this way.

I should note that there is another approach I neglected to mention, which is to create a custom model binder for the view model and to perform the validation and setting of model state in there rather than the controller. While this is a better separation of concerns than putting the code in the controller, it still leaves a lot to be desired and can be quite tedious. On occasion, when you actually need to use custom model binding (e.g. not just for validation) it can become important to put errors in the model state though.

Conclusions

Now, the example code I’ve written doesn’t really give a good indication of the advantages of the final solution (that I recommend). This is mainly because I was only performing a single view model validation on a single property of that validation – the more custom validation you have the more the unobtrusive solution shines. It’s also worth noting that your test code will become significantly less complex for each example I gave though as well. Another consideration is that the unobtrusive code, while it means you have to write less code all up does hide away a lot of what is happening in “magic”. For someone new to the solution this could pose a problem and make the solution hard to understand and for this reason if you are using this approach I recommend it forms a part of the (brief) documentation of your solution that supplements the code and tests.

At the end of the day, you should take a pragmatic approach, if all you need is one or two really simple validations then you probably don’t need to put in the code for the unobtrusive validation and at that point the unobtrusive validation will probably complicate rather than simplify your solution. If you are lucky enough to have some sort of base libraries that you use across projects and you have a consistent team that are familiar with it’s use then it makes sense to abstract away the unobtrusive validation code so that you can simply be up and running with it straight away for all projects.

Data type validation in ASP.NET MVC 3

This post outlines some experimentation that was conducted to find the different approaches that can be taken to perform data type validation in ASP.NET MVC 3 (when binding a view model).

I did some work on this over a year ago with Miguel Madero when he was doing some consulting work with my team. Frankly, I’m confused that I can’t find a post on my blog about it because I swear that I did one.

Regardless, this one is a fairly easy post to write because it’s basically easier said in code. As such I’ll direct you to the Github repository we created and put a small explanation below.

What do I mean by data type validation?

I mean validating the semantic form of the data – e.g. is it an integer number, is it an email address, is it one of a number of enumeration values? etc. I don’t mean validating the format of the data or the metadata or properties of the data – e.g. does it have a length greater than x characters, is it smaller than number y, does it conform to a given regular expression, is it the same as another property in the view model?

I realise that the line between data type and data format can be blurred, particularly when it comes to strings, so another way to put it is that I’m referring to the primary validation you will perform before being able to assign the data to the given property in the view model. Then on top of that you might want to perform other validations.

What are the ways that you can perform this validation in ASP.NET MVC?

We found three ways, feel free to post a comment if you discover any other ways and I’ll be happy to include that in the Github repo (or even better send me a pull request):

  • Custom validation attributes; e.g.
    [Digits]
    public string DigitsWithCustomAttribute { get; set; }
    
  • Custom Data Type attribute; e.g.
    [DataType("Digits")]
    public string DigitsWithDataTypeAttribute { get; set; }
    
  • Custom type; e.g.
    public Digits DigitsAsCustomType { get; set; }

Motivation and findings

The reason why we did this was because at the time the documentation for how to perform custom data type validation (outside of the build-in validation MVC provides) was confusing and lacking. It may have improved since then though…

At the end of the day, the easiest to implement was the custom validation attribute, but the nicest and tersest end result was from the most complex to implement in the custom type. I should note that one of the cool things (that all three methods supported) is that you can pass metadata to the JavaScript for client-side validation (you will have to write JavaScript validation code as well though for anything that jQuery Validate doesn’t support out of the box). The way that Microsoft have implemented this through their unobtrusive client validation code is pretty clever and well thought out :).

The readme file for the Github repository explains where to look to find the relevant code.

Enjoy!