Archive for the 'Tutorials' Category

Mercurial: Undoing an uncommitted merge

Monday, July 12th, 2010

I’ve moved from Subversion to Mercurial at work to get past some merge problems SVN was giving me. After a few teething problems everything is working out fantastic. I’m also mainly using the command line rather than a GUI front end which is surprisingly efficient.

I just did a merge to a stable branch then realised I had forgotten a change that really should be done on the branch I was merging from (just a version number update). Unfortunately you can’t seem to merge revisions over the top of an existing uncommitted merge so I needed to roll back the merge and start again. In Subversion I would just revert the changes, but Mercurial is a bit smarter about its merges.

To see the parents of the working copy, run hg parents. After doing the merge there should be two parents. There are two steps in rolling back the merge. Note the period (.) at the end of both of these commands:

hg revert --all -r .
hg update -C -r .

Calling hg parents should now just show the original parent.

Accessing anonymous object properties using reflection

Monday, April 19th, 2010

Anonymous objects are a way to create strongly typed objects without having to declare a class or struct in C# 3.5 and above. Declaring an anonymous object is easy:

var breakfast = new
{
    Cereal = "High fibre",
    Coffee = "Latte",
    Bacon = "Crispy"
};

In the scope of the object’s declaration, accessing the properties of breakfast is as simple as breakfast.Cereal. However accessing the properties outside of that scope is not as simple. Say we have an object ben with a method Eat(object meal). Within ben.Eat() we can’t do something directly with meal.Coffee because Coffee isn’t known in ben.Eat()‘s scope.

Getting a property value using reflection is pretty basic but takes a couple of steps. There are much more advanced uses of reflection that allow access to hidden properties, fields and methods, but picking public properties is probably the easiest case. The following method returns the value of a public property of an object. This could be used on an anonymous object, or on any other class of object.

using System.Reflection;
...
object GetPropertyValue(object o, string propertyName)
{
    var prop = o.GetType().GetProperty(propertyName);
    if (prop == null) return null;
    return prop.GetValue(o, null);
}
...
var cereal = GetPropertyValue(breakfast, "Cereal");
Assert.That(cereal, Is.EqualTo("High fibre"));

prop is a PropertyInfo object that lets the value of a property be retrieved via reflection. The same method can be used to get a dictionary of [property name, value] from an anonymous object:

prop is a PropertyInfo object that lets the value of a property be retrieved via reflection. The same method can be used to get a dictionary of [property name, value] from an anonymous object:

IDictionary<string, object> ObjectToDictionary(object o)
{
    var dict = o.GetType().GetProperties().ToDictionary(
        prop => prop.Name, prop => prop.GetValue(o, null)
            );
    return dict;
}

This sets up a dictionary where the key is the name of the property, and the value is (ahem) the value of the property:

var breakfastDictionary = ObjectToDictionary(breakfast);
Assert.That(breakfastDictionary.Count, Is.EqualTo(3));
Assert.That(breakfastDictionary["Coffee"], Is.EqualTo("Latte"));

Using anonymous objects and reflection is a bit slower to execute than using strongly-typed objects, but once the methods are in place to access the properties, the savings in developer time can be great. Leaving more time for breakfast. Speaking of which, I’m late for work.

Extension Methods in C#

Saturday, March 20th, 2010

This is pretty basic and has been around for a while but I always forget about it until it’s too late. From C# 3.0 onwards we’ve been able to declare methods that extend a class. There’s no magic, the method doesn’t actually get added to the class and can’t access the internals of the class, it’s just a shorthand way of making a static call.

The extension method is declared in a static class:

public static class PimpMyStringExtension
{
    public static string Pimp(this string s)
    {
        return s + " is pimped out";
    }
}

Adding the this keyword to Pimp‘s string s argument is what indicates that Pimp is an extension method to the string class. The Pimp method can now be called against any string:

Assert.That("test".Pimp(), Is.EqualTo("test is pimped out"));

As long as the PimpMyStringExtension is accessible to the consuming code, the String gets the Pimp() method added. "test".Pimp() actually just calls the static method under the covers, which is actually still an option:

Assert.That(PimpMyStringExtension.Pimp("test"), Is.EqualTo("test is pimped out"));

Extra arguments can be added to the extension method as well:

 public static string Pimp(this string s, int i)
{
    return s + " has been pimped with " + i;
}
...
Assert.That("test".Pimp(7), Is.EqualTo("test has been pimped with 7"));

Using Jeditable for inline editing

Thursday, February 4th, 2010

Using the Jeditable plugin for jQuery enables inline editing of a block of text. This makes it easy to take a static view and simply drop in editability. Say we start with the following HTML:

<label>Name:</label> <span class="employeeName">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating">Highly awesome</span>

We want to be able to edit the employeeName and employeeRating spans. We need two actions (asssuming an MVC framework) to update the name and rating. The URLs might be something like /employee/set_name/{id} and /employee/set_rating/{id}. Each action should accept HTTP POST, take the new value in $_REQUEST['new_value'] or similar, and return a HTTP status of 200 on success and 500 on failure, with the error message in the response. For example, using Slab (my PHP5 MVC framework, in development) the set_name action might be like this:

class EmployeeController extends AppController {
	function set_name($id) {
		$this->Employee->save(array(
			'id' => $id',
			'name' => $this->data['new_value']);
		));
		return $this->ajaxSuccess($this->data['new_value']);
	}
}

Slab catches uncaught exceptions and returns an AJAX failure with the exception message as the body of the response.

To hook up the fields to the actions, modify the HTML to include the URLs to the actions. While this means the markup has behavioural elements and isn’t purely presentational (and has a non-standard attribute), it makes the script a bit simpler and easy to move into a static .js file, and is a quick way to get a page working.

<label>Name:</label> <span class="employeeName" editUrl="/employee/set_name/7">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating" editUrl="/employee/set_rating/7">Highly awesome</span>

Now for the script itself:

$(function(){
	$('.employeeName, .employeeRating').editable(
		function(value, settings) {
			return $.ajax({
				url: $(this).attr('editUrl'),
				data: { 'new_value': value },
				async: false,
				type: 'post'
			}).responseText;
		}, {
			indicator: 'Saving...',
			tooltip: 'Click to edit',
			onblur: 'submit'
		}
	);
});

The first argument is a function that returns the new value of the field. This is important when doing things like replacing line breaks with <br/> which we’re not worrying about, but it also gives us the ability to write our own AJAX code. By default Jeditable makes assumptions about how the update is done. The async option in the call to $.ajax() blocks until the call returns, and lets the function return the response of the AJAX call. The second argument are options to set some text to show while calling the update function, the tooltip to display when hovering over the span, and to submit changes on blurring the input which makes it seem a bit more usable when there are multiple fields.

Injecting Rhino Mocks with Ninject

Wednesday, January 20th, 2010

So today I hit a hat trick. I needed to test a class that had an injected dependency, and needed some functionality that I didn’t want to add to a fake and would rather isolate to the test. I needed to use a mocking framework. This is my first time using mocks (and only my second week of dependency injection) so this may not use best practices, but this _is_ a blog after all.

I’m using Ninject 2 for dependency injection, NUnit 2.5.3 for unit testing, and Rhino Mocks 3.6 for mocking. NUnit has a mocking framework built in but it doesn’t use strong typing, which I think was causing problems with Ninject.

What I’m really showing here is an example of how to inject a dynamically declared mock instead of a concrete fake. The fact that it is in the context of a test is actually irrelevant, but using mocks and fakes are obviously important in testing to reduce the complexity of the test.

Initially I’m using the default ConcreteFoo implementation of IFoo in the test. This test fails as intended:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Ninject;
using NUnit.Framework;
using Rhino.Mocks;

namespace Trifecta
{
    public interface IFoo
    {
        string Name { get; }
    }
    public class ConcreteFoo : IFoo
    {
        public string Name { get { return "You don't want to see me"; } }
    }

    public class FooConsumer
    {
        [Inject] public IFoo Foo { get; set; }

        public FooConsumer() {}
    }

    [TestFixture]
    public class FooConsumerTestFixture
    {
        IKernel Kernel { get; set; }

        [SetUp]
        public void SetUp()
        {
            // This is the standard setup that will need to be overridden in the
            // test.
            Kernel = new StandardKernel();
            Kernel.Bind<IFoo>().To<ConcreteFoo>();
        }

        [Test]
        public void FooConsumerGetsTheFoo()
        {
            // This test depends on a specific behaviour in IFoo, but ConcreteFoo
            // is going disappoint right now.
            var fooConsumer = Kernel.Get<FooConsumer>();

            Assert.That(fooConsumer.Foo.Name, Is.EqualTo("The foo for you"));
        }
    }
}

Settting up and binding the mock is all done in the test method. The mock IFoo instance is created, and the functionality that the test requires is added. IFoo is then bound to a delegate which returns the mock instance. The binding has a condition that causes the mock binding to be used rather than the ConcreteFoo binding, this seems to be easier then setting up the kernel from scratch for the test (possibly I’m just missing how to rebind).

[Test]
public void FooConsumerGetsTheFoo()
{
		// Create a mock implementation of IFoo that has the behaviour the test requires
		var mocks = new MockRepository();
		var mockFoo = mocks.StrictMock<IFoo>();
		Expect.Call(mockFoo.Name).Return("The foo for you");
		mocks.ReplayAll();

		// Bind the mock when injecting IFoo into FooConsumer. This overrides the binding
		// created in SetUp()
		Kernel.Bind<IFoo>().ToMethod(context => mockFoo).WhenInjectedInto<FooConsumer>();

		// fooConsumer's Foo should now be the mock IFoo created above
		var fooConsumer = Kernel.Get<FooConsumer>();

		Assert.That(fooConsumer.Foo.Name, Is.EqualTo("The foo for you"));
}

The test should now pass.

Form validation with jQuery

Wednesday, December 9th, 2009

Every time I’ve implemented client-side form validation I’ve started from scratch and done it a little differently. Usually it devolves into a messy set of if statements and duplicated code. Here’s my latest method, which separates the validation rules from the processing. It uses jQuery because if you’re not using a Javascript library you should be. This will only handle relatively simple validation cases.

So start with a form:

	<form id="mailingListSubscription" action="subscribe.php">
		Name: <input type="text" name="name" id="name" /><br />
		Email: <input type="text" name="email" id="email" /><br />
		Phone: <input type="text" name="phone" id="phone" /><br />
		<button type="submit">Subscribe</button>
	</form>

All fields are required, and I’m going to use some magical regex (found on the interthingy somewhere) to validate the email address. This script sets up the rules:

	var rules = [
		{ id: 'name', test: function(val) { return val != ''; }, msg: 'Please enter your name' },
		{ id: 'email', test: function(val) { return val.search(/^[^@]+@[^@]+.[a-z]{2,}$/i) != -1; }, msg: 'Please enter a valid email address' },
		{ id: 'phone', test: function(val) { return val != ''; }, msg: 'Please enter your phone number' }
	];

Each rule has the id of the form element being tested, a message that gets displayed on failing the rule, and a function that validates the value of the form element. I also could add multiple rules for the one input.

This script sets up the submit handler for the form, which does the validation using the array of rules set up above:

	$(function(){
		$('form#mailingListSubscription').submit(function(){
			for (var i = 0; i < rules.length; i ++) {
				var rule = rules[i];
				var target = $('#'+rule.id);
				if (!rule.test(target.val())) {
					alert(rule.msg);
					target.focus();
					return false;
				}
			}
			return true;
		});
	});

On a test failing, the rule’s msg value is shown and the target of the test gets focus. This could be changed to something more user friendly like showing the message next to the target field.

Deleting items in a table with AJAX via JQuery

Sunday, November 29th, 2009

This is a very straight-forward tutorial on implementing a jQuery-driven ‘delete via AJAX’ feature. Say we have a plain HTML table containing a list of items and a ‘Remove’ link. I’m not going to describe the back-end, but I’m assuming something groovy like CakePHP or ASP.NET MVC. I’ve also assumed that the delete request always succeeds and never returns an error, which may not be the case. The script itself is a more than required but is my preferred method as I can extend the elements in the UI fairly easily.

	<table>
		<tr><td>Chickpeas</td>      <td><a href="/items/delete/1" class="delete">Delete</a></td></tr>
		<tr><td>Garlic</td>         <td><a href="/items/delete/2" class="delete">Delete</a></td></tr>
		<tr><td>Olive oil</td>      <td><a href="/items/delete/3" class="delete">Delete</a></td></tr>
		<tr><td>Tahini</td>         <td><a href="/items/delete/4" class="delete">Delete</a></td></tr>
		<tr><td>Cumin</td>          <td><a href="/items/delete/5" class="delete">Delete</a></td></tr>
		<tr><td>Lemon juice</td>    <td><a href="/items/delete/6" class="delete">Delete</a></td></tr>
	</table>

The delete hrefs (/items/delete/XX) link to an action or page that deletes the specified item and returns a HTTP status of 200 (OK). If the action just redirected to the current page then this table should work as it stands, which is probably a good way to check that everthing works as expected without involving AJAX features. If you just want to set up the client side without implementing any server-side code, create the following in delete_test.php and use it for the delete links:

<?php header('HTTP/1.1 200 OK'); ?>

Make sure that jQuery 1.3+ has been included in the page and add the following:

<script type="text/javascript">
$(function(){
	var ui = {
		init: function(){
			$('a.delete').live('click', ui.delete_click);
		},

		delete_click: function(){
			link = this;
			$.get(link.href, function(data, status) {
				$(link).parents('tr').remove();
			});
			return false;
		}
	};

	ui.init();
});
</script>

Very basic stuff but it works. It could be jazzed up by fading out the items first or updating a status label. If there is a significant delay between calling the delete action and getting a response the user may not think anything has happened, so perhaps the delete link should change or be disabled.

Subversion on a USB stick

Sunday, September 27th, 2009

I use Subversion for version control at work, so I wanted to use it for a couple of websites and projects that I play with at home. I’ve been thinking about buying a cheap server or NAS that I could set up but couldn’t justify the cost and electricity just for want of version control.

As it happens, my Subversion client of choice TortoiseSVN can create and access local Subversion repositories. Probably all SVN clients can do this, and this is just a feature of the system, but when I’m used to seeing the version control purely as a client/server configuration this was a bit of a surprise. TortoiseSVN integrates nicely with Windows Explorer which makes it extremely easy to work with. If I had to load a seperate SVN client just to commit changes I would most likely put it off and/or forget about it. TortoiseSVN makes working with Subversion so easy that it is the main reason I keep giving up on Linux for my development machines.

One of the attractions of version control is that the project is portable – I can check out (make a local copy of) a website on my home PC, make changes, commit the changes to the server, then update the site on my laptop, without having to worry about copying files (and having different versions of files in the one place). That requires the Subversion server to be accessible on both machines, and if I don’t happen to have internet access for any reason that may not be possible.

Setting up a repository on a USB stick gives me most of the benefits of the typical client/server setup. The biggest downside is a lack of backups, which is something that needs to be maintained on a server anyway, and should be worked around by making backups of the repositories on the USB stick. In any case even if the repository fails I still should have multiple working copies on various machines. Not ideal but at least the files won’t be lost.

So how to do this? First install TortoiseSVN. I’m going to assume familiarity with SVN, and with TortoiseSVN in particular.

On the USB stick, make a folder to store the repositories. I called my folder svnrepos. Inside that folder, make another folder for the first repository. This is the name of the repository so call it something sexy, like bentest. Right click the folder, go to TortoiseSVN, and Create repository here. Wheels will turn, and a message should appear saying the repository was created.

Now go to your development folder, or wherever you want to check out a working copy of the project. Right-click the development folder (eg C:\Development\www) and select SVN Checkout.

The URL of repository is the path to the local repository that you created, as a file URL. Mine is file:///E:/svnrepos/bentest (note there are three slashes after the file: part). The checkout directory is where the working copy will be created. It should be automatically filled in when editing the repository URL, but can be changed. Mine is C:\Development\www\bentest. Click OK and you should have revision 0 of the repository ready to create trunk, branch and tag folders and add content.

Version control. Distributed backups of your precious work. No reliance on internet access and access to private Subversion server. Beautiful.

I haven’t experimented with this so far but I suspect there may be issues if the USB drive comes up on another driver letter. The repository url will probably need to be changed in the working copy. That should be possible via the Relocate command in TortoiseSVN’s context menu.

UPDATE: Relocate is indeed the command to use. TortoiseSVN throws up a warning about corrupting your working copy, but as long as the path entered is the new path to the same place in the repository (eg from file:///H:/svnrepos/bentest/trunk to file:///F:/svnrepos/bentest/trunk) this is the best/only method.

Editing past log comments in Subversion

Tuesday, March 18th, 2008

Subversion is my source version control software of choice, but it’s not immediately obvious how to edit the log comment of a past commit (such as after adding a particularly scathing remark that may not be a wise career move). A caveat is that you need to have administrator access to the Subversion repository.

In the repository directory (wherever you created the repository) is a hooks folder (on my system this is H:\IT\svnrepos\pas\hooks). This folder contains scripts that are called by Subversion when various events occur (hooks). The files that are created in a repository’s hooks folder by default are templates of hooks designed for Linux etc. On a Windows server they need to be created as batch files (*.bat) to be executed.

What you need to do is create a hook that will run prior to changing a revision property (such as a log comment) and let Subversion know that changing the comment is permitted. By default changing the log comment is disabled (obviously, or you wouldn’t be reading this). Make a new file in the hooks folder called pre-revprop-change.bat and write the following into it:

if "%4" == "svn:log" exit 0

echo Property '%4' cannot be changed >&2
exit 1

The %4 argument contains which operation is being performed. If the operation is svn:log we indicate success, which is a return code of 0. Otherwise it prints an error and exits with a non-zero, which indicates an error (and that the operation shouldn’t be allowed). Once that is saved, you should be able to use your to Subversion client to edit the comment. Be careful with what you do, as revision properties aren’t versioned, and you won’t be able to undo your changes. You should also probably rename pre-revprop-change.bat to pre-revprop-change.bat.bak once finished.

Displaying Contacts in Microsoft Outlook Address Book

Tuesday, December 4th, 2007

If you can’t get your contact list coming up in Outlook, here’s a how-to that works well. Two things to look out for are Outlook not closing properly (it may run as a notification button, open Task Manager and kill the Outlook process off just to make sure) which seems to stop the fix from working, and the fact that right-clicking on the Outlook icon to get to mail settings doesn’t work if the Outlook icon is a shortcut (ie 99% of the time). To get into mail settings, open Control Panel then Mail once Outlook is shut down.