Tag Archives: ASP.net MVC

Debug JavaScript in MVC

Most JavaScript libraries come with a minified version that is quick to load, and a debug version that lets you debug issues. In ASP.net MVC you really want to be using the debug JavaScript while developing, and the minified Javascript when your site goes into production. I thought up this handy tip that gives a good return, for little investment.

Step 1: Change your layout pages to reference your JavaScript files via a UrlHelperExtensions class.

Step 2: In the UrlHelperExtensions class write some code like this:

public static string Scripts(this UrlHelper helper, string fileName)
{
    return helper.Content("~/Content/Scripts/" + fileName);
}
public static string knockout(this UrlHelper helper)
{
    if (System.Diagnostics.Debugger.IsAttached)
        return Scripts(helper, "knockout-1.2.1.debug.js");
    return Scripts(helper, "knockout-1.2.1.js");
}
public static string CDNjquery(this UrlHelper helper)
{
    if (System.Diagnostics.Debugger.IsAttached)
       return "//ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js";
    else
        return "//ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js";
}

The jQuery example here is using a CDN in the hopes that the visitor already has it in their browser cache.

Now your JavaScript will load quickly and you can still debug during development.

Skipping MVC web.config files with msdeploy

This post describes how to deploy a ASP.net MVC web application with msdeploy, while skipping the overwriting of the root web.config file. Sounds easy, what could possiblie go wrong? Well, msdeploy can be a real pain to try and figure out, but at least it’s the sort of thing you write once and keep in the back pocket.

This example deploys from an existing ‘last build’ staging area to a ‘beta’ staging area but doesn’t copy across the configuration or error files.

"c:\Program Files\IIS\Microsoft Web Deploy V2\msdeploy.exe" -verb:sync -source:iisApp="LastBuild" -dest:iisApp="Beta" -skip:objectName=dirPath,absolutePath="elmah" -skip:objectName=filePath,absolutePath="^((?!Views).)*web\.config$" -skip:objectName=filePath,absolutePath="settings-override.xml"
pause

The tricky bit that this command is handling is that MVC doesn’t just have the one web.config file. Each view folder also contains a web.config file used by the view engine, so simply ignoring files name web.config will deploy a broken web application. The example above works because msdeploy allows regular expressions, this regular expression skips over the web.config in the root directory but still copies over the others that are in ‘Views’  folders.

You can see how the regular expression works at this handy site.

Introducing Benchy

Benchy is an open source .net tool for benchmarking the execution speed of sections of code after each build. Benchmarks are graphed so that changes to performance characteristics in builds can be easily visualised.

I created Benchy because I wanted to do some performance tuning, but I was reluctant to start without having a reliable way to measure the results of my changes over time. I also wanted to be able to see when changes were introduced that had negative impacts on performance. Benchy is my first complete and released open source project. Starting things is hard, finishing things is even harder.

It was fun to be able to start a fresh green fields project that has potential to be useful. As Benchy is a simple system and a new project, I found it was pretty straightforward to write tests first and do Test Driven Development. (TDD with .net, it exists!) I often feel uneasy making things more complex than they need to be, so I was glad that I used Moq for the tests. I really liked not having to add a whole bunch of extra cruft to mock out dependencies during testing.

I shamelessly stole most of the framework concepts from nUnit.

I used flot for graphing the benchmark results.

Read all about it on its dedicated page at http://www.keza.net/benchy/

Or have a look at the source at https://github.com/kezakez/Benchy

Thanks to the company I work at for supporting my ideas and open source.

Client Side Validation of Dynamically Loaded Input Fields in MVC3

In MVC3 it’s possible to enable client side validation of dynamically loaded input fields by marking up the associated models with attributes via unobtrusive javascript. The result is validation code that is executed straight away on the client side to give the user feedback as well as on the server side to stop bad data from being entered. This approach is a double edged sword, since on one hand you get client and server side code for free, but you’re also limited to a few different kinds of input validation. The other catch associated with this approach is if you are dynamically loading form fields into your page that you want validated, it will not work automatically. 

To understand why, let me tell you a story that explores the depths of your model’s views and controllers as well as the life of your page.

First, your controller is accessed by the incoming request.

Then your controller will load up a model that has properties marked up with validation attributes.

The model is passed to the view.

When the view engine starts pumping out the resulting html it sees the attributes and the unobtrusive javascript settings and adds extra attributes to your html.

The request is fulfilled and the page content is loaded into the browser.

When the page is loaded the unobtrusive and validation javascript scripts are loaded and the validation script adds event handlers to the fields on the page.

It’s at this point that validation should work as expected.

However, if you make an AJAX request that gets a different form or more fields to show on the page, the new content will not run the client side validation.

This is because the content we loaded via the AJAX request is not hooked up like the fields that were there when the page first loaded.

So to get around the issue, all we really need to do is hook up the fields that were dynamically loaded into the page. This can be achieved by adding a bit of javascript to where you are dynamically loading your new fields:

$("#contentid").load("/ContentUrl", postData, function (responseText, textStatus, xmlhttpRequest) {
  if (textStatus == "success") {
    jQuery.validator.unobtrusive.parse("#contentid");
  } else if (textStatus == "error") {
    $("#contentid").html(responseText);
  }
});

The important bit in this code snippet is where we call jQuery.validator.unobtrusive.parse, this hooks up the validation functions to the control events that are required for unobtrusive validation. Now that you can validate input, don’t be a validation nazi.

Server-Sent Events in ASP.net MVC

Google Chrome (Chromium) recently released a version of their browser with support for server-sent events. I used this technology and ASP.net MVC to create a WebSlides application.

I created a nifty throw-away demo called WebSlides that switches between slides (PNG images). The slide show presenter navigates to a URL on their smart phone and is able to tap on back or forward links to change the current slide. The audience and the computer running the projector run a browser that points to another URL. As the presenter changes the slide all the clients connected see the updated slide.

What is a server-sent event?

Basically a server-sent event is a draft web standard that (on the ball) web browsers support to allow updates from the server to be “pushed” out to the browser. It is similar to WebSockets which has been all the rage (with cool experiments) but it is not a duplex communication channel. When you see the term “pushed” in regard to server-sent events you should note that what is actually happening is that the browser is actually polling a server URL. You can easily see this when you intercept traffic with fiddler. What it means though is you will not have to write the JavaScript to do the polling and it also gives you a way to only send data to the client when it is required. In my case I use it to update the slide the browser is showing when the presenter changes the slide.

How did I do it?

I created the WebSlides demo using ASP.net MVC, I believe I am the first to create something like this as support for server-sent events is pretty fresh. I found that this guy created a chat client with cold fusion on the server-side which is pretty cool.

In my demo I created a new ActionResult called ServerSentEventResult that does all the heavy lifting you need to do make the browser happy.

So all you have to do is use it like this in your controller.

ServerSentEventResult eventStream = new ServerSentEventResult();
Follower followerModel = new Follower();
eventStream.Version = followerModel.Version;
eventStream.Content = () =>
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.Serialize(followerModel);
};

Another interesting point to note about my implementation is the lambda used to get the content, you may remember that the browser will poll the server to get events, so why make the server serialize data if it is not necessarily going to send it every request.

The rest of the magic happens on the client side with jQuery, If you have come this far I will leave it to you to dig around on github to see how that works.