Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data in Windows 10 UWP Andy Wigley XML, JSON, SQLite or EF Core ?

Similar presentations


Presentation on theme: "Data in Windows 10 UWP Andy Wigley XML, JSON, SQLite or EF Core ?"— Presentation transcript:

1

2 Data in Windows 10 UWP Andy Wigley XML, JSON, SQLite or EF Core ?
Microsoft, Senior Developer Evangelist

3

4

5 Agenda Data Storage in UWP XML or JSON serialization SQLite
Entity Framework Core 1.0

6 4/28/2017 Data Storage in UWP © 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

7 Locations where apps can access data
4/28/2017 Locations where apps can access data Cloud Credential Locker App App File Open/Save Picker APIs Picker Provider apps Publishers Shared Folder File System B/ground Transfer r/w r/w r/w r/w Temp App data Folders Pictures Videos Music - Direct access needs manifest capabilities Roaming App data Folders App Known Folders Local App data Folders r/w r/w r/w App Package Folder Removable Storage (SD Card) r/o © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

8 Serializing POCO to files

9 Data serialization using Windows.Data.Json; ..
public string Stringify() {     JsonArray jsonArray = new JsonArray();     foreach (School school in Education)     {         jsonArray.Add(school.ToJsonObject());     }     JsonObject jsonObject = new JsonObject();     jsonObject["id"] = JsonValue.CreateStringValue(Id);     // Treating a blank string as null     if (String.IsNullOrEmpty(Phone))         jsonObject["phone"] = JsonValue.CreateNullValue();     else         jsonObject["phone"] = JsonValue.CreateStringValue(Phone);     jsonObject["name"] = JsonValue.CreateStringValue(Name);     jsonObject["education"] = jsonArray;     return jsonObject.Stringify(); }

10 Data deserialization using Windows.Data.Json; ..
JsonObject jsonObject = JsonObject.Parse(jsonString); Id = jsonObject.GetNamedString("id", ""); IJsonValue phoneJsonValue = jsonObject.GetNamedValue("phone"); if (phoneJsonValue.ValueType == JsonValueType.Null) {     Phone = null; } else {     Phone = phoneJsonValue.GetString(); } Name = jsonObject.GetNamedString("name", "");

11 SQLite

12 Why SQLite? Worlds’ most popular database Rich Features Reliable
Widely used on iOS, Android, Python, Mono etc… Public Domain Small, Fast, Reliable Rich Features Embedded SQL in-process database engine Read/writes to ordinary disk files Supports multiple tables, indices, triggers and views Cross-platform – freely copy database files between 32-bit and 64-bit, or little endian and big endian Reliable Reputation for being very reliable Large automated test suite All transactions are ACID even if interrupted by system crashes or power failures

13 SQLite.org Documentation SQL Syntax C/C++ API Reference
Source and tools download

14 SQLite now included in the UWP SDK
Since Windows 10 v1511/SDK Build 10586, native code can reference SQLite directly from SDK To reference the SDK SQLite: include the following header in your project: #include <winsqlite/winsqlite3.h> Configure the project to link to winsqlite3.lib (right-click project > Properties > Linker > Input > add winsqlite3.lib to Additional Dependencies) Benefits: reduce the size of your application package rely on the platform to update the library periodically Using the SDK SQLite might also lead to performance advantages such as faster launch times

15 Managed code SQLite usage
Rely on WinRT component wrappers, or C# p/invoke code On NuGet: SQLitePCL SQLiteWinRT SQLite-NET *doesn’t work currently!* These need sqlite3.dll to be referenced by your project Install SQLite for Universal App Platform Visual Studio Extension (.vsix), then reference from your project

16 Choice of .NET APIs …and others! SQLite-NET
LINQ syntax Lightweight ORM SQLitePCL or SQLite-WinRT SQL statements Thin wrapper around the SQLite C API var db =  new SQLite.SQLiteAsyncConnection(App.DBPath); var _customer = await  (from c in db.Table<Customer>() where c.Id == customerId  select c).FirstOrDefaultAsync(); if (customer != null) {      var Id = _customer.Id;      var Name = _customer.Name;      } using (var conn = new SQLiteConnection("demo.db")) {      Customer customer = null; using (var statement = conn.Prepare( "SELECT Id, Name FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); if (SQLiteResult.DONE == statement.Step()) { customer = new Customer() { Id = (long)statement[0], Name = (string)statement[1] }; } …and others!

17 Create database *SQLite-NET* private void LoadDatabase() {
{              // Set the path to the SQLite database              var DBPath = Path.Combine( Windows.Storage.ApplicationData.Current.LocalFolder.Path, "customers.sqlite");      // Initialize the database if necessary              using (var db = new SQLite.SQLiteConnection(DBPath,  SQLite.SQLiteOpenFlags.ReadWrite | SQLite.SQLiteOpenFlags.Create)) {                  // Create the tables if they don't exist                  db.CreateTable<Customer>();                  db.CreateTable<Project>();              }          }

18 Define entity objects *SQLite-NET* public class Customer {
    [PrimaryKey, AutoIncrement]          public int Id { get; set; }          public string Name { get; set; }          public string City { get; set; }          public string Contact { get; set; }      }

19 Create database and tables
SQLite-WinRT private void LoadDatabase()         {              // Specify database location    var db = new SQLiteWinRT.Database(ApplicationData.Current.LocalFolder, "sqlitedemo.db"); try  {          // Open a connection to the SQLite database – creates it if it does not exist    await db.OpenAsync();    Customer                     (Id      INTEGER PRIMARY KEY AUTOINCREMENT,             Name    VARCHAR( 140 ),                      City    VARCHAR( 140 ),                      Contact VARCHAR( 140 ) );";       await db.ExecuteStatementAsync(sql);    }         catch (Exception ex) {           var result = SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);      throw new ApplicationException("Database create failed with error " + result);        }

20 Tip: SQLite-Net The SQLite-Net NuGet package does not work in UWP
NuGet v3 does not allow a package to add additional content files to your project SQLite-Net actually consists of two C# source files , SQLite.cs and SQLiteAsync.cs that use p/invoke to call functions exported from sqlite3.dll – NuGet V2 used to add these files! Solution: Reference SQLite for Universal App Platform extension SDK (as normal) Copy SQLite.cs and SQLiteAsync.cs from a Windows 8.1 project

21 4/28/2017 Demo: SQLite © 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

22 But those SQLite updates are so annoying!
SQLite gets updated frequently Breaks your project references Coordinating team on specific version is a problem Can store SQLite SDK local to project

23 <SDKReference…>
Copy SDK from C:\Program Files (x86)\Microsoft SDKs\UAP\v \ExtensionSDKs to \libs folder in solution root

24 <SDKReference…>
Edit csproj so that it looks in your \libs folder first for SDKs <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="…"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\..." /> <PropertyGroup> <SDKReferenceDirectoryRoot>$(SolutionDir)\libs;$(SDKReferenceDirectoryRoot) </SDKReferenceDirectoryRoot> </PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">x86</Platform> <ProjectGuid>{ B5-4E3E-8805-B862CDEAAE1D}</ProjectGuid> </Project>

25 Further Information on direct SQLite programming:
A Developer's Guide to Windows 10: SQLite Local Database

26 Entity Framework Core 1.0

27 EF Core 1.0 Lightweight and extensible version of Entity Framework
New Platforms Full .NET Framework ASP.NET Core Windows 10 UWP Mac Linux New Data Stores: Relational & non- relational Not a magic abstraction that hides underlying data store High level services that are useful on all/most stores Non-common concerns handled by provider extensions Example providers Relational (SQL Server, SQLite, Postgres, etc.) Azure Table Storage Redis In Memory (for testing) SQLite is currently the only supported provider for UWP

28 “Code First” data model
public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) optionsBuilder.UseSqlite($"Filename=Blogging.db"); } protected override void OnModelCreating(ModelBuilder modelBuilder) // Make Blog.Url required modelBuilder.Entity<Blog>() .Property(b => b.Url) .IsRequired();

29 Define entities public class Blog { public int BlogId { get; set; }
public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public Blog Blog { get; set; }

30 4/28/2017 Demo: EF Core 1.0 © 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

31 Ne zaboravite ispuniti upitnike.
Čekaju vas vrijedne nagrade!

32


Download ppt "Data in Windows 10 UWP Andy Wigley XML, JSON, SQLite or EF Core ?"

Similar presentations


Ads by Google