Beyond Simple Asserts with ApprovalTests

In a test, we are often testing (asserting) individual items such as an (int) age is correct or a string matches an expected value.

If we are practicing test-first development we’ll write our asserts first.

Approval tests allow us to go beyond simple asserts.

What if the thing we’re checking is not a simple value, for example that a pie chart image matches the input data? Or what if we want to use our human judgement to decide when something looks correct, something that is hard to codify in one or more basic asserts?

ApprovalTests for .NET can be install via NuGet. Once installed, it gives us a whole new world when it comes to checking the output of code.

For example, say we are developing a class to represent a stickman. We want to be able to tell an instance to raise left arm or raise right leg for example.

Example of Using Approval Tests

So lets start with a test:

[Fact]
[UseReporter(typeof(DiffReporter))]
public void ShouldHaveDefaultPosture()
{
    var sut = new StickMan();

    Approvals.Verify(sut);
}

And an empty StickMan:

public class StickMan
{        
}

Here we’re using xUnit.net (the [Fact] attribute) but you could be using NUnit for example.

The first thing to notice here is there is no traditional Assert method, instead we’re using Approval Tests to verify the state of the system under test (sut).

The other think to notice is the [UseReporter] attribute that tells Approval Tests to use a diff tool to display errors when a test fails.

If we run this test, we’ll get a diff tool opened:

More...

SHARE:

Run Local Development and Store-Installed Versions of Windows Store Apps Side-by-Side

If you’ve released a Windows Store app and you want to actually use the released version yourself on the same machine you develop the app on, running the dev version from Visual Studio may overwrite the real Store-installed version.

As a workaround you can edit some files to change the package name so when you run it in dev it won’t override the store version. But you need to remember to change back when you release next version.

A while ago I came across a post using various steps to achieve this but it seem a bit complex an involved additional targets, etc.

So I hacked together my own utility: CohabitStoreApp.

It’s a low tech utility that you add as a pre-build step in your Store App project and it does 2 things:

  1. In DEBUG config, adds LOCALDEV to package identity and changed background color to red
  2. in non-DEBUG config removes LOCALDEV from package identity and restores background color

Check out the example app and the readme for more info.

SHARE:

Using Sass Maps to Save Time in CSS

Sass is a superset of CSS that “compiles” down to regular CSS usable by any browser. It adds features such as functions, logic, and loads more.

Sass already had the concept of lists that allow a one-dimensional list of values to be defined; Sass 3.3 introduced maps – a series of key-value pairs.

Defining a Sass Map

To define a variable called team-colors containing a map of values (in this case a map of soccer teams and their colors):

$team-colors: (
    australia: #F7AD31,
    england: #FFF,
    sweden: #FFE700,
    japan: #435AAD
);

Iterating over a Sass Map

Now we can iterate through all the team names and access their color values:

@each $team, $color in $team-colors{
    .#{$team} {   
        background-color: $color;
  }
}

This will create a CSS class with the name of the team (using Sass interpolation syntax) and its associated background color:

.australia {
  background-color: #F7AD31;
}

.england {
  background-color: #FFF;
}

.sweden {
  background-color: #FFE700;
}

.japan {
  background-color: #435AAD;
}

There’s also a number of functions for manipulating maps such as map-get and map-has-key.

 

To learn how to simplify your CSS and save time writing it with Sass, check out my Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

New Open Source Project–Named Colors

I’ve been tinkering with an idea for a new open source project called NamedColors.

As its name suggests, it’s a list of color values (hex RGB) with associated names. In addition, a number of related “emotions” can be associated with each color.

A Named Color is defined as:

<NamedColor>
    <Name>MetroUITeal</Name>
    <RGB>00aba9</RGB>
    <Emotions>
    </Emotions>
</NamedColor>

You can see the current (short) list on GitHub.

The idea is to create a number of projections for use in different programming languages / platforms. For example CSS, Sass, and .NET PCL.

The project is in its early stages at the moment, and I’m not sure what applications people will find for it – it will be interesting to see what happens.

Projections are created using T4 templates.

There are other projections planned, such as a XAML dictionary of colors and brushes.

If anyone has any other ideas for projections feel free to add an issue or send me a pull request – also for adding other named colors.

Eventually for .NET there will be a NuGet PCL available containing all the named colors and way to say “give me a sad color”, etc.

SHARE:

Women in IT

I’m a white male. I’ve never been subject to discrimination in the workplace because of these things, so I wondered whether I have any claim to write about women in IT.

I have worked in all-male teams and in teams with (limited) numbers of women. I’ve also had (mostly) male managers and (occasional) female managers. Whilst it’s not very scientific, those teams with women in them felt different, a different energy or dynamic. There may be evidence to support this: according to this article in HBR “if a group includes more women, its collective intelligence rises”.

I recently tweeted “I'm wondering if we should seek gender-neutral versions of craftsman and journeyman in #IT?  "crafter" and "journey____" ?? #WomenInIT” and this spurred me to write this article.

Is “craftsman” too gendered a term? If so something like “crafter” is quite an easy change to make “software craftsman” becomes “software crafter”, I actually quite like this.

“Journeyman” seems a little harder, “journeyperson” seems a little clunky; perhaps “journeying software developer”? I’m not sure.

There is sometimes the view that this is all “political correctness gone mad”, so it’s probably a good idea to start with what we want our industry and our day-to-day work lives to be like.

If we accept that women improve our teams, and better teams make better software, and better software improves the world; then we need more women in IT. If this means that we (that is the “male we”) need to use a few different words here and there then so be it. We just need to think of good, non-patronising, sincere, gender-neutral (and hopefully still catchy) versions of these words.

There is of course a whole lot more to encouraging (or not discouraging) more girls to take an interest in IT, from schooling systems to general societal gender-biases.

Ultimately if I as an individual want the benefits of more women in the teams I work in, then I need to ask myself what can I do to help make this happen.

Often discussions such as these turn into “I only believe in meritocracy, I don’t care what gender you are” type statements. I too ultimately believe in the “best person should get the job” type thinking, however I also recognize that as a white male I’ve never had to deal with discrimination.

Diversity in general is usually a good thing: religion, gender, race, technical background, age, etc. A team, comprised of 10 people that are all the same, with exactly the same skills and outlooks will be weaker overall than a more diverse team.

How can we represent the world with our software if we don’t represent it within our development teams?

SHARE:

Using LinqToTwitter in Windows Store Apps

LinqToTwitter is an open source library to help work with the Twitter API. It can be used in a Windows Store app to authorise a user and your app and allow querying and sending of Tweets.

Setting Up

First install the NuGet package into your Windows Store app. You’ll then need to head over to https://dev.twitter.com/ and sign in and define an app – you’ll end up with a couple of items that you’ll need later to authorise your app to use the API: API Key (aka consumer key) & API Secret (aka consumer secret).

image

 

Authorising Your App for a Given User

The first step is that the user must sign in to Twitter and grant your app access to their Twitter account.

First include the namespaces: LinqToTwitter and LinqToTwitter.WindowsStore.

Next create an instance of an InMemoryCredentialStore and set the consumer key and secret for your app as defined above.

var c = new InMemoryCredentialStore
{
    ConsumerKey = "your API key here",
    ConsumerSecret = "your API secret here"
};

Next, create a WindowsStoreAuthorizer and use the InMemoryCredentialStore and a callback address – this callback doesn’t actually have to do anything):

var authorizer = new WindowsStoreAuthorizer
{
    CredentialStore = c,
    Callback = "http://somecallbackaddresshere.com/blah.html"
};

Now calling the AuthorizeAsync method will bring up the Twitter auth dialog.

await authorizer.AuthorizeAsync();

Following the await, if the auth succeeded you can get the OAuthToken and OAuthTokenSecret with: authorizer.CredentialStore.OAuthToken and authorizer.CredentialStore.OAuthTokenSecret.

Sending a Tweet

To send a Tweet, an instance of a TwitterContext is needed. To create this an authorizer is passed to its constructor. You can use the instance (“authorizer”) you already have, or if you’re sending from a different part of the app codebase you may need to re-create one. To do this:

var authorizer = new WindowsStoreAuthorizer
{
    CredentialStore = new InMemoryCredentialStore
                      {
                          ConsumerKey = "your key",
                          ConsumerSecret = "your secret",
                          OAuthToken = token received from AuthorizeAsync,
                          OAuthTokenSecret = token received from AuthorizeAsync
                      }
};

To create the context:

var context = new TwitterContext(authorizer);

