MinimalVS.NET: How to make Visual Studio 2010 a little more TextMate-y

If, like me, you use TextMate at home and Visual Studio at work, then you might find this handy. I like the short cuts used in TextMate (and almost all applications on Linux/OsX) to close windows and navigate open tabs.

  • Grab the “Monaco” font here and install that mofo.
  • Then, grab my Ultimate TextMate settings file here (right click, save as). This Theme is a variant of Rob Conery’s Vibrant Theme. I added JS and CSS settings and tweaked the C# settings a bit.
  • Find and remove all bindings to “CTRL+W” and re-assign it to “File.Close”
  • Install the “Windows Productivity Tools” here
  • Next, find the “Window.NextDocumentWellTab” short cut (added by Productivity Tools) and unmap it from all commands. Add “ALT+SHIFT+]” for next tab
  • Then, find the “Window.PreviousDocumentWellTab” short cut (added by Productivity Tools) and unmap it from all commands. Add “ALT+SHIFT+[“ for previous tab
  • Find the “View.SolutionExplorer” shortcut and map it to “ALT+D”
  • Find the “Window.CloseToolWindow” and map it to “ALT+X”

Note: I have cheated a bit on the last two as we don’t have a Command key, but hopefully I made it a bit simpler.

The last thing to do, is to move SolutionExplorer to the left side and remove all toolbars and tool windows. Now you should have a very clean Visual Studio and can use Resharper’s GoTo commands to navigate your solution and only use “ALT+D” and “ALT+X” to show/hide the SolutionExplorer when needed.

A challenge for you: Try to go a whole day without using the mouse. In fact, put that bugger far out of reach behind your computer.


PS: I didn’t include the Keyboard shortcuts in the settings file, as I thought you might like to mix an match those to your preference.

Quick Autotest for NodeUnit and Node.Js on Mac OSX


Very simple way to get Autotesting in Node.js.

What is Autotesting? Simply put, it runs your unit tests automatically whenever you save a relevant file within your project.

  • First, install GROWL and GROWLNotify for Mac (http://growl.info/)
  • Next we want to install the ‘watchr’ gem…
    gem install watchr
    
  • Next create a file called autotest.watchr in the root of your Node.js project with the following ruby script…
    def run_all_tests
      print 'clear'
      puts "Tests run #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}"
      result_text = `nodeunit [TESTFOLDER]`
      result = result_text.include? 'failed'
      if result
    	`growlnotify -m 'Unit Tests Failed' Node Unit`
      else
    	`growlnotify -m 'All Unit Tests Passed' Node Unit`
      end
    end
    
    run_all_tests
    watch("(test|lib)(/.*)+.js") { |m| run_all_tests }
    
    @interrupted = false
    
    # Ctrl-C
    Signal.trap "INT" do
      if @interrupted
        abort("\n")
      else
        puts "Interrupt a second time to quit"
        @interrupted = true
        Kernel.sleep 1.5
    
        run_all_tests
        @interrupted = false
      end
    end
    

    Do not change the ` chars. This actually tells Ruby to output the text directly to the console (for those that didn’t know)

  • Replace [TESTFOLDER] in file above with your test folder
  • Run watchr..
    watchr autotest.watchr
    

Thats it! Now simply edit a .js file in your solution and the tests will run automatically and inform you of failures.

Feel free to add your favourite icons for failures and passes to GROWL. If you do, please send us an updated script ;)

Getting started with Express, Node.js and NodeUnit on Windows using Komodo Edit

I have been using Node.js with TextMate on my Mac for a while now and wanted to replicate my experience on a windows machine. This proved a bit trickier than I expected, but with a little tweaking I eventually ended up with something quite close.

Although Jetbrains have released a brilliant IDE called Webstorm, I was looking for something free and less clunky. When learning a new language I prefer to know exactly what is happening and how its all orchestrated. Moving to webstorm would be an option you should consider only if you are very comfortable of the inner workings of Node.js

After a bit of searching I found Komodo. Version 7 has built-in Node.js support and provides autocompletion.

With a few tweaks and plugins we can make Komodo look like TextMate’s ugly cousin…

  1. Grab Komodo here
  2. Next grab and install the Monaco font from here
  3. Download the Autumn (or any other theme you prefer) from Kolormodo
  4. There are many plugins available including JsLint or the JSDebugger

Next lets install Node

  1. Grab and install the windows version of Node.js here. The installer would have added the path to node.exe in your PATH environment variable. If you open a command window and type node and get ‘bad command’ then try reloading your ENV vars or restarting the computer.
  2. Next install express and nodeunit globally (this enables you to use the executables)
      npm install -g express
      npm install -g nodeunit
      
  3. Lets create a new project:
         express my_node_project -t ejs 
    
         cd my_node_project
         npm install express
         npm install nodeunit
         npm install ejs
         

    First we generate a project scaffold with express and use the EJS view template engine (you can choose from a number of templates). We then install the local dependencies of express, nodeunit, and ejs. This is separate from the global installations (think NuGet).
    This generates a package.json file…

    {
        "name": "application-name"
      , "version": "0.0.1"
      , "private": true
      , "dependencies": {
          "express": "2.5.2"
        , "ejs": ">= 0.0.1"
      }
    }
    

    Just like Gems in Ruby, you can update your dependencies at any time by typing the following in the root folder of your project (this is looking at your packages.json file):

    npm install
    
  4. Create a test folder in your root project folder and add a few tests (call the file app_test.js if you wish)
    exports.testSomething = function(test){
        test.expect(1);
        test.ok(true, "this assertion should pass");
        test.done();
    };
    
    exports.testSomethingElse = function(test){
        test.ok(false, "this assertion should fail");
        test.done();
    };
    

    … and run them

    // Specify a folder
    nodeunit test
    // OR specify a file
    nodeunit test\app_test.js
    
  5. Run Node:
    node app.js
    

    open http://localhost:3000 in any browser and you should have a fully functional MVC application running. Most of the magic happens in your Route declarations

    exports.index = function(req, res){
      res.render('index', { title: 'Express' })
    };
    

    … which is registered in your app.js file

    app.get('/', routes.index);
    

You’d probably want to connect this baby up to your favourite NoSQL db. A quick start would be to use Mongoose which is a MongoDb ORM mapper and uses the ActiveRecord pattern.

If you really want to start doing some cool stuff I’d recommend learning KnockoutJs. It takes about 40minutes to go through the tutorials. Pay most attention to the SinglePageJS app section.

In Node.Js we can now add json endpoints and use KnockoutJS to create state-full web applications like Gmail.

An example json endpoint in express would be…

app.get('/people.json', function(request, response) {
  // We want to set the content-type header so that the browser understands
  //  the content of the response.
  response.contentType('application/json');

  // Normally, the would probably come from a database, but we can cheat:
  var people = [
    { name: 'Dave', location: 'Atlanta' },
    { name: 'Santa Claus', location: 'North Pole' },
    { name: 'Man in the Moon', location: 'The Moon' }
  ];

  // Since the request is for a JSON representation of the people, we
  //  should JSON serialize them. The built-in JSON.stringify() function
  //  does that.
  var peopleJSON = JSON.stringify(people);

  // Now, we can use the response object's send method to push that string
  //  of people JSON back to the browser in response to this request:
  response.send(peopleJSON);
});

Unfortunately the above is more like a “pseudo state-full” app as we are still sending Http requests along the wire. BUT not to worry… this is where Socket.io comes in…
With Socket.io you can talk directly to the Node.js server using WebSockets!

// SERVER
var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

// CLIENT
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Now GO! I have given you ENOUGH cool-aid to get going with Node.js on windows!

My favourite TED talks

I have always been a huge fan of TED talks and have been watching since it started becoming available on youtube a few years back. Some late comers have asked me recently if I could give them a shortlist of some of the best talks I have seen. Below a short compilation of the jaw-droppers, the inspiring and the amazing talks I have seen.

First. the ones that started it all for me…

Jill Bolte Taylor – Stroke of insight
JJ Abrams – Mystery box

Science

Vilayanur Ramachandran – Your mind
V. Ramachandran – The neurons that shaped civilization
Beau Lotto – Optical illusions show how we see
Richard Dawkins – Our queer universe
David Deutsch – A new way to explain explanation
Dan Denett – Cute, sexy, sweet and funny
Dan Denett – Our consciousness
Dan Denett – Dangerous memes
Garrett Lisi – Theory of everything
Brian Greene – String Theory
Jeff Hawkins – How brain science will change computing
Henry Markram – Supercomputing the brains secrets
Craig Venter – Unveils synthetic life
Lee Cronin – Making matter come alive
Daniel Wolpert – The real reason for brains

Jaw-dropping

Jack Horner – Building a dinosaur from a chicken
Theo Jansen – Creating new creatures out of bottles and pipes
Robot flies like a bird
Todd Kuiken – A prosthetic arm that feels
Johnny Lee – Wii remote hacks
Jeff Han – Breakthrough touchscreen
David Bolinsky – Animating the cell
Marco Tempest – Magic of truth and lies on ipods
Terry Moore – How to tie your shoes
Daniel Tammet – Different ways of knowing

Other

Michael Shermer – Believing strange things
Michael Shermer – The pattern behind self deception
Jason Fried – Why work doesn’t happen at work
Aubrey de Grey – We can avoid aging
David Mcandless – The beauty of data visualizations

These are just a short list of items I thought were worth sharing. If I had more time to go through the videos again, I am sure I would find double the items. These however stood out from memory and I hope you enjoy!

Smart Search with Norvig Spelling Correction and Levenshtein Distance Algorithm in C#

Before I write anything, I would like to thank the sources for their code snippets from which I compiled my version. (Norvig Spelling Correction, Lorenzo Stokes, Website: http://www.codegrunt.co.uk/2010/11/02/C-Sharp-Norvig-Spelling-Corrector.html, Accessed: September 2011) and (Levenshtein Distance Algorithm, Lasse Johansson, Website: http://www.merriampark.com/ldcsharp.htm, Accessed: September 2011)

This search will first correct any spelling mistakes in your search query, then it will try to get a list of exact matches, partial matches and finally a distance query. The distance query will use the Levenshtein Distance Algorithm to find words that you may have meant.

Firstly, you need the big.txt file http://norvig.com/big.txt
The Dictionary that it creates from this file takes about 1.5s to load, so I would inject this at the start of your application via a container. In this case I am using Autofac

var bigDictionary = Regex.Matches(Resources.big.ToLower(), "[a-z]+")
    .Cast<Match>()
    .GroupBy(m => m.Value, m => m.Value)
    .ToDictionary(gr => gr.Key, gr => gr.Count());

builder.RegisterInstance(bigDictionary)
    .Named<IDictionary<string, int>>("BigTxt")
    .AsSelf()
    .SingleInstance();

builder.Register(c => new SearchService(c.ResolveNamed<IDictionary<string, int>>("BigTxt"))).As(typeof(ISearchService))
                .InstancePerHttpRequest();

Second we need the Search Service
UPDATE: I have refactored this into a Self Contained Service

using StrEnum = System.Collections.Generic.IEnumerable<string>;

public class SearchService
{
    private readonly IDictionary<string, int> bigDictionary;
    private const string ALPHABET = "abcdefghijklmnopqrstuvwxyz";

    public SearchService(IDictionary<string, int> bigDictionary)
    {
        this.bigDictionary = bigDictionary;
    }

    public StrEnum SearchThroughList(string searchTerm, StrEnum itemList)
    {
        var matches = new List<string>();
        string[] words = searchTerm.Split(' ');
        string term = string.Join(" ", words.Select(GetPossibleMisspelledWord));
        matches.AddRange(GetClosestMatch(term, itemList));

        if (matches.Count() == 0)
        {
            matches.AddRange(GetDistanceMatch(itemList, term));
        }
        return matches.Distinct();
    }

    private static StrEnum GetClosestMatch(string word, StrEnum titles)
    {
        var matches = new List<string>();

        string exactMatch = titles.SingleOrDefault(x => x.ToLowerInvariant() == word.ToLowerInvariant());
        if (exactMatch != null)
           matches.Add(exactMatch);

        StrEnum partialMatches =
                titles.Where(x => x.ToLowerInvariant().Contains(word.ToLowerInvariant()));

        matches.AddRange(partialMatches);

        return matches;
    }

    private static StrEnum GetDistanceMatch(StrEnum titles, string word)
    {
        var distanceDictionary = new Dictionary<string, int>();
        titles.ToList().ForEach(x => distanceDictionary.Add(x, Distance(x, word)));
        return distanceDictionary
           .Where(y => y.Value == distanceDictionary.Values.Min()).Select(x => x.Key).Take(2);
    }

    private string GetPossibleMisspelledWord(string word)
    {
        var nWords = bigDictionary;
        Func<StrEnum, StrEnum> nullIfEmpty = c => c.Any() ? c : null;

        StrEnum candidates = nullIfEmpty(new[] { word }.Where(nWords.ContainsKey))
            ?? nullIfEmpty(Edits(word).Where(nWords.ContainsKey))
            ?? nullIfEmpty((Edits(word).SelectMany(Edits, (e1, e2) => new { e1, e2 })
                .Where(match => nWords.ContainsKey(match.e2))
                .Select(match => match.e2))
                .Distinct());

        return candidates == null ? word : candidates
            .OrderByDescending(cand => (nWords.ContainsKey(cand) ? nWords[cand] : 1)).First();
    }

    private static int Distance(string s, string t)
    {
        var n = s.Length;
        int m = t.Length;
        var d = new int[n + 1, m + 1];
        if (n == 0) return m;
        if (m == 0) return n;
        for (int i = 0; i <= n; d[i, 0] = i++) {}
        for (int j = 0; j <= m; d[0, j] = j++) {}
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                int cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);
                d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                                  d[i - 1, j - 1] + cost);
            }
        }
        return d[n, m];
    }

    private static StrEnum Edits(string w)
    {
        // Deletion
        return (from i in Enumerable.Range(0, w.Length)
                select w.Substring(0, i) + w.Substring(i + 1))
        // Transposition
        .Union(from i in Enumerable.Range(0, w.Length - 1)
               select w.Substring(0, i) + w.Substring(i + 1, 1) +
                      w.Substring(i, 1) + w.Substring(i + 2))
        // Alteration
        .Union(from i in Enumerable.Range(0, w.Length)
               from c in ALPHABET
               select w.Substring(0, i) + c + w.Substring(i + 1))
        // Insertion
        .Union(from i in Enumerable.Range(0, w.Length + 1)
               from c in ALPHABET
               select w.Substring(0, i) + c + w.Substring(i));
    }
}

This would produce the following results:

search for afterlfe

will match:

Afterlife
The Afterlife
An Afterlife with Jane

a search for Tip Gaer

will match:

Top Gear
Top Gear Series 2
Top Gear Polar Special

a search for Tip Gaer Poler spfoul

will match:

Top Gear Polar Special

The Super Top 10 Quality Code Guidelines

A few months ago we asked a couple of developers to answer a simple question. “What constitutes ‘Good Code’?”. The answer had to be in the form of a checklist with 10 guidelines.

So here it is! The number after the item is the amount of times we encountered it (or similar).

1. High test coverage at all levels is essential 10
2. Follow the Solid Principles 10
3. Reading the code should substitute reading documentation – It should make sense 8
4. Always do the simplest thing possible, have small methods and classes – remember YAGNI 8
5. Organise and format your code in a logical way and stick to it 6
6. Use names that reflect the business domain and have real meaning 6
7. Implement GoF patterns where applicable but nowhere else 5
8. Code should be resillient to errors but error handling should not invade the design 3
9. Reuse code where possible 3
10. Don’t reimplement the wheel 3

A little about the participants…

Al Priest. Al describes himself as, “an architect working at BBC Worldwide. I’ve been developing ever since the BBC Micro was popular and since 2002 I’ve been developing in C#”. Catch him at http://www.socialanimal.com

Maarten Balliaaw is currently employed as .NET Technical Consultant at RealDolmen. He describes his interests as mainly web applications developed in ASP.NET (C#) or PHP and the Windows Azure cloud platform. Catch him at http://blog.maartenballiauw.be

Pete Camfield runs a weekly meeting at BBC Worldwide primarily aimed at engaging the development community in a number of ways such as organising dojo’s, presentations, study groups and the like. Catch him at http://leftshift.wordpress.com

Marcel du Preez who I am not going to introduce in the third person as it is me typing this. I currently work for BBC Worldwide and have worked on projects such as BBC Listener, Top Gear, RadioTimes and also created http://www.boxjs.com. Catch me… well… here or @marceldupreez

Julian Everett is software architect at BBC.com and has more than 13 years experience designing and building distributed enterprise applications on Microsoft and Java technology stacks. Catch him at http://julianeverett.wordpress.com

Andreas Håkansson (aka TheCodeJunkie), creator of Nancy, Open-source ninjah, software craftsman, believer of agile practices, blogger, twitter addict, swede… Catch him at http://thecodejunkie.com

Josh Chisholm has worked on high caliber projects around BBC and usually leads Dojo sessions on all kinds of technologies. Catch him at @joshski

Derek Ekins currently works on BBC.com and his passion is open source development in Ruby on Linux. He is also co-owner of this blog and you can catch his articles by browsing the archives.

Andrew Revell describes himself as a “Wanderer, developer, New Zealander, moderately ambitious dreamer, occasional accidental philosphiser”, he has worked on projects including Top Gear, Love Earth, BBC Listener and many more. Catch him at http://llevera.wordpress.com

Duane Strikwerda has years of experience in mainly high profile websites built, most recently using ASP.NET’s MVC framework.

We would love to hear your feedback and if there is anything you think we missed, please leave your additions in the comments below.

Creating ruby gui applications – an introduction to ruby shoes

As part of my effort to detect objects using opencv I have found myself performing a mind numbing task and as every lazy programmer knows this is the time to build a tool.

After a bit of investigation into the various gui libraries for ruby I have found one that seems pretty good called Ruby Shoes. There seem to be a few variants of this particular library. Strangely the classic Red Ruby Shoes version does not act like a regular ruby library. It seems to be a runtime that uses ruby. The Green Shoes variant however is a straightforward ruby library. You can gem install green_shoes and get up and running straight away.

A gui application in Ruby Shoes is called a shoe app and is started by calling:

Shoes.app do
  # application code goes here
  title "Hello World!"
end

As I want to create an image selection tool I need to be able to track mouse clicks, movements and releases and then draw a rectangle as this is going on.

After playing around for a while I came up with this:

require 'green_shoes'
Shoes.app  do
  title "Selection tool"
  image("your_image.jpg").click do |button, click_left, click_top|
    mouse_down = true
    release do
      mouse_down = false
    end

    nofill
    @selection = rect :left => mouse[1], :top => mouse[2], :width => 1, :height => 1

    motion do |move_left, move_top|
      if mouse_down
        width =  move_left - click_left
        height =  move_top - click_top

        width = 1 if width < 1
        height = 1 if height < 1

        @selection.style(:width => width, :height => height)
      end
    end
  end
end

There are probably more efficient ways to handle the release but this was the best I could come up with in half an hour.

I found the manual quite helpful to figure all this out.

Your swanky new smart phone may be causing your elbow pain

Have a look at the following symptoms

  • Pain or tenderness in the outer part of your elbow (lateral epicondyle)
  • Gripping something with your hand causes slight discomfort in your outer elbow
  • You have difficulty keeping your arm straight
  • Your outer elbow muscle twitches when you keep your arm still
  • Weak grip strength

Sounds familiar? It may be that you are suffering from Tennis Elbow. Don’t play tennis, I hear you say? That is because Tennis Elbow refers to a condition called Lateral epicondylitis, which essentially means, overuse of the lateral side of the elbow (Wikipedia, 2011). With all these great smart phones around, walking home has suddenly turned into a scene from “Night of the Living Dead”. “Zombies” standing around looking down at their phones with the usual groan. Doctors have reported an increase in elbow pain complaints in the last few years and have even coined a new term “Cellphone Elbow” (Ergow, 2009) to join a large list of new age diseases.

Not to worry though. You can prevent “CellPhone Elbow” with a few simple tips.

  • Try to stay fit and exercise your arms regularly. (even swinging your arms more when you walk would help)
  • Limit your phone usage or at least switch arms from time to time
  • Paul Brown (PaulBrown.net, 2011) also provides a simple exercise to do regularly:

    Take one hand in the other and gently flex the held hand’s wrist. That is, bend the wrist in the direction of the palm of the hand.
    Straighten that same arm’s elbow.
    Slowly rotate the forearm so the elbow crease is pointing away from your body.
    Hold for 30 – 60 seconds.


Sources:
ErgoWeb, Cellphone Elbow, Online: http://www.ergoweb.com/news/detail.cfm?id=2348, Accessed: 27/07/2011
Paul Brown, iPhone Elbow, Online: http://www.paulbrown.net/iphone-elbow/, Accessed 27/07/2011
Wikipedia, Tennis Elbow, Online: http://en.wikipedia.org/wiki/Tennis_elbow, Accessed 27/07/2011