custom software development to help your business take flight™

Little "f" famous

Posted by Joe Wilson on Saturday, September 19, 2009 2:53 PM

I was proud when I got married, when my kids were born, and when I accomplished stuff in my career.

But this may be the topper.  My submission to the "blog" of "unnecessary" quotation marks was posted!

It's good to be famous, even if it's little "f" famous.

Tags:
Categories: General


kick it on DotNetKicks.com shout it on DotNetShoutOut

Validation frameworks in ASP.NET MVC

Posted by Joe Wilson on Tuesday, September 15, 2009 9:09 PM

There are plenty of validation frameworks out there.  I've worked with NHibernate Validators, Microsoft's Enterprise Application Blocks, and now Data Annotations.  They primarily work by adding attributes to the properties in the class you want to validate. 

How are they different?

Not very.  The biggest difference between them is their syntax.  I guess the Validation Blocks from Microsoft's P&P group have a lot of configuration options, but I haven't needed that on a project.  The most prominent differences are in the attributes themselves.

You can probably make a case for Data Annotations having a slight advantage since it's going to be in the .NET base-class libraries.  Easier to deal with assemblies installed in the GAC instead of the ones you have to drag around for each deployment.

How do you integrate them with MVC?

Each of these frameworks can be integrated with ASP.NET MVC.  But the best validation call is one you don't have to explicitly make.  Huh?

It's OK to call MyClass.IsValid() in a controller action, but if you can avoid it, I think you're better off.  Otherwise, what happens if you forget to call it?

Instead, use a model binder that invokes the validation framework for you.  This is how I am using the Data Annotations model binder with the MVC framework:

ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();

Now this guy will intercept calls to your controller actions and reject invalid incoming view models.  Here is a simple tutorial for using Data Annotations that goes into more detail.

How do you lay this out in the solution?

I have an Application Services layer that my MVC layer calls into.  My controllers have constructors with an interface to an application service injected into them.  My IoC container decides which concrete version of this application service interface to use at runtime.

Next, my Application Service layer has a DTO folder that holds all the DTOs (property-only classes) my views need in my MVC app.  These are not my domain entities.  There might be a lot of overlap with those domain entities, but these DTOs are just there for communication between the UI layer and Application Services layer.  These DTOs are where I put my validation attributes.

So now I've got views that are tightly bound to the DTOs, which are owned in the Application Services layer.  This allows strong typing of the view so I can use the DTO's properties as my view's model.  This is handy for the Html Helpers to get design-time IntelliSense and compile-time checking.

What else can you do?

I haven't spent a lot of time looking into it, but xVal looks pretty strong for client side AND server side validation using Data Annotations and a couple other validation frameworks.  It also lets you validate your business rules in your domain and throw an exception.  I need to check into this more, because that sounds like the validation holy grail for validation to me: getting UI validation and business rule validation into a common format.

Tags: , , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Where should validation go?

Posted by Joe Wilson on Monday, September 14, 2009 10:06 PM

<groan>Not this argument again!</groan>

The short answer: I don't know.

The long answer: Yeah, I really don't know.

There is still no widely accepted answer on this one.  Reasonable people disagree.  One camp pushes it up closer to the UI, the other down lower so it shelters the domain from invalid states.  Some like it sprinkled across layers; some like it centralized.

I think Steve Sanderson is correct that validation falls on a continuum from easy UI validation, like required fields, to complex business rules that need to be checked closer to or in the domain entities.

I also think Jimmy Bogard is correct that context matters when it comes to validation.  This object is valid for what?  Saving to the database?  Emailing to sales?  Displaying on the screen?  The validation rules depend on the the behavior you are validating.

These days, I think of validation as either UI Validation (required fields, min/max length, etc.), Domain Validation (start date/time must be before end date/time, order must have at least one item, etc.), or Database Validation (is this value unique, is this ID value going to throw a foreign key violation).  This is based on when you can validate in the call chain more than what it's valid for.  I still like validation in context, but those business rules end up in my Domain Validation logic with method names like CanSendEmailToCustomer().

Sharp Architecture uses NHibernate Validators as attributes on the domain entities.  The best thing about this is your validation is centralized.  It's sitting right there in your domain, and you know where to go if there is a rule change.

The other good thing about this approach is your entity should always be valid when saved.  The built-in Repository<TEntity> calls in Sharp Architecture enforce validation before inserts and updates, so you're covered there.  If you want to call MyEntity.IsValid() in a method, you can do that as well.

The bad thing is those validation attributes can start looking like UI concerns when they have user-centric error messages in them ("Hey, user, that's not a valid format for a phone number").  And if there is a rule that doesn't lend itself to attributes (e.g., orders must have at least one order item), you are on your own.

I started with validation attributes on my domain entities, and when my attribute messages got too UI-looking, I moved to using Data Annotations on DTOs in my application service layer for UI validation.  The DTOs are made to be client facing, so I'm not bothered by user-specific messages in them. 

Then when Domain or Database Validation problems come up, a ValidationException is thrown up through the application service to the UI so the calling app can either display or handle it.  I haven't played with it yet, but I think this is what xVal is doing, too.

The more I think about it, the more I see my web app as just another client calling into my application service layer which is encapsulating my domain.  So my web app is the "user" and the message needs to be just enough for that user, not necessarily the end user.  Maybe a validation exception token is sent out from the application service layer to the UI, and the UI translates that to a string from a very UI-centric resource file?

Bu I'm still not happy with this.  I feel like I have the right kind of validation in the right places, but I would still like a more centralized approach for easier refactoring of business rules.  I've used the Specification Pattern before, and it does a great job of centralizing the rules.  But making yet another class for yet another required field and adding it to yet another Composite Specification?  Seems like your walking away from a lot of the productivity attributes can give you.

Obviously, my thoughts on validation are still not fully formed.  I'm still arguing with myself.  My dream validation would be:

  • centralized for easy refactoring and rule changes
  • automatically called for routine things so I don't forget (like saving the order to the database)
  • allow ad hoc calls for non-routine things (like validating the order confirmation email can be sent to the customer)
  • handle simple validation like attributes so I can be productive
  • handle complex validation like specifications so I'm not limited
  • UI-agnostic so the centralized validation goo isn't holding end-user strings, except when I'm too lazy to set up the resource file, in which case strings can be passed up from this layer

I told you I didn't know! :>

Tags: , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Review of Sharp Architecture

Posted by Joe Wilson on Monday, September 14, 2009 8:40 PM

I've been using the open-source project Sharp Architecture for about 6 months now, and version 1.0 was recently released.  It's a really great way to get rolling quickly on a project using ASP.NET MVC, Domain Driven Design (DDD), NHibernate, and Castle Windsor.

I won't go into the details about what Sharp Architecture does.  I'll just cover what I like in the first version and what I hope makes it into future releases.

What I like

Decoupled Design

The Sharp Architecture framework uses inversion of control right out of the box with Castle Windsor and the Common Service Locator wrapping container calls.  The MyProject.Core assembly holds your domain model and interfaces to your repositories.  Implementations of those repositories are in MyProject.Data. 

There is also a MyProject.ApplicationServices assembly for times when your controller logic starts to look heavier than it should or you prefer to push all your logic into an application layer so you can skim off the MVC UI for something else at some point (Silverlight?  WCF?).  I like this approach with very lightweight controllers and views for just this reason.

NHibernate Training Wheels

Billy McCafferty, the principal author on the project, is one of the gurus on NHibernate best practices.  NHibernate is very powerful, but some tools, like Fluent NHibernate, which uses C# code to map your domain to your database instead of XML, are.well.kind of fluid.and still under construction.

I'm still new to NHibernate and very new to Fluent NHibernate, so I get tripped up often.  It's nice to know that my solution is using best practices for tools where my footing is not as sure, like NHibernate session management.

Templates + Conventions

The Visual Studio solution and T4 templates inside Sharp Architecture are the things that makes it different from being just another reference implementation or architecture guidance.  You can get a new, empty Sharp Architecture solution going in about 30 seconds with the Visual Studio solution template.  The T4 templates help you add controllers and views built around conventions and the property names in your domain entity.

I used to be a big fan of code generation.  It's nice to spit out a bunch of classes very quickly, but there really has to be a balance.  If it gens too much code, is it all stuff you really need?  If it only gens a little bit, did you need a code generator at all?

Sharp Architecture does a good job of giving you a jump start on stuff you will probably want or at least a place-holder for stuff you will want.  It doesn't litter the solution with too much junk.

For instance, it doesn't generate a repository for your domain entity because you can use use the IRepository<MyDomainEntity> and Repository<MyDomainEntity> in the Sharp Architecture assemblies.  It doesn't generate NHibernate mappings for your domain entity because the mapping conventions cover most cases.  If you do need additional repository methods or have unconventional database mappings, it's easy to inherit from and override these.  Sharp Architecture uses generics, base classes, and conventions to keep from needing a lot of code generation.

Documentation, Sample Code, Wiki, and Forum Support

This project is much better documented than most open-source projects.  In addition to the "getting started" and 'using the framework" documents, there is a sample Northwind project that comes with the download files.  Online, there is a wiki and a Google Group that is actively monitored if you need additional help.

I know real programmers only use Reflector for documentation.  :>  But don't underestimate the value of documentation for widespread adoption.  You can have a great open source project that doesn't get very far if people don't know how to get up and running quickly and fully exploit the framework.  That won't be a problem for Sharp Architecture.

Helpers

Sharp Architecture libraries are chock full of all kinds of convenience methods and helpers.  Want to write a database integration test using SQLite?  Just have your test class inherit from RepositoryTestsBase().  Want to hit the live database?  Inherit from DatabaseRepositoryTestsBase().  Want to design by contract and check incoming parameters and return values easily?  Look into the Check.Require() and Check.Ensure().

There are a ton of things like this that all of us have written before.  Most developers I know walk around with a couple assemblies to make coding their next project easier.  With Sharp Architecture, these are referenced in your solution right after File > New Project.

Folder Structure

Everyone has their own preferred solution and folder structure.  The default project and folder organization in a new Sharp Architecture solution is pretty close to what I was already using and is simple for any developer to jump in and follow along.

This may not seem like a big deal because a good structure looks obvious in hindsight, but it's nice to not have to dig around for things.  I've worked on solutions that have 20+ projects.  Sharp Architecture goes the other way and you end up with about four projects in a normal MVC app.

What I would like to see in future releases

I don't have any strong objections to the design choices in Sharp Architecture.  Most of the things here are more a matter of style/taste than anything.

Controllers back in MyProject.Web project

You can read Billy's view on putting the controllers in the web project. His main point is that controllers should be written and tested independent of the other assemblies so you don't succumb to temptation and do things like go straight to your repository from your controller instead of asking your IoC tool to give you the concrete repository instance.

That's fair.  But my controllers don't do much besides call into my application services layer, render views, and redirect to other controller actions. I don't mind having a reference to the entire web project in my unit test project so I can test routes and the very little logic I have in my controllers.

In his article, Billy describes the pain of having done it the way I prefer.  Maybe this is one of those lessons where you have to experience it yourself to internalize it.  Like my dad telling me the stove was hot when I was a kid. :>

MyProject.Infrastructure instead of MyProject.Data

Maybe I've looked at Code Camp Server or listened to Jeffery Palermo talk too much, but I lump data handling into a larger category of infrastructure concerns.  Sharp Architecture's solution template gives you MyProject.Data, which holds the NHibernate mappings and conventions and the repository classes. 

But I have other utility/infrastructure things I need to put somewhere, like logging, emailing, etc.  I prefer having MyProject.Infrastructure with Data as a folder underneath it so I can throw all my infrastructure implementation code into that assembly.  The interfaces for these guys still go in MyProject.Core, just like the repository interfaces.

More emphasis on MyProject.ApplicationServices

I prefer to have as little logic as possible in my views and controllers.  I push as much as I can to an application layer so the UI can be replaced or added to with minimal impact.  In Sharp Architecture, you've got MyProject.ApplicationServices for exactly that.  There is one Northwind example that uses this layer, but in the other samples, the controllers are doing the application flow work.

I think it's better to have an application service passed into the controller's constructor so the controller doesn't need to know much except routing, views, redirects, the app service method to call, etc.  I don't mind having these UI logic concerns in the controller, but anything beyond that needs to be in an application layer.

I've borrowed a metaphor from the SQL Server installer that talk about "surface area".  I think of the MyProject.ApplicationServices layer as a wrapper around all the app logic.  The methods in this layer are the surface area of my application, and they encapsulates all the implementation code my domain is dealing with.  Calls into this layer can kick off multi-step processes, handle workflow, and usually have long, explicit method names.  But this is the only part of my domain's surface area that is exposed externally.

The MVC web project is one client calling into this application layer, but there may be others someday on even medium-sized projects.  If your app becomes more popular and you've followed this approach, you can add other clients that call into your application service layer like a WCF service, a system tray tool, etc.  These guys may have their own specialized methods or may use something the web application was using.  Either way, you are very intentional on the surface area you expose.

I think Sharp Architecture gets this right.  I would just like to give it a little nudge to make it a point of emphasis.

Conclusion

I've used a lot of different frameworks, but Sharp Architecture comes closest to the way I want to work already.  The templates and documentation put it well beyond a reference implementation, and you can work with a simplified solution sitting on top of a lot of abstracted complexity to get you productive right away.

Tags: , , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Which IoC container should I use?

Posted by Joe Wilson on Thursday, September 10, 2009 12:07 PM

This came up on the Alt.Net Yahoo Group/mailing list today.  There are tons of tools out there for inversion of control.  They have been compared here and other places online.  Nobody wants their app tied to the Betamax of IoC tools, so people are anxious to pick the best one.

All containers keep a hash table of your interfaces mapped to your concrete classes.  Most will let you request a specific instance with a string token.  Most will let you control instance creation (singleton, etc.).  The popular IoC containers have fluent configuration and use conventions to figure out that IEmailService maps to EmailService.

So which one should you pick?  Go with the one you already know best and/or the one that is easiest for your dev team to configure.  That's because with the Common Service Locator wrapping your IoC get instance calls, the provider becomes a moot point. 

This is an old OO principal - encapsulate the stuff that can change.  Jeremy Miller pointed out the need for a common IoC wrapper to do just this.  Today's hot new open source IoC container could be tomorrow's dormant project.  If you wrap the calls, you can rip out your IoC provider and most of your code stays the same since it's calling the wrapper.

Here's how I'm doing this using Castle Windsor in a Sharp Architecture project.  First, I create a class to wire up my IoC configurations for my app. 

public static class RegisterIoCContainer
{
    public static void AddComponentsTo(IWindsorContainer container)
    {
        AddApplicationConcernsTo(container);
        AddCoreConcernsTo(container);
    }

    private static void AddApplicationConcernsTo(IWindsorContainer container)
    {
        container.Register(Component
            .For<IMappingEngine>
            .Instance(Mapper.Engine)
            .LifeStyle.Singleton);

        container.Register(AllTypes.Pick()
            .FromAssemblyNamed("MyApp.ApplicationServices")
            .WithService.FirstInterface()
            .Configure(c => c.LifeStyle.Transient));
    }

    private static void AddCoreConcernsTo(IWindsorContainer container)
    {
        container.Register(AllTypes.Pick()
            .FromAssemblyNamed("MyApp.Infrastructure")
            .WithService.FirstNonGenericCoreInterface("MyApp.Core")
            .Configure(c => c.LifeStyle.Transient));
    }
}

Note the use of convention-based mappings between assemblies and the different instance lifestyles.  Mapper.Engine has a Singleton lifestyle.  Not that there's anything wrong with that. :>

Next, I create a class to tell Common Service Locator to use Castle Windsor as the provider and to load up those IoC configurations:

    public static class RegisterServiceLocator
    {
        public static void Register()
        {
            var container = new WindsorContainer();

            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));

            RegisterIoCContainer.AddComponentsTo(container);
        }
    }

Then I call RegisterServiceLocator.Register() on Application_Start() in the Global.asax.  From then on, I can call the Common Service Locator to get my instance from my interface:

var instance = ServiceLocator.Current.GetInstance<IEmailService>();

I don't often need to use this syntax, since I'm usually pushing external dependencies into a constructor and letting auto-wiring resolve the dependency chain for me.  But I do use this syntax for testing that Common Service Locator is finding the instance I want.

Tags: , ,
Categories: Technical


kick it on DotNetKicks.com shout it on DotNetShoutOut

Image Details