June 2010 Entries

Policing ActionResults

In the previous post we looked at using unit tests and reflection to ensure every controller derived from a specific base class in an ASP.NET MVC application. You might use a base class to ensure action filters are always in place for auditing, logging, or other general purpose security and runtime diagnostics. You can also use action filters to inspect the result of a controller action. For example, you might want to check the Url of every RedirectResult to prevent  open redirects in your application. Spammers love sites with open redirects. Edit: thanks, Sergio for catching...

Enforcing a Base Controller

In the previous post we talked about using a base controller class in ASP.NET MVC. The truly paranoid will worry about new developers on the team who don't know the rules and don't use the base class. One automated solution to this problem is to write a unit test to enforce the rule. [TestMethod] public void AllControllersDeriveFromFootballController() { var badControllers = GetConcreteTypesAssignableTo<IController>() .Where(TypeIsNotDerivedFrom<FootballController>); if(badControllers.Any()) { var controllerNames = AggregateTypeNames(badControllers); ...

Action Filter versus Controller Base Class

One of the features (or challenges) with ASP.NET MVC is the number of approaches you can use to successfully implement a feature. Take the "log each action method" requirement. One possible approach is to use a custom action invoker, however, an action invoker already has enough responsibilities (see Jonathon's post), and also has a fairly low level API. A custom action filter is the better choice. public class LogAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // ... log stuff before execution ...

A Pictorial and Prose Filled Guide To Impressing Designers

“Is the software installed?” asked my friend Kenny Cole. “Yes”. Our eyes tracked the mouse on screen as I right-clicked on a project and picked Open With –> Expression Blend 4. Diodes flickered. Hard drives whirred. A dialog box appeared.     Kenny’s angular face raised an eyebrow.  “A modal dialog ... interesting start,” he said. “Yes,” I replied with a nervous laugh, “well, this only happens once in a blue moon”. I moved the mouse and clicked Close as fast as possible. Diodes flickered. Hard...

Optional Parameters Do Not Create Default Constructors

At least not from the reflection API's point of view. For example, given the following class ... public class Wig { public Wig(string name = "Angry") { // ... } } ... you can successfully instantiate the class as if it had a default, parameterless constructor: var wig = new Wig(); However, trying to do this via Activator will fail: var wig = Activator.CreateInstance<Wig>(); // MissingMethodException: // No parameterless constructor defined for this object. Which makes sense once you realize optional parameters are compiler sugar, and the following code...

Checking Client Download Success with ASP.NET MVC

Scenario: You want to know if a client completes a large download successfully. Possible Solution: Create a custom ActionResult (perhaps derived from FileStreamResult) that streams the data and checks to see if the client remains connected. public class CheckedFileStreamResult : FileStreamResult { public CheckedFileStreamResult(FileStream stream, string contentType) :base(stream, contentType) { DownloadCompleted = false; } public bool DownloadCompleted { get; set; } protected override void WriteFile(HttpResponseBase response) ...

Parr's Rules for MVC Views

There are a number of ideas to chew on in this 6 year old paper by Terence Parr: "Enforcing Strict Model-View Separation in Template Engines". Parr is one of the creators of the StringTemplate template engine, which is ".. as simple, consistent, and powerful as possible without sacrificing strict model-view separation". One of the highlights is the list of 5 rules implied by strict separation. Parr introduces them like so: Before formalizing my intuition, I kept a few simple rules and tests in mind to evaluate entanglement. Could I reuse this template with a completely...

NDC 2010 Wrap Up

I was in Oslo, Norway the week of June 14th for the Norwegian Developer’s Conference. One of the recurring side conversations I had at this conference centered around the contrast between a vendor led conference and an independent conference (like the NDC). If you’ve only been to vendor conferences then you owe it to yourself to experience the amazing depth and breadth of the entire .NET world. Sure, the NDC had sessions on the latest bits from Window Azure and Windows Mobile, but the following topics did not fall into the minority: Life beyond...

Of .prototype and function()

Years ago, when I began to take JavaScript seriously, I thought prototypical inheritance was marvelous. Accordian = function (element, isOpen) { this.element = element; this.isOpen = isOpen; } Accordian.prototype = { open: function () { // ... }, close: function (value) { // ... } }; It took some time, but eventually I wondered if using an OOP approach in page scripts was like using cranes to tow compact cars....

Make the JavaScript Test Pass

Add code on the commented line: var f = function () {           var value = // ???    return f.sum = (f.sum || 0) + value;} ... to make the following QUnit test pass: test("Running sum", function () {     equals(f(3), 3);    equals(f(3), 6);    equals(f(4), 10);     jQuery([1, 2, 3]).each(f);    equals(f(0), 16); }); Possible Answer It's a goofy scenario, but one possible solution uses a technique you'll see frequently inside today's JavaScript libraries. First, we'll need to use the implicit arguments parameter inside the function f, and take (pop) just the last value. This would be trivially easy if the arguments parameter was...

When Your ASP.NET MVC Custom Error Doesn't Render...

You've put [HandleError] on your controller and you've set <customErrors mode="On"> in the web.config file. So why do you still see the yellow screen of death? I've heard various wrong explanations for this phenomena, including "it only works under IIS" and "it only works in release mode". But the custom error view does work in debug mode and it does work with the Visual Studio WebDev web server. I think the most common reason for the error view not to display is because the error view throws an uncaught exception. The first place to check when the...

Testability & Entity Framework 4.0

This white paper describes and demonstrates how to write testable code with the ADO.NET Entity Framework 4.0 and Visual Studio 2010. This paper does not try to focus on a specific testing methodology, like test-driven design (TDD) or behavior-driven design (BDD). Instead this paper will focus on how to write code that uses the ADO.NET Entity Framework yet remains easy to isolate and test in an automated fashion. We’ll look at common design patterns that facilitate testing in data access scenarios and see how to apply those patterns when using the framework. We’ll also look at specific features of the...

Visual Studio 2010 JavaScript Intellisense Behavior

After I installed Visual Studio 2010 I was having a difficult time editing .js files in Visual Studio. I habitually type the "(" character as soon as the function I want to call is highlighted in the Intellisense window, but in 2010 this behavior was no longer auto-completing the function name. At first I thought this behavior was due to the new "suggestion mode" in Intellisense, but no amount of toggling with CTRL+ALT+SPACE would bring back the auto-complete behavior. It turns out the two Intellisense modes (completion mode and suggestion mode) are not included...

Repositories and the Save Method

One of the questions I've been getting lately goes like this: Should a Repository class have a Save method? And the standard answer: It depends. It's hard to keep track of all the different approaches to implementing the repository pattern these days, but I assume when someone asks me this type of question they are thinking of using code like this: var employee = new Employee(); employeeRepository.Save(employee); var account = new Account(); accountRepository.Save(account); This style always strikes me as odd. It looks like code that wants to move away from...

Scott Allen
Posts - 869
Comments - 4493
Stories - 14