MobileTFL 1.1.0.0

April 17th, 2010

A really quick note, MobileTFL, the London Tube status application for Windows Mobile 6+, has just been updated to version 1.1.0.0.

Changes: Supported new TFL data feed format, fixed breaking bug.

Get it here: http://www.davidwhitney.co.uk/content/blog/index.php/software/

I’m currently an Android user while awaiting Windows Phone 7, so I’ve only been able to test this against unit tests and the device emulator, but it looks fine. That said, feedback would be appreciated.

Thanks to all the people that emailed me to let me know the app had broken.

Automatic Html Encoding in ASP.NET 4.0

April 13th, 2010

I spent today at Microsofts Techdays Visual Studio 2010 launch event in London.  Lots of interesting stuff, covered in depth all over the internet (just Google, or bing, if you’re a sadist “changes from .NET 3.5 to .NET 4.0″).  A tiny thing that caught my attention for it’s pure utility to the masses is a new operator in ASP.NET 4.0 that deals with Html Encoding of data implicity.

You’ll likely be familiar (especially if you’re working with ASP.NET MVC) with the <%= notation for referencing properties in the context of the ASP page.  In ASP.NET 4.0 this has been joined by <%: This addition automagically HtmlEncodes any content between the opening and closing tags to prevent repetitive tag soup of <%=HttpUtility.HtmlEncode(myProperty)%> all over your views, and removes the temptation to push HtmlEncoding into your Controller or Model, two places where encoding really shouldn’t be a concern.

Just struck me as a nice little change that’ll make everyday life that little bit easier for a majority of web developers. Sure it’s not quite the new Xaml designer (which is a work of beauty) or Intellitrace (which looked like a total game changer for retrospective debugging), but you know, it’s the little things that count.

What Are APIs Anyway?

February 19th, 2010

What are APIs anyway?

Everyone’s heard of APIs these days.  Facebook has them, Twitter has them, Hotmail has them, Microsoft Office has them, Windows has them, Mac OS has them, pretty much everything has them.  I’m going to try and explain in simple terms, but also, almost by contradiction, in detail, what an API really is.  I’ll try and explain why SOAP isn’t how you clean yourself, and how being restful isn’t the same as being lazy.

APIs aren’t new, in fact, APIs are really really old.

Let’s start with a really simple definition.  API is an acronym and it stands for “Application Programming Interface”

To steal the current definition from Wikipedia “An application programming interface (API) is an interface implemented by a software program to enable interaction with other software, much in the same way that a user interface facilitates interaction between humans and computers. APIs are implemented by applicationslibraries and operating systems to determine the vocabulary and calling conventions the programmer should employ to use their services. It may include specifications for routinesdata structuresobject classes and protocols used to communicate between the consumer and implementer of the API.”

That’s a mouthful.  So to translate that into English, an API is a pre-defined set of “stuff” that allows one program to “talk” to another program.  This “stuff” is normally a set of “functions” that another program can call which makes the program being called do something.  Sometimes that other program is really just another part of the same program, and sometimes it’s a different system on a different machine in a different country.  That something is normally described in some kind of documentation, written somewhere, by someone.

If this sounds really vague it’s because in the real world, it really is.  Some of the first “APIs” involved dropped text files into directories on a computer that another program would watch for a read from, and subsequently do “something”.  Arguably the most widely used API is the one that we use to write software for Windows (the Win32 API) and by contrast, that’s a C++ library of code that you can only call if you’re a programmer.  In the real world, we’ve tried to solve some of this ambiguity by standardizing the way APIs work around a few common bits of technology; both for our own sanity and to hopefully help software all just kind of work together.

A lot of APIs are code libraries called by other code libraries to do a specific task.  Microsoft released DirectX to deal with 3d graphics, OpenGL offered an open alternative.  Microsoft released the Windows API for Windows development; Apple released Carbon and Cocoa to program Mac OS.  That said when you hear about or discuss APIs casually, what you’re probably thinking about are actually “Web APIs”.

Web APIs

A Web API is an API like anything else, except it’s designed to work over the web.  As a result of this, since about 1994, there have been a number of efforts by a number of people (yes, that vague again!) to standardize the way systems communicate over the internet.

At first, everyone kind of invented their own way of communicating over the internet, people would connect to a server on some port (a port is just a pre-defined “way in”) and send some random pre-defined data in there, and that would make the computer at the other end do something.  Every API was different, and every time that you needed to talk to a different system, you had a really steep learning curve to work out how to talk to every application you wanted to integrate with.  It was a bit rubbish really.

So in 1998 a bunch of really smart people (Dave Winer, Don Box, Bob Atkinson, and Mohsen Al-Ghosein) got together and came up with SOAP (“Simple Object Access Protocol”).  SOAP is a big bunch of XML that was designed (and ratified) as a standard language that every different system could understand. SOAP is often also referred to as “web services”.

Basically it was designed to reduce the learning curve of learning the details of each system.  So now, if Timmy wanted to talk to Peters shiny new web application, he could point his developer tools at a standard location (something called a WSDL (web service description) document) and he could just ask Peters web application what it did, and how he could use it.

SOAP was actually pretty good and solved a lot of problems and is still widely used today.  It really made waves by helping Microsoft software work pretty well with Java software and everyone was happy.

Almost.

See, because SOAP was solving a lot of big problems in freaking huge enterprise systems, it had a lot to be concerned about; lots of security, lots of encryption, lots of authentication.   That meant that the SOAP “language” was pretty big.  As an example, here (stolen from Wikipedia again!) is the SOAP message that would be sent across the internet to get the current stock price of IBM, from some cool stock price giving web service.

POST /InStock HTTP/1.1

Host: www.example.org

Content-Type: application/soap+xml; charset=utf-8

<?xml version=”1.0″?>

<soap:Envelope

xmlns:soap=”http://www.w3.org/2001/12/soap-envelope”

soap:encodingStyle=”http://www.w3.org/2001/12/soap-encoding”>

<soap:Body xmlns:m=”http://www.example.org/stock”>

<m:GetStockPrice>

<m:StockName>IBM</m:StockName>

</m:GetStockPrice>

</soap:Body>

</soap:Envelope>

People soon started thinking “Look at all that crap! What’s it all for! Why do I need it?! There’s lots of overhead here!  It slows me down!” and everyone thought “oh actually, well said” and RESTful web services were born.

REST is yet another stupid acronym that actually doesn’t count as an acronym because it uses random letters but developers think is either cool clever or funny.  What it claims to mean is “REpresentational State Transfer” and was largely both a reaction to the complexity and overheads of SOAP, but also being designed by Roy Fielding (one of the authors of the “Hypertext transfer protocol”, the silly http:// bit you type in a browser) it was conceived as an API model that was “closer to the nature of the web”.

What this means to us lay folk, is that while SOAP can technically be used over other protocols (it’s not bound to http), and as such has to bake in security and authentication models into its protocol, REST is designed specifically for the web, it doesn’t work without the web, and it wouldn’t make any sense without the web.  Fielding basically decided that “the web does all of that stuff anyway”, we have security via https / SSL certificates, we have semantics that describe getting and pushing data in the HTTP headers (HTTP headers explain what you’re trying to do to the server you’re connecting to, for example, you use GET for getting stuff, POST and PUT for doing stuff), so let’s just use that and be done with it.

As a result of this way of thinking, REST is a simplified and less general Web API pattern, not concerned with infrastructure like SOAP is.  I’ll convert the above stock price example into a REST example below.

GET /Stocks/Price/IBM HTTP/1.1

Host: www.example.org

Content-Type: application/xml; charset=utf-8

Done.

Basically, REST takes out all the fluff, an decides that if you want to get a stock price for IBM, just make a GET request to the URL http://www.example.org/Stocks/Price/IBM and let the web server at the other end work out what to do from the URL.

The above example would probably return an XML document that looks like this.

<stocks><stock name=”IBM” price=”3.45”/></stocks>

People have started to gravitate towards REST due to its simplicity.  There’s lots of other stuff a RESTful web service should do, it should provided you with all the information that a computer would need to go through a process, just like a user interface gives the user all the information they need to click through a process, but fundamentally it’s simple and leverages the existing semantics of the web to its advantage.

Ok, Give Me One Of Those!

So now we know what an API is there to do (let two systems talk to each other) and how they do it (as a general rule, either via SOAP or RESTful services) and we know that everyone else has one, let’s get one of our own.

There are plenty of tools available in pretty much any programming language to make making creating APIs pretty easy.  There are plenty of design concerns to take into account when building an API but in my opinion, the way to approach the problem is to work out what your users really want to do with your application, website or platform, and let them do it.

A good API lets another programmer talk to your system using terms that he understands, so take the time building up a glossary of your business terms vs. what the public understands those concepts to be.  Don’t build API methods that look like:

/PaymentResolutionProcess/PaymentResolveTable3/Resolve/EntityId/123

because it means nothing to anyone, instead, build a bunch of methods that make sense for people to use, the above example could look like this instead:

/Payment/MakePayment/123

Watch your language, and build sensible interactions with your system.  Don’t make APIs for stuff that isn’t going to be used, and where possible, just have the APIs call the same code that your website does.

Get this right, and you’re on a gradual but successful road to calling your “website” a “platform”.

C# Access Modifiers Are Type Specific, NOT Instance Specific

February 17th, 2010

Here’s an interesting example from a brief discussion I was having on twitter yesterday with @DotNetWill.

Did you realize that access modifiers in .NET are type specific rather than instance specific. It’s not a weird edge case, it is exactly how the language spec lays it out, but it’s not how most people think access modifiers work. This is because it’s not very often that any given type will have a reference to ANOTHER instance of that type, it just tends to not come up.

Either way, could make for some hilariously difficult debugging if you weren’t aware of it and something was “playing with your privates” by reference.

You might have seen this kind of usage in a singlet*on, constructor or builder class (or as @jagregory pointed out, cloning methods), but generally it’s just not a very common usage example. However, it WILL both compile and execute.

// Example of access modifiers being specific to a type not an instance
public class MyType
{
     private MyType _innerMyType;

     public MyType()
     {
     }

     public void MakeInnerMyType()
     {
          _innerMyType = new MyType();
          _innerMyType._innerMyType = new MyType();
     }
}

Nothing ground breaking, but a fun and interesting little example illustrating a common misconception.

ASP.NET MVC View Engine That Supports View Path Inheritance

January 19th, 2010

I was working on a small MVC project where we were dealing with Inherited controllers (SomeController was inherited by SomeMoreSpecificController) and we decided that it’d be nice to have a similar hierarchy of sharing and inheritance at the View level.

Unfortunately, out of the box, ASP.net MVC looks in two default locations for your views and partials by convention.  The first is /Views/ControllerName/ViewName.aspx, the second is /Views/Shared/ViewName.aspx.  We wanted to allow SomeController to have it’s own set of more generic views, that could later be overridden in special cases by the views provided by SomeMoreSpecificController.

In order to do this in ASP.net MVC, you need to override the default view engine to change the location that the runtime looks for your views.

“Here’s one I made earlier”.

Using this ViewEngine, if you call an action method on SomeMoreSpecificController it’ll first check /Views/SomeMoreSpecificController/…, then /Views/SomeController/… (the base class), then finally /Views/Shared, allowing you a little more control over the organisation of your views.

using System.Collections.Generic;
using System.Web.Mvc;
using System;
using System.Globalization;
using System.Linq;

namespace MyMvc.Mvc
{

    public class InheranceViewEngine : WebFormViewEngine
    {
        private const string CacheKeyFormat = ":ViewCacheEntry:{0}:{1}:{2}:{3}:";
        private const string CacheKeyPrefixMaster = "Master";
        private const string CacheKeyPrefixView = "View";
        private static readonly List<string> EmptyLocations= new List<string>();

        public InheranceViewEngine()
        {
            ViewLocationFormats = new[]
                                  {
                                      "~/Views/{1}/{0}.aspx", "~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.aspx",
                                      "~/Views/Shared/{0}.ascx"
                                  };
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (String.IsNullOrEmpty(viewName))
            {
                throw new ArgumentException("viewName");
            }

            List<string> viewLocationsSearched;
            List<string> masterLocationsSearched;

            string controllerName = controllerContext.RouteData.GetRequiredString("controller");
            string viewPath = GetPath(controllerContext, ViewLocationFormats, viewName, controllerName, CacheKeyPrefixView, useCache, out viewLocationsSearched);
            string masterPath = GetPath(controllerContext, MasterLocationFormats, masterName, controllerName, CacheKeyPrefixMaster, useCache, out masterLocationsSearched);

            if (String.IsNullOrEmpty(viewPath) || (String.IsNullOrEmpty(masterPath) && !String.IsNullOrEmpty(masterName)))
            {
                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));
            }

            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
        }

        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            List<string> strArray;
            if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); }
            if (string.IsNullOrEmpty(partialViewName)) { throw new ArgumentException("Partial View Name is null or empty.", "partialViewName"); }
            string requiredString = controllerContext.RouteData.GetRequiredString("controller");
            string str2 = GetPath(controllerContext, PartialViewLocationFormats, partialViewName, requiredString, "Partial", useCache, out strArray);
            if (string.IsNullOrEmpty(str2))
            {
                return new ViewEngineResult(strArray);
            }

            return new ViewEngineResult(CreatePartialView(controllerContext, str2), this);
        }

        private string GetPath(ControllerContext controllerContext, string[] locations, string name, string controllerName, string cacheKeyPrefix, bool useCache, out List<string> searchedLocations)
        {

            searchedLocations = EmptyLocations;

            if (String.IsNullOrEmpty(name))
            {
                return String.Empty;
            }

            if (locations == null || locations.Length == 0)
            {
                throw new InvalidOperationException();
            }

            bool nameRepresentsPath = IsSpecificPath(name);
            string cacheKey = CreateCacheKey(cacheKeyPrefix, name, (nameRepresentsPath) ? String.Empty : controllerName);

            if (useCache)
            {
                string result = ViewLocationCache.GetViewLocation(controllerContext.HttpContext, cacheKey);

                if (result != null)
                {
                    return result;
                }
            }

            if (nameRepresentsPath)
            {
                return GetPathFromSpecificName(controllerContext, name, cacheKey, ref searchedLocations);
            }
            return GetPathFromGeneralName(controllerContext, locations, name, controllerName, cacheKey, ref searchedLocations);
        }

        private string GetPathFromGeneralName(ControllerContext controllerContext, string[] locations, string name, string controllerName, string cacheKey, ref List<string> searchedLocations)
        {
            string result = String.Empty;
            searchedLocations = new List<string>();

            for (int i = 0; i < locations.Length; i++)
            {
                string virtualPath = String.Format(CultureInfo.InvariantCulture, locations[i], name, controllerName);
                if (FileExists(controllerContext, virtualPath))
                {
                    searchedLocations = EmptyLocations;
                    result = virtualPath;
                    ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, result);
                    return result;
                }
                searchedLocations.Add(virtualPath);
            }

            return GetPathFromGeneralNameOfBaseTypes(controllerContext.Controller.GetType(), locations, name, controllerContext, cacheKey, result, ref searchedLocations);
        }

        private string GetPathFromGeneralNameOfBaseTypes(Type descendantType, string[] locations, string name, ControllerContext controllerContext, string cacheKey, string result, ref List<string> searchedLocations)
        {
            Type baseControllerType = descendantType;
            if (baseControllerType == null
                || !baseControllerType.Name.Contains("Controller")
                || baseControllerType.Name == "Controller")
            {
                return result;
            }

            for (int i = 0;i < locations.Length;i++)
            {
                string baseControllerName = baseControllerType.Name.Replace("Controller", "");
                string virtualPath = String.Format(CultureInfo.InvariantCulture, locations[i], name, baseControllerName);

                if (!string.IsNullOrEmpty(virtualPath) &&
                    FileExists(controllerContext, virtualPath))
                {
                    searchedLocations = EmptyLocations;
                    result = virtualPath;
                    ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, result);
                    return result;
                }

                searchedLocations.Add(virtualPath);
            }

            return GetPathFromGeneralNameOfBaseTypes(baseControllerType.BaseType, locations, name, controllerContext,
                                                     cacheKey, result, ref searchedLocations);
        }

        private string CreateCacheKey(string prefix, string name, string controllerName)
        {
            return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat,
                                 GetType().AssemblyQualifiedName, prefix, name, controllerName);
        }

        private string GetPathFromSpecificName(ControllerContext controllerContext, string name, string cacheKey, ref List<string> searchedLocations)
        {
            string result = name;

            if (!FileExists(controllerContext, name))
            {
                result = String.Empty;
                searchedLocations = new List<string>{ name };
            }

            ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, result);
            return result;
        }

        private static bool IsSpecificPath(string name)
        {
            char c = name[0];
            return (c == ‘~’ || c == ‘/’);
        }

    }
}

I don’t understand Bayonetta

January 10th, 2010

I keep seeing glowing reviews of Bayonetta.  You might have seen it advertised, the game with the “witch” that looks like Sarah Palin, who uses her hair as both a weapon and her outfit, has guns on the heels of her shoes and features in a game that has a button for “dance / taunt”.  This game has unanimously been receiving 100% or near reviews from practically every major game publication.

But you know what, I really don’t understand this game.  For a little context, I play everything.  The well reviewed stuff when it first releases, and then the mediocre games when the price drops to around £20.

But I’m just not interested in this game.  The pre release hype is tacky, it looks terrible (I don’t mean the style, the style is reasonable but playing the demo, it looks noticeably rough around the edges) and the game play appears to be extremely repetitive.

I downloaded the demo and just didn’t quite get to it until the game released, gave it a shot and was mildly entertained at best, and bored with it’s "not retro, just not sophisticated" game play within minutes.

I just don’t understand the heaps of praise people are giving this game.  Sex sells, and that aside (because actually the sexuality in the game is very comic-book like and gets annoying fast, like, during the duration of the demo fast), the game play appears to be simple, repetitive, and if it’s 16 hours long, probably outstays its welcome.

I picked up Wet recently, a game that sells itself on roughly the same premise of "hot girl on a vendetta" for £20 and found it repetitive, gratuitous but a fun 10 hour game.  It wasn’t a good game, but it was cheap and short enough to execute what it was attempting effectively.  It got panned.  Bayonetta was made by an influential game designer but suffers all of the same flaws of the former game, whilst suffering an uncomfortable character premise.  It’s been widely acclaimed.  I just don’t understand why.  I’d honestly pay no more than about £5 for this game, and I’d probably give up playing very quickly.

These impressions are obviously all based on the pre-release hype, marketing material and the (terribly named) "First Climax" demo.

A friend of mine quipped "if I was playing Bayonetta and somebody walked in, I’d turn it off and pretend it was porn".  I can’t help but agree with that sentiment.

Albums of the year… 2009…

December 15th, 2009

It’s the time of year when people make lists to fill the internet with content, so for anyone that cares I’m going to talk about music for a few moments.

In my eyes (ears?) there are three obvious contenders to album of the year but choosing between them is exceptionally difficult…

1. Alice In Chains – Black Gives Way To Blue

A perfect Alice album, stunning, but at the same time, EXACTLY what I expected from Alice In Chains.  Excellent but unsurprising.  Had the pleasure of seeing them play the 900 capacity gig in London just before the album released and was blown away.  If anything, I actually was let down by how much they didn’t let new front man William Duvall lead the album, falling back on Jerry Cantrell performing most of the leads (presumably so as not to alienate the fans).  The irony being, Duvall’s one track “Last of my kind” practically steals the show ever so slightly nudged out by “Acid Bubble”.

2. Mastodon – Crack The Skye

Simply stunning.  A cut above anything Mastadon have done before, subtle, progressive and excellently written.  Swings from dramatic and fast back down to slow winding near-ballads.  Totally unexpected and excellent.  There is honestly not a track on this album that I don’t feel is outstanding.  Full of enough straight out metal to please just about anyone while drenching listeners with atmosphere and sprawling epics.  As full-of-platitudes as that description sounds it’s pretty accurate.  “The Last Baron” totally steals the show.

3. Katatonia – Night Is The New Day

Somehow a cumulation of everything Katatonia have attempted in the past.  The production is some of the best in modern metal (and all self-produced) and Jonas’ vocals REALLY shine, mixed with the signature ethereal Katatonia guitar and a few bleak bleak moments.  Again redefining what melodic dark hard rock should sound like.  Very intimate.  This is a dark album, upsetting in tone full of little uplifting refrains.  I love the subtle guitar parts and optimistic feel on “Onward Into Battle”, the driving brooding bass on “The Promise of Deceit” and clearly the most miserable song I’ve heard in years in “Nephilim” (bleak beyond words), but in the end “The Longest Year” steals the show, not with darkness and misery but with a hint of optimism.

I think the album I enjoy most is Katatonia’s effort, but in measured consideration, Mastodon is the most impressive, excellent album I’ve heard all year.

Honourable mentions?

Porcupine Tree – The Incident (under rated compared to Fear of a Blank Planet)
Devin Townsend Project – Addicted (just plain excellent, but we all know Deconstruction is where it’s going to be at)
Riverside – Anno Domini High Definition. (nice grown up brooding hard rock)

Writing Presentable Code Pt.1 – Properties and Variables

November 4th, 2009

At work we’re currently discussing coding standards, specifically to synchronise development in two countries and keep the style consistent across the teams.  You know, the usual stuff. 

When people start discussing coding standards, it quickly devolves into a religious debate and honestly, I think a lot of it comes down to personal preference.  Because of that, I’m going to spend a post or two telling your why you’re wrong and why I wouldn’t take your code to dinner however much it offered to put out.  Because clearly my way is the only right way!

Joking aside, I want to go into some detail on how I present and write my code, and hopefully explain why.  It’s all going to be slanted towards (who do I think I’m kidding, it’s going to be in) C# so as ever, your mileage may vary with any advice you extrapolate.  I’m going to start out by showing you some bad examples, attempt to explain why I think they’re bad, and offer my alternative.

Properties and Variables

The way you declare your properties and variables is seemingly insignificant, but if you get it wrong it trashes the readability of your code.  Take this code sample for example:

image

All I’ve done in the above screenshot is declare a few properties, a few instance variables and a constructor.  And it looks awful and un-maintainable despite the lack of any significant code smell, all due to the manner in which I’ve declared the variables.  It’s a laundry list of mistakes.

  1. Using field backed properties when an auto-property will suffice.
  2. Defining auto-properties split across multiple lines for no explicable reason.
  3. Adding utterly redundant code comments (the code-criticism comments aside).
  4. Terrible and ambiguous variable naming.
  5. Variable names that contain hints at data types.

The above code sample is practically unreadable, even without the comments, it’s long winded and obtuse:

image

Now, I come from the school of thinking that is pretty much convinced that typing things is bad, repeating yourself is bad, hell, writing code is bad.  So don’t.  Less really is more, pick your favourite buzz phrase.  Cleaning up your code should involve making it as simple and as clear as is humanly possible.

Thankfully, if you take advantage of the language features of C#3, you can quickly make something like that look like this:

image

Just by tidying up the way you declare and use your variables, you can make your code eminently more readable.  If you compare the two examples, you’ll see that all I’ve done is

Use single line declarations for auto-properties.

  • Why waste 3-5 lines on an auto-property that can easily fit one one without any loss in readability.

Removed data backed properties in exchange for auto-properties with access modifiers on the setter.

  • Functionally equivalent and far neater

Renamed badly named properties (in the first example “FLineOfAddress”) to be more meaningful.

  • Remove abbreviations where possible, they damage readability
  • Assume the maintainer of your code has no business knowledge, make things easy
  • Meaning is always better in variable names than in comments / meta-data
  • Don’t fear long variable names, modern IDEs have auto-complete, you don’t have to type that stuff by hand.  Embrace your tooling!
  • If you can’t tell what’s in your property or variable from it’s name, you’ve failed, go back and try again.
    • This honestly includes stuff like foreach(var item in MyCollection) and StringBuilder sb = new StringBuilder();  Both bad and wrong, don’t do it.

Only retained comments where the comment data is truly meaningful. 

  • The above example isn’t particularly good (everyone knows what a URL is), but only keep comments in your code where they add something that you couldn’t attain with careful renaming and code restructuring / refactoring.  The meaning of your code should be obvious to the reader without metadata.

Stick to a solid naming convention for public / private / protected variables and properties.

  • The well trodden convention I’m following above is lowerCamelCase plus…
    • A leading underscore for private instance variables (determining scope)
    • Regular lowerCamelCase for local variables
    • UpperCamelCase for property names, constants and statics.
    • No data types in your variable names.  This is not 1980. The IDE gives you all that lovely meta-data, don’t give yourself RSI duplicating it in your variable names.

Cleaning up usage

  • Removing this., you get the same scoping from using _ by convention in your variable names, save those fingers from RSI…
  • Using instance and local variables instantly becomes clearer by sticking to convention.

Using var to reduce duplication in code.

This is often controversial but I feel that using var, for the most part, reduces the amount of typing required without any loss of clarity.  Take the following examples:

image
It’s clear to me that no clarity is lost by not typing "StringBuilder” twice.  It’s still right there in front of you and allows you to keep your variable declarations more uniform.  Despite popular misconception this doesn’t affect the type safety of C#, the language and your variable are still strongly typed, the compiler just infers that when you said var you meant StringBuilder at compile time.   If it isn’t really obvious what an object is when you instantiate it, you’re probably doing something really wrong elsewhere.

People occasionally like to argue that while for declarations var is all well and good, when you’re using it for return values it causes a loss of clarity.  It’s an interesting point but always feels slightly off the mark to me.  Whenever people attempt to give me an example of this lack of clarity, it’s always that th
eir variables or properties are ambiguously or inappropriately named, and the code clarity can be regained and even improved by naming the variables involved in a more descriptive way.  Take the following snippet for example:

image
In the first case, I’d agree that using a var called “l” to store the return value of that method would lead to a loss in clarity.  But if you had string l = RetrieveTextLabel(); and then, say, 20 lines down attempted to use a variable called “l” you’d probably deserve a swift kicking for naming something so poorly.  By contrast, var textLabel is exceptionally descriptive.  People also occasionally say that using var in foreach loops causes this ambiguity, but again, if you name your collection appropriately and your yeilded value correctly, it really is never an issue.

Even more importantly, if you get your naming right, var actually helps you quickly refactor your code.  As long as you understand the “meaning” of your variables, the IDE can fill in the blanks with regard to data types, because for the most part, it really doesn’t matter what type of data is actually in that variable when you’re reading the code as long as it’s meaning is a known quantity.  I actually feel that the dynamic language crowd learnt this lesson long ago, and people that work predominantly in strongly typed languages actually tend to rely on the type system like a crutch to excuse terrible naming conventions.  Time to learn from PHP…

    In conclusion…

    To make your code readable you should stick to conventions for naming, always strive to add meaning in variable names and be as brief as possible.  Don’t litter your code with crap and you’ll be thankful for it later.

    Obviously, this is all my opinion, but I swear by it.

    I’ll be following up this post in the next few days with some continued patterns for readable code.

    Reusable Editable Fields for ASP.net MVC Using jQuery

    October 8th, 2009

    A friend recently asked me about editing items inline using ASP.net MVC, the kind of thing that was auto magically wired up with post backs in “old fashioned” asp.net so I’ve whipped up a small example showing how you can use jQuery to declaratively set up interactive field editing with a sprinkling of Ajax and JSON.

    I’m basing this example on the default ASP.net MVC starter project for brevity (download attached) but here’s an overview:

    First you need to set up an Action method (or multiple action methods) on your controller to accept the modification of data.  In my example I’ve added an unimaginative method called “SetField” to the HomeController that looks like this:

    public ActionResult SetField(string fieldName, string fieldValue)
    {
        var response = Json(fieldValue);
        return response;
    }

    As you can see, it doesn’t do very much (useful implementation left to the reader) but it accepts the parameters of a field name, and a field value.  You’ll need to roll your own validation and sanity checking here.  It then returns the fieldValue using the MVC Json helper object, as a Json object.  In a real world example, you’d want to call and update in this method.

    Now, in the view, jQuery does most of the hard work.

    First I added a few CSS classes to the header on the master page (for the sake of example):

    <style type="text/css">
        .editableItem { display: block; }
        .fieldViewer { display: block; }
        .fieldEditor { display: none; }
        .editableItemCancel { display: block; }
        .editableItemBox { display: block; }
    </style>

    I then added an example to the view that looked like this:

    <div class="editableItem" id="editable_FieldName">
        <div class="fieldViewer">Click me to edit me!</div>
        <div class="fieldEditor"><input class="editableItemBox" type="text"/><span class="editableItemCancel">cancel</span></div>
    </div>

    With this HTML I set up some conventions that I’ll rely on when using jQuery.  Firstly, every editable item should use the class “editableItem” and have the id “editable_FieldName”.  I use the class in a jQuery selector and the Id to establish which field is being edited.  Inside the editableItem should be a fieldViewer, containing the current data, and a fieldEditor, which is hidden by default, and contains some kind of editable controller and a cancel button.  You could insert these elements at runtime if you wished, but in order to keep the example simple I’ve declared them in the HTML.

    Next I added some jQuery… The jQuery defines some Javascript behaviour associated with the classes used in the HTML, this way, the mark-up can be reused to edit multiple fields rather than being keyed to the Id of a specific field.

    <script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        jQuery(document).ready(function() {

            $(".editableItem .fieldViewer").click(function() {
                var parentId = $(this).parent().attr("id");
                $(‘#’ + parentId + " .fieldEditor .editableItemBox").val($(‘#’ + parentId + " .fieldViewer").text());
                $(‘#’ + parentId + " .fieldViewer").toggle();
                $(‘#’ + parentId + " .fieldEditor").toggle();
            });

            $(".editableItem .fieldEditor .editableItemCancel").click(function() {
                var parentId = $(this).parent().parent().attr("id");
                $(‘#’ + parentId + " .fieldViewer").toggle();
                $(‘#’ + parentId + " .fieldEditor").toggle();
            });

            $(‘.editableItem .editableItemBox’).keypress(function(e) {
                if (e.which == 13) {
                    var parentId = $(this).parent().parent().attr("id");
                    var fieldName = parentId.replace(/editable_/, "");

                    $.post(‘/Home/SetField’,
                    {
                        fieldName: fieldName, fieldValue: $(‘#’ + parentId + " .editableItemBox").val()
                    },
                        function(data) {
                            $(‘#’ + parentId + " .fieldViewer").text(eval(‘(‘ + data + ‘)’));
                            $(‘#’ + parentId + " .fieldViewer").toggle();
                            $(‘#’ + parentId + " .fieldEditor").toggle();
                        })
                }
            });

        });
    </script>

    Quite simply, if you click the editable field, it toggles into a textbox.  If you hit enter on the textbox, the value is posted to the previously defined Action on the Controller.  If you hit cancel, the display is toggled back.

    I’d not recommend copy and pasting this exact example into a production system, but hopefully it’ll guide you through a simple scenario.  You can use a similar technique to add all sorts of little Ajax tricks (auto-suggest, lookups, dynamic menus) to your ASP.net MVC site using jQuery and Json (both of which are included in the core asp.net MVC framework).

    Download the example solution here

    Creating a WCF Proxy to talk to Magento

    October 5th, 2009

    I got a message from a friend who was struggling to do an integration piece with the Magento eCommerce Platform using the SOAP endpoint available at http://yourserver.co.uk/api/v2_soap?wsdl.

    He brought an interesting problem to me, namely that the WCF svcutil executable (and built in Visual Studio 2008) was failing to generate any proxy code when supplied with a seemingly valid wsdl.

    I did a quick test and managed to instantly reproduce the error.

    Weirder still, when using the “old” .Net 2.0 add web reference method rather than the .Net 3.0+ “Add Service Reference”, the framework managed to create a non-WCF reference just fine.

    Dropping down to the command line I saw some unusual messages being displayed by svcutil.exe:

    c:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin>SvcUtil.exe http://yourserver.co.uk/api/v2_soap?wsdl
    Attempting to download metadata from ‘http://yourserver.co.uk/api/v2_soap?wsdl’ using WS-Metadata Exchange or DISCO.

    (Lots of error messages here…)

    Error: Cannot import wsdl:portType
    Detail: An exception was thrown while running a WSDL import extension: System.Se
    rviceModel.Description.XmlSerializerMessageContractImporter
    Error: The ‘ ‘ character, hexadecimal value 0×20, cannot be included in a name.
    Parameter name: name
    XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:Magento']/wsdl:p
    ortType[@name='Mage_Api_Model_Server_V2_HandlerPortType']

    Error: Cannot import wsdl:binding
    Detail: There was an error importing a wsdl:portType that the wsdl:binding is de
    pendent on.
    XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='urn:Magento']/wsdl:
    portType[@name='Mage_Api_Model_Server_V2_HandlerPortType']
    XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:Magento']/wsdl:b
    inding[@name='Mage_Api_Model_Server_V2_HandlerBinding']

    Error: Cannot import wsdl:port
    Detail: There was an error importing a wsdl:binding that the wsdl:port is depend
    ent on.
    XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='urn:Magento']/wsdl:b
    inding[@name='Mage_Api_Model_Server_V2_HandlerBinding']
    XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:Magento']/wsdl:s
    ervice[@name='MagentoService']/wsdl:port[@name='Mage_Api_Model_Server_V2_Handler
    Port']

    Generating files…
    Warning: No code was generated.
    If you were trying to generate a client, this could be because the metadata docu
    ments did not contain any valid contracts or services
    or because all contracts/services were discovered to exist in /reference assembl
    ies. Verify that you passed all the metadata documents to the tool.

    Warning: If you would like to generate data contracts from schemas make sure to
    use the /dataContractOnly option.

    c:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin>

    So I did a little digging through the WSDL and found an undocumented bug in Magneto’s schema.

    First I saved a local copy of the WSDL and used visual studio to reformat the document into some sort of readable state, then I had to make a few corrections to the WSDL to allow SvcUtil to correctly parse the malformed document.

    Change 1:  Replace a badly encoded apostrophe – I removed the “’s” from the following operation definition…

    <operation name="customerGroupList">
    <documentation>Retrieve customer’s groups</documentation>
    <input message="typens:customerGroupListRequest"/>
    <output message="typens:customerGroupListResponse"/>
    </operation>

    Change 2: Replace a trailing space in an operation name

    <message name="catalogProductGetSpecialPriceRequest">
      <part name="sessionId" type="xsd:string"></part>
      <part name="product" type="xsd:string"></part>
      <part name="storeView " type="xsd:string"></part>
    </message>

    If you look carefully at the above message definition, you’ll notice that name=”storeView “ contains a space, making the wsdl invalid.  Remove the space so it reads “storeView”.

    With these two errors corrected, SvcUtil had no problem generating an appropriate WCF proxy from the corrected wsdl file.

    Magneto will hopefully fix this error in the WSDL, but until this time, it’s probably quite safe to follow these steps to generate your own proxy.

    To reproduce:

    • Go to http://yourserver.co.uk/api/v2_soap?wsdl and save the contents of your file to the local disk (c:\test\main.wsdl)
    • Open the file in visual studio, and reformat the document for readability (CTRL+K, CTRL+D).
    • Remove the apostrophe from the documentation tag for the customerGroupList operation.
    • Remove the space after the name=”storeView “ in the catalogProductGetSpecialPriceRequest message definition.
    • Open a command prompt and enter
    • c:\test>c:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe main.wsdl
    • SvcUtil will produce two files, Magento.cs (your WCF proxy) and output.config, your endpoint configuration.