Showing posts with label UWP. Show all posts
Showing posts with label UWP. Show all posts

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.

Sunday, October 16, 2016

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.























Monday, November 30, 2015

Using SQLite with Windows 10 UWP & EF7

We will build a 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 the 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-beta6
  • 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-beta6
Install-Package Microsoft.CodeAnalysis.CSharp –Version 1.0.0
image

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
  • If you compile, there will be an error in the migration file. Due to a bug in the migration scaffolder in Beta6 you will need to manually edit the generated migration. Remove (or comment out) the .Annotation("Sqlite:Autoincrement", true) and add a comma (,) at the end of the line before it.
  • 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 void Initialize(SkillsContext context) {
      if (!context.Skills.Any()) {
          var sailor = context.Skills.Add(new SkillLookup { Skill = "Sailor" }).Entity;
          var fisher = context.Skills.Add(new SkillLookup { Skill = "Fisherman" }).Entity;
          var smith = context.Skills.Add(new SkillLookup { Skill = "Gold Smith" }).Entity;
          var gardner = context.Skills.Add(new SkillLookup { Skill = "Gardner" }).Entity;
          var mason = context.Skills.Add(new SkillLookup { Skill = "Mason" }).Entity;

          context.Contacts.AddRange(
              new Contact() {
                  FirstName = "Jim",
                  LastName = "Sailor",
                  Email = "jim@sailor.com",
                  Skill = sailor.Skill
              },
              new Contact() {
                  FirstName = "Jane",
                  LastName = "Sailor",
                  Email = "jane@sailor.com",
                  Skill = sailor.Skill
              },
              new Contact() {
                  FirstName = "Bob",
                  LastName = "Fisher",
                  Email = "jim@fisher.com",
                  Skill = fisher.Skill
              },
              new Contact() {
                  FirstName = "Susanne",
                  LastName = "Smith",
                  Email = "susanne@smith.com",
                  Skill = smith.Skill
              },
              new Contact() {
                  FirstName = "James",
                  LastName = "Gardner",
                  Email = "james@gardner.com",
                  Skill = gardner.Skill
              },
              new Contact() {
                  FirstName = "Perry",
                  LastName = "Mason",
                  Email = "perry@mason.com",
                  Skill = mason.Skill
              }
          );
          context.SaveChanges();
      }
  }
}
  • 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.ApplyMigrations();
                    DummyData.Initialize(db);
                }
  • 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 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.
  • Debug >> Start Without Debugging
  • The application will build and launch on your local machine:

image
  • 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. 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 EF7.