BLOG

I Read... There... I Said It!

03 July 2009 by Stuart Cam

I am sometimes asked "so how do you keep up-to-date with all that's happening in the industry?".

Well, I...

The problem is making time for these endeavours. Usually I will alternate between them, much like a buffet, occasionally gorging on a particular topic when I am in the right frame of mind. Obsessive? possibly... but I think it's important to have a varied diet to keep it exciting.

Online articles and coding websites are great for picking up the odd skill or two but they often lack the depth required for some topics.

I had attempted to reconcile my love of technical books and mitigate some of their downsides (size, weight, cost and errata) by purchasing a Sony PRS-500 and seeking out digital versions of titles. I bought the unit when it first launched a couple of years ago and since then it has seen relatively little action. It's been quite a disappointment. The main problem is screen size, or lack thereof. It's way too small to render diagrams and code snippets with clarity. If your primary goal is to read technical books then I'd suggest avoiding the unit altogether and consider a tablet PC instead. That, or take a look at the much larger 9.7" Kindle DX.

I have recently purchased a round of new books in dead-tree format, which I intend to read over the coming weeks...

Software Development

97 Things Every Software Architect Should Know - Various

97 Things Every Software Architect Should Know - Various

I originally found out about the book through Udi Dahan's blog. Udi has made a couple of article contributions and figured it would be worth a read since I respect his opinions on software development and admire his NServiceBus framework.

The book contains small snippets of non-technical advice from a variety of architects - experience which, in some cases, has been hard won.

The unedited contributions from each author are available for free.


SOA in Practice: The Art of Distributed System Design - Nicolai M. Josuttis

SOA in Practice: The Art of Distributed System Design - Nicolai M. Josuttis

What are the two rules of distributed computing?

1. Do not distribute, it's difficult
2. See #1 (asynchronously)

I know, I know, it's a terrible joke! I had been looking around for an authoritative book on SOA and distributed systems and this book came highly recommended for cutting through the hype. The accompanying website can be found here.


.NET Framework

Effective C#: 50 Specific Ways to Improve Your C# - Bill Wagner

Effective C#: 50 Specific Ways to Improve Your C# - Bill Wagner

I had originally found out about this book through my professional network on LinkedIn via Chris Fulstow. He had mentioned that he was reading the book so I figured it must be worth a look.

It's full of best practices specifically for C#, covering some of the more esoteric language 'features' and how to avoid digging yourself into a big hole with them.

Take a listen to the interview with Bill Wagner on .NET Rocks!


More Effective C#: 50 Specific Ways to Improve Your C# - Bill Wagner

More Effective C#: 50 Specific Ways to Improve Your C# - Bill Wagner

I figured I ought to buy the sequel as it contains information on how to get the best out of the newest C# features such as LINQ and Lambda Expressions.

I heard about this book through Chris Fulstow (again) and subsequently through another .NET Rocks! podcast with Bill Wagner.


ASP.NET MVC 1.0 Quickly - Maarten Balliauw

ASP.NET MVC 1.0 Quickly - Maarten Balliauw

I've been aware of the ASP.NET MVC framework for quite some time. Pretty much the day after Scott Guthrie announced a prototype at the ALT.NET conference. I was looking for a short book which would assume knowledge of ASP.NET and cut straight to the .NET MVC implementation.

Since v1.0 is fairly new there are numerous online tutorials for earlier versions and some great MVC blogs, but not much in the way of printed books. This looked to be the best of a small bunch.


Windows Presentation Foundation Unleashed - Adam Nathan

Windows Presentation Foundation Unleashed - Adam Nathan

I have a minor confession. I have zero WPF experience, which is a little embarrassing since it replaced GDI+ long, long ago.

Unlike many other technical books this one is printed on glossy paper in full colour and totally jam packed with pictures and diagrams. Perfect presentation for learning a presentation framework!

An ex-colleague, Jack Ukleja, recommended this book.


Other Technologies

The Definitive ANTLR Reference - Terrence Parr

The Definitive ANTLR Reference - Terrence Parr

I purchased a digital copy of this book some time ago and have nearly finished reading it... in the bath... on my PRS-500... wrapped rather optimistically in cling film. This time I figured I'd buy the paper version and risk the £16.88 it would cost me to replace if I dropped it!

Bath + electrical items != mix.


Compilers: Principles, Techniques and Tools - Various

Compilers: Principles, Techniques and Tools - Various

Probably the densest, in both physical and subject matter, of all the books I purchased. I had a quick flick through some of the material and it looks pretty heavy going and full of maths. I anticipate that this will take a long time to read and no doubt expose many other holes in my knowledge along the journey.

My primary motivation was to supplement the ANTLR book with other compiler topics.


Collective Intelligence in Action - Satnam Alag

Collective Intelligence in Action - Satnam Alag

A rather interesting book intended for a Java audience, but which contains mathematics and algorithms suitable for implementation elsewhere. I discovered the book whilst surfing the internet for recommendation engines, which itself was a spur from reading about a recommendation engine that Joel Pobar had written in F#.

Hopefully this book will shed some insight on writing a sophisticated Web 2.0 application.


NHibernate in Action - Various

NHibernate in Action - Various

Another re-purchase of a book I own in digital form. I have followed it through the Manning Early Access Program.

My main gripe is that it doesn't cover the newest version of NHibernate, but given the time it takes to write a book and the speed at which frameworks evolve it's forgivable.

One of the best references for NHibernate available today.


Other

Here Comes Everybody - Clay Shirky

Here Comes Everybody - Clay Shirky

If I had a dollar for every time I heard Jeff Atwood mention Clay Shirky on the StackOverflow podcast I'd probably be able to buy this book without opening my wallet! Instead, I decided to spend my own money and discover the material for myself.

It comes highly rated and promises some insight on the huge changes we are seeing on the internet today with social networking and the wisdom (or madness) of crowds.


The Paradox of Choice: Why More is Less - Barry Schwartz

The Paradox of Choice: Why More is Less - Barry Schwartz

This is the least technical book of the bunch, cited as a reference in The Cult of the Amateur - a book I really enjoyed reading on my travels.

I would probably consider myself a 'maximiser' when it comes to making purchases - perhaps this book will change the way I rationalise my spending decisions? Perhaps it will change the way I buy books? :)


Simply put, read books and treat your education as a #1 priority.

Bill Hicks would probably agree (just with more swearing):

Tags: , , ,

Categories: .NET | Books | C Sharp | General | MVC | SOA | Web

.NET 4.0 - The Game Changers (In My Opinion)

27 May 2009 by Stuart Cam

If you haven't yet noticed .NET 4.0 and Visual Studio 2010 are out of CTP and into Beta. Bleeding-edge developers might want to download and take them for a spin.

There are quite a few new features in .NET 4.0, the most interesting for me are:

  • Task Parallel Library (TPL). Now a first class citizen in the framework, the Parallel FX (PFX) library makes writing multithreaded code a breeze. I had the opportunity to attend a talk on the PFX library with Joe Duffy at TechEd, Sydney 2008 . It's nice to see this library finally make it into the BCL.
  • Dynamic Language Runtime (DLR). Dynamic languages, such as IronPython and IronRuby, now make 'official' status in the .NET framework. C# implements a new dynamic keyword to interop with dynamic languages. Here is a great video on Channel 9 with Eric Lippert and the C# compiler developers where they talk about C#'s static viewpoint on dynamic typing.
  • Code Contracts & Pex. Remember Spec#? the superset of C# with design-by-contract features? Well, the team in Microsoft Research have decided to bundle all of the idioms into a .NET library, welcome the new namespace System.Diagnostics.Contracts. This video at PDC 2008 gives a great overview of C# design-by-contract programming, and a wonderful demonstration of Pex. Download Code Contracts for Visual Studio 2008.

The IDE is also gradually making the transition to WPF making the whole visual experience a lot more pleasing. I wonder how far the customisation will be taken?

.NET 4.0 doesn't quite have the same impact on me (personally) that .NET 3.5 had (I am still blown away by just how powerful and brilliant LINQ is). That said it's really exciting to see Microsoft taking the framework forward and offering their take on the future of Windows programming. Take a look at how .NET is changing.

Tags: , , ,

Categories: .NET | C Sharp

Mocking A Generic Method And Generic Constraint

14 May 2009 by Stuart Cam

I just stumbled across a problem in my integration testing around a particular scenario.

The problem occurs when attempting to create a mock instance for a class that has a generic method with a generic constraint - either at the class or method level.

Consider the following code:

public interface IFoo<T> where T : IBar
{
  T Get();
}

We have added a constraint to the interface IFoo such that T must implement IBar. So far so good, apart from the 'standard' Rhino Mocks code below throws an exception:


public class MyBar : IBar {
  //...
}

//...

var mockInstance = Mocks.DynamicMock<IFoo<MyBar>>();

This fails with an error:

System.TypeLoadException: Access is denied: 'IFoo`1[MyBar]'.

The problem is that the underlying BCL has a bug in Reflection Emit which causes it to generate invalid code. Oh dear. This has already been raised as an issue with MS - but they are failing to resolve it. Go and make your feelings heard!

Ayende has a workaround in Rhino Mocks 3.4 and above, so now you can write the following:

var mockInstance = Mocks.DynamicMockWithRemoting<Foo<MyBar>>();

This pushes the creation of the mock object through some additional hoops to bypass the BCL bug. Smart!

Tags: , ,

Categories: .NET | C Sharp | TDD

C# Distance Between Two Post Codes

08 May 2009 by Stuart Cam

Google provides a fantastic Map API to retrieve address information for a particular post code (zip code to our fellow Americans).

I needed to calculate the distance between two UK post codes, and stumbled across a handy URL for querying Google:

http://maps.google.com/maps/geo?q=SW1A%202AA&output=xml

The URL above retrieves information for 10 Downing Street, London, UK.

Parse the longitude and latitude information from Google for two post codes, in conjuntion with the Haversine Formula for a working solution:

using System;
using System.Net;
using System.Web;
using System.Xml;

namespace Codebrain
{
    public static class Distance
    {
        // Handy structure for Long/Lat information
        public struct Coords
        {
            public double Longitude;
            public double Latitude;
        }

        // Unit calculations
        public enum Units
        {
            Miles,
            Kilometres
        }

        // Will return a null if the Google API is unable to find either post code, or the country constraint fails
        public static double? BetweenTwoPostCodes(string postcodeA, string postcodeB, string countryCodeWithin, Units units)
        {
            var ll1 = PostCodeToLongLat(postcodeA, countryCodeWithin);
            if (!ll1.HasValue) return null;
            var ll2 = PostCodeToLongLat(postcodeB, countryCodeWithin);
            if (!ll2.HasValue) return null;
            return ll1.Value.DistanceTo(ll2.Value, units);
        }

        // Overload for UK post codes
        public static double? BetweenTwoUKPostCodes(string postcodeA, string postcodeB)
        {
            return BetweenTwoPostCodes(postcodeA, postcodeB, "GB", Units.Miles);
        }

        // Uses the Google API to resolve a post code (within the specified country)
        public static Coords? PostCodeToLongLat(string postcode, string countryCodeWithin)
        {
            // Download the XML response from Google
            var client = new WebClient();
            var encodedPostCode = HttpUtility.UrlEncode(postcode);
            var url = string.Format("http://maps.google.com/maps/geo?q={0}&output=xml", encodedPostCode);
            var xml = client.DownloadString(url);
            var doc = new XmlDocument();
            doc.LoadXml(xml);

            // Create a custom namespace manager
            var nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("ge", "http://earth.google.com/kml/2.0");
            nsmgr.AddNamespace("oa", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0");

            // Any results?
            var nodelist = doc.SelectNodes("//ge:kml/ge:Response/ge:Placemark", nsmgr);
            if (nodelist == null || nodelist.Count == 0) return null;

            // Results are already ordered by accuracy, so take the first one
            var node = nodelist[0];

            // Check the Country constraint
            var countryname = node.SelectSingleNode("oa:AddressDetails/oa:Country/oa:CountryNameCode", nsmgr);
            if (countryname.FirstChild.Value != countryCodeWithin)
                return null;

            // Get the raw Long/Lat coordinates (I wish there was a nicer way..
            // perhaps averaging the LongLat enclosing box?)
            var coords = node.SelectSingleNode("ge:Point/ge:coordinates", nsmgr).FirstChild.Value.Split(',');
            double longitude;
            double lattitude;
            if (!Double.TryParse(coords[0], out longitude)) return null;
            if (!Double.TryParse(coords[1], out lattitude)) return null;

            return new Coords
                       {
                           Longitude = longitude,
                           Latitude = lattitude
                       };
        }

        public static double DistanceTo(this Coords from, Coords to, Units units)
        {
            // Haversine Formula...
            var dLat1InRad = from.Latitude * (Math.PI / 180.0);
            var dLong1InRad = from.Longitude * (Math.PI / 180.0);
            var dLat2InRad = to.Latitude * (Math.PI / 180.0);
            var dLong2InRad = to.Longitude * (Math.PI / 180.0);

            var dLongitude = dLong2InRad - dLong1InRad;
            var dLatitude = dLat2InRad - dLat1InRad;

            // Intermediate result a.
            var a = Math.Pow(Math.Sin(dLatitude / 2.0), 2.0) +
                    Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) *
                    Math.Pow(Math.Sin(dLongitude / 2.0), 2.0);

            // Intermediate result c (great circle distance in Radians).
            var c = 2.0 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1.0 - a));

            // Unit of measurement
            var radius = 6371;
            if (units == Units.Miles) radius = 3959;

            return radius * c;
        }
    }
}

Example Usage:

// The long way...
var distance = Distance.BetweenTwoPostCodes("BS1 6QQ", "SW1A 2AA", "GB", Distance.Units.Miles);
if (distance.HasValue) Console.WriteLine(distance.Value + " miles");
// ...or the short way
var distance = Distance.BetweenTwoUKPostCodes("BS1 6QQ", "SW1A 2AA");
if (distance.HasValue) Console.WriteLine(distance.Value + " miles");

It's not 100% accurate and technically speaking the distance is 'as the crow flies', but if you need simple information it'll do the trick nicely!

Tags: , , ,

Categories: .NET | C Sharp | Web


© Codebrain Consultancy 2010. All Rights Reserved. Registered in England: 5682074. VAT: GB 870198408. Log in