Jamie Penney

Moving to Medium

I've decided to move my blog over to Medium since even the slightest impediment to writing will stop me from blogging regularly. Will be quite a bit easier to update and zero maintenence so with any luck there'll be a bit more content in the future.

New Job at Raygun.io

This week I started a new job at Raygun.io, working on their error tracking software. Good times! I wrote a post for their blog about Resharper, you should check it out.

Getting the Most Out of Heroku’s Freebies

I used to use Heroku a few years back whenever I needed a little bit of Ruby on Rails hosting, but then I started needing background workers (which you can’t get for free) and larger databases so I shifted to self-hosting. I already had a Rimuhosting VPS, so it didn’t make sense to spend money when I didn’t need to.

I’ve gotten sick of having to write cron jobs and organise monitoring and all that sort of busy work for what are pretty basic sites, so I decided to have another shot at using Heroku.

Turns out my current side project (a place my family and I can record and share our weight loss goals) fits within the free tier for everything except for the email notification jobs. Drat. Luckily I can minimise the cost of this by using a gem called HireFire. I will only need maybe a few minutes of worker time per month, and this gem will make sure that workers are spun up and down as needed so I don’t waste any money I don’t need to.

On top of that, there are a number of free Heroku Addons that can keep everything speedy on a low use site. The Memcache addon has a 5MB free option that you can hook into Rack::Cache and Rails for faster caching. If you are on a small site you will still get a bit of extra speed out of that.

This next trick is a bit cheeky, but it kinda fits with my monitoring needs any way. The New Relic addon offers uptime monitoring (as well as short term site performance stats), which it gives you by pinging your site on a scheduled basis. This has the side effect of keeping your app running - Heroku will shut down a free site that hasn’t been hit in a while. Still not sure if I’m ok with this or not…

There is one more thing you might overlook - Gzip compression of static assets. Heroku’s Cedar stack serves requests directly (see the HTTP Routing documentation)to the application stack, so you don’t get HTTP caching or gzip compression for free. Your app needs to handle these itself, but this is relatively easy. You need two pieces of Rack middleware: Rack::Cache and Rack::Deflater.

For Rack::Cache you will need to add the Memcache addon to your app in Heroku, install the dalli gem and setup the Rack::Cache middleware to use it by adding this to your config/environment/production.rb file:

config.middleware.use Rack::Cache, :metastore => "memcached://#{ENV['MEMCACHE_SERVERS']}", :entitystore => "memcached://#{ENV['MEMCACHE_SERVERS']}" While you are there, set the cache store to use Dalli as well with config.cache_store = :dalli_store

Using Rack::Deflater is easy as pie. In config.ru add the following right above your run MyApp::Application line: use Rack::Deflater In theory you shouldn’t need to do this. Rails 3.1 added Rack::Deflater by default, but the Cedar stack on Heroku doesn’t seem to do it. An unfortunate side effect of adding Deflater this way is it will gzip everything, including images. I’m still thinking of a way to get around this, probably with my own middleware wrapper around Deflater.

That’s all I’ve done so far and things are pretty snappy. If you have any other tips for making the most out of Heroku, let me know in the comments.

Getting SimpleCov and Spork to Play Together

I have been using SimpleCov to measure the code coverage of my specifications, and it has been excellent. I would recommend it, if only for how easy it was to get it working with RSpec.

I have run into one problem though - running it under Spork generates no results! As far as I can tell, this is a problem with the way Spork caches your application files. SimpleCov uses the Ruby 1.9 built in profiling features, and either 1.9 or Spork need the files under inspection to be loaded after the profiling has started. Unfortunately your application files aren’t reloaded when you are using Spork, that’s kind of the point!

Some people seem to be able to get away with merely turning off application file caching in config/environments/test.rb, but that didn’t work for me. Instead, I have come up with a different solution: Only turn on code coverage reporting when I run RSpec outside of Spork. At the top of spec/spec_helper.rb I have the following block:

  require 'simplecov'
  SimpleCov.start 'rails' do
    add_filter "/spec/"
  puts "Running coverage tool\n"

That way I can run RUN_COVERAGE=true rspec spec/ in the root of my application directory, and RSpec will run with SimpleCov enabled. As an added bonus, the code coverage metrics aren’t running on every test run, so my tests are faster!

Rails 3 Form Builder for Twitter Bootstrap Form Elements

Edit: I have updated this for Bootstrap 2. See the links at the bottom of the page for both versions.

I have been working on a website in my spare time to help me organise my life a bit better, and one of the things that always trips me up with these kinds of projects is the visual style. For a while I had a basic fixed width style I used, but it didn’t really fit properly with what I wanted to build. A little while after I had started, Twitter released Bootstrap, a nice looking CSS framework. I decided to have a go at using it on my site (in a separate git branch of course) and it ended up only taking me less than an hour to get it all up and looks alright.

One thing that bothered me though was the repetition in my forms - the format for showing labels that line up nicely next to the form elements was the same across all input types, and so was the error handling. This got me thinking: why should I retype all of this when the Rails FormBuilder class is already doing half the work? Surely I could just override some of the methods to make this work?

I needed to learn more about Ruby metaprogramming to get it to work - I still wanted the core functionality of the default rails FormBuilder, just with some extra DOM nodes wrapped around it. Ruby lets you redefine methods at runtime, but also allows you to alias the old methods so you can refer to them inside your new version of the method. So I ended up writing a method that does the Bootstrap boilerplate DOM wrapper creation and calls the original method to generate the input element itself.

I still haven’t overridden all of the FormBuilder methods because I need to actually test them (and I don’t have a use for them yet), but the basics are here in this Gist: https://gist.github.com/1236567. The methods I have overridden are in basic_helpers, the ones that output multiple inputs are in multipart_helpers. The great thing is I have only had to add method names to those two arrays as needed - none of the input types have needed special casing. This might not be the case for all of them, but one can only hope. If you do find this useful, or want to add and test some more of the helpers, please fork my Gist and leave me a comment.

Edit: Here are links to both the v1 and v2 form builders:

Version 1 form builder: https://gist.github.com/1236567 Version 2 form builder: https://gist.github.com/1829710

Testing Content_for in Rails 3.x Helpers With RSpec

After having a quick look around the net (and not finding anything up to date and useful) I came up with the following basic test structure for testing my ApplicationHelper methods that served up content_for things like page titles, javascript includes, etc:

require 'spec_helper'

describe ApplicationHelper do
  describe "title" do
    it "should call content_for(:title) with the title passed" do
      helper.title("title stuff")
      helper.content_for(:title).should == "title stuff"

Dependency Viewer

A while back I posted a quick app I wrote to display dependencies between visual studio projects using GraphViz (here). I’ve done a bit more work on it since then, cleaning up the project and adding support for custom processing of the graph elements before they are rendered using extensions. I’ve also put the project on GitHub for ease of updating. You can access that here: http://github.com/jamiepenney/VS-Dependency-Viewer

I’m going to talk about how the extension mechanism works. It uses the Managed Extension Framework (MEF), which you can read about here: http://www.codeplex.com/MEF. You don’t need to know a lot about MEF to write an extension - in fact you can get away without knowing anything apart from how to download it and which attribute to use on your extension class.

To create a custom graph processor, you’ll need to create a new Class Library project in Visual Studio. This project needs to reference Quickgraph.Graphviz.dll, System.ComponentModel.Composition, and DependencyViewer.Common.dll. The first two you can get from the lib directory in the Dependency Viewer project, and the Common dll you can get by building the DependencyViewer.Common project. Once you’ve got your project up and running, create a new class that implements DependencyViewer.Common.Interfaces.IGraphProcessor.

The IGraphProcessor interface is pretty basic so far. These are the important methods:

  • PreProcessGraph

    • This method lets you change formatting options on the graph before the other graph elements are processed. You could use this to set the size, background colour, etc.
  • ProcessEdge

    • This method lets you change formatting options on a dependency connection after the defaults have been set (there aren’t any defaults yet though).
  • ProcessVertex

    • This method lets you change formatting options on a project node after the defaults have been set. By default the Name is set to the name of the project and the shape is set to Ellipse.

You can have blank implementations of any methods you don’t need.

To get the main application to find your custom graph processor, you just have to register it as an implementation of IGraphProcessor by adding the Export attribute to your implementation. So in this case, you’d put [Export(typeof(IGraphProcessor))] on your class.

Once you’ve done that, build your project, copy the dll into the directory where you are running the main application, and then the magic happens. MEF will automatically pick up your implementation when you next render your solution.

There is an example implementation in the Dependency Viewer project called TestProjectProcessor. It finds non unit testing projects that reference NHibernate and colours them a different colour, so that you can see what projects refer to your data projects. I got the idea from Melle Koning’s blog post on the subject here.

NHibernate and the Repository Pattern

I’ve been writing a small time tracker web application to teach myself ASP.Net MVC, and am using NHibernate as the ORM. I’m trying to use best practises while building this app, and one issue I was trying to deal with was whether to build a layer over the top of NHibernate. My first set of controller actions used NHibernate directly, with a dependency injected ISessionFactory. This was fine for simple queries (like get Task with id 1) but it meant more and more of my model concerns were leaking into my Controllers. I had thought that NHibernate provided enough of an abstraction over my model for this to not matter, but I was quite wrong.

Remembering I had seen some argument over whether using a generic repository was a good idea or not, I started searching around and found quite a few blogs saying it was a bad idea. They made sense, and one blog had a great solution: Create a Repository<T, U> abstract class for common CRUD style operations, inherit your specific Repository from that, and only expose meaningful methods in your interface to client code. The benefits of this approach are many - your client code can only see methods that are applicable to each model class, you don’t have to duplicate your common CRUD operations for each model class, and it is easy as pie to unit test.

This last point is the one worth mentioning in my books. The great thing about separation of concerns is it should make things easier to pull apart for unit testing. Because my Repository methods have meaningful names, and are pretty fine grained, my mocking setup looks almost readable. It is immediately obvious from reading my tests that TaskController.List(5) should call ITaskRepository.GetLatestTasks(5). Not only that, but most of the Controller actions have been reduced to “Get this from Repository, return to View” or “Save this thing to the Repository”. They are small, obvious methods, and that makes them easier to test, and easier to maintain.

Windows 7 Shortcut Keys

I found a great list of keyboard shortcuts for Windows 7 today here. The best part of this list were the keys for manipulating windows - Windows + Left Arrow will dock the window to the left hand side of the screen, much like if you drag the window to the side of the screen. The right arrow also works like this.

If you have multiple monitors, using the mouse it doesn’t let you dock to the side connected to the other screen. So you can only dock to the far left and far right with the mouse. Not so with the keyboard. Each time you hit the keyboard combo, it will move it to the next dock position in that direction. That means you can have windows docked all over your extended desktop, like so:


I’ve got two windows on each screen (as you can see, the right hand screen has the task bar, so you should be able to see where the screens split).

This is pretty useful at home. Having huge screens is great, being able to have 4 docked windows without fiddling around with the mouse is fantastic.

Fun With the Symbian Emulator

The other night I stumbled on the PyS60 project, an open source port of the python runtime to Symbian S60 based phones. I own a Nokia N95, and I got kind of excited about this because I would like to mess around with development for it but can’t bring myself to work with C++ in my spare time.

I thought it would be pretty easy to develop for as Python is interpreted, I thought I could just edit text files on the phone and run them to test them out. Turns out you can’t do that (not easily anyway), you need to package them on your computer, then upload the package to the phone, then install it, then run it. That killed that idea.

I looked at the Symbian emulator, and the PyS60 team have a mod for it that installs the python runtime so you can just run script files on the emulated phone. “This is great!” I think, before actually trying it.

For starters, the python runtime doesn’t work in the emulator when the emulator is running on Windows 7 x64 - damn. I have a VPC image with Windows XP on it though, so I fire that up, install everything, then try run it. The emulator crashes after about 15 seconds of loading.

After browsing the Nokia forums for a while, I find out the problem. VPC is actually connecting to the virtual machine over RDP, and so the audio drivers are the RDP Remote Audio drivers.

What do audio drivers have to do with a phone emulator I hear you ask? Good question, but it is one the Nokia forum dwellers have no answer for. Many people have complained that the Symbian Emulator does not work when connecting to the machine hosting it via RDP. There are other issues with particular sound card drivers or applications also causing it to crash. This is a prime example of bad error handling. Why, if the audio part of the emulator cannot work with some drivers, does it crash instead of continuing without audio?

So that brought down my plans for making millions of dollars from fart applications for Symbian based phones.

Strange Visual Studio Lockup After Debugging

I had been having an issue with VS 2008 on Windows 7 x64 today. After debugging an application the whole IDE would lock up, minimise itself, then bring itself back to the foreground. This was pretty disruptive and I was getting quite irritated with it, but I could not find any mention of it through Google.

I did happen to stumble upon a StackOverflow question (here) where a different problem was outlined, however this answer reminded me of an issue Scott Hanselman had with an app he was doing a demo with, so I thought I would give it the fix a shot. Strangely enough, I think it has fixed it, although I am not sure why (it seems unrelated). Anyway, here is the fix, just in case anyone else has a similar problem:

Fix: Disable checking of Publisher’s Certificate Revocation

  1. Go to Internet Options in Internet Explorer or Control Panel

  2. Then go the Security Tab, scroll towards the bottom

  3. Uncheck the ‘Check for Publisher’s Certificate Revocation’ checkbox

  4. Click OK.