Wednesday, 17 February 2010

Resx Resource Problems when Unit Testing

If you use resx files for something like translations in your web apps, you'll notice problems when unit testing as your web app won't be running in its natural state and those resources won't be loaded as normal. Typically you'll get the error...

Could not load file or assembly App_GlobalResources


I'm yet to find a decent solution for this problem but here's how I currently get around it in MVC apps. Here I'm replacing my dependency on Strings.resx in App_GlobalResources.

First thing to do is to create a ResourceManager property and make use of this instance within the class you're testing. Now whenever you need to make use of the resource you have to replace the normal syntax of Strings.FieldYouWant with StringsResource.GetString("FieldYouWant") as shown in the method MethodBeingTested().

public class MyController
{
   public ResourceManager StringsResource
   {
      get;
      private set;
   }

   public MyController()
       : this(Strings.ResourceManager)
   {}

   public MyController(ResourceManager stringsResourceManager)
   {
      StringsResource = stringsResourceManager;
   }

   public object MethodBeingTested()
   {
      return new ContentResult( StringsResource.GetString("FieldYouWant") );
   }
}

In your test project you'll need to create a Strings.resx mirrored source file and make use of this when testing MyController class. Do this by instantiating with a resource from the calling test assembly...

var stringsResource
   = new ResourceManager("test.assembly.Strings", Assembly.GetExecutingAssembly());
var controller = new MyController(stringsResource);
...not pretty, but at least you can run your unit tests without an exception slapping you around the face. Any one got a better solution?

Tuesday, 16 February 2010

Using Analytics to Track Events & AJAX Navigation

Google Analytics is THE way to record and analyse everything about the traffic on your site. Whilst it's real easy to setup you need to change the default behaviour if you want to record javascript events and AJAX navigation changes; this is how to do exactly that.

Analytics requires two things to work. You need the Analytics resource on the client...

<script type="text/javascript">
   var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
   document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
...and call the tracker with your unique ID (provided when you sign up)...
<script type="text/javascript">
   try {
      var pageTracker = _gat._getTracker("123456789");
      pageTracker._trackPageview();
   } catch (err) { }
</script>
...it's the pageTracker._trackPageview(); part that sends the data to Google Analytics. Without parameters the current URL is sent. However, you can override the default behaviour and pass the URL as an argument.

So change the second part to...

<script type="text/javascript">
   try {
      var pageTracker = _gat._getTracker("123456789");
   } catch (err) { }
</script>
...then you can call pageTracker._trackPageview('/My-Virtual-URL'); with your 'virtual' URLs at will - perfect for recording javascript events and AJAX navigation changes :)

Wednesday, 10 February 2010

Hudson as an Alternative to TFS

I've been looking at alternatives to Team Foundation Server for my latest project's continuous integration tool... and I think I've found it!

Hudson was suggested to me by a colleague (Jonathan Relf) after his attempts with Cruise Control became a little frustrating.

You'll have Hudson installed and building your projects in under an hour unless you're stupid or get carried away with the large number of plugins, including a Chuck Norris plugin ;)

Someone has too much time on their hands...

I particularly enjoyed...

  • VERY easy to setup
  • LOADS of plugins
  • Setup, monitioring and configuration is all through a nice web based interface

I'll keep you posted with how I get on.

Wednesday, 27 January 2010

Unit Test Naming Conventions

Unit test names can be horribly long and misleading at times. I particularly hate...

AMethod_That_IS_Long_n_HasUnderscores_AT_Random_Points

Naming them in a concise, clear manner is important but consistency is the key. I use a simple convention to help me with naming my test methods that I've seen others use.

// MethodNameBeingTested_Input_Output
ToySearch_WhenNoToysFound_ReturnsZeroToysFoundView

Steve Sanderson suggested (on his blog) that we call this naming convention SSR (Subject, Scenario, Result), sounds good to me :)

IE AJAX Caching Issue

I don't want to pick on IE again (it has been less than 24 hours since my last post about IE), but I'm afraid I have to. I've been working on a new project recently that makes use of AJAX. I usually develop in Firefox and then fix all my IE problems afterwards. This time however one of my AJAX areas of the site seemed to rarely update in IE (if at all), other browsers were fine.

After some playing around I came to the conclusion that IE was caching my AJAX requests. You could argue that IE is right to cache the requests, as the HTTP spec states that GET requests should be cached. But given the browser knows a XMLHttpRequest is being made the caching is completely uneccessary/unwanted. Once I knew the problem the fix was easy. I just needed to append something random to the request URI, a number or timestamp for example.

So instead of requests to /Resource, just use /Resource?ie={random}. It's fairly straight forward to generate a random number in Javascript:


// Random number between 0 and 100
Math.floor(Math.random()*101);


Realising that I wouldn't be alone in tackling the issue I found people used similar tactics to get around the problem. Another neat way is to change the request to be a POST.

IE6? Time to Upgrade Says Microsoft

IE6 we haven't been friends for a while now. We haven't been able to sit at the same desk for some time, around seven years without an argument starting.

Needless to say I am not in the least bit sad to hear you are finally being ousted by your makers; Microsoft are trying to get the heavily used browser's users to upgrade. Although web savvy users have updated their browser, Microsoft is targeting the tough cookies and touting its own IE 8 as a better alternative.

It's about time :)

Tuesday, 26 January 2010

Syntax Highlighter for C#, XML, SQL and More

I used SyntaxHighlighter before on my last blog and it is perfect for putting snippets of code up with your blog posts. Looks like its come on a treat too and even offers hosted source files for those of us without access to file hosting (and those of us too lazy). Would like to see them using a CDN for the hosted files though - maybe the Amazon S3 service.

Plugging the highlighter couldn't be easier, just refererence a few CSS and JS files. There's a quick explanation here of getting the hosted version working on your blog.

Example using syntax highlighter...

string output = "SyntaxHighlighter is brillo!";

// Tell the world...
Console.WriteLine(output);

Why oh why?! - Take 2

So I’d gone and done it. Finally created a new blog on the impressive tumblr platform. But soon ran into problems when I wanted archive and category features on the micro blogging platform. Not even the new kid on the block Posterious had all the features I needed. So I decided to come back on Blogger and give it another chance. After all it's quick, customisable and has all the features I need right now.

So why start a new blog anyway?… Well my last blog was getting around 3000 hits a month before I stopped posting entries around 18 months ago and its still getting 2000 now. I found posting little snippets for getting around bugs and problems I had stumbled across were not just good for me to record for future reference, but the blog posts that people found most useful.

Every developer uses the net to find solutions for the problems they come across and this blog is my contribution to the developer communities; hope you find something useful :)