Now that we have a context, we can use it to send a new Tweet:

await _context.TweetAsync("tweet content here");

SHARE:

New Pluralsight Course - Improve Your Application User Experience with Humanizer

My new Pluralsight course Making .NET Data Types More Human With Humanizer was recently released.

With Humanizer our application user experience can be improved. For example we’ve all seen (and probably written) applications that just add “(s)” to a list of things: “1 order(s)” rather that adding the “s” only when there is more than 1 order.

Another use case is the Humanization of DateTimes. For example in a logging application we’d probably want the log entry date and time right down to the millisecond. In a Twitter app for example, that level of detail is not essential to the user experience; in this instance Humanizer can give us a string such as “2 hours ago” which is a lot easier on the eye.

Check out the GitHub site, give a shout out to the creator Mehdi Khalili on Twitter, or watch the Pluralsight course here.

You can start watching with a Pluralsight free trial.

SHARE:

Debugging Share To and Background Agents in Windows Store Apps

When your main app is running via Visual Studio, when there is a problem you’ll get an exception and Visual Studio will break into the debugger to help you figure out the problem.

There’s a couple of scenarios that are a little more difficult to debug but are easy enough to do once you know how to access it in Visual Studio.

The two things that can be problematic are debugging background agents and debug share to functionality if your app is a share target. If you share to your app if it’s not already running you may not have things like dependency injection registered or other setup code. This is because a differnt code path executes when you launch the app normally to when you launch via share charm. The other thing is debugging background agents, if you are (for example) using a timed agent that executes every hour you don’t want to wait around for an hour before you can test.

Debugging Apps Launched from Share Charm

This technique also applies if you want to start debugging when you start your app from the desktop, even if you didn’t start it from Visual Studio.

Make sure your app is built and deployed: if you just want to deploy but not launch go to the Build menu and choose Deploy Solution.

At this point your app is freshly installed but is not running.

More...

SHARE:

Create More Maintainable CSS in Less Time with Sass and Visual Studio

My new Pluralsight course was recently released that shows how to use Sass when developing ASP.Net web applications.

Sass (CSS with superpowers) allows the creation of regular CSS, but produce it with loads of cool features that regular programmers know such as variables and functions.

Sass is a superset of CSS and has a .scss file extension. A CSS file is a valid Sass (.scss) file.

A tool “compiles” the Sass .scss file to regular CSS. One way to do this in Visual Studio is to install the free Web Workbench extension. Once installed, whenever you save the .scss file, Web Workbench will create the accompanying .css file as shown in the following screenshot:

CSS files generated from Sass

(Notice here the minified version is being created by Web Workbench because the full version is installed.)

Sass Variables

Sass variables can be defined and then used wherever regular CSS property values are used. For example, the following shows 3 variables declared and used in the .scss file:

$main-brand-color: pink;
$secondary-brand-color: #111;
$base-font-size: 50px;

body {
    background-color: $main-brand-color;
    color: $secondary-brand-color;
    font-size: $base-font-size;
}

This produced the following .css:

body {
  background-color: pink;
  color: #111111;
  font-size: 50px; }

Mixins

Mixins decrease the amount of boilerplate CSS we need to write. For example using vendor prefixes throughout the stylesheet. Rather than writing all the prefixes by hand we can declare and invoke a mixin:

@mixin border-radius($radius){
    -webkit-border-radius: $radius;
    -moz-border-radius: $radius;
    border-radius: $radius;
}

.border {
    @include border-radius(10px);
}

This produces the following CSS:

.border {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px; }

Inheritance

Repetition can be reduced with Sass inheritance. In the following example, happy and sad inherit from greeting:

.greeting {
  border: 1px solid #000;
  padding: 10px;
}

.happy {
  @extend .greeting;
  border-color: yellow;
}

.sad {
  @extend .greeting;
  border-color: grey;
}

This produces:

.greeting, .happy, .sad {
  border: 1px solid #000;
  padding: 10px; }

.happy {
  border-color: yellow; }

.sad {
  border-color: grey; }

Now in the HTML, when the happy or sad class is used, the element will also get the greeting styles without having to apply both classes explicitly.

These examples just scratch the surface of the feature set of Sass. To learn more check out the official site or my Simplifying CSS in Visual Studio With Sass Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE: