Posts by Dave Nash

How to write your first smart phone app in Xamarin Forms

Smart phones are everywhere today, in fact you can’t walk down the street without spotting someone glued to that little screen; interacting with one of the thousands of apps available to download and enjoy. But, have you ever wondered what involved with writing an app yourself?

In this tutorial for beginners we’re going to build a simple app using Xamarin Forms from Microsoft which has the benefit of using a single codebase which can work across Android and iOS; which means you don’t have to worry about learning two different languages or writing the same code twice! The screenshots for this tutorial have been created using a Mac and the simulator device is the iOS Simulator but don’t let that discourage you if you’re using a Windows machine, you can still complete the tutorial by using an Android Virtual Device.

So, let’s get started!

The first thing you’ll need to do is install Visual Studio Community, during the installation process make sure you select the option to install Android + Xamarin.Forms and iOS + Xamarin.Forms on Visual Studio for Mac or, if you’re using Windows, Mobile development with .NET on Visual Studio.

Once you’ve finished installing Visual Studio, we’ll move on.

Step 1. Creating a Solution

The first thing we’ll need to do is create a Solution; a Solution is where we’ll keep all of our code and will be separated into separate Projects, but we’ll go into that in more detail later. For now, click on the File drop down menu and select New Solution…

Step 2. Choosing a Solution

You’ll be presented with the screen shown below asking you to choose a template, I’ve never been one for taking shortcuts when there’s something that can be learned, so let’s select a Blank Forms App then click Next.

Step 3. Configuring our app

The next screen lets us configure our app by specifying a name, choosing target platforms and the method for sharing our code between Android and iOS. You can check the screenshot or copy and paste the options below:

  • App Name: My Library
  • Organization Identifier: com.mycompany
  • Target Platforms: Android and iOS
  • Shared Code: Use .NET Standard

Once you’re happy, click Next.

Step 4. Finishing up configuration

The final screen is used to specify our Solution and Project names, select a location for our work and define whether we want to use Version Control and create an App Center Test. Since this is a simple app we’ll dispense with the last two options and just worry about the naming and location:

  • Project Name: MyLibrary
  • Solution Name: MyLibrary
  • Location: <Your desktop or some other place you like to save files>

Finish up by clicking Create.

Step 5. Getting better acquainted

Once the set-up process has been completed you’ll be presented with a screen similar to the one below; you’ll notice there are two tabs open called MainPage.xaml and MainPage.xaml.cs, these are the two files that represent the first page your app will load. There are two because one contains declarative XAML used to layout controls and the other “code-behind” file contains imperative C# code used to control specific actions. You will also see the Solution Explorer displayed on the side of the screen which provides a graphical representation of your Solution, as shown in the list below:

  • Solution
    • MyLibrary
      • MyLibrary
        • Getting Started
        • Dependencies
        • App.xaml
          • App.xaml.cs
        • MainPage.xaml
          • MainPage.xaml.cs
      • MyLibrary.Android
      • MyLibrary.iOS

The more eagle-eyed of you might have noticed there is an App.xaml and App.xaml.cs code-behind file, more on those later.

Step 6. Running our app

OK, the temptation is too great, before we start writing any code let’s see our blank app working in a simulator! If you Visual Studio is working as expected you should be able to just click on the ‘play’ button shown in the screenshot and our app should just begin to build; if that doesn’t happen make sure you have selected the correct target from the dropdown menu. The build target should be MyLibrary.iOS or MyLibrary.Android, the process should be Debug and the deployment target should be a Simulator (iOS) or Virtual Device (Android).

Assuming your app has built and deployed as expected, this is what you should see; pretty heat, huh?

Step 7. Adding a list

That’s great, we’ve got this far and we know the app runs out of the box, now it’s time to start writing some code! Go back to Visual Studio and click the ‘stop’ button which was the ‘play’ button previously.

All apps contain controls, without them apps wouldn’t be the run-away success they are because no one would be able to use them!

So let’s add our first control.

Visual Studio should still have the MainPage.xaml file open but if it doesn’t double click on it in the Solution Explorer to open it. XAML stands for eXtensible Application Markup Language and was released by Microsoft in 2008 as a clean and simple way for app developers to create layouts in a similar fashion to HTML. If you take a quick look at the code you’ll spot on the first line that XAML is actually XML.

MainPage.xaml contains three nested visual elements, a visual element is a catch-all name for anything we use to provide layout in Xamarin Forms, in fact it is the basic class that all controls and views derive from.

  • ContentPage – used to display individual pages or screens in Xamarin Forms
    • StackLayout – used to display controls in a horizontal or vertical stack
      • Label – used to display text on the screen

We’re going to replace the Label with something a little more useful for our app, so delete the text below.

        <!-- Place new controls here -->
        <Label Text="Welcome to Xamarin.Forms!" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />

And replace it with this text.

        <ListView>
            <ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>A Tale of Two Cities</x:String>
                    <x:String>To Kill a Mockingbird</x:String>
                    <x:String>Of Mice and Men</x:String>
                    <x:String>Pride and Prejudice</x:String>
                    <x:String>Ulysses</x:String>
                </x:Array>
            </ListView.ItemsSource>
        </ListView>

Then save the file but clicking on File > Save, Cmd+S (Mac) or Ctrl+S (Windows) and run the app again by clicking on the ‘play’ button again. Here’s what you should see.

Well done, we’ve now got a list of book titles on our main page, but it would be better if we could allow users of our app to add their own books to the list. So let’s press on…

Step 8: Adding Navigation

At the moment we have a single page app, but most modern apps have many more pages; so we’re going to need to give our users a way of moving back and forth between pages, we do this using navigation.

We add navigation to an app using a NavigationPage, which wraps all our other pages and provides a means of moving between them; to do this we need to open the App.xaml.cs file and replace the following line:

            MainPage = new MainPage();

With this line:

            MainPage = new NavigationPage(new MainPage());

As you might have spotted, the line literally wraps an instance of our MainPage with a NavigationPage instance.

The next step in adding navigation is to give our existing pages a title, so we make it easy for our app’s users to see what page they’re on; since we only have the one page at the moment this will be quick. Open MainPage.xaml.cs and add the following parameter just before the closing angle-bracket > at the end of the line that begins <ContentPage:

Title="My Library"

So the line should appear like this (I’ve added carriage returns to make the line easier to read):

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MyLibrary"
             x:Class="MyLibrary.MainPage"
             Title="My Library">

Now hit the ‘play’ button and you should see that our app now has navigation.

 

Step 9. Create a new page

So, let’s add a new page; you can do this by clicking on File > New File… or right-clicking on the MyLibrary project and selecting New File…

On the New File dialog box, select the Forms option followed by the Forms ContentPage XAML file type, then enter AddBookPage in the Name text box and click New.

Visual Studio will then create the AddBookPage.xaml and AddBookPage.xaml.cs files in the MyLibrary project.

Let’s add some more code, open the AddBookPage.xaml file and replace the contents with the following code:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyLibrary.AddBookPage"
             Title="Add Book">
    <ContentPage.Content>
        <StackLayout Margin="10">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Grid.Row="0" Text="Title"/>
                <Entry Grid.Column="1" Grid.Row="0" Placeholder="Title"/>
                <Label Grid.Column="0" Grid.Row="1" Text="Author"/>
                <Entry Grid.Column="1" Grid.Row="1" Placeholder="Author"/>
                <Label Grid.Column="0" Grid.Row="2" Text="ISBN"/>
                <Entry Grid.Column="1" Grid.Row="2" Placeholder="ISBN"/>
            </Grid>
            <Button Text="Add Book"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

What we’ve added here is a StackLayout which wraps a Grid which we use to layout three Label controls, three Entry controls and a Button. The Grid is configured to contain two columns of equal width which fills the width of the screen, there’s no need to specify how many rows we will need as Xamarin is clever enough to work out we’ll need three when we assign visual elements to them using the Grid.Row parameter. Notice we have also given the page title of Add Book, this will show up in the navigation bar when being viewed by the user.

Now we need to give our user a way to open the Add Book page, we do this by adding a toolbar item that appears in navigation bar of the app’s Main Page. Start by opening the MainPage.xaml file and add the following code between the ContentPage and StackLayout elements:

    <ContentPage.ToolbarItems>
        <ToolbarItem x:Name="_addBook" Name="Add Book"></ToolbarItem>
    </ContentPage.ToolbarItems>

So the page should now look like this:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MyLibrary"
             x:Class="MyLibrary.MainPage"
             Title="My Library">
    <ContentPage.ToolbarItems>
        <ToolbarItem x:Name="_addBook" Name="Add Book"></ToolbarItem>
    </ContentPage.ToolbarItems>
    <StackLayout>
        <ListView>
            <ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>A Tale of Two Cities</x:String>
                    <x:String>To Kill a Mockingbird</x:String>
                    <x:String>Of Mice and Men</x:String>
                    <x:String>Pride and Prejudice</x:String>
                    <x:String>Ulysses</x:String>
                </x:Array>
            </ListView.ItemsSource>
        </ListView>
    </StackLayout>
</ContentPage>

So, we’ve declared that a toolbar item should appear, but as yet it doesn’t know what to do when it’s clicked, so let’s fix that now; open the MainPage.xaml.cs file and, after the line that reads InitializeComponent();, add the following text:

            _addBook.Clicked += (object sender, EventArgs e) =>
            {
                Navigation.PushAsync(new AddBookPage());
            };

So the file should now look like this:

using System;
using Xamarin.Forms;

namespace MyLibrary
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            _addBook.Clicked += (object sender, EventArgs e) =>
            {
                Navigation.PushAsync(new AddBookPage());
            };
        }
    }
}

As you might have noticed, the toolbar item’s x:Name property was defined as _addBook in the XAML file, so that’s what we have referenced in the code-behind file. Here we assign a function to the Clicked EventHandler which adds – or pushes – an instance of the AddBookPage onto the top of the navigation stack. The stack behaves like a list of pages, the last one added is the one that is currently displayed and the user can pop pages off the list to return to previous ones, like they would sing a back button on a web browser.

Now hit the ‘play’ button and you should see that our app has a toolbar item called Add Book that, when clicked, displays the Add Book page.

10. Adding a Model, View Model and binding

Now we have pages to display a list of books and add new books, we now need a way to store book information. We can do this for now by keeping them in memory; the next tutorial will dive into persistent storage using a database.

Let’s first add a place to save the fields we have defined in the AddBookPage for each book, we’ll do this by creating what is known as a model; so go ahead and add a new file but, instead of choosing a Forms Content Page XAML type, we’ll create an Empty Class and call it Book.

Inside the Book.cs file replace the contents with the following code:

namespace MyLibrary
{
    public class Book
    {
        public string Title { get; set; }

        public string Author { get; set; }

        public string ISBN { get; set; }
    }
}

We have create a model for a book that contains three properties, Title, Author, and ISBN; they have be given public access with a getter and setter, this means we will be able to bind them to the Entry controls we added earlier in the AddBookPage.xaml file.

So, where are we now? We have a way of taking book properties from the user by the AddBookPage and a way of storing them in memory; now we need a way of binding them together, we’ll do this using a View Model. Add a new Empty Class and call it AddBookPageViewModel, then inside the AddBookPageViewModel.cs file that you’ve just created, replace the contents with the following code.

namespace MyLibrary
{
    public class AddBookPageViewModel
    {
        public Book Book { get; set; }

        public AddBookPageViewModel()
        {
            Book = new Book();
        }
    }
}

We’ve given the View Model a property called Book and in the AddBookPageViewModel‘s constructor we’ve created a new instance of Book and assigned it to the property. Now, let’s bind the View Model’s properties to the AddBookPage. Open the AddBookPage.xaml.cs file and add the following code after the line that starts InitializeComponent():

            BindingContext = new AddBookPageViewModel();

So the contents should now look like this:

using Xamarin.Forms;

namespace MyLibrary
{
    public partial class AddBookPage : ContentPage
    {
        public AddBookPage()
        {
            InitializeComponent();

            BindingContext = new AddBookPageViewModel();
        }
    }
}

As you can see, we’ve told the page that the BindingContext should be a new instance of the AddBookPageViewModel, a BindingContext is an object that contains properties we can bind to on a page; so let’s bind to them now. Open the AddBookPage.xaml file and update the Entry controls for Title, Author, and ISBN by adding the following properties for each one in turn:

Text="{Binding Book.Title}"

Text="{Binding Book.Author}"

Text="{Binding Book.ISBN}"

So the file should now look like this:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyLibrary.AddBookPage"
             Title="Add Book">
    <ContentPage.Content>
        <StackLayout Margin="10">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Grid.Row="0" Text="Title"/>
                <Entry Grid.Column="1" Grid.Row="0" Placeholder="Title" Text="{Binding Book.Title}"/>
                <Label Grid.Column="0" Grid.Row="1" Text="Author"/>
                <Entry Grid.Column="1" Grid.Row="1" Placeholder="Author" Text="{Binding Book.Author}"/>
                <Label Grid.Column="0" Grid.Row="2" Text="ISBN"/>
                <Entry Grid.Column="1" Grid.Row="2" Placeholder="ISBN" Text="{Binding Book.ISBN}"/>
            </Grid>
            <Button Text="Add Book"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

11. Here’s where it gets tricky

So, we now have a page to display a list of books, a page to let us add a book, a model to contain the details of a book, and a view model to bind them together; but without the use of a database how should we store the books we add in memory? There are a number of ways this can be achieved but the easiest way for the interests of this tutorial is to create a place that exists for as long as the app is running where we can store the details of our books. 

Open the App.xaml.cs file and add the following code at the beginning of the file:

using System.Collections.ObjectModel;

Then add this property after the opening brace of class declaration that begins public partial class App:

        public ObservableCollection<Book> Books { get; } = new ObservableCollection<Book>
        {
            new Book { Title = "A Tale of Two Cities" },
            new Book { Title = "Of Mice and Men" },
            new Book { Title = "Pride and Prejudice" },
            new Book { Title = "To Kill a Mockingbird" },
            new Book { Title = "Ulysses" }
        };

So the whole file should look like this:

using System.Collections.ObjectModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace MyLibrary
{
    public partial class App : Application
    {
        public ObservableCollection<Book> Books { get; } = new ObservableCollection<Book>
        {
            new Book { Title = "A Tale of Two Cities" },
            new Book { Title = "Of Mice and Men" },
            new Book { Title = "Pride and Prejudice" },
            new Book { Title = "To Kill a Mockingbird" },
            new Book { Title = "Ulysses" }
        };

        public App()
        {
            InitializeComponent();

            MainPage = new NavigationPage(new MainPage());
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

We’ve just added an ObservableCollection to the App class, an ObservableCollection is a list which reports to anything that is bound to it when it has been updated; which means we’ll be able to automatically update our list of books on the MainPage.xaml page when we add one without any extra code. So let’s go ahead and bind the two together.

Create a new Empty Class and call is MainPageViewModel then replace its contents with the following code:

using Xamarin.Forms;

namespace MyLibrary
{
    public class MainPageViewModel
    {
        public App App { get; private set; }

        public MainPageViewModel()
        {
            App = (App)Application.Current;
        }
    }
}

We have created a property called App that references our main App instance, now we need to update our MainPage.xaml.cs file to use this view model as a BindingContext; go head and open it and add the following line after the _addBook.Clicked code we added before:

            BindingContext = new MainPageViewModel();

The whole file should now look like this:

using System;
using Xamarin.Forms;

namespace MyLibrary
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            _addBook.Clicked += (object sender, EventArgs e) =>
            {
                Navigation.PushAsync(new AddBookPage());
            };

            BindingContext = new MainPageViewModel();
        }
    }
}

All we need to do now is update our ListView in MainPage.xaml so it uses the ObservableCollection instead of the static array of books we added earlier; go ahead and open the file and replace the ListView with the following code:

        <ListView ItemsSource="{Binding App.Books}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Title}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

So the whole file should now look like this:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MyLibrary"
             x:Class="MyLibrary.MainPage"
             Title="My Library">
    <ContentPage.ToolbarItems>
        <ToolbarItem x:Name="_addBook" Name="Add Book"></ToolbarItem>
    </ContentPage.ToolbarItems>
    <StackLayout>
        <ListView ItemsSource="{Binding App.Books}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Title}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

As you can see, we’ve replaced the ItemsSource property with a binding to the Books ObservableCollection in the App instance we referenced in the view model. We’ve also created a ItemTemplate which contains a TextCell that we have bound to the Title property of the Book object.

Step 12. Adding a book to the list

Right, let’s get this app finished, all we need to do now is add the book to the list; so let’s open the AddBookPageViewModel.cs file and add the following lines after the AddBookPageViewModel constructor:

        public void AddBook()
        {
            ((App)Application.Current).Books.Add(Book);
        }

So now the file should look like this:

using Xamarin.Forms;

namespace MyLibrary
{
    public class AddBookPageViewModel
    {
        public Book Book { get; set; }

        public AddBookPageViewModel()
        {
            Book = new Book();
        }

        public void AddBook()
        {
            ((App)Application.Current).Books.Add(Book);
        }
    }
}

We’ve added a function that, when called, will add the Book – whose details the user has filled out – to the ObservableCollection in the main App class. Now, let’s move on to wiring up the button by opening the AddBookPage.xaml file and update the Button by adding an x:Name property:

x:Name="_addBookButton"

So the file should now look like this:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyLibrary.AddBookPage"
             Title="Add Book">
    <ContentPage.Content>
        <StackLayout Margin="10">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Grid.Row="0" Text="Title"/>
                <Entry Grid.Column="1" Grid.Row="0" Placeholder="Title" Text="{Binding Book.Title}"/>
                <Label Grid.Column="0" Grid.Row="1" Text="Author"/>
                <Entry Grid.Column="1" Grid.Row="1" Placeholder="Author" Text="{Binding Book.Author}"/>
                <Label Grid.Column="0" Grid.Row="2" Text="ISBN"/>
                <Entry Grid.Column="1" Grid.Row="2" Placeholder="ISBN" Text="{Binding Book.ISBN}"/>
            </Grid>
            <Button x:Name="_addBookButton" Text="Add Book"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Now let’s open the AddBookPage.xaml.cs file and add the following text to the AddBookPage constructor:

            _addBookButton.Clicked += (object sender, System.EventArgs e) =>
            {
                ((AddBookPageViewModel)BindingContext).AddBook();
                Navigation.PopAsync();
            };

So the whole file should now look like this:

using Xamarin.Forms;

namespace MyLibrary
{
    public partial class AddBookPage : ContentPage
    {
        public AddBookPage()
        {
            InitializeComponent();

            BindingContext = new AddBookPageViewModel();

            _addBookButton.Clicked += (object sender, System.EventArgs e) =>
            {
                ((AddBookPageViewModel)BindingContext).AddBook();
                Navigation.PopAsync();
            };
        }
    }
}

What we’ve done here is add a function to the Clicked EventHandler of the Button we named _addBookButton to call the AddBook function we added in the AddBookPageViewModel.cs file, followed by popping the page off the Navigation stack so we return to the Main Page.

Now, let’s click the ‘play’ button; if all went according to plan you should now be able to see a list of books, and add new ones using the Add Book page.

Build a blockchain with C++

So, you might have heard a lot about something called a blockchain lately and wondered what all the fuss is about. A blockchain is a ledger which has been written in such a way that updating the data contained within it becomes very difficult, some say the blockchain is immutable and to all intents and purposes they’re right but immutability suggests permanence and nothing on a hard drive could ever be considered permanent. Anyway, we’ll leave the philosophical debate to the non-techies; you’re looking for someone to show you how to write a blockchain in C++, so that’s exactly what I’m going to do.

Before I go any further, I have a couple of disclaimers:

  1. This tutorial is based on one written by Savjee using NodeJS; and
  2. It’s been a while since I wrote any C++ code, so I might be a little rusty.

The first thing you’ll want to do is open a new C++ project, I’m using CLion from JetBrains but any C++ IDE or even a text editor will do. For the interests of this tutorial we’ll call the project TestChain, so go ahead and create the project and we’ll get started.

If you’re using CLion you’ll see that the main.cpp file will have already been created and opened for you; we’ll leave this to one side for the time being.

Create a file called Block.h in the main project folder, you should be able to do this by right-clicking on the TestChain directory in the Project Tool Window and selecting: New > C/C++ Header File.

Inside the file, add the following code (if you’re using CLion place all code between the lines that read #define TESTCHAIN_BLOCK_H and #endif):

#include <cstdint>
#include <iostream>

These lines above tell the compiler to include the cstdint, and iostream libraries.

Add this line below it:

using namespace std;

This essentially creates a shortcut to the std namespace, which means that we don’t need to refer to declarations inside the std namespace by their full names e.g. std::string, but instead use their shortened names e.g. string.

So far, so good; let’s start fleshing things out a little more.

A blockchain is made up of a series of blocks which contain data and each block contains a cryptographic representation of the previous block, which means that it becomes very hard to change the contents of any block without then needing to change every subsequent one; hence where the blockchain essentially gets its immutable properties.

So let’s create our block class, add the following lines to the Block.h header file:

class Block {
public:
    string sPrevHash;

    Block(uint32_t nIndexIn, const string &sDataIn);

    string GetHash();

    void MineBlock(uint32_t nDifficulty);

private:
    uint32_t _nIndex;
    int64_t _nNonce;
    string _sData;
    string _sHash;
    time_t _tTime;

    string _CalculateHash() const;
};

Unsurprisingly, we’re calling our class Block (line 1) followed by the public modifier (line 2) and public variable sPrevHash (remember each block is linked to the previous block) (line 3). The constructor signature (line 5) takes three parameters for nIndexIn, and sDataIn; note that the const keyword is used along with the reference modifier (&) so that the parameters are passed by reference but cannot be changed, this is done to improve efficiency and save memory. The GetHash method signature is specified next (line 7) followed by the MineBlock method signature (line 9), which takes a parameter nDifficulty. We specify the private modifier (line 11) followed by the private variables _nIndex, _nNonce, _sData, _sHash, and _tTime (lines 12–16). The signature for _CalculateHash (line 18) also has the const keyword, this is to ensure the method cannot change any of the variables in the block class which is very useful when dealing with a blockchain.

Now it’s time to create our Blockchain.h header file in the main project folder.

Let’s start by adding these lines (if you’re using CLion place all code between the lines that read #define TESTCHAIN_BLOCKCHAIN_H and #endif):

#include <cstdint>
#include <vector>
#include "Block.h"

using namespace std;

They tell the compiler to include the cstdint, and vector libraries, as well as the Block.h header file we have just created, and creates a shortcut to the std namespace.

Now let’s create our blockchain class, add the following lines to the Blockchain.h header file:

class Blockchain {
public:
    Blockchain();

    void AddBlock(Block bNew);

private:
    uint32_t _nDifficulty;
    vector<Block> _vChain;

    Block _GetLastBlock() const;
};

As with our block class, we’re keeping things simple and calling our blockchain class Blockchain (line 1) followed by the public modifier (line 2) and the constructor signature (line 3). The AddBlock signature (line 5) takes a parameter bNew which must be an object of the Block class we created earlier. We then specify the private modifier (line 7) followed by the private variables for _nDifficulty, and _vChain (lines 8–9) as well as the method signature for _GetLastBlock (line 11) which is also followed by the const keyword to denote that the output of the method cannot be changed.

Ain't nobody got time for that!Since blockchains use cryptography, now would be a good time to get some cryptographic functionality in our blockchain. We’re going to be using the SHA256 hashing technique to create hashes of our blocks, we could write our own but really – in this day and age of open source software – why bother?

To make my life that much easier, I copied and pasted the text for the sha256.h, sha256.cpp and LICENSE.txt files shown on the C++ sha256 function from Zedwood and saved them in the project folder.

Right, let’s keep going.

Create a source file for our block and save it as Block.cpp in the main project folder; you should be able to do this by right-clicking on the TestChain directory in the Project Tool Window and selecting: New > C/C++ Source File.

Start by adding these lines, which tell the compiler to include the Block.h and sha256.h files we added earlier.

#include "Block.h"
#include "sha256.h"

Follow these with the implementation of our block constructor:

Block::Block(uint32_t nIndexIn, const string &sDataIn) : _nIndex(nIndexIn), _sData(sDataIn) {
    _nNonce = -1;
    _tTime = time(nullptr);
}

The constructor starts off by repeating the signature we specified in the Block.h header file (line 1) but we also add code to copy the contents of the parameters into the the variables _nIndex, and _sData. The _nNonce variable is set to -1 (line 2) and the _tTime variable is set to the current time (line 3).

Let’s add an accessor for the block’s hash:

string Block::GetHash() {
    return _sHash;
}

We specify the signature for GetHash (line 1) and then add a return for the private variable _sHash (line 2).

As you might have read, blockchain technology was made popular when it was devised for the Bitcoin digital currency, as the ledger is both immutable and public; which means that, as one user transfers Bitcoin to another user, a transaction for the transfer is written into a block on the blockchain by nodes on the Bitcoin network. A node is another computer which is running the Bitcoin software and, since the network is peer-to-peer, it could be anyone around the world; this process is called ‘mining’ as the owner of the node is rewarded with Bitcoin each time they successfully create a valid block on the blockchain.

To successfully create a valid block, and therefore be rewarded, a miner must create a cryptographic hash of the block they want to add to the blockchain that matches the requirements for a valid hash at that time; this is achieved by counting the number of zeros at the beginning of the hash, if the number of zeros is equal to or greater than the difficulty level set by the network that block is valid. If the hash is not valid a variable called a nonce is incremented and the hash created again; this process, called Proof of Work (PoW), is repeated until a hash is produced that is valid.

So, with that being said, let’s add the MineBlock method; here’s where the magic happens!

void Block::MineBlock(uint32_t nDifficulty) {
    char cstr[nDifficulty + 1];
    for (uint32_t i = 0; i < nDifficulty; ++i) {
        cstr[i] = '0';
    }
    cstr[nDifficulty] = '\0';

    string str(cstr);

    do {
        _nNonce++;
        _sHash = _CalculateHash();
    } while (_sHash.substr(0, nDifficulty) != str);

    cout << "Block mined: " << _sHash << endl;
}

We start with the signature for the MineBlock method, which we specified in the Block.h header file (line 1), and create an array of characters with a length one greater that the value specified for nDifficulty (line 2). A for loop is used to fill the array with zeros, followed by the final array item being given the string terminator character (\0), (lines 3–6) then the character array or c-string is turned into a standard string (line 8). A do…while loop is then used (lines 10–13) to increment the _nNonce and _sHash is assigned with the output of _CalculateHash, the front portion of the hash is then compared the string of zeros we’ve just created; if no match is found the loop is repeated until a match is found. Once a match is found a message is sent to the output buffer to say that the block has been successfully mined (line 15).

We’ve seen it mentioned a few times before, so let’s now add the _CalculateHash method:

inline string Block::_CalculateHash() const {
    stringstream ss;
    ss << _nIndex << _tTime << _sData << _nNonce << sPrevHash;

    return sha256(ss.str());
}

We kick off with the signature for the _CalculateHash method (line 1), which we specified in the Block.h header file, but we include the inline keyword which makes the code more efficient as the compiler places the method’s instructions inline wherever the method is called; this cuts down on separate method calls. A string stream is then created (line 2), followed by appending the values for _nIndex, _tTime, _sData, _nNonce, and sPrevHash to the stream (line 3). We finish off by returning the output of the sha256 method (from the sha256 files we added earlier) using the string output from the string stream (line 5).

Right, let’s finish off our blockchain implementation! Same as before, create a source file for our blockchain and save it as Blockchain.cpp in the main project folder.

Add these lines, which tell the compiler to include the Blockchain.h file we added earlier.

#include "Blockchain.h"

Follow these with the implementation of our blockchain constructor:

Blockchain::Blockchain() {
    _vChain.emplace_back(Block(0, "Genesis Block"));
    _nDifficulty = 6;
}

We start off with the signature for the blockchain constructor we specified in Blockchain.h (line 1). As a blocks are added to the blockchain they need to reference the previous block using its hash, but as the blockchain must start somewhere we have to create a block for the next block to reference, we call this a genesis block. A genesis block is created and placed onto the _vChain vector (line 2). We then set the _nDifficulty level (line 3) depending on how hard we want to make the PoW process.

Now it’s time to add the code for adding a block to the blockchain, add the following lines:

void Blockchain::AddBlock(Block bNew) {
    bNew.sPrevHash = _GetLastBlock().GetHash();
    bNew.MineBlock(_nDifficulty);
    _vChain.push_back(bNew);
}

The signature we specified in Blockchain.h for AddBlock is added (line 1) followed by setting the sPrevHash variable for the new block from the hash of the last block on the blockchain which we get using _GetLastBlock and its GetHash method (line 2). The block is then mined using the MineBlock method (line 3) followed by the block being added to the _vChain vector (line 4), thus completing the process of adding a block to the blockchain.

Let’s finish this file off by adding the last method:

Block Blockchain::_GetLastBlock() const {
    return _vChain.back();
}

We add the signature for _GetLastBlock from Blockchain.h (line 1) followed by returning the last block found in the _vChain vector using its back method (line 2).

Right, that’s almost it, let’s test it out!

Remember the main.cpp file? Now’s the time to update it, open it up and replace the contents with the following lines:

#include "Blockchain.h"

This tells the compiler to include the Blockchain.h file we created earlier.

Then add the following lines:

int main() {
    Blockchain bChain = Blockchain();

    cout << "Mining block 1..." << endl;
    bChain.AddBlock(Block(1, "Block 1 Data"));

    cout << "Mining block 2..." << endl;
    bChain.AddBlock(Block(2, "Block 2 Data"));

    cout << "Mining block 3..." << endl;
    bChain.AddBlock(Block(3, "Block 3 Data"));

    return 0;
}

As with most C/C++ programs, everything is kicked off by calling the main method, this one creates a new blockchain (line 2) and informs the user that a block is being mined by printing to the output buffer (line 4) then creates a new block and adds it to the chain (line 5); the process for mining that block will then kick off until a valid hash is found. Once the block is mined the process is repeated for two more blocks.

Time to run it! If you are using CLion simply hit the ‘Run TestChain’ button in the top right hand corner of the window. If you’re old skool, you can compile and run the program using the following commands from the command line:

gcc -lstdc++ \
    -o TestChain \
    -std=c++11 \
    -stdlib=libc++ \
    -x c++ \
    main.cpp Block.cpp Blockchain.cpp sha256.cpp
./TestChain

If all goes well you should see an output like this:

Mining block 1...
Block mined: 000000c1b50cb30fd8d9a0f2e16e38681cfcf9caead098cea726854925ab3772
Mining block 2...
Block mined: 0000005081063c8c854d11560cfea4fe734bde515a08565c26aa05448eea184e
Mining block 3...
Block mined: 000000ea61810fa85ff636440eb803263daf06b306c607aced9a1f996a421042

Congratulations, you have just written a blockchain from scratch in C++, in case you got lost I’ve put all the files into a Github repo. Since the original code for Bitcoin was also written in C++, why not take a look at its code and see what improvements you can make to what we’ve started off today?

If you have any questions or comments – as always – I’d love to hear them; please put them in the comments below.

How to use JWT with Seneca, Passport and Express on NodeJS

Ever wondered how to get JWT access working on Seneca running through Express? I certainly was! Here’s a quick tutorial showing you the code I put together after reading lots of other blogs and scratching my head.

Start off by creating a workspace, open a command prompt and create a directory called seneca-jwt-tutorial then move inside it:

$ mkdir seneca-jwt-tutorial
$ cd seneca-jwt-tutorial

 

Next we need to initialise npm, feel free to press <ENTER> for all the questions that pop up:

$ npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install  --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (seneca-jwt-tutorial) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/dave/Desktop/seneca-jwt-tutorial/package.json:

{
  "name": "seneca-jwt-tutorial",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)

 

Then we’ll need to install all the packages we’re going to use, these are:

  • body-parser
  • express
  • express-session
  • jsonwebtoken
  • passport
  • passport-jwt
  • seneca
  • seneca-web
  • seneca-web-adapter-express

Use the following command to install them all together:

$ npm install --save body-parser \
  express express-session \
  jsonwebtoken \
  passport passport-jwt \
  seneca seneca-web seneca-web-adapter-express

 

Right, now it’s time to start adding some code, create repo.js which we’ll use to store our user information:

$ touch repo.js

 

Then copy this code into repo.js, it’s an array and a couple of methods to query the values in the array; in a production environment you’d probably want to replace this with something a little more permanent and a bit more secure:

'use strict'

var storage = [
    { id: 1, username: 'jack', password: 'admin', displayName: 'Jack', email: 'jack@example.com' },
    { id: 2, username: 'jill', password: 'admin', displayName: 'Jill', email: 'jill@example.com' }
]

function findById (id, cb) {
    process.nextTick(() => {
        var idx = id - 1

        if (storage[idx]) {
            cb(null, storage[idx])
        }
        else {
            cb(new Error('User ' + id + ' does not exist'))
        }
    })
}

function findByUsername (username, cb) {
    process.nextTick(() => {
        for (var i = 0, len = storage.length; i < len; i++) {
            var record = storage[i]
    
            if (record.username === username) {
                return cb(null, record)
            }
        }

        return cb(null, null)
    })
}

exports.users = {
    findById: findById,
    findByUsername: findByUsername
}

 

Next we create routes.js which we’ll use to map out our routes and pin them to Seneca action patterns:

$ touch routes.js

 

Then copy this code into routes.js, as you can see we are creating three routes, one insecure telling you to login (home), one to handle the login process (login) and another which is secure (profile):

'use strict'

module.exports = [
    {
        pin: 'role:admin,cmd:*',
        map: {
            home: {
                GET: true,
                POST: true,
                alias: '/'
            },
            login: {
                POST: true
            },
            profile: {
                GET: true,
                auth: {
                    strategy: 'jwt',
                    fail: '/',
                }
            }
        }
    }
]

 

Our next task is to create plugin.js where we’ll put the Seneca action patterns for each of our routes:

$ touch plugin.js

 

Next copy this code into plugin.js, a quick look will see that the patterns correspond to the names of the routes, one for home, one for login and the last one for profile. Notice that the login pattern makes use of the repo to find a user by username:

'use strict'

var Jwt = require('jsonwebtoken')
var Repo = require('./repo.js')

module.exports = function plugin (options) {
    var seneca = this;

    seneca.add('role:admin,cmd:home', (msg, done) => {
        done(null, {ok: true, message: 'please log in...'})
    })

    seneca.add('role:admin,cmd:login', (msg, done) => {
        if (msg.args.body.username && msg.args.body.password) {
            var username = msg.args.body.username;
            var password = msg.args.body.password;
        }

        Repo.users.findByUsername(username, (err, user) => {
            if (err) {
                done(err)
            }
            else if (!user) {
                done({ ok: false, err: "no such user found" })
            }
            else if (user.password !== password) {
                done({ ok: false, err: "password did not match" })
            }
            else {
                var payload = {id: user.id};
                var token = Jwt.sign(payload, options.secretOrKey);
                
                done(null, {ok: true, token: token})
            }
        })
    })

    seneca.add('role:admin,cmd:profile', (msg, done) => {
        done(null, {ok: true, user: msg.args.user})
    })
}

 

Finally we create index.js which is where we’ll wire everything up:

$ touch index.js

 

Next copy this code into index.js:

  • Lines 1-16: Require all the packages we’re going to use.
  • Lines 18-20: Create our JWT options object that tells Passport where to look for the token and our chosen secret which you should definitely change when working with production code.
  • Lines 22-37: Create the JwtStrategy and action to check the payload from the token against our repo.
  • Lines 39-45: User serialization and deserialization methods for Passport.
  • Lines 47-52: Create the Express service to handle HTTP requests.
  • Lines 54-71: Create our Seneca configuration and service and tell the server which port it should be listening to.
'use strict'

var BodyParser = require('body-parser')
var Express = require('express')
var Passport = require('passport')
var PassportJwt = require('passport-jwt')
var Seneca = require('seneca')
var Web = require('seneca-web')

var Plugin = require('./plugin.js')
var Repo = require('./repo.js')
var Routes = require('./routes.js')

var ExtractJwt = PassportJwt.ExtractJwt
var JwtStrategy = PassportJwt.Strategy

var jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader()
jwtOptions.secretOrKey = 'ArnoldRimmer'

var strategy = new JwtStrategy(jwtOptions, function(payload, next) {
    console.log('payload received', payload)
    Repo.users.findById(payload.id, (err, user) => {
        if (err) {
            next(err)
        }
        else if (!user) {
            next(null, false)
        }
        else {
            next(null, user)
        }
    })
})

Passport.use(strategy)

Passport.serializeUser((user, cb) => {
    cb(null, user)
})

Passport.deserializeUser((user, cb) => {
    cb(null, user)
})

var app = Express()
app.use(BodyParser.urlencoded({ extended: true }))
app.use(BodyParser.json())
app.use(Passport.initialize())

var config = {
    adapter: require('seneca-web-adapter-express'),
    auth: Passport,
    context: app,
    options: { parseBody: false },
    routes: Routes
}

var seneca = Seneca()
seneca.use(Plugin, { secretOrKey: jwtOptions.secretOrKey })
seneca.use(Web, config)
seneca.ready(() => {
    var server = seneca.export('web/context')()

    server.listen('4000', (err) => {
        console.log(err || 'server started on: 4000')
    })
})

 

Assuming that’s all done and it’s now time to start it up, use the following command:

$ node index.js

 

If all went ahead without a hitch you should see this output:

{"kind":"notice","notice":"hello seneca lckpjngjlfme/1487116033208/8390/3.3.0/-","level":"info","when":1487116033310}
server started on: 4000

 

Now it’s time to get testing, fire up Postman or an equivalent API querying tool and start by sending a GET request to http://localhost:4000 (See the screenshot below for request settings)

 

Then POST the username jack with a password of admin to http://localhost:4000/login (See the screenshot below for request settings)

 

You should then be rewarded with a JSON Web Token, which you can use in an Authorization header prepended with JWT:

Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNDg3MTE5MzQ0fQ.i5X2qOAdSGFahPZtFak-KpOXHA0tpLEaSfRpMn-CwM8

 

Copy the contents of token and add it to an Authorization and send a GET request to http://localhost:4000/profile (See the screenshot below for request settings)

 

If you get back a similar response to the one shown above, you’re done. If you found any problems with this tutorial please let me know in the comments, similarly if you found this tutorial helpful please feel free to let me know too!