Concurrent Sessions in MVC2

September 21st, 2010 by David Bending No comments »

There’s lots of rules that control how many concurrent connections you can have in an ASP.net MVC2 application.

Firstly the browser itself limits the number of connections it will make to the same domain.  The limit used to be 2 (as per the HTTP specification).  Some browsers increase this limit, but older browsers like IE6 will still stick to it.

Secondly you have the number of threads available in IIS to content with.  Thomas Masquardt’s Blog gives a very detailed explanation of this.

Finally MVC itself has some limitations. Basically you can only have a single request using a read-write session at any given time.  This means that if you have a controller serving up images, and you don’t take any steps to avoid the problem, you will only ever serve up one image at a time.  Imran Baloch’s Blog gives a lot more information about this and shows how to create session-less actions to avoid the issue.  For me the solution is quite simple.  By placing the following code in Global.asax.cs:

protected void Application_BeginRequest()
{
    if((Request.Url.AbsoluteUri.ToUpperInvariant().Contains("REFRESHPRICES")
        && Request.Cookies["ASP.NET_SessionId"] != null))
    {
        Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);
    }
}

I can make the session for my action read-only, and sidestep the limit.

Warning

Just marking the session sate as read-only doesn’t prevent you from trying to modify the session.  It’s up to you to maintain thread-safety if you decide to lie to the framework.

Share

MVC2 Cross Field Validation

August 10th, 2010 by David Bending 6 comments »

Introduction to Validation

Nearly all web applications require some form of validation. Validation performs two main purposes: helping the user to enter correct values on a web page, and protecting the application from invalid or malicious input.

Validation can take place client-side within the browser, or server-side when the page is posted to the server. ASP.NET MVC2 comes with a flexible framework for applying validation using data annotations on the view model. Scott Gu has written an excellent tutorial on basic MVC validation here: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx.

Limitations of Built-in MVC Validation

The built-in validation works well for standard scenarios, but there are a few common scenarios it can’t cope with. One of the main issues is that validation can only be done on a model property in isolation. Often we will want to validate a property based on the current value of some other property: for instance we may want our confirm password field value to be the same as the password box.

In this article we will extend the MVC validation framework to provide support for cross-field validation. We’ll do this in part by creating custom validation attributes as described in Phil Haack’s article (http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx) but we’ll also need to extend the validator framework to allow us to validate across fields.

Extending the Framework to Support Cross-Field Validation

To create a custom validation attribute we usually derive from ValidationAttribute and override the IsValid method, however IsValid only gets passed the value of the property to validate and we are going to need to see the value of other fields in the model. To accommodate this we’ll create an interface ICrossFieldValidationAttribute that has an IsValid method with access to the entire view model (note these code snippets only show significant lines – download the example solution to get the whole files):

public interface ICrossFieldValidationAttribute
{
    bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata);
}

Next we build a base class for cross-field validators. This base class uses the extended IsValid defined above, rather than the narrower method used in the framework’s DataAnnotationsModelValidator class.

public abstract class CrossFieldValidator<TAttribute> : DataAnnotationsModelValidator<TAttribute>
        where TAttribute : ValidationAttribute, ICrossFieldValidationAttribute
{
    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        var attribute = Attribute as ICrossFieldValidationAttribute;

        if (!attribute.IsValid(ControllerContext, container, Metadata))
        {
            yield return new ModelValidationResult {Message = ErrorMessage};
        }
    }
}

Building the Validation

Now that we have a cross-field validation framework in place, we can build our new attribute.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EqualToPropertyAttribute : ValidationAttribute, ICrossFieldValidationAttribute
{
    public string OtherProperty { get; set; }

    public bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata)
    {
        var propertyInfo = model.GetType().GetProperty(OtherProperty);
        var otherValue = propertyInfo.GetGetMethod().Invoke(model, null);

        if (modelMetadata.Model == null) modelMetadata.Model = string.Empty;
        if (otherValue == null) otherValue = string.Empty;

        return modelMetadata.Model.ToString() == otherValue.ToString();
    }
}

And apply it to the view model:

public class Account
{
    public string Password { get; set; }

    [EqualToProperty(OtherProperty = "Password")]
    public string ConfirmPassword { get; set; }
}

We also need to create a validator class to emit the correct client-side rules, and to invoke the IsValid method.

public class EqualToPropertyValidator : CrossFieldValidator<EqualToPropertyAttribute>
{
    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "equaltoproperty",
            ErrorMessage = Attribute.FormatErrorMessage(Metadata.PropertyName),
        };

        rule.ValidationParameters.Add("otherProperty", Attribute.OtherProperty);

        return new[] { rule };
    }
}

Finally we need to create a JavaScript function to evaluate the rule client-side:

jQuery.validator.addMethod("equaltoproperty", function (value, element, params) {
    if (this.optional(element)) {
        return true;
    }

    var otherPropertyControl = $("#" + params.otherProperty);
    if (otherPropertyControl == null) {
        return false;
    }

    var otherPropertyValue = otherPropertyControl[0].value;
    return otherPropertyValue == value;
});

function testConditionEqual(element, params) {
    var otherPropertyControl = $("#" + params.otherProperty);
    if (otherPropertyControl == null) {
        return false;
    }

    var otherPropertyValue;
    if (otherPropertyControl[0].type == "checkbox") {
        otherPropertyValue = (otherPropertyControl[0].checked) ? "True" : "False";
    } else {
        otherPropertyValue = otherPropertyControl[0].value;
    }

    return otherPropertyValue == params.comparand;
}

And the final step is to register our new attribute with MVC. We do this in Global.asax Application_Start method like this:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EqualToPropertyAttribute),
                                                      typeof(EqualToPropertyValidator));
 

Example

The example code is here CrossFieldValidation.

Share

Exception in WCF Service (HRESULT: 0×80131045)

August 2nd, 2010 by David Bending No comments »

I couldn’t understand why I could call my WCF service from WcfTestClient, but when I hit it with integration tests built using the unit test framework I got this message:

Test method Lookup.IntegrationTests.HttpLabelTests.GetLabel threw exception:
System.ServiceModel.ProtocolException: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '<html>
    <head>
        <title>Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Common' or one of its dependencies. Strong name signature could not be verified. &nbsp;The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)</title>
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Lucida Console";font-size: .9em}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandabl'. ---> System.Net.WebException: The remote server returned an error: (500) Internal Server Error.

The answer is CodeCoverage.  By default Visual Studio 2010 tries to measure coverage for every assembly in the service bin.  To avoid the problem turn this off, and add coverage for each assembly you are interested in individually.

Share

Removing types from Unity in unit tests

April 27th, 2010 by David Bending No comments »

Calling teardown on the UnityContainer doesn’t remove a registration from Unity.  Here’s how to unit test code that resolves a type configured by RegisterInstance rather than configuration.  IoC is a thin wrapper around the UnityContainer.

        private ControllerContext _controllerContext;
        private ModelMetadata _modelMetadata;
        private Proposer _proposer;
        private ILookup _lookup;
        private LifetimeManager _lifetimeManager;

        [TestInitialize]
        public void SetupTest()
        {
            _controllerContext = new ControllerContext();
            _modelMetadata =
                ModelMetadataProviders.Current.GetMetadataForType(() => _proposer.AcceptedTerms, typeof (bool));
            _proposer = new Proposer();
            _lifetimeManager = new ContainerControlledLifetimeManager();
            _lookup = MockRepository.GenerateStrictMock<ILookup>();
            IoC.UnityContainer.RegisterInstance(typeof(ILookup), _lookup, _lifetimeManager);
        }
        [TestCleanup]
        public void VerifyExpectations()
        {
            _lifetimeManager.RemoveValue();
            _lookup.VerifyAllExpectations();
         }       
        [TestMethod]
        public void ErrorMessageIsCorrectlyGenerated()
        {
            var target = new NotDefaultIfAttribute("test/notDefaultIf")
            {
                OtherProperty = "Surname"
            };
            _lookup.Expect(l => l.GetLabel("test/notDefaultIf")).Return("Blah blah {0} blah");
            Assert.AreEqual("Blah blah AcceptedTerms blah", target.FormatErrorMessage("AcceptedTerms"));
        }

Share

Brown M&M’s and Coding Standards

March 2nd, 2010 by David Bending No comments »

I've been doing more work on running coding dojos and as part of that I've been thinking about compliance to published coding standards and what the purpose of those standards are.  Some of the rules have a very clear purpose: doing it in a certain way is just plain better.  Other rules have a more subtle intentI think: essentially they are brown M&M's. 

Let me explain: Van Halen arranged notoriety for having a rider than insisted on having all brown M&M's removed on pain of forfeiture of the show.  Most people put this down to rock star arrogance, but actually the reason for this clause is a lot more interesting.  This is from David Lee Roth's autobiography:

Van Halen was the first band to take huge productions into tertiary, third-level markets. We'd pull up with nine eighteen-wheeler trucks, full of gear, where the standard was three trucks, max. And there were many, many technical errors — whether it was the girders couldn't support the weight, or the flooring would sink in, or the doors weren't big enough to move the gear through. The contract rider read like a version of the Chinese Yellow Pages because there was so much equipment, and so many human beings to make it function. So just as a little test, in the technical aspect of the rider, it would say "Article 148: There will be fifteen amperage voltage sockets at twenty-foot spaces, evenly, providing nineteen amperes . . ." This kind of thing. And article number 126, in the middle of nowhere, was: "There will be no brown M&M's in the backstage area, upon pain of forfeiture of the show, with full compensation."

So, when I would walk backstage, if I saw a brown M&M in that bowl . . . well, line-check the entire production. Guaranteed you're going to arrive at a technical error. They didn't read the contract. Guaranteed you'd run into a problem. Sometimes it would threaten to just destroy the whole show. Something like, literally, life-threatening.

So maybe that's what some of the style rules in coding standards are.  Brown M&M's.  A way to see if whoever wrote the code was paying attention and thinking about what they are doing.

Share

The Agile Restaurant

February 18th, 2010 by David Bending No comments »

I've been doing Agile training again, and after yesterday's course I started thinking of a better way to explain what process means in an Agile world and how it differs from either an ISO-style paperfest or anarchy.  This is the analogy I came up with.

Think about dining in a decent restaurant.  There's a certain number of interactions you expect to  happen – you're going to be greeted and seated, you expect to  be offered an aperitif or water, you'll expect to see the menu and the wine list, and your going to expect your water, wine and dinner to be served.  If any of these steps are missed you're likely to feel annoyed, but also if you are asked every 5 minutes if you'd like to see the wine list, that's going to be annoying too.

There's a few ways round this.  In some places each waiter looks after a number of tables and only deals with those.  This means they always know the state of each table and are unlikely to repeat tasks.  The problem is this is quite inefficient. If we get a large party in and the rest of the room is quiet we'd like all our available waiters to help.  We also have specialists (like the sommelier) who is going to have to serve the whole room. We might also have junior staff (the guy who brings the water) who isn't yet ready to deal with more complex tasks.

The traditional prescriptive methodology approach would be to introduce some kind of table checklist. We'd have a set of boxes and tick off the tasks: has the water been offered? Have they seen the menu? and so on.  The maitre d' could then manage these table cards and allocate them to staff.  He can also 'report' on the status of the room to the owner by looking at the cards.  Sounds good?  Well it does offer a fairly strong guarantee that we will perform each table task exactly once, but we have introduced a major organisational task that's going to keep one of our seniors busy all night.  We've also prevented the team from being able to be proactive – if they spot a table where things don't seem to be happening they can't pitch in and help without getting approval from the supervisor. I think that's why this isn't how decent restaurants do it.

In reality, restaurants create a lightweight protocol to let each other know what's going on without the diner necessarily even knowing.  When aperitifs or water is offered they will place a bottle coaster on the table.  Each table might be set with generic wine glasses that are never used.  Once the wine is ordered (but before it arrives which might take some time) they will be removed completely if no wine is required or replaced replaced with specific white or red wine glasses.  The details will vary, but the principle is the same.

Any member of staff can see at a glance what state the table is in and deal with it accordingly.  There's a system, but it doesn't need a prescriptive process with a command and control structure.  The team can be proactive and deal with problems having confidence that they understand the situation and what is required – what does or doesn't need to be done.  That's the kind of system we want a self-empowered agile team working in.  We can't report by looking at cards, but we can look around the room and know exactly how will each table is doing which is what we really want to know, and we also still have a guarantee that we won't duplicate tasks.

This is the kind of process we are looking to create for the self-empowered Agile team.

Share

Maintenance plans in SQL Server 2008 failing on Windows Server 2008 R2

February 16th, 2010 by David Bending No comments »

I was having problems getting maintenance plans running.  I could see an error being logged by DCOM, but  when I went into component services to modify launch permissions everything was greyed out.  The solution is obvious, and can be found in the link below:

61738644-F196-11D0-9953-00C04FD919C1 Launch Permissions – Event 10016 on Windows Server 2008 R2 (SharePoint 2007 & SharePoint 2010) | Ulysses Ludwig's SharePoint blog.

Share

Quotations

February 4th, 2010 by David Bending No comments »

I just came across a good thread on Linked In of people's favourite Agile related quotations.  Here's my pick of the bunch:

 

The best is the enemy of the good.

 

Attributed on LinkedIn to Sir John Harvey-Jones, but it's actually Voltaire: "Le mieux est l'ennemi du bien."

Stop Starting, Start Finishing!
- Sterling Mortensen

If you want to build a ship, don't drum up the people to gather wood, divide the work and give orders. Instead, teach them to yearn for the vast and endless sea.
- Antoine De Saint-Exupery

In preparing for battle I have always found that plans are useless, but planning is indispensable.
- Dwight D. Eisenhower

It is a bad plan that admits of no modification.
- Publilius Syrus

Story tests verify "Building the right thing" vs. unit test that verify "Building the thing right".

Man who says ‘it cannot be done’ should not interrupt the man doing it.
- old Chinese proverb

It is not the strongest of the species that survives, nor the most intelligent, but the one most responsive to change.
- Charles Darwin

Here is Edward Bear, coming downstairs now, bump, bump, bump, on the back of his head. It is, as far as he knows, the only way of coming downstairs, but sometimes he feels that there really is another way, if only he could stop bumping for a moment and think of it. And then he feels that perhaps there isn't.
- A. A. Milne 

The biggest problem with communication is the illusion it has occurred.
- Michael James

Share

Effective Software Development – How to Compare Elephant Herds

February 3rd, 2010 by David Bending No comments »

It’s funny because it’s true…

effective software development.

Share

Pex – Some Early Thoughts

February 2nd, 2010 by David Bending 1 comment »

I've been looking recently at Pex, Microsoft's automated white box testing software. There's basically 4 parts to Pex:

  1. A framework for writing parameterised unit tests.
  2. An explorer, for finding boundary conditions in code.
  3. Suggestions of preconditions that should be added to methods.
  4. Moles – a way of stubbing even static properties and methods (such as DateTime.Now).

Parameterised Unit Tests (PUT)

When manually writing unit tests, we often end up with blocks of tests that are essentially the same in concept, but with different input/output combinations.  For example, an addition routine might have tests for different combination of negative and positive numbers.  Pex creates its tests a parameterized tests.  There is a template test, and underneath that an instance of each test value.

The templates are placed in a source file and look like normal unit tests.  The parameterised versions are stored underneath in a .g.cs file.  These files are not intended to be edited and are created automatically by the Pex explorer.

You can also write your own PUTs.  More on this later…

The Explorer

The 'white box' part of Pex refers to the explorer.  This essentially looks at all the possible paths through a piece of code and generates a test for each. Let's look at this piece of code:

public int Add(int x, int y)
{
    return x + y;
}

If we run Pex on this, we get the following test:

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Add01()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Add(s0, 0, 0);
    Assert.AreEqual<int>(0, i);
    Assert.IsNotNull((object)s0);
}

Actually there's a bit more to it – but this shows the basic details.  As we can see, it's a fairly dull test.  in particular Pex hasn't added any code to see if the result of the operation has overflowed. On the other hand let's see what it does if there's a bit more going on in the method:

public int Fibonacci(int n)
{
    if (n < 0)
    {
        throw new ArgumentOutOfRangeException("n");
    }

    if (n == 0)
    {
        return 0;
    }

    if (n == 1)
    {
        return 1;
    }

    return Fibonacci(n - 2) + Fibonacci(n - 1);
}

This is an (admiteddly rubbish) implementation of Fibonacci. It's more interesting that Add because there's more paths through it. This time when we run Pex we get:

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci01()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 0);
    Assert.AreEqual<int>(0, i);
    Assert.IsNotNull((object)s0);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci02()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 1);
    Assert.AreEqual<int>(1, i);
    Assert.IsNotNull((object)s0);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci03()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 2);
    Assert.AreEqual<int>(1, i);
    Assert.IsNotNull((object)s0);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Fibonacci04()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, int.MinValue);
}

[TestMethod]
[PexGeneratedBy(typeof(CalculatorTest))]
public void Fibonacci05()
{
    int i;
    Calculator s0 = new Calculator();
    i = this.Fibonacci(s0, 14);
    Assert.AreEqual<int>(377, i);
    Assert.IsNotNull((object)s0);
} 

So Pex has created a test case for each path through the program.

Suggestions

When passing reference types to a method, Pex will realise that the value could be null.  For all such methods it will suggest the a pre-condition is added.  There's also a button that will get Pex to automatically insert the pre-condition into the code for you.  This saves a bit of time, but isn't a huge win.  That said Pex does understand code contracts so there may be bigger wins to be had here.

Moles

Pex also contains a mocking framework called Moles.  Unlike most mocking frameworks, Moles do their work at runtime level (like Isolator) and consequently you can use them to mock static properties.  Consider this code:

public void Y2kBug()
{
    if (DateTime.Now == new DateTime(1999, 12, 31))
    {
        throw new InvalidProgramException("Arrgghhh!!!!");
    }
} 

We'd like to unit test this, and we don't want to have to change the system clock to do so.  Unfortunately, DateTime.Now is static so the likes of Rhino Mocks and MoQ can't help.  With Pex Moles we can do the following:

[TestMethod]
[ExpectedException(typeof(InvalidProgramException))]
[HostType("Moles")]
public void Y2kBugTest()
{
    MDateTime.NowGet = () => new DateTime(1999, 12, 31);

    Y2k target = new Y2k();
    target.Y2kBug();
} 

We have generated Moles for mscorlib (by choosing Add New Item -> Pex Moles) in Visual Studio.  This creates a mole for each mscorlib type in the Moles namespace with the M prefix.  We then tell the mole to return the value we ant in the unit test (note that we supply a delegate not a value, and that properties are a Put and a Get mole).  By specifying the HostType attribute for our test, we cause the unit test runner to route the code trhough a mole supplying the value we want.

See Nikolai Tellman's video for more on this at: http://channel9.msdn.com/posts/Peli/Moles-Replace-any-NET-method-with-a-delegate/.

 

Share