Sunday, 28 October 2012

Getting started with Roslyn

I heard about Roslyn recently. No, not the Rosslyn from the Da Vinci Code, Microsoft Roslyn, the project which exposes the C#/VB compiler APIs allowing all kind of code analysis, generation and refactoring goodness, amongst other things. Interesting stuff. 

It took me a while to get going with Roslyn so thought I'd record some stuff I found useful. 

First things first

After downloading Roslyn read the project overview whitepaper. Finished? Read it again. The core concepts are pretty fundamental.

Installed with Roslyn is a handy getting started guide. 

Of course I didn't realise this at first *face palm* so I stumbled along blindly for a while. Arguably the most useful inclusion is the Syntax Debugger Visualizer. With this you can explore syntax trees by clicking directly on the code which jumps to the appropriate section of the syntax tree. To view the visualizer click on the magnifying class when debugging a syntax tree or node variable. Here's more information on the Syntax Debugger Visualizer.
Also included in the getting started guide is more documentation and a lot of example code. It's worth taking time to look through both of these. I wanted to write a quick fix, so the make const quick fix sample was particularly useful, as were unit test and tree transformation samples.

Creating code programmatically

The Syntax object can be used to create nodes and tokens. E.g.

Generally I've found it easier to generate statements/syntax trees/whatever from code strings. There are a whole bunch of ParseXyz methods.

Finding stuff in the syntax tree

One way to find nodes/tokens/trivia in a syntax tree is simply to use the Syntax Debugger Visualizer to understand the structure then write your query based on that information. LINQ is your friend. As well as DescendantNodes also look at methods such as Ancestors(), DescendantNodesAndTokens() and DescendantTrivia().

Finding a variable type

The semantic model can be obtained by calling GetSemanticModel from a Compilation or IDocument object. Other ways may be available.

Altering code

There is a lot of ways to alter code. Bare in mind that all Roslyn objects are immutable. The methods I've used the most so far are things like ReplaceNode, RemoveNode, ReplaceToken, RemoveToken etc. In addition there are several With* methods. E.g. WithBlock, WithClassDeclaration. In Roslyn a "block" is exactly what you would expect. I.e. A section of code between two curly braces.

It's worth noting ReplaceNode is an extension method and will only be visible if Roslyn.Compilers and Roslyn.Compilers.CSharp are referenced.

Formatting code

When inserting new code into a syntax tree the formatting will be terrible. You can fix it manually by inserting the relevant trivia. Don't bother. Format() method for the win.

Enabling Roslyn in Visual Studio

One gotcha to look out for. If you write a Roslyn extension then install it, the extension will not work unless Roslyn is enabled. This had me scratching my head for some time. By default Roslyn is only enabled in the debug instance of VS fired up when you run a Roslyn project. To enable it add "/rootsuffix Roslyn" to your VS shortcut. How do you know Roslyn is enabled? Each code tab will include "[Roslyn]". Thanks to Stack Overflow for that tip.

Sunday, 14 October 2012

DDD North 2012

I had a cracking day at DDD North so thought I'd write up some of my thoughts on the talks I attended.

10 practices that made me the developer I am today

Garry Shutler presented this talk. It struck a chord with me, particularly his experience of leaving university without a bunch of fairly important skills. All the topics covered were relevant. For the most part they were familiar. If I were to draw up a list of ten practices I believed made a good developer it would share many of the same points so it's nice to know someone with more experience than yourself values similar practices (it gives me a warm fuzzy feeling). There were several topics covered which I don't do and they were food for thought. You can find a brief summary of the talk here.

Async C# 5.0 - patterns for real world use

This talk was basically an introduction to C# async, or magic as I like to call it. The code looks like regular linear code, but it's not. Liam Westley covered the basic keywords, some examples and some gotchas. Interesting stuff.

BDD - look ma! No Frameworks

Out of all the talks I attended this one caused my brain to hurt the most, in a good way. In the hour Gemma Cameron introduced us to Behaviour Driven Development (which I previously knew nothing about). If I understand correctly BDD is kind of a mix of TDD and DDD. One of the important aspects of BDD is communication. Talking to people, speaking in their language, finding out what they want, working out their motivation, all with aim of making software that people actually want. Another important aspect of BDD is how you test. As I understand it the idea is to write tests than can be read by a non techy. This means that firstly the tests should be readable, using words that will be understood outside of code land, and secondly the tests should be top down, meaning they should test a behaviour rather than a method of a class. Obviously there is more to BDD than these two points, but these are the main things I took from the talk. 

