On Showing Up

So I just listened to episode 1000 of .NET Rocks. I’ve been listening to this podcast for many years, through biting snow-covered walks in England to the cosseted comfort of an air-conditioned car in Australia when it’s 43C outside.

1000 episodes is an amazing achievement and it got me thinking.

There’s a lot of popular talk at the minute on advancing your career, becoming an outlier, and building a personal brand. The thing is there’s one underlying trait that successful people seem to possess: showing up.

"if the rope breaks nine times, we must splice it together a tenth time"

Fear is a big motivator, for the longest time (like so many other developers I’ve met) fear was present; fear of not knowing everything, fear of looking stupid, fear of not being able to find another job. For the most part I’ve let this fear fly away and one of the ways I think I’ve done this through persistence, thorough showing up.

I think if you take an approach of continuous personal improvement you will. Don’t be afraid to put yourself out into the world, whether this be blogs, user groups, Twitter, or lunchtime “brown bag” sessions presenting to your colleagues where you work.

There are always going to be people who criticize, but there are also always going to be people who say “thanks”.

There’s a Tibetan saying that “if the rope breaks nine times, we must splice it together a tenth time” – this is showing up, even when you feel you have nothing to contribute, are fearful of criticism, or feel like you can’t get anywhere – there are always choices, and showing up is one of them.

As Jim Carey says: “you can fail at what you don’t want, so you might as well take a chance on doing what you love”.

SHARE:

Custom FeatureToggle Implementations for Non-Continuous-Delivery Usages

My open source fetaure toggling library contains a number of prebuilt toggles for common things such as enabling a feature based on the date, or a configuration value.

It’s also easy to create custom toggles by implementing IFeatureToggle.

Up to now, FeatureToggle has mainly been an aid for continuous delivery; a “half done” feature can simply be configured off so it doesn’t appear in the UI.

I’m wondering if the following approach has merit, namely treating conditionally available features as a first class citizens. So this is not just using them for continuous delivery but to encapsulate actual features of the application.

The example below requires 3 NuGet packages:

  • FeatureToggle.Core
  • FeatureToggle.WPFExtensions
  • MVVMLight

So the feature in the application will restrict the availability of mature rated games to customers who are 18+.

First off the feature toggle:

using FeatureToggle.Core;

namespace CustomFeatureToggle
{
    class MatureTitleSelectionFeature : IFeatureToggle
    {       
        public MatureTitleSelectionFeature(Customer customer)
        {
            FeatureEnabled = customer.Age >= 18;
        }

        public bool FeatureEnabled { get; set; }
    }
}

Here the business logic is encapsulated in the feature toggle and can be tested.

Next the viewmodel:

class MainViewModel : ViewModelBase
{
    private Customer _selectedCustomer;
    private IFeatureToggle _matureTitlesFeature;
    private ObservableCollection<Customer> _customers;

    public MainViewModel()
    {
        Customers = new ObservableCollection<Customer>
                    {
                        new Customer {Name = "Sarah", Age = 32},
                        new Customer {Name = "Robert", Age = 17}
                    };

        SelectedCustomer = Customers[0];

        MatureTitlesFeature = new MatureTitleSelectionFeature(SelectedCustomer);
    }

    public ObservableCollection<Customer> Customers
    {
        get
        {
            return _customers;                 
        }
        set
        {
            _customers = value; 
            Set(() => Customers, ref _customers, value);                 
        }
    }

    public Customer SelectedCustomer
    {
        get
        {
            return _selectedCustomer;
        }
        set
        {
            _selectedCustomer = value;
            
            Set(() => SelectedCustomer, ref _selectedCustomer, value);

            MatureTitlesFeature = new MatureTitleSelectionFeature(SelectedCustomer);
        }
    }

    public IFeatureToggle MatureTitlesFeature
    {
        get
        {
            return _matureTitlesFeature;
        }
        set
        {
            _matureTitlesFeature = value;

            Set(() => MatureTitlesFeature, ref _matureTitlesFeature, value);
        }
    }
}

Here, every time the selected customer changes, a new (immutable) toggle is created based on the customer’s details, i.e. Age.

The visibility in the UI of mature titles is simple data binding, using a visibility convertor from FeatureToggle.WPFExtensions.

