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

New Pluralsight Course - Automated ASP.NET MVC Testing: End to End

My new Pluralsight course Automated ASP.NET MVC Testing: End to End was just published.

The course looks at tools and techniques to be able to tests models, controller actions, Razor view rendering logic, and implement automated functional UI browser testing.

The course wraps up by showing how to design and implement a continuous integration build in TeamCity that runs the tests created during the course.

Check it out the full table of contents.

Using Cyclomatic Complexity as an Indicator of Clean Code

Cyclomatic complexity is one way to measure how complicated code is, it measures how complicated the structure of the code is and by extension how likely it may be to attract bugs or additional cost in maintenance/readability.

The calculated value for the cyclomatic complexity indicates how many different paths through the code there are. This means that lower numbers are better than higher numbers.

Clean code is likely to have lower cyclomatic complexity that dirty code. High cyclomatic complexity increases the risk of the presence of defects in the code due to increased difficulty in its testability, readability, and maintainability.

Calculating Cyclomatic Complexity in Visual Studio

To calculate the cyclomatic complexity, go to the the Analyze menu and choose Calculate Code Metrics for Solution (or for a specific project within the solution).

This will open the Code Metrics Results window as seen in the following screenshot.

image

Take the following code (in a project called ClassLibrary1):

namespace ClassLibrary1
{
    public class Class1
    {
    }
}

If we expand the results in the Code Metrics Window we can drill down into classes and right down to individual methods as in the following screenshot.

image

Read full article...

The ConditionalWeakTable in .NET

The ConditionalWeakTable class exists in the System.Runtime.CompilerServices namespace and as its namespace suggests is used in compilation processes.

The class allows a key-value pair to be stored (using its Add method), once the key object no longer has any references outside of the ConditionalWeakTable the key can be destroyed during garbage collection as the key is held as a weak reference inside the table, as opposed to a usual strong reference. At this point the key object can be garbage collected. Also at this point, if the value object also has no other references, it too can be collected. Or too quote MSDN: “It does not persist keys. That is, a key is not kept alive only because it is a member of the collection”.

The following code shows a console application followed by its output:

using System;
using System.Runtime.CompilerServices;

namespace ConditionalWeakTableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var cwt = new ConditionalWeakTable<SomeKeyClass, SomeValueClass>();

            Console.WriteLine("Creating new instance of SomeKeyClass called key1");
            var key1 = new SomeKeyClass();

            Console.WriteLine("Creating new instance of SomeValueClass called value1");
            var value1 = new SomeValueClass();

            Console.WriteLine("Creating variable anotherReferenceToKey1 referencing key1");
            var anotherReferenceToKey1 = key1;

            Console.WriteLine("Adding key1, value1");
            cwt.Add(key1, value1);




            Console.WriteLine("Press a key to set key1 to null");
            Console.ReadLine();
            key1 = null;
            Console.WriteLine("key1 to null");

            ForceGc();




            Console.WriteLine("Press a key to set anotherReferenceToKey1 to null");
            Console.ReadLine();
            anotherReferenceToKey1 = null;
            Console.WriteLine("anotherReferenceToKey1 to null");

            ForceGc();            




            Console.WriteLine("End of program - press any key to exit");
            Console.ReadLine();
        }


        private static void ForceGc()
        {
            Console.WriteLine("Forcing garbage collection and waiting for finalizers");
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }


    class SomeKeyClass
    {
        ~SomeKeyClass()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("****** SomeKeyClass Destroyed");
            Console.ResetColor();
        }        
    }

    class SomeValueClass
    {
        ~SomeValueClass()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("****** SomeValueClass Destroyed");
            Console.ResetColor();
        }
    }
}

image

 

So here, even though the cwt contains an entry using key1, it is held in a weak way so it will not prevent garbage collection.

Also notice in this example, the value object has not been destroyed as we still have a reference to it in the variable value1.

If we change the code to also set value1 to null, when the Garbage Collector runs it will destroy the key object as before, but now there are also no references to the value object, so it too can be destroyed:

static void Main(string[] args)
{
    var cwt = new ConditionalWeakTable<SomeKeyClass, SomeValueClass>();

    Console.WriteLine("Creating new instance of SomeKeyClass called key1");
    var key1 = new SomeKeyClass();

    Console.WriteLine("Creating new instance of SomeValueClass called value1");
    var value1 = new SomeValueClass();

    Console.WriteLine("Creating variable anotherReferenceToKey1 referencing key1");
    var anotherReferenceToKey1 = key1;

    Console.WriteLine("Adding key1, value1");
    cwt.Add(key1, value1);




    Console.WriteLine("Press a key to set key1 to null");
    Console.ReadLine();
    key1 = null;
    Console.WriteLine("key1 to null");

    ForceGc();




    Console.WriteLine("Press a key to set anotherReferenceToKey1, value1 to null");
    Console.ReadLine();
    anotherReferenceToKey1 = null;
    value1 = null;
    Console.WriteLine("anotherReferenceToKey1 & value1 to null");

    ForceGc();            




    Console.WriteLine("End of program - press any key to exit");
    Console.ReadLine();
}

 

image

 

So even though this is not a class we’d use in everyday coding, it’s one of the many interesting things in .NET that are hidden away in namespaces we don’t usually use. It also should be noted that it doesn’t really behave as a “normal” dictionary, for example it doesn’t contain GetEnumerator method.

To learn some cool C# Tips, check out my free C# Tips eBook or my Pluralsight C# Tips and Traps course.

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.

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