How to: Get anchor navigation working with Durandal

I’ve started using Durandal as my SPA framework of choice, and so far I really like it. I had actually written a (much less mature) framework to do lots of the same stuff – essentially, getting Knockout, Sammy, Require, jQuery, (etc) all working together – so I’m glad that I can now just use Durandal to do it all for me!

One disadvantage of the Single Page App model is that it “breaks” the traditional anchor navigation of HTML, since it uses the URL hash to define the route to be activated. This is a fair enough thing to lose given everything that you gain from using a single page app; however, it would be great if you could get the benefits of both – for example, to allow you to use a plugin like Bootstrap’s ScrollSpy.

tl;dr

  • You can use a regular expression which includes a bookmark hash when you’re configuring your URL;
  • You need to defer scrolling to your bookmark’s location until after the view has been attached;
  • You can use the routeInfo.hash passed to your view model’s activate method to generate your bookmark URLs dynamically.

Continue reading

Passing your ASP.NET MVC application’s base URL to javascript using RequireJS

I’ve been using RequireJS in conjunction with ASP.NET MVC on my latest project at work, and the combination is quite good! One thing I’ve struggled with though is passing the base URL of the application into my javascript files. Traditionally, I’ve done this using a property like UrlBase on the javascript window object, but now that just feels dirty.

Thankfully, there’s a fairly easy and clean way to accomplish this goal, which I’ll share with you now. First, you need to establish what the base url is. Lots of people seem to come up with a way to do this, but here’s the one that I find most reliable.


Update: Well, you learn something new everyday, and OJ has pointed out that there’s a far easier way, simply using Request.ApplicationPath. This simplifies things a lot, as we no longer need to push anything through the ViewBag; instead we can write the application path directly in the page when we’re defining our appConfig module.


Now, the “tricky” part – hooking this up using RequireJS. Scanning through the RequireJS documentation reveals that you can name your modules when they’re defined. Generally this is discouraged as it limits portability; but that’s ok for us here as portability is pretty much off the table.

The other key point is that you must not try to define your module before the require configuration has loaded. As you can see below, we’re defining a new module named appSettings after we’ve configured RequireJS:

<!-- Contains the require configuration -->
<script src="@Url.Content("~/Scripts/require.js")"
        data-main="@Url.Content("~/scripts/application")" 
        type="text/javascript"></script>
    
<!-- Inject an "appSettings" module -->
<script type="text/javascript">
    define("appSettings", function () {
        return {
            urlBase: "@Request.ApplicationPath"
        };
    });
</script>

From articles I’ve read on the web, there is a possible race-condition here – that require may not have finished configuring before the appSettings module is defined – but I’m yet to see this occur.

Anyway – now that we’ve got our appSettings module, we can just include it as a dependency for other modules when we need to:

define(["appSettings"], function (appSettings) {
    console.log(appSettings.urlBase);

    // Define your module!
});

And, once again, all is well with the world.

Unity, stop throwing SynchronizationLockException

I always like to call a spade a spade. So when it comes to having exceptions thrown, I’d like to think they pop up in exceptional circumstances. Unfortunately that doesn’t hold true when using Microsoft Unity IoC container.

Go ahead and turn on first-chance exceptions and you will notice everytime you call RegisterInstance Unity is throwing and catching a SynchronizationLockException.

The easiest way around this is to update Unity via Nuget since it has apparently been fixed in  2.1.505.2. But for those of us using it as part of Enterprise Library 5 or don’t have the luxury of upgrading the component, I prefer the following workaround proposed by Koen VV on StackOverflow:

/// <summary>
/// KVV 20110502
/// Fix for bug in Unity throwing a synchronizedlockexception at each register
/// </summary>
class LifeTimeManager : ContainerControlledLifetimeManager
{
    protected override void SynchronizedSetValue(object newValue)
    {
        base.SynchronizedGetValue();
        base.SynchronizedSetValue(newValue);
    }
}

Now just use this lifetime manager when registering your instance and you are good to go:

container.RegisterInstance(myInstance, new LifeTimeManager());

MVC 3 SEO Friendly URLs

Continuing on from my previos article on adding a xml sitemap, today we will be looking at adding seo friendly urls to MVC 3.

Rather than re-inventing the wheel here I would instead redirect you to this awesome article. One of the reasons I like this article is it still gives you the ability to use our database indexes since we are still getting our products by their primary key.

The only thing I would add to the article is the ability to redirect mysite.com/Product/1/RandomString to mysite.com/Product/1/Product-Name since we already know what product the user is trying to access if the typo is in the product name. This is also handy if you have already deployed your website with the previous routes.

string expectedName = product.Name.ToSeoUrl();
string actualName = (productName ?? "").ToLower();

// permanently redirect to the correct URL
 if (!string.Equals(expectedName, actualName))
 {
 return RedirectToActionPermanent("Details", new { productName = expectedName });
 }

Now all we need to do is update our MVCSiteMapProvider from before:

var node = new DynamicNode();
node.Title = product.Name.ToSeoUrl();
node.RouteValues.Add("id", product.Id);

Hardcore PNG Optimization

Image optimization is one of the necessary evils when it comes to fast websites. Until we live in a world where things perform by default, this will be the case.
As a happy customer who purchased a license to PNGOutWin, I take great interest in creating the smallest png files possible. There are currently plenty of tools out there you can use to get the job done. Namely (not including online tools) :

While blogging about image optimization isn’t new, there was recently a great tool that caught my eye – PngSlim. It is a drag and drop batch file that you can use in windows to squeeze out every last byte of those png files. While it takes a while and only uses one thread, I find it consistently able to grab a few more bytes than the above mentioned solutions. If you do head over a download a copy I would recommend updating the individual utilities in the apps folder for the best output.

While I don’t recommend using PNGSlim as a post build option because of it’s speed – you can always use it on your images before you add them to your solution. One of the best things I love about PNG optimization is that because it is lossless you aren’t losing any information, regardless of the number of programs you put it through!

Building Single Page Web Apps for Desktop, Tablet and Mobile

Gone are the days when you can get away with building web applications that make repeated trips to the server to render html. Thanks to the proliferation of apps on devices like iPhone, iPad and Android, users now expect a fast, rich, engaging experience while using their apps. Any lag – perceived or real – is no longer acceptable.

The mobile OS makers (apple, google, MS, etc) will push you toward building native applications using their custom frameworks – but who wants to learn a new programming language and application framework?

I have years of experience using open web technologies, why can’t I use these skills? And can I use these skills and deploy into the mobile market places?

Yes… You… Can…

With HTML5, CSS3, Javascript and some complimentary technologies you can build your application once and then customize it for each platform you wish to target.

First let’s start with the theory… the what, why and how questions for building single page apps.

Bert Appward’s Field Guide to Web Applications

NOTE: It would be foolish of me to favour or argue the value of the technologies, platforms and frameworks I’m about to propose over others. This article is but one of many that aggregates a list technologies that have or look to be useful for building SPA from my point of view. I welcome, and strongly urge you to leave a comment about your experiences with said technologies and leave recommendations for other technologies that you think are invaluable.

Data Access

There are numerous technologies – open-source & proprietary – that can be used to build your data persistence layer. This article focuses on .net technologies but I think it’s worth noting that that where you persist and query your data from is not as important as how you do it. In short to build a SPA you will want to provide a RESTful API that accepts and returns json.

The newly released Asp.Net Web API is the quickest and easiest way to build a RESTful API for your SPA to communicate with. It provides OData hooks and can sit on top of an Entity Framework instance.

Javascript client-side framework

To ease development and prevent re-inventing the wheel it’s best to utilize a mature and comprehensive client-side application framework. There are numerous javascript MV* (MVC, MVP, MVVM) frameworks knocking about but the framework the MS is backing is an MVVM framework called knockout.js. It has excellent documentation, a great tutorial environment and strong community backing.

Learn about knockout.js here (essential reading/watching)

learn knockout.js – interactive tutorials
Tutorial, benefits, comparisons with other frameworks
Building HTML5 and JavaScript Apps with MVVM and Knockout
note: you can sign up for a free trial account and watch the majority of these videos for free but you can’t go wrong spending the $50 for a months full access.

Now that you know a bit more about how knockout.js works, check out this TechDays talk – Building Single Page Web Apps for Desktop, Tablet and Mobile where Steve Sanderson walks you through a complete but brief implementation of a SPA using the ASP.NET WEB API, Knockout.js and some complimentary javascript libraries including history.js and upshot.js

The tutorials and documentation listed so far should get you well and truly started on the basics of building an SPA. As tutorials often focus on explaining a limited set of technology, the following section details complimentary frameworks and technologies that can help you with building a feature complete, efficient, maintainable SPA.

Complimentary technologies/frameworks

Javascript Dependency Resolution and Namespacing

You will want to avoid Javascript spaghetti and structure your client side application using structured folders, files and namespacing. The following libraries can help you out here.

  • requireJS – file and module loading – client side
  • cassette – asset bundling for .net – server side

CSS Pre-Processors (Amp up your CSS abilities)

Web to native mobile app frameworks

  • Appcelerator – build native apps using web technologies
  • KraniumJS – makes your appcelerator titanium apps a little more open web
  • PhoneGap – native app wrapper around browser control with exposure to device level APIs
  • AppMobi – native app wrapper around browser control with exposure to device level APIs

Data Libraries

  • YQL – Yahoo Query Language that let’s you go cross domain across web services

UI Frameworks / Widgets

Notification Frameworks

Responsive/Adaptive Design Techniques

Tools

  • Asana- Task Management (for Teams)
  • Visual Web Developer + Resharper + NuGet = a MS developers complete toolset?
  • Web Workbench for Visual Studio – syntax highlighter and intellisense for SASS, LESS and Coffeescript
  • BandAid – VS Debugger Extension
  • Google Chrome + Window Resizer & YSlow extensions
  • IDEA – WebStorm – alternate IDE with top of the line Javascript/HTML support and refactoring
  • LinqPad - execute Linq queries against your DB

Have you had success with any of the above technologies?
Do you rate a particular framework/technology/platform over another?
Are there any other tools, frameworks or services that I should take a look at?

Great .NET Interview Questions

Most of you out there probably already subscribe the blog of Scott Hanselman (if you don’t you should). For those that don’t I urge you to check out the follow list of great interview questions. They are very helpful for when you need to do a technical interview. In saying that, even if you aren’t interviewing someone, I would recommend you check them out for yourself. See how you go – I for one had to google what a web garden was. What did you learn? Are there any questions you would add to the list? I for one would add a question about contravariance and covariance to the Senior .NET section.

MVC 3 XML Sitemap

Ok, so you’ve got your shiny new mvc3 app up and running. Now, it’s time to bake in some of that SEO goodness. Here’s how you can easily add a sitemap.xml to your new mvc application. The solution specified below not only pumps out the xml file to submit to the search engines, but it is also a System.Web.SiteMapProvider, so you can use it for menus and wherever else you want to use your sitemap.

I’m a big fan of NuGet, so bring up the Package Manager Console and grab MvcSiteMapProvider (or download it from github).

Install-Package MvcSiteMapProvider

Once it is installed there will be a new Mvc.sitemap file added with the following to your solution:

<mvcSiteMapNode title="Home" controller="Home" action="Index">
    <mvcSiteMapNode title="About" controller="Home" action="About"/>
</mvcSiteMapNode>

Now for the easy bit: to get a ~/sitemap.xml to auto-generate for us based on our controller actions we specified in the sitemap file above. All you need to do is simply add the following to your route registration (generally Global.Application_Start()):

XmlSiteMapController.RegisterRoutes(RouteTable.Routes);

Now, like a lot of other people out there my next question was, what about my dynamically generated content from the database (such as Product/Details/1)?  Easy – MvcSiteMapProvider comes with dynamic node support. Just create a class like the following:


public class ProductDetailsDynamicNodeProvider : DynamicNodeProviderBase
 {
     public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
     {
         // Create a node for each product
         foreach (Product product in productService.GetAllProducts())
         {
             var node = new DynamicNode();
             node.Title = product.Name;
             node.RouteValues.Add("id", product.Id);

             yield return node;
         }
     }
     public override CacheDescription GetCacheDescription()
     {
        return new CacheDescription("ProductDetailsDynamicNodeProvider")
        {
            SlidingExpiration = TimeSpan.FromMinutes(60);
        };
    }
 }

Things to note with the above code: you don’t have to override the cachedescription method, but this does allow us to specify how long all our products will be cached for in the sitemap. Then, you can add your dynamic node to the mvc.sitemap files as follows:

<mvcSiteMapNode title="Details" action="Details"
dynamicNodeProvider="Website.ProductDetailsDynamicNodeProvider, Website"/>

Now you are done and have a working auto-generated mvc sitemap. For those of us who are using it to generate breadcrumbs, check out the awesome example of html helpers in the documentation.

Next time, I’ll be looking at creating SEO friendly URLs in MVC.

Overriding the default serialization behavior in Json.NET

We use Newtonsoft Json.NET heavily in our project to control our JSON serialization. For the most part, it works absolutely perfectly out-of-the-box, but every now and then, we need to customize the way that serialization works for a particular object.

Such an occasion occurred today. Basically, I have a list of EmployeeActivity objects – where each instance is a subclass of EmployeeActivity. So, for example:

public abstract class EmployeeActivity
{
    public TimeSpan Start { get; set; }
    public TimeSpan Stop { get; set; }

    public virtual bool IsAvailable
    { 
        get { return false; }
    }
}

public class AbsenceActivity : EmployeeActivity
{
    public string Reason { get; set; }
}

public class BreakActivity : EmployeeActivity
{
    public string BreakName { get; set; }
}

json.NET does a perfect job of serializing my objects, and they rebuild perfectly when I’m back in javascript land – however, I have no way of knowing the actual type of each activity in my array! To alleviate this, I wanted to create my own serializer which also injected the type name into each of the serialized objects – or at least, that’s what I thought I wanted to do!

As it turns out, there’s a bit of an easier option. JsonConvert uses a ContractResolver in order to work out how to Serialize/Deserialize each class, and you can override the default contract resolver when running serialization:

// This class contains the activity list
ActivityViewModel = new ActivityViewModel(DateTime.Today);

// Serialize using a custom contract resolver
string jsonViewModel = JsonConvert.SerializeObject(viewModel, 
    Formatting.None, new JsonSerializerSettings
    {
        ContractResolver = new ActivityJsonContractResolver()
    });

The contract resolver’s job is to return a JsonContract which describes the object to be returned. For a POCO, this would typically be an instance of JsonObjectContract, which (amongst other things) describes the properties of the class which should be serialized.

So, all I needed to do was to extend the contract for subclasses of EmployeeActivity, such that it inherited a new Property to be serialized:

public class DiaryActivityJsonContractResolver : DefaultContractResolver
{
    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        JsonObjectContract contract = base.CreateObjectContract(objectType);

        if (typeof(EmployeeActivity).IsAssignableFrom(objectType))
        {
            contract.Properties.Add(new JsonProperty
            {
                Readable = true,
                ShouldSerialize = value => true,
                PropertyName = "Type",
                PropertyType = typeof(string),
                Converter = ResolveContractConverter(typeof(string)),
                ValueProvider = new StaticValueProvider(objectType.Name)
            });
        }

        return contract;
    }
}

Truth be told, I’m not 100% sure if I need to implement as many of the properties on the JsonProperty that I’m creating. But you can see what’s going on here – I’m effectively telling the object contract that there’s an additional property called Type which needs to be serialized, that it’s a string, and that it should return whatever value is resolved by the StaticValueProvider. Speaking of which, here’s the last piece of the puzzle – a simple value resolver that always returns the same value:

/// <summary>
/// JSON value provider that always returns a static value
/// </summary>
public class StaticValueProvider : IValueProvider
{
    private readonly object _staticValue;

    public StaticValueProvider(object staticValue)
    {
        _staticValue = staticValue;
    }

    public void SetValue(object target, object value)
    {
        throw new NotSupportedException();
    }

    public object GetValue(object target)
    {
        return _staticValue;
    }
}

json.NET is fantastic, and it’s very extensible, but finding out where to start and what to do can be a little bit tricky. I managed to figure this out only by downloading the source files and poking through the code myself; hopefully this will be helpful to someone else in the same situation!

Extension methods for base/derived types

I had a situation today which I thought was prime for writing some extension methods: I wasn’t allowed to modify the original type, and I also couldn’t subclass it, either. Extension methods to the rescue!

One thing which made the situation slightly interesting though, was that the original type also had a whole bunch of derived types – and for each of them, I wanted to customise the relevant extension method! Well, that’s all well and good, but what I really wanted to know was: lets say I was operating on a collection of the base types (where each individual item was an instance of a derived type), which extension method would get invoked?

Only one way to find out – write some code! For simplicity, I used the base class Animal, and added two derived types: Dog and Elephant.

    public abstract class Animal
    {
        public string Name { get; set; }
        public bool HasBoyBits { get; set; }
        public abstract string Type { get; }
    }

    public class Dog : Animal
    {
        public string Breed { get; set; }

        public override string Type
        {
            get { return "Dog"; }
        }
    }

    public class Elephant : Animal
    {
        public bool HasTusks { get; set; }

        public override string Type
        {
            get { return "Elephant"; }
        }
    }

Now for the extension method: CanBreed. For the base type Animal, the rule was simple – the animals had to be of the same type, and of the opposite sex:

    public static class AnimalExtensions
    {
        public static bool CanBreedWith(this Animal animal, Animal other)
        {
            return animal.Type == other.Type 
                && animal.HasBoyBits != other.HasBoyBits;
        }
    }

For dogs, we only want to breed with dogs that are already of the same pedigree; and for elephants, we only want to breed with other elephants that have the same tusk status (yes, it’s pretty ambiguous, but whatever):

    public static class DogExtensions
    {
        public static bool CanBreedWith(this Dog dog, Animal other)
        {
            return AnimalExtensions.CanBreedWith(dog, other)
                && ((Dog) other).Breed == dog.Breed;
        }
    }

    public static class ElephantExtensions
    {
        public static bool CanBreedWith(this Elephant elephant, Animal other)
        {
            return AnimalExtensions.CanBreedWith(elephant, other)
                && ((Elephant) other).HasTusks == elephant.HasTusks;
        }
    }

Finally, the test data: two lists of animals, separated by gender:

    var baxter = new Dog { Name = "Baxter", HasBoyBits = true, Breed = "Jack Russell" };
    var missy = new Dog { Name = "Missy", HasBoyBits = false, Breed = "Jack Russell" };
    var jazzy = new Dog { Name = "Jazzy", HasBoyBits = false, Breed = "Poodle" };

    List<Animal> boys = new List<Animal>
    {
        baxter,
        new Elephant { Name = "Lance", HasBoyBits = true, HasTusks = true }
    };

    List<Animal> girls = new List<Animal>
    {
        missy,
        jazzy,
        new Elephant { Name = "Renee", HasBoyBits = false, HasTusks = true },
        new Elephant { Name = "Hephalump", HasBoyBits = false, HasTusks = false }
    };

Now, what I had to test was if .NET would use the Runtime type of each animal to work out which extension method to invoke. I was pretty confident that both of these would pass:

    Assert.IsTrue(baxter.CanBreedWith(missy));
    Assert.IsFalse(baxter.CanBreedWith(jazzy));

And sure enough, the unit test succeeds with flying colours. However, to make things slightly trickier, what if we do this?

    foreach (var boy in boys)
    {
        foreach (var girl in girls)
        {
            bool canBreed = boy.CanBreedWith(girl);

            Console.WriteLine("{0} can{2} breed with {1}",
                boy.Name, girl.Name, canBreed ? String.Empty : "'t");
        }
    }

Unfortunately, here’s what the output looks like:

Baxter can breed with Missy
Baxter can breed with Jazzy
Baxter can’t breed with Renee
Baxter can’t breed with Hephalump
Lance can’t breed with Missy
Lance can’t breed with Jazzy
Lance can breed with Renee
Lance can breed with Hephalump

So we can see that the animals aren’t allowed to breed when they’re of differing types (hence AnimalExtensions.CanBreedWith is being invoked); however, each type of animal is allowed to breed with any other animal of the same type. No joy! (Well, joy for the animals I suppose…)

On retrospect, this is pretty much the behavior that I expected, but I was still disappointed to find out that I had been right. Worse still, once the sample code was up and running, I thought, “Hey, I should have used Rabbits instead of Elephants, and then always returned false in the CanBreed method, because that would have been funnier”. Ahh, hindsight, where were you before?

Oh well. Time for some refactoring!