Author Archives: claytonone

Breakout

If you’re looking for a fun game to pass the time, look no further than our latest game “Breakout”! Available to download on Android and Windows Phone below!

The game was build using the Unity game engine, which I highly recommend if you are looking to build a game.

Get it on Google Play

Get it from Microsoft

Caliburn Micro Part 7: Basic Dependency Injection With WinRT and Phone 8.1

This tutorial is mostly targeted at Windows Phone development but most of it will carry over to Windows 8 store apps and to a certain extent, desktop apps.

Caliburn makes available the WinRTContainer which can be used to register dependencies. The different ways they can be registered are listed below.

RegisterInstance – The registered instance will be returned each request
RegisterPerRequest – A new instance of the specified type will be returned each time
RegisterSingleton – Similar to register instance but singletons are only constructed when the first request is made
Handler – Provides a way of adding logic for context sensitive implementations
AllTypesOf – Registers all specified types in an assembly as singletons

Example

Say we had a small application that allowed the adding of users. The viewmodel takes a single parameter in its constructor which is an interface to a database.

public class AddUsersViewModel
{
    public AddUsersViewModel( IDataStore dataStore )
    {
    }
}

In this instance we only want one instance of the AddUsersViewModel to exist at a time so we register it as a singleton with the container. The code below is from App.xaml.cs.

protected override void Configure()
{
    container = new WinRTContainer();

    container.RegisterWinRTServices();

    container.RegisterSingleton( typeof( AddUsersViewModel ), null, typeof( AddUsersViewModel ) );
}

Now given that our viewmodel takes arguments in its constructor, we want Caliburn to inject those for us when it creates the singleton instance of it. Note that _dataStore is an instance of IDataStore that we have created.

protected override void Configure()
{
    container = new WinRTContainer();

    container.RegisterWinRTServices();

    container.RegisterInstance( typeof( IDataStore ), null, _dataStore );

    container.RegisterSingleton( typeof( AddUsersViewModel ), null, typeof( AddUsersViewModel ) );
}

With the above code caliburn will automatically inject our instance of IDataStore into the constructor of AddUsersViewModel when it creates an instance of it. This is especially useful when you are using the navigation service in Windows Phone 8.1 apps.

C# – Wait Until A Condition Is True

Sometimes the need arises to wait for a condition or property to become true, this is especially useful for unit / integration tests. The System.Threading namespace contains SpinWait which will enable use to enter a condition that we want to wait on to see if it becomes true.

In the code example below we have a property called _waitUntilTrue, execution will not pass SpinWait until this becomes true. The timer will set it to true after 5 seconds and execution will continue;

public class Program
{
    private static bool _waitUntilTrue = false;

    public static void Main( string[] args )
    {
        Timer timer = new Timer( 5000 );
        timer.Elapsed += delegate { _waitUntilTrue = true; };
        timer.AutoReset = false;
        timer.Start();

        DoWork();
    }

    private static void DoWork()
    {
        System.Threading.SpinWait.SpinUntil( () => _waitUntilTrue );

        Console.WriteLine( "Now True" );
    }
}

A timeout can also be specified as a second argument to SpinWait which will continue execution if the condition does not become true in the specified time. If this argument is specified, SpinWait returns a Boolean value which is true if the condition is satisfied within the timeout and false otherwise.

C# – Constraining Type Parameters

Sometimes it can be useful to constrain what types can be passed to generic classes. Say for example that you were building a generic binary tree, then you might what to ensure that only types that implemented IComparable can be used.

The where keyword is used to specify constraints.

public class BinaryTree<T> where T : IComparable<T>

As detailed on MSDN the full list of constraints is listed below.

where T: struct
The type argument must be a value type. Any value type except Nullable can be specified.

where T : class
The type argument must be a reference type, including any class, interface, delegate, or array type.

where T : new()
The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.

where T :
The type argument must be or derive from the specified base class.

where T :
The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U
The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

Caliburn Micro Part 6: The Window Manager

Caliburn usually takes care of creating the main window for use, but what if we wanted to dynamically create a popup window our self? To do this we can use the provided WindowManager class.

Creating a popup window

IWindowManager manager = new WindowManager();
manager.ShowDialog( myViewModel, null, null );

Simple put the code above creates a new modal window which shows the view associated with the supplied view model (myViewModel).

Customising the window

We can do this by passing an array of settings to the ShowDialog function, to do this we use an ExpandoObject which is interpreted at runtime ( this means that you won’t get any intelli sense or error checking). You can add any property to the ExpandoObject that would be settable on a wpf window.

dynamic settings = new ExpandoObject();
settings.WindowStartupLocation = WindowStartupLocation.CenterOwner;
settings.ResizeMode = ResizeMode.NoResize;
settings.MinWidth = 450;
settings.Title = "My New Window";
settings.Icon = new BitmapImage( new Uri( "pack://application:,,,/MyApplication;component/Assets/myicon.ico" ) );

IWindowManager manager = new WindowManager();
manager.ShowDialog( myViewModel, null, settings );

Notes

The new window does not have to be modal, there are other functions on the window manager for showing a non modal window and a popup.

That’s it for this tutorial join us next time for a look at using Dependency Injection.

Entity Framework – The Basics

Entity Framework makes creating and accessing databases easier and removes the need to write lots of data access code.

Getting Started

Add the NuGet packege listed below to your project – searching the NuGet package manager for “Entity Framework” should bring it up.

Creating a Model

Firstly we need a create a model that will represent our data, this can just be a simple C# class with a couple of properties. Below is a simple customer model.

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Creating a Context

Now we need to create a context which will handle the communication with the database.

public class CustomerContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

Putting It All Together

Finally we just need to add some code that will save a customer instance into our database.

using( CustomerContext ctx = new CustomerContext() )
{
    Customer customer = new Customer() { Name = "Bob Smith" };
    ctx.Customers.Add( customer );
    ctx.SaveChanges();
}

Finally

You may wonder why the code above works as we didn’t create a database, the beauty of Entity Framework is that it does all of this for us. If you check Sql Server Management Studio you should notice that a database has been created along with a table for our customers.

C# Async / Await – The Basics

The await and async keywords were introduced in C# version 5.0 so you’ll need that version or higher to use them.

Introduction

The await and async keywords can be used to make task based programming a lot easier by reducing the amount of code that you have to write. The async modifier is used on method declarations to denote that the function will wait for a task to complete at some point. The await modifier is used to state that execution on the current thread will not continue until the awaited task has completed. This also ensures that the UI thread is not blocked.

Example

public async Task DoWork()
{
    await Task.Run( () => LongRunningFunction() );

    // Do something else here
}

In the example above no code below the await will be executed until the LongRunningFunction completes. Control returns to the caller of the DoWork function so that the UI thread is not blocked.

NOTES

Note that it is considered good practise to return Task rather can void on async functions.

C# using Statement

The using statement provides a convenient way to automatically call dispose on objects that implement the IDisposable interface once they go out of scope.

CODE

using (StreamReader sr = new StreamReader("SomeFile.txt"))
{
    string text = sr.ReadLine();
}

NOTES

The using statement ensures that dispose gets called even if an exception gets thrown.

Using Graphs and Charts In WinRT Apps – The Basics

Visual Studio does not provide a chart control by default for use in WinRT apps but we can get around this by using the ones provided in the WinRT XAML Toolkit.

Getting Started

Create a new blank Windows Store project in Visual Studio and then add the two NuGet packages listed below – searching in the NuGet package manager for “WinRT XAML Toolkit” should bring them both up.

Creating an empty chart

In MainPage.xaml add the following XAML namespace reference.

xmlns:Charting="using:WinRTXamlToolkit.Controls.DataVisualization.Charting"

Now lets add an empty chart that we’ll use to hold the chart type that we are interested in.

<Charting:Chart Name="MyChart" Width="500" Height="500" Title="My Chart" Margin="0">
</Charting:Chart>

Adding a Pie Chart

There are many different types of chart that can be created but for the sake of simplicity we will just create a pie chart in this tutorial.

<Charting:Chart Name="MyChart" Width="500" Height="500" Title="Chart" Margin="0">
    <Charting:PieSeries Margin="0" IndependentValuePath="Item1" DependentValuePath="Item2" IsSelectionEnabled="True" />
</Charting:Chart>

Note that IndependentValuePath determines what we want to show on each pie segment like its name and DependentValuePath determines the size of each pie segment. I’ve set them to “Item1” and “Item2” as we are using a Tuple to pair the values together as you will see below.

Populating the pie chart

Open the code behind file for MainPage.xaml and add the following code which will create three segments in the pie chart.

public MainPage()
{
    this.InitializeComponent();

    this.Loaded += MainPage_Loaded;
}

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    List<Tuple<string, int>> myList = new List<Tuple<string,int>>()
    {
        new Tuple<string, int>("Item 1", 20),
        new Tuple<string, int>("Item 2", 30),
        new Tuple<string, int>("Item 3", 50)
    };

    (MyChart.Series[0] as PieSeries).ItemsSource = myList;
}

If you build you application you should see a pie chart with three segments shown onscreen. That’s all for this tutorial but stay tuned for more on the WinRT XAML Toolkit.