Working As A Team

I read a post today entitled “Don’t Be The Smartest Guy In the Room”. The gist of the post was that the author had been in a team where a highly intelligent developer continually had the best ideas and was making everyone else on the team feel incapable and eroding their confidence.

He suggested that such smart people shouldn’t have the last word and should sometimes sit on their ideas and select inferior solutions from less capable developers so that they aren’t intimidated and made to feel worthless.

The author suggested listening to the opinions of others and speaking less. This part I agree with – smart people showing off and beating up others with their ideas is destructive behaviour. But to suggest good ideas should be withheld to make people feel better about themselves is just wrong. There are better ways to deal with this.

Most development teams comprise people with a mixture of skills and experience. I rarely find I am choosing between one solution or another as though they are discrete alternatives, but rather taking the best of a range of ideas.

I would certainly not want to sit on a great idea and select an inferior approach to appease someone. That would waste the value of the idea and also waste a learning opportunity. I would be doing a disservice to my team and client.

Instead, I try to present a problem and then solicit opinions through discussion and debate. Like any problem solver, often I’ll have a rough solution in mind, but rather than offer this outright, through a team conversation I can give less experienced members of the team the chance to put forward their own ideas and draw their own conclusions.

Sometimes, to kickstart a discussion, I’ll start with an overly simplified approach and ask people to find the problems.

By asking questions such as “Have you thought about X?” or “How could we handle Y?” you can guide an inclusive conversation where everyone has a chance to contribute.

I’m always careful to ask quieter team members open questions to see what they think about various aspects – especially aspects with which I know they are familiar – and I’ll always close by reminding people that they can always find me or email the team if they have any further thoughts.

Inevitably, what happens is that we reach a better solution through collaboration – one that sometimes looks very different from the idea we started with, and one that everyone feels a part of and motivated to deliver. Not only that, everyone gets to practice thinking through and articulating ideas, and that is a critical development skill.

Fix for Entity Framework 7 Migration Problem in Shawn Wildermuth’s ASP.NET 5 Pluralsight Sourse

Shawn Wildermuth posted a great ASP.NET 5 course up at Pluralsight here.

This post is a quick fix to a problem I ran into updating the database in the ASP.NET Identity Section. Note – I have been using the RC1-Final version of ASP.NET 5.

When you try to run the project so that it migrates the identity schema into the database, migration fails. The reason is that originally the database was created in the `Startup.cs` class with a call to:

db.Database.EnsureCreated()

This will prevent migrations from working because it doesn’t (by design) create the necessary system generated __EFMigrationsHistory table in the DB. If you change this line of code to:

db.Database.Migrate();

then everything works (at least for me) because with this code, when the database is first created the migrations table will be added. Note you will need to have created the database via this method in the first place – you can’t add/change this line of code after the DB is already created as the migrations table can’t be added retrospectively. If this is where you are, you have no easy option but to drop and recreate the DB. Also, you will need to manually add samhastings as the username in the two existing Trips in the DB, since the migration code doesn’t account for this.

Julie Lerman posted on this in a lot more detail here. Hope this helps!

Process this!

During a code review the other day, I came up against an old friend – in this case a method called “ProcessImage”. Set inside, of course a class called “ImageProcessor”. Method names should be *intention* revealing, not *implementation* revealing. If you think of a program as being like a sausage machine – meat in, sausages out – then don’t call the operative method “ProcessMeat” – call it “MakeSausages”. This reveals the purpose clearly and uses the language of the business.

Uploading an existing local git repo to a new github/bitbucket repo.

Note to self: Bitbucket and Github’s instructions for uploading an existing local repo have this instruction:

git remote add origin <address>

But something in my set-up (posh-git?) adds a default origin entry causing this to fail with:

fatal: remote origin already exists

To fix this use:

git remote set-url origin <address>

And then upload as normal with:

git push -u origin

Maybe this post will prevent me having to look this up every time I run into it! :)

Get a .gitignore file for Visual Studio fast with gitignore.io and Powershell

I often use the wonderful service at https://www.gitignore.io to grab a .gitignore file suitable for Visual Studio use. Unfortunately, the file has unix line endings – so I’ve boiled the operation down to a single line of Powershell that sorts that out in one go:

(curl https://www.gitignore.io/api/visualstudio).Content
  -split "`n" -join "`r`n" | set-content .gitignore

Use Powershell 4 to check file signatures/hashes

I wasted a couple of DVDs this morning trying to burn a corrupted download of SQL Server from MSDN. Finally the light dawned and I decided to check the file hash. MSDN subscriber downloads have the SHA1 hash on the download page. I didn’t have my usual checker installed yet on my new laptop, and in googling I discovered that Powershell 4 can now do this natively!

The command you need is Get-FileHash – MSDN uses SHA1 rather than the default SHA256 of this command so the following will do it:

Get-FileHash <filepath> -Algorithm SHA1

Rx Hammer-Nail Syndrome

This post is inspired by a recent post by Mike Taulty. I think you’ll agree it’s a great introductory post on how to use Rx.

I’m a big fan of Rx – it’s an awesome technology. But sometimes I am guilty of over-using it – the old adage that given a shiny Rx hammer every problem looks like a nail definitely applies!

If you haven’t already, please take a look at Mike’s post here to compare with what follows.

While the post was clearly intended as an instructive and motivational example, it did remind me of my own tendency to reach for Rx in similar production-code situations. I often need to remind myself that a non-Rx version can sometimes be more straight-forward. I think this applies here if you look at code re-written to leverage the async/await syntax of C# 5:

Firstly, here is the non-Rx version of MakeObservableMovieDbRequest:

static async Task<T> MakeMovieRequestAsync<T>(
    string url,
    params KeyValuePair<string, string>[] additionalParameters)
{
    var client = new RestClient(BaseUrl) { Proxy = new WebProxy() };

    var parameterisedUrl = new StringBuilder(MakeUrl(url));

    foreach (var keyValuePair in additionalParameters)
    {
        parameterisedUrl.AppendFormat(@"&{0}={1}",
            keyValuePair.Key, keyValuePair.Value);
    }

    var request = new RestRequest(parameterisedUrl.ToString());

    var result = await client.ExecuteGetTaskAsync<T>(request);

    return result.Data;
}

Since a Task can be easily translated to an IObservable<T> with a call to ToObservable(), I think it’s just easier and more flexible to leave this function returning a Task. With the use of async/await we remove some braces and make the code more readable.

The same is true when using this method to page through the action movies:

static async Task GetActionMovies()
{
    var genreCollection =
        await MakeMovieRequestAsync<GenreCollection>(@"genre/list");

    var actionGenreId = (from genre in genreCollection.Genres
                            where genre.Name == "Action"
                            select genre.Id).First();

    var actionMoviesUrl = string.Format(
        @"genre/{0}/movies", actionGenreId);

    var actionMovieCollection =
        await MakeMovieRequestAsync<MovieCollection>(actionMoviesUrl);

    var totalPages = actionMovieCollection.TotalPages;

    for (int i = 1; i <= totalPages; i++)
    {
        var parameter = new KeyValuePair<string, string>(
            "page", i.ToString(CultureInfo.InvariantCulture));
        var movies = await MakeMovieRequestAsync<MovieCollection>(
            actionMoviesUrl, parameter);

        foreach (var movie in movies.Results)
        {
            Console.WriteLine("Movie {0}", movie.Title);
        }
    }            
}

The use of async/await means this code tells a clear story here – there are no obscure uses of Rx features like Concat to constrain concurrency; the for loop makes it clear how the results are being pulled together.

There are plenty of examples where Rx makes sense – often when coordinating complex streams.

The Rx solution is actually quite involved with some concepts that are not particularly intention revealing. In my opinion, in this case it makes the solution harder to maintain compared with the async/await approach.

As I said at the beginning, I’m often guilty of this – its very easy to forget how baffling Rx can be to the uninitiated. It should be used only when it brings real advantages to the table.

You often don’t have to look too far for this – even an idea as simple as adding a Timeout and decent error handling can be surprising hard to express with the TPL and yet quite simple with Rx. Pre .NET 4.5 and async/await, having to chain tasks together the old way was also a real chore.

That said, I won’t be stopping my love affair with Rx anytime soon – there’s plenty more nails that need hammering in with it!

Constraining a stream of events in Rx to a maximum rate

Sometimes, you want to limit the rate at which events arrive from an Rx stream.

The Throttle operator will suppress an event if another arrives within a specified interval. This is very useful in many instances, but it does have two important side-effects – even an unsuppressed event will be delayed by the interval, and events will get dropped altogether if they arrive too quickly.

I came across a situation where both of these were unacceptable. In this particular case, the desired behaviour was as follows: The events should be output at a maximum rate specified by a TimeSpan, but otherwise as soon as possible.

One solution works like this. Imagine our input stream is a bunch of people arriving at a railway station. For our output, we want people leave the station at a maximum rate. We set the maximum rate by having each person stand at the front of a flatbed railroad truck and sending that truck out of the station at a fixed speed. Because there is only one track, and all trucks travel at the same speed and have the same length, people will leave the station at a maximum rate when trucks are departing back-to-back. However, if the track is clear, the next person will be able to depart immediately.

So how to we translate this metaphor into Rx?

We will use the Concat operator’s ability to accept a stream of streams and merge them together back-to-back – just like sending railroad trucks down the track.

To get the equivalent of each person onto a railroad truck, we will use a Select to project each event (person) to an observable sequence (railroad truck) that starts with a single OnNext event (the person) and ends with an OnComplete exactly the defined interval later.

Lets assume the input events are an IObservable<T> in the variable input. Here’s the code:

var paced = input.Select(i => Observable.Empty<T>()
                                        .Delay(interval)
                                        .StartWith(i)).Concat();

I’ll leave it as an exercise to turn this into an extension method for easy reuse!