Using Azure {App Services, DocumentDB} with Raspberry Pi sensors running Raspbian.

Annnd Hello!

This is Kinani again, back with a series of blog posts which will be posted across the upcoming months.

Today I’ll be working on a very interesting side project of mine,  actually it’s not really side project. the truth is, that I’m learning how to handle new toys in order to integrate them with my senior Graduation Project, and the best way to learn something is by teaching it to YOU… THE PEOPLE. so let’s begin.

Basically we’re going to store Raspberry Pi’s sensor readings in a relatively new database type from Microsoft called DocumentDB, DocumentDB is a NoSQL database which means there’s no relationships involved between collections, In DocumentDB there’s no tables it’s called ‘Collections’. and collections can store Documents, so in a relational DBs documents are the ‘fields’ in the tables. not just storing we’ll also project the data through an MVC application hosted on Azure.

Why DocumentDB?

  • Elastically scalable (It’s just a JSON Database)
  • Queries with familiar SQL syntax, and yes you can use LINQ.
  • Low latency (less than 10 ms latencies on reads and less than 15 ms latencies on writes) making it a prefect match for IoT solutions!
  • Embedded JavaScript engine, so yeah you can execute JS code right away within the DB. 

Prerequisites

  • Azure subscription, don’t have one? MS got you covered MS Dev Essentials Program offers $25 monthly as credit for free(Will cover the App service part but not DocumentDB, for it you will have to activate the free 30-days free trial.
  • A Raspberry Pi 2 Model B+.
  • A Raspbian operating system running on the Raspberry.
  • Visual Studio 2015 Community Edition.
  • Azure SDK for .NET version 2.5.1 or higher.
  • A sensor (Here I used Ultra sonic HC-SR04 module, and I’ll be continuing this blog post with the assumption of you being aware of how to wire up the module with the Raspberry Pi)

Creating DocumentDB account

From the Azure portal side bar button click New

AzureHome

Then Databases > NoSQL(DocumentDB)

NewDocDB

Fill in the ID for your DocumentDB account, create new Resource Group if needed, and chose the closest location of the data center to you(for better latency)

NewDocDB2

Then wait until the deployment completes, and we’re ready to go.

NecDocDB3

Click on it

NewDocDB4

Then from Keys, we need the following. copy them for later use:

  • Endpoint URL
  • Primary/Secondary Key (either of them will work)

NewDocDB5

Moving on to Visual Studio 2015, Here we’ll start working on the MVC project.

VisualMain

On your keyboard press Ctrl+Shift+N, to create new project, templates -> Visual C# -> Web -> ASP.NET Web Application(.NET framework)

NewProject

Click Ok, and then chose the MVC Template, check Host in the cloud, like the following.

MVCHostCloud

Click OK, and new window will appear to enter your new Azure Web App data.

NewAppService

We’ll now start to add DocumentDB .NET SDK to our project and you can do that by using NuGeT Package Manager Console.

From Tools -> NuGeT Package Manager -> Package Manager Console

And type the following in the Console:

Install-Package Microsoft.Azure.DocumentDB

Accept the License window when it appears.

The next step is to add the Model that will represent our data, In Solution Exlorer, right-click the Models folder, click Add, and then click Class.

AddClass

Enter the name and then click Add

AddClass2

Change the the class code to following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace UltraReadingWeb.Models
{
public class UltraReading
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "reading")]
public string Reading { get; set; }
}
}
view raw UltraReading.cs hosted with ❤ by GitHub

This model is made up of two properties:

  • Id
  • Reading (reading is the actual reading of the sensor)

We have the JsonProperty attribute over each of them for serialization/deserialization, recalling that DocumentDB is just a big JSON container.

We now add the Controller of our MVC, In Solution Explorer, right-click the Controllers folder, click Add, and then click Controller

AddController

Then Add Scaffold dialog appears, select the MVC Controller – Empty, then click Add.

Naming controllers in MVC follows the Model, so in our case we named the Model “UltraReading” so our Controller will be named “UltraReadingController

Before adding the code to our controller, we need to write the code of the DocumentDB driver; as we’ll be using it within the Controller.

Within Solution Explorer, Add new folder named Common

AddNewFolder

Add to the Common folder new class and name it “DocDBRepo

Change the code to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using System.Configuration;
using System.Linq.Expressions;
using System.Threading.Tasks;
using UltraReadingWeb.Common;
namespace UltraReadingWeb.Common
{
public static class DocDBRepo<T> where T : class
{
private static DocumentClient client;
public static void Initialize()
{
client = new DocumentClient(new Uri(Constants.EndPoint)
, Constants.AuthKey);
CreateDatabaseIfNotExistsAsync().Wait();
CreateCollectionIfNotExistsAsync().Wait();
}
private static async Task CreateDatabaseIfNotExistsAsync()
{
try
{
await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(Constants.DatabaseId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDatabaseAsync(new Database { Id = Constants.DatabaseId });
}
else
{
throw;
}
}
}
private static async Task CreateCollectionIfNotExistsAsync()
{
try
{
await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(Constants.DatabaseId, Constants.CollectionId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(Constants.DatabaseId),
new DocumentCollection { Id = Constants.CollectionId },
new RequestOptions { OfferThroughput = 1000 });
}
else
{
throw;
}
}
}
public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
{
IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
UriFactory.CreateDocumentCollectionUri(Constants.DatabaseId, Constants.CollectionId))
.Where(predicate)
.AsDocumentQuery();
List<T> results = new List<T>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<T>());
}
return results;
}
}
}
view raw DocDBRepo.cs hosted with ❤ by GitHub

Coming to back to the Controller, we now can write it’s logic
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Threading.Tasks;
using UltraReadingWeb.Models;
using UltraReadingWeb.Common;
namespace UltraReadingWeb.Controllers
{
public class UltraReadingController : Controller
{
[ActionName("Index")]
public async Task<ActionResult> IndexAsync()
{
var items = await DocDBRepo<UltraReading>.GetItemsAsync(r => r.Reading != string.Empty);
// Important: Not the best optimized way to do it, acutally it's very harmful to the user exprience.
// You may want to explore another option.
return View(items.Reverse().Take(15));
}
}
}

What we did here is just querying all the Readings that’s not empty, reversing the results, taking the first 15.

Now, we move on to the last piece in MVC, and that’s the View.

In Solution Explorer, expand the Views folder, right-click the empty UltraReading folder that Visual Studio created for you when you added the UltraReadingController earlier, click Add, and then click View.

In the Add View dialog box, do the following:

  • In the View name box, type Index.
  • In the Template box, select List.
  • In the Model class box, select UltraReading (UltraReadingWeb.Models).
  • Leave the Data context class box empty.
  • In the layout page box, type ~/Views/Shared/_Layout.cshtml.

Then click Add.

We edit that View code into the following

@model IEnumerable<UltraReadingWeb.Models.UltraReading>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Reading)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Reading)
</td>
</tr>
}
</table>
view raw index.cshtml hosted with ❤ by GitHub

In that view, we’re just iterating on the Reading property and displaying them each in a table row.

Remember the two important SECRET strings you copied from Azure portal? now we’re gonna use them.

In the Common folder, add new class, name it “Constants“. have it changed to:
** DON’T FORGET TO REPLACE THE DATA WITH YOURS.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UltraReadingWeb.Common
{
public static class Constants
{
public static readonly string DatabaseId = "SensorsReadings";
public static readonly string CollectionId = "UltraSonicCollection";
public static readonly string EndPoint = "YOUR_END_POINT_HERE";
public static readonly string AuthKey = "YOUR_PRIMARY_KEY_HERE";
}
}
view raw Constants.cs hosted with ❤ by GitHub

One last two pieces of code to add is in Global.asax.cs file, in the Application_Start method.

DocDBRepo<UltraReading>.Initialize();
view raw Global.asax.cs hosted with ❤ by GitHub

and the other is in App_Start\RouteConfig.cs

Replace the following line of code:

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
view raw RouteConfig.cs hosted with ❤ by GitHub

to:

defaults: new { controller = "UltraReading", action = "Index", id = UrlParameter.Optional }
view raw RouteConfig.cs hosted with ❤ by GitHub

Here we’re just routing incoming requests to UltraReading controller instead off Home controller.

And we’re done on the ASP Web App part. let’s publish it to Azure, making it public.

Right click on your project and select Publish

Publish

Once the new window is here, all is left to do is to click Publish button, and depending on your Internet speed; this web app will be available to access.

Now, Switching to your Raspberry Pi!

By reaching this stage, you’re expected to:

  • Have your Raspberry Pi connected to the Internet.
  • RPi is running the Raspbian OS/Debian based Linux.
  • Your choice of sensors is already connected to the RPi.

In your RPi bash:

RaspberryNano

once you reach this command:

nano code.py

Continue with the following:

Raspberry

import RPi.GPIO as GPIO
import time
import pydocumentdb.document_client as document_client
masterKey = 'YOUR_PRIMARY_KEY'
host = 'YOUR_END_POINT'
client = document_client.DocumentClient(host, {'masterKey': masterKey})
while True:
GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
print "Distance Measurement In Progress"
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
print "Waiting For Sensor To Settle"
time.sleep(2)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
print "Distance:",distance,"cm"
GPIO.cleanup()
document_definition = {'id': '',
'reading' : distance}
created_document = client.UpsertDocument('dbs/SensorsReadings/colls/UltraSonicCollection',document_definition)
time.sleep(2.0)
view raw code.py hosted with ❤ by GitHub

Remember to replace:

  • YOUR_PRIMARY_KEY
  • YOUR_END_POINT

And also note that this code, is written for the HC-SR04 module.

One last thing worth mentioning, is the URI used with UpsertDocument, it follows the following scheme:

dbs/[database_name]/colls/[collection_name]

RaspberryWorking

And that’s it~!

Final

we’re done here 😀

Github repo: https://github.com/Kinani/UltraReadingWeb

Credits goes to this article, for the ASP web App part:

https://docs.microsoft.com/en-us/azure/documentdb/documentdb-dotnet-application

Backend your application with Azure for free

Hello there, did you ever wanted to create application which have a backend in the cloud?  Okay, if you’re a student with an activated DreamSpark account, You can now activate Azure for FREE.

What’s new?

Microsoft included Azure Mobile Apps to its offer for students “DreamSpark aka Imagine Access”, And that’s GREAT! You can now create and configure your backend on the Cloud for FREE.

What can I do with Azure Mobile Apps?

  • Build engaging iOS, Android, and Windows apps
  • Broadcast push with customer segmentation (Push Notification)
  • Enterprise single sign-on with Active Directory (Authentication)
  • Apps can work offline and sync
  • Social integration with Facebook, Twitter, Google

What could you need more?!

So, today we’re going to create a UWP Application and add a backend to the application using my own DreamSpark offer.

Prerequisites:

Let’s get this done!

We begin by opening Azure Portal, from New -> Web + Mobile -> Mobile App

portal1

 

We enter the App Service Name, make sure that the subscription used is DreamSpark, you can create a new Resource Group If you like (It’s just a way for you to help categorizing your resources), And the app service plan. Click create and wait :d

portal2

 

Congratulations for your first Mobile Service on Azure.

portal3

We click on the service to open it :d All settings -> Quick Start -> Windows C#

portal4

We need a database, a table, and a client(Application) to consume our Mobile service. Creating the database is straightforward.

portal5

To test the Mobile Service, we’ll download Azure Todo App. And we begin by creating a TodoItem table for that app in our database.

You mark “I acknowledge that this will overwrite all site contents.”

Then click “Create TodoItems table”

 

Then we download the project, Build & run it to see the result. (Note that this Pre-configured app is a Windows 8.1 Universal app NOT UWP)

portal7

 

The result:

TodoRuning

Now, we know that our service is running just fine. Time to run something we wrote :d

Events Sample App

What’ll do?

  • Add a new table to our service to CRUD the events.
  • Create a new UWP Project
  • Install AzureMobileService Packages (APIs)
  • Add to App.xaml.cs a MobileServiceClient object (Mobile Service API)
  • Create our MVVM(Model-View-ViewModel)

 

Add a new Events Table

 

We open the service again from Azure, All settings -> Easy tables -> Add

EasyTables

AddTable

Note:

Normally in a production environment, You will definitely have to edit the permissions.

Then We click on the new created Table “EventItem” -> Manage Schema -> Add a Column

TableSchema

TableSchema2

And add the following columns:

eventName , Type : String

eventDate , Type: String

eventPlace , Type: String

TableSchemaFinale

 

We now need to copy MobileServiceClient, remember this? You just need “CONNECT AN EXISTING APP”, then copy your MobileServiceClient code and paste it somewhere as you’ll need it soon, it will be similar to this:

 public static MobileServiceClient MobileService = 
            new MobileServiceClient("https://sssssss.azurewebsites.net");

portal7

One final thing before moving to Visual Studio, you will need to add this variable to your Mobile App Application settings. Why? Check this.

MS_SkipVersionCheck  =  true

SkipCheckVersion

 

Create new UWP project (Events sample app)

Press “Ctrl+Shit+N” or from File -> New -> Project -> Visual C# -> Windows – >Blank App (Universal Windows)

Before we do anything, we need to install the missing packages:

Type this in the console “Install-Package WindowsAzure.MobileServices” and press Enter

PackageManagerConsole

Note:

If you find any erros while following up with me, make sure to right click (or Ctrl + Period) the error then Quick Action & add the missing Usings:

Quick

then

Quick2

 

Now, we open App.xaml.cs and we add the code you copied from Azure Portal previously. Add it within the App Class. Here’s my App.xaml.cs code (Note that I’ve deleted the unnecessary comments)

 sealed partial class App : Application
    {  
        public static MobileServiceClient MobileService = 
            new MobileServiceClient("https://kinanitest.azurewebsites.net");

        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
        
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = false;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            
            if (rootFrame == null)
            {
                
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            
            Window.Current.Activate();
        }

        
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

       
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }

Creating our MVVM:

 

We start by the Model (EventItem.cs)

[JsonProperty(PropertyName = “”)]  // This is for JSON serializing/deserializing

 public class EventItem
    {
        public string Id { get; set; }
        [JsonProperty(PropertyName = "eventName")]
        public string EventName { get; set; }
        [JsonProperty(PropertyName = "eventDate")]
        public string EventDate { get; set; }
        [JsonProperty(PropertyName = "eventPlace")]
        public string EventPlace { get; set; }
    }

 

Then we implement our ViewModel (EventItemViewModel)

What’ll our view model contain?

  • Class to represent the table
  • A Collection to store the table items to use locally
  • A method to insert new event
  • A method to retrieve all events from Cloud (Azure)

EventItemViewModel.cs

 public class EventItemViewModel
    { 
        private IMobileServiceTable<EventItem> eventTable;
        private MobileServiceCollection<EventItem, EventItem> _eventItems;

        public MobileServiceCollection<EventItem,EventItem> EventItems
        {
            get
            {
                return _eventItems;
            }
        }

        public EventItemViewModel()
        {
            try
            {   
                eventTable = App.MobileService.GetTable<EventItem>();
            }
            catch
            {
                // Handle Exception
            }
        }

        public async Task<bool> insertEvent(EventItem newEvent)
        {
            try
            {
                await eventTable.InsertAsync(newEvent);
                _eventItems.Add(newEvent);
                return true;
            }
            catch
            {
                // Handle exception
                return false;
            }
        }

        public async Task<MobileServiceCollection<EventItem, EventItem>> GetEvents()
        {
            try
            {
                _eventItems = await eventTable
                    .ToCollectionAsync();
                return EventItems;
            }
            catch
            {
                // Handle it
                return null;
            }
        }
    }

MainPage.xaml

UI contains only a simple databinding to show our data for the users(which in this case only you) besides 3 text boxes and a button to enter a new data.

MainPageXaml

MainPage.xaml.cs

What we did there?

  • Create a new instance from the View Model
  • Click handler for the button which inserts new event data
  • An override for OnNavigatedTo , which fires when the page is being navigated to 😀 and this handler set the databindings to the local events collection.
 public sealed partial class MainPage : Page
    {
        private EventItemViewModel eventsVM = new EventItemViewModel();
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void InsertEventBtn_Click(object sender, RoutedEventArgs e)
        {
            EventItem newEvent = new EventItem()
            {
                EventName = EventNameTxtBox.Text,
                EventDate = EventDateTxtBox.Text,
                EventPlace = EventPlaceTxtBox.Text
            };
            await eventsVM.insertEvent(newEvent);
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {   
            EventsListView.ItemsSource = await eventsVM.GetEvents();
        }
    }

 

Hi5! You can now go & test your application!

FinalApp

 

On the next blog posts, I’ll continue adding the rest of Azure Mobile Apps other services like Authentication, Notifications… Stay tuned!

Download the full sample form here.

Designig your Azure MySQL DB with a UWP Demo

Hey 🙂

In this blog post we’ll talk about Azure MySQL DB (free for Studentns from Microsoft Imagine Access aka: Dreamspark ) How to design it, Basic UWP todo demo \w/

In a previous blog post I talked about the DB creation process, how to obtain the DB info ( host name, username,  password, connection string) And also how to connect it to a C# Console App.

Now we’ll continue assuming you have your DB info.

Design MySQL DB

We can use many tools to connect to the DB, but here we’ll use the official MySQL Workbench

MySQL Workbench can be downloaded from here along with the Connectors, What’s a Connector?

A Connector is the DB driver that you include in your project to be able to interact and connect to your DB through your application.

After Installing the Workbench with the default settings. We open it:

workbenchMain

 

Then we click the Add button to add a new DB:

AddButton

We insert the DB info then click Ok.

Now we click the New DB to establish a connection.

ClickDB

Here you can do whatever you want to your DB. let’s go and add a Table ( That’s what you will usually do 😀 )

createTable1

Now we start adding the columns we need at our DB, in This case we’ll need only two columns:

  • idtodo : INT, Primary Key, Not Null, Unique, Auto Incremental
  • whatToDO: varchar(200)

createTable2

And

createTable3

 

Then we click apply, wait for a little bit then we review or add any SQL Script wee need, Then click Apply in the wizard.

Note:

You can see the script for creating the table, you can absolutely go and execute your script directly without having to walkthrough what I did here.

createTable4

The table created successfully and ready to use!

createTable5

UWP Demo (Basic Todo app)

Before we begin please note that the Dreamspark free MySQL is limited to 4 concurrently connections. So It will be optimal for your private use or for testing purposes.

What we’ll do?

  • Create the UWP Project
  • Reference the connector
  • Implementing our MVVM (Model-View-ViewModel)

Creating the project

We click File -> New Project -> from the Installed List we click -> Visual C# ->Windows -> Universal -> then Pick the UWP Project: Blank App (Universal Windows)

Reference the connector

addref

Then we click browse and go to the following path, Please note that the “Connector.NET 6.9” version might differ by the time you’re reading this so you should go and look it up yourself.

C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies\RT

We select the connector then we’re ready to go.

Implementing the MVVM

We’ll only create one page that contains a list of our Todo items, and a Text Box with a button to add the Text Box content as a new Todo.

Todo Model:

 public class Todo
    {
        public string whatToDO { get; set; }
        public Todo(string what)
        {
            whatToDO = what;
        }
    }

ViewModel (TodoViewModel.cs):

 public class TodoViewModel
    {
        private static TodoViewModel _todoViewModel = new TodoViewModel();
        private ObservableCollection<Todo> _allToDos = new ObservableCollection<Todo>();

        public ObservableCollection<Todo> AllTodos
        {
            get
            {
                return _todoViewModel._allToDos;
            }
        }

        public IEnumerable<Todo> GetTodos()
        {
            try
            {

                using (MySqlConnection connection = new MySqlConnection("YOUR CONNECTION STRING HERE"))
                {
                    connection.Open();
                    MySqlCommand getCommand = connection.CreateCommand();
                    getCommand.CommandText = "SELECT whatToDO FROM todo";
                    using (MySqlDataReader reader = getCommand.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            _todoViewModel._allToDos.Add(new Todo(reader.GetString("whatToDO")));
                        }
                    }
                }
            }
            catch(MySqlException)
            {
                // Handle it 🙂
            }
                return _todoViewModel.AllTodos;
        }

        public bool InsertNewTodo(string what)
        {
            Todo newTodo = new Todo(what);
            // Insert to the collection and update DB
            try
            {
                using (MySqlConnection connection = new MySqlConnection("YOUR CONNECTION STRING HERE"))
                {
                    connection.Open();
                    MySqlCommand insertCommand = connection.CreateCommand();
                    insertCommand.CommandText = "INSERT INTO todo(whatToDO)VALUES(@whatToDO)";
                    insertCommand.Parameters.AddWithValue("@whatToDO", newTodo.whatToDO);
                    insertCommand.ExecuteNonQuery();
                    _todoViewModel._allToDos.Add(newTodo);
                    return true;

                }
            }
            catch(MySqlException)
            {
                // Don't forget to handle it
                return false;
            }

        }


        public TodoViewModel()
        { }

What we did at GetTodos():

  • Established the connection
  • We opened it
  • Initializing the command ( Query )
  • Execute the command
  • Read incoming values and initializing new Todo objects then adding it to our ObservableCollection for data binding later.

What we did at InsertNewTodo(string what):

  • Started by creating new object of the Todo class & initialize it.
  • Established the connection
  • We opened the connection
  • Initializing the command ( Query )
  • Add the Query string
  • Add any parameters to the Query
  • Execute the command(Query)
  • Add the new Todo to the ObservableCollection
 Note:
MySQL API for WinRT is not supporting SSL connection, So you’ll have to turn it off by adding SslMode=None to your connection string.
App.xaml.cs code:
We just create a public static instance from our ViewModel to be consumed from all over the app.
 public static TodoViewModel TODO_VIEW_MODEL = new TodoViewModel();

MainPage.xaml Code:

Within the Main Grid:

<StackPanel Orientation="Vertical">
            <ListView x:Name="Todos">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock FontSize="25" Text="{Binding whatToDO}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <TextBox x:Name="NewTodoTxtBox" FontSize="25" Header="New Todo:"/>
                <Button x:Name="InsertTodoBtn" Click="InsertTodoBtn_Click" Content="Insert New Todo" 
                 Margin="0,20,0,0"/>
</StackPanel>  

MainPage Code-Behind(within MainPage Class):

 public MainPage()
        {
            this.InitializeComponent();
        }

        private void InsertTodoBtn_Click(object sender, RoutedEventArgs e)
        {
            // Try the the View Model insertion and check externally for result
            App.TODO_VIEW_MODEL.InsertNewTodo(NewTodoTxtBox.Text);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Todos.ItemsSource = App.TODO_VIEW_MODEL.GetTodos();
        }

We’re done!

finalMySQL

 

Download the full sample from here.

 

Camera API usage and sample [Arabic][بالعربي]

 

في اولى مدوناتي بالعربي! هنتكلم النهاردا عن ازاي نتستخدم الكاميرا وتطبيقها في مثال، هحاول أتكلم بالفصحى على قدر الإمكان عشان اوصل لأكبر قدرممكن من الجمهورالعربي.

لنبدأ!

 

في البداية نقوم بفتح Project جديد في Visual Studio 2015
ونختار
Universal Windows 

 CreateProject

 

بعد ذلك نقوم بانشاءالواجهة UI للبرنامج وسوف يكون البرنامج مكون من شاشة واحدة وعليها جميع الـ Controls الازمة.

Visual Studio يقومافتراضياً بانشاء الـ MainPage لك.

نقومباختيار 13”Desktop لتحكم وشاشة اكبر.

MainPageUIChoseDesktop

 

نبدأبكتابة الـ XAML للـ MainPage هنا :


XAMLDesigner

الان، الواجهة UI مكونة من مكونين رئيسين :
نافذة للكاميرا
وشريط أدوات بالأسفل للـ
Controls الأخرى المتعلقة بالكاميرا مثل التسجيل وايقافه الخ..

نبدأبتقسيم الـ UI الي Rows :

XAMLRowsDeff

اول Row للكاميرا والآخر للـ Controls الأخرى

بعد ذلك نقوم بوضع الكائن الخاص بالكاميرا والـ Controls بالاضافة كائن اضافي سآتي على ذكره لاحقاً في وقت استخدامه، تجاهله الآن 🙂

FullXAML

 

هنا قمنا
باستخدام :
CaptureElement :للكاميرا

MediaElement :لاحقا 😀

بالاضافة لل Controlsالمحتواة بداخل CommandBar

هذا هوالشكل النهائي للـ UI
UIFinal

نبدأ الان
بكتابة الـ
Code-Behind للـ MainPage يُطلق عليه أحياناًالـ Logic لانه بالفعل مايعطي لبرنامجك منطقاً او بمعنى آخر يبدأ بتنفيذ وظائفه، لانه على وضعه الحالي ليس سوى شكل خالِ من المضمون!


للوصول للـ
Code-Behind :
Code-Behind

نبدأبكتابة الـ Fields الخاصة بنا والمكونة من :

MediaCapture :يعتبر هذا الـClass العمود الفقري لأي برنامج يستخدم الكاميرا.

MediaCaptureInitializationSettings :يبدوا من الاسم ما هو وظيفته ! يقوم بتهيئة الـ MediaCapture

private StorageFolder folder = ApplicationData.Current.LocalFolder

مجرد اختصار للوصول للمجلد الخاص بالبرنامج بحيث يمكنك الوصول اليه باستخدام folder فقط بدلاً من ApplicationData.Current.LocalFolder

captureFile :الملف الذي سنقوم بالكتابة فيه، ماذا سنكتب؟ بالتأكيد الفيديو المُسجل بالكاميرا.

 

fileNameForURI :تجاهله الان.شكراً 🙂

نقوم الآن بكاتبة هذه ال Method وظيفتها كما يبدو من اسمها، عند الدخول الى الـ Page تقوم بالعمل وهناك ايضاً نقيضها وهو OnNavigatedFrom لكن لن نستخدمها هنا، بسبب ان برنامجنا مكون من Page واحدة فقط فلا داعي لها.
OnNavigatedTo

 


نقومبكتابة التالي بداخلها :

OnNavigatedToFULL

ووظيفة هذا الكود :
يقوم بتهيئة الـ
MediaCapture و انشاء Object منه لنتعامل معه ،ونفس الوضع معMediaCaptureInitializationSettings

بعد ذلك نبدأ باخبار هذاالـ
Objectعن نوع الـ Input 

نقوم بتمرير هذا الـ Object الخاص بالتهيئة للـ mediaCapture بعد ذلك نحن جاهزين لنربط الـ CaptureElement
بالـ
mediaCapture ،وللتذكير فقد كان اسمها :
camPreviewName

 

الان نحن جاهزين لنبدأ الـ Preview اوبمعنى آخراظهار الصورة للمستخدم

 

من الآن الي آخر الـ Code سترى الكثير من هذا السطر الكودي  مع اختلاف الـ Controls ،وظيفته فقط هو تفعيل اوعدم تفعيل الـ
Control بمعنى تمكين اوايقاف المستخدم من التعامل مع الـ Control:

this.StopRecordAppBar.IsEnabled = false

بعد ذلك سنقوم بكتابة الـ Controls Click Event Handlers اي الكود الذي سيعمل عند الضغط على اي Control
من الثلاث .

RecordAppBar
RecordAppBarFULL

 

StopRecordAppBar

StopRecordAppBarFULL

 

StartPreviewAppBar

StartPreviewAppBarFULL

وكما ترى هنا فقد جئت على استخدام الكائن او الـObject الذي اخبرتك بتجاهله وظيفة، هذا الكائن بكل بساطه هو عرض الفيديوالمُسجل للمستخدم.

انتهينا ! ممم نوعاً مازال هناك شئ بسيط يجب عمله لكي يعمل البرنامج. وهو أخذ الإذن مُسبقا من نظام التشغيل الذي بدوره يأخذ الاذن من المستخدم باستخدام الكاميرا والميكروفون.

Capabilities

 

مبروك يا ريس:))

Source-Code


 

 

 

 

Using your free MySQL Database from Dreamspark

Now you have been a Dreamspark student for a while, and you still didn’t use your free Azure subscription?! Not anymore now you have a reason to 🙂

And I quote from here:

Microsoft Azure for DreamSpark gets you started with the services you need to develop in the cloud at no cost:

  • Azure App Service Web Apps is a part of a fully managed cloud offering that enables you to build and deploy web apps in seconds. Use ASP.NET, Java, PHP, Node.js or Python. Run popular web apps and CMS solutions. Set up continuous integration and deployment workflows with VSO, GitHub, TeamCity, Hudson or BitBucket – enabling you to automatically build, test and deploy your web app on each successful code check-in or integration tests.
  • MySQL Database from ClearDB adds the power of MySQL to your Web Apps. With clearDB MySQL you can deploy more kinds of web apps and CMS solutions such as WordPress, Joomla, Acquia Drupal, phpBB, and more.
  • Application Insights provides a 360° view across availability, performance and usage of your ASP.NET services and mobile applications for Windows Phone, iOS and Android platforms. Search and analyze your data to continuously improve your application, prioritize future investments and improve overall customer experience.
  • Visual Studio Online is the fastest and easiest way yet to plan, build, and ship software across a variety of platforms. Get up and running in minutes on our cloud infrastructure without having to install or configure a single server.

Yeah pretty awesome!

So today we’re going to create our database then connect it to our C# code, Let’s dive in.

First we log in to Azure portal , then New -> Data + Storage

NewDataStorage

We chose MySQL Database

NewMySQL

Then we type the database name, and make sure that Pricing Tier is set to Mercury ( as it’s the only free tier )

We chose the closet location for Servers according to your geological location, Accept the Legal Terms, Then we’re ready to create!

Note that Database username and password are set to you automatically.PricingTierMercury

We wait the database to finish creating

Creating

To connect to any MySQL Database we need a ConnectionString that includes:

  • Database name
  • Host/server name
  • User Id (username)
  • Password

To retrieve the connection string we click on the MySQL database you just created -> All settings -> Properties :

SQLMain

We copy the Connection String

ConnectionString

Keep it safe and secret away from bad guys.


Connection Time 🙂

Before making a connection you need to download the .NET Connector and reference it within your project.
To download it you have two options :

  1. Download MySQL Installer ( Preferred )
  2. Include a NuGet Package.

After whatever option you made, it’s time to reference MySQL to your C# project:

AddRefrence

At Extensions We look for MySQL.Data and add it.

Then we need to add this line of code within the usings section

 using MySql.Data.MySqlClient;  

We’re ready to go! here’s my full console code:

 using MySql.Data.MySqlClient;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace ForBlogConsole  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       string connectionString = "your connection string";  
       MySqlConnection conn = new MySqlConnection(connectionString);  
       try  
       {  
         conn.Open();  
         Console.WriteLine("Connection Openned!, And MySQL server version is: {0}", conn.ServerVersion);  
       }  
       catch(Exception ex)  
       {  
         Console.WriteLine("Error: {0}", ex.ToString());  
       }  
     }  
   }  
 }  

The result :

ConnectionMade

The next post of this series will be about designing your MySQL database and implementing the basic operations on it.

SQLite with UWP

Windows  10 is here! And yeah it’s the exact right time for me to start blogging, let’s dive in 🙂
SQLite allows you to store your relational data in a simple easy way, with it’s embedded database engine it gives you a whole new level of efficiency.
So yes, it’s pretty popular among developers. but due to this efficiency and being a self dependent engine it doesn’t give you all the feature you’d use ( merely ) with other databases engines like Microsoft SQL server or whatever you used to.
You can easily download SQLite from SQLite.org !!  there you’ll find SQLite for .NET / C# or if you’re targeting any other platform for sure you’ll find your desired version there.
From a .NET perspective you get a native DLL file (sqlite3.dll) which is as you guessed the SQLite engine, where you can consume the database APIs, using C# you’ll need a wrapper around the C-style APIs to consume it.
There’s some good wrappers out there like :
– SQLite-NET
– SQLite-PCL
– SQLite.Net-PCL ( which we’ll use here )
– etc…
To make SQLite usable for you ( Visual Studio I mean ) we’ll need to install the visual studio extension:
Extension and updates
or you can download it directly from SQLite.org.
After that we reference it to our project ( From Solution Explorer -> References )
Add reference
Don’t forget to include Visual C++ Runtime as it’s a Dependency for SQLite .
ref2
Now we add the wrapper through NuGet manager so we can interact with the database via C# :
chose NuGet
 And chose SQLite.Net-PCL
NuGet
 When creating an Windows App that interact with data, it’s preferred to use the MVVM design Pattern , and that what we will do here.
We start by creating our Model Class which will shape our database Table.
ModelClass
SomeModel.cs code :
 You can shape this class whatever meets your requirements,
 using SQLite.Net.Attributes;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace SQLiteBlog.Model  
 {  
   class SomeModel  
   {  
     [PrimaryKey][AutoIncrement]  
     public int Id { get; set; }  
     public string Name{ get; set; }  
   }  
 }  
Then we get to the ViewModel:
SomeViewModel.cs
ViewModel1
SomeViewModel.cs code :
 using SQLite.Net;  
 using SQLiteBlog.Model;  
 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace SQLiteBlog.ViewModel  
 {  
   class SomeViewModel  
   {  
     private int id;  
     public int Id  
     {  
       get { return id; }  
       set  
       {  
         if (id == value)  
           return;  
         id = value;  
         RaisePropertyChanged("Id");  
       }  
     }  
     private string name = string.Empty;  
     public string Name  
     {  
       get { return name; }  
       set  
       {  
         if (name == value)  
           return;  
         name = value;  
         RaisePropertyChanged("Name");  
       }  
     }  
     public SomeViewModel GetItem(int itemId)  
     {  
       var item = new SomeViewModel();  
       using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))  
       {  
         var _item = (db.Table<SomeModel>().Where(  
           c => c.Id == itemId)).Single();  
         item.Id = _item.Id;  
         item.Name = _item.Name;  
       }  
       return item;  
     }  
     public string SaveItem(SomeViewModel item)  
     {  
       string result = string.Empty;  
       using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))  
       {  
         try  
         {  
           var existingItem = (db.Table<SomeModel>().Where(  
             c => c.Id == item.Id)).SingleOrDefault();  
           if (existingItem != null)  
           {  
             existingItem.Name = item.Name;  
             int success = db.Update(existingItem);  
           }  
           else  
           {  
             int success = db.Insert(new SomeModel()  
             {  
               Name = item.Name  
             });  
           }  
           result = "Success";  
         }  
         catch  
         {  
           result = "This item was not saved.";  
         }  
       }  
       return result;  
     }  
     public string DeleteItem(int itemId)  
     {  
       string result = string.Empty;  
       using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))  
       {  
         var existingItem = dbConn.Query<SomeModel>("select * from SomeModel where Id =" + itemId).FirstOrDefault();  
         if (existingItem != null)  
         {  
           dbConn.RunInTransaction(() =>  
           {  
             dbConn.Delete(existingItem);  
             if (dbConn.Delete(existingItem) > 0)  
             {  
               result = "Success";  
             }  
             else  
             {  
               result = "This item was not removed";  
             }  
           });  
         }  
         return result;  
       }  
     }  
     public event PropertyChangedEventHandler PropertyChanged;  
     protected virtual void RaisePropertyChanged(string propertyName)  
     {  
       var handler = this.PropertyChanged;  
       if(handler != null)  
       {  
         handler(this, new PropertyChangedEventArgs(propertyName));  
       }  
     }  
   }  
 }  

Now the class which will populate your XAML data templates:

ViewModel2

SomeItemsViewModel.cs code:

 using SQLite.Net;  
 using SQLiteBlog.Model;  
 using System;  
 using System.Collections.Generic;  
 using System.Collections.ObjectModel;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace SQLiteBlog.ViewModel  
 {  
   class SomeItemsViewModel : SomeViewModel  
   {  
     private ObservableCollection<SomeViewModel> items;  
     public ObservableCollection<SomeViewModel> Items  
     {  
       get  
       {  
         return items;  
       }  
       set  
       {  
         items = value;  
         RaisePropertyChanged("Items");  
       }  
     }  
     public ObservableCollection<SomeViewModel> GetItems()  
     {  
       items = new ObservableCollection<SomeViewModel>();  
       using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))  
       {  
         var query = db.Table<SomeModel>().OrderBy(c => c.Name);  
         foreach (var _item in query)  
         {  
           var item = new SomeViewModel()  
           {  
             Id = _item.Id,  
             Name = _item.Name  
           };  
           items.Add(item);  
         }  
       }  
       return items;  
     }  
   }  
 }  

As you see this class is inheriting from SomeViewModel.cs, Now we design our views which is here only one view ( MainPage )
MainPage XAML  code :

 <Page  
   x:Class="SQLiteBlog.MainPage"  
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
   xmlns:local="using:SQLiteBlog"  
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
   mc:Ignorable="d">  
   <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
     <Grid.RowDefinitions>  
       <RowDefinition Height="Auto"/>  
       <RowDefinition Height="*"/>  
     </Grid.RowDefinitions>  
     <StackPanel x:Name="MyStackPanel" Grid.Row="0" Margin="20,40,0,0">  
       <TextBox x:Name="NameTextBox" Header="Insert your Name" Margin="0,0,0,20"/>  
       <Button x:Name="RefreshButton" Content="Refresh my data" Click="RefreshButton_Click"/>  
     </StackPanel>  
     <ListView x:Name="MyListView" AutomationProperties.AutomationId="ItemListView"  
       AutomationProperties.Name="Items In Group"  
       TabIndex="1"  
       Grid.Row="1"  
       IsItemClickEnabled="True"  
       ItemClick="ItemView_ItemClick"  
       SelectionMode="Multiple"  
       IsSwipeEnabled="false"  
       Margin="12,0,0,0" Header="Items:" SelectionChanged="MyListView_SelectionChanged">  
       <ListView.ItemTemplate>  
         <DataTemplate>  
           <Grid Height="99" Margin="0,5">  
             <Grid.ColumnDefinitions>  
               <ColumnDefinition Width="Auto"/>  
               <ColumnDefinition Width="*"/>  
             </Grid.ColumnDefinitions>  
             <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="99" Height="99">  
             </Border>  
             <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="12,0,0,0">  
               <TextBlock Text="{Binding Id}" FontSize="30"/>  
               <TextBlock Text="{Binding Name}" FontSize="30"/>  
             </StackPanel>  
           </Grid>  
         </DataTemplate>  
       </ListView.ItemTemplate>  
     </ListView>  
   </Grid>  
 </Page>  

Code Behind for MainPage.cs

 using SQLiteBlog.ViewModel;  
 using System;  
 using System.Collections.Generic;  
 using System.Collections.ObjectModel;  
 using System.IO;  
 using System.Linq;  
 using System.Runtime.InteropServices.WindowsRuntime;  
 using Windows.Foundation;  
 using Windows.Foundation.Collections;  
 using Windows.UI.Xaml;  
 using Windows.UI.Xaml.Controls;  
 using Windows.UI.Xaml.Controls.Primitives;  
 using Windows.UI.Xaml.Data;  
 using Windows.UI.Xaml.Input;  
 using Windows.UI.Xaml.Media;  
 using Windows.UI.Xaml.Navigation;  
 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  
 namespace SQLiteBlog  
 {  
   /// <summary>  
   /// An empty page that can be used on its own or navigated to within a Frame.  
   /// </summary>  
   public sealed partial class MainPage : Page  
   {  
     SomeItemsViewModel itemsViewModel = null;  
     ObservableCollection<SomeViewModel> items = null;  
     public MainPage()  
     {  
       this.InitializeComponent();  
     }  
     private void ItemView_ItemClick(object sender, ItemClickEventArgs e)  
     {  
     }  
     private void MyListView_SelectionChanged(object sender, SelectionChangedEventArgs e)  
     {  
     }  
     private void RefreshButton_Click(object sender, RoutedEventArgs e)  
     {  
       // Note that the entries are being saved to your datbase, so whenever you click  
       // this button you reload the whole database with your new entries.  
       // of course you can implement your flush button to drop the DB, or whatever operation you wanna do 🙂  
       MyListView.ItemsSource = null;  
       itemsViewModel = new SomeItemsViewModel();  
       if (NameTextBox.Text != string.Empty)  
       {  
         itemsViewModel.SaveItem(new SomeViewModel() { Name = NameTextBox.Text });  
       }  
       items = itemsViewModel.GetItems();  
       MyListView.ItemsSource = items;  
     }  
   }  
 }  

One last job to do, We add these couple of lines to our App.xaml.cs ,To solve the red lines issue at our ViewModel class.

LinesForApp

( Note : Please ignore Insights code here )

 

 using SQLite.Net;  
 using SQLiteBlog.Model;  
 using System;  
 using System.Collections.Generic;  
 using System.IO;  
 using System.Linq;  
 using System.Runtime.InteropServices.WindowsRuntime;  
 using System.Threading.Tasks;  
 using Windows.ApplicationModel;  
 using Windows.ApplicationModel.Activation;  
 using Windows.Foundation;  
 using Windows.Foundation.Collections;  
 using Windows.Storage;  
 using Windows.UI.Xaml;  
 using Windows.UI.Xaml.Controls;  
 using Windows.UI.Xaml.Controls.Primitives;  
 using Windows.UI.Xaml.Data;  
 using Windows.UI.Xaml.Input;  
 using Windows.UI.Xaml.Media;  
 using Windows.UI.Xaml.Navigation;  
 namespace SQLiteBlog  
 {  
   /// <summary>  
   /// Provides application-specific behavior to supplement the default Application class.  
   /// </summary>  
   sealed partial class App : Application  
   {  
     public static string DB_PATH = Path.Combine(ApplicationData.Current.LocalFolder.Path, "db.sqlite");  
     public static SQLite.Net.Platform.WinRT.SQLitePlatformWinRT SQLITE_PLATFORM;  
     public App()  
     {  
       Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(  
         Microsoft.ApplicationInsights.WindowsCollectors.Metadata |  
         Microsoft.ApplicationInsights.WindowsCollectors.Session);  
       this.InitializeComponent();  
       this.Suspending += OnSuspending;  
       SQLITE_PLATFORM = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();  
       if (!CheckFileExists("db.sqlite").Result)  
       {  
         using (var db = new SQLiteConnection(SQLITE_PLATFORM, DB_PATH))  
         {  
           db.CreateTable<SomeModel>();  
         }  
       }  
     }  
     private async Task<bool> CheckFileExists(string fileName)  
     {  
       try  
       {  
         var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);  
         return true;  
       }  
       catch  
       {  
       }  
       return false;  
     }  
     /// <summary>  
     /// Invoked when the application is launched normally by the end user. Other entry points  
     /// will be used such as when the application is launched to open a specific file.  
     /// </summary>  
     /// <param name="e">Details about the launch request and process.</param>  
     protected override void OnLaunched(LaunchActivatedEventArgs e)  
     {  
 #if DEBUG  
       if (System.Diagnostics.Debugger.IsAttached)  
       {  
         this.DebugSettings.EnableFrameRateCounter = false;  
       }  
 #endif  
       Frame rootFrame = Window.Current.Content as Frame;  
       // Do not repeat app initialization when the Window already has content,  
       // just ensure that the window is active  
       if (rootFrame == null)  
       {  
         // Create a Frame to act as the navigation context and navigate to the first page  
         rootFrame = new Frame();  
         rootFrame.NavigationFailed += OnNavigationFailed;  
         if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)  
         {  
           //TODO: Load state from previously suspended application  
         }  
         // Place the frame in the current Window  
         Window.Current.Content = rootFrame;  
       }  
       if (rootFrame.Content == null)  
       {  
         // When the navigation stack isn't restored navigate to the first page,  
         // configuring the new page by passing required information as a navigation  
         // parameter  
         rootFrame.Navigate(typeof(MainPage), e.Arguments);  
       }  
       // Ensure the current window is active  
       Window.Current.Activate();  
     }  
     /// <summary>  
     /// Invoked when Navigation to a certain page fails  
     /// </summary>  
     /// <param name="sender">The Frame which failed navigation</param>  
     /// <param name="e">Details about the navigation failure</param>  
     void OnNavigationFailed(object sender, NavigationFailedEventArgs e)  
     {  
       throw new Exception("Failed to load Page " + e.SourcePageType.FullName);  
     }  
     /// <summary>  
     /// Invoked when application execution is being suspended. Application state is saved  
     /// without knowing whether the application will be terminated or resumed with the contents  
     /// of memory still intact.  
     /// </summary>  
     /// <param name="sender">The source of the suspend request.</param>  
     /// <param name="e">Details about the suspend request.</param>  
     private void OnSuspending(object sender, SuspendingEventArgs e)  
     {  
       var deferral = e.SuspendingOperation.GetDeferral();  
       //TODO: Save application state and stop any background activity  
       deferral.Complete();  
     }  
   }  
 }  

We are done !

result

Project source code 🙂