Monday, October 24, 2016

Configuring your Azure website to use a custom domain

Whenever you create an Azure website you are given a default domain azurewebsites.net to work with. If, for example, your website is named supersite then the fully qualified address for your site would be http://supersite.azurewebsites.net.

Suppose you wish to link your own custom domain to your azure website. As an example, let us assume that we wish to use a custom name like http://code.zift.ca instead of the default name of http://supersite.azurewebsites.net. This tutorial takes you through some very simple and short steps to achieve this.

Before we proceed, it is assumed that you have the following:
  • You must have a domain name that you already own.
  • You have an Azure subscription
1) Go to the Azure portal at http://portal.azure.com and login.

2) Click on your web application in Azure. In the example below, my azure website is named CodeFirstStuff2.

image

3) In the second blade, find and click on “Custom domains”.

image

If, in the third blade, you see a message “Click here to upgrade your App Service to assign custom hostnames to your app.”, then it means that you need to upgrade from the free tier to one that supports custom domains. Click on the above message and you will be reminded that your pricing tier is “F1 Free”, which does not support custom domains. The next tier up is pricing tier “D1 Shared”, which does support custom domains. It, however, costs $11.76 per month (at the time of writing). If you are OK with this additional cost then click on pricing tier “D1 Shared”, then click on the Select button.

image

4) If the third blade looks like below, then you are indeed able to create a custom domains for your Azure website:

image

Note the name at the bottom of the above blade. In this demo it is codefirststuff2.azurewebsites.net. You will need this address in the next important step where you will configure a CNAME DNS record to point to your {your web app name}.azurewebsites.net.

5) This next step involves your domain name registrar. Examples of some domain registrars are: godaddy.com, namecheap.com, fatcow.com, hostgator.com, etc …

Go to your domain registrar and add a CNAME host record that points to the hostname assigned to your Azure site. This is what my CNAME record looked like with my Canadian registrar, where I configured domain name zift.ca to use a host name code:

image

If you are unsure about how to configure the CNAME DNS record, then contact your domain registrar’s support desk and they will be happy to help you.
To prove that your DNS name change has indeed propagated, you can always use a website named https://www.whatsmydns.net/. Here’s what it looked like for me:

image

You can see from the above evidence that the CNAME DNS record change that was made has propagated across our planet (except for Paris, France). Now we can configure Azure with the new host name.

6) Return to Azure’s portal.

image

Click on “+ Add hostname”.

The following will appear in the fourth blade:

image

7) Enter the fully qualified custom address into the Hostname field (example: code.zift.ca), then click on the Validate button.

image

If you get two OKs at the bottom then you are good to go.

image

Click on the “Add hostname” to save your changes.

The real test comes by trying out your custom domain. Point your browser to your custom domain (Example: http://code.zift.ca) and make sure that your website is successfully loaded. I am happy to report that it worked for me when I pointed my Microsoft Edge browser to my custom domain name.

image



Sunday, October 23, 2016

Deploy UWP Windows app into Raspberry Pi 2 device running Windows 10 IoT Core

In a previous post, I discussed building a Windows 10 UWP app that uses EF Core and SQLite. In this post I will show you how to deploy the same application to the Raspberry Pi 2 device running Windows 10 IoT Core. These are the pre-requisites you need to fulfill before continuing with this tutorial:
  • Needless to say, you need to own a Raspberry PI, version 2 or 3, device
  • Your development computer needs to be running the Windows 10 operating system
  • Install Visual Studio 2015. The community edition is more than adequate.
  • A monitor is needed with HDMI input in order to view the UI on the Raspberry Pi device.
  • An Ethernet cable is necessary to connect your development computer to the Raspberry Pi device
  • An HDMI cable to connect the Raspberry Pi device to your monitor.
  • One microSD card that will contain the Windows 10 IoT Core operating system on the Raspberry PI. microSD cards need to be at least 8 GB in size. Slower and older cards are inconsistent when flashing and may fail to work. Class 4 SD cards are not supported and at a minimum Class 10 SD cards should be used.
    View the list of recommended cards.
  • A mouse with a USB connector
  • A keyboard with a USB connector

Installing Windows 10 IoT on your Raspberry Pi device

Once you have all the above in place we are ready to go. The first step is to install Windows 10 IoT Core on the microSD Card.

1) Insert the microSD card into the adapter on your computer.

2) Go to https://developer.microsoft.com/en-us/windows/iot

3) Click on the “Get started now” button.

image

4) Click on the device you have. In my case, I clicked on “Raspberry Pi 2”.

image

5) In step 2, click on “Install onto my blank microSD card”.

image

6) In step 3 click on “Windows 10 IoT Core”.

image

7) Click on Next.

image

8) Since you already have Windows 10 installed on your computer, on the “Get the tools” page, skip straight to step 2 then click on “Download Dashboard”. This will download a setup.exe file onto your computer . Run the setup.exe application to install an application named “Windows 10 IoT dashboard” on your connected microSD card.

image

9) Insert the microSD card into the adapter that is attached to your computer.

10) Start the “Windows 10 IoT dashboard” application on your computer.

image

11) Connect the mouse and keyboard to the Raspberry Pi.

12) Click "Set up a new device".

13) Select “Raspberry Pi” from the dropdown.

14) Enter device name, password and Wi-Fi network to connect to.

15) Download and install Windows 10 IoT Core onto your microSD card.

16) Power OFF your Raspberry Pi device.

17) Remove the microSD  card that is attached to your computer and insert it into the Raspberry Pi device.

18) Connect an HDMI cable between your Raspberry Pi device and monitor.

19) Connect an Ethernet network cable between the Raspberry Pi and your computer.

20) Power ON your Raspberry Pi device. You should see the Windows 10 operating system start screen on the Raspberry Pi device.

image

21) Back in the “Windows 10 IoT dashboard” application on your desktop computer, click on “My Devices”. Your device should get detected and you should see the name, model, and IP address:

image

22) To see that your Raspberry Pi device is indeed connected with your computer, click on your device.

image

23) On your device’s page, click on “Open Windows Device Portal in browser”. You may be asked to enter the administrator password that you previously entered.

image

Feel free to navigate around using the various links to get familiar with what is on your Raspberry Pi Windows 10 IoT device.

Deploy UWP .NET Core app onto your Raspberry Pi device

If you have done my building a Windows 10 UWP app that uses EF Core and SQLite tutorial, then you can deploy that application to your Raspberry Pi. Otherwise, you can create a UWP application from scratch and deploy that instead. For the purpose of this exercise, we will go ahead and create a brand new vanilla UWP app.
  • File >> New >> Project
  • Templates >> Visual C# >> Windows >> Universal
  • Choose the “Blank App (Universal Windows)” template
  • Give the application name IoTDemo then click OK
image
  • Choose minimum version to be same as target version then click OK.
  • Edit MainPage.xaml and add the following code between the opening and closing <Grid> tags:
<TextBlock Text="Hello UWP on Windows 10 IoT core" Margin="200,200,0,0"/>
  • Compile the application then hit Ctrl + F5 to run it on your local machine. You will see the following window appear on your screen:
image
  • Close the above window by clicking on the X in the top-right corner.
  • Choose the ARM processor in Visual Studio
image
  • Select “Remote Machine” for target device.
image
  • The following dialog will appear:
image
  • Go back into the “Windows 10 IoT dashboard” application on your desktop.
  • Click on “My devices” on the left side. Right-click on your Raspberry Pi device and select “Copy IP address”.
image
  • Paste the IP address in the Address field on the Visual Studio “Remote Connections” dialog.
  • For “Authentication Mode” leave it as “Universal (Unencrypted Protocol).
  • Click on the Select button.
  • Click on “Remote Machine” to deploy and run the application on the Raspberry Pi device.
image
  • You may see a warning message like the one below. If you do see such a message and the deployment does not error out, then you are good.
image
  • If all goes well, you should see the UWP app running on your Raspberry PI device:
20161023_180941
20161023_182117

The fact that you can put modern apps on a small and inexpensive networked device like the Raspberry PI opens up a lot of opportunities. I sincerely hope this demo makes you come up with some bright ideas that translate into production ready apps.

Monday, October 17, 2016

Connecting to Azure Website with FTP

There are circumstances when it is necessary to transfer files between your development computer and your Azure website. Here’s how you can connect using the free FileZilla FTP client.
You can download FileZilla from https://filezilla-project.org/download.php.

It is assumed that you have an Azure subscription. Otherwise, you can get a free one month trial subscription at https://azure.microsoft.com/en-us/free.
  • Login into portal.azure.com
image
  • On the left-side, click on “App Services”.
image
  • Click on your website on the first blade. In the above case it is cartoonapi.
image
  • Click on “Deployment credentials” in the second blade.
image
  • Configure the FTP username and password in the third blade then click on Save.
  • The next step is to use these credentials on your FTP client. Start Filezilla:
image
  • Click on File >> Site Manager…
  • Click on the “New Site” button in the “Site Manager” dialog.
image
  • Give the site a name. In my case I called it cartoonapi.
  • Change “Logon Type” to Normal.
  • Go back to the Azure portal and click on Overview in the second blade.
image
  • “Copy the values for “FTP hostname” & “FTP/deployment username” and paste these values into Host and User respectively in Filezilla. Use the “Click to Copy” function in Azure, so that the username and hostname can be copied correctly.
image
  • Enter the Password you configured previously.
  • Click on Connect. You may receive an unknown certificate dialog like this:
image
  • Click on OK. If everything is good, you will be connected to your website and will see the following folders:
image
  • Your website is under the site folder.
This is one way to deploy and also maintain your site. Of course, there are many other much simpler ways, especially from within Visual Studio, where you can do a direct publish from Visual Studio into Azure.

Reference:

https://blogs.msdn.microsoft.com/microsoftimagine/2015/12/22/microsoft-azure-tutorial-how-to-upload-a-website-to-the-cloud-via-ftp/

Sunday, October 16, 2016

Hydrate C# class with data from Azure Web API service

In this post I will give an example on how one can easily hydrate a C# class with data coming from an Azure Web API service. Hydration is used in the context of loading data from a data sources into C# objects. In this case the data source is a Web API service located at http://cartoonapi.azurewebsites.net/api/cartoon.

If you point your browser to this address you will see the following JSON response representing a list of cartoon characters and their respective pictures:

[{"name":"Aladdin","pictureUrl":"images/aladdin.png"},
{"name":"Bambam Rubble","pictureUrl":"images/bambam_rubble.png"},
{"name":"Bambi","pictureUrl":"images/bambi.png"},
{"name":"Barney Rubble","pictureUrl":"images/barney_rubble.png"},
{"name":"Betty Flintstone","pictureUrl":"images/betty_flintstone.png"},
{"name":"Dino","pictureUrl":"images/dino.png"},
{"name":"Donald Duck","pictureUrl":"images/donald_duck.png"},
{"name":"Flintstone Family","pictureUrl":"images/flintstone_family.png"},
{"name":"Flounder","pictureUrl":"images/Flounder.png"},
{"name":"Fred Flinrstone","pictureUrl":"images/fred_flinrstone.png"},
{"name":"Goofy","pictureUrl":"images/Goofy.png"},
{"name":"Jasmine","pictureUrl":"images/jasmine.png"},
{"name":"Jumbo","pictureUrl":"images/jumbo.png"},
{"name":"Mermaid","pictureUrl":"images/mermaid.png"},
{"name":"Micky Mouse","pictureUrl":"images/micky_mouse.png"},
{"name":"Minnie Mouse","pictureUrl":"images/minnie_mouse.png"},
{"name":"Pebbles Flintstone","pictureUrl":"images/pebbles_flintstone.png"},
{"name":"Peter Pan","pictureUrl":"images/peter_pan.png"},
{"name":"Pinocchio","pictureUrl":"images/pinocchio.png"},
{"name":"Pluto","pictureUrl":"images/pluto.png"},
{"name":"Simba","pictureUrl":"images/simba.png"},
{"name":"Snow White","pictureUrl":"images/snow_white.png"},
{"name":"Tigger","pictureUrl":"images/tigger.png"},
{"name":"Tinkerbell","pictureUrl":"images/tinkerbell.png"},
{"name":"Tweety","pictureUrl":"images/tweety.png"},
{"name":"Wilma Flintstone","pictureUrl":"images/wilma_flintstone.png"}]


Let’s build a simple console application. Fire up your Visual Studio 2015 and let’s get started.
  • File >> New >> Project
  • Templates >> Visual C# >> Console Application
  • Name the application WebApiConsoleClient
We need to create a class that closely matches the nature of the Web API JSON object. Therefore, add the following CartoonCharacter class to the console application project:

public class CartoonCharacter {
  public string Name { get; set; }
  public string PictureUrl { get; set; }
}


We need to install the We API Client libraries. To that end, execute the following command from within the Package Manager Console window in Visual Studio 2015:

Install-Package Microsoft.AspNet.WebApi.Client

We can use HttpClient to read CartoonCharacter instances from an HTTP response, without having to write a lot of deserialization code. Add the following global HttpClient declaration right above the Main() method in Program.cs.

static HttpClient client = new HttpClient();

Resolve the namespace for the HttpClient class.

It is necessary to access data from a Web API service asynchronously. Add the following method to Program.cs.

static async Task RunAsync() {
    client.BaseAddress = new Uri("
http://cartoonapi.azurewebsites.net");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try {
        // Get all cartoon characters
        IEnumerable<CartoonCharacter> cartoonCharacters = null;
        HttpResponseMessage response = await client.GetAsync("/api/cartoon");
        if (response.IsSuccessStatusCode) {
            cartoonCharacters = response.Content.ReadAsAsync<IEnumerable<CartoonCharacter>>().Result;
        }

        foreach (var item in cartoonCharacters) {
            Console.WriteLine("Name: {0}\t Picture: {1}", item.Name, item.PictureUrl);
        }
    } catch (Exception e) {
        Console.WriteLine(e.Message);
    }

    Console.ReadLine();
}


In the above code, we first initialize the HttpClient instance with this code:

client.BaseAddress = new Uri("http://cartoonapi.azurewebsites.net");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


The above code sets the base URI for HTTP requests, and sets the Accept header to "application/json", which tells the server to send data in JSON format.

The following code sends a GET request for a  collection of CartoonCharacter instances:

IEnumerable<CartoonCharacter> cartoonCharacters = null;
HttpResponseMessage response = await client.GetAsync("/api/cartoon");
if (response.IsSuccessStatusCode) {
  cartoonCharacters = response.Content.ReadAsAsync<IEnumerable<CartoonCharacter>>().Result;
}


The GetAsync method sends the HTTP GET request. The method needs to be asynchronous, because it performs network I/O. When the method completes, it returns an HttpResponseMessage that contains the HTTP response. If the status code in the response is a success code, the response body contains the JSON representation of a collection of CartoonCharacter objects. Call ReadAsAsync to de-serialize the JSON payload to CartoonCharacter instances.

HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code.

Resolve all classes and do a quick compile to ensure that all is OK.

Add the following statement inside the Main() method to call our asynchronous RunAsync() method:

RunAsync().Wait();

Hit F5 to test your application. Your output should look like this:

image

You should be able to re-purpose the above code for reading from any other Web API service out there.

Reference:

https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Building a Windows 10 UWP app with EF Core and SQLite

We will build a Windows 10 UWP app that uses the following two tables:
image

The Skills table is simply a lookup table that contains a list of skills that will populate a drop-down-list (or combo-box) in our UI.

Create a new UWP app in Visual Studio 2015:
  • File >> New >> Project
  • Templates >> Visual C# >> Windows >> Universal
  • Choose the “Blank App (Universal Windows)” template
  • Give the application name UwpSkills then click OK
image
  • Choose minimum version be same as target version then click OK.
Install SQLite
  • Visual Studio Extension (.vsix)
  • In Visual Studio 2015, install SQLite: Tools >> Extensions and Updates ...
  • Or Download from SQLite.org >> Download page
image

Enter SQLite in the search box. Select “SQLite for Universal App Platform” then click on the Install button.
Why SQLite?
  • SQLite is an open source product
  • The world’s most widely used small database
  • SQLite runs on almost all platforms, including mobile devices
  • There is great support for SQLite in UWP apps
  • Can be easily accessed from C# & VB
  • Rich DB with many features. Not as sophisticated as Oracle or SQL Server
  • Home of SQLite is http://sqlite.org
Install Entity Framework
In order to use SQLite with EF7, we will need to install the EF SQLite:
  • Tools >> NuGet Package Manager >> Package Manager Console
  • Inside the Package Manager Console, run:
Install-Package EntityFramework.SQLite –Version 7.0.0-rc1-final
  • In order to run code first migrations, we will also need to install EF commands packages. Run the following:
Install-Package EntityFramework.Commands –Version 7.0.0-rc1-final
Create your model
It is time to define entity classes and a DB context class that make up your model.
  • Under the project node, create a folder named Models
  • Add a new class named Contact.cs
  • Replace the Contact class name and its contents with the following code:
public class Contact {
   public int ContactId { get; set; }
   [StringLength(40)]
   [Required]
   public string FirstName { get; set; }
   [StringLength(40)]
   [Required]
   public string LastName { get; set; }
   [StringLength(100)]
   [Required]
   public string Email { get; set; }

   public string Skill { get; set; }
   public SkillLookup SkillLookup { get; set; }
}
  • Resolve the namespace for the StringLength annotation.
  • Similarly, create another class inside the Models folder named SkillLookup and replace the class name and its contents with the following code:
public class SkillLookup {
   [Key]
   public string Skill { get; set; }

   public List<Contact> Contacts { get; set; }
}
  • Resolve the namespace for the Key annotation.
  • In the Models folder, add a new class named SkillsContext.
  • Replace the SkillsContext class name and its contents with the following code:
public class SkillsContext : DbContext {
   public DbSet<Contact> Contacts { get; set; }
   public DbSet<SkillLookup> Skills { get; set; }

   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
      string databaseFilePath = "SkillDB.db";
      try {
          databaseFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, databaseFilePath);
      } catch (InvalidOperationException) { }

      optionsBuilder.UseSqlite($"Data source={databaseFilePath}");
   }
}
  • Resolve namespaces for DbSet, Path, and ApplicationData.
  • Build the application to ensure you do not have any compile-time errors.
Create the SQLite database
Now that you have a model, you can use migrations to create the SQLite database.
  • Tools >> NuGet Package Manager >> Package Manager Console
  • In the “Package Manager Console” run the following Package Manager command to scaffold a migration that creates an initial set of tables for your model:
Add-Migration InitialMigration
image
  • Build the application and make sure you do not have any compile-time errors.
  • For testing purposes, we will add dummy data that gets created when the application starts. In the Models folder, add a class named DummyData.
  • Replace the DummyData class name and its contents with the following code:
public static class DummyData {
  public static List<SkillLookup> GetSkills() {
    List<SkillLookup> skills = new List<SkillLookup>() {
      new SkillLookup() {Skill = "Sailor"},
      new SkillLookup() {Skill = "Baker"},
      new SkillLookup() {Skill = "Walker"},
      new SkillLookup() {Skill = "Gardner"},
      new SkillLookup() {Skill = "Carpenter"},
      new SkillLookup() {Skill = "Fisher"},
      new SkillLookup() {Skill = "Harper"},
      new SkillLookup() {Skill = "Winter"},
    };
    return skills;
  }

  public static List<Contact> GetContacts(SkillsContext db) {
    List<Contact> contacts = new List<Contact>() {
      new Contact() {
        FirstName = "Jim",
        LastName = "Sailor",
        Email = "jim@sailor.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Sailor").Skill
      }, new Contact() {
        FirstName = "Jane",
        LastName = "Harper",
        Email = "jane@harper.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Harper").Skill
      }, new Contact() {
        FirstName = "Ed",
        LastName = "Winter",
        Email = "ed@winter.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Winter").Skill
      },
      new Contact() {
        FirstName = "Bob",
        LastName = "Fisher",
        Email = "jim@fisher.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Fisher").Skill
      }, new Contact() {
        FirstName = "Susanne",
        LastName = "Smith",
        Email = "susanne@baker.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Baker").Skill
      }, new Contact() {
        FirstName = "James",
        LastName = "Gardner",
        Email = "james@gardner.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Gardner").Skill
      }, new Contact() {
        FirstName = "Sue",
        LastName = "Carpenter",
        Email = "sue@carpenter.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Carpenter").Skill
      }, new Contact() {
        FirstName = "Perry",
        LastName = "Walker",
        Email = "perry@walker.com",
        Skill = db.Skills.FirstOrDefault(s => s.Skill == "Walker").Skill
      }
    };
    return contacts;
  }
}

  • Once again, do a quick build to ensure that you do not have any compiler errors.
Apply any pending migrations
Since we want the database to be created on the device that the app runs on, we will add some code to apply any pending migrations to the local database on application startup. The first time that the app runs, this will take care of creating the local database for us.
  • Right-click on App.xaml in Solution Explorer and select View Code
Add the following code at the bottom of the class constructor:
using (var db = new SkillsContext()) {
    db.Database.Migrate();

    if (!db.Skills.Any()) {
        db.Skills.AddRange(DummyData.GetSkills());
        db.SaveChanges();

        db.Contacts.AddRange(DummyData.GetContacts(db));
        db.SaveChanges();
    }
}
  • Since Migrate() is an extension method, you will need to add the following using statement
using Microsoft.Data.Entity;
  • Resolve the namespaces for SkillsContext and ApplyMigration.
Building the UI
We will now build a basic user interface so that our application can interact with data.
  • Open MainPage.xaml
  • Add the page load handler inside the root element Page tag:
Loaded="Page_Loaded"
  • Add the following attribute to the <Grid> tag to provide the grid control with a left margin of 200 and a top margin of 100:
Margin="200,100,200,0"
  • Add the following XAML code inside <Grid>:
<Grid.ColumnDefinitions>
   <ColumnDefinition Width="80" />
   <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
   <RowDefinition Height="40" />
   <RowDefinition Height="40" />
   <RowDefinition Height="40" />
   <RowDefinition Height="40" />
   <RowDefinition Height="40" />
   <RowDefinition Height="*" />
</Grid.RowDefinitions>

<TextBlock Text="First Name" Grid.Column="0" Grid.Row="0" />
<TextBox Name="FirstName" Grid.Column="1" Grid.Row="0" Margin="0,0,0,5" />

<TextBlock Text="Last Name" Grid.Column="0" Grid.Row="1" />
<TextBox Name="LastName" Grid.Column="1" Grid.Row="1" Margin="0,0,0,5" />

<TextBlock Text="Email" Grid.Column="0" Grid.Row="2" />
<TextBox Name="Email" Grid.Column="1" Grid.Row="2" Margin="0,0,0,5" />

<TextBlock Text="Skill" Grid.Column="0" Grid.Row="3" />
<ComboBox Name="Skills" Grid.Column="1" Grid.Row="3" 
         DisplayMemberPath="Skill" SelectedValuePath="Skill" Margin="0,0,0,5" />

<Button Click="Add_Click" Grid.Column="1" Grid.Row="4" Margin="0,0,0,5" >Add</Button>

<ListView Name="Contacts" Grid.ColumnSpan="2" Grid.Row="5">
   <ListView.ItemTemplate>
       <DataTemplate>
           <StackPanel Orientation="Horizontal" >
               <TextBlock Text="{Binding FirstName}" />
               <TextBlock Text="{Binding LastName}" Margin="5,0,0,0" />
           </StackPanel>
       </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

Now we will add some code to wire up the UI with our SQLite DB.
  • Right-click MainPage.xaml in Solution Explorer and select View Code
  • Add the following methods to the class:
private void Page_Loaded(object sender, RoutedEventArgs e) {
   using (var db = new SkillsContext()) {
       Skills.ItemsSource = db.Skills.ToList();
       Contacts.ItemsSource = db.Contacts.OrderBy( c => c.FirstName) .ToList();
   }
}

private void Add_Click(object sender, RoutedEventArgs e) {
   using (var db = new SkillsContext()) {
       var contact = new Contact {
           FirstName = FirstName.Text,
           LastName = LastName.Text,
           Email = Email.Text,
           Skill = Skills.SelectedValue.ToString()
       };

       db.Contacts.Add(contact);
       db.SaveChanges();

       Skills.SelectedValue = null;
       FirstName.Text = string.Empty;
       LastName.Text = string.Empty;
       Email.Text = string.Empty;
       Contacts.ItemsSource = db.Contacts.OrderBy(c => c.FirstName).ToList();

   }
}
  • Resolve the namespace for SkillsContext.
Running the UWP application
You can now run the application to see it in action.
  • Hit F5 on the keyboard or click Debug >> Start Without Debugging
  • The application will build and launch on your local machine:
image
Note:
When you run your app in debug mode, there are two sets of three numbers, white on black, that appear in the top left corner of the application's window. These numbers are framerate counters to help monitor app performance. You can have them not show, if you like, by disabling the following code in the App.xaml.cs file:

#if DEBUG
  if (System.Diagnostics.Debugger.IsAttached)  {
    this.DebugSettings.EnableFrameRateCounter = true;
  }
#endif
  • Enter some data then click on the Add button.
image
  • When you click on the Add button, the data will be saved in your SQLite database. It will then be retrieved and displayed below the button.
  • Close the application.
Running application on the phone emulator
This app can run equally well on a phone.

If you have not installed phone emulators yet, click on the down-arrow beside “Local Machine” and select “Download New Emulators…”.

image

Once you have installed the new emulators, make sure you restart Visual Studio.
  • In Visual Studio, set the processor to x86 and the emulator to “Mobile Emulator 10.0.10240.0 720p 5 inch 1GB” then click on the emulator to run the application on the phone: This will first start the emulator, deploy the app on it, then run the app. Depending on your processor speed, the emulator may take some time to launch.
Enter a new contact on your phone. You will determine that the app works equally well.
image
Where is the database file?
In the SkillsContext.cs file, add a breakpoint to the line right after the following:

databaseFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, databaseFilePath);

Run the application and inspect the value of the databaseFilePath variable. Determine just the path then go to that location. It is located somewhere under c:\Users\{your user name}\AppData\Local\Packages. You will find the database file named SkillDB.db.

To view the contents of this database file:
Take a moment to appreciate that SQLite in now a first class citizen in EF Core.
Continue with the tutorial which explains how to deploy your application to the Raspberry Pi 2 IoT device.