To be honest I didn't leave convinced. My impression of BDD is that it's a mish mash of other things. Communication is important, but it's by no means the only software development process to promote it. What about the testing aspect? To me it sounds like a automated acceptance testing which again isn't new. I feel there is benefit from this kind of testing but my preference would be alongside unit tests rather than instead of. Another problem I had was that I can't get my head round how I would apply this to a complex example. How would I write this kind of test in my code base at work? I have no idea. With difficulty I would imagine. 

One other topic, mentioned briefly, not specific to BDD is the self shunt pattern. Apparently this is a technique which can be used rather than mocking when unit testing. It's now on my reading list.

Javascript sucks and it doesn't matter

There was a large amount of stuff covered in this talk by Rob Ashton most of which I'll not use as I don't write a great deal of Javascript, but very interesting none the less. The most useful thing I took from the talk was that qUnit isn't great for writing unit tests that have a large amount of DOM interaction, something I've previously tried to do. A much nicer way of doing it is using a headless browser called zombie.js. Another one for the reading list. Here is a summary of the talk.

C# + Powershell = happy couple

Unfortunately I was half asleep at this point in the day. Getting up at six o'clock doesn't agree with me. Still it was intersting. Jimmy covered the basics of writing your own Powershell cmdlet in C#. Turns out it's fairly straight forward and potentially very useful. I say potentially because I can't think of any useful cmdlets to write. I will though, eventually.

Sunday, 7 October 2012

Book review - Mastering Mountain Bike Skills

If Mountain Biking The Manual was the starter, Mastering Mountain Bike Skills would be the main course. I re-read this book recently and I think it's fair to say I'd completely forgotten how good it was. As with The Manual, it's jam packed full of incredibly useful information that is very well explained. But importantly, it succeeds where The Manual fails. There are diagrams and photos of everything. Want to know the correct attack position? There's a photo of that. Not sure of the best line to take through a switchback. There's several diagrams for that. Want to know which part of your bum rests on the saddle? There's a diagram for that! It's difficult to overstate how useful diagrams and photos are when trying to visualise an unfamiliar technique, and for me visualisation is one of the best ways to start the learning process.

What topics are covered? As with the Manual all the basics are there. Attack position, braking, cornering, flow, jumps, drops, pumping, bike setup, the list goes on. Certainly everything I want to know is clearly explained with a bunch of diagrams/photos. I had several eureka moments when reading MMBS. "Oh right, so that's how you're supposed to do it!", "Ahhh so that's why pumping makes you faster!" If you had been in a room with me you would have seen a lightbulb appear above my head, on more than one occasion. In addition, at the end of each chapter is a troubleshooting section. Common problems and the solutions. Really really useful stuff.

There's something else I like about MMBS. Don't be fooled into thinking it's just a dry text book, it has personality, by the bucket load. Several pages made me smile. Here are a few of my favourite quotes:

On exploring the limits of your cockpit:

"Push back until your arms straighten or your bum gets the knobby treatment."

On braking during a corner:

"If a unicorn suddenly appears if your corner, first straighten out; then brake hard. If you've been practicing your braking skills, you'll be under control before you strike the magical beast."

On doing a wheelie:

"Explosively push your torso upward and backward with your arms. At the same time, uncork a powerful pedal stroke. If you are nice to puppies your front wheel will pop up."

To summarise; great explanations, lots of diagrams, buy it now. 

Saturday, 22 September 2012

Book review - Mountain Biking The Manual

Mountain Biking The Manual does what it says on the tin. It is absolutely packed with information. In 255 pages it covers subjects like a brief history of mountain biking, equipment, training, psychology, crashing, recovery and competition. And that's just to start with. The meat for me is the mountain biking technique. It's all in there, from the basics including body position, flat corners, berms, rocks, roots, pumping and flow right up to getting air, manuals, bunny hops, flips and tail whips. 

What I like about his book is that it covers so many topics but it never feels like a chore to read because each section is quite short. You can read it cover to cover, or dip in and out. Importantly it's very well written. The author, Chris Ball, is very good at breaking down the essentials of each technique so they can be understood and be applied on the trail. I learnt so much from this book on the first read, and have come back to it again and again when I need a refresher on something. 

I do have one complaint. However good your prose is, sometimes what you're trying to explain is much clearer if you use a diagram. Mountain Biking The Manual would definitely benefit from some diagrams. 

If you've just started mountain biking, buy this book now, it'll save you at least two face plants (not guaranteed). Even if you've been biking for a while, provided you're not an expert, it's worth having on your bookshelf.


As much a I like this book Mastering Mountain Bike Skills is better. If I could only choose one, it would be Mastering Mountain Bike Skills. Sorry Chris!

Wednesday, 29 August 2012

How much sleep do I need? An unscientific study

I've been noticing more and more lately that I often feel tired through the day, sometimes even as early as midday. In addition to feeling tired I sometimes struggle to maintain concentration for small periods of time which can be seriously demotivating. It's the cerebral equivalent of wading through deep water (if that makes sense). Everything takes a lot of effort and is generally very slow. I've not measured this (I have no way of measuring it) but I wouldn't be surprised if my bug count increased significantly when I feel like this. Sorry colleagues. Not everything is doom and gloom though. At other times, admitted less frequently, I feel sharp as a tack, full of motivation and as awake as a very awake person. Lately I've been wondering if these lapses can be attributed to sleep. 

How much sleep do you need?

All the information I can find on this suggests that the amount of sleep required varies by age and by person. Typically kids will need more sleep. For adults it's entirely subjective. Jimmy may be able to function on six hours sleep a night whereas his mate Ted will need nine hours. On average the figures I've seen suggest that between seven and a half and nine hours per night is fairly normal.

Sleep deprivation

Doing a bit of reading there are some pretty serious problems associated with sleep deprivation. Increased difficulty concentrating, making decisions and carrying out mental tasks; decreased motivation, decreased reaction times and creativity, to name but a few. I'm not saying I suffer from this kind of thing, not by a long shot. However one article I read suggested you could be sleep deprived even if you feel sluggish in the afternoon or feel sleepy in warm rooms. That's me all over. I'm practically a slug most afternoons. 

Sleep debt

Sleep debt is the accumulated amount of extra time you need to sleep to make up for missed sleep. This article suggests that if you feel drowsy after a large meal or in a warm room then you have sleep debt. As you can imagine having sleep debt isn't an unusual occurrence. Who hasn't missed a few hours sleep here and there? Clearly the effects of sleep debt won't be as pronounced as sleep deprivation but it can still lead to some reduction in productivity, excessive drowsiness and apathy amongst other things. 

So how to you reduce your sleep debt? The simple answer is sleep more, however some would suggest that sleep debt isn't as easy to recover from as you might expect. You can't just miss five hours and make up five hours the next night, it must be done slowly in one to two hour increments.

What can I do about my drowsiness?

I have never worried about the amount of sleep I get. If I'm tired I'll go to bed early. If I feel particularly awake or I'm working on something I'm more likely to stay up later. This means I don't get a regular amount of sleep and I've no idea how many hours of sleep I am actually getting. So, I decided to start recording what time I go to bed, what time I get up and how I feel throughout the day. In addition I thought it would be interesting to vary the amount of sleep I get which would hopefully give some indication of how much sleep I actually need and also help work out if my tiredness through the day was due to lack of sleep. 

I'm hoping it'll be as easy as six hours sleep = zombie, seven and a half hours sleep = Super Alert Man.

Not scientific you say?

I'm ignoring some pretty important factors which can affect how awake you feel, purely because they are difficult to measure. Primarily there's not necessarily any correlation between the number of hours you spend in bed and the number of hours sleep you get. Then add to that things like stress, busyness, alcohol, noise (say snoring or road works) and the possibility that it can take up to a week to adjust to a new sleeping pattern then I've potentially got some pretty unreliable results. Oh well, I did say it wasn't scientific. You want science? Go somewhere else! I'm really just interested in getting a general idea of how I feel after different amounts of sleep.


I've picked up a few tips to improve the quality of sleep, some of which are pretty obvious, others not quite so much. Here are some of the most useful ones:
  • Go to bed and get up at regular times
  • Take naps if tired but not too close to your usual bed time otherwise it might interfere will you normal sleep pattern
  • Wind down before going to sleep. E.g. Read a book or take a bath. Coding till one in the morning then trying to go straight to sleep is a recipe for disaster
  • Cut down on caffeine, particularly in the late afternoon/evening
  • Staying up late to "fit more in" is counter intuitive. You may get more done in the short term, but in the long term you'll suffer


In an effort to quantify how sleepy I was feeling through the day I gave myself a rating from one to five every day for about two months. One being the most alertest thing since alertness was invented and five being practically narcoleptic. I also recorded other things which I thought might be pertinent such as staying up late for whatever reason or getting up early. 

My results seem to indicate, I would say with about 61% confidence (50% of all statistics are made up on the spot), that about eight hours to eight and a half hours sleep is ideal for me. I can survive on less sleep but after two or more nights with less than eight hours sleep there was often a noticeable increase in my tiredness.

Fairly obviously on days when there had been more activity and usual, travelling for instance, I was more tired. Also on days when I didn't wind down before bed it took me noticeably longer to get to sleep and I generally felt worse the following day.

You could say that that my conclusions are pretty obvious, and you would have a fair point. But still it was an interesting exercise and I learned some useful stuff. Time for a well deserved nap I think.

Sunday, 22 July 2012

Simple database driven feature toggles for ASP.NET MVC

A bit like a broken record I keep mentioning that we use continuous integration at work. So blah blah blah, we need feature toggles. My previous experience has involved using a very simple feature toggling mechanism and looking into a few other open source feature toggling tools. For this blog I'm going to ramble on about another simple idea that I implemented using toggles stored in a database. This solution is specific to ASP.NET MVC due to the way the toggles are populated but I imagine similar mechanisms exist in other frameworks. Although I wrote most of the code, I can't take credit for the idea. That goes to a couple of my colleagues (see their blogs here and here). They each claim it was their idea. I'll let them fight it out. 

How it works

The feature toggles are stored in a static class. What? A static class?!? I don't like it! Bear with me. I thought the same when I first heard the idea but I was convinced otherwise. This static class is used purely to store the values of the toggles, that's it. This comes with a few significant benefits. Primarily it can be defined in a common project (our solution has a lot of projects) and then be used anywhere, view, service, or controller. In addition it doesn't need to be passed around via constructor injection so it doesn't pollute a huge number of classes in the code base. Just to highlight that point, there is absolutely zero IoC setup required to use toggles once the initial implementation is done. But wait, there's more good stuff. What about unit tests? Will adding feature toggles break them? Nope. Because the static class is just a container the toggles will default to being off. If you want to create unit tests which test the toggle being on, just set the toggle to true in the unit test. Easy.

So how is it populated? It's very simple. A new Action Filter is applied to all controllers. For our code this is very easy because all controllers inherit from a base class. On every page load this Action Filter retrieves the toggle values from the database, if they have changed. 

Why get toggles from the database? There are a few good reasons. Firstly it's very easy to change their value at run time. Secondly it's very easy to make them available to every project in a solution. This is in contrast to a previous mechanism I tried whereby the toggles were stored in appSettings in a web.config file which required the adding of a file attribute to the appSettings element in each project where the toggles were required. Another benefit of using database toggles is that the implementation can easily be extended. It would be fairly easy to add new features like toggles controlled by date or toggle state. E.g. Always on, always off.

Are there any disadvantages to this approach? Currently because the toggles are populated by an Action Filter they can only be used in MVC applications, not windows services or console applications etc. 

The code

FeatureToggles static class

Each feature toggle is simply a public static boolean with a private setter. Why a private setter? It indicates to others using that class that they shouldn't change the value of an individual toggle variable. However there does need to be a mechanism for setting toggle values for unit testing purposes, which is done by SetToggleValue. Reflection is used to prevent the need for any extra code being written when a toggle is added.

SetFeatureToggles is used to populate all the toggles using reflection. Again reflection means no code changes are required when adding or removing toggle variables. The toggle name passed in must match the name of the toggle variable. Note, the FeatureToggle classes passed into the method simply contain two properties, string Name and bool IsActive.

GetActiveFeatureTogglesAsStringForBodyTag returns a string containing a space separated list of toggle variable names prefixed with "FT_" which is outputted in the class attribute of the body tag in each page. This allows CSS rules to be defined for when the toggle is on.

HasBeenInitalised is required to ensure the toggle values are retrieved from the database the first time the application is run. This is a quirk of our implementation because the cache isn't necessarily invalidated when the application is restarted.

Action Filter

The job of this Action Filter is very straight forward. If the toggles have changed retrieve the values from the database and repopulate the static toggle variables. This avoids reloading the toggles on every page load. I'm not showing the implementation details of FeatureToggleService because it's very specific to our application. There's nothing special going on to be honest. GetAll() simply returns a list of FeatureToggle classes either from the cache, if populated, or the database. The FeatureToggle class has two properties, string Name and bool IsActive. HaveValuesChanged() unsurprisingly returns a bool indicating whether the toggle values have changed.

How to add a toggle

To start using a feature toggle only one step is required. Add a public static boolean property to FeatureToggles class.

Obviously the toggle will always be false until you also add the toggle to the database. This is done using a simple admin tool which can add, remove or flip toggles. Whenever one of these actions is taken the cache is cleared which will cause the static toggle values to be refreshed.

How to use a toggle

In code

In views

Programmatically hide or show a feature:

Or use the outputted CSS class:


  • Incredibly easy to add a new toggle
  • Incredibly easy to use a toggle in any layer of the application
  • Easy to extend the implementation. E.g. Add date after which toggle is active
  • Existing unit tests are not broken 
  • Toggles can be flipped easily at run time with no need to manually edit a config file
  • No IoC set up required
  • Toggles can incorporate CSS

  • Only works in MVC projects
  • Some people won't like the static class implementation

Wednesday, 18 July 2012

A brief look at some feature toggle tools

When using continuous integration branching is considered a no no. This being the case you need feature toggles. The concept is quite simple, but how do you actually use them in code? I've come across this tricky problem at work and with the help of some colleagues came up with a very simple approach. But what if you don't want to roll out your own? What's available? Here is a brief overview of three tools available based on a quick Google search. 


  • Custom feature states. E.g. Previewable will only be seen by users who meet certain criteria. Established means the feature toggle cannot be removed 
  • Custom feature availability functions. E.g. Make feature available on site load or presence of a cookie
  • Feature dependencies
  • Feature availability dates
  • Feature specific settings can be defined using JSON

  • Toggles defined in enum and web.config
  • Availability checking methods set up
  • Manifest set up. The manifest service is used to check the state of existing toggles. This service must be injected into any class where toggles are required

  • Large amount of control over when and how to flip toggles
  • Available via NuGet

  • More configuration required that other feature toggling tools I looked at
  • No view examples provided. I'm unsure how NFeature would be used to add a toggle to a view
  • Potentially tricky to implement. This is probably just my fault, but I found it difficult to see how NFeature could be easily integrated with our existing code base
  • Manifest service must be injected into any class where toggles are required. On a big project this could affect a large number of classes


  • Custom feature toggle types including always on, always off, enabled and after date
  • Supports XAML
  • Toggles can be loaded from the database
  • WPF and Windows phone 7 support
  • Custom feature toggle implementations can be created by implementing IFeatureToggle

  • Toggles defined in appSettings
  • Each toggle must also be created as a new class which extends an existing feature toggle class. E.g. EnabledOnDatesFeatureToggle

  • Supports multiple platforms
  • Multiple toggle types
  • No service class required so no IoC set up required
  • Incredibly simple to set up and use 
  • Toggle type and provider are extensible
  • Available on NuGet

  • You have to create a class for each toggle
  • Toggles can't be used statically and must be instantiated as far as I could tell. This isn't a major issue to be fair, I'm just not a fan
  • Difficult to use across large solution. E.g. I would like to be able to define my toggles in a common project and use them in several web projects
  • Breaks existing unit tests. I'm unsure how to mock toggles when using FeatureToggle


  • Can check features statically or with instance
  • Fluent interface
  • Multi tenancy support
  • Custom behaviours (to be honest after reading the documentation I was unsure what custom behaviours were)

  • Toggles defined in custom configSection
  • Create a class which implements IFeature

  • Can check features statically or with instance
  • Fluent interface looks very flexible and powerful
  • Multi tenancy support

  • Personally, I found the documentation quite confusing. After reading the readme I still had a lot of unanswered questions about how to use the toggles and wasn't sure about how to configure FeatureSwitcher in my own projects

Monday, 28 May 2012

Software development is difficult

Sometimes I find software development a little depressing. It gets me down, so I thought I'd have a bit of a rant about some of the reasons why.

You're never right and nothing is certain

You're doing it wrong. You're never right. Ever. There's no such thing. Just accept it. Everyone has a different take on what is good and bad practice. Everyone has their own ideas on what works and what doesn't. You will find people who agree with you, but you'll find just as many people who don't. There is no black and white, it's all one gigantic grey area. To make matters worse, I have a computer "science" degree but many people will tell you that software development isn't really a science. Much of what we do is based on very little evidence, a few success stories, the spouting of an enthusiastic evangelist or perhaps some misguided beliefs. All of this means that it's almost impossible to be sure that you're doing it "the right way". It does my head in.

How good am I?

How do you know if you're a good programmer? By what yardstick do you decide? Salary? Fame? What you build? Contribution to open source software? How much you blog? Your Stack Overflow reputation? How many books you've written? The size of your team? The super clever, better than everyone else's, framework you've written? How much public speaking you do? The number of followers you have on Twitter? The quality of your code? That's another debate of course. The number of visitors to your site? How much money you've made? 

Is it important? Probably not. Arguably the most important thing is that you enjoy what you do. Some would suggest that you can't be a good software development unless you enjoy it. I certainly believe that. But is that enough?


You can't know everything. You can't even know a little. The breadth of knowledge required for software development is immense, the total amount of things you can learn is ridiculous. But what should you learn? The skills required to do your job obviously. But how about the things you think would be useful, or the latest framework/tool that people are raving about, or maybe just something you're interested in. Don't forget staying up to date with all frameworks/libraries/techniques/tools that you're currently using. They're all being developed at 100mph. 

That's only technical knowledge of course. There are many other skills you need to be a good software developer. Requirements gathering, version control, motivation, writing, teaching, documentation, time management, prioritisation, learning (I consider it a skill), problem solving, testing, typing, to list but a few. My head is going to explode. 

It's not all bad

I'm probably complaining for no good reason. It's not like I have a hugely stressful, mundane or dangerous job. In fact I consider myself lucky to have a job that interests me and that I find challenging. In this industry, provided you have the right attitude and motivation, you never stop learning, growing and progressing. I'm rarely bored, and there's nothing worse than being bored. 

Tuesday, 15 May 2012

Writing my first iPhone app

Since I've just finished writing an iPhone app for the Teesside basketball league I thought it would be a good time to write about some of my experiences of iPhone development.

Update April 2015 - Unfortunately the Teesside basketball league is no more so I have shut down the website and removed the app from the App Store.

A lot to learn

Professionally I'm a .NET developer, so my main language is C# and the IDE I use the most is Visual Studio. Obviously this is on a Windows machine. So from the outset I had a lot to learn. How to use a Mac for starters, then on to Xcode, Objective-C and the iPhone frameworks. It was more than a little bit daunting. 


I've spent a significant amount of time using other very good IDEs such as Eclipse and Visual Studio so Xcode had a lot to live up to. I felt it held up pretty well. Code completion, code analysis, version control integration, iPhone/iPad simulator, all good stuff. Refreshingly it's also very quick. Admittedly the project I'm typically loading isn't very big but Xcode typically loads in a matter of seconds rather than the minutes I wait for Visual Studio to start. 

When downloading Xcode you don't just get the IDE, it's a suite of tools. Interface builder used to be a separate application but as of version 4 it's integrated into Xcode. I like it. It's not quite as simple as dragging and dropping UI elements on to a view as I'd hoped but it's arguably easier than having to understand HTML and CSS. Out of the box you also get various 'instruments' to help analyse your application. The leaks instrument is the only one I've used so far, and it's very useful. Having something like this out of the box for a .NET web application would be great.

It's not all good though. Perhaps I'm a little spoilt by Resharper but the refactoring and code generation features in Xcode are a little lacking. It's hardly a showstopper though. Another negative is that it's quite error prone. I've experienced numerous crashes. So much so I've got into the habit of using the save all shortcut every minute or so. The handling of folders frustrated me a little as well. I like my projects organised in a nice clean folder structure where every file has it's place. As far as I can tell there's no way to create folders within Xcode. You can only create 'groups' which look like folders but only exist within the IDE. The only solution that I could find was to create folders manually and drag them into Xcode. 


Sweet Jesus, its a sea of square brackets! That was my first thought when seeing some Objective-C, which is entirely justified because there are more square brackets that you can shake a stick at. It's fair to say that I found the language quite difficult to get into. There's the aforementioned square brackets confusing my brain, pointers, memory management, strange method names and header files. But, you know what, after a bit of practice it's really not that difficult. The square brackets are used to call methods, or rather send messages, to a class. My fear of pointers was entirely unjustified because in Objective-C is a non issue (in my experience so far anyway). All you need to remember is that object types must be declared as pointers. That's it, there's no pointers to pointers or dereferencing. As of iOS 5 with the introduction of ARC the memory management isn't particularly tricky either. How about the strange method names? Well, they actually make quite a lot of sense when you think about it. So all in all, aside from some syntactical strangeness it's not a bad language to work with.

Was it worth the time?

Someone asked my recently why I was developing a native app rather than a HTML 5 app. Good question. I'm not convinced it's a particularly good reason but web development is my job and I'm pretty sick of trying to create web sites that work in multiple browsers. So the idea of writing a mobile web app that will function reasonably on approximately a gazillion devices, in my own time, makes me feel a little sick. All I want to do is write some code. Partly to try out new techniques and ideas. Partly to learn something new. And partly because I believe building an application, particularly on an unfamiliar platform, is a great way to learn. For this reasons writing a native app was a no brainer for me. 


To learn Xcode and iPhone development I highly recommend Paul Hegarty's Stanford lectures. They really were incredibly useful. In terms of books, I can't recommend any in particular. I bought a couple, one on Objective-C and one on iPhone development. But, due to a combination of a huge amount of free online documentation and the books only covering a small subset of what can be done on the iPhone, I've hardly used either. 

Other than the Stanford lectures a few other resources I found useful were:

Monday, 7 May 2012

Using variables with Seleium IDE

Testing part of the application I work on involves filling out a fairly long registration form. I've been using Selenium IDE to make my life easier but I still have to change a few fields before I can submit the form. I.e. Email and username, because they must be unique. I normally add an ever increasing number to the end of the fields which doesn't take long but it annoys me that I still have manual steps. So I wondered if it is possible to use variables in the test script. Turns out it is. 

The 'store' command saves a variable. Confusingly, for me at least, the 'target' is the variable value and the 'value' is the name of the variable. Once the variable is declared it can be used to populate other fields using the syntax ${variableName}.

The image below shows an example. I've created a variable called testNumber which is used to populate the Email, EmailConfirm and Username fields with unique values.


Friday, 23 March 2012

Bad times with Entity Framework and WCF

I recently wanted to make some data from a .NET MVC website I built some time ago available externally via a web service. After a little research I decided WCF was the way to go and set about creating a test service class that would return some data which was accessed using the Entity Framework (unfortunately my ORM of choice at the time). It was more difficult than I expected. 


My project uses .NET MVC 3, Entity Framework and Ninject amongst other things. The first job was to make sure I could inject the required service classes into my WCF service. Fortunately this was a piece of cake thanks to this excellent blog post. I'm not going to go into the WCF configuration because, to be honest, my knowledge of WCF is rubbish.

Problems sighted over the starboard bow

Setting aside my total lack of experience with WCF the first issue I encountered was that some of my queries worked perfectly while others failed with the mysterious error message "The underlying connection was closed: The connection was closed unexpectedly". After much Googling and many dead ends I eventually stumbled upon a Stack Overflow post which suggested checking the event viewer. Low and behold I find a considerably more specific error message:

System.ServiceModel.CommunicationException: There was an error while trying to serialize parameter The InnerException message was 'Type 'System.Data.Entity.DynamicProxies.SomeType_795A7B31EA6BCD0D7B9CFE73379DD55F309C0BEE00A295CAF276B939BB5BF4E6' with data contract name 'SomeType_795A7B31EA6BCD0D7B9CFE73379DD55F309C0BEE00A295CAF276B939BB5BF4E6:' is not expected. 

Further Googling of this error revealed the problem. Lazy loading. Entity Framework supports lazy loading by default, provided your navigation properties are virtual. Unfortunately WCF does not support Entity Frameworks lazy loading. What a pain in the ass. It turns out that to disable lazy loading the ProxyCreationEnabled property of DbContext must be set to false, which leads to further difficulties. With lazy loading disabled any required navigation properties must be eagerly loaded, which unfortunately isn't possible by default. The only way that I am aware of to do this using Entity Framework is by calling the Include method explicitly for any navigation properties you want to return.

A solution

I found a solution, albeit one that was very specific to my needs. Firstly I created two separate database context classes that extended DbContext. One to be used for the web service, which set ProxyCreationEnabled to false and one for the WCF web service with ProxyCreationEnabled set to true. Fortunately using Ninject this was pretty straight forward. Secondly was the eager loading problem. I decided it would be almost impossible to specify exactly which properties needed to be eagerly loaded for each query, so the only other option I could think of was to eagerly load all the navigation properties. There are problems with this solution. It will likely return more data than is required and I'm only aware of how to load one level of navigation properties, which could also cause problems. By this I mean if entity A has navigation properties B and C, when returning a list of As, I can eagerly load properties B and C. If B and C have their own navigation properties they will not be loaded. To achieve this kind of eager loading I created a method which used reflection to get all the public properties from an entity and return a list of those which were navigation properties (in my case navigation properties could be identified by a common base class). Each of the navigation properties in the list could then be passed into the Include method to tell Entity Framework to eagerly load each property. After making these changes all my queries worked perfectly. Huzzah! 
As pleased as I was to get this working, to be honest I'm still not one hundred percent convinced that this solution will hold up. Unfortunately I can't think of a better one. Oh well, time will tell I suppose.

Sunday, 19 February 2012

Simple feature toggles in .NET 4

The problem

Where I currently work we use continuous integration. When software is in development this doesn't cause any problems. Just commit, it doesn't matter if you break something or add a new feature. When your software is live, it's a whole different story, everything becomes a bit scarier. Assuming you release fairly regularly, say once a day, new features and other changes must be hidden from the user until they are ready. This is where feature toggles come in. The theory behind feature toggles is very simple, but implementing them in .NET was causing me a headache. I struggled to find any useful information on a practical, tried and tested solution. 

This blog is my attempt to explain the solution me and a couple of colleagues came up with in a fairly short space of time. I'm perfectly happy to say it's not perfect or super elegant, but it works, and it's simple. For a more comprehesive feature toggle solution it could be worth looking at NFeature. It turned up while I was looking for examples of feature toggling in .NET and while I haven't tried it, it looks like a nice solution. At the time I wasn't happy to introduce yet another dependency on a 3rd party piece of software so opted not to use it.


Any feature toggling solution we used needed satify a number of requirements. Most importantly the toggles must be accessible in any project within the parent .NET solution and must be configurable for each environment. E.g. On in your testing environment, off in live. In addition I wanted to make it as easy as possible to remove the toggles. That being the case I wanted each toggle to be defined in a single location that when deleted would cause build failures until all references to the toggle were removed. Finally I wanted an implementation where toggles could be used in the view, controller and model and would not break any unit tests.


The first step is to create a new web.config file to hold the toggles. Why a seperate file? This way web.configs from each project where the toggles are to be used can refer to this one file. I called my file featureToggles.config. This file can be used to store simple boolean appSettings which define whether the toggle is on or off.

  <add key="MyFeatureToggle" value="true" />

When the featureToggle.config file is created, if you're using .NET 4, config transforms will automatically be created for you. They are required for this particular solution. If you're using .NET 3.5 or below you'll have to find another way to handle the transforms, sorry. Add a transform value for each environment. For instance my live transform might look like this:

<appSettings xmlns:xdt="">
 <add key="MyFeatureToggle" value="false" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>

How are the new appSettings loaded when they aren't included in the web.config file? One of my colleagues helped with that. The file attribute of the appSettings element allows you to specify a file which contains extra appSettings. So for whichever projects in your solution need to use the feature toggle simply add a reference to it in the appSettings element. For example our solution contains two web projects both of which require use of the feature toggles, so their appSettings elements would look something like this:

<appSettings file="featureToggles.config">

<appSettings file="../Web/featureToggles.config">

It's worth noting that if you are automating your builds using something like MSBuild you will need to add an extra step to apply the appropriate transform to the new featureToggles.config. I'm not going to go into the details here but if you want more information this post should help.

The next step is to get the appSettings values out of the config file. To do this I created a static class:

public static class FeatureToggles
  public static bool MultipleCards()
     return ConfigurationManager.AppSettings["MyFeatureToggle"] != null 
 && ConfigurationManager.AppSettings["MyFeatureToggle"].ToLower() == "true";

This the single place in code where the feature toggle is defined. If you want to remove the feature toggle simply delete the appropriate method from the static class and clean up the build errors. Why a static class? Because it can be used very easily in areas you aren't worried about unit testing. E.g. Views. What about using feature toggles in your model where introducing a static class would break unit tests? For that purpose I created a wrapper round the static class:

public class FeatureToggleService : IFeatureToggleService
  public bool MyFeatureToggle()
    return FeatureToggles.MyFeatureToggle();

The FeatureToggleService class can be injected into any model class. The return value can be mocked so you can unit test your code with the toggle both on and off. Now it's simply a case of adding feature toggle code when you need hide a feature. For example:

<% if(FeatureToggles.MyFeatureToggle()) { %>
   <%--Link to some awesome new feature--%>
<% } %>

   // New code
   // Old code

In summary

  • It's simple
  • Toggles can be loaded into multiple projects from one transformed file
  • Existing unit tests are not broken and feature toggle service can be mocked so features can be tested while switched on

  • Adding a new toggle involves more steps that I would like
  • As far as I'm aware the appSettings file attribute can only contain one value, so if it's used to load feature toggles it can't be used for anything else
  • In a big project the featureToggleService would potentially need to be injected into a large number of classes which I don't like. Do you inject it into all classes, or just the ones you need and then remove it when you're done? Rock. Hard place
  • Toggles must be flipped by manually editing a file