Share via


Fun with Xamarin: Building a Simple Working Memory Game App with Web API and SignalR


Introduction

This article will walk you through on how to build a simple data-driven mobile game application using the power of Xamarin and ASP.NET Web API. We will also build a real-time leader board page using ASP.NET SignalR to monitor player rankings.

Background

This project was born and started as a proof-of-concept application about “Working Memory” in a form of a game. We will use Xamarin and Visual Studio for the following reasons:

  • Xamarin is now fully integrated with the latest Visual Studio release (VS 2017 as of this time of writing).
  • Xamarin allows you to build cross-platform apps (iOS, Andriod, and UWP) using C#.
  • We are an experienced C# developer.
  • Familiarity with Visual Studio development tools.
  • We don't need to learn how to use other frameworks, editors, tools and other programming languages to build native apps.
  • We can take advantage of the cool features provided by Xamarin such as cloud testing and app monitoring.
  • Xamarin and Visual Studio are quite popular and stable platform for building real-world apps.
  • Xamarin has its own dedicated support site. So when you encounter any problem during your development, you can easily post your query to their dedicated forums.

If you have the opportunity to work with a mobile application using Xamarin, then you should be excited as this is getting more popular nowadays. Yes, it's exciting but at the same time scary especially if you don't have any much experience with the technology and mobile devices. This means that you will need to learn from scratch about how everything works with this technology and the Xamarin framework itself. You should be also aware that there's a bit of learning curve to deal with as working with these technologies is completely different compared to web development. This article aims to guide newcomers like you to get started with a simple Mobile game application development.

This article is for .NET developers who are interested in mobile application development. If you are looking for a simple game application that requires some kind of features that connects data from a mobile app to other services such as a REST application or web application, then this article is for you. This article will walk you through on building a simple Working Memory game application using the power of Xamarin and ASP.NET .

Before we dig down further, let’s talk about a bit of Working Memory.

What is a Working Memory?

According to the documentation, a Working Memory is a cognitive system with a limited capacity that is responsible for temporarily holding information available for processing. Working memory is important for reasoning and the guidance of decision-making and behavior. We can say that Working Memory is a crucial brain function that we use to focus our attention and control our thinking. For more information, please see the References section at the end of this book.

What You Will Learn

This article is targeted for beginners to intermediate .NET developers who want to build a data-driven mobile application that connects to other services from scratch and get their hands dirty with a practical example. This article is written in such a way that it’s easy to follow and understand. As you go along and until such time you finished following the article, you will learn how to:

  • Setup a SQL Server database from scratch
  • Build a simple Working Memory game application using Xamarin.Forms that targets both iOS and Android platforms.
  • Create an ASP.NET Web API project
  • Integrate Entity Framework as our data access mechanism
  • Create an ASP.NET MVC 5 project
  • Integrate ASP.NET SignalR within ASP.NET MVC application

Prerequisites

Before you go any further, make sure that you have the necessary requirements for your system and your development environment is properly configured.  This particular demo uses the following tools and frameworks:

  • Visual Studio 2015
  • SQL Server Management Studio Express 2014
  • Xamarin 4.1
  • ASP.NET Web API 2
  • ASP.NET MVC 5
  • ASP.NET SignalR 2.2
  • Entity Framework 6

A basic knowledge of the following language and concept is also required:

  • C#
  • JavaScript
  • AJAX
  • CSS
  • HTML
  • XAML
  • HTTP Request and Response
  • OOP

Development Tools Download

You can download Visual Studio and SQL Server Express edition at the following links:

Five Players, One Goal

As you can see from the prerequisites section, we are going to use various technologies to build this whole game application to fulfill a goal. The diagram below illustrates the high-level process of how each technology connects to each other.

Figure 1: High-level diagram of how each technology interacts

Based on the illustration above, we are going to need to the following projects:

  • A Mobile app
  • A Web API app
  • A Web app

To summarize that, we are going to build a mobile application using (1) Xamarin.Forms that can target both iOS and Android platform. The mobile app is where the actual game is implemented. We will build a (2) Web API project to handle CRUD operations using (3) Entity Framework. The Web API project will serve as the central gateway to handle data request that comes from the mobile app and web app. We will also build a web application to display the real-time dashboard for ranking using (4) ASP.NET MVC and (5) ASP.NET SignalR. Finally, we are going to create a database for storing the player information and their scores in SQL Server.

Game Objective

The objective of this game is very simple; you just need to count how many times: The light will blink on, the speaker will beep and the device will vibrate within a span of time.  The higher your level is, the faster it blinks, beeps and vibrates. This would test how great your memory is.

Game Views

This section will give some visual reference about the outputs of the applications that we are going to build.

Figure 2: Mobile App Welcome View

The very first time you open the app, it will bring the Registration page wherein you could register using your name and email. This page also allows you to log-in using your existing account.

Here’s running view of the Registration page:

Figure 3: Mobile App Register View

Once you registered or after you successfully logged in to the system, it will bring the following page below:

Figure 4: Mobile App Main View

Clicking the “START” button will start playing the game within a short period of time as shown in the figure below:

Figure 5: Mobile App Game View

After the time has elapsed, it will bring you to the result page wherein you can input your answer of how many times each event happened.

Figure 6: Mobile App Answer View

Clicking the “SUBMIT” button will validate your answers whether you got them right and proceed to the next level or restart the game to your current level. Note that your score will automatically be synced to the database once you surpass your current best score.

Here are some of the screenshots of the results:

   

Figure 7: Mobile App Results View

And here’s a screenshot of the real-time web app dashboard for the rankings which triggered by ASP.NET SignalR.

Figure 8: Web App Ranking View

That’s it. Now that you already have some visual reference how the app will look like, it’s time for us to build the app and get our hands dirty with real code examples.

Let’s Begin!

We'll try to keep this demo as simple as possible so starters can easily follow. By “simple”, it means to limit the talking about theories and concepts, but instead jumping directly into the mud and get our hands dirty with code examples.  

Let’s go ahead and fire up Visual Studio and then create a new Blank XAML App (Xamarin.Forms Portable) project as shown in the figure below:

Figure 9: New Project

For this demo, we will name the project as “MemoryGame.App”. Click OK to let Visual Studio generate the default project templates for you.  You should now be presented with this:

Figure 10: Default Generated Files

Note that the solution only contains the .Droid and .iOS projects. This is because I omitted them .Windows project for specific reasons. This means that we will be focusing on Android and iOS apps instead.

The Required NuGet Packages

The first thing we need is to add the required packages that are needed for our application. Now go ahead and install the following packages in all projects:

  • Xam.Plugins.Settings
  • Xam.Plugin.Connectivity

We'll be using the Xam.Plugins.Settings to provide us a consistent, cross-platform settings/preferences across all projects (Portable library, Android, and iOS projects). The Xam.Plugin.Connectivity will be used to get network connectivity information such as network type, speeds, and if a connection is available. We'll see how each of these references is used in action later.

You can install them via PM Console or via NPM GUI just like in the figure below:

Figure 11: Install NuGet Packages

We also need to install the following package under the MemoryGame.App project:

  • Newtonsoft.Json

We will be using Newtonsoft.Json later in our code to serialize and deserialize an object from an API request.

Once you’ve installed them all, you should be able to see them added in your project references just like in the figure below:

Figure 12: References

Setting Up a New Database

The next step is to set up a database for storing the challenger and rank data. Now go ahead and fire-up SQL Server Management Studio and execute the following SQL script below:

CREATE Database  MemoryGame
GO
 
USE [MemoryGame]
GO
 
CREATE TABLE  [dbo].[Challenger](
    [ChallengerID] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](50) NOT NULL,
    [LastName] [varchar](50) NOT NULL,
    [Email] [varchar](50) NULL,
CONSTRAINT [PK_Challenger] PRIMARY KEY  CLUSTERED 
(
    [ChallengerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
            IGNORE_DUP_KEY = OFF, 
            ALLOW_ROW_LOCKS  = ON, 
            ALLOW_PAGE_LOCKS  = ON) 
            ON [PRIMARY]
) ON  [PRIMARY]
 
GO
 
CREATE TABLE  [dbo].[Rank](
    [RankID] [int] IDENTITY(1,1) NOT NULL,
    [ChallengerID] [int] NOT NULL,
    [Best] [tinyint] NOT NULL,
    [DateAchieved] [datetime] NOT NULL,
 CONSTRAINT [PK_Rank] PRIMARY KEY  CLUSTERED 
(
    [RankID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
            IGNORE_DUP_KEY = OFF, 
            ALLOW_ROW_LOCKS  = ON, 
            ALLOW_PAGE_LOCKS  = ON) ON  [PRIMARY]
) ON  [PRIMARY]
 
GO

The SQL script above should create the “MemoryGame” database with the following table:

Figure 13: Database Schema

The database tables that we’ve created earlier are very plain and simple. The dbo.Challenger table just contains some basic properties for us to identify a user who plays the game. The dbo.Rank table holds some basic property to help us identify which user has the highest rank.

Creating the Web API Project

Now that we’ve done setting up our database, it’s time for us to build a REST service to handle database calls and CRUD operations. We are choosing Web API because it’s a perfect fit to build RESTful services in the context of .NET. It also allows other apps (Mobile, Web Apps, and even Desktop Apps) to consume our API via EndPoints. This would enable our application to allow clients to access data in any form of application for as long as it supports HTTP services.

Ok, let’s proceed with our work. Switch back to Visual Studio and then create a new project by right-clicking on the main solution and then select Add > New Project > Visual C# > Web.  Select ASP.NET Web Application (.NET Framework) and name the project as “MemoryGame.API” just like in the figure below:

Figure 14: New Project

Click OK and then select “Empty” from the ASP.NET project template. Check the “Web API” option only and then click Ok to let Visual Studio generate the project for you just like in the figure below:

Figure 15: Default Generated Files

Now that we have our Web API project ready, let’s continue by implementing our Data Access to work with data from the database.

Integrating Entity Framework

For this demo, we’re going to use a Database-First approach with Entity Framework 6 (EF) as our data access mechanism so that we can just program against the conceptual application model instead of programming directly against our database.

What is Entity Framework?

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

This could simply mean that using EF we will be working with entities (class/object representation of your data structure) and letting the framework handle the basic select, update, insert & delete (CRUD operations). In traditional ADO.NET you will write the SQL queries directly against tables/columns/procedures and you don't have entities so it’s much less objecting oriented.

We are going to use EF because it provides the following benefits:

  • Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.
  • Applications are freed from hard-coded dependencies on a particular data engine or storage schema.
  • Mappings between the conceptual model and the storage-specific schema can change without changing the application code.
  • Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.
  • Multiple conceptual models can be mapped to a single storage schema.
  • Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model.     

For more information read: https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx

Setting Up a Data Access

In the MemoryGame.API project, create a new folder called “DB” under the Models folder. Within the “DB” folder, add an ADO.NET Entity Data Model. To do this, just follow these steps:

  1. Right-click on the “DB” folder and then select Add > New Item > ADO.NET Entity Data Model. 

  2. Name the file as “MemoryGameDB” and then click Add.

  3. In the next wizard, select EF Designer from Database.

  4. Click the “New Connection…” button.

  5. Supply the Database Server Name to where you created the database in the previous section.

  6. Select or enter the database name. In this case, the database name for this example is “MemoryGame”.

  7. Click the Test Connection button to see if it’s successful just like in the figure below:

    * 

    Figure 16: Test Connection*

  8. Click OK to generate the connection string that will be used for our application.

  9. In the next wizard, Click “Next”

  10. Select Entity Framework 6.x and then click “Next”

  11. Select the “Challenger” and “Rank” tables and then click “Finish”.

The .EDMX file should now be added to the “DB” folder just like in the figure below:

Figure 17: The Entity Model

What happens there is that EF automatically generates the business objects for you and let you query against it. The EDMX or the entity data model will serve as the main gateway by which you retrieve objects from the database and resubmit changes.

Implementing Data Access for CRUD Operations

The next step is to create a central class for handling Create, Read Update and Delete (CRUD) operations. Now, create a new folder called “DataManager” under the “Models” folder. Create a new class called “GameManager” and then copy the following code below:

using System;
using System.Collections.Generic;
using System.Linq;
using MemoryGame.API.Models.DB;
 
namespace MemoryGame.API.Models.DataManager
{
    #region DTO
    public class  ChallengerViewModel
    {
        public int  ChallengerID { get; set; }
        public string  FirstName { get; set; }
        public string  LastName { get; set; }
        public byte  Best { get; set; }
        public DateTime DateAchieved { get; set; }
    }
    #endregion
 
    #region HTTP Response Object
    public class  HTTPApiResponse
    {
        public enum  StatusResponse
        {
            Success = 1,
            Fail = 2
        }
 
        public StatusResponse Status { get; set; }
        public string  StatusDescription { get; set; }
    }
    #endregion
 
    #region Data Access
    public class  GameManager
    {
        public IEnumerable<ChallengerViewModel> GetAll { get { return GetAllChallengerRank(); } }
 
        public List<ChallengerViewModel> GetAllChallengerRank()
        {
 
            using (MemoryGameEntities db = new MemoryGameEntities())
            {
                var result = (from c in  db.Challengers
                              join r in  db.Ranks on c.ChallengerID equals r.ChallengerID
                              select new  ChallengerViewModel
                              {
                                  ChallengerID = c.ChallengerID,
                                  FirstName = c.FirstName,
                                  LastName = c.LastName,
                                  Best = r.Best,
                                  DateAchieved = r.DateAchieved
                              }).OrderByDescending(o => o.Best).ThenBy(o => o.DateAchieved);
 
                return result.ToList();
            }
        }
 
 
        public HTTPApiResponse UpdateCurrentBest(DB.Rank user)
        {
            using (MemoryGameEntities db = new MemoryGameEntities())
            {
                var data = db.Ranks.Where(o => o.ChallengerID == user.ChallengerID);
                if (data.Any())
                {
                    Rank rank = data.FirstOrDefault();
                    rank.Best = user.Best;
                    rank.DateAchieved = user.DateAchieved;
                    db.SaveChanges();
                }
                else
                {
                    db.Ranks.Add(user);
                    db.SaveChanges();
                }
            }
 
            return new  HTTPApiResponse
            {
                Status = HTTPApiResponse.StatusResponse.Success,
                StatusDescription = "Operation successful."
            };
        }
 
        public int  GetChallengerID(string email)
        {
            using (MemoryGameEntities db = new MemoryGameEntities())
            {
                var data = db.Challengers.Where(o => o.Email.ToLower().Equals(email.ToLower()));
                if (data.Any())
                {
                    return data.FirstOrDefault().ChallengerID;
                }
 
                return 0;
            }
        }
 
        public HTTPApiResponse AddChallenger(DB.Challenger c)
        {
            HTTPApiResponse response = null;
            using (MemoryGameEntities db = new MemoryGameEntities())
            {
                var data = db.Challengers.Where(o => o.Email.ToLower().Equals(c.Email.ToLower()));
                if (data.Any())
                {
                    response =  new  HTTPApiResponse
                    {
                        Status = HTTPApiResponse.StatusResponse.Fail,
                        StatusDescription = "User with associated email already exist."
                    }; 
                }
                else
                {
                    db.Challengers.Add(c);
                    db.SaveChanges();
 
                    response = new  HTTPApiResponse
                    {
                        Status = HTTPApiResponse.StatusResponse.Success,
                        StatusDescription = "Operation successful."
                    };
                }
 
                return response;
            }
        }
 
        public ChallengerViewModel GetChallengerByEmail(string email)
        {
            using (MemoryGameEntities db = new MemoryGameEntities())
            {
                var result = (from c in  db.Challengers
                              join r in  db.Ranks on c.ChallengerID equals r.ChallengerID
                              where c.Email.ToLower().Equals(email.ToLower())
                              select new  ChallengerViewModel
                              {
                                  ChallengerID = c.ChallengerID,
                                  FirstName = c.FirstName,
                                  LastName = c.LastName,
                                  Best = r.Best,
                                  DateAchieved = r.DateAchieved
                              });
                if (result.Any())
                    return result.SingleOrDefault();
            }
            return new  ChallengerViewModel();
        }
 
        public HTTPApiResponse DeleteChallenger(int id)
        {
            HTTPApiResponse response = null;
            using (MemoryGameEntities db = new MemoryGameEntities())
            {
                var data = db.Challengers.Where(o => o.ChallengerID == id);
                if (data.Any())
                {
                    try
                    {
                        var rankData = db.Ranks.Where(o => o.ChallengerID == id);
                        if (rankData.Any())
                        {
                            db.Ranks.Remove(rankData.FirstOrDefault());
                            db.SaveChanges();
                        }
 
                        db.Challengers.Remove(data.FirstOrDefault());
                        db.SaveChanges();
 
                        response = new  HTTPApiResponse
                        {
                            Status = HTTPApiResponse.StatusResponse.Success,
                            StatusDescription = "Operation successful."
                        };
                    }
                    catch (System.Data.Entity.Validation.DbUnexpectedValidationException)
                    {
                        //do stuff
                        response = new  HTTPApiResponse
                        {
                            Status = HTTPApiResponse.StatusResponse.Fail,
                            StatusDescription = "An unexpected error occured."
                        };
                    }
                }
                else
                {
                    response = new  HTTPApiResponse
                    {
                        Status = HTTPApiResponse.StatusResponse.Fail,
                        StatusDescription = "Associated ID not found."
                    };
                }
 
                return response;
            }
        }
    }
    #endregion
}

Let’s take a look of what we just did there.

The code above is composed of three (3) main regions: The Data Transfer Object (DTO), the HTTP response object and the GameMananger class.

The DTO is nothing but just a plain class that houses some properties that will be used in the View or any client that consumes the API.

The HTTPApiResponse object is class that holds 2 main basic properties: Status and StatusDescription. This object will be used in the GameManager class methods as a response or return object.

The GameManager class is the central class where we handle the actual CRUD operations. This is where we use Entity Framework to communicate with the database by working with conceptual data entity instead of real SQL query. Entity Framework enables us to work with a database using .NET objects and eliminates the need for most of the data-access code that developers usually need to write.

The GameManager class is composed of the following methods:

  • GetAll() – A short method that calls the  GetAllChallengerRank() method.
  • GetAllChallengerRank() - Gets all the challenger names and it’s rank.  It uses LINQ to query the model and sort the data.
  • GetChallengerByEmail(string email) – Gets the challenger information and rank by email.
  • GetChallengerID(string email) – Gets the challenger id by passing an email address as a parameter.
  • AddChallenger(DB.Challenger c) – Adds a new challenger to the database.
  • UpdateCurrentBest(DB.Rank user) – Updates the rank of a challenger to then newly achieved high score.
  • DeleteChallenger(int id) – Deletes a challenger from the database.

The Web API EndPoints

Now that we have our data access ready, we can now start creating the API endpoints to serve data.

Create a new folder called “API” within the root of the application. Create a new Web API 2 Controller – Empty class and name it as “GameController” and then copy the following code below:

using MemoryGame.API.Models.DataManager;
using MemoryGame.API.Models.DB;
using System.Collections.Generic;
using System.Web.Http;
 
namespace MemoryGame.API.API
{
    public class  GameController : ApiController
    {
        GameManager _gm; 
        public GameController()
        {
            _gm = new  GameManager();
        }
 
        public IEnumerable<ChallengerViewModel> Get()
        {
            return _gm.GetAll;
        }
 
        [HttpPost]
        public HTTPApiResponse AddPlayer(Challenger user)
        {
            return _gm.AddChallenger(user);
        }
 
        [HttpPost]
        public void  AddScore(Rank user)
        {
            _gm.UpdateCurrentBest(user);
        }
 
        [HttpPost]
        public HTTPApiResponse DeletePlayer(int id)
        {
            return _gm.DeleteChallenger(id);
        }
 
        public int  GetPlayerID(string  email)
        {
            return _gm.GetChallengerID(email);
        }
 
        public ChallengerViewModel GetPlayerProfile(string email)
        {
            return _gm.GetChallengerByEmail(email);
        }
    }
}

Just like in the GameManager class, the GameController API is composed of the following endpoints/ methods:

Method

EndPoint

Description

Get()

api/game/get

Get all the challenger and rank data

AddPlayer(Challenger user)

api/game/addplayer

Adds a new challenger

AddScore(Rank user)

api/game/addscore

Adds or updates a challenger score

DeletePlayer(int id)

api/game/deleteplayer

Removes a player

GetPlayerID(string email)

api/game/getplayerid

Get the challenger id based on email

GetPlayerProfile(string email)

api/game/getplayerprofile

Get challenger information based on email

Enabling Cors

Now that we have our API ready, the final step that we are going to do on this project is to enable Cross-Orgin Resource Sharing (a.k.a CORS). We need this because this API will be consumed in other application that probably has a difference domain.

To enable CORS in ASP.NET Web API, do:

  1. Install Microsoft.AspNet.WebApi.Cors via nugget

  2. Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

    config.EnableCors();
    
  3. Finally, add the [EnableCors] attribute to the GameController class:

    [EnableCors(origins: "http://localhost:60273", headers: "*", methods:  "*")]
    public class  GameController : ApiController
    

Note that you’ll have to replace the value of origins based on the URI of the consuming client. Otherwise, you can use the “*” wild-card to allow any domain to access your API.

Building the Mobile Application with Xamarin Forms

MemoryGame.App(Portable) Project

Now that we have the API ready, we can now start implementing the Memory Game app and start consuming the Web API that we’ve just created earlier. Switch back to MemoryGame.App(Portable) project and then create the following folders:

  • REST
  • Services
  • Classes
  • Pages

The GameAPI Class

Since we’ve done creating out API endpoints earlier, let’s start by creating the class for consuming the API. Create a new class called “GameAPI.cs” under the REST folder and then copy the following code below:

using System;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using MemoryGame.App.Classes;
using System.Net.Http;
 
namespace MemoryGame.App.REST
{
    public class  GameAPI
    {
        private const  string APIUri = "<YOUR API URI>"; //replace this value with the published URI to where your API is hosted. E.g http://yourdomain.com/yourappname/api/game
        HttpClient client;
        public GameAPI()
        {
            client = new  HttpClient();
            client.DefaultRequestHeaders.Host = "yourdomain.com"; >"; //replace this value with the actual domain
            client.MaxResponseContentBufferSize = 256000;
        }
 
        public async Task<bool> SavePlayerProfile(PlayerProfile data, bool  isNew = false)
        {
            var uri = new  Uri($"{APIUri}/AddPlayer");
 
            var json = JsonConvert.SerializeObject(data);
            var content = new  StringContent(json, Encoding.UTF8, "application/json");
 
            HttpResponseMessage response = null;
            if (isNew)
                response = await ProcessPostAsync(uri, content);
 
 
            if (response.IsSuccessStatusCode)
            {
                Settings.IsProfileSync = true;
                return true;
            }
 
            return false;
        }
 
        public async Task<bool> SavePlayerScore(PlayerScore data)
        {
            var uri = new  Uri($"{APIUri}/AddScore");
 
            var json = JsonConvert.SerializeObject(data);
            var content = new  StringContent(json, Encoding.UTF8, "application/json");
            var response = await ProcessPostAsync(uri, content);
 
            if (response.IsSuccessStatusCode)
                return true;
 
            return false;
        }
 
        public async Task<int> GetPlayerID(string email)
        {
            var uri = new  Uri($"{APIUri}/GetPlayerID?email={email}");
            int id = 0;
 
            var response = await ProcessGetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                id = JsonConvert.DeserializeObject<int>(content);
            }
 
            return id;
        }
 
        public async Task<PlayerData> GetPlayerData(string email)
        {
            var uri = new  Uri($"{APIUri}/GetPlayerProfile?email={email}");
            PlayerData player = null;
 
            var response = await ProcessGetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                player = new  PlayerData();
                var content = await response.Content.ReadAsStringAsync();
                player = JsonConvert.DeserializeObject<PlayerData>(content);
            }
 
            return player;
        }
 
        private async Task<HttpResponseMessage> ProcessPostAsync(Uri uri, StringContent content)
        {
            return await client.PostAsync(uri, content); ;
        }
 
        private async Task<HttpResponseMessage> ProcessGetAsync(Uri uri)
        {
            return await client.GetAsync(uri);
        }
    }
}

The code above is pretty much self-explanatory as you could probably guess by its method name. The class just contains some method that calls the API endpoints that we have created in the previous section.

Implementing the Service Interfaces

Next, we will create a few services that our app will need. Add the following class/interface files to the Services folder:

  • IHaptic.cs
  • ILocalDataStore.cs
  • ISound.cs

Now copy the corresponding code below for each file.

The IHaptic Interface
namespace MemoryGame.App.Services
{
    public interface  IHaptic
    {
        void ActivateHaptic();
    }
}
The ILocalDataStore Interface
namespace MemoryGame.App.Services
{
    public interface  ILocalDataStore
    {
        void SaveSettings(string fileName, string text);
        string LoadSettings(string fileName);
    }
}
The ISound Interface
namespace MemoryGame.App.Services
{
    public interface  ISound
    {
        bool PlayMp3File(string fileName);
        bool PlayWavFile(string fileName);
    }
}

The reason why we are creating the services/interfaces above is that iOS and Android have different code implementation on setting the device vibration and sound. That’s why we are defining interfaces so both platforms can just inherit from it and implement code specific logic.

Let’s move on by creating the following objects within the Classes folder:

  • Settings.cs
  • Helper.cs
  • PlayerManager.cs
  • MemoryGame.cs

Before we start, let’s do a bit of clean-up first. Remember we’ve installed the Xam.Plugins.Settings in the previous section right? You will notice that after we installed that library, the Settings.cs file was automatically generated within the Helpers folder. Leaving the Settings.cs file there is fine but we wanted to have a clean separation of objects so we will move the Settings.cs file within the Classes folder. Once you’ve done moving the file that, it’s safe to delete the Helper folder. To summarize the project structure should now look similar to this:

Figure 18: The Settings Class

The Settings Class

Now open the Settings.cs file and then replace the default generated code with the following:

using Plugin.Settings;
using Plugin.Settings.Abstractions;
using System;
 
namespace MemoryGame.App.Classes
{
    public static  class Settings
    {
        private static  ISettings AppSettings => CrossSettings.Current;
 
        public static  string PlayerFirstName
        {
            get => AppSettings.GetValueOrDefault(nameof(PlayerFirstName), string.Empty);
            set => AppSettings.AddOrUpdateValue(nameof(PlayerFirstName), value);
        }
 
        public static  string PlayerLastName
        {
            get => AppSettings.GetValueOrDefault(nameof(PlayerLastName), string.Empty);
            set => AppSettings.AddOrUpdateValue(nameof(PlayerLastName), value);
        }
 
        public static  string PlayerEmail
        {
            get => AppSettings.GetValueOrDefault(nameof(PlayerEmail), string.Empty);
            set => AppSettings.AddOrUpdateValue(nameof(PlayerEmail), value);
        }
 
        public static  int TopScore
        {
            get => AppSettings.GetValueOrDefault(nameof(TopScore), 1);
            set => AppSettings.AddOrUpdateValue(nameof(TopScore), value);
        }
 
        public static  DateTime DateAchieved
        {
            get => AppSettings.GetValueOrDefault(nameof(DateAchieved), DateTime.UtcNow);
            set => AppSettings.AddOrUpdateValue(nameof(DateAchieved), value);
        }
 
        public static  bool IsProfileSync
        {
            get => AppSettings.GetValueOrDefault(nameof(IsProfileSync), false);
            set => AppSettings.AddOrUpdateValue(nameof(IsProfileSync), value);
        }
 
        public static  int PlayerID
        {
            get => AppSettings.GetValueOrDefault(nameof(PlayerID), 0);
            set => AppSettings.AddOrUpdateValue(nameof(PlayerID), value);
        }
 
    }
}

If you notice from the code above, we have defined some basic properties that our app needs.  We are defining them in Settings.cs file so that we can access properties from shared code across all our applications, thus having a central location for shared properties.

The Helper Class

Let’s proceed by creating a new class called “Helper.cs” and then copy the following code below:

using Plugin.Connectivity;
 
namespace MemoryGame.App.Helper
{
    public static  class StringExtensions
    {
        public static  int ToInteger(this string  numberString)
        {
            int result = 0;
            if (int.TryParse(numberString, out  result))
                return result;
            return 0;
        }
    }
 
 
    public static  class Utils
    {
        public static  bool IsConnectedToInternet()
        {
            return CrossConnectivity.Current.IsConnected;
        }
    }
}

The Helper.cs file is composed of two classes: StringExtension and Utils. The StringExtension class contains a ToIntenger() extension method to convert a valid numerical string value into an integer type. The Utils class on the other hand contains an IsConnectedToInternet() method to verify internet connectivity. We will be using these methods later in our application.

The PlayerManager Class

Now let’s create the class for managing the player data and score. Create a new class called “PlayerManager.cs” and then copy the following code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace MemoryGame.App.Classes
{
    #region API DTO's
    public class  PlayerProfile
    {
        public string  FirstName { get; set; }
        public string  LastName { get; set; }
        public string  Email { get; set; }
    }
 
    public class  PlayerScore
    {
        public int  ChallengerID { get; set; }
        public byte  Best { get; set; }
        public DateTime DateAchieved { get; set; }
    }
 
    public class  PlayerData
    {
        public string  FirstName { get; set; }
        public string  LastName { get; set; }
        public byte  Best { get; set; }
        public DateTime DateAchieved { get; set; }
    }
 
    #endregion
 
    public static  class PlayerManager
    {
        public static  void Save(PlayerProfile player)
        {
            Settings.PlayerFirstName = player.FirstName;
            Settings.PlayerLastName = player.LastName;
            Settings.PlayerEmail = player.Email;
        }
 
        public static  PlayerProfile GetPlayerProfileFromLocal()
        {
            return new  PlayerProfile
            {
                FirstName = Settings.PlayerFirstName,
                LastName = Settings.PlayerLastName,
                Email = Settings.PlayerEmail
            };
        }
 
        public static  PlayerScore GetPlayerScoreFromLocal()
        {
            return new  PlayerScore
            {
                ChallengerID = Settings.PlayerID,
                Best = Convert.ToByte(Settings.TopScore),
                DateAchieved = Settings.DateAchieved
            };
        }
 
        public static  void UpdateBest(int score)
        {
            if (Settings.TopScore < score)
            {
                Settings.TopScore = score;
                Settings.DateAchieved = DateTime.UtcNow;
            }
        }
 
        public static  int GetBestScore(int currentLevel)
        {
            if (Settings.TopScore > currentLevel)
                return Settings.TopScore;
            else
                return currentLevel;
        }
 
        public async static Task<bool> Sync()
        {
            REST.GameAPI api = new  REST.GameAPI();
            bool result = false;
 
            try
            {
                if (!Settings.IsProfileSync)
                    result = await api.SavePlayerProfile(PlayerManager.GetPlayerProfileFromLocal(), true);
 
                if (Settings.PlayerID == 0)
                    Settings.PlayerID = await api.GetPlayerID(Settings.PlayerEmail);
 
                result = await api.SavePlayerScore(PlayerManager.GetPlayerScoreFromLocal());
 
            }
            catch
            {
                return result;
            }
 
            return result;
        }
 
        public async static Task<bool> CheckScoreAndSync(int score)
        {
            if (Settings.TopScore < score)
            {
                UpdateBest(score);
                if (Utils.IsConnectedToInternet())
                {
                    var response = await Sync();
                    return response == true ? true : false;
                }
                else
                    return false;
            }
            else
                return false;
        }
 
        public async static Task<PlayerData> CheckExistingPlayer(string email)
        {
            REST.GameAPI api = new  REST.GameAPI();
            PlayerData player = new  PlayerData();
 
            if (Utils.IsConnectedToInternet())
            {
                player = await api.GetPlayerData(email);
            }
 
            return player;
        }
    }
}

The code above is composed of a few methods for handling CRUD and syncing data. Notice that each method calls the method defined in the GameAPI class. We did it like this so we can separate the actual code logic for the ease of maintenance and separation of concerns.

Here’s a quick definition of each methods below:

  • The Save() method saves the player information within the application settings.
  • The GetPlayerProfileFromLocal() method fetches the player information from the application settings.
  • The GetPlayerScoreFromLocal() method fetches the player score details from the application settings.
  • The UpdateBest() method updates the player score details within the application settings.
  • The GetBestScore() method fetches the player top score from the application settings.
  • The asynchronous Sync() method syncs the player profile and score details with data from the database into the local application settings.
  • The asynchronous CheckScoreAndSync() method updates the top score to the database.
  • The asynchronous CheckExistingPlayer() method verifies the existence of a player from the database.

The Required XAML Pages

Now that we are all set, it’s time for us to create the following pages for the app:

  • Register
  • Home
  • Result

Let’s start building the Register page. Right-click on the Pages folder and then select Add > New Item > Cross-Platform > Forms Xaml Page. Name the page as “Register” and then copy the following code below:

The Register Page
<?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="MemoryGame.App.Pages.Register">
 
  <StackLayout VerticalOptions="CenterAndExpand">
    <Label Text="Working Memory Game"
          FontSize="30"
          HorizontalOptions="Center"
          VerticalOptions="CenterAndExpand" />
 
    <Label x:Name="lblWelcome" Text="Register to start the fun, or Log-on to continue the challenge!"
          FontSize="20"
          HorizontalOptions="Center"
          VerticalOptions="CenterAndExpand" />
    <StackLayout x:Name="layoutChoose" Orientation="Horizontal" Spacing="5" VerticalOptions="CenterAndExpand" HorizontalOptions="Center">
      <Button x:Name="btnNew"
           Text="Register"
           FontSize="20"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand"
           Clicked="OnbtnNewClicked"/>
      <Button x:Name="btnReturn"
           Text="Log-on"
           FontSize="20"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand"
           Clicked="OnbtnReturnClicked"/>
    </StackLayout>
 
    <StackLayout x:Name="layoutRegister" VerticalOptions="CenterAndExpand" IsVisible="False">
      <Label Text="First Name" />
      <Entry  x:Name="entryFirstName" />
      <Label Text="Last Name" />
      <Entry  x:Name="entryLastName" />
      <Label Text="Email" />
      <Entry  x:Name="entryEmail" />
 
      <StackLayout  Orientation="Horizontal" Spacing="3" HorizontalOptions="Center">
        <Button x:Name="btnRegister"
               Text="Let's Do This!"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand"
               Clicked="OnbtnRegisterClicked"/>
        <Button x:Name="btnCancelRegister"
               Text="Cancel"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand"
               Clicked="OnbtnCancelRegisterClicked"/>
      </StackLayout>
    </StackLayout>
 
    <StackLayout x:Name="layoutLogin" VerticalOptions="CenterAndExpand" IsVisible="False">
      <Label Text="Email" />
      <Entry  x:Name="entryExistingEmail" />
 
      <StackLayout  Orientation="Horizontal" Spacing="3" HorizontalOptions="Center">
        <Button x:Name="btnLogin"
               Text="Let me in!"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand"
               Clicked="OnbtnLoginClicked"/>
        <Button x:Name="btnCancelLogin"
               Text="Cancel"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand"
               Clicked="OnbtnCancelLoginClicked"/>
      </StackLayout>
    </StackLayout>
  </StackLayout>
</ContentPage>

The mark-up above uses XAML to build the application UI. You may have noticed that it contains some controls such as Buttons and Labels to build the form. Each Buttons has an event attached to it to perform certain action. Here’s the corresponding code behind for the Register page:

using System;
using Xamarin.Forms;
using MemoryGame.App.Classes;
using System.Threading.Tasks;
using MemoryGame.App.Helper;
 
namespace MemoryGame.App.Pages
{
    public partial  class Register : ContentPage
    {
        public Register()
        {
            InitializeComponent();
        }
 
        enum EntryOption
        {
            Register = 0,
            Returning = 1,
            Cancel = 2
        }
 
        protected override  void OnAppearing()
        {
            base.OnAppearing();
            NavigationPage.SetHasBackButton(this, false);
        }
        async void  CheckExistingProfileAndSave(string email)
        {
            if (Utils.IsConnectedToInternet())
            {
                try
                {
                    PlayerData player = await PlayerManager.CheckExistingPlayer(email);
                    if (string.IsNullOrEmpty(player.FirstName) && string.IsNullOrEmpty(player.LastName))
                    {
                        await App.Current.MainPage.DisplayAlert("Error", "Email does not exist.", "OK");
                    }
                    else
                    {
                        Settings.PlayerFirstName = player.FirstName.Trim();
                        Settings.PlayerLastName = player.LastName.Trim();
                        Settings.PlayerEmail = email.Trim();
                        Settings.TopScore = player.Best;
                        Settings.DateAchieved = player.DateAchieved;
 
                        await App._navPage.PopAsync();
                    }
                }
                catch
                {
                    await App.Current.MainPage.DisplayAlert("Oops", "An error occured while connecting to the server. Please check your connection.", "OK");
                }
            }
            else
            {
                await App.Current.MainPage.DisplayAlert("Error", "No internet connection.", "OK");
            }
 
            btnLogin.IsEnabled = true;
        }
 
        void Save()
        {
            Settings.PlayerFirstName = entryFirstName.Text.Trim();
            Settings.PlayerLastName = entryLastName.Text.Trim();
            Settings.PlayerEmail = entryEmail.Text.Trim();
            App._navPage.PopAsync();
        }
 
        void ToggleEntryView(EntryOption option)
        {
            switch (option)
            {
                case EntryOption.Register:
                    {
                        lblWelcome.IsVisible = false;
                        layoutChoose.IsVisible = false;
                        layoutLogin.IsVisible = false;
                        layoutRegister.IsVisible = true;
                        break;
                    }
                case EntryOption.Returning:
                    {
                        lblWelcome.IsVisible = false;
                        layoutChoose.IsVisible = false;
                        layoutRegister.IsVisible = false;
                        layoutLogin.IsVisible = true;
                        break;
                    }
                case EntryOption.Cancel:
                    {
                        lblWelcome.IsVisible = true;
                        layoutChoose.IsVisible = true;
                        layoutRegister.IsVisible = false;
                        layoutLogin.IsVisible = false;
                        break;
                    }
            }
        }
        void OnbtnNewClicked(object sender, EventArgs args)
        {
            ToggleEntryView(EntryOption.Register);
        }
        void OnbtnReturnClicked(object sender, EventArgs args)
        {
            ToggleEntryView(EntryOption.Returning);
        }
        void OnbtnCancelLoginClicked(object sender, EventArgs args)
        {
            ToggleEntryView(EntryOption.Cancel);
        }
        void OnbtnCancelRegisterClicked(object sender, EventArgs args)
        {
            ToggleEntryView(EntryOption.Cancel);
        }
 
        void OnbtnRegisterClicked(object sender, EventArgs args)
        {
            if (string.IsNullOrEmpty(entryFirstName.Text) || string.IsNullOrEmpty(entryLastName.Text) || string.IsNullOrEmpty(entryEmail.Text))
                App.Current.MainPage.DisplayAlert("Error", "Please supply the required fields.", "Got it");
            else
                Save();
        }
 
        void OnbtnLoginClicked(object sender, EventArgs args)
        {
            if (string.IsNullOrEmpty(entryExistingEmail.Text))
                App.Current.MainPage.DisplayAlert("Error", "Please supply your email.", "Got it");
            else
            {
                btnLogin.IsEnabled = false;
                CheckExistingProfileAndSave(entryExistingEmail.Text);
            }
        }
    }
}

The code above is very self-explanatory as you can probably guess by its method name. Let’s continue by building the Home page. Right click on the Pages folder and then select Add > New Item > Cross-Platform > Forms Xaml Page. Name the page as “Home” and then copy the following code below:

The Home Page
<?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="MemoryGame.App.Pages.Home">
 
  <StackLayout Padding="10">
    <StackLayout>
      <StackLayout Orientation="Horizontal">
        <Label x:Name="lblBest" FontSize="20" HorizontalOptions="StartAndExpand" />
        <Button x:Name="btnSync" Text="Sync" Clicked="OnbtnSyncClicked" HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand" />
      </StackLayout>
 
      <Label x:Name="lblTime"
           FontSize="30"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    </StackLayout>
 
    <Label x:Name="lblLevel"
           FontSize="30"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    <StackLayout Orientation="Horizontal" Spacing="3" HorizontalOptions="Center" BackgroundColor="White">
      <Image x:Name="imgLightOff" Source="lightoff.png" WidthRequest="100" HeightRequest="40" />
      <Image x:Name="imgLightOff2" Source="lightoff.png" IsVisible="False" WidthRequest="100" HeightRequest="40" />
      <Image x:Name="imgLightOn" Source="lighton.png" IsVisible="False" WidthRequest="100" HeightRequest="40" />
      <Image x:Name="imgSpeaker" Source="speakeron.png" WidthRequest="100" HeightRequest="40" />
      <Image x:Name="imgHaptic" Source="vibration.png" WidthRequest="100" HeightRequest="40" />
    </StackLayout>
    <Label Text="The light will blink on, the speaker will beep and the device will vibrate at different times. Try to count how many times each one happens."
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
 
    <Button x:Name="btnStart"
            Text="Start"
            HorizontalOptions="Center"
            VerticalOptions="CenterAndExpand"
            Clicked="OnButtonClicked"/>
  </StackLayout>
 
</ContentPage>

Here’s the corresponding code-behind that you will see in Home.xaml.cs

using System;
using System.Threading.Tasks;
using MemoryGame.App.Classes;
using Xamarin.Forms;
using MemoryGame.App.Services;
using MemoryGame.App.Helper;
 
namespace MemoryGame.App.Pages
{
    public partial  class Home : ContentPage
    {
        private static  int _blinkCount = 0;
        private static  int _soundCount = 0;
        private static  int _hapticCount = 0;
        private static  int _level = 1;
 
        public int  _cycleStartInMS = 0;
        public int  _cycleMaxInMS = 7000; // 7 seconds
        private const  int CycleIntervalInMS = 2000; // 2 seconds
        private const  int PlayTimeCount = 3; // 3 types default
 
        enum PlayType
        {
            Blink = 0,
            Sound = 1,
            Haptic = 2
        }
 
        public static  int CurrentGameBlinkCount
        {
            get { return _blinkCount; }
        }
 
        public static  int CurrentGameSoundCount
        {
            get { return _soundCount; }
        }
 
        public static  int CurrentGameHapticCount
        {
            get { return _hapticCount; }
        }
 
        public static  int CurrentGameLevel
        {
            get { return _level; }
        }
 
        public Home()
        {
            InitializeComponent();
        }
 
        protected async override void  OnAppearing()
        {
            base.OnAppearing();
 
            if (string.IsNullOrEmpty(Settings.PlayerFirstName))
                await App._navPage.PushAsync(App._registerPage);
            else
            {
 
                PlayerManager.UpdateBest(_level);
 
                if (Result._answered)
                    LevelUp();
                else
                    ResetLevel();
 
                lblBest.Text = $"Best: Level {PlayerManager.GetBestScore(_level)}";
                lblLevel.Text = $"Level {_level}";
            }
        }
 
        static void  IncrementPlayCount(PlayType play)
        {
            switch (play)
            {
                case PlayType.Blink:
                    {
                        _blinkCount++;
                        break;
                    }
                case PlayType.Sound:
                    {
                        _soundCount++;
                        break;
                    }
                case PlayType.Haptic:
                    {
                        _hapticCount++;
                        break;
                    }
            }
        }
 
        public static  void IncrementGameLevel()
        {
            _level++;
        }
 
        void ResetLevel()
        {
            _level = 1;
            _cycleStartInMS = CycleIntervalInMS;
            lblTime.Text = string.Empty;
        }
 
        async void  StartRandomPlay()
        {
            await Task.Run(() =>
            {
 
                Random rnd = new  Random(Guid.NewGuid().GetHashCode());
                int choice = rnd.Next(0, PlayTimeCount);
 
                switch (choice)
                {
                    case (int)PlayType.Blink:
                        {
                            Device.BeginInvokeOnMainThread(async () =>
                            {
 
                                await imgLightOff.FadeTo(0, 200);
                                imgLightOff2.IsVisible = false;
                                imgLightOff.IsVisible = true;
                                imgLightOff.Source = ImageSource.FromFile("lighton.png");
                                await imgLightOff.FadeTo(1, 200);
 
                            });
                            IncrementPlayCount(PlayType.Blink);
                            break;
                        }
                    case (int)PlayType.Sound:
                        {
                            DependencyService.Get<ISound>().PlayMp3File("beep.mp3");
                            IncrementPlayCount(PlayType.Sound);
                            break;
                        }
                    case (int)PlayType.Haptic:
                        {
                            DependencyService.Get<IHaptic>().ActivateHaptic();
                            IncrementPlayCount(PlayType.Haptic);
                            break;
                        }
                }
            });
        }
 
        void ResetGameCount()
        {
            _blinkCount = 0;
            _soundCount = 0;
            _hapticCount = 0;
        }
 
        void LevelUp()
        {
            _cycleStartInMS = _cycleStartInMS - 200; //minus 200 ms
        }
 
        void Play()
        {
            int timeLapsed = 0;
            int duration = 0;
            Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            {
                duration++;
                lblTime.Text = $"Timer: { TimeSpan.FromSeconds(duration).ToString("ss")}";
 
                if (duration < 7)
                    return true;
                else
                    return false;
            });
 
            Device.StartTimer(TimeSpan.FromMilliseconds(_cycleStartInMS), () => {
                timeLapsed = timeLapsed + _cycleStartInMS;
 
                Device.BeginInvokeOnMainThread(async () =>
                {
                    imgLightOff2.IsVisible = true;
                    imgLightOff.IsVisible = false;
                    await Task.Delay(200);
 
                });
 
                if (timeLapsed <= _cycleMaxInMS)
                {
                    StartRandomPlay();
                    return true; //continue
                }
 
                btnStart.Text = "Start";
                btnStart.IsEnabled = true;
 
                App._navPage.PushAsync(App._resultPage);
                return false; //not continue
            });
        }
 
        void OnButtonClicked(object sender, EventArgs args)
        {
            btnStart.Text = "Game Started...";
            btnStart.IsEnabled = false;
 
            ResetGameCount();
            Play();
        }
 
        async void  OnbtnSyncClicked(object sender, EventArgs args)
        {
 
            if (Utils.IsConnectedToInternet())
            {
                btnSync.Text = "Syncing...";
                btnSync.IsEnabled = false;
                btnStart.IsEnabled = false;
 
                var response = await PlayerManager.Sync();
                if (!response)
                    await App.Current.MainPage.DisplayAlert("Oops", "An error occured while connecting to the server. Please check your connection.", "OK");
                else
                    await App.Current.MainPage.DisplayAlert("Sync", "Data synced!", "OK");
 
                btnSync.Text = "Sync";
                btnSync.IsEnabled = true;
                btnStart.IsEnabled = true;
            }
            else
            {
                await App.Current.MainPage.DisplayAlert("Error", "No internet connection.", "OK");
            }
        }
    }
}

The StartRandomPlay() method above is the core method of the class above. The method is responsible for playing different criteria at random, whether invoke a sound, vibration or just blink an image. Notice that we’ve used the DependencyService class to inject the Interface that we’ve defined in the previous steps. These allow us to call platform-specific methods for playing a sound or vibration.

Now right click on the Pages folder and then select Add > New Item > Cross-Platform > Forms Xaml Page. Name the page as “Result” and then copy the following code below:

The Result Page
<?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="MemoryGame.App.Pages.Result">
 
  <StackLayout>
    <Label Text="How many times did the light blink, the speaker beep and the device vibrate?"
            HorizontalOptions="Center"
            VerticalOptions="CenterAndExpand" />
 
    <StackLayout Orientation="Horizontal" Spacing="3" HorizontalOptions="Center" BackgroundColor="White">
      <Image x:Name="imgLight" Source="lightoff.png" WidthRequest="100" HeightRequest="40" />
      <Image x:Name="imgSpeaker" Source="speakeron.png" WidthRequest="100" HeightRequest="40" />
      <Image x:Name="imgHaptic" Source="vibration.png" WidthRequest="100" HeightRequest="40" />
    </StackLayout>
 
    <StackLayout Orientation="Horizontal" HorizontalOptions="Center" Spacing="5">
      <Picker x:Name="pickerLight" HorizontalOptions="FillAndExpand" WidthRequest="100">
        <Picker.Items>
          <x:String>0</x:String>
          <x:String>1</x:String>
          <x:String>2</x:String>
          <x:String>3</x:String>
          <x:String>4</x:String>
          <x:String>5</x:String>
          <x:String>6</x:String>
          <x:String>7</x:String>
          <x:String>8</x:String>
          <x:String>9</x:String>
          <x:String>10</x:String>
        </Picker.Items>
      </Picker>
      <Picker x:Name="pickerSpeaker" HorizontalOptions="FillAndExpand" WidthRequest="100">
        <Picker.Items>
          <x:String>0</x:String>
          <x:String>1</x:String>
          <x:String>2</x:String>
          <x:String>3</x:String>
          <x:String>4</x:String>
          <x:String>5</x:String>
          <x:String>6</x:String>
          <x:String>7</x:String>
          <x:String>8</x:String>
          <x:String>9</x:String>
          <x:String>10</x:String>
        </Picker.Items>
      </Picker>
      <Picker x:Name="pickerHaptic" HorizontalOptions="FillAndExpand" WidthRequest="100">
        <Picker.Items>
          <x:String>0</x:String>
          <x:String>1</x:String>
          <x:String>2</x:String>
          <x:String>3</x:String>
          <x:String>4</x:String>
          <x:String>5</x:String>
          <x:String>6</x:String>
          <x:String>7</x:String>
          <x:String>8</x:String>
          <x:String>9</x:String>
          <x:String>10</x:String>
        </Picker.Items>
      </Picker>
    </StackLayout>
    <Label x:Name="lblText" FontSize="20"
          HorizontalOptions="Center"
          VerticalOptions="CenterAndExpand" />
    <StackLayout Orientation="Horizontal" HorizontalOptions="Center" Spacing="40">
      <Label x:Name="lblBlinkCount"
          HorizontalOptions="Center"
          VerticalOptions="CenterAndExpand" />
      <Label x:Name="lblBeepCount"
          HorizontalOptions="Center"
          VerticalOptions="CenterAndExpand" />
      <Label x:Name="lblHapticCount"
          HorizontalOptions="Center"
          VerticalOptions="CenterAndExpand" />
    </StackLayout>
    <Button x:Name="btnSubmit"
            Text="Submit"
            HorizontalOptions="Center"
            VerticalOptions="CenterAndExpand"
            Clicked="OnButtonClicked"/>
    <Button x:Name="btnRetry"
           Text="Retry"
           IsVisible="False"
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand"
           Clicked="OnRetryButtonClicked"/>
  </StackLayout>
 
</ContentPage>

Here's the corresponding code behind:

using System;
using Xamarin.Forms;
using MemoryGame.App.Classes;
 
namespace MemoryGame.App.Pages
{
    public partial  class Result : ContentPage
    {
        public static  bool _answered = false;
        public Result()
        {
            InitializeComponent();
            ClearResult();
 
        }
 
        protected override  void OnAppearing()
        {
            base.OnAppearing();
            ClearResult();
            NavigationPage.SetHasBackButton(this, false);
        }
        void ClearResult()
        {
            lblText.Text = string.Empty;
            lblBlinkCount.Text = string.Empty;
            lblBeepCount.Text = string.Empty;
            lblHapticCount.Text = string.Empty;
            pickerLight.SelectedIndex = 0;
            pickerSpeaker.SelectedIndex = 0;
            pickerHaptic.SelectedIndex = 0;
            btnSubmit.IsVisible = true;
            btnRetry.IsVisible = false;
            _answered = false;
        }
 
        bool CheckAnswer(int actualAnswer, int selectedAnswer)
        {
            if (selectedAnswer == actualAnswer)
                return true;
            else
                return false;
        }
 
        void Retry()
        {
            btnSubmit.IsVisible = false;
            btnRetry.IsVisible = true;
        }
        async void  OnButtonClicked(object sender, EventArgs args)
        {
            if (pickerLight.SelectedIndex >= 0 && pickerSpeaker.SelectedIndex >= 0 && pickerHaptic.SelectedIndex >= 0)
            {
                lblText.Text = "The actual answers are:";
                lblBlinkCount.Text = Home.CurrentGameBlinkCount.ToString();
                lblBeepCount.Text = Home.CurrentGameSoundCount.ToString();
                lblHapticCount.Text = Home.CurrentGameHapticCount.ToString();
 
                if (CheckAnswer(Home.CurrentGameBlinkCount, Convert.ToInt32(pickerLight.Items[pickerLight.SelectedIndex])))
                    if (CheckAnswer(Home.CurrentGameSoundCount, Convert.ToInt32(pickerSpeaker.Items[pickerSpeaker.SelectedIndex])))
                        if (CheckAnswer(Home.CurrentGameHapticCount, Convert.ToInt32(pickerHaptic.Items[pickerHaptic.SelectedIndex])))
                        {
                            _answered = true;
                            Home.IncrementGameLevel();
 
                            var isSynced = PlayerManager.CheckScoreAndSync(Home.CurrentGameLevel);
 
                            var answer = await App.Current.MainPage.DisplayAlert("Congrats!", $"You've got it all right and made it to level {Home.CurrentGameLevel}. Continue?", "Yes",  "No");
 
                            if (answer)
                                await App._navPage.PopAsync();
                            else
                                Retry();
                        }
 
                if (!_answered)
                {
                    var isSynced = PlayerManager.CheckScoreAndSync(Home.CurrentGameLevel);
 
                    var answer = await App.Current.MainPage.DisplayAlert("Game Over!", $"Your current best is at level {Home.CurrentGameLevel}. Retry?", "Yes",  "No");
                    if (answer)
                        await App._navPage.PopAsync();
                    else
                        Retry();
                }
            }
        }
 
        void OnRetryButtonClicked(object sender, EventArgs args)
        {
            App._navPage.PopAsync();
        }
    }
}

The code above handles the logic for validating your answers against the actual count of each play type occurred. If all your answers are correct then it will get you the next level, otherwise it resets back.

Implementing Haptic and Sound Service in iOS and Android Platform

Now it’s time for us to implement an actual implementation for each interface that we have defined in the previous steps. Let’s start with Android. Add a new folder called “Services” in the MemoryGame.App.Droid project and then copy the following code for each class:

The Haptic Service (Droid)

using Android.Content;
using Android.OS;
using Xamarin.Forms;
using MemoryGame.App.Droid.Services;
using MemoryGame.App.Services;
 
[assembly: Dependency(typeof(HapticService))]
namespace MemoryGame.App.Droid.Services
{
    public class  HapticService : IHaptic
    {
        public HapticService() { }
        public void  ActivateHaptic()
        {
            Vibrator vibrator = (Vibrator)global::Android.App.Application.Context.GetSystemService(Context.VibratorService);
            vibrator.Vibrate(100);
        }
    }
}

The Sound Service (Droid)

using Xamarin.Forms;
using Android.Media;
using MemoryGame.App.Droid.Services;
using MemoryGame.App.Services;
 
[assembly: Dependency(typeof(SoundService))]
 
namespace MemoryGame.App.Droid.Services
{
    public class  SoundService : ISound
    {
        public SoundService() { }
 
        private MediaPlayer _mediaPlayer;
 
        public bool  PlayMp3File(string  fileName)
        {
            _mediaPlayer = new  MediaPlayer();
            var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName);
            _mediaPlayer.Prepared += (s, e) =>
            {
                _mediaPlayer.Start();
            };
            _mediaPlayer.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
            _mediaPlayer.Prepare();
            return true;
        }
 
        public bool  PlayWavFile(string  fileName)
        {
            //TO DO: Own implementation here
            return true;
        }
    }
}

Note: For Android add the required images under the “drawable” folder and add the sound file to the “raw” folder.

Now, do the same for the MemoryGame.App.iOS project. Copy the following code below for each service:

The Haptic Service (iOS)

using Xamarin.Forms;
using AudioToolbox;
using MemoryGame.App.iOS.Services;
using MemoryGame.App.Services;
 
[assembly: Dependency(typeof(HapticService))]
namespace MemoryGame.App.iOS.Services
{
    public class  HapticService : IHaptic
    {
        public HapticService() { }
        public void  ActivateHaptic()
        {
            SystemSound.Vibrate.PlaySystemSound();
        }
    }
}

The Sound Service (iOS)

using Xamarin.Forms;
using MemoryGame.App.iOS.Services;
using System.IO;
using Foundation;
using AVFoundation;
using MemoryGame.App.Services;
 
[assembly: Dependency(typeof(SoundService))]
 
namespace MemoryGame.App.iOS.Services
{
    public class  SoundService : NSObject, ISound, IAVAudioPlayerDelegate
    {
        #region IDisposable implementation
 
        public void  Dispose()
        {
 
        }
 
        #endregion
 
        public SoundService()
        {
        }
 
        public bool  PlayWavFile(string  fileName)
        {
            return true;
        }
 
        public bool  PlayMp3File(string  fileName)
        {
 
            var played = false;
 
            NSError error = null;
            AVAudioSession.SharedInstance().SetCategory(AVAudioSession.CategoryPlayback, out  error);
 
            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), "mp3");
            var url = NSUrl.FromString(sFilePath);
            var _player = AVAudioPlayer.FromUrl(url);
            _player.Delegate = this;
            _player.Volume = 100f;
            played = _player.PrepareToPlay();
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
                _player = null;
            };
            played = _player.Play();
 
            return played;
        }
    }
 
}

Note: For IOS add the required images and sound file under the Resource folder.

Setting Permissions

For Android, add the following configuration under AndroidManifest.xml

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

The Output

Here’s an actual screenshot of the output when deploying and running the app in real device:

 

Figure 19 & 20: Live Output

Building a Simple Real-time Leaderboard Web App with ASP.NET SignalR and MVC

Before we start, let’s get to know what is ASP.NET Signal is all about.

What is SignalR?

ASP.NET SignalR is a new library for ASP.NET developers that make developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available. SignalR supports Web Sockets, and falls back to other compatible techniques for older browsers. For more information see: https://www.asp.net/signalr

Now, create a new ASP.NET Web Application project and name it as “MemoryGame.Web” just like in the figure below:

Figure 21: New Project

Click “Ok” and then select the “ Empty MVC” template in the next wizard and then hit “OK” again to generate the project for you.

Integrating ASP.NET SignalR

Install “Microsoft.Asp.Net.SignalR” in your project via NuGet. The version used for this project is “2.2”. Once installed, you should be able to see them added to the references folder:

Figure 22: ASP.NET SignalR References

The Microsoft.AspNet.SignalR.Core is responsible for pulling in the server components and JavaScript client required to use SignalR in our application. Microsoft.AspNet.SignalR.SystemWeb contains components for using SignalR  in applications hosted on System.Web.

Adding a Middleware for SignalR

We need to create a middleware for SignalR so we can configure to use it by creating an IApplicationBuilder extention method. Create a new class and name it as “Startup.cs”. Copy the following code below:

using Microsoft.Owin;
using Owin;
 
[assembly: OwinStartup(typeof(MemoryGame.Web.Startup))]
namespace MemoryGame.Web
{
    public class  Startup
    {
        public void  Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

The configuration above will add the SignalR service to the pipeline and enable us to use ASP.NET SignalR in our application.

Adding a Hub

Next is to add an ASP.NET SignalR Hub. Add a new class and then copy the following code below:

using Microsoft.AspNet.SignalR;
 
namespace MemoryGame.Web
{
    public class  LeaderboardHub : Hub
    {
        public static  void Show()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<LeaderboardHub>();
            context.Clients.All.displayLeaderBoard();
        }
    }
}

To provide you a quick overview, the Hub is the centerpiece of the SignalR. Similar to the Controller in ASP.NET MVC, a Hub is responsible for receiving input and generating the output to the client. The methods within the Hub can be invoked from the server or from the client.

If you are new to ASP.NET MVC, I’d recommend you to download my other e-book here: http://www.c-sharpcorner.com/ebooks/asp-net-mvc-5-a-beginner-s-guide

Adding an MVC Controller

Now add a new “Empty MVC 5 Controller” class within the “Controllers” folder and then copy the following code below:

using System.Web.Mvc;
 
namespace MemoryGame.Web.Controllers
{
    public class  HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

The code above is just an action method that throws an Index View.

Adding a View

Add a new Index view within the “Views/Home” folder and then copy the following code below:

<div id="body">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>Leader Board</h1>
            </hgroup>
        </div>
    </section>
    <section class="content-wrapper main-content clear-fix">
        <h1>
            <span>
                Top Challengers
                <img src="Images/goals_256.png" style="width:40px; height:60px;" />
            </span>
        </h1>
        <table id="tblRank" class="table table-striped table-condensed table-hover">
        </table>
    </section>
</div>
 
@section scripts{
    @Scripts.Render("~/Scripts/jquery.signalR-2.2.2.min.js")
    @Scripts.Render("~/signalr/hubs")
 
    <script type="text/javascript">
        $(function () {
            var rank = $.connection.leaderboardHub;
            rank.client.displayLeaderBoard = function () {
                LoadResult();
            };
 
            $.connection.hub.start();
            LoadResult();
        });
 
        function LoadResult() {
            var $tbl = $("#tblRank");
            $.ajax({
                url: 'http://localhost:61309/api/game/get',
                type: 'GET',
                datatype: 'json',
                success: function (data) {
                    if (data.length > 0) {
                        $tbl.empty();
                        $tbl.append('<thead><tr><th>Rank</th><th></th><th></th><th>Best</th><th>Achieved</th></tr></thead>');
                        var rows = [];
                        for (var i = 0; i < data.length; i++) {
                            rows.push('<tbody><tr><td>' + (i +1).toString() + '</td><td>' + data[i].FirstName + '</td><td>' + data[i].LastName + '</td><td>' + data[i].Best + '</td><td>' + data[i].DateAchieved + '</td></tr></tbody>');
                        }
                        $tbl.append(rows.join(''));
                    }
                }
            });
        }
    </script>
}

Take note of the sequence for adding the client Scripts references:

  • jQuery
  • jQuery.signalR
  • /signalr/hub

jQuery should be added first, then the SignalR Core JavaScript and finally the SignalR Hubs script.

The reference to the SignalR generated proxy is dynamically generated JavaScript code, not to a physical file. SignalR creates the JavaScript code for the proxy on the fly and serves it to the client in response to the "/signalr/hubs" URL/. For more information see: https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

The LoadResult() function uses a jQuery AJAX to invoke a Web API call through AJAX GET request. If there’s any data from the response, it will generate an HTML by looping through the rows. The LoadResult () function will be invoked when the page is loaded or when the displayLeaderboard() method from the Hub is invoked. By subscribing to the Hub, ASP.NET SignalR will do the entire complex plumbing for us to do real-time updates without any extra work needed in our side.

Output

Here’s the final output when you deploy and run the project.

Figure 23: Leaderboard page

The data above will automatically update without refreshing the page once a user from the mobile app syncs their best score.

GitHub Repo

You can view and fork the source code here: https://github.com/proudmonkey/Xamarin.MemoryGameApp

Summary

In this article we've learned the following:

  • Setting up a SQL Server database from scratch
  • Building a simple Working Memory game application using Xamarin.Forms that target both iOS and Android platform.
  • Creating an ASP.NET Web API project
  • Integrating Entity Framework as our data access mechanism
  • Creating an ASP.NET MVC 5 project
  • Integrating ASP.NET SignalR within ASP.NET MVC

References: