Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 96,595 hits
  • Meta

Archive for the ‘ASP.NET MVC’ Category

Using StructureMap to Configure Applications and Components

Posted by coreycoogan on May 24, 2010


By now it’s probably a pretty safe assumption that any developer who’s worth their salt has at least heard of Inversion of Control (IoC) or Dependency Injection (DI), if not used it at least once. IoC as an architectural concept has many benefits, including testability and helping with Open/Closed Principle compliance. The specifics of DI have been discussed many times over, so consult your friendly neighborhood Google for more on the topic. What I’d like to talk about is the tooling that helps developers achieve IoC in their own systems. The tool is known as a Container and there are many good options to choose from in the .NET space. Top picks include Castle, StructureMap (SM), AutoFac, Ninject and even the very sad entry from Microsoft – Unity.

Why StructureMap?

I’ve had to use Unity at a current gig because it was approved and didn’t require .NET 3.5, but I’ll say right off that Unity is a very simple Container that lacks the features that make working with a Container fun. Granted, we’re using version 1.1, so I can’t speak to some of the enhancements found in 2.0.

I’ve blogged about Castle in the past, which I was using because it came standard in the S#arpArchitecture. Castle is a very good Container, but it has its downfalls. The biggest, in my opinion, is that its fluency is not very intuitive. Despite how many times I’ve used it, I can’t configure an application without looking at a previous example. It just doesn’t seem to flow and feels a bit clunky. It’s still a great tool, so I don’t want to take anything away from all the hard work that has gone into it.

Then there’s StructureMap. What can I say – SM rocks and I actually have fun using it. The fluent DSL flows easily and it is capable of doing everything I’ve ever really wanted it to. Some of my favorite, and most used features, include the default convention, the ease of adding custom conventions, registering open generics and showing what’s been configured. If you haven’t worked with it, have a look and play around with it. Like anything, it will take a bit to learn the ins and outs, but after that it’s pure joy. (NOTE: some of the doc I’m linking to is a bit out of date – the only downside to SM, however, there is plenty on CodeBetter)

Define Components

It is common practice to break different layers into separate components/assemblies/VisualStudio.Net Projects, such as Core, Data, Infrastructure, etc. It is also very common to have components shared throughout the enterprise, such as Inventory, SalesProcessing, Products, etc. This is what I’m referring to as components. Since each component may have its own unique DI requirements, configuring applications to initialize each of those components, as well as itself, can become challenging and when done incorrectly can make applications brittle.

Configuring the Application

The application, in the context of this post, refers to the actual executable – web site, Windows Form, WPF, Console, Windows Service, WCF. When using an IoC Container, the application should always have the responsibility of configuring and initializing the Container. It’s not uncommon to see some developers configuring a Container at the component level because that’s where the knowledge of the component’s dependencies exists. How would the application know about special conventions or nuances that the Container should be handling? The problem with this is the case where the application wants to leverage the Container and swap out one dependency for another.

Equally as painful is the practice of configuring all the components directly from the application. Once a developer gets everything working, the configuration is typically copied/pasted to other applications that use the same components. Now when something changes, someone has the joy of [hopefully] finding all the occurrences of the code in question and pasting a new version on top of it.

Configuring Components

So we don’t want the components to configure themselves in the Container and we don’t want to copy/paste the component configuration in all the consuming applications. How do we do it then? Well I’m glad you asked. The answer is found in StructureMap’s Registry facility.

A Registry in SM is a custom class, derived from the StructureMap.Configuration.DSL.Registry class. This is where the nuts and bolts of an SM configuration should exist. A component can have one or more registries, broken down into any sized unit that makes sense. Maybe the Inventory application has a registry for some common domain services and another for specific communication mechanisms that may vary depending on the type of application.

Here’s an example of a simple component Registry that has a couple specific needs and then relies on scanning and default conventions for the rest.


public class ProfileRegistry : Registry
{
	public ProfileRegistry()
	{
	    ForSingletonOf<IProfileValidator>()
		.Use<ProfileValidator>();

	    Scan(scanner =>
		     {
			 scanner.AssemblyContainingType<IProfileRepository>();

			 //use the default convention
			 scanner.WithDefaultConventions();

		     });
	}
}

Initializing the Application

Now that our components have their own default configurations broken into one or more Registry classes, we need to get that into our Container. As previously mentioned, it is the responsibility of the application to configure and initialize the Container. This is something we generally want to happen only once. This can be accomplished by putting the code to handle the initialization of SM, NHibernate, Logging, whatever, in a BootStrapper that gets called at the application’s entry point. This can be the Global.Application_Start in a web application or inside the Program class of a console or WinForm application.

Initializing Component Registries

So how does the BootStrapper initialize SM with each component registry? With StructureMap, there are actually three common techniques.

By Type

This technique is pretty straight forward and probably suits the majority of cases. In this example, we know what the Registries are and simply add them by type to SM’s configuration during initialization.


public static class Bootstrapper
{
	public static void Initialize()
	{

		ObjectFactory.Initialize(cfg =>
		{
		    cfg.AddRegistry<ProfileRegistry>();
		});

	}
}

By Instance

SM also offers the ability to add a registry to the SM configuration as an instance. This comes in very handy when you have a Registry that requires an instance of some type for its own configuration.

A real-life example of this is when using an NHibernate Session/Call pattern in a StructureMap enabled WCF service (details available in this post). In this case, I want the Wcf.NHibernate registry to tell SM how it should resolve an ISession. In order for this to happen, the Registry will need an initialized ISessionFactory instance, which will be passed to it by the application’s BootStrapper. Once the registry is instantiated, just add it to the SM’s configuration.


public static class Bootstrapper
{
	public static void Initialize()
	{
		ObjectFactory.Initialize(cfg =>
		{
		    cfg.AddRegistry<ProfileRegistry>();

			//get the sessionfactory from another method
		    ISessionFactory sessionFactory = InitFactory();

		    //create the WCF NH Registry
		    var nhWcfRegistry = new WcfNHibernateRegistry(sessionFactory);

			//add the Registry as an instance
		    cfg.AddRegistry(nhWcfRegistry);
		});
	}
}

By Scanning

Last but least, SM Registries can be added to the configuration via scanning. I really like SM’s ability to scan the types specified and apply common and custom conventions for type registration. I won’t go into details here, as the documentation is pretty good in this area.

During a scan, SM can be told to look for all Registry implementations and automatically add them to the configuration using the IAssemblyScanner.LookForRegistries() method. This can come in handy if you are scanning your components from your application. If you have a large number of components, it may be tempting to scan all the application’s assemblies and find registries, but be warned that this can make for a very long startup when you consider the number of types in your third party assemblies, like Log4Net, NHibernate, Castle, etc. Of course, you can always apply a convention to limit which components get scanned, but it’s definitely something to be aware of. Just put some thought into your use of IAssemblyScanner.AssembliesFromApplicationBaseDirectory() and IAssemblyScanner. AssembliesFromPath(path:string).


Scan(scanner =>
{
	 //include this
	scanner.TheCallingAssembly();

	//include the Data component
	scanner.AssemblyContainingType<IProfileRepository>();

	//include all the registries
	scanner.LookForRegistries();

});

Conclusion

Using Dependency Injection/IoC is a great way to build loosely coupled, composeable applications. An IoC Container is a tool that is used to tell your application how it should compose your types by defining the “what” and the “how” of your application’s dependency resolution. StructureMap is one of many available choices of IoC Containers for .NET, but its rich feature set and intuitive fluent DSL have put it at the top of my list.

Many examples and tutorials for StructureMap show how to configure a trivial application where all the types exist within the application or from application specific components. When dealing with components that are shared across the enterprise, it is important to give every consuming application a way to configure SM with their default configuration without copying the code into every application’s startup and without putting the configuration decisions solely in the hands of the component. This can be achieved through the use of the StructureMap Registry, which can be defined as coarse or granular as required at the co

Posted in Alt.Net, Architecture and Design, ASP.NET MVC, C#, IoC, NHibernate, StructureMap, TDD, Uncategorized | Tagged: , , , , , | 2 Comments »

Castle Windsor Tutorial in Asp.Net MVC

Posted by coreycoogan on November 6, 2009


Castle Windsor is one of the more popular IoC containers in the .NET space today.  Others include StructureMap, NJect, AutoFac, Unity and others.  My top choices are StructureMap and Castle, but I’ve never really used NJect or AutoFac and it’s my opinion that Unity is the weakest of them all and hardly worth mentioning.  I’ll show some of the basics of Castle Windsor – enough to get you setup in your ASP.NET MVC, or any other .NET application. I’ll show you enough to handle 90%+ of the most common IoC needs. Much of my examples come from the S#arp Architecture, which I’m using in my current project.

Castle Windsor Configuration Options

Windsor offers 2 configuration options – .config file or code.  Like many others, I have moved away from trying to do everything in my .config file and do more in code, practicing Convention or Configuration (CoC).  Because the novelty of .config files is so early 2000’s, I’ll focus on configuring Castle using good ‘ole C# and some conventions I follow in my applications.

Common Conventions

Nothing ground breaking here, but I like to keep my controllers as light as possible.  Therefore, I keep my application logic in an application service layer.  My app services have one ore more repositories injected into them where domain objects can be retrieved for performing operations.  My repositories, application services and interfaces all reside in different layers, which in my case is a physical assembly.  Some folks prefer to inject repositories directly into the controller, which works as well, but using services works better for me because I feel I get better separation and it simplifies the controller’s constructor, which is how I handle dependency injection.

So here’s the breakdown of my layers (assemblies/projects):

Application Layer:
Application Services, Application Service Interfaces

Data Layer:
Repository Implementations

Domain Layer (Core):
Repository Interfaces

UI Layer:
Controllers

Configuring Castle to Handle My Conventions

All of my dependency injection is through the object’s constructor.  As long as Windsor can resolve all the dependencies required by the constructors, it will be able to create and resolve the dependent objects as well.  IoC configuration is typically left to the application (MVC, WinForms, WPF, etc.), so you would bootstrap the configuration in some sort of Application Start event, which in the case of ASP.NET is available from the Global.asax.  All the code you’re about to see will exist in a class responsible for the IoC configuration that gets called from my Application_Start event.

First, a sample of a repository class and its interface, then how to automatically register all repositories in one swoop.


//my repository class from the Data assembly
namespace S2sol.Rpo.Data
{
     public class ClassroomRepository : S2sol.Rpo.Core.DataInterfaces.IClassroomRepository
    {
    }
}

//my Repository interface from the Core assembly
namespace S2sol.Rpo.Core.DataInterfaces
{
    public interface IClassroomRepository
    {
    }
}

//this is how I would resolve an IClassroomRepository to its implementation from Castle
IClassroomRepository repo = container.Resolve<IClassroomrepository>();

To make things simple, I’ll use Castle’s AllTypes.Pick() method, which effectively scans the types in an assembly. In my example below, I’m scanning my Data assembly and looking for non-generic interfaces that are the first interface defined on the classes in my Core assembly and register them with the container.

private static void AddRepositoriesTo(IWindsorContainer container)
{
    container.Register(
    AllTypes.Pick()
    .FromAssembly(typeof(UserRepository).Assembly) //get the assembly where this repository lives
    .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core") //look for interfaces from this assembly
    );
}

I’m going to want to automatically register all my Application Services as well so they can be injected into my controllers. This syntax is a little simpler because those interfaces and implementations are in the same assembly.

private static void AddApplicationServicesTo(IWindsorContainer container)
{
      container.Register(
        AllTypes.Pick()
        .FromAssembly(typeof(ProfileService).Assembly)
        .WithService.FirstInterface());
}

Now I’ll want to make sure that all my controllers are registered. This done by using the RegisterControllers extension method from the MvcContrib.Castle library.

private static void AddControllersTo(IWindsorContainer container)
{
	container.RegisterControllers(typeof(HomeController).Assembly);
}

Now all that’s left is to show the simple part, and that’s how to register any one-offs that may not fit into your conventions. For example, I have an IValidator interface that I want to resolve to the Validator implementation I’m using in this project.

container.AddComponent<IValidator,Validator>();

It’s as simple as that. Once this has been put in place, I can just continue to develop repositories, application services, controllers and their respective interfaces and never have to remember to register any of them as long as I follow my conventions.

Castle’s Factory Facility

Facilities are how Castle handles extensibility. These are plugins for Castle that can be used for just about anything. Some of the more popular ones support NHibernate, WCF and logging. The one that comes in handy for my needs is the FactorySupportFacility. This facility allows me to configure a factory method in the container and control how objects get resolved.

The RoomParentsOnline MVC application makes use of a custom IPrincipal object that gets injected into my UserSession class, along with an HttpSessionStateBase implementation. The UserSession class is used for interacting with the current user, and by passing it an IPrincipal and HttpSessionStateBase, I have a testable design that I can develop using TDD.

//constructor for the UserSession implementation
public UserSession(IProfileService profileSerivce,
            HttpSessionStateBase session, IPrincipal principal)

The first thing to do is make sure that Castle knows about the Factory Facility that I wish to use. To do this, you can either register the facility in the .config file or in code. I’ll show you how to add it in code. This would be done in your registrar class’s constructor to make sure it’s available right away.

container.AddFacility<FactorySupportFacility>();

Now that Castle knows I’m using the Factory facility, I can tell it how I want to resolve the IPrincipal and HttpSessionStateBase. I also have to tell it how to resolve an IIdentity because of the way my code is accessing it (for testability). In the code below, I am telling Windsor to keep the registered objects available during the scope of a request. I then pass it the Function expression for how to create the object, which is all coming from the HttpContext.

private static void AddSecurityConcernsTo(IWindsorContainer container)
{
	container.Register(Component.For<IIdentity>()
	  .LifeStyle.PerWebRequest
	  .UsingFactoryMethod(() => HttpContext.Current.User.Identity));

	container.Register(Component.For<IPrincipal>()
	  .LifeStyle.PerWebRequest
	  .UsingFactoryMethod(() => HttpContext.Current.User));
	
	container.Register(Component.For<HttpSessionStateBase>()
		.LifeStyle.PerWebRequest
		.UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));


}

I’m sure you’ll agree that this code makes it very simple to invert some of those pesky dependencies that come from the core ASP.NET plumbing. This technique is very effective for designing testable classes that need to interact with some of the “ugly stuff”.

The MvcContrib WindsorControllerFactory

Now that we have our Windsor container all configured to resolve our controllers, why not let the MVC framework use that container for creating our controllers. This can be done quite easily using the WindsorControllerFactory from the MvcContrib project. This is an implementation of ASP.NET MVC’s IControllerFactory interface. Using it is simple – just create an instance and give it your container and then register the factory with MVC. This is something that needs to be done during Application_Start.

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));

Common Service Locator

The last thing that I’ll mention is the CommonServiceLocator project. If you already have your IoC configured, you might as well make it available to all your code that may need to get object implementations without dependency injection. The CommonServiceLocator makes this easy by adapting all the major IoC containers to work under a common interface with a few key static methods. This is something that should also happen in the Application_Start.

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

Bringing it all Together

Now I’ll just put everything together for your copy/paste pleasure.

Global.asax

protected void Application_Start()
{
	InitializeServiceLocator();

	//do everything else here
}

/// <summary>
/// Instantiate the container and add all Controllers that derive from 
/// WindsorController to the container.  Also associate the Controller 
/// with the WindsorContainer ControllerFactory.
/// </summary>
protected virtual void InitializeServiceLocator()
{
	//create the container
	IWindsorContainer container = new WindsorContainer();
	//set the controller factory
	ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
	//configure the container
	ComponentRegistrar.AddComponentsTo(container);
	//setup the common service locator
	ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
}

ComponentRegistrar.cs

public class ComponentRegistrar
    {
        public static void AddComponentsTo(IWindsorContainer container)
        {
            container.AddFacility<FactorySupportFacility>();

            AddControllersTo(container);
            AddGenericRepositoriesTo(container);
            AddCustomRepositoriesTo(container);
            AddApplicationServicesTo(container);
            AddOneOffs(container);
            AddSecurityConcernsTo(container);
        }

		//add all my controllers
        private static void AddControllersTo(IWindsorContainer container)
        {
            container.RegisterControllers(typeof(HomeController).Assembly);
        }

		//handle any one off registrations that aren't convention based
        private static void AddOneOffs(IWindsorContainer container)
        {
            container.AddComponent<SharpArch.Core.CommonValidator.IValidator,Validator>("validator");
        }

       //handle registrations for my security classes
        private static void AddSecurityConcernsTo(IWindsorContainer container)
        {
            container.Register(Component.For<IIdentity>()
              .LifeStyle.PerWebRequest
              .UsingFactoryMethod(() => HttpContext.Current.User.Identity));

            container.Register(Component.For<IPrincipal>()
              .LifeStyle.PerWebRequest
              .UsingFactoryMethod(() => HttpContext.Current.User));
            
            container.Register(Component.For<HttpSessionStateBase>()
                .LifeStyle.PerWebRequest
                .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));


        }


		//register my application services
        private static void AddApplicationServicesTo(IWindsorContainer container)
        {
            container.Register(
                AllTypes.Pick()
                .FromAssembly(typeof(ProfileService).Assembly)
                .WithService.FirstInterface());
        }
		
		//register all custom repositories (not generic)
        private static void AddCustomRepositoriesTo(IWindsorContainer container)
        {
            container.Register(
                AllTypes.Pick()
                .FromAssembly(typeof(UserRepository).Assembly)
                .WithService.FirstNonGenericCoreInterface("S2sol.Rpo.Core"));
        }

		//register all my SharpArch generic repos
        private static void AddGenericRepositoriesTo(IWindsorContainer container)
        {
            container.AddComponent("entityDuplicateChecker",
                typeof(IEntityDuplicateChecker), typeof(EntityDuplicateChecker));
            container.AddComponent("repositoryType",
                typeof(IRepository<>), typeof(Repository<>));
            container.AddComponent("nhibernateRepositoryType",
                typeof(INHibernateRepository<>), typeof(NHibernateRepository<>));
            container.AddComponent("repositoryWithTypedId",
                typeof(IRepositoryWithTypedId<,>), typeof(RepositoryWithTypedId<,>));
            container.AddComponent("nhibernateRepositoryWithTypedId",
                typeof(INHibernateRepositoryWithTypedId<,>), typeof(NHibernateRepositoryWithTypedId<,>));

        }
    }

Conclusion

This post ended up being longer than I originally intended, but hopefully you gleaned some nice little gems here. Castle Windsor is really easy to setup and use and there are many contributions out there that add more great functionality. Sometimes it’s hard to know how to use these types of tools without some concrete examples and I hope to have you shown you some useful ones here.

Posted in Alt.Net, Architecture and Design, ASP.NET, ASP.NET MVC, Design Patterns, IoC, Uncategorized | Tagged: , , , , , , , , , , , , , | 23 Comments »

Adding Icons to ValidationSummary and Information Boxes with JQuery

Posted by coreycoogan on November 2, 2009


What’s so special about ValidationSumary and Information Boxes?

When there are errors or important information that you need to call out to your users, it is important to make it unmistakably noticeable. You want to stack the odds in your favor as much as possible that the user will see your call outs and act on them accordingly. Unfortunately, the ValidationSummary in ASP.NET and ASP.NET MVC comes very vanilla. You can change the appearance in MVC by defining the “validation-summary-errors” CSS class that is set to the ValidationSummary by default, but this isn’t always enough. The same goes true for an Information Box, which is what I call a box that contains important information that I want the user to see.

It is very typical for users to gloss over these important messages when they are rendered as text only. Placing the text in a colored box with a brightly colored border can help, but I’ve still experienced frustrated users claiming that registration is broken because they miss the message that says their email has already been used. To combat this, it’s a good practice to use familiar operating system icons for Error, Information, Warning, etc. Most users will recognize familiar icons and have learned to pay attention when they see them.

Here’s an example of what we’re going to achieve:

Error callout box

Info Callout Box

Styling the “Callout Box”

I use the same technique to style all my callout boxes. It’s very simple to do with JQuery, CSS and a few icons. I’ll demonstrate this for both an Error and Info callout.

First, the CSS classes. Each type of callout (error, info, warning) will require 2 classes. One class will style the box that contains the text and the other will be used to hold the applicable icon.

.infobox
{
    border: solid 1px #228ef1; 
    padding: 5px 8px 5px 8px;
    text-align:left;
    vertical-align:middle;
    background-color:#F1E7D1;
}

.infoimage
{
   padding: 5px 15px 5px 15px;
    background:#F1E7D1 url(/images/icons/info-24x24.png) no-repeat;
    background-position:left center;
}

.errorbox
{
    border: solid 1px red; 
    padding: 5px 8px 5px 8px;
    text-align:left;
    vertical-align:middle;
    background-color:#F1E7D1;
}

.errorimage
{
   padding: 5px 15px 5px 15px;
    background:#F1E7D1 url(/images/icons/err-24x24.png) no-repeat;
    background-position:left center;
    vertical-align:middle;
    display:inline-block;
    height:100%;
}

For my error callouts, I want to add one more class. This will handle the heading of my errors, which typically reads something like “Please fix the following errors”.

.errorhead
{
    color:#CC0000;
    font-weight:bold;
    font-size:15px;
    padding-left:18px;
}

Using JQuery to Construct the Callout Box

The HTML used to put the icon in the callout box requires nested DIV or SPAN elements. I don’t want to depend on my memory to always add the nested elements each time I want a callout, I want to simply write something like this:

<div id="CustomSearchSelect" class="infobox">
            <strong>Can't Find Your School?</strong> Try a <a id="CustomSearchLink" href="#">Custom Search</a>.
</div>

<div class='errorbox'>
This action is not allowed!
</div>

That’s where JQuery is able to help us. By using the prepend function, we can have the appropriate icon automatically injected into our callout box. We do this by adding the following to our JQuery ready function in our Master Page.

$(document).ready(function() {
$(".infobox").prepend("<span class='infoimage'>&nbsp;</span>");
$(".errorbox").prepend("<span class='errorimage'><span class='errorhead'>Looks like we have a small problem...</span></span>");
});

Pretty simple, right? Here’s what’s happening here. The script is finding the elements styled with the infobox and errorbox class and sticking in a SPAN element styled with the corresponding icon class. The errorbox gets the additional heading added here as well. You could do the same thing for Warn, Question or any other conventions you wish to follow.

Styling the ValidationSummary

The ValidationSummary requires a little bit of extra effort. This is because I’m using the xVal 1.0 and a ValidationSummary for client-side error handling as described in my last blog post. The only thing I need to do is define the HTML for my ValidationSummary, but hide it unless I have Model Errors in my MVC application. This is done by wrapping my ValidationSummary in a div styled with the errorbox class like so.

<% string display = ViewData.ModelState.IsValid ? "none" : "block"; %>
<div class="errorbox" id="validationSummary" style="display:<%=display%>"> 
    <%= Html.ValidationSummary() %>
</div>

Finding the Icons

I found some pretty nice icons on various free icon websites. It took a bit of time to run them all down, so I’m including them here for you in a zip file.

Icon Zip File

Posted in ASP.NET, ASP.NET MVC, CSS, jQuery, UI | Tagged: , , , , | 4 Comments »

ASP.NET MVC Auto Model Validation with xVal

Posted by coreycoogan on October 30, 2009


Overview

Validation is one of those necessary evils of software development.  Every application needs it and there are about as many ways to handle it as there are opinions.  No matter how you slice it, it’s usually a pain and just plain boring.  One of the things that has helped ease that pain are the assortment of validation frameworks that are available that allow the use of Attribute decorated models to specify validation rules.  If you are like me and prefer the View Model pattern when developing your Asp.Net MVC apps, then this is a perfect fit.  Now add the well crafted xVal Validation framework with automatic client-side validation via JQuery Validation and things begin to get easier.  In this post, I’ll take this one step further by showing how to use an
Action Filter approach, which I borrowed from the Code Camp Server code base, with NHibernate Validator to automatically validate the View Model via a ValidateModelAttribute that can be placed on the controller.  I’ve applied the same code in the past using Castle Validator by using the Adapter Pattern in a couple hours.

First things first, make sure you get everything you need by getting the latest versions of xVal, JQuery Validation, NHibernate Validator and/or Castle Validator.  I will warn you that if you get either of the mentioned Validators from the source trunk, you may have to recompile the xVal Rules Providers against those bits.  I had this problem with a breaking change from NHibernate Validator version 1.2.0.1003, but fortunately I found a patch here for xVal and was able to build the source and get everything working.  If anyone needs help with that, leave a comment and I’d be glad to lend a hand.

xVal Setup

There are a few basic steps to getting xVal available to your MVC project.  This post by xVal’s creator, Steve Sanderson, is a great place to get this introductory stuff.

Step 1:  Reference xVal.dll and xVal.RuleProviders.XXX.dll.

Step 2: Add the xVal.jquery.validate.js and jquery.validate.js libraries to your project and reference them in a masterpage or view.

Step 3: Add the xVal namespaces to the web.config so you won’t have to fully qualify your calls and can take advantage of the extension methods.

<add namespace="xVal.Html"/>
<add namespace="xVal.Rules"/>

Step 4: Add the validator to the xVal Rule Providers collection in the Global.asax Application_Start event handler.

xVal.ActiveRuleProviders.Providers.Add(new NHibernateValidatorRulesProvider());

View Model Decoration

Now that we have the basics out of the way, we can start setting up our View Model for validation.  The first step is to decorate the properties on our model with the validation attributes.  In the case of NHibernate Validator, there are many to choose from, including [Email], [NotNullNotEmpty] and [Pattern].  Here’s an example of a RegisterViewModel class from the Room Parents Online project. By including a value for the Message parameter, I’ve provided a useful error message that will get displayed to the user.

[NotNullNotEmpty(Message = "Email is Required"), Email(Message = "Invalid Email"), Length( 50)]
public virtual string Email { get; set; }

[NotNullNotEmpty(Message = "Confirm Email is Required"), Email(Message = "Invalid Email"), Length( 50)]
public virtual string ConfirmEmail { get; set; }

[NotNull(Message="Please specify the best time to be contacted")]
public virtual BestTimeToContact BestTimeToContact { get; set; }

[NotNull(Message = "Please specify if you wish to be contacted through email")]
public virtual bool AllowNotification { get; set; }

[NotNull(Message = "Please specify who can see your contact info")]
public virtual UserVisibleTo UserVisibleTo { get; set; }

[NotNullNotEmpty(Message="Nickname is required"), Length(50)]
public virtual string Nickname { get; set; }

[Pattern(@"^(\d{4})?$", Message = "The area code of your phone number are not valid")]
public virtual string Phone1 { get; set; }

The View

The next thing to do is prepare the View for xVal validation. First, make sure you have the xVal and JQuery validation scripts reference, either in the particular View or the Masterpage.

Step 1: If you prefer for all your errors to be grouped together like I do, create a Validation Summary with an ID assigned:

<div id="validationSummary" >
<%= Html.ValidationSummary() %>
</div>

Step 2: Use the xVal extension method to emit the JQuery Validation script.  The sample below takes the type of View Model as a generic parameter and tells xVal what Validation Summary to use for displaying error messages.  The .AddRule methods are handy little AJAX rule executions that are new in version 1.0.  Get more details in Steve’s post.

<%= Html.ClientSideValidation&lt;S2sol.Rpo.Web.Models.Profile.RegisterModel&gt;()
.AddRule("Email", new RemoteRule((Url.Action("ValidateUniqueEmail"))))
.AddRule("Nickname", new RemoteRule((Url.Action("ValidateUniqueNickname"))))
.UseValidationSummary("validationSummary") %>

The ValidateModelAttribute Filter

We’re almost there. Now we only need to hook up the filter to validate the model automatically. First, a quick peek at what the Action method looks like that will invoke the automatic model validation via the filter:

[AcceptPost]
[ValidateModel(typeof(RegisterModel))]
[Transaction]
public virtual ActionResult Register(RegisterModel model)

Now let’s have a look at the code for the validation filter itself:

namespace S2sol.Rpo.Web.Security.Filters
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
	public class ValidateModelAttribute : ActionFilterAttribute
	{
		private readonly Type _viewModelType;
		private readonly IValidator _validatorRunner;

		public ValidateModelAttribute(Type viewModelType)
            : this(viewModelType, ServiceLocator.Current.GetInstance<IValidator>())
		{
		}

		public ValidateModelAttribute(Type viewModelType, IValidator validatorRunner)
		{
			_viewModelType = viewModelType;
			_validatorRunner = validatorRunner;
		}

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			object model = GetModelFromActionParameters(filterContext);

            var errors = _validatorRunner.ValidationResultsFor(model);

            //check if the model has ICompositeValidationResult
            if (model is ICompositeValidationResult)
            {
                ICompositeValidationResult validate = model as ICompositeValidationResult;
                if (!validate.IsValid())
                {
                    foreach (var err in validate.GetResults())
                        errors.Add(err);
                }
            }

			if (errors.Count > 0)
			{
				AddErrorsToModelState(filterContext, model,errors);
			}
		}

		private object GetModelFromActionParameters(ActionExecutingContext filterContext)
		{
			foreach (var kvp in filterContext.ActionParameters)
			{
				if (kvp.Value == null)
				{
					continue;
				}

				if (kvp.Value.GetType() == _viewModelType)
				{
					return kvp.Value;
				}
			}

			throw new NullReferenceException("The action parameter was null.  Check the binding prefix.");
		}

		private void AddErrorsToModelState(ControllerContext context, object model, ICollection<IValidationResult> results)
		{
                   //IValidationResult is defined in the SharpArchitecture
                   foreach (IValidationResult result in results)
                   {
                     context.Controller.ViewData.ModelState.AddModelError(result.PropertyName, result.Message);
                   }
		}

		private static string FlattenErrors(string[] errorsForProperty)
		{
			return string.Join(", ", errorsForProperty);
		}
	}
}

After it’s all done and compiled, here’s an example of a failed registration attempt with client and server side validation and the only thing I have to do is decorate my model with my chosen validation constraints and decorate my action method with the ValidateModelAttribute filter.

Posted in ASP.NET, ASP.NET MVC | Tagged: , , , , , , , | 4 Comments »

Client Side Dependent Dropdowns with JQuery without AJAX

Posted by coreycoogan on September 12, 2009


There are several terms to describe the common UI technique of having 2 dropdown lists, with the selections of the first dropdown changing the options of the second.  Common terms for this include Dependent Dropdowns, Context Sensitive Dropdowns,  Contextual Dropdowns and probably others.

I recently had a requirement for this functionality in a control in an ASP.NET MVC project.  When I searched for some samples on how to do this in JQuery, I realized that all the samples I found used AJAX to populate the second list.  In this particular case, it made more sense to keep everything on the client, so that’s what I developed.  This post is about how I accomplished this using JQuery, JSON.NET and a ViewModel with a couple extension methods.  If you’re looking for ways to do this with AJAX, you’ll have to read one of the many other examples in the blogosphere.

The Requirement

The user needs a way to choose a color for a product.  The chosen color is categorized under a parent color (Blue.Baby, Blue.Sky, Yellow.Banana, Yellow.Lemon).  The user should be able to first pick a parent color and then view a list of all child colors from which to pick.  The catalog of color selections is stored in a database and should be used to drive the dropdowns.  The dropdowns are just a helper as the user is able to input any color name they wish, regardless of whether or not it appears in the second dropdown.  Up to 5 colors can be chosen per product, so the color selection should be a control that can be repeated on a view, however, this post will ignore that requirement and show how this can be accomplished in a singular fashion.

The  Object Model

The ViewModel that drives the View where this functionality resides contains an IList<VendorColor> property, which will be used to populate the dropdowns.  The VendorColor class looks like this:


public class VendorColor
 {
      readonly int _vendorColorId;
      readonly string _primaryColor;
      readonly string _secondaryColor;

 public VendorColor(int vendorColorId, string primaryColor,
                                       string secondaryColor)
 {
      _vendorColorId = vendorColorId;
      _primaryColor = primaryColor;
      _secondaryColor = secondaryColor;
 }

 public int VendorColorId { get { return _vendorColorId; } }

 public string PrimaryColor { get { return _primaryColor; } }

 public string SecondaryColor { get { return _secondaryColor; } }
 }

Extension Methods

In order to keep everything on the client, we’ll need to get the pertinent data from the collection of VendorColor objects to the View so it’s accessible by JQuery and JavaScript.  To do this, 2 extension methods were written to serialize the required data to JavaScript objects.

First, we need to gather the distinct PrimaryColor values from the list of VendorColor objects and get them into an array.  Here’s what that extension method looks like.


public static string PrimaryColorsAsJsArray(this List colors)
 {
 //get the distinct primary colors from the collection
 var primaries =
 (from c in colors
 select c.PrimaryColor).Distinct();

 //append each value into a JavaScript Array string, start with an empty string for blank option
 StringBuilder sb = new StringBuilder("var arrPrimary = [\"\",");
 foreach (var primary in primaries)
 sb.AppendFormat("\"{0}\",", primary);

 //remove the last comma and add ending bracket
 sb.Remove(sb.Length - 1, 1);
 sb.Append("];");

 return sb.ToString();

 }

This results in the following javascript:

var arrPrimary = ["","Red","Blue","Green","Yellow"];

The next extension method will be used to serialize the entire collection of VendorColor objects to JSON objects that we can later parse with JQuery and fill our dependent dropdown list. This is ridiculously easy with the help of the awesome JSON.NET library. Check out what can be done in one line of code!


public static string VendorColorsToJsonArrary(this List colors)
 {
 return "var arrSecondary = " +
 Newtonsoft.Json.JsonConvert.SerializeObject(colors) + ";";
 }

This results in the following javascript (formatted for readability):

var arrSecondary = [
                    {"VendorColorId":1,"PrimaryColor":"Red","SecondaryColor":"blood"},
                    {"VendorColorId":2,"PrimaryColor":"Red","SecondaryColor":"apple"},
                    {"VendorColorId":3,"PrimaryColor":"Blue","SecondaryColor":"sky"},
                    {"VendorColorId":4,"PrimaryColor":"Blue","SecondaryColor":"baby"},
                    {"VendorColorId":5,"PrimaryColor":"Green","SecondaryColor":"lime"},
                    {"VendorColorId":6,"PrimaryColor":"Green","SecondaryColor":"lettuce"},
                    {"VendorColorId":7,"PrimaryColor":"Yellow","SecondaryColor":"sunshine"},
                    {"VendorColorId":8,"PrimaryColor":"Yellow","SecondaryColor":"lemon"}
                 ];

The View

Now let’s tie it all together by seeing the view and all the javascript that makes this work. It should be noted that my view is utilizing the latest version of the JQuery library.


    //use vars for my controls so JQuery and Javascript won't have to retype each time
    var primaryDd = '#PrimaryColor';
    var secondaryDd = '#SecondaryColor';

 

Now the script that makes all this work, complete with comments. In the real world, this is stored in an external .js file, as it should be. This keeps the views cleaner and Google favors it for SEO. Keep in mind that the script is using the vars defined above.

function ClearDd1(dropDown1) {
    $(dropDown1)[0].options.length = 0;
}

function ClearDd2(dropDown2) {
    $(dropDown2)[0].options.length = 0;
}

function BindSecondary(dd1, dd2) {

    //clear the options before rebinding them
    ClearDd2(dd2);

    //get the selected value from dropdown 1
    var sel = $(dd1).val();

    //use the JQuery grep function to find all objects in my JSON collection
    //where the PrimaryColor equals the selection from the first dropdown.
    //this is really the key to making this work elegantly
    var arr = $.grep(arrSecondary, function(a) { return a.PrimaryColor == sel; });

    //for each JSON object, write an option to the second dropdown
    $(arr).each(
                function(i) {
                    $("").attr("value", arr[i].VendorColorId)
                                      .text(arr[i].SecondaryColor).appendTo(dd2);
                });
}

function SelectColor(dd2, hid, txt) {

    //the selected value from the second dropdown
    var selVal = $(dd2).val();

    //make sure a color has been selected
    if (selVal == '') {
        alert('You must select a secondary color or cancel');
        return false;
    }

    //grab the text from the selected option
    var selText = $(dd2 + ' :selected').text();

    //store the ID, or option value, in a hidden form field
    $(hid).val(selVal);
    
    //send the selected color into a text field
    $(txt).val(selText);
}

Conclusion

JQuery and ASP.NET Ajax has made it very easy to use AJAX to accomplish dependent dropdowns. In many cases, it’s wasteful and unnecessary to go to the server for this information over and over again. In such cases it can be advantageous to do this purely on the client. Using JSON.NET to serialize objects from .NET to JSON and using JQuery and its “grep()”, “each()” and “val()” methods to get the right data and handle population and selection. This solution didn’t take too long to develop, but if you know a better way, I’d love to hear about it.

Posted in ASP.NET MVC, jQuery | Tagged: , , , | 1 Comment »

Asp.Net MVC, S#arp Architecture and Blood

Posted by coreycoogan on September 5, 2009


The Bleeding Edge

The Bleeding Edge

As mentioned in a previous post, I’ve embarked on a side project that provides tangible value to a relatively large mass of people.  This project, http://www.roomparentsonline.com, started some time ago and seemed like the perfect opportunity to move from toying with ASP.NET MVC and NHibernate to actually writing a production app with those tools.  Had I stuck with the same old stack I’m sure the project would be done by now, but instead I’m just getting started with developing actual features.  This is a very similar situation described in Rob Conery’s latest post, but I’m listening to Bad Corey and forging ahead because I really want to up my skills in this area.

So where was all my time spent?  Some was dedicated towards getting the design I got from Mark Sternig into the MVC framework.  Other time was spent getting the membership stuff setup and figuring out how I was going to lay all that out, but the other 90% was spent with Fluent NHibernate (FNH) and getting slashed by the bleeding edge of every cool OSS project out there.  Now I know why a common Alt.Net slogan is “Running with Scissors”.

S#arp Archecture 1.0 RTM

My first major hurdle was caused by the fact that I didn’t want to wait anymore for SharpArch to be released in 1.0, so I moved ahead with the latest.  I already had some significant development done when 1.0 was released 10 days later.  The RTM release was significant and fixed many issues, but there’s no way to simply upgrade the templates.  So I started by copying over all the 1.0 binaries, which caused some compatibility issues because dependencies were built against previous versions of Castle, NHibernate, etc.  I began upgrading bit by bit and found the updated classes in the new template and began to upgrade my project.  It was painful, but in the end it worked and all was good.  Time to move on to getting some mappings done.

Fluent NHibernate

For those of you not familiar with what Fluent NHibernate is, it basically lets you configure NHibernate through a fluent interface without requiring XML files.  I personally hate configuring with XML files, which is why I was so intrigued by this project.  The example project and articles I’ve read make FNH seem so simple.  It was only after I began to dive deep that I realized it seemed simple because the examples were simple.  When I tried doing things like mapping table-per-hierarchy relationships, I started pulling my hair out.  Things just didn’t work as I expected them to.  So I began to post to the FNH Group and got some great help, mostly from the creator himself, James Gregory.  Much of the advice was the same – get latest from the trunk as odds were this was a bug that’s already been fixed.

This is where the fun began.  Upgrading to FNH from the trunk meant upgrading NHibernate, meant upgrading multiple Castle projects, meant upgrading NHiberate Validator meant upgrading xVal meant upgrading all core Sharp Architecture libraries.  As you can imagine, this was going to be painful, but I saw no other option.  To make matters worse, the version from the trunk had many breaking changes so I was also breaking stuff that I actually had working.  Thankfully, Tom Cabanski informed the SharpArch group that he had rebuilt all the binaries against these latest versions and provided them in a tidy little zip file.  This was a huge help and I can’t thank Tom enough.

The Future

I’m now at a place where I can begin to actually implement features.  I’ve said a sad goodbye to my self-imposed deadline of having this app, at least registration, done by start of the 2009 school year, but I’ve learned a lot and have much more to learn.  During the upgrade process, I was also able to move to the 1.0 release of Linq to NHibernate.  It’s wonderful to think how many great projects came to fruition this summer after reading about them in their idea phase for so long.  The .NET OSS community is strong and I’m grateful to be enjoying the fruits of their labor.  Anyway, I finally figured out how to blend automappings and Fluent mappings, which was required to do class-per-hierarchy, but I’ll save that for another post.  I also have a nice validation implementation utilizing NHibernate Validator, JQuery Validation and xVal, but that post is coming as well.

Posted in ASP.NET MVC, Fluent Nhibernate, NHibernate, S#arp Architecture | Tagged: , , , , , , | 5 Comments »

Asp.Net MVC and Server Controls

Posted by coreycoogan on August 25, 2009


I’m involved on the fringe of an MVC project right now and the core group of developers have no experience in ASP.NET MVC.  This group is more experienced in traditional Web Forms development and didn’t take the time to learn anything about MVC and how it works.  Unfortunately, this led to some major problems.  I’d like to reiterate here for anyone who stumbles across this post one major lesson that this development team learned.
DON’T EVER USE SERVER CONTROLS AND VIEW STATE IN ASP.NET MVC.

Some controls may be work some of the time, but it’s best to just stay away.  If you are going to use ASP.NET MVC, then go all in.  Everything you want to do in Web Forms is possible in MVC, just in a different way.  Embrace the truth of web development!

Posted in ASP.NET, ASP.NET MVC | Tagged: , , , , , | 1 Comment »

ASP.NET MVC and S#arp Architecture

Posted by coreycoogan on August 21, 2009


It’s been a while since I’ve posted.  I’ve been very busy with my paying job and my side project, Room Parents Online (RPO).  For RPO, I’m using the S#arp Architecture, developed by Billy Mcafferty.  It’s a great framework for getting a new MVC project started, but one of the real benefits of using it for me was the initial setup and configuration of Fluent NHibernate.  I have never written a real production app in NH at all, so this was something I’ve been wanting to do for a long time.  There’s been plenty of pain on the bleeding edge, but more on that in future posts.

Now that I’ve laid the ground work, expect to see more posts coming from the RPO project.  I’ve been working on this project for about a month, so I have a good bit of material already, and will find the time to blog about the project regularly.  Topics to come will include:

- Automatic Model validation with xVal (this post was started 10 days ago)
– Fluent NHibernate
– NHibernate
– The pains of running with scissors
– ASP.NET MVC
– Google integration
– JQuery
– S#arp Architecture

So stay tuned for some good Alt.net stuff.

Posted in Alt.Net, Architecture and Design, ASP.NET MVC, S#arp Architecture | Tagged: , , , , , | 1 Comment »

Mockup Alternative to Visio and PowerPoint

Posted by coreycoogan on July 24, 2009


As  I was writing the title for this post, I ran through many iterations before settling on this one soley for the purpose of being more targeted towards search terms.  Here’s some of the runner ups:

  • Mockups in Visio and PowerPoint Suck!
  • Say goodbye to Visio and PowerPoint mockups
  • Mockups in Visio and PowerPoint….Never!

Sample Mockup It should be clear now just how much I hate Visio and PowerPoint for doing mockups.  Neither of these tools were built for this purpose, so it’s no surprise that the process is awkward and usually time consuming.  Thankfully, I came across a far superior tool a while back in a DDD post by Casey Charlton.

The tool is called Balsamiq and it’s pretty amazing.  It’s whole reason for existence is for doing mockups – not presentations,  flow charts or anything else.  It runs on Adobe Air, so the installation can take a while if you don’t have this runtime on your machine already, but updates are free for life and come down pretty quick.

Balsamiq comes in 2 flavors, the desktop edition and the web edition, as well as plug-ins to some popular CMS and Project software packages.  The license is cheap, only $79 for a single license and cheaper for multiple seats.  The project file is saved in an XML format, so it can be checked into source control and easily shared.  It has a ton of built-in controls to allow you to mock everything from Maps to Browser Windows to Grids to Buttons and just about any other UI element you can think of.  The only downside is that you can’t make reusable components, which means a simple change to something like a header could result in hand-editing every mockup file you created.

Sample MockupI won’t go into too much detail here.  If this sounds good to you and you want to learn more, watch the quick demo video and then take a test drive with the browser edition (no setup required).

Posted in Architecture and Design, ASP.NET, ASP.NET MVC | Tagged: , , , | 2 Comments »

Asp.Net MVC HTML Helper Alternative

Posted by coreycoogan on June 11, 2009


I’m still learning ASP.NET MVC and gearing up for 2 projects.  At first glance of a typical View, I had a classic ASP flashback.  Now that I understand how it really works, I see that the only commonality is the use of the ASP delimiter tags (<%%>).

I’m not real crazy with the default ASP.NET MVC view engine and have examined some alternatives, such as MVC Contrib and Spark.  A new strategy has emerged however, developed by Eric Hexter.  Eric is dubbing his project Opinionated Input Builders.  It’s very early stage, but it’s definitely interesting and worth checking out.

Posted in ASP.NET MVC | Tagged: , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.