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:

CREATEDatabase
MemoryGame

GO

USE [MemoryGame]

GO

CREATETABLE
[dbo].[Challenger](

[ChallengerID] [int] IDENTITY(1,1)
NOTNULL,

[FirstName] [varchar](50)
NOTNULL,

[LastName] [varchar](50)
NOTNULL,

[Email] [varchar](50)
NULL,

CONSTRAINT[PK_Challenger] PRIMARYKEY
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

CREATETABLE
[dbo].[Rank](

[RankID] [int] IDENTITY(1,1)
NOTNULL,

[ChallengerID] [int]
NOTNULL,

[Best] [tinyint]
NOTNULL,

[DateAchieved] [datetime]
NOTNULL,

CONSTRAINT[PK_Rank] PRIMARYKEY
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.

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

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

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

Figure 16: Test Connection

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

In the next wizard, Click “Next”

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

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:

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.

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:

usingMemoryGame.API.Models.DataManager;

usingMemoryGame.API.Models.DB;

usingSystem.Collections.Generic;

usingSystem.Web.Http;

namespaceMemoryGame.API.API

{

publicclass
GameController : ApiController

{

GameManager _gm;

publicGameController()

{

_gm =
new
GameManager();

}

publicIEnumerable<ChallengerViewModel> Get()

{

return_gm.GetAll;

}

[HttpPost]

publicHTTPApiResponse AddPlayer(Challenger user)

{

return_gm.AddChallenger(user);

}

[HttpPost]

publicvoid
AddScore(Rank user)

{

_gm.UpdateCurrentBest(user);

}

[HttpPost]

publicHTTPApiResponse DeletePlayer(intid)

{

return_gm.DeleteChallenger(id);

}

publicint
GetPlayerID(string
email)

{

return_gm.GetChallengerID(email);

}

publicChallengerViewModel GetPlayerProfile(stringemail)

{

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:

Install Microsoft.AspNet.WebApi.Cors via nugget

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

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:

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

namespaceMemoryGame.App.Services

{

publicinterface
IHaptic

{

voidActivateHaptic();

}

}

The ILocalDataStore Interface

namespaceMemoryGame.App.Services

{

publicinterface
ILocalDataStore

{

voidSaveSettings(stringfileName, stringtext);

stringLoadSettings(stringfileName);

}

}

The ISound Interface

namespaceMemoryGame.App.Services

{

publicinterface
ISound

{

boolPlayMp3File(stringfileName);

boolPlayWavFile(stringfileName);

}

}

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:

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:

usingPlugin.Connectivity;

namespaceMemoryGame.App.Helper

{

publicstatic
classStringExtensions

{

publicstatic
intToInteger(thisstring
numberString)

{

intresult = 0;

if(int.TryParse(numberString,
out
result))

returnresult;

return0;

}

}

publicstatic
classUtils

{

publicstatic
boolIsConnectedToInternet()

{

returnCrossConnectivity.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:

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

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 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 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 Output

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

b

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:

usingMicrosoft.Owin;

usingOwin;

[assembly: OwinStartup(typeof(MemoryGame.Web.Startup))]

namespaceMemoryGame.Web

{

publicclass
Startup

{

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

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:

usingSystem.Web.Mvc;

namespaceMemoryGame.Web.Controllers

{

publicclass
HomeController : Controller

{

publicActionResult Index()

{

returnView();

}

}

}

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:

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.