Archive for November, 2009

Google Frame to save the day 0

madmen_icon

When they announced Google Frame I was really puzzled. Why? Who would actually want to use IE so badly they would install this? Why not just use the super sexy Chrome and all its goodness?

It finally hit me when today we found a rendering discrepancy on our intranet between IE and the rest of the universe. Ugh! We’re going to hack this thing to get it to work for the three people that want to use IE.

Wait. There is a masked superhero that will save the day. Google Frame!

I have to add one line to my page:

<meta http-equiv="X-UA-Compatible"
         content="chrome=1">

install the plug-in and I’m done! It looks beautiful. The best part is no more sludge and crime in our CSS. Google Frame can clean it all up and prevent any future offenses.

Are extensive extension method an anti-pattern 0

I was explaining my dilemma to a Java friend and the e-mail ended up being fairly interesting, so I thought I would share it.

I’m sure Java has extension methods, but I’ll give it a once over just in case.  You can extend existing classes without sub-classing by extension methods.

public static IEnumerable<SelectListItem>
                            AsSelectListItems( this IEnumerable<Person> listOfPeople){
   IList<SelectListItem> selectListItems = new List
();
   foreach(var person in listOfPeople){
      selecListItems.Add(new SelectListItem(person.ID,
					    string.Format("{0} {1} {2}",
                                                          person.First,
                                                          person.Middle,
                                                          person.Last));
   }
   return selectListItems;
}

Right. So the this operator tells the compiler to basically create this function:

public static IEnumerable<SelectListItem>
                           AsSelectListItems(IEnumerable<Person> listOfPeople);

And invoke it every time you see this:

IEnunerable<Person> p = myService.GetAllPeople();
IEnumerable<SelectListItem> s = p.AsSelectListItems();

You probably knew all this, but it explains how we are using them. We end up calling a lot of extension methods off other extension methods.

myViewData.PersonSelectListItems = myService.GetAllPeople()
                                                   .AsSelectListItems()
                                                   .OrderedByText()
                                                   .StartingWithAnEmptyItem();

In this example we have three extension method calls and I think it really makes the code much more readable, but it makes testing this code a little more difficult. Obviously, the myService is a mocked dependency which will return a fake list of people, but the other extension method calls cannot be mocked, and the scope of the test bleeds a bit.

I like the syntax it gives, but now I’m going to test potentially four classes when I should be testing only one.

This gets pretty pandemic in our code. Especially trying to make Selenium’s API and the assertion API of Nunit and xUnit more fluent.

Data Annotation Validation of More Complicated Rules 0

Using Data Annotation validation is great. It’s simple. It’s declarative. It’s fine and dandy if all you need to validate is simple, single property rules.

[Required]
public string FirstName {get;set;}

The problem is, we are never that fortunate to only have simple rules like that. Even rules only slightly more complex made me scratch my head at first. For example, take the following rule:

If the address is inside the United States, then State is required.

Simple enough, but how to do it with Data Annotation. Initially I decided not to validate this rule via annotation and did something like the following in my controller action.

var additionalErrors = MyViewData.ValidateAddress(dataFromMyForm);
foreach (var errorInfo in additionalErrors)
{
    ModelState.AddModelError(errorInfo.PropertyName, errorInfo.ErrorMessage);
}

That works and all, but it feels really sloppy. Not only does it feel sloppy, but now my model validation lives in two places; the model binder and the controller action. Yuck! And what’s even worse, is I have to consider the model validation in my tests for that controller action.

It would be better to do the validation via a custom validation attribute, but how to do that on the class? First let’s create a custom validation attribute.

public class UsaAddressRequiresStateAttribute : ValidationAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return "State is required.";
    }

    public override bool IsValid(object value)
    {
        var address = value as IAddress;
        if (address == null) return true;
        if (address.Country == "United States")
           return !string.IsNullOrEmpty(address.State);
        return true;
    }
}

Pretty simple right? And don’t worry. We’re not actually using "United States" in our production application. Now, decorate the class with that attribute.

[UsaAddressRequiresState]
public class MyViewData : IAddress {
}

In my particular case, my view data class implements IAddress, which lets me name my view data address fields whatever they want and still expose them to the validator. The limitation with this method is you can only validate one address on each form. There is surely a better way to do this, but I didn’t need to discover it right now.

That’s it. The model binder will now check that validation when binds the model and we’ll see the errors in the model state. if you want the to appear in JavaScript if you do client side validations, I suggest you check you the Phil Haack post about custom validation.

Type Safe Unit Testing of Data Annotations Validations 0

We’re using the Data Annotations Validators in ASP.Net MVC 2.0, but there wasn’t a really great way to unit test them. I’ve read Brad Wilson’s blog post about how to set them up and unit test them, but I didn’t like how you relied on the name of the property as a string.

// Arrange
var propertyInfo = typeof(Contact).GetProperty("FirstName");

It would be nicer if that used lambda expressions to get the name of the property, so I set out to do just that. Before we begin, I need to remind you, as always, I don’t know what I’m doing. This is my first tiny venture into expression trees so it is possible isn’t the best way to do things, but so far, it’s working for me.

I created a base Specification to wrap up a lot of the messy bits of getting property names by lambdas. I took a look at how the ASP.Net MVC helpers did it and roughly followed their pattern.

public class DataAnnotationSpecification<T> : Specification
{

    public PropertyInfo Property(Expression<Func<T,object>> op)
    {
        return Property(GetInputName(op));
    }

    public PropertyInfo Property(string propertyName)
    {
        return typeof (T).GetProperty(propertyName);
    }

    public static string GetInputName<TProperty>(Expression<Func<T, TProperty>> expression)
    {
        // not sure I totally understand this
        if (expression.Body.NodeType == ExpressionType.Convert)
        {
            var ue = (UnaryExpression)expression.Body;
            return GetInputName((MemberExpression) ue.Operand );
        }

        if (expression.Body.NodeType == ExpressionType.MemberAccess)
        {
            return GetInputName((MemberExpression)expression.Body);
        }
        throw new NotImplementedException();
    }

    private static string GetInputName(MemberExpression memberExpression)
    {
        return memberExpression.Member.Name;
    }

}

I know this probably doesn’t cover an exhaustive list of expressions, but we’re only talking about Property access tests here so we’re probably in the clear.

To make things a bit nicer, I also created some extensions off PropertyInfo to help setup their assertions.

public static class AttributeAssertions
{

    public static void ShouldNotBeRequired(this PropertyInfo @this)
    {
        @this.ShouldNotHaveAttribute<RequiredAttribute>();
    }

    public static void ShouldBeRequired(this PropertyInfo @this)
    {
        @this.ShouldHaveAttribute<RequiredAttribute>();
    }

    private static T PropertyAttributeOn<T>(ICustomAttributeProvider propertyInfo)
    {
        return propertyInfo.GetCustomAttributes(typeof (T), false)
            .Cast<T>()
            .FirstOrDefault();
    }

    public static void ShouldHaveAttribute<T>(this PropertyInfo @this)
    {
        PropertyAttributeOn<T>(@this).ShouldNotBeNull();
    }
    public static void ShouldNotHaveAttribute<T>(this PropertyInfo @this)
    {
        PropertyAttributeOn<T>(@this).ShouldBeNull();
    }
}

We only have the ShouldBeRequired and ShouldNotBeRequired right now, but you could see it will be easy to extend upon them.  The finished spec looks something like this.

public class When_testing_the_state_of_the_CustomerViewData
    : DataAnnotationSpecification<CustomerViewData>
{
    [Then] public void the_customer_first_name_is_required()
    {
        Property(x => x.CustomerFirstName).ShouldBeRequired();
    }

    [Then] public void the_customer_middle_name_is_not_required()
    {
        Property(x => x.CustomerMiddleName).ShouldNotBeRequired();
    }

    [Then] public void the_customer_last_name_is_required()
    {
        Property(x=>x.CustomerLastName).ShouldBeRequired();
    }

    [Then] public void the_email_address_is_required()
    {
        Property(x=>x.CustomerEmailAddress).ShouldBeRequired();
    }

}

That’s not so bad, and it stands up to any refactoring we might do.

There is no ViewData item of type ‘IEnumerable<SelectListItem>’ that has the key ‘myProperty’. 1

While figuring out the ASP.Net MVC 2.0 Preview 2 Expression HtmlHelpers (that’s a mouthful), I ran into this error a couple times. It didn’t make any sense to me because there shouldn’t be ViewData item with the key “MyProperty” with that type.

It turns out I was doing this:

<%= Html.DropDownListFor(x=>x.MyProperty, Model.AllMyPropertyListItems) %>

It throws this exception when AllMyPropertyListItems is null.

Replacing Rhino with Moq 2

We’re just starting down the path of serious and extensive testing with mocks and fakes. Our initial tests were all done using Rhino Mocks, mostly because it had a well established reputation and we had no reason not to give it a try. The syntax is beautiful and did everything we needed, until we tried to make a test similar to this one pass successfully.

public interface IFoo
{
    string Bar();
}

[Fact] public void TestWithRhino()
{
    var mock = MockRepository.GenerateStub<IFoo>();
    mock.Stub(x => x.Bar()).Return("bar");
    mock.Stub(x => x.Bar()).Return("baz");
    Assert.Equal("baz",mock.Bar());
}

We couldn’t, at least we couldn’t using strictly stubs. From what I could gather, we could if we used a more complicated for of mocking besides stubs. We only need stubs, or fakes, because we don’t need to test all the interaction, just the ending state.

Since we don’t have any serious stock in using Rhino, as an alternative I decided to take a look at using Moq. The syntax for Moq is not as nice. It is more wordy, but I do like how it doesn’t rely on extensions methods for everything. But what about the sample test?

[Fact] public void TestWithMoq()
{
    var mock = new Mock<IFoo>();
    mock.Setup(x => x.Bar()).Returns("bar");
    mock.Setup(x => x.Bar()).Returns("baz");
    Assert.Equal("baz", mock.Object.Bar());
}

It passes! Switching wasn’t that difficult, but where is the ugly syntax I‘ve run into so far? Well this in Rhino:

MockOrdersRepository.AssertWasNotCalled(x=>x.StartOrder(null,null,null,null));

…becomes this in Moq:

MockOrdersRepository   .Verify(x=>x.StartOrder( It.IsAny<string>(),                            It.IsAny<string>(),                            It.IsAny<string>(),                            It.IsAny<string>()),              Times.Never());

It might be I am not familiar enough with either to say that is the equivalent assertion of both, but it is working for us. I am probably missing something that is causing Moq to look more verbose.

Flickr Paging Oddities 0

It might have always been this way, but Flickr is making some odd choices when paging their photos. As you can see in the screenshot, it stacks the photos in three columns, but only completely fills the first two, leaving an empty slot in the last column.

image

I’ve tried this with several different searches, different ordering, etc, and it appears to be random. Sometimes it completely fills up the grid, sometimes it leaves one space, sometimes it leaves two. The first time I saw it, I thought my search only brought up one page of result, but then saw the pager at the bottom, along with the number of results.

I don’t know what they are thinking, but it’s odd. At least to me.

Testing when ModelState is invalid. 0

As a follow up to my previous post, testing when ModelState is relatively simple, but leaves me feelings a little uneasy about my tests.

Here is an example tests, stripped down to remove some of the unnecessary bits

public class When_submitting_lead_data_that_is_in_an_invalid_state : Specification
{
    // class fields...etc

    protected override void Given()
    {
        base.Given();
        _mockOrdersRepository = MockRepository.GenerateStub<IOrdersRepository>();
        _checkoutController = new CheckoutController(_mockOrdersRepository);

        _leadDataWithEmptyPlanName = new PreCheckoutViewData();

        // add an error to the model state
        _checkoutController.ModelState.AddModelError("", "");

        _exceptionWasThrown = false;
    }

    protected override void When()
    {
        base.When();
        try
        {
            _checkoutController.Checkout(_leadDataWithEmptyPlanName);
        } catch(ArgumentNullException)
        {
            _exceptionWasThrown = true;
        }
    }

    [Then] public void an_exception_is_thrown()
    {
        _exceptionWasThrown.ShouldBe(true);
    }
}

This feels pretty loose to me, but there can be another tests that tests which states the model will appear invalid.

ModelState.IsValid is always true 2

We ran into a snag with using the new default Data Annotations Validation in ASP.Net MVC 2.0 Preview 2. Maybe it isn’t a snag, but it is not the behavior I would have expected.

Take the following model:

public class Person
{
  public string ID { get; set; }

  public string FirstName { get; set; }
  public string LastName { get; set; }

  [Required (ErrorMessage = "Required")]
  public string EmailAddress { get; set; }
}

Pretty straight forward, but if you post this form:

    <form action="/person/edit" method="post">
        <input type=hidden name="id" id="id" value="" />
        <input type="text" id="firstname" name="firstname" /> 
        <input type="text" id="lastname" name="lastname" /> 
        <input type="submit" />
    </form> 

To this controller action:

[HttpPost] public virtual ActionResult Edit(Person data)
{
   if (!ModelState.IsValid) throw new ItBrokeException();
   return View();
}

Personally, I would expect every post of that form to show up as invalid, but infact, it is always true. Add the following input to the form and it works.

   <input type="text" id="emailaddress" name="emailaddress" /> <br/>

After that, the ModelState.IsValid returns false, like it should.

Pay no attention to the magic behind the curtain with Cassini 0

Cassini can be very misleading. For example, spin up web site that uses routing in Cassini and it works without a problem. Do you have to add the routing module or handler? Nope. It just works. It’s so nice and helpful, but that really gives you a false sense of security.

IIS is not so nice. We recently ran into this where things worked great in Cassini, but as soon as they were deployed to IIS, nothing routed. It turns out we were missing a bit in the web.config that enabled routing.

I just stole that section from a newly created MVC 2.0 application’s web.config.

Next Page »