New Clean C# eBook

Clean C# eBook Cover image

 

I just published the initial version of my new Leanpub book: Clean C#.

As with my other Leanpub eBooks, Clean C# will be published incrementally. You can currently get it for free or pay whatever you can.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Tracking Technical Debt with TechDebtAttributes

Technical debt can build up over time, slows down development speed, and could increase the risk of defects.

If you work in situation where it’s not always possible to create clean code or you’ve inherited a legacy application you may wish to start cataloguing where and how painful tech debt is.

Introducing TechDebtAttributes

image

I just released an initial NuGet version of an open source project called TechDebtAttributes.

It allows attributes to be used to mark classes, methods, etc as containing technical debt.

When the [TechDebt] attribute is applied you need to specify 2 mandatory values: pain and effort to fix.

Pain is a relative measure of how painful the tech debt is; for example how much it slows you down when changing code, how unhappy you are with it, how many defects are caused by it, etc.

Effort to fix is also a relative measure of the ease, amount of effort/time it will take to fix and remove the debt.

Optionally a description of the debt can also be specified.

Once attributes have been applied, a (string) report can be generated:

***Start of Tech Debt Report - finding all [TechDebt] attribute usages

Benefit to fix: 4999.5  AnotherExampleUsageAssembly.Mango Pain:9999 Effort to fix:2
Benefit to fix: 1666.7  Void .ctor() Pain:5000 Effort to fix:3
Benefit to fix: 5 Quick fix to stop stupid stuff happening sometimes Void SomeMethod() Pain:5 Effort to fix:1
Benefit to fix: 2  ExampleUsage.SillyEnum Tomato Pain:47 Effort to fix:23
Benefit to fix: 0.5 What kind of cheese is this? ExampleUsage.Cheese Pain:3 Effort to fix:6
Benefit to fix: 0.4 What exactly is inner cheese ExampleUsage.Cheese+InnerCheese Pain:3 Effort to fix:8
Benefit to fix: 0.3 This really is silly ExampleUsage.SillyEnum Pain:2 Effort to fix:6
Benefit to fix: 0.2 This is dumb, we should remove it ExampleUsage.ISomeDumbInterface Pain:10 Effort to fix:44
Benefit to fix: 0.1 This should be moved to it's own interface Void Y() Pain:10 Effort to fix:100
Benefit to fix: 0 There's a lot of work to fix this whole class for not much gain ExampleUsage.SomeThing Pain:1 Effort to fix:200

***End of Tech Debt Report.

You can also use a method to specify the maximum total pain you’re willing to accept, if the total pain from all [TechDebt] attributes exceeds this an exception will be thrown and your test will fail.

See the Readme on GitHub for more info.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Design Principals in Practice: Source Code Formatting

(This article is part of the Design Principals in Practice series)

We often take for granted, design principles that are in use in the real world; even in source code these principles affect out ability to comprehend the meaning.

I’m not talking specifically about clean code ideas such as well-named Booleans but rather source code at a higher, more visual level.

Let’s take a look at some design principles and how we can (mis)use them.

Proximity

The Gestalt principle of Proximity states that things that are closer to each other seem more related.

Take the following code, there is an automatic sense that method A and B feel related to each other:

public class Class1
{
    public void A()
    {
        //
    }

    public void B()
    {
        //
    }




    public void C()
    {
        //
    }
}

This is because they are in closer proximity to each other, method C feels more distant and unrelated.

The principle of Proximity can be used when declaring varaibles:

public void SomeMethod()
{
    bool isVipCustomer;
    int years;

    string x;

    decimal y;
}

Here,we get a sense that isVipCustomer and years are related, though years should be renamed to something like yearsAtVipStatus rather than relying on Proximity.

Proximity also applies to where variable are declared, for example the traditional approach of declaring them all at the top of the method (low proximity), versus declaring them throughout the method when the are needed (high proximity).

Similarity

Things that are similar in some way seem more related, this similarity could be in shape, size, color, texture, etc.

IDEs such as Visual Studio use similarity of color to help us perceive what a piece of code is; blue for keywords, green for comments etc.

Naming conventions in source code can increase or decrease the level of similarity to other pieces of code. For example, take the following code:

_firstName = "Sarah";
_lastName = "Smith";            
fullName = _firstName + " " + _lastName;

Here we get a sense that _firstName and _lastName are similar somehow (they are fields in the containing class) Also notice here that I’ve deliberately removed whitespace, if we add some whitespace in we also get the principle of Proximity activated:

_firstName = "Sarah";
_lastName = "Smith";       
     
fullName = _firstName + " " + _lastName;

Uniform Connectedness

We can strongly increase the feeling of relatedness using Uniform Connectedness. For example:

image

In this image the dots enclosed inside the line feel strongly related.

In C#, code blocks contain groups of (hopefully) functionally cohesive code. So lines of code are contained inside sets of braces {}.

So, whilst this may be stretching the comparison a little, in some sense the braces are containing and increase the feeling of relatedness. Take the following example:

bool a;
bool b;
bool c;
bool d;

These Booleans feel related due to their proximity, but if we contain them in some additional braces:

{
    bool a;
    bool b;
}
{
    bool c;
    bool d;
}

We now see two strongly distinct groups.

In the age-old argument about one line code blocks in if statements:

if (true) Console.Write("true");

if (true)
    Console.Write("true");

if (true)
{
    Console.Write("true");
}

Whilst people have different opinions on the style here (I currently favour the explicit bottom approach), the bottom example exhibits strong demarcation of the logical condition and the code that gets executed. Though it’s also interesting to note the principle of Proximity in effect in the first example.

Symmetry

Humans tend to like the appearance of symmetry. One style of C# code that always appears jarring to my eyes is the use of unbalanced (asymmetrical) braces. In the code below the first if statement feels less symmetrical than the second:

if (true) {
    Console.Write("true");
}

if (true)
{
    Console.Write("true");
}

If you glance at these two versions (try to ignore the actual code) the bottom example feels more natural, more symmetrical; feel how your eyes are naturally drawn to the centre of the braces. There may of course be an aspect of conditioning here, if you read mostly C# code in the first style (you of course have my condolences) your mind may have become accustomed to it.

Conclusion

Out of all these principles, probably the easiest one to use is that of Proximity. Simply use whitespace to increase or decrease the relatedness of code. It’s amazing sometimes what a simple empty line can do to improve the readability of source code.

SHARE:

Progress Update on C# Tips eBook

An updated version of my C# Tips eBook has just been released. This brings the book to around 80% complete.

The book includes useful C# Tips, design patterns, and tools.

The remaining 20% of effort will include continuing to add new content, arranging and ordering existing content, cross referencing and final proof reading.

Check out the book on Leanpub.

SHARE:

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:

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:

An Overview of Structured Logging with Serilog

Traditional logging techniques (such as writing lines of text to files) results in the loss of structure and semantics.

Structured logging enables richer, more semantic, structured log data to be created. But more importantly queried.

Serilog is an open source logging library that facilitates this structured logging.

Serilog can be used in the traditional way, for example writing to files, but it is designed to allow capture of structured data.

There are multiple provided “sinks” that route log data to a store; from unstructured data stores such as text files (single and rolling) to structured stores such as RavenDB. Multiple sinks can be configured so the same log event is written to both stores.

Writing to multiple sinks with Serilog

To create structured data, the logging code looks slightly different from traditional (unstructured) logging code. Once the logger is configured, to log an information level event we could write something like the following:

Log.Information("Log in succeeded for {UserId}. Authentication service took {LogInMilliseconds}.", userId, responseTime);

Here, a log event is being written that contains two pieces of structured, sematic data: UserId and LogInMilliseconds. If this message is written to an unstructured source (such as text file) then a simple string will be written. If a structured sink is used then the individual data items will be stored as well.

This means that this structured information can be richly queried, for example queries such as: “show me all the logins for user 42 where the login time exceeded 200ms” or “show me all the logins that took more than 1000ms”.

Check out the Serilog site for more info or my Modern Structured Logging With Serilog and Seq Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

Reducing MVVM Light Viewmodel Code with Fody Property Dependencies and Custom Property Changed Methods

In other previous articles I’ve written about Fody and this article we’ll see how we can use the PropertyChanged.Fody addin with MVVM Light viewmodels.

Windows Store app screenshot

The preceding screenshot shows the app in action: a name TextBox is twoway data-bound to the viewmodel, when a different name is typed, the TextBlock shows the uppercase version.

The user can also type a color into the color box and a bit of reflection happens to convert this string to a color from the Colors class.

Windows Store app screenshot with different bg color

The following code shows the (non Fody-fied) viewmodel:

More...

SHARE:

Using the Xbox Music API in Universal Windows Apps

The Xbox Music API can be used by third party developers (i.e. you and me) to search for artists, songs, albums, etc and also get access to actually play songs.

There are two flavours at present: “unauthenticated” and “authenticated”.

Authenticated access allow playing of full songs and working with user playlists. Playlist changes will automatically roam to user’s other devices. The full access to play full songs requires that the user has an Xbox Music Pass.

Unauthenticated access doesn’t allow access to user playlists, and streaming of music is restrict to 30 second previews.

At present anyone can get unauthenticated access via the Xbox Music RESTful API on Azure Marketplace. Authenticated access is currently limited, you need to apply for the pilot program. I’ve applied for this, hopefully I’ll be accepted so I can understand this part better.

Getting Started with Unauthenticated Access

We need an access key to allow our apps to able to use the (unauthenticated) API. To do this follow these instructions to register and create an application in Azure Marketplace. Don’t worry about the code samples at the bottom of the post, there’s a client API we can use instead.

So now you should have an application registered (you might have to enter some web address in the redirect URI – I’m not sure what this is for at this point).

More...

SHARE:

Consuming Server-Side SignalR Events in Universal Windows App Clients

In a previous article I wrote about creating server side SignalR timer events.

As part of my learning of SignalR I wanted to see how easy it would be to create a Universal Windows app consuming these server side events.

So first off I created a new blank Universal app:

creating universal app in Visual Studio screenshot

 

Next installed the SignalR NuGet package into both app projects: install-package Microsoft.AspNet.SignalR.Client

In the Windows 8.1 Store app project XAML I added a simple bound TextBlock that will display the server messages:

<Page
    x:Class="UpTimeUni.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UpTimeUni"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Viewbox>
            <TextBlock Text="{Binding Uptime}">please wait...</TextBlock>
        </Viewbox>
    </Grid>
</Page>

I also added similar XAML in the Windows Phone 8.1 main page.

More...

SHARE: