A Good TDD Process Diagram?

I am trying to create a flow diagram that depicts the Test Driven Development process and I need your expertise/opinion/criticism in nailing it down.

Take a look below and let me know what is wrong, what is right and what can be done better.

image

I drew the above diagram based on my understanding of TDD and by referencing other diagrams that I found online.  Specifically:

image

from http://www.agiledata.org/essays/tdd.html

image

from http://designindrive.com/?p=31

image

from http://tinyurl.com/498pjg

Client & Server Side Validation in ASP.NET MVC

[Update: The code is open-sourced at http://code.google.com/p/mvcvalidation/]

The asp.net mvc codeplex preview 5 version just came out a few days ago and it includes a lot nice enhancements.  For the best introduction read Scott’s post

Some of my favorite changes happened in validation.  Incidentally, I was already working on a post to talk about doing client and server side validation the easy way.  The inspiration came after reading Steve Sanderson’s post and watching his screencast on how he created a model-based client-side validation – very cool.

I want a simple way to perform client and server side validation for the application I am creating for my book and my objectives are simple (yet there is no easy way to do it):

  1. Have a model-based validation mechanism
  2. Have the least amount of repetition (DRY)
  3. Client side validation using jQuery
  4. Server side validation

First, I will show you how it works then I will explain how I got there.  Here is my model class for a user

   1: public class User
   2: {
   3:     public virtual string UserName { get; set; }
   4:     public virtual string Email { get; set; }
   5:     public virtual string Password { get; set; }
   6:     public virtual Guid ProviderId { get; set; }
   7: }

To add validation to it, I simply decorate it with the appropriate validation attributes.  It ends up looking like this:

public class User
{
    [ValidateNonEmpty("Username is required")]
    public virtual string UserName { get; set; }

    [ValidateNonEmpty("Email is required")]
    [ValidateEmail("Invalid email address")]
    public virtual string Email { get; set; }

    [ValidateNonEmpty("Password is required")]
    [ValidateLength(4,50,"Password should be at least 4 characters long")]
    public virtual string Password { get; set; }

    public virtual Guid ProviderId { get; set; }
}

I then generate the client script by adding 1 line of code to my view

<%=Html.ClientSideValidation("formCreateList", ViewData.Model) %>

On the server side, I simply make a call to a validation method from my controller

[Authorize]
[AcceptVerbs("POST"), ActionName("Create")]
public ActionResult Save(User newUser)
{
    AppHelper.ValidateModel(ViewData.ModelState, newUser);
    //the rest of the action code
}

If there are any validation errors on the server, I display the errors by using the framework helper method ValidationSummary.  All I have to do is add this 1 line to the view

<%=Html.ValidationSummary() %>

JavaScript

That’s all there is to it.  Now let’s talk about how it works.  The first challenge was generating the JavaScript to validate on the client. 

I decided to use the excellent jQuery Validation plugin.  The plugin gives me 2 ways to validate my form.  The first method uses classes on the the fields to be validated, for example a required email field would look like this

<input id="email" name="email" size="25"  class="required email" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The second method uses rules that are defined in JavaScript and look like this

<script type="text/javascript"> 
$("#signupForm").validate({
        rules: {
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            email: "Please enter a valid email address"
        }
    });
</script>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Check out the plugin documenation and demos to understand how it all works.

Since I was generating the script on the server and I wanted to make only one call, I went with the second option.

The script generator simply loops through all the model properties and their attributes and generate the appropriate script.  Afterthought: Now that I think about it, I could have easily generated a script to add classes to the elements using jQuery’s addClass method…  Oh well, maybe someone else will be kind enough to do it.

Castle Validator

I used the Castle Validator Component as my validation framework.  That’s where all the validation attributes you see above come from, but you can also create your own validators.  I then created a class called JQueryValidationProvider that implements IBrowserValidationGenerator interface in the Castle.Components.Validator namespace.  I haven’t implemented the entire interface and only have a couple of validations working (I will update the source code when it is all done).  Here is a couple of methods that I implemented.

public void SetEmail(string target, string violationMessage)
{
     Rules.Add(new ValidationRule(Validate.Email, violationMessage));
}
public void SetAsRequired(string target, string violationMessage)
{
    Rules.Add(new ValidationRule(Validate.Required, violationMessage));
}

As you can see, all I am really doing is just adding the validation rule to List of ValidationRules.  ValidationRule is a straight forward class and looks like this:

internal class ValidationRule
{
    public ValidationRule(Validate validate) : this(validate, null) { }
    public ValidationRule(Validate validate, string failureMessage)
        : this(validate, failureMessage, null) { }
    public ValidationRule(Validate validate, string failureMessage, object value)
    {
        Validate = validate;
        Value = value;
        if (failureMessage != null)
        {
            ErrorMessage = failureMessage;
        }
        else
        {
            //setup default error messages
            switch (Validate)
            {
                case Validate.Required:
                    ErrorMessage = "This field is required";
                    break;
                default:
                    ErrorMessage = "Field error";
                    break;
            }
        }

    }
    public readonly object Value;
    public readonly Validate Validate;
    public readonly string ErrorMessage;
}

The helper ClientSideValidation method simply loops through the collection of rules and generate the appropriate JavaScript.  Here it is

public static string ClientSideValidation(this HtmlHelper htmlHelper,
    string formName,
    object modelToValidate)
{
    var results = new StringBuilder();
    var rules = new StringBuilder();
    var messages = new StringBuilder();
    results.AppendFormat("$("#{0}").validate({1}", formName, "{");
    results.AppendLine();
    rules.AppendFormat("rules: {0}", "{");
    messages.AppendFormat("messages: {0}", "{");

    var props = TypeDescriptor.GetProperties(modelToValidate.GetType());

    var propCounter = 0;
    foreach (PropertyDescriptor prop in props)
    {
        var generator = new JQueryValidationProvider();
        foreach (var attrib in prop.Attributes.OfType<AbstractValidationAttribute>())
        {
            var v = attrib.Build();
            v.ErrorMessage = v.ErrorMessage ?? "*";
            v.Initialize(new CachedValidationRegistry(), null);
            v.ApplyBrowserValidation(null, InputElementType.Undefined,
                                     generator, null, null);
        }

        if (generator.Rules.Count > 0)
        {
            if (propCounter > 0)
            {
                rules.Append(",");
                messages.Append(",");
            }
            rules.AppendLine();
            messages.AppendLine();
            rules.AppendFormat("{0}: {1}", prop.Name.ToLower(), "{");
            messages.AppendFormat("{0}: {1}", prop.Name.ToLower(), "{");
            rules.AppendLine();
            messages.AppendLine();

            for (var i = 0; i < generator.Rules.Count; i++)
            {
                var rule = generator.Rules[i];
                rules.AppendFormat("{0}", rule.GetRuleString());
                messages.AppendFormat("{0}", rule.GetMessageString());

                if (i < generator.Rules.Count - 1)
                {
                    rules.Append(",");
                    messages.Append(",");
                }
                else
                {
                    rules.Append("}");
                    messages.Append("}");
                }
                rules.AppendLine();
                messages.AppendLine();
            }

            propCounter++;
        }
    }

    rules.Append("},");
    messages.Append("}");
    rules.AppendLine();
    messages.AppendLine();
    results.Append(rules.ToString());
    results.Append(messages.ToString());
    results.Append("});");

    return string.Format("<script type='text/javascript'><!--{1}{0}{1}--></script>", 
                            results.ToString(), Environment.NewLine);
}

Changes

Halfway through this post, I read Steve Sanderson’s new post and Stephen Walther’s new post on validation, I made some changes to the code.  I agree with their point that the controller shouldn’t be responsible for initiating the validation and it should be done at a lower layer.  I refactored the code and my controller now looks like this

[AcceptVerbs("POST")]
public ActionResult Create(User user)
{
    try
    {
        user = new User();
        UpdateModel(user, new[] { "name", "email" });
        var service = new UserService();
        service.Save(user);
    }
    catch (RuleViolationException ex)
    {
        MvcValidator.PopulateModelStateWithErrors(user, ViewData.ModelState, ex);
    }
    return View(user);
}

 

The validation gets initiated at the service (business logic) layer and if there is a rule violation an exception is thrown.  I then take the exception and pass it to a helper method that populates the model state. Note: I could probably rewrite this so that the ModelState population happens before the exception throwing which will eliminate the call to the population method.

My view looks like this

<%=Html.ValidationSummary() %>
<form id="formCreate" name="formCreate" 
        action='<%=Url.Action("Create")%>' method="post">
    <label for="name">Name</label>
    <input type="text" id="name" name="name" />
    <br />
    <label for="email">Email</label>
    <input type="text" id="email" name="email" />
    <br />
    <input type="submit" value="Submit" />
</form>
<%= Html.ClientSideValidation("formCreate", ViewData.Model) %>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Now if I try to submit the form, the client script validation runs and I get these errors

clip_image001

If you get rid of client validation and only use server validation

to submit the form, the form would look like this

clip_image001[4]

Finally, here is the client JavaScript generated in the view:

<script type='text/javascript'><!--
    $("#formCreate").validate({
        rules: {
            name: {
                required: true,
                minlength: "3",
                maxlength: "25"
            },
            email: {
                email: true,
                required: true
            }
        },
        messages: {
            name: {
                required: "Username is required",
                minlength: "Username should be between 3 and 25 characters long",
                maxlength: "Username should be between 3 and 25 characters long"
            },
            email: {
                email: "Invalid email address",
                required: "Email is required"
            }
        }
    });
--></script> 

 

Pros & Cons

Here is what I think the pros of this design are:

  1. I love using model attributes to define validation rules
  2. I like that I only need 2 lines in my view
  3. I like that I don’t have to do anything in the controller other than catch an exception and call a helper method

The one thing I don’t like about this design is that it feels like there is a lot of dependencies.  I might need to refactor the code and move things around.  Here is my dependency diagram

image

Credit

This code was possible because of other people’s work:

Stephen Walther – link

Steve Sanderson – link and link 2

Hamilton Verissimo – link

Rick Strahl – link

Scott Guthrie – link

Source Code

Click here to download the rough-quality source code.

Let me hear what you think of this design.  What’s wrong with it?  What’s right?  Should I put this up on codeplex?

Deciding Between ASP.NET MVC and WebForms

I am trying to create a decision flowchart for my ASP.NET MVC book and wanted to get some community feedback.  Does this diagram make sense?  What other factors should one consider that should make it into the chart?

image

Things to Note

I have tried to use the general consensus of the community for each decision.  For example, some might argue that MVC is better for prototyping but I would say the majority would disagree.

Keep in mind that these choices are not set in stone and are not mutually exclusive but are more like a guide to which platform would be better suited to satisfy a particular requirement.  For example you might want to use TDD but still end up choosing on WebForms.  (I should probably assign a weight to each question)

The "No" branch doesn’t mean exactly NO.  I mean, answering No to "Want cleaner HTML?" doesn’t mean you have something against clean HTML or you want crappy HTML – no one wants that.  Think of the question in terms of "is clean html important to you?" 

Let me hear your feedback below and I will incorporate it in version of 2 of the diagram and post it back on the blog.  Hopefully, this will help someone choose between ASP.NET MVC and WebForms on a new project.

Also, I don’t think a flowchart diagram is the best type of diagram for this type of decision tree.  Can you suggest a better format?

Is this Better than Constructor Injection?

So after I finished my post on property injection I thought of something, maybe I shouldn’t use constructor injection for my classes.  Maybe, I can just use lazy properties that would call my IoC (Ninject) Kernel to instantiate the object.  So instead of defining a constructor like this:

public IAccountService Service { get; set; }

[Inject]
public AccountController(IAccountService service)
{
    Service = service;
}

I could just have a property Service do the work like this:

public IAccountService Service
{
    get
    {
        return (IAccountService) Kernel.Get(typeof (IAccountService));
    }
}

If I get rid of all my constructor parameters then I won’t need to change my ControllerFactory to use the Ninject Factory.  This keeps looking better and better.

What do you think?  I keep reading everywhere that construction injection is the way to go.  But why complicate my constructor when I can have the properties do the heavy lifting?  I would love to hear what you think.

Property Injection in ASP.NET MVC with Ninject

I got a design challenge with asp.net mvc.  I want to keep track of the currently logged in user in the session because I don’t want to hit the database every time I need to get the username or id for a query.  And I have all my controllers inherit from a base controller named BaseController.  So, I added a CurrentUser property to the BaseController and I want it to automagically work without the derived controllers having to do anything.  Here is a class diagram to help clarify:

image

The CurrentUser Property needs to look something like this:

public User CurrentUser
{
    get
    {
        var key = "currentuser";
        if (Session[key] == null)
        {
            Session[key] = /*get user from database some how*/;
        }
        return (User) Session[key] ;
    }
}

This looks simple enough but it is not.  The reason it is not simple is because to get the current user I have to call Membership.Provider.GetUser from the BaseController.  The problem with that is that it creates a dependency on the MembershipProvider class which I don’t want to have, because it will make testing very hard.

One obvious solution was to add the MembershipProvider (which is an abstract class) to the BaseController’s construct and then pass a mocked instance during testing…  The problem with this design is that now my BaseController will be forced to have a parameterized constructor which means that I have to change the code in all the derived controllers to handle that and pass the appropriate instance of MembershipProvider.  Sounds like a code smell.

My solution was to create the MembershipProvider class using my IoC container – in this case, my Ninject Kernel.  This allows me to inject a SqlMembershipProvider in development and runtime and inject a mocked provider in testing.  So the final CurrentUser property looks like this:

public User CurrentUser
{
    get
    {
        var key = "currentuser";
        if (Session[key] == null)
        {
            var Provider
                = (MembershipProvider)
                    Kernel.Get(typeof(MembershipProvider));

            Session[key] = AppHelper.CreateUserFromMembershipUser
                            (Provider.GetUser(User.Identity.Name, true));
        }
        return (User) Session[key] ;
    }
}

If you have been paying attention, you are probably wondering  what is this “Kernel” thing.  Well Kernel is an instance of the Ninject Kernel which itself was injected into the BaseController class like this:

[Inject]
public IKernel Kernel { get; set; }

I could have done this differently.  For example, I could have injected the provider itself using property injection like this:

[Inject]
public MembershipProvider Provider { get; set; }

The only problem is that the provider isn’t needed by all the derived classed and I didn’t want to have a public property in the base class that would hardly be used anywhere else.   On the other hand Kernel could be globally used to instantiate an object.

What do you think?  Is this the way to do it?  Is there a better way?

Mocking and Dependency Injection in ASP.NET MVC

Here is the situation, my controller constructors take multiple interfaces as parameters.  I do this in order to use constructor injection which allows me to inject the controllers with mocked objects in my unit tests.

For example, my AccountController takes IEmailService, IFormsAuthentication and MembershipProvider (abstract class) as parameters.

During my testing, I want to mock the email, authentication and membership calls.  For example when the user calls FormsAuthentication.Login, I don’t really care if actual call succeeded but rather that my login action works appropriately in the case FormstAuthentication.Login succeeds (or fails).  I just want to mock that call.

I started off creating a few tests and slowly they have grown to several.  There was a lot of repeated code in my unit tests and to be a good citizen of the DRY universe, I needed to refactor the code.

For IoC, I initially started with StructureMap but now I am using Ninject

I created this module to bind my interfaces to mocked instances.  It looks like this:

internal class TestModule : StandardModule
{
    public override void Load()
    {
        Bind<IEmailService>()
            .ToConstant(MyMocks.MockEmailService.Object);
        
        Bind<IFormsAuthentication>()
            .ToConstant(MyMocks.MockFormsAuthentication.Object);
        
        Bind<MembershipProvider>()
            .ToConstant(MyMocks.MockMembershipProvider.Object);
        
        Bind<IContactListService>()
            .ToConstant(MyMocks.MockContactListService.Object);
    }
}

Notice that I bind the interfaces to actual instances and not classes.  These instances are declared in a global static class that will be accessed from my unit tests.  As you can tell from the name, they are all mocked objects (I am using Moq).  Here is how the MockEmailService looks (all the others are declared the same way):

internal static class MyMocks
{
    private static Mock<IEmailService> _mockEmailService;
    public static Mock<IEmailService> MockEmailService
    {
        get
        {
            _mockEmailService = _mockEmailService ?? new Mock<IEmailService>();
            return _mockEmailService;
        }
    }

 

So all this is good to setup Ninject and create my mocks.  Now I want to easily and generically create a controller, so I can quickly create unit tests.  In order to do that, I created a TestControllerFactory class that basically creates a controller with all the appropriate dependencies injected.

   1: internal static class TestControllerFactory
   2: {
   3:     private static IKernel _kernel;
   4:     public static IKernel Kernel
   5:     {
   6:         get
   7:         {
   8:             if (_kernel == null)
   9:             {
  10:                 var modules = new IModule[] { new TestModule() };
  11:                 _kernel = new StandardKernel(modules);
  12:             }
  13:             return _kernel;
  14:         }
  15:         private set
  16:         {
  17:             _kernel = value;
  18:         }
  19:     }
  20:  
  21:     public static T GetControllerWithFakeContext<T>(string httpMethod) 
  22:         where T : Controller
  23:     {
  24:         var con = Kernel.Get<T>();
  25:         con.SetFakeControllerContext();
  26:         if (con != null) con.Request.SetHttpMethodResult(httpMethod);
  27:         return con;
  28:     }
  29:  
  30: }

In line #10, I use the TestModule class mentioned above to setup the Ninject Kernel.  In lines #21 to #28, I create an instance of T which must be of type Controller from the Kernel which will automatically create the Controller with all the mocked objects.  In line #25 and #26, I just set a fake/mocked context and the Http Method for the request (more info here).

Now my unit tests are very clean and easy to setup.    Using MbUnit as my unit test framework, here is a unit tests that tests the reset password functionality.

   1: [Test]
   2: public void ResetPasswordQuestion_Should_Send_Email_On_Success()
   3: {
   4:     var newpassword = "newpassword";
   5:     MyMocks.MockMembershipProvider
   6:          .Expect(p => p.ResetPassword(username, answer))
   7:          .Returns(newpassword);
   8:     MyMocks.MockEmailService
   9:          .Expect(m => m.SendPasswordReset(username, newpassword));
  10:  
  11:     var ac = TestControllerFactory
  12:                 .GetControllerWithFakeContext<AccountController>("POST");
  13:  
  14:     var results = ac.ResetPasswordQuestion(username, question, answer);
  15:     //write some asserts in here to make sure things worked
  16:  
  17:     //verify all mocks
  18:     MyMocks.MockMembershipProvider.VerifyAll();
  19:     MyMocks.MockEmailService.VerifyAll();
  20: }

Line #5: I mock the ResetPassword call on the membership provider and tell it to return the new password

Line #8: I mock the SendPasswordReset method on the email service

Line #11: Get an instance of AccountController from the Ninject Kernel

I just write some code to make sure the expected results took place and that my mocks were properly exercised and that’s pretty much it.  No need to have an SMTP server working to test this, no need to have a database, no need to have an authentication method, no need to implement the interfaces or write dummy methods.

I am like a kid in a candy store with all these things: mocking, dependency injection, inversion of control, unit testing…  I am loving it.

So what do you think?  Is this a good way to go about it?  Is there a better way and what is it?

Ninject: Killer IoC

In my previous post, The Best IoC Container, I decided to go with StructureMap as the framework of choice.  I received a comment telling me to check out Ninject and then a day or two after, I saw Corey Gaudin’s post on using Ninject with MVC, so I decided to try it out.

It wasn’t too hard to get up and running in asp.net mvc.  Corey’s post was a good starting point but I was too lazy to type all his code in, I wrote my own.  It was pretty easy to get Ninject to work.

I basically created a NinjecteControllerFactory class that inherits from the DefaultControllerFactory and overrode a couple of methods.  The class looks like this:

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel _kernel;
    public NinjectControllerFactory(params IModule[] modules)
    {
        _kernel = new StandardKernel(modules);
    }

    protected override IController GetControllerInstance(Type controllerType)
    {
        return _kernel.Get(controllerType) as IController;
    }
}

 

Then in my Gloval.asax.cs file, I called this code to setup Ninject.

IModule[] modules = new IModule[] { new WebModule() };
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(modules));

 

The WebModule module has my configuration and looks like this:

public class WebModule : StandardModule
{
    public override void Load()
    {
        Bind<IAppService>().To<AspAppService>();
        Bind<IEmailService>().To<EmailService>();
        Bind<IContactService>().To<ContactService>();
        Bind<IContactRepository>().To<SqlContactRepository>();
        Bind<IFormsAuthentication>().To<FormsAuthenticationWrapper>();
        Bind<MembershipProvider>().ToConstant(Membership.Provider);
    }
}

 

Of course, you can create as many modules as you want to configure your application and pass them in the controller Factory.

This code was working fine for me and then Nate Kohari mentioned that there is a Ninject.Framework.Mvc extension that allows me to easily integrate Ninject into the MVC pipeline.  So, I decided to download the code, build it and use it.  I initially had some issues because it was referencing a different version of the core dll, so I had to rebuild that as well.

I changed my Global.asax.cs file to the following:

public class GlobalApplication : NinjectHttpApplication
{
    protected override void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
    }

    protected override IKernel CreateKernel()
    {
        IModule[] modules = new IModule[] { new AutoControllerModule(Assembly.GetExecutingAssembly()), new WebModule() };
        return new StandardKernel(modules);
    }
}

Initially I was getting errors when navigating to an injected controller, which was fixed by add the AutoControllerModule to my modules and passing it the current assembly.

So far Ninject is looking great, the API is fluent and very discoverable and the contextual binding is very slick.  So I am going to stick with it for now and see how it goes.  The documentation seems pretty good and the Nate is very responsive in the Google Group.