<Window x:Class="CustomFeatureToggle.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:toggles="clr-namespace:FeatureToggle.Toggles;assembly=FeatureToggle.WpfExtensions"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <toggles:FeatureToggleToVisibilityConverter x:Key="ToggleVisConverter"></toggles:FeatureToggleToVisibilityConverter>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <ComboBox DisplayMemberPath="Name" 
                      ItemsSource="{Binding Customers, Mode=TwoWay}"
                      SelectedItem="{Binding SelectedCustomer}"></ComboBox>
            <TextBlock>All audience titles here</TextBlock>
            <TextBlock Visibility="{Binding MatureTitlesFeature, Converter={StaticResource ToggleVisConverter}, Mode=TwoWay}">Mature titles here</TextBlock>
        </StackPanel>
    </Grid>
</Window>

I’m wondering how this approach would scale out for larger apps.

screenshot showing mature visible

 

screenshot showing mature invisible

SHARE:

In Process Http Server for Integration Test Faking with Owin, Katana, and WebAPI

Sometimes when integration testing we need an HTTP endpoint. We can set one up in our solution (for example a Web Api project) and make sure it’s running before we execute our integration tests but it can be painful. Also consider when running on a build server, the web site will need to be provisioned, etc.

For isolated integration tests that require some HTTP endpoint we can create an HTTP endpoint from within our test code that doesn’t require a separate web project. This means that when tests run they have no external dependency in the sense of a “real” website being hosted somewhere – even if that somewhere is on the local dev machine. Another advantage of the approach outlined below is that because it’s all in-process it’s also faster than actually going through the network stack.

The System Under Test

We are going to test the following class that calls a service to change a string to uppercase:

using System;
using System.Net;

namespace ClassLibrary
{
    public class ToUpperServiceGateway
    {
        private readonly string _serviceEndpoint;

        public ToUpperServiceGateway(string serviceEndpoint)
        {
            _serviceEndpoint = serviceEndpoint;
        }

        public string MakeUppercase(string lowercase)
        {
            using (var wc = new WebClient())
            {
                return wc.DownloadString(_serviceEndpoint + "/" + lowercase);
            }
        }
    }
}

This code uses WebClient to call a web service. In the integration tests we want to spin up a website that will return a mock value for example.

Writing the Initial Test Code

So an initial test could look somethine like:

using Xunit;

namespace ClassLibrary.IntegrationTests
{
    public class UpperCaseTests
    {
        [Fact]
        public void ShouldGetUppercase()
        {
            var sut = new ToUpperServiceGateway("http://localhost:8084/api/toupper");

            var upper = sut.MakeUppercase("hello");

            Assert.Equal("HELLO", upper);            
        }
    }
}

If we run this we get “System.Net.WebException Unable to connect to the remote server” as we’d expect as there’s no website at the address.

Creating an In-Process Web API Endpoint

First off, in the test project install a few of NuGets: Microsoft.AspNet.WebApi.OwinSelfHost and Microsoft.Owin.Testing.

The first thing is to create a Web API controller, again in the test project, to fake out a real service:

using System.Web.Http;

namespace ClassLibrary.IntegrationTests
{
    public class ToUpperController : ApiController
    {
        public string Get(string lower)
        {            
            return "FAKE"; // fake value
        }
    }
}

Here, regardless of what’s passed in we’re just returning a fake value.

The next task is to create some configuration for Owin setting up our test controller:

using System.Web.Http;
using Owin;

namespace ClassLibrary.IntegrationTests
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{lower}");

            appBuilder.UseWebApi(config);
        }
    }
}

We can now refactor the test to create an in-memory Web API controller that can respond to our SUT:

using Microsoft.Owin.Hosting;
using Xunit;

namespace ClassLibrary.IntegrationTests
{
    public class UpperCaseTests
    {
        [Fact]
        public void ShouldGetUppercase()
        {
            using (WebApp.Start<Startup>("http://localhost:8084")) // base hosting address
            {
                var sut = new ToUpperServiceGateway("http://localhost:8084/api/toupper"); 
                // api/toupper matches our test controller / route

                var result = sut.MakeUppercase("hello");

                Assert.Equal("\"FAKE\"", result); // extra " because Web API response is not returning text/plain
            }
        }
    }
}

The test now passes, as our SUT connects to our in-memory test controller.

Note: For even simpler code that doesn’t require a test controller we could also use Nancy.

SHARE:

UX Observations: TED Xbox One App

This is the first in a new series of articles I want to start, noting user experience things I use/see and observing how they could potentially be improved. The articles in this series aren’t meant to be mean or critical, merely observational.

In this article we’ll be looking at the TED app for the Xbox One. (If you haven’t heard of TED before, they are videos of talks on technology, design, art, etc. some of which are deeply moving and inspiring).

Here’s a screenshot of the main menu.

image

Overall I love this app, clean and simple, it’s also nice that it’s themed white as a change from the other darkly themed Xbox apps such as the Video app.

The groupings on the main menu are nicely grouped and intuitive and follow the basic Xbox One UI patterns.

There are however a couple of specific user experience things I struggle with in this app.

What Video is Currently Selected?

The first is when selecting a video to watch. Take a look at the screenshot below: which video is currently selected? It’s hard to tell right?

image

The currently selected and not-selected items are too similar, we need the currently selected video to stand out, or to put it another way: there is not enough contrast between selected and unselected.

Below is a mock up of what simply adding the TED red brand color to the selected video border could look like:

image

Now we’ve increased the contrast/decreased the similarity between selected and unselected videos.

Alternatively we could make the background description color a pale red:

image

Again these are just lo-fi mock ups but they show some ways we could start to think about making the the currently selected video more easily distinguishable.

Playlist Play

Here is a screenshot of a playlist with one of the videos selected:

image

Hitting A on the controller unfortunately doesn’t just go and play the video. You have to go across to the “Play talk” button and then hit A. Every time, I make this mistake, and there’s a “cognitive pause” while I wonder why the video isn’t playing.

Moving across to the play button:

image

To fix this we could simply make pressing A on a selected video in the playlist (as in the first screenshot) a “shortcut” to playing the video by hitting A.

 

Feel free to comment if you have other observations or ideas for improvement or you think this is a good idea for a series.

SHARE:

C# Tips eBook 50% Complete

I just published a new version of my C# Tips eBook that marks the half way point of the project.

C# Tips is available in PDF, EPUB, and MOBI.

The book is scheduled for completion by the end of the year and has 521 readers at present. It is currently free, you may also pay whatever you think it’s worth.

You can download it now from Leanpub.

An abridged copy of the current table of contents is shown below.

  • Merging IEnumerable Sequences with LINQ
  • Auto-Generating Sequences of Integer Values
  • Improving Struct Equality Performance
  • Creating Generic Methods in Non-Generic Classes
  • Converting Chars to Doubles
  • Non Short Circuiting Conditional Operators Using C# Keywords for Variable Names
  • Three Part Conditional Numeric Format Strings
  • Customizing the Appearance of Debug Information in Visual Studio
  • Partial Types
  • The Null Coalescing Operator
  • Creating and Using Bit Flag Enums
  • The Continue Statement
  • Preprocessor Directives
  • Automatically Stepping Through Code
  • Exceptions in Static Constructors
  • Safe Conversion To and From DateTime Strings
  • Parsing Strings into Numbers with NumberStyles
  • Useful LINQ Set Operations
  • The Decorator Pattern
  • The Factory Pattern
  • NUnit
  • xUnit.net

SHARE:

Write Less Repetitive Boilerplate Code with Fody

My newest Pluralsight course on Fody was just released.

Fody is a tool that frees us up from having to write repetitive boilerplate code. For example we can automate IDisposable implementation or automatically add Equals(), GetHashCode() and equality operators.

Fody is not one tool, but a collection of individual “addins” around the core Fody, with the core GitHub members: Simon Cropp, Rafał Jasica, and Cameron MacFarland.

Automatically Implementing Equality

As an example of what’s possible with Fody, we can auto-implement equality.

So first off we install the Equals Fody addin via NuGet:

PM> Install-Package Equals.Fody

Now we can add the [Equals] attribute to indicate that we want to auto-implement equality.

We can opt-out specific properties so they won’t be considered during equality by applying the [IgnoreDuringEquals] attribute.

We can also provide custom equality logic by creating a method and decorating it with the [CustomEqualsInternal] attribute. So for example if either altitude is –1 then consider altitudes equal.

The following code shows these attributes in action:

[Equals]
public class Location
{
    [IgnoreDuringEquals] 
    public int Altitude { get; set; }
    
    public int Lat { get; set; }
    public int Long { get; set; }

    [CustomEqualsInternal]
    private bool CustomEqualsLogic(Location other)
    {
        // this method is evaluated if the other auto-equal properties are equal

        if (this.Altitude == other.Altitude)
        {
            return true;
        }

        if (this.Altitude == -1 || other.Altitude == -1)
        {
            return true;
        }

        return false;
    } 
}

For a list of available addins or to contribute (or even create your own addin) check out the GitHub project site.

To learn more about how Fody works, how to use some of the available addins, and how to create your own check out my Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

FeatureToggle 2.1 Released

Version 2.1 of my open source feature toggling library has just been released.

This new version contains two new toggles.

The RandomFeatureToggle as its name suggests will randomly enable/disable a feature.

The EnabledOnDaysOfWeekFeatureToggle allows configuration of a toggle to become enabled on specific weekdays.

 

Check out the documentation and release notes for more info.

SHARE:

Implementing Platform Specific Code in Universal Windows Apps with MVVMLight and Dependency Injection

In previous articles I’ve covered using MVVMLight in Universal Windows Apps and using C# partial classes and methods to implement different code on Windows Phone and Windows Store apps.

While partial classes/methods are a quick win to alter small amounts of code for each platform, overuse might become painful as the solution gets bigger. There are also limitations of partial methods such as they can only return void, they are implicitly private, cannot be virtual, etc.

If we’re using MVVMLight (or another framework or hand-rolled viewmodels) we can use dependency injection.

The viewmodel class is still shared between the two apps and doesn’t need to have partial methods which means we have more flexibility in the code we write.

As a dependency in the constructor, the viewmodel takes an instance of a class that implements an interface.

This interface-implementing class can then be two different classes, one in the phone project and one in the store project.

architecture diagram

So for example, in the shared project the following interface can be defined:

interface IGreetingService
{
    string GenerateGreeting();
}

Again in the shared project, the viewmodel is defined:

internal class MainViewModel : ViewModelBase
{
    private readonly IGreetingService _greetingService;
    private string _greeting;

    public MainViewModel(IGreetingService greetingService)
    {
        _greetingService = greetingService;

        SayHi = new RelayCommand(() => Greeting = _greetingService.GenerateGreeting());
    }

    public RelayCommand SayHi { get; set; }

    public string Greeting
    {
        get { return _greeting; }
        set { Set(() => Greeting, ref _greeting, value); }
    }
}

The key thing here is the constructor: it takes an IGreetingService.

When the SayHi command is executed, whichever instance of an IGreetingService was passed to the viewmodel, it’s GenerateGreeting() method will be called.

So in the store project the following class can be created:

public class WindowsStoreGreeter : IGreetingService
{
    public string GenerateGreeting()
    {
        return "Hello from Windows Store app!";
    }
}

And in the phone app:

public class WindowsPhoneGreeter : IGreetingService
{
    public string GenerateGreeting()
    {
        return "Hello from Windows Phone app!";
    }
}

It is in these specific implementations of the interface that the platform specific code is written.

So in the code-behind of the main window in the store app (for demonstration simplicity we’re not using a view model locator or DI library here):

public MainPage()
{
    this.InitializeComponent();

    this.DataContext = new MainViewModel(new WindowsStoreGreeter());
}

And in the phone app:

public MainPage()
{
    this.InitializeComponent();

    this.NavigationCacheMode = NavigationCacheMode.Required;

    this.DataContext = new MainViewModel(new WindowsPhoneGreeter());
}

In these code fragments a new MainViewModel is being created and supplied with a platform-specific IGreetingService implementation.

So in this way the shared MainViewModel class can still contain the majority of the code so we only have to write it once. But we still get the ability to write platform-specific code.

SHARE:

New RavenDB FeatureToggle

I just published new NuGet package for my open source .NET feature toggling library.

This package allows you to turn features on/off depending on what’s configured in a RavenDB database.

PM> Install-Package FeatureToggle.RavenDB

Extract from documentation:

BooleanRavenDBFeatureToggle

This toggle is not available on Windows Phone or Windows Store apps.

This toggle get it’s value from a RavenDB database.

Create a Toggle for the feature you want to control by inheriting from BooleanRavenDBFeatureToggle:

private class SaveToPdfFeatureToggle : BooleanRavenDBFeatureToggle{ }

Add RavenDB connection string to app/web config:

<connectionStrings>
    <add name="FeatureToggle.SaveToPdfFeatureToggle" connectionString="Url = http://localhost:8080;database=FeatureToggleInterationTests"/>    
</connectionStrings>

The database should contain a collection called “BooleanToggleSettings” with a document for every toggle that contains a property “Enabled”:

{
  "Enabled": true
}

Check out the test setup to see an example of writing some toggle config entries.

SHARE:

Using Shared Projects in Non-Universal App Projects

Using Visual Studio 2013 Update 2 and the Shared Project Manager Extension it’s possible to use shared projects in non Universal App projects.

This video shows a brief intro to shared projects in the context of Universal Apps and then how linked files work and how to refactor them to shared project.

As the documentation states: “Please note that this extension is preview technology and may have unforseen issues in the projects and solutions that it creates.”

Check out the video on YouTube or Vimeo.

SHARE: