An Alternative to SQLite in Windows Store Apps

SQLite is a popular embedded database in use in Windows Store and Windows Phone apps, thought it can sometimes be tricky to get setup: there are a few different choices of NuGet packages / Visual Studio extensions to get up and running with.

An alternative embeddable database to use in Windows Store apps is BrightstarDB.

BrightstarDB is embeddable like SQLite but one big difference is that it’s a NoSQL database based on RDF. It still remains accessible to .NET developers via its entity framework like layer that supports niceties such as LINQ. BrightstarDB can also be used in desktop/web applications in addition to Windows Phone (Silverlight) apps.

Usage

First, in a Windows Store project install the NuGet packages: “BrightstarDB” and “BrightstarDB.Platform”

This will install the relevant libraries and will also create a file called “MyEntityContext.tt” which will generate a strongly typed data context for us to work with.

To define an entity, an interface is used and marked with the [Entity] attribute:

[Entity]
interface IToDoItem
{
    string Id { get; }
    string Description { get; set; }
}

Now when the MyEntityContext.tt file is right clicked and the option Run Custom Tool is selected, the MyEntityContext.cs file will be generated that knows how to save and retrieve ToDoItems. Entities can also be defined with relationships.

As a basic user interface that allows creation of a to do and loading existing todos in alphabetical order:

<Page
    x:Class="ToDo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    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}" Width="300">
        <StackPanel>
            <TextBox PlaceholderText="New task description" Name="NewDescription"></TextBox>
            <Button Name="Create" Click ="Create_OnClick">Create</Button>
            <Button Name="Load" Click ="Load_OnClick">Load</Button>
            <ListView Name="Tasks" DisplayMemberPath="Description"></ListView>
        </StackPanel>
    </Grid>
</Page>

To implement the code that saves a new ToDoItem to the embedded database:

private const string _connectionString = "type=embedded;storesDirectory=data;storename=tasksdb";

private void Create_OnClick(object sender, RoutedEventArgs e)
{
    using (var ctx = new MyEntityContext(_connectionString))
    {
        var newTask = ctx.ToDoItems.Create();

        newTask.Description = NewDescription.Text;

        ctx.SaveChanges();
    }
}

This click handler creates an instance of the generated MyEntityContext, creates a new entity, sets some property values, and finally calls SaveChanges() to write the changes to the underlying database store. Also note the BrightstarDB connection string field.

To retrieve data:

private void Load_OnClick(object sender, RoutedEventArgs e)
{
    using (var ctx = new MyEntityContext(_connectionString))
    {
        Tasks.ItemsSource = ctx.ToDoItems.OrderBy(x => x.Description);                                
    }
}

Here we’re using some LINQ to sort by description and assign the result to the list in the UI.

So if we add the values in the order “Zulu”, “Tango”, “Foxtrot”; when we retrieve them they will look like the following screenshot:

Windows Store app using BrightstarDB

 

For more information check out the documentation or my Introduction to BrightstarDB Pluralsight Course.

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.

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.

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.

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...

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.

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.

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.