Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Phone number code puzzle November 4, 2011

Filed under: Coding,Scala — Rupert Bates @ 1:53 pm

Once upon a time I was presented with the following test in an interview:

Given a mapping of digits to an array of characters, ie.


Print out all the string permutations a given input of digits maps to.
So for instance the string “23” should return:

Another way to think of this is a function that returns all the possible combinations of letters the digits could represent if they were keypresses on a standard phone keypad.

I did a pretty bad job at this when I was asked it, partly because it was quite late at night, and partly because it’s not the sort of thing you find yourself doing that often, but today I found myself with a little bit of spare time on my hands and thought I’d give it another go.

I chose to do it in Scala rather than in Java which I had used last time and of course this led to the solution being much more elegant and succinct. If fact this is exactly the sort of problem that demonstrates the value of functional programming.

import collection.immutable.{List, Map}
import java.lang.String

object PhoneNumbers extends App {
  val input = "1234"
  val data = Map(
    0 -> List("0"),
    1 -> List("1"),
    2 -> List("a", "b", "c"),
    3 -> List("d", "e", "f"),
    4 -> List("g", "h", "i"),
    5 -> List("j", "k", "l"),
    6 -> List("m", "n", "o"),
    7 -> List("p", "q", "r", "s"),
    8 -> List("t", "u", "v"),
    9 -> List("w", "x", "y", "z")
  getCombinations(input.substring(0, 1), input.substring(1))
    .foreach(f => Console.println(f))

  def getCombinations(current: String, remaining: String): List[String] = {
    val vals = data(Integer.parseInt(current));
    if (remaining.length() == 0)
      return vals

    val restOfString = getCombinations(remaining.substring(0, 1), remaining.substring(1))

      .map(f => restOfString.map(f2 => f + f2))


How to save the position of a ScrollView when the orientation changes in Android July 28, 2011

Filed under: Android,Coding — Rupert Bates @ 2:29 pm

To save and restore the scroll position of a ScrollView when the phone orientation changes you can do the following:
Save the current position in the onSaveInstanceState method:

    protected void onSaveInstanceState(Bundle outState) {
                new int[]{ mScrollView.getScrollX(), mScrollView.getScrollY()});

Then restore the position in the onRestoreInstanceState method, note that we need to post a runnable to the ScrollView to get this to work:

    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        final int[] position = savedInstanceState.getIntArray("ARTICLE_SCROLL_POSITION");
        if(position != null)
            mScrollView.post(new Runnable() {
                public void run() {
                    mScrollView.scrollTo(position[0], position[1]);

Great error message from Castle Windsor March 30, 2010

Filed under: C#,Coding — Rupert Bates @ 8:19 pm

This is a great exception from the Castle Windsor IOC container:

Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
Add '<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />' to the <httpModules> section on your web.config

It tells you exactly what you need to do to fix the problem. If only more developers took the time to throw such helpful exceptions!

Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
Add ‘<add name=”PerRequestLifestyle” type=”Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel” />’ to the <httpModules> section on your web.config


Format a string in RFC 2822 format for use with Http headers in c# March 17, 2010

Filed under: Asp.Net,C#,Coding,Web — Rupert Bates @ 11:45 am
var lastModified = AppStart.ToString("ddd, dd MMM yyyy hh:mm:ss ") + "GMT"; //note the hard coded GMT, there doesn't seem to be any other way to get this

Custom Date and Time Format Strings on MSDN
Standard Date and Time Format Strings on MSDN


Call an extension method on IEnumerable using reflection February 17, 2010

Filed under: C#,Coding — Rupert Bates @ 6:27 pm

I recently needed to invoke the Cast extension method on a List via reflection, and found it was a bit different to what I was used to
I tried:

var cast = typeof (List<string>).GetMethod("Cast");

but this returned null, then after a bit of digging around I realised that because Cast is an extension method, I needed to get it from the class it is defined in which is System.Linq.Enumerable. This code gets us the MethodInfo for Cast:

var cast = typeof (Enumerable).GetMethod("Cast");

Then because Cast is a generic method we need to provide it with the TResult type parameter as follows:

var constructedCast = cast.MakeGenericMethod(ListType);

Then we can invoke it:

var castVals = constructedCast.Invoke(null, new[]{ theList});

notice that the first parameter to Invoke is null because extension methods are static, and also that we pass in the List we want to invoke the method on, which then becomes the ‘this’ parameter of the extension method.

The result of Cast is a CastIterator and I wanted a List so I can then call ToList in the same way and I end up with a List cast to the type I am interested in.

//The result of Cast<TResult> is a a CastIterator so we need to call ToList on this
var toList = typeof (Enumerable).GetMethod("ToList");
var constructedToList = toList.MakeGenericMethod(ListType);
var castList = constructedToList.Invoke(null, new [] {castVals});

Ruby’s ‘times()’ function in C# January 24, 2010

Filed under: C#,Coding,Uncategorized — Rupert Bates @ 10:20 pm

I’ve seen a lot of people enthuse about Ruby’s times() function which allows you to write code like:

5.times { |i| puts i }

which prints out:
It is a really nice syntax and it struck me that you could use similar syntax in C# by defining the following extension method on int:

public static class IntExtensions
	public static void Times(this int i, Action<int> func)
		for(int j = 0; j < i; j++)

Which then lets you write:

5.Times(i => Console.Write(i));

with the same results


Create an Asp.Net MVC HtmlHelper for use in unit tests November 17, 2009

Filed under: Asp.Net,C#,Coding,MVC,Web — Rupert Bates @ 5:47 pm

Here’s a utility factory class to create an HtmlHelper instance so that you can unit test extension methods written on it. It will take a controller and a model for methods which rely on those. I adapted it from this post, and changed it to work with Asp.Net version 1.0 and to accept a model.

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using KableDirect.Web.FrontEnd.Controllers;

namespace KableDirect.UnitTests
    class HtmlHelperFactory
        public static HtmlHelper CreateInstance(RouteData route)
            return CreateInstance(route, new HomeController());
        public static HtmlHelper CreateInstance(RouteData route, Controller controller)
            return CreateInstance(route, controller, null);
        public static HtmlHelper CreateInstance(RouteData route, Controller controller, object model)
            HttpContextBase httpContext = new HttpContextDummy();

            var cc = new ControllerContext(httpContext, route, controller);
            var vd = new ViewDataDictionary(model);
            ViewContext vc = new ViewContext(cc, new ViewDummy(), vd, new TempDataDictionary());
            return new HtmlHelper(vc, new ViewDataContainerDummy(vd), new RouteCollection());

        // Dummy classes needed to be able to create HtmlHelper

        private class HttpRequestDummy : HttpRequestBase
            public override string ApplicationPath
                get { return ""; }

            public override string AppRelativeCurrentExecutionFilePath
                // Any shorter string here gives exception:
                // index larger than length of string
                get { return "~/"; }

            public override string PathInfo
                get { return ""; }

        private class HttpResponseDummy : HttpResponseBase
            public override string ApplyAppPathModifier(string virtualPath)
                return virtualPath;

        private class HttpContextDummy : HttpContextBase
            public override HttpRequestBase Request
                get { return new HttpRequestDummy(); }

            public override HttpResponseBase Response
                get { return new HttpResponseDummy(); }

        private class ViewDummy : IView
            public void Render(ViewContext viewContext, System.IO.TextWriter writer)
                throw new NotImplementedException();

        private class ViewDataContainerDummy : IViewDataContainer
            public ViewDataContainerDummy()

            public ViewDataContainerDummy(ViewDataDictionary dataDictionary)
                _data = dataDictionary;

            private ViewDataDictionary _data;
            public ViewDataDictionary ViewData
                get { return _data; }
                set { _data = value; }



An Implementation of Fold for C# August 20, 2009

Filed under: C#,Coding,Functional programming,Uncategorized — Rupert Bates @ 9:22 am

I expect there are a number of implementations of this around, but I couldn’t find one so I wrote this. It is an extension method which implements Fold on IEnumerable

public static class Extensions
  public delegate TDestination FoldOperation<TSource, TDestination>(TSource item, TDestination acc);
  public static TDestination Fold<TSource, TDestination>(this IEnumerable<TSource> list, FoldOperation<TSource, TDestination> foldOperation, TDestination acc)
     foreach(TSource item in list)
       acc = foldOperation(item, acc);
     return acc;

I can then use this Fold function for something like this which takes an object with a number of properties and creates a querystring with the name/value pairs of all of those properties which are non-null:

public class UrlConstructor
  //Takes a RequestParameter object with a number of properties which
  //if their value is set should be translated into querystring parameters
  public static string ConstructUrl(RequestParameters rp)
    //Get all the properties where the value is not null
    var values = typeof(RequestParameters).GetProperties().Where(p => (p.GetValue(rp, null) != null));

    //Fold these values up into a string
    var querystring = values.Fold(((p, acc) => acc + p.Name + "=" + p.GetValue(rp, null) + "&"), "").TrimEnd('&');

    return "http://mybaseurl.com/default.aspx?" + querystring;

A couple of coding maxims April 23, 2008

I’ve a heard a couple of pithy little rules about coding recently which I thought were worth sharing.

The first was from Microsoft’s Chief Software Architect Ray Ozzie in this interview. He says something along the lines of ‘never start coding unless you have 4 contiguous hours to work on it without being interrupted, otherwise you’re introducing more bugs than you are usable code’. I found this slightly depressing because I never DO have that time anymore (as my work role becomes more strategic and architectural) and yet I’m not prepared to give up coding yet. I think it’s fair to say though that the coding that I do do now is much more of the ‘technology spike’ type, not the everyday grind of production code, and while this allows you to cherry pick stuff you find interesting, I do miss the rigour of writing code which is going to be released into the wild.

The second maxim is one which I really like from a guy called Tom Lazar who I met through work; he said that since debugging code is twice as hard as writing it in the first place, you should only ever write code that is half as clever as you are capable of writing. I love this, (almost) totally agree with it, and wish that more people (particularly inexperienced developers) would also see the wisdom in it.


A pattern for using Linq to SQL in a multi-tier environment February 8, 2008

Filed under: architecture,C#,Coding — Rupert Bates @ 11:00 am

This post shows an approach for using Linq to Sql within a multi tier Asp.Net application, and particularly how it can be made to work well with ObjectDataSources. It is here as a discussion piece as well as a usable bit of code.

The key features are a Request-scoped datacontext and entity controller classes which provide easy to use Create, Retrieve, Update and Delete (CRUD) operations implemented with Generics. It also discusses the use of DataLoadOptions and approaches to submitting changes back to the database.

Entity Controller classes

Each database entity has an associated controller class which is used to perform common CRUD operations. Specific entity controllers inherit from a generic class GenericController which already implements all the basic Select, Insert, Update & Delete operations.

public class GenericController<TEntity, TDataContext> where TDataContext : DataContext
    public static List<TEntity> SelectAll()
    public static void Insert(TEntity entity)
    public static void Update(TEntity entity)
    public static void Delete(TEntity entity)

Specific controllers then inherit from this by specifying the entity type which they are concerned with as well as the type of the DataContext used, as follows:

//ProductController class
public class ProductController : GenericController<Product, NorthwindDataContext>

which allows client code such as the following:

   IList<Product> products = ProductController.SelectAll();

The use of Generics means that I don’t need to add any code at all into my ProductController to get all the standard CRUD operations in a fully type safe way. My ProductController class can now be customised to add any further data access methods which are specific to Products, for instance GetByCategoryId().

Request scoped DataContext

The second part of this solution is the request scoped DataContext. This is a pattern that is commonly used with the Hibernate OR mapper as well as elsewhere, and it means that there is only ever one DataContext per Http request which is stored in the HttpContext.Items collection. It is implemented as a protected property of the GenericController class as follows:

        protected static TDataContext DataContext
                //We are in a web app, use a request scope
                if (HttpContext.Current != null)
                    TDataContext _dataContext = (TDataContext)HttpContext.Current.Items["_dataContext"];
                    if (_dataContext == null)
                        _dataContext = Activator.CreateInstance<TDataContext>();
                        HttpContext.Current.Items.Add("_dataContext", _dataContext);
                    return _dataContext;
                    //If this is not a web app then just create a datacontext
                    //which will have the same lifespan as the app itself
                    //This is only really to support unit tests and should not
                    //be used in any production code. A better way to use this
                    //code with unit tests is to mock the HttpContext
                    if (_dataContext == null)
                        _dataContext = Activator.CreateInstance<TDataContext>();
                    return _dataContext;

Using the HttpContext.Items collection does introduce a dependency on System.Web to your data layer, but I’ve made the decision that since this solution is specifically designed for use in Asp.Net applications, this is acceptable. Checking for a valid HttpContext and then using an static variable if it doesn’t exist gives a bit of flexibility to use the class outside of a web app, for instance in unit tests, although this will produce subtly different results, so mocking the HttpContext would probably be a better approach.

The usefulness of this approach can be seen if you consider a page which uses a number of ObjectDataSources; if we configure our ObjectDataSource to use the DataContext directly then each one will create and dispose of a new DataContext this will not only quickly become a performance overhead, but will also present us with a problem when specifying LoadOptions for the DataContext resulting in more complex, less maintainable code or quite possibly code which doesn’t specify loading options at all.

It should be noted that this approach means that if I have a CategoryController class as well as a ProductController class, both of which inherit from GenericController, both of these classes will use the same DataContext. In other words the DataContext is shared across the whole request, not just by one class type.


Before going any further, we need to look at the thorny issue of DataLoadOptions. As a number of people have noted the way that Linq to Sql works, means that the DataLoadOptions for your DataContext need to be set before any operations are carried out, and cannot subsequently be changed. This means that in my Asp.Net application I will need to set the DataLoadOptions for the whole request somewhere near the start (assuming of course that I need to set DataLoadOptions at all). It also means that my UI or business layer will need to take responsibility for this.

What this means in practice is that in a classic Web forms type app I will probably set the DataLoadOptions in the OnInit event of my page, if I’m using MVC then my controller will do it. I don’t really have a problem with this, particularly in the case of an MVC app as I think this is probably the best place to actually specify how you want your data loading logic to work. I’m interested to hear other opinions on this.

Submitting changes

Another feature of the Linq to Sql architecture is the way that changes are only submitted to the database when the SubmitChanges() method is called on the DataContext. This means that we must either decide at which point to call SubmitChanges() or delegate this responsibility to client code.
To make the classes as flexible as possible any operations which require a call to SubmitChanges (Insert, Update and Delete), are provided with a boolean parameter which specify whether to submit changes immediately or not. There is also an overload of these methods without this parameter which is equivalent to passing true (again this makes use of ObjectDatasources much more straightforward).
The SubmitChanges method of the DataContext is also exposed through the controller class to give Client code the ability to call this explicitly.

The code

You can download the code for this post from CodeGallery

The code consists of 2 projects

  • The data access layer – this is made up of Linq to Sql dataclasses generated from the Northwind database, a class GenericController (discussed above) and two concrete subclasses ProductController and CategoryController.
  • A test web project – this project has one page with a GridView and a FormView which use the data layer via ObjectDataSources to list all the products in the Northwind database, allow editing and deletion of those projects, and insert new products via the FormView.

To run the example project:

  • Download and unzip the release
  • Open the solution in VS2008
  • Change the connection string in the web.config to point to a Northwind database
  • Run the web project

To use the code in your own projects

  • Copy the class GenericController into your Linq to Sql project
  • Create one entity controller class for each Linq to Sql entity, inheriting from GenericController
  • Optionally define any new entity specific data access operations in your entity controller classes