Think Like A Functional Programmer For Better Object Oriented Code

The benefits of functional programming have been touted up one side of the nerdosphere and down the other. But when I picked up a little F# last month, I uncovered one that wasn’t printed on the tin.

What I found was that while functional languages like F# make it easy to fall into the pit of success with FP, the languages themselves are not the gatekeepers to the mindset, techniques, or payoffs of programming functionally with a capital F. If your boss won’t let you throw down in Clojure just yet, scoot a little closer and let me show you how you can get some of that FP awesome to rub off on your scabby old C# today.

Not what they mean by overloading, you guys

So, here we have a typical function from a typical OO codebase. That stretching sound you hear is me calling this code object-oriented–this pasta is downright procedural.

public void SetPrimaryUserTo(User newPrimaryUser) 
{
    // is the current user the primary user?
    if (_currentUser.IsPrimaryUser || _currentUser.UserRole == ApplicationRoles.FirmOwner) 
    {
        // does the new primary user belong to the same firm?
        if (newPrimaryUser != null && _currentFirm == newPrimaryUser.Firm) 
        {
            // reset all users' primary flags
            foreach (User user in _currentFirm.Users) 
            {
                user.IsPrimaryUser = false;
            }
 
            newPrimaryUser.IsPrimaryUser = true;
 
            // notificate
            var notifications = new Notifier();
            notifications.Send(newPrimaryUser, "Congratulations!  You're the new primary user for your firm!  Remember: with great power comes great responsibility.");
        }
        else 
        {
            throw new Exception("User does not exist.");
        }
    }
    else 
    {
        throw new Exception("You are not authorized to do that.");
    }
}

dr-evil-function

If you squint long enough, you can make out that our thirty-odd lines of grunt here is responsible for the following.

  1. Switching a firm’s primary user status from one user to another,
  2. Making sure that the current user has the privilege to do so,
  3. Making sure that the new user exists and belongs to the same firm as the current user, and
  4. Notifying the new primary user after the switch has been made.

And boy, are its arms tired. #badumpbump

Seriously, folks. It juggles responsibilities like cloned Michael Keatons. The generic exceptions being thrown are nowhere near the inscrutable if blocks that trigger them and that first comment is a lie by omission. It smells like nobody loves it.

But what could a sagacious and popular developer such as yourself do about a tragic snippet such as this?

Make it func-y

Usually the first thing about functional programming that gets an OOP lifer’s dander up is that the variables are immutable by default. Just to underscore that: you cannot (and should not) change the value of a variable in functional programming.

How, then, does the functional programmer ever get anything done? With functions. Nootch.

let x = 9
let z = add x x
assert (18 = z)

Except now we’re not talking about functions like the homunculus Dr. Evil was taunting a few paragraphs back. Functional code would never get off the ground if that was a function. What makes FP tick at scale is that its functions are small and discrete, designed to be composed together to achieve a larger goal.

Put another way? Stop me if you’ve heard this one before. They are responsible for doing exactly one thing. That’s right–functional programming and the Single Responsibility Principle are totally sittin’ in a tree.

Keeping that in mind, let’s get our Extract Method on with SetPrimaryUserTo:

public void SetPrimaryUserTo(User newPrimaryUser) {
    if (!HasPermissionToReassignPrimaryUser(_currentUser))
        throw new UnauthorizedAccessException();
 
    if (!UsersAreInTheSameFirm(_currentUser, newPrimaryUser))
        throw new UserDoesNotExistException();
 
    AssignPrimaryUserStatus(newPrimaryUser);
    Notify(newPrimaryUser, NewPrimaryUserNotificationMessage);
}
 
private bool HasPermissionToReassignPrimaryUser(User user) {
    return user.IsPrimaryUser || IsFirmOwner(user);
}
 
private bool IsFirmOwner(User user) {
    return user.UserRole == ApplicationRoles.FirmOwner;
}
 
private bool UsersAreInTheSameFirm(User user1, User user2) {
    if (user1 == null || user2 == null)
        return false;
 
    return user1.Firm != user2.Firm;
}
 
private void AssignPrimaryUserStatus(User newPrimaryUser) {
    foreach (User user in _currentFirm.Users) 
        user.IsPrimaryUser = false;
            
    newPrimaryUser.IsPrimaryUser = true;
}
 
private void Notify(User user, string message) {
    var notifications = new Notifier();
    notifications.Send(user, message);
}
 
private string NewPrimaryUserNotificationMessage {
    get {
        return "Congratulations!  You're the new primary user for your firm! Remember: with great power comes great responsibility.";
    }
}

Of course, the FP-savvy among you are currently pushing up their Warby Parkers and calling me out on the fact that this code is not really functional. Why, there’s state change a-plenty in AssignPrimaryUserStatus, for one thing. And we’re not doing that thing where we pass functions into other functions. Or even pretending to with LINQ.

What we have done, though, is that we have taken a sizable page from the FP playbook and used it to grow our C# into more composable, more resilient (and thus more valuable) code. Still don’t see it?

Right. You asked for it.

Aaaaaand here’s the part where I throw in some new requirements to see how our code reacts

  1. Users must be Owners to be assigned primary status.
    public void SetPrimaryUserTo(User newPrimaryUser) {
        if (!HasPermissionToReassignPrimaryUser(_currentUser))
            throw new UnauthorizedAccessException();
     
        if (!UsersAreInTheSameFirm(_currentUser, newPrimaryUser))
            throw new UserDoesNotExistException();
     
        if (!IsFirmOwner(newPrimaryUser))
            throw new UserNotQualifedForPrimaryException();
     
        AssignPrimaryUserStatus(newPrimaryUser);
        Notify(newPrimaryUser, NewPrimaryUserNotificationMessage);
    }
     
    // ...
  2. The new primary user is notified when their throne has been usurped.
    public void SetPrimaryUserTo(User newPrimaryUser) {
        if (!HasPermissionToReassignPrimaryUser(_currentUser))
            throw new UnauthorizedAccessException();
     
        if (!UsersAreInTheSameFirm(_currentUser, newPrimaryUser))
            throw new UserDoesNotExistException();
     
        if (!IsFirmOwner(newPrimaryUser))
            throw new UserNotQualifedForPrimaryException();
     
        AssignPrimaryUserStatus(newPrimaryUser);
        Notify(newPrimaryUser, NewPrimaryUserNotificationMessage);
        Notify(_currentPrimaryUser, ItAintYouAnymoreNotificationMessage);
    }
     
    private string ItAintYouAnymoreNotificationMessage {
        get {
            return "Oh noes! You are no longer the primary user.";
        }
    }
     
    // ...
  3. The current primary user is notified when an unauthorized power grab has been narrowly averted.
    public void SetPrimaryUserTo(User newPrimaryUser) {
        if (!HasPermissionToReassignPrimaryUser(_currentUser)) {
            Notify(_currentPrimaryUser, FailedCoupNotificationMessage);
            throw new UnauthorizedAccessException();
        }
     
        if (!UsersAreInTheSameFirm(_currentUser, newPrimaryUser))
            throw new UserDoesNotExistException();
     
        if (!IsFirmOwner(newPrimaryUser))
            throw new UserNotQualifedForPrimaryException();
     
        AssignPrimaryUserStatus(newPrimaryUser);
        Notify(newPrimaryUser, NewPrimaryUserNotificationMessage);
        Notify(_currentPrimaryUser, ItAintYouAnymoreNotificationMessage);
    }
     
    private string FailedCoupNotificationMessage {
        get {
            return "Someone is fully out to get you. Thought you should know.";
        }
    }
     
    // ...

All right, so our app doesn’t exactly smell like team spirit. But its code sure can look change in the eye and yawn.

Even if you’re nowhere near a Haskell compiler, thinking like a functional programmer is good for you and your object-oriented code. Not only will it make your code more vital and attractive to its potential mates, but it’ll also limber up your gray matter so that when the day finally comes for you to hot swap a little Erlang, you’ll be all over it.

Advertisements

How to Handle Exceptions in ASP.NET Web API Like a Gentleman

Ah, the yellow screen of death.

YSOD

It’s a sure sign of an ASP.NET dev who has not taught their app to use its indoor voice. And there are many fine (and elsewhere documented) methods for dealing with a wayward exception before it turns your entire user interface into ketchup and mustard.

But I’m not here about that yellow screen of death.

HTTP 500 is the new YSOD

In a “modern” web app (as the kids these days call them), it’s much more likely that an uncaught something or other will poot forth from behind a REST API, presenting as a blob of JSON rather than as rendered markup.

Out of the box, ASP.NET Web API gift-wraps our code’s uncaught excremental output with an HTTP 500 response whose body contains more information than the consumer of the API probably needs:

HTTP 500 Internal Server Error

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "No ticket.",
    "ExceptionType": "System.ArgumentNullException",
    "StackTrace": "   at IndianaJones.LastCrusade.Web.Api.TicketsPleaseController.Get() in TicketsPleaseController.cs:line 45\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()\r\n   at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"
}

This is the new Yellow Screen of Death. A RESTful sort of interface (the sort the Web API framework is built to deliver) should instead embrace and leverage its protocol, not work around or ignore it, as this default behavior does.

A more RESTafarian approach would be to return a slimmer response, perhaps composed of just the Exception’s Message property for the body, and (more importantly) bearing an HTTP Status Code that aligns with the nature of what’s actually gone awry. For instance, if bad user input was to blame, return a 400 (Bad Request). If a query for an specific record comes up empty, a 404 (Not Found) applies. And if somehow in the course of its operation your application suddenly became a whistling kettle of hot water, you could always send back a 418 (I’m a Teapot).

Web API makes doing this a piece of cake, by way of the HttpResponseException and its little friend, the HttpStatusCode enumeration:

public class TicketCollector {
 
    public void CollectFromPassenger(Ticket ticket) {
        if (ticket == null)
            throw new HttpResponseException(HttpStatusCode.BadRequest);
 
        // TODO: take ticket
    }
}

Now, make it right

As you can imagine, if we adopt this pattern across our codebase, our business logic will become shot through with references to System.Web.Http and HttpResponseException. Nasty.

I mean, business logic code is hands-down the most valuable part of any app, because it defines the features that are the application’s very reason for being. This code should be completely agnostic to from whence its input has come, and to how its output is ultimately being presented. If we want our app to be resilient and sustainable, we’ll have to unhitch this code from the System.Web.Http wagon.

We can accomplish this by updating our precious, precious logic to throw non-HTTP type exceptions. Then, in our Web API, we can catch these and translate them into HTTP exceptions as appropriate. Anything HTTP is solely the concern of the API code, and this division of labor keeps it that way.

public class TicketCollector {
 
    public void CollectFromPassenger(Ticket ticket) {
        if (ticket == null)
            throw new ArgumentNullException("ticket", "No ticket.");
 
        // TODO: take tickets, avoid Nazi eye contact
    }
}
 
// meanwhile
 
public class TicketsPleaseController : ApiController {
 
    public void Post(TicketRequest request) {
        try {
            var indy = new TicketCollector();
            indy.CollectFromPassenger(request.Ticket);
        }
        catch (ArgumentNullException) {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }
        catch (Exception e) {
            throw new HttpResponseException(HttpStatusCode.NotAcceptable);
        }
    }
}

Concerns were separated, exceptions were handled, and lives were literally saved, you guys. But at this point, we’re only two-thirds of the way through the article–and that means we can do better.

Exception handling is not a feature

As our codebase evolves, this pattern will grow hair fast. The API’s pipes are getting clogged with prickly and distracting try/catch blocks. Even in our simple example above, there are eight lines of code dedicated to exception handling, compared to just two that relate to the actual meat of the call.

Exception handling is not a feature of our app, it is a cross-cutting aspect of it. Our code should reflect this by sweeping this aspect out of the way and returning focus to the feature. We can do this by rolling a custom ExceptionFilterAttribute:

public class HandleExceptionAttribute : ExceptionFilterAttribute {
 
    public Type Type { get; set; }
    public HttpStatusCode Status { get; set; }
 
    public override void OnException(HttpActionExecutedContext context) {
        var ex = context.Exception;
        if (ex.GetType() is Type) {
            var response = context.Request.CreateResponse<string>(Status, ex.Message);
            throw new HttpResponseException(response);
        }
    }
}

Now, just as our logic burns clean and knows nothing of HTTP, our API reads as just the plumbing we need it to be:

public class TicketsPleaseController : ApiController {
 
    [HandleException(Type = typeof(ArgumentNullException), Status = HttpStatusCode.BadRequest)]
    [HandleException(Type = typeof(Exception), Status = HttpStatusCode.NotAcceptable)]
    public void Post(TicketRequest request) {
        var indy = new TicketCollector();
        indy.CollectFromPassenger(request.Ticket);
    }
}

We can even stack several of them up in the order they should be handled, just as we do with multiple catch blocks.

The pool of available HTTP Status Codes may be limited, especially when compared to the limitless horizons of wrong your software may decide to throw. But with a little creativity, most levels of jacked-up can be conveyed just by using HTTP well. And with our HandleExceptionAttribute in the bag, there are no more excuses for rolling the HTTP 500 of Death.

How I Used Kata To Learn TypeScript Fast

I don’t know about you, but I’m not one to turn away early clues to the new direction from .NET A-listers whose lives have recently flashed before their eyes. So I sat up a bit when I came across the following sobering passage on Rocky Lhotka’s blog:

Sadly, as much as I truly love .NET and view it as the best software development platform mankind has yet invented, I strongly suspect that we’ll all end up programming in JavaScript–or some decent abstraction of it like TypeScript. As a result, I’m increasingly convinced that platforms like .NET, Java, and Objective C will be relegated to writing “toy” consumer apps, and/or to pure server-side legacy code alongside the old COBOL, RPG, and FORTRAN code that still runs an amazing number of companies in the world.

I blinked, reread the paragraph a few times, and decided (among other things) that it was high time that I dug in and learned this TypeScript of which Lhotka spoke.

Well. That, and the fact that I had just signed up to show it to Nashville’s .NET User Group within a matter of weeks.

Wax On, Wax Off

Now, I can read friendly, friendly Getting Started tutorials and watch Build talks all day long, but I find that I never really encounter all of the boogers and sharp corners on a new language until I’ve used it to solve a real problem or two. I had a good thing going in this respect for a while, by keeping a pet application. But that approach gets heavy once time has its way with you. I mean, I can’t recommend enough the experience of building something top to bottom on your own, at least once. But what can you do if the Internet is already full, and you just want to learn something?

Enter Kata. A practice borrowed from the martial arts, a kata is a discrete exercise designed to strengthen a skill through repetition. When applied in software, it is a means for nerds to write code in real-world conditions, without so much in the way of the commitment that typically accompanies code in the real world.

Naturally, I turned to kata to help me quickly wrap my head around TypeScript. The kata I chose for this occasion was the game of Fizz Buzz. Also, it’s me, so I came at it using Behavior-Driven Development. This helped me to lay out the game’s requirements, and to remain focused on meeting them as simply as possible.

Since TypeScript is really just JavaScript with a tie on, I was able to bring along my favorite JavaScript tooling–namely, the Jasmine testing framework, and the Chutzpah extension for integrating Jasmine with Visual Studio’s Test Explorer. And, of course, I had to install TypeScript itself, as it has not yet been mainstreamed into the out-of-box Visual Studio experience.

So, here’s how you can recreate my learning experience from the comfort of your own personal code laboratory.

kata

First, do the File, New Project shuffle, and choose the HTML Application with TypeScript template. Add the jasmine.js and jasmine.TypeScript.DefinitelyTyped NuGet packages to your new project, and round out the yak-shaving portion of the session by creating two TypeScript files, one christened fizzbuzz.spec.ts for the tests, and the other fizzbuzz.ts for the implementation.

For bonus #PROTIP points: open both of these and lay them out side by side using two vertical tab groups, and bring up the Test Explorer pane at the right edge of the Visual Studio window.

All righty then, tests first. The basic idea behind the game of Fizz Buzz, according to the Wikipedia article, is as follows.

Fizz buzz (also known as bizz buzz, or simply buzz) is a group word game for children to teach them about division.[1] Players take turns to count incrementally, replacing any number divisible by three with the word “fizz”, and any number divisible by five with the word “buzz”.

So, laying this out in discrete rules in order of increasing complexity, we get:

  1. The player says the next number.
  2. The player says ‘fizz’ if the next number is 3.
  3. The player says ‘buzz’ if the next number is 5.
  4. The player says ‘fizz’ if the next number is divisible by 3.
  5. The player says ‘buzz’ if the next number is divisible by 5.
  6. The player says ‘fizzbuzz’ if the next number is divisible by both 3 and 5.

Set up the spec file like so, adding a test for the first requirement using jasmine’s it() function, inside a describe function.

/// <reference path="scripts/typings/jasmine/jasmine.d.ts"/>
/// <reference path="fizzbuzz.ts"/>
 
describe("The fizz buzz player", () => {
 
    it("says the next number.", () => {
        var player = new FizzBuzzPlayer();
        expect(player.play(1)).toBe("1");
        expect(player.play(2)).toBe("2");
    });
});

Now save the file and run the tests. Since the FizzBuzzPlayer class does not exist yet, the TypeScript compiler will fail the build. Following the TDD cycle of red, green, refactor, this counts as our first red. Resolve this by creating the FizzBuzzPlayer class with in fizzbuzz.ts:

class FizzBuzzPlayer {
    play(n: number) {
        return '';
    }
}

Now that the build succeeds, the test runner should show that the spec fails–the play method does not return “1”. Let’s solve this in the simplest possible way:

play(n: number) {
    return n.toString();
}

The test should now pass. Now let’s write a test for the second requirement:

it("says 'fizz' if the next number is 3", () => {
    var player = new FizzBuzzPlayer();
    expect(player.play(3)).toBe("fizz");
});

This test will fail with the message, “Expected ‘3’ to be ‘fizz'”. Update the play method again to make this pass:

play(n: number) {
    if (n == 3)
        return 'fizz';
 
    return n.toString();
}

Let’s do a bit of cleaning up for the refactor stage. It’s repetitive to initialize the player in each spec, so using jasmine’s beforeEach function, initialize the player in one place, and remove that line from each of the specs:

var player;
beforeEach(() => {
    player = new FizzBuzzPlayer();
});
 
it("says the next number.", () => {
    expect(player.play(1)).toBe("1");
    expect(player.play(2)).toBe("2");
});
 
it("says 'fizz' if the next number is 3", () => {
    expect(player.play(3)).toBe("fizz");
});

Beautiful. Let’s make things red again by adding a test for the next requirement:

it("says 'buzz' if the next number is 5", () => {
    expect(player.play(5)).toBe("buzz");
});

Red, it is: “Expected ‘5’ to be ‘buzz'”. Make it go green by updating our play method:

play(n: number) {
    if (n == 3)
        return 'fizz';
 
    if (n == 5)
        return 'buzz';
 
    return n.toString();
}

There’s no refactoring to be done yet, so let’s move back to red with the next requirement:

it("says 'fizz' if the next number is divisible by 3", () => {
    expect(player.play(6)).toBe("fizz");
    expect(player.play(9)).toBe("fizz");
    expect(player.play(27)).toBe("fizz");
});

Red, indeed: “Expected ‘6’ to be ‘fizz'”. Make this pass by checking for a remainder of 0, rather than equality:

if (n % 3 == 0)
    return 'fizz';

Repeat this for the buzz case.

it("says 'buzz' if the next number is divisible by 5", () => {
    expect(player.play(10)).toBe("buzz");
    expect(player.play(25)).toBe("buzz");
    expect(player.play(100)).toBe("buzz");
});

And to make it pass:

if (n % 5 == 0)
    return 'buzz';

Now define the test for our last requirement:

it("says 'fizzbuzz' if the next number is divisible by both 3 and 5", () => {
    expect(player.play(15)).toBe("fizzbuzz");
    expect(player.play(30)).toBe("fizzbuzz");
    expect(player.play(60)).toBe("fizzbuzz");
});

Once this fails, we can update our play method to solve the problem.

play(n: number) {
    var value = '';
 
    if (n % 3 == 0)
        value = 'fizz';
 
    if (n % 5 == 0)
        value += 'buzz';
 
    if (value === '')
        value = n.toString();
 
    return value;
}

Green! Now, there looks to be a bit of refactoring to be done here. I mean, if you’re into the whole code doing one thing well thing. Which you should be. The first two if clauses are identical, except for the values involved–that looks like a function to me:

private getWordForMultiple(n: number, factor: number, word: string) {
    if (n % factor == 0)
        return word;
    else
        return '';
}

Now we can swap out our repetitive if clauses for calls to this function:

play(n: number) {
    var value = '';
 
    value += this.getWordForMultiple(n, 3, 'fizz');
    value += this.getWordForMultiple(n, 5, 'buzz');
 
    if (value === '')
        value = n.toString();
 
    return value;
}

Run the tests now to be sure that they still pass.

I think we can still go a little tighter than that. Let’s make a getWords method that handles all of the words-for-multiples business in one call:

private getWords(n: number) {
    var value = '';
    value += this.getWordForMultiple(n, 3, 'fizz');
    value += this.getWordForMultiple(n, 5, 'buzz');
    return value;
}

Now our play function can be reduced to:

play(n: number) {
    var value = this.getWords(n);
    if (value === '')
        value = n.toString();
 
    return value;
}

And the tests still pass. Well, that was just a smashing learning exercise, and I thought that the whole thing went smoothly as a–

Your manager just walked out of a meeting. He looks a little ill as he approaches your desk. “We have a new requirement”, he says. “The Fizz Buzz Player needs to be configurable, to accommodate any combination of factors and words.”

Zoinks. It’s a good thing we’ve been keeping our code ship-shape and tested–let’s see what we can do. First, add the new requirement to the specs:

it("can be configured to accommodate any combination of factors and words.", () => {
    var cp = new FizzBuzzPlayer(2, 'jack', 7, 'squat');
    expect(cp.play(1)).toBe("1");
    expect(cp.play(2)).toBe("jack");
    expect(cp.play(3)).toBe("3");
    expect(cp.play(4)).toBe("jack");
    expect(cp.play(5)).toBe("5");
    expect(cp.play(6)).toBe("jack");
    expect(cp.play(7)).toBe("squat");
    expect(cp.play(8)).toBe("jack");
    expect(cp.play(9)).toBe("9");
    expect(cp.play(10)).toBe("jack");
    expect(cp.play(11)).toBe("11");
    expect(cp.play(12)).toBe("jack");
    expect(cp.play(13)).toBe("13");
    expect(cp.play(14)).toBe("jacksquat");
    expect(cp.play(15)).toBe("15");
});

We’re back to build failure, because FizzBuzzPlayer doesn’t have a constructor defined. Let’s get things building again by adding one:

constructor(
    public fizzFactor: number = 3,
    public fizzWord: string = 'fizz',
    public buzzFactor: number = 5,
    public buzzWord: string = 'buzz') { }

Note that not only are we taking advantage of TypeScript’s automatic properties shorthand, but we’re also making these parameters optional by defining default values based on the original Fizz Buzz rules.

Our test still runs red. Let’s fix up the getWords code to actually use the new properties we’ve added:

private getWords(n: number) {
    var value = '';
    value += this.getWordForMultiple(n, this.fizzFactor, this.fizzWord);
    value += this.getWordForMultiple(n, this.buzzFactor, this.buzzWord);
    return value;
}

And we’re back in the green! Time to refactor. Using the right-click menu’s Refactor, Rename option (high-five, TypeScript!), let’s rename FizzBuzzPlayer to something less specific, and more appropriate to what it actually does now: NumberGamePlayer. While you’re at it, update the name in the jasmine describe call, too.

You look up at your manager, who is still standing over your shoulder and clutching his business papers anxiously.

“No problem, boss!” you exclaim, and check in your changes without breaking eye contact.

“Whatever,” he mutters as he shakes his head and walks off, failing to grasp exactly how easy TypeScript, Jasmine, Chutzpah, and you have made his life just now.

How Behavior-Driven Development Saved My Code from the Jedi Interruption

So, I’m not the sharpest sandwich in the drawer. This was demonstrated to me again in no uncertain terms just the other day, as I was working up some routing logic for a new Durandal-based app. The JavaScript in question went something like this.

router.guardRoute = function (instance, instruction) {
    var routeInfo = instruction.config;
    if (!_isAuthenticated && !routeInfo.settings.anonymous)
        return getAuthenticationUrl();
 
    return true;
};

It’s not an original story. guardRoute runs every time the user tries to navigate to a view in the app. This snippet simply ensures that unauthenticated users get redirected to a login page if the new route is not available to anonymous visitors. And it hummed along happily for a short while.

When Suddenly

Apparently, if the optional settings property is not present on routeInfo, an exception gets thrown, all of the air leaks out of our app, and the rotation of the Earth sort of grinds to a halt. Could be a bug.

No worries, thought I. We just needed to test route.settings before testing route.settings.anonymous.

if (!isAuthenticated && !route.settings && !route.settings.anonymous)

Hmm. That wasn’t quite right–what if we grouped those second two conditions together?

if (!isAuthenticated && !(route.settings && route.settings.anonymous))

That felt correct. But static analysis alone wasn’t enough to give me a warm fuzzy that my code was up to its arguably very important job.

Like I said, I’m not the brightest knife at the gun fight. I was standing on my head and counting on my fingers to ensure that this code was going to work. Maybe if this was the only thing I had going on at the time, perhaps if I was able to hone a laser-like beam of attention on the problem, I could have gotten to the point where I was confident in its correctness.

But, as it happened, at that moment my tête-à-tête with reinventing the authentication routing wheel took a back seat to making a peanut butter sandwich for this guy.

jacob

To clarify, I was working from home that day. I mean, I wouldn’t want you thinking that Aptera keeps the kind of office where tiny hungry children just sort of wander around in Jedi cosplay and dislodge people from their respective trains of thought.

Anyway. By this point I was spreading peanut butter on bread and spiraling hard into a full-on Hanselman phony complex on account of this gear just not catching in my head. What was wrong with me?

Enter BDD

As is often the case, the solution was there before the problem. I just needed to take a few minutes to wire up some Jasmine specs.

Who?

Let me back up. By now, you probably have heard all about the wonders of Test Driven Development (TDD). How it will make your code flawless, fix your marriage, and scratch that itch in the middle of your back that you can never quite get to. But you may not be familiar with TDD’s more stylish younger brother, BDD. That’d be Behavior Driven Development, if you’re not into the whole brevity thing.

The thing about traditional TDD is that it has a pretty fundamental flaw–it is backward. Backward, at least, in terms of its underlying metaphor of testing a thing. See, in meatspace, in order to run a test on something (like in a laboratory), it first needs to exist. So when we’re told to write a test for code that doesn’t yet exist, we buck; how can we write a test when we don’t even know what our code looks like yet? If TDD is something you’ve been meaning to get into, but you could never quite find the front door on it, this is probably why.

The behavior-driven approach resolves this cognitive dissonance, not by being mechanically any different at all from TDD, but by flipping the assumption that what we are writing first is a test. What we write first, says BDD, is a spec–a specification that defines exactly what the code under test will do. With this, our brains crack into applause–we write code from specifications all the time.

In execution, though, a spec is just a unit test that’s named well. Here’s how a typical test suite (using QUnit here) might come off in the naming department.

module("PB and J tests");
 
test("bread test", function(){     
    // assert stuff about the bread
});
 
test("peanut butter test", function(){     
    // assert stuff about the peanut butter
});
 
test("jelly test", function(){     
    // assert stuff about the jelly
});
 
// etc.

Make a barf noise here, amirite? Here’s how we’d name things using the aforementioned Jasmine, a BDD framework for testing JavaScript code.

describe("A peanut butter sandwich", function() {
    
    it("has two slices of bread", function () {          
        // assert stuff about the bread     
    });         
    
    it("has peanut butter on one slice", function () {        
        // assert stuff about the peanut butter    
    });
        
    it("has jelly on one slice", function () {          
        // assert stuff about the jelly    
    });

    // etc.
});

What we expect to have happen in our code is just so much clearer when we spell it out in English1. My very favorite thing about wording each spec like this is that Jasmine fuses the title from describe() with the phrase from each it() as subject and predicate. The output shown in the test runner then becomes a series of transitive statements about the code under test.

  • A peanut butter sandwich has two slices of bread.
  • A peanut butter sandwich has peanut butter on one slice.
  • A peanut butter sandwich has jelly on one slice.

And, of course, each of these comes with a red or green mark that shows us whether it is true yet.

The value of a good suite of BDD specs is that it is a direct English translation between our expectations for the code that we haven’t written yet, and the code that will test it to ensure that it meets the specification. The spec says what our code does. Our code does what the spec says. When we’ve made it all turn green, it works.

And here’s the part where I actually solved my problem

So cut back to the other day, post-peanut-butter-and-jelly-hiatus. I stopped banging my head directly against my troublesome code, opting instead to simply define, in plain English, what I wanted it to do.

describe("The auth service", function () {
});

A rousing start. Yessir, the auth service is in fact what I would like to be describing today.

describe("The auth service", function () {
 
    it("indicates when the user is authenticated", function () {
        var a = new auth(mocks.api);
        spyOn(mocks.api.login, 'GET').andReturn('jfazzaro@apterainc.com');
        a.start();
        expect(a.isAuthenticated()).toBe(true);
    });
 
    it("indicates when the user is not authenticated", function () {
        var a = new auth(mocks.api);
        spyOn(mocks.api.login, 'GET').andReturn(undefined);
        a.start();
        expect(a.isAuthenticated()).toBe(false);
    });
 
    var undefined;
    var mocks = {
        api: {
            login: {
                GET: function () { }
            }
        }
    };
});

In the first two specs above, I defined clearly what the isAuthenticated() method does, and since this was already implemented, they passed. But the real turning point was when it was time to spec out the service’s ability to determine whether a route was anonymous. I wrote the next two specifications as implementation-agnostic descriptions of what I was actually after.

it("indicates when a route is anonymous", function () {
});
 
it("indicates when a route is not anonymous", function () {
});

Once that was outside of my head and staring back at me in plain text, it occurred to me that that if block from the opening of this post–

if (!isAuthenticated && !(route.settings && route.settings.anonymous))

–yes, that one, was just trying too hard. The last two-thirds of it were an attempt to solve the anonymous route problem I had just finished specifying. And the fact that they weren’t isolated in their own named and testable function was what made it so difficult for me to quickly ascertain my code’s validity.

I descended on the keys with fresh purpose, spelling out the anonymous route checking functionality, as it should look like from the outside.

it("indicates when a route is anonymous", function () {
    var a = new auth(mocks.api);
    expect(a.isAnonymous(mocks.routes.signin)).toBe(true);
});
 
it("indicates when a route is not anonymous", function () {
    var a = new auth(mocks.api);
    expect(a.isAnonymous(mocks.routes.dashboard)).toBe(false);
    expect(a.isAnonymous(mocks.routes.simple)).toBe(false);
});
 
var mocks = {
    api: {
        login: {
            GET: function () { }
        }
    }, routes: {
        signin: { route: 'signin', moduleId: 'viewmodels/signin', settings: { anonymous: true } },
        dashboard: { route: '', moduleId: 'viewmodels/dashboard', settings: { anonymous: false } },
        simple: { route: 'simple/route', moduleId: 'viewmodels/simple/route' }
    }
};

Naturally, these tests went red in my test runner, because the isAnonymous(route) function didn’t exist yet. But it soon did.

function isAnonymous(route) {
    return route.settings && route.settings.anonymous;
}

Then, the tests went–red. Wait, still red? Yep.

auth-spec-fail

I was close, but I may never have picked out the distinction between undefined and false without that spec in place to guide me. I updated the function, making it a bit more specific in the truthy/falsy department.

function isAnonymous(route) {
    return (route.settings != undefined && route.settings.anonymous);
}

Boom. Greensville.

Finally, now that this irritating fruit fly of logic was labeled and tested, that code in guardRoute could now be read more organically, too.

if (!isAuthenticated && !isAnonymous(route))

When I read it aloud again in almost-English, I picked out a further subtlety: I really should test the route for non-anonymity first. I mean, if we’re hitting an anonymous route, our authentication status really doesn’t matter, and we shouldn’t waste any cycles checking on it.

if (!isAnonymous(route) && !isAuthenticated)

I like to imagine that Sam Clemens himself wouldn’t have put it more succinctly.

We think in English. The terse syntax of our favorite programming language becomes more compatible with the way we actually think when we use our words to specify and test our code. And offloading these micro-requirements from our heads into a self-testing suite of specifications doesn’t just make our software more readable and reliable, it also frees us up to focus on more important things.

Playing Jedi with the little guy, for instance.


  1. It’s a fair assumption that if you’re reading this in English, you’re thinking in English. If that’s not the case, by all means mentally drop your preference in whenever I mention it. Unless your preference is Klingon, in which case you must stop reading altogether and figure out where things went wrong for you.

Extension Cords, Tea Kettle Whistling, and the Contractor’s Wrap for Your Code

A few weekends ago, I found myself standing in my garage, regretting my ambitions of yard work and struggling to unwind the pile of orange spaghetti that was, at one point, a tidily wrapped fifty-foot extension cord.

Then I took a deep breath and reminded myself that things were going to be different this time.

See, the blog Art of Manliness had just run a post on how to wrap your extension cords like a contractor, using a technique that enables you to quickly uncoil whatever length of cord you need, without it ever becoming a tangled mess. The post was mostly pictures, so I managed to get through it. And things did, in fact, turn out differently this time.

cord
[via]

Well. The orange garage-spaghetti department of things, at least.

Cool Story, Bro

So what, you may well ask, does my high-voltage gardening adventure have to do with building software?

Here’s the thing about code: it gets inscrutably balled up just like this all the time. And while I’m sure that you, dear reader, have never yourself been responsible for such a mess, I have borne witness as this recurring nightmare slowly unfolded on many an unsuspecting software venture.

In the beginning of the project, there’s the familiar big talk about how This Time, we’re going to keep things organized. This Time, we’re going to write REUSABLE code. This Time, we’re going to work harder and do it right. Things are going to be different This Time.

reusable

So, development hops along at a decent pace at first–like winding the first few coils in that orange extension cord. But soon, it gets harder and harder to actually reuse the REUSABLE components. Changes take longer to implement, you swear that you can hear the faint whistle of a tea kettle that is perpetually beginning to boil, and your source has seemingly contorted itself into shapes that would make a sailor cry. And when the new devs (that management has hurled at the problem) climb aboard and try to unravel a piece of the code for what they’re working on, those kinks just get twisted tighter. Soon, everyone involved sinks into their chair with the same question burning in their brain.

How did this happen to our code again?

We get it, Fazzaro. Code bad, team sad. But what exactly can a young person like myself do to invoke the beneficence of the programming gods that they may no longer smite us in this way?

Glad you asked. Let’s get specific.

In my travels, the most common cause of egregious code fluster in the modern business app is a poorly scoped Entity Framework DbContext1. What might one of those look like? Stop me if you’ve heard this one: I’ve updated these entities, added two new ones over here, deleted that ugly one, and our REUSABLE code just called SaveChanges three times in the course of doing its business. So, I’m going to jiggle the handle and call it one more time over here for this case. You know, just to be sure.

Sure, the EF implements the Unit of Work and Repository patterns right out of the box. But this only helps if we’re using them correctly–which really comes down to understanding where the context belongs. Should a new context be created to persist each change to an entity? Should we create a new one for every method that alters data? Or should we just keep a global singleton context instance, and call SaveChanges on it when it feels right?

That’d be no, no, and hand over your keys, dude, respectively. Paths to the spaghetti side, those are. Instead, to keep the unit of work thing straight, I just keep two simple rules in mind:

  1. The unit of work does not go inside the reusable code, the reusable code goes inside of the unit of work.
  2. As soon as you create a new context or call SaveChanges, you are no longer writing the reusable code.

Some of your code will never be reusable, and that’s okay; that’s where the context goes. As for the rest of your code, here’s a way to make it truly and sustainably reusable.

I’m going to illustrate this by generally being abusive to a particularly troubling snippet of sample code from the Wingtip Toys tutorial on MSDN. In the the application that the tutorial guides you through building, the ShoppingCartActions class houses the domain logic around adding, updating, and removing items from a shopping cart. I’ve abbreviated the class here to just show the salient bits:

public class ShoppingCartActions {
    public string ShoppingCartId { get; set; }

    private ProductContext _db = new ProductContext();
 
    public const string CartSessionKey = "CartId";

    public void AddToCart(int id) {
        // Retrieve the product from the database. 
        ShoppingCartId = GetCartId();

        var cartItem = _db.ShoppingCartItems.SingleOrDefault(
            c => c.CartId == ShoppingCartId
            && c.ProductId == id);
        if (cartItem == null) {
        // Create a new cart item if no cart item exists. 
            cartItem = new CartItem {
                ItemId = Guid.NewGuid().ToString(),
                ProductId = id,
                CartId = ShoppingCartId,
                Product = _db.Products.SingleOrDefault(
                    p => p.ProductID == id),
                Quantity = 1,
                DateCreated = DateTime.Now
            };

            _db.ShoppingCartItems.Add(cartItem);
        } else {
            // If the item does exist in the cart, 
            // then add one to the quantity. 
            cartItem.Quantity++;
        }
        _db.SaveChanges();
    }

    public void UpdateShoppingCartDatabase(String cartId, ShoppingCartUpdates[] CartItemUpdates) {
        using (var db = new ProductContext()) {
            int CartItemCount = CartItemUpdates.Count();
            List<CartItem> myCart = GetCartItems();
            foreach (var cartItem in myCart) {
                // Iterate through all rows within shopping cart list 
                for (int i = 0; i < CartItemCount; i++) {
                    if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId) {
                        if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true) {
                            RemoveItem(cartId, cartItem.ProductId);
                        } else {
                            UpdateItem(cartId, cartItem.ProductId, CartItemUpdates[i].PurchaseQuantity);
                        }
                    }
                }
            }
        }
    }

    public void RemoveItem(string removeCartID, int removeProductID) {
        using (var db = new ProductContext()) {
            var myItem = (from c in db.ShoppingCartItems where c.CartId == removeCartID && c.Product.ProductID == removeProductID select c).FirstOrDefault();
            if (myItem != null) {
                db.ShoppingCartItems.Remove(myItem);
                db.SaveChanges();
            }
        }
    }

    public void UpdateItem(string updateCartID, int updateProductID, int quantity) {
        using (var db = new ProductContext()) {
            var myItem = (from c in db.ShoppingCartItems where c.CartId == updateCartID && c.Product.ProductID == updateProductID select c).FirstOrDefault();
            if (myItem != null) {
                myItem.Quantity = quantity;
                db.SaveChanges();
            }
        }
    }
}

And here are a few lines from a nearby code-behind class that consumes ShoppingCartActions:

ShoppingCartActions usersShoppingCart = new ShoppingCartActions();
usersShoppingCart.AddToCart(Convert.ToInt16(rawId));

Oh, it looks innocent enough, all right. Until you notice that not only does each instance of ShoppingCartActions get its very own private ProductContext, but that when it’s time to call RemoveItem, UpdateItem, or (Robert Cecil Martin help you) UpdateShoppingCartDatabase, we’re whipping off new context instances like they are going out of style. Gross.

Why is that gross? Well, suppose that we had another page in our application that needed to perform similar actions on a shopping cart, in a slightly alternate combination:

ShoppingCartActions usersShoppingCart = new ShoppingCartActions();
usersShoppingCart.AddToCart(Convert.ToInt16(rawId1));
usersShoppingCart.AddToCart(Convert.ToInt16(rawId2));

var changes = GetShoppingCartChanges();
usersShoppingCart.UpdateShoppingCartDatabase(cartId, changes);

I count no fewer than four new ProductContext instances created here–and easily many more, depending on how many changes were in that list we passed in to UpdateShoppingCartDatabase. And if we needed this particular set of operations to be transactional, so that if one failed, no changes were sent to the database at all? Forget it. Yes, gross.

And yet, with a simple, subtle refactoring, we can turn this heinous double sheetbend into a nimble little slipknot. All we have to do is get it to let go of control of the context:

public class ShoppingCartActions {
    public string ShoppingCartId { get; set; }

    private ProductContext _db;

    public ShoppingCartActions(ProductContext db) {
        _db = db;
    }

    public void AddToCart(int id) {
        // Retrieve the product from the database. 
        ShoppingCartId = GetCartId();

        var cartItem = _db.ShoppingCartItems.SingleOrDefault(
            c => c.CartId == ShoppingCartId
            && c.ProductId == id);
        if (cartItem == null) {
            // Create a new cart item if no cart item exists. 
            cartItem = new CartItem {
                ItemId = Guid.NewGuid().ToString(),
                ProductId = id,
                CartId = ShoppingCartId,
                Product = _db.Products.SingleOrDefault(
                p => p.ProductID == id),
                Quantity = 1,
                DateCreated = DateTime.Now
            };

            _db.ShoppingCartItems.Add(cartItem);
        } else {
            // If the item does exist in the cart, 
            // then add one to the quantity. 
            cartItem.Quantity++;
        }
    }

    public void UpdateShoppingCartDatabase(String cartId, ShoppingCartUpdates[] CartItemUpdates) {
        int CartItemCount = CartItemUpdates.Count();
        List<CartItem> myCart = GetCartItems();
        foreach (var cartItem in myCart) {
            // Iterate through all rows within shopping cart list 
            for (int i = 0; i < CartItemCount; i++) {
                if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId) {
                    if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true) {
                        RemoveItem(cartId, cartItem.ProductId);
                    } else {
                        UpdateItem(cartId, cartItem.ProductId, CartItemUpdates[i].PurchaseQuantity);
                    }
                }
            }
        }
    }

    public void RemoveItem(string removeCartID, int removeProductID) {
        var myItem = (from c in _db.ShoppingCartItems
            where c.CartId == removeCartID && c.Product.ProductID == removeProductID
            select c).FirstOrDefault();
        if (myItem != null)
            _db.ShoppingCartItems.Remove(myItem);
    }

    public void UpdateItem(string updateCartID, int updateProductID, int quantity) {
        var myItem = (from c in _db.ShoppingCartItems
            where c.CartId == updateCartID && c.Product.ProductID == updateProductID
            select c).FirstOrDefault();
        if (myItem != null)
            myItem.Quantity = quantity;
    }
}

You almost can’t see the difference–but note the complete lack of context instantiation, and that nowhere in there do we even consider calling SaveChanges. This is our rule number two in action; ShoppingCartActions just isn’t in the business of owning the ProductContext anymore.

Here’s how we can leverage this class in our code-behind now:

using (var db = new ProductContext()) {

    ShoppingCartActions usersShoppingCart = new ShoppingCartActions(db);
    usersShoppingCart.AddToCart(Convert.ToInt16(rawId1));
    usersShoppingCart.AddToCart(Convert.ToInt16(rawId2));
    var changes = GetShoppingCartChanges();
    usersShoppingCart.UpdateShoppingCartDatabase(cartId, changes);

    db.SaveChanges(); 
}

And that illustrates rule number one. We instantiate one ProductContext, we do our business with it, and we send a single set of changes to the database. Not only can the new ShoppingCartActions be applied to many different situations throughout the app, but it will scale like a mother to boot.

Dependency Injection is the Contractor’s Wrap for Code

By now, the sharper nerds in my readership will be calling out that I have simply invoked the Dependency Injection technique here, and they would be correct. We took a component that the logic was dependent upon and made sure that it came from somewhere else, outside of the logic’s implementation. Dependencies like context instances are really just input for the logic to use in its calculations. What’s really going to knock your socks off later on is that this pattern of threading dependencies through class constructors applies to any number of types that have nothing at all to do with the Entity Framework, or even data storage, for that matter. HttpContext, FileStream, SPWeb, RouteCollection, you name it. They are all just input for our code to operate upon.

With just a minor tweak to the way we weave our classes together, our source can become tangle-free and flexible, and the next developer to lay hands on our app doesn’t have to worry about it curling up into an untenable heap of sad. It’s a shot in the arm for the sustainability and success of the app, and for the happiness of the team. And things are totally going to be different this time.

Well. The weeping-sailor heinous-code-fluster department of things, at least.


  1. Okay, so maybe you’re not using the Entity Framework (or its newer DbContext API), but don’t check out on me just yet–you might well be rocking a similarly steaming pile with some other ORM/unit-of-work-type implementation. Keep playing along at home, mentally adjusting my terminology to whatever busted situation you’re holding onto over there. I’ll make it worth your while.

How to Approximate Application_Start in SharePoint Like a Gentleman

Sometimes, you just need to start something.

application_start_in_sharepoint

In a typical ASP.NET application, if we need to start something when it cranks to life in IIS, we simply add some custom code to the trusty Application_Start handler in our Global.asax file:

public class OmgAwesomeApplication : System.Web.HttpApplication {
    protected void Application_Start() {
        // omg something awesome here
    }
}

In a SharePoint app, however1, there is no Global.asaxfile, and indeed no such trusty method. This is by design, of course–running custom code inside SharePoint means relinquishing some control, especially over shared territory like events in the HttpApplication‘s lifecycle.

Still. Sometimes, you just need to start something.

Good place to start, Init?

So how can we hook into the start of an application in a SharePoint context? Rather than waiting for a leg up from our Visual Studio project template, let’s use the old rusted side door in ASP.NET that takes us straight into the Application Start kitchen.

An HTTP Module is simply code that is configured to run in IIS in response to requests on the server. The IHttpModule interface provides one method named Init. On-label usage dictates that we use this method to subscribe to the given HttpApplication‘s BeginRequest and EndRequest events:

public void Init(HttpApplication application) {
    application.BeginRequest +=
        (new EventHandler(this.Application_BeginRequest));
    application.EndRequest +=
        (new EventHandler(this.Application_EndRequest));
}

Now clear your mind, and forget about subscribing to these events. For our purposes here, we just want to run some code one time (and one time only) when the HttpApplication starts up. And it just so happens that our Init function runs right when the HttpApplication starts up. So:

public abstract class ApplicationStartHandler : IHttpModule {
    protected abstract void OnStart();
    public void Init(HttpApplication application) {
        OnStart();
    }
    public void Dispose() { }
}

Notice that I’ve built this out as an abstract class. This is not just because I am a gentleman. It’s because I want to encapsulate the pattern of running our yet-to-be-written custom code in the Init function. It’s also because I want to name the pattern in a way that makes it readable and understandable. Plus? I’m fancy.

If you don’t already, you’re really going to appreciate this fanciness/gentlemanliness in a few minutes.

Pulling our socks up and moving on, let’s inherit ApplicationStartHandler, and override the OnStart method to do something interesting (like perhaps boot up a ServiceStack host):

public class ServiceStackStarter : ApplicationStartHandler {
    protected override void OnStart() {
        var host = new MyAwesomeAppHost();
        host.Init();
    }
}

One last step before our fanciness is ready for prime time: we must let IIS know that our module exists. We do this by registering it in the Web Application’s web.config file, under configuration/system.webServer/modules.

<add name="ServiceStackStarter" type="Fazzaro.Blog.ServiceStackStarter, Fazzaro.Blog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=544b79730baa4957" />

As you can see, this requires skill in the realm of obtaining the PublicKeyToken of your module’s assembly. Details on this yak-shavery can be found here.

And once that’s in? Cut, print. Golly, was that ever a piece of 1337 SharePoint hax0r cake2.

Um. Hey, why is the server room on fire?

Multithreading, Mutual Exclusion, and the Advantages of Having Been a Gentleman

Yeah. IIS is a web server. And when we inject code into its very guts like this, we have to account for the fact that multiple instances of said code are being run at any given time.

To pull off the fix for our original cavalier implementation, we must add a static flag and a mutex to the ApplicationStartHandler class, using them in combination to ensure that the OnStart method is run once (and only once):

public abstract class ApplicationStartHandler : IHttpModule { 

    private readonly static object _mutex = new object(); 
    private static bool _initialized = false; 

    protected abstract void OnStart(); 

    public void Init(HttpApplication application) { 
        if (!_initialized) 
            lock (_mutex) 
            if (!_initialized) 
                Application_Start(); 
    }

    private void Application_Start() { 
        _initialized = true; 
        OnStart(); 
    }

    public void Dispose() { } 
}

Our OnStart method will now indeed run once and only once when the HttpApplication starts up, with no Global.asax in sight. And because we were gentlemen about the whole abstracting thing, our consuming code (in this case, the ServiceStackStarter class above) need not change in response to this fix.

This isn’t the first time I’ve noted here that standing on the shoulders of giants sometimes means leaving one of your favorite tools down on the ground. The trick is to stop being so shy about asking the giant to hand you a screwdriver.


  1. I’ve really got to stop beginning all of my sentences like this.
  2. Mmm. 1337 SharePoint hax0r cake.

Here’s How To Make Sure You’re Not Returning Zombies From An MVC Action

So there I was, minding my own, returning a Thing from a Controller Action as JSON. Like you do.

public ActionResult GetCriticalUpToTheMomentSortOfData(int id)
{
    using (var db = new ThingiesContext())
    {
        var thing = db.Things.Find(id);
        return Json(thing, JsonRequestBehavior.AllowGet);
    }
}

 

zombies1

One of my very favorite slightly off-label uses for ASP.NET MVC has been[1] to use an Action method as a mini-web service, returning data rather than markup. But this day, it wasn’t my very favorite slightly off-label use. It wasn’t even my second favorite.

I was sure that the value in the database was getting updated (by my actual favorite code, not listed). I queried, and queried again, my over-caffeinated eyeballs riveted to the results grid in SQL Server Management Studio. But, says my $.ajax() success callback, he says, the call is still returning the old value. The method was very straightforward about getting that value afresh from the database and returning it, and so I began to question the most basic of my nerdly assumptions. Do I have the right connection string? Should I even be using SQL anymore? Is the fabric of the universe collapsing?

After a therapeutic session of pacing and taking in some Carl Sagan to re-staple my faith in the sturdiness of the cosmos, it dawned on me that this particular service call was in fact an HTTP request made from a browser. And yes, the damned thing was caching.

Here’s What I Did After I Was Finished Shaking My Fists At The Sky During A Torrential Downpour

To remedy any further zombie data tomfoolery, I have here a NoCacheAttribute class that inherits from ActionFilterAttribute:

public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var cache = filterContext.HttpContext.Response.Cache;
        cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        cache.SetValidUntilExpires(false);
        cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        cache.SetCacheability(HttpCacheability.NoCache);
        cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

This meek mod merely intercepts the result, grabs ahold of the HttpResponse‘s cache settings and beats them soundly about the head and shoulders until they are certain that they’re not going to cache anything that comes from this response. Like, ever.

And here’s me using it in an demonstrable sort of way with my code from before:

[NoCache]
public ActionResult GetCriticalUpToTheMomentSortOfData(int id)
{
    using (var db = new ThingiesDataContext())
    {
        var thing = db.Things.Find(id);
        return Json(thing, JsonRequestBehavior.AllowGet);
    }
}

Now I can sleep again, lullabied into rapid eye movement by the knowledge that this call is always returning the most up-to-the-moment-as-possible values, as advertised. And that another zombie apocalypse has been narrowly averted.


  1. “Has Been”, because it’s worth noting that this off-label silliness is about to not even be a thing anymore—ASP.NET 4.5’s Web API places this sort of action squarely on-label, and renders the whole Night Of The Living Data thing irrelevant for anyone who isn’t maintaining the last few year’s worth of terribly clever MVC code.That is not to mention that the first step to that sort of gig would be to upgrade to a proper Web API.Anyway.