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.

And replace it with this text.

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:

With this line:

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:

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

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:

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:

So the page should now look like this:

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:

So the file should now look like this:

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:

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.

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():

So the contents should now look like this:

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:

So the file should now look like this:

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:

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

So the whole file should look like this:

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:

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:

The whole file should now look like this:

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:

So the whole file should now look like this:

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:

So now the file should look like this:

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:

So the file should now look like this:

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

So the whole file should now look like this:

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):

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

Add this line below it:

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:

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):

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:

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.

Follow these with the implementation of our block constructor:

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:

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!

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:

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.

Follow these with the implementation of our blockchain constructor:

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:

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:

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:

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

Then add the following lines:

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:

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

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:

 

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

 

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:

 

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

 

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:

 

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

 

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):

 

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

 

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:

 

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

 

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.

 

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

 

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

 

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:

 

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!