Wednesday, August 13, 2014

Why are my form values being cached after the first POST?

Here is the controller source code:

and here is the view code:

Run the code and submit the form. Notice after the first submit, the value in the textbox will change from 0 to 1. Upon subsequent POST’s though, that value won’t change from 1. Why is that?

I ran into this oddity earlier today and did some research, but it wasn’t until a colleague of mine found a key bit of knowledge that the puzzle was solved. During my findings, I noticed many people trying to solve “form values cached after POST” by setting the attribute autocomplete=”off”. Specifically that attribute is placed on the <input>, or even the <form> (due to how different browsers handle this attribute, you may need to place it on <form>, since it may not work otherwise). However in my case, regardless of there being an autocomplete attribute on my <form>, the form values were still cached. Huh?

As a plan B, I tried the following view instead:

This time, when I POST the form, the textbox value increments as expected – 0, 1, 2, 3… etc. So why does this work, whilst using the HTML helper method TextBoxFor resulted in cached values? It’s all to do with ModelState.

When Html.TextBoxFor() (or Html.TextBox()) executes, it merges values from the ModelState back into the view. It does this so that if there is a validation error, the value causing the error is rendered on the page. In other words, the old value is used, not the new value that is passed from the action method. This was very confusing at first, but if you think about it, it does make sense. If this did not happen, then you’d get validation errors shown, but with the wrong values being highlighted as the problem.

You can get around this by removing a value from ModelState:

In the above example, “Number” will no longer be merged from ModelState when the view is rendered.

Saturday, June 14, 2014

Unit Test Object Builder – Enter the Expando!

Whilst reading the rather brilliant book Growing Object-Oriented Software, Guided By Tests, I saw an interesting example of using a builder pattern for creating object instances. Here’s a example:

Customer customer = new CustomerBuilder().WithFirstName(“John”).Build();

A builder object can take care of initializing object instances, or even create a list of those object instances. Take a look at nBuilder for an example of a great framework that does just that. What caught me out was the method “WithFirstName”. Interesting; the property “FirstName” appears in the method name. Previously I had seen objects initialized similar to the following

Customer customer = Builder<Customer>.CreateNew().With(c => c.FirstName = "John").Build();

This got me thinking – having just played around with ExpandoObject I decided to have a got at replicating the CustomerBuilder seen in the Growing Objects book. Here’s my attempt:

public static class ObjectChauffeur
{
    public static dynamic Create<T>()
    {
        var result = new ExpandoObject() as IDictionary<string, object>;

        var targetType = typeof(T);

        var targetInstance = Activator.CreateInstance<T>();

        PropertyInfo[] properties = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var prop in properties)
        {
            Func<object, object> targetAction = (param) =>
            {
                prop.SetValue(targetInstance, param, null);

                return result;
            };

            result.Add(string.Concat("With", prop.Name), targetAction);
        }

        CreateBuildFunciton(result, targetInstance);

        return result;
    }

    private static void CreateBuildFunciton<T>(IDictionary<string, object> expando, T instance)
    {
        Func<T> buildFunc = () => instance;

        expando.Add("Build", buildFunc);
    }
}

Before I explain what’s going on, this sample illustrates how to use the above class. First, let’s create a Person object:

public class Person
{
    public int Age { get; set; }

    public string FirstName { get; set; }

    public IList<int> Numbers { get; set; }

    public string Surname { get; set; }

    public override string ToString()
    {
        return string.Concat(this.FirstName, " ", this.Surname, " is ", this.Age);
    }
}

Now, let’s get the chauffer to build an instance of Person:

Person person = ObjectChauffeur.Create<Person>()
    .WithFirstName("Jason")
    .WithSurname("Evans")
    .WithAge(36)
    .WithNumbers(new List<int>() { 1, 2 })
    .Build();

Review the ObjectChauffer class and, specifically, look at the method Create<T>(). It basically uses reflection to iterate through all the public properties of the type T. For each property name the word “With” is prepended. Finally, since ExpandoObject implements IDicitonary<string, object>, we can add the property name and it’s value to an internal dictionary that is returned as the dynamic object.

Admittedly this isn’t the most practical “helper” class ever built, certainly the lack of intellisense when you start typing “With”, and not knowing property names of the target type off hand, will be annoying. But hey, I thought it was an interesting experiment at least.

Saturday, June 07, 2014

Access XML data using ExpandoObject

I haven’t dabbled much with any of the dynamic features available in the .NET Framework, but I recently came across this very handy technique of using ExpandoObject to iterate, and access, XML data a lot cleaner. Let’s use the following XML

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <FirstName>Jason</FirstName>
  </Employee>
  <Employee>
    <FirstName>Mark</FirstName>
  </Employee>
</Employees>

Using an XDocument, we would need to write the following code to iterate through each employee

var doc = XDocument.Load("XmlFile1.xml");

foreach (var element in doc.Element("Employees").Elements("Employee"))
    Console.WriteLine(element.Element("FirstName").Value;

This is how I, and I assume many other devs, have gone about accessing XML data inside an XDocument. So here’s a neater way – an extension method that will do the hard work for us

public static class ExpandoXml
{
    public static dynamic AsExpando(this XDocument document)
    {
        return CreateExpando(document.Root);
    }

    private static dynamic CreateExpando(XElement element)
    {
        var result = new ExpandoObject() as IDictionary<string, object>;

        if (element.Elements().Any(e => e.HasElements))
        {
            var list = new List<ExpandoObject>();

            result.Add(element.Name.ToString(), list);

            foreach (var childElement in element.Elements())
                list.Add(CreateExpando(childElement));
        }
        else
        {
            foreach (var leafElement in element.Elements())
                result.Add(leafElement.Name.ToString(), leafElement.Value);
        }

        return result;
    }
}

Taking in an XDocument, the extension method will iterate through all the XElements, and each child element of those, building up a hierarchy of ExpandoObjects. This provides us the ability to access the XML like so

 var doc = XDocument.Load("XmlFile1.xml").AsExpando();

 foreach (var employee in doc.Employees)
     Console.WriteLine(employee.FirstName);

That looks much better.

Tuesday, February 07, 2012

Example of Builder Design Pattern

I happened to come across an interesting idea from a Java blogger regards the Builder design pattern. For those of you who are not familiar with this pattern, check out the Wikipedia explanation. Check out this code:

    public class Address
    {
        public string Protocol { get; set; }
        public string Description { get; set; }
        public int Port { get; set; }
        public string Path { get; set; }
        public string Url { get; set; }

        private Address(AddressBuilder addressBuilder)
        {
            this.Protocol = addressBuilder._protocol;
            this.Url = addressBuilder._url;
            this.Port = addressBuilder._port;
            this.Path = addressBuilder._path;
            this.Description = addressBuilder._description;
        }

        public interface IBuild
        {
            Address Build();
            IBuild Description(string description);
            IBuild Path(string path);
            IBuild Protocol(string protocol);
        }

        public interface IPort
        {
            IBuild Port(int port);
        }

        public interface IUrl
        {
            IPort Url(string url);
        }

        public static IUrl Builder()
        {
            return new AddressBuilder();
        }

        public class AddressBuilder : IUrl, IBuild, IPort
        {
            public string _description;
            public string _path;
            public int _port;
            public string _protocol;
            public string _url;

            public Address Build()
            {
                return new Address(this);
            }

            public IBuild Description(string description)
            {
                this._description = description;
                return this;
            }

            public IBuild Path(string path)
            {
                this._path = path;
                return this;
            }

            public IBuild Port(int port)
            {
                this._port = port;
                return this;
            }

            public IBuild Protocol(string protocol)
            {
                this._protocol = protocol;
                return this;
            }

            public IPort Url(string url)
            {
                this._url = url;
                return this;
            }
        }
    }

Now there’s a lot going on here, but lets see what the above code allows us to do:

var address = Address.Builder()
    .Url("ddd")
    .Port(23)
    .Build();

We can build an Address instance using the Builder pattern, which has this nice fluent API to it. The key idea is that, since port and url are mandatory fields, we have designed the builder in such a way that those fields must be given a value before the “Build()” method can be called. If you look at the code you’ll see that this is achieved by having a nested “Builder” class that implements private interfaces associated with the Address object. The method “Address.Builder()” returns a new Builder instance via the IUrl interface. That interface has a “Port” method which must be called. The Port method returns an IBuild interface which has the “Build()” method which will actually create the Address instance.

Have a play around with this code, I think it’s a very nice way to create objects whilst making it clear which properties are mandatory.

Monday, November 21, 2011

The Agile Testing & BDD eXchange 2011

Check out these videos taken from the recent The Agile Testing & BDD eXchange. You'll find talks on topics such as:

- BDD
- Living Documentation
- Testing

I know what I'll be watching tonight :) (Coffee? (Check), Biscuits? (Check), Slippers? (Check))

Sunday, November 20, 2011

KnockoutJS 1.3 Almost Here

For those of you who are fans of Steve Sanderson’s excellent MVVM (Model View View Model) framework KnockoutJS, you'll be pleased to hear that the release candidate for version 1.3 is now available. There are a number of improvements including better syntax for defining event handling (a popular fix for many people who felt that the current method of event binding was a bit messy).

Check out this blog article by Steve, which talks about the upcoming changes.

Saturday, November 19, 2011

Using MSpec.Fakes–Part 2

Next example I’d like to show is how to force a method to return a specific value:

public class example_when_told_to : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () =>
        {
            sut = An<IHelper>();
            sut.WhenToldTo(s => s.OK(Arg<int>.Is.Anything)).Return(4567);
        };

    private Because of = () => result = sut.OK(1);

    private It should_be_4567 = () => result.ShouldEqual(4567);
}

Here I use ‘WhenToldTo()’ in order to control the return value of ‘OK()’. I could also do this:

public class example_when_told_to : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () =>
        {
            sut = An<IHelper>();
            sut.WhenToldTo(s => s.OK(23)).Return(4567);
        };

    private Because of = () => result = sut.OK(23);

    private It should_be_4567 = () => result.ShouldEqual(4567);
}

So when ‘OK()’ is called with a specific argument, in this case 23, I want to return the value 4567. OK, so let’s have a look at using the ‘WithSubject’ parent class. First, we need the code for the salary calculator which Helper is using:

public interface ISalaryCalculator
{
    double CalculateSalary(double baseSalary, double bonus);

    int GetValue();
}

public class SalaryCalculator : ISalaryCalculator
{
    public double CalculateSalary(double baseSalary, double bonus)
    {
        return baseSalary + bonus;
    }

    public int GetValue()
    {
        return 34;
    }
}

Now here is the example test class we’ll be referencing:

public class example_using_WithSubject_1 : WithSubject<Helper>
{
    private static int result;

    private Establish context = () => The<ISalaryCalculator>().WhenToldTo(x => x.GetValue()).Return(1);

    private Because of = () => result = Subject.OK(1);

    private It should_be_1 = () => result.ShouldEqual(1);
}

We’re using WithSubject and passing it the type of Helper. What this give us is a .Subject property that we can use to access the SUT (i.e. the instance of Helper). The other cool thing is that since Helper requires an implementation of ISalaryCalculator in it’s constructor, an instance of ISalaryCalculator will be created for us. Not only that, but we can control the behaviour of the ISalaryCalculator instance via the ‘The<>’ method.

In the above example I’m stating that when ISalaryCalculator.GetValue() is called, it should return 1. We can also verify calls against the ISalaryCalculator like this:

public class example_using_WithSubject_2 : WithSubject<Helper>
{
    private static int result;

    private Because of = () => result = Subject.OK(1);

    private It should_be_1 = () => The<ISalaryCalculator>().WasToldTo(x => x.GetValue());
}

That’s all for now. I might write a bit more about using Stubs in your MSpec.Fakes tests for part 3.