This site works best in modern browsers. Looks like you're using an old one, you should upgrade if you can.

C# Tips eBook Complete

I’m pleased to announce that my C# Tips eBook is now complete and currently has over 1,000 readers.

The book is free and you may pay whatever you can afford.

https://s3.amazonaws.com/titlepages.leanpub.com/cstips/large?1416887188

 

Thanks to all the readers who supported the writing of this book.

Download C# Tips today.

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.

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.

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.

about jason

My Bio Photo

Jason Roberts is a Journeyman Software Developer, Microsoft MVP, writer, Pluralsight author, open source contributor and Windows Phone & Windows 8 app author.

He holds a Bachelor of Science in computing and is an amateur music producer and landscape photographer.

MVP Logo

Pluralsight Author Badge

Sign up for the Don't Code Tired Newsletter

Disclaimer
The opinions expressed herein represent my personal opinions and do not represent my employer's views in any way.

© Copyright 2014, Jason Roberts