I’m trying to push a very large (for me) repository to BitBucket. The .hg folder is 2.5 G which is a pretty big chunk. This is my first time using BitBucket, in fact until now my experience of hosting Mercurial repos has been limited to either file shares or hg serve, so initially I tried pushing over HTTP.
Four hours later and no real data had been sent, so I did some looking and decided to try using SSH. It seems to be working well at the moment (still sending as I type) but I’m not going to attempt writing my own tutorial so here are some links I found useful:
Quick tip / reminder to myself. I’m adding some tests to an ancient (almost two years old :-) ) Winforms control that uses a ListView. All I’m doing is making sure that a particular context menu item is enabled or disabled depending on the state of the object in the tag of the selected item in the ListView. The details aren’t important. Trust me.
The issue is that since the control being tested is never actually displayed, the ListView control doesn’t update its SelectedItems property. I found a Stack Overflow question and answer regarding this. The (marked as) ‘correct’ answer involves flashing up a hidden form containing the control. Potentially messy. If I was testing a form I could just flash that up but still, not an ideal solution. The second answer to the question does the trick. Fourth line is the money shot:
// Select the first list view item:
controlBeingTested.myListView.Items[0].Selected = true;
// then trick controlBeingTested.myListView.SelectedItems into being updated:
controlBeingTested.myListView.AccessibilityObject.ToString();
The downside is that the Accessibility reference needs to be added to the unit test assembly.
I just read a [post by David Tchepak][http://www.davesquared.net/2010/12/revisting-replacing-ruby-instance.html] where he describes a way of replacing a method on an instance of a class on the fly, allowing the replacement to close over locals. This would be useful for unit testing at the least. The technique that Dave uses is cool – this is a simplified version:
name = "Anonymous Dave"
greeter.extend Module.new do
self.send(:define_method, :say_hello) do
puts "G'day #{name}"
end
end
This is replacing the greeter.say_hello method with the closure on the fourth line. Since I’m spoiled by C#’s lambda syntax, I wanted to get this onto one line:
Nice, but there is a bit of repetition. .extend is a method on the Object class, which extends the instance with the new module. Unfortunately Object doesn’t have a method to just replace a single method. The following opens the Object and moves much of the boilerplate code into a new method to do that:
class Object
def redefine(name, &block)
self.extend Module.new {
self.send(:define_method, name, block)
}
end
end
redefine probably isn’t the best name, since there is no need for the named method to exist before redefining it. This is the new way to replace the say_hello method:
The Skype plugin for Internet Explorer finds text it thinks is phone numbers and adds controls around it to let the user call the number via Skype. Nasty work. Especially since it also picks up ABNs, company numbers, etc, and tends to break the page layout as well.
To fix it, this meta declaration needs to be added to the head element:
So I’ve been getting my console-fu on since moving to [Mercurial][http://blog.belfryimages.com.au/category/mercurial/] at work, and finding ways to get more efficient. One thing that bugs me is having to spend time grabbing the mouse to search Google via a browser. I’ve also wanted to spend some time with Ruby, so to acheive both goals I wrote a little script that uses the Google AJAX Search API, which returns search results as a JSON object. The full code is available as a [gist on my GitHub][http://gist.github.com/503145]. There are a couple of interesting (for me anyway) parts of the code that I’ll go through now.
The request/response is done via a HTTP GET responding with a JSON-serialised object graph. A query string is built up and parsed into a URI object (using the same reference), then the request is made and parsed from the text JSON representation into an associative array (the result of JSON.parse):
require 'net/http'
require 'json'
...
queryURI = "http://ajax.google....."
queryURI = URI.parse(queryURI)
data = Net::HTTP.get_response(queryURI)
data = data.body
data = JSON.parse(data)
I’ve used both pre- and post-fix conditional structures:
if command.to_i.to_s == command && (1..results.length).include?(command.to_i)
url = results[command.to_i - 1]['url']
puts "Opening #{url}"
`start #{url}`
command = ''
end
page += 1 if command == '+'
page -= 1 if command == '-'
Rather than using a not operator like ! the unless operator can be more fluent and easier to understand:
A problem with C#’s foreach loop syntax is that there is no easy way to include an index short of rolling your own and incrementing in the loop. Usually it is easier to resort to the less pretty for (var i = 0; i < ..; i++) syntax. Ruby includes a variant of Array::each that takes care of the index:
results.each_with_index do |result, index|
# ...
end
And of course writing two line breaks is very fun:
2.times { puts '' }
All up it was very educational spending some time building something a bit significant in Ruby, and the result should hopefully be pretty fun to use.
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.
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:
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.
I’ve written a very simple plugin for jQuery that takes a template and a model and returns a view of the model. To make sure it worked I wrote some tests and examples, and since I did that I figured I would write a little mini-site. The plugin itself is pretty straightforward:
(function($){
$.fn.cliche = function(model){
var template = $(this).html();
template = template.replace(/%7C/g, '|'); // pipes in a href like <a href="|... get converted to %7C, convert it back
template = template.replace(/\|.*?\|/g, function(f) {
var val = model;
var fieldParts = f.replace(/\|/g, '').split('.');
for (var i = 0; i < fieldParts.length; i ++) {
val = val[fieldParts[i]];
}
return val;
});
return template;
};
}(jQuery));
It is used by setting up a template (putting it into a script type="text/html” block is convenient and hides it from display) and calling cliche(model) on the jQuery object:
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. This will only handle relatively simple validation cases.
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.