Download Slides - Andy Wigley`s Blog

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Concurrency control wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

SQL wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Functional Database Model wikipedia , lookup

Database wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

ContactPoint wikipedia , lookup

PL/SQL wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Clusterpoint wikipedia , lookup

Transcript
Data in Windows 10 UWP
XML, JSON, SQLite or EF Core ?
Andy Wigley
Microsoft, Senior Developer Evangelist
Agenda
•
•
•
•
Data Storage in UWP
XML or JSON serialization
SQLite
Entity Framework Core 1.0
Locations where apps can access data
Credential
Locker
Publishers
Shared
Folder
Cloud
Picker
Provider
apps
B/ground
Transfer
Temp
Roaming
App data
Localdata
App
Folders
App
data
Folders
Folders
App Package
Folder
Removable
Storage
(SD Card)
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();
}
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", "");
Why SQLite?
Worlds’ most popular database
Rich Features
Reliable
SQLite.org
• Documentation
• SQL Syntax
• C/C++ API Reference
• Source and tools
download
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
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
Choice of .NET APIs
SQLite-NET
LINQ syntax
Lightweight ORM
var db =
new SQLite.SQLiteAsyncConnection(App.DBPath);
var _customer = await
(from c in db.Table<Customer>()
where c.Id == customerId
select c).FirstOrDefaultAsync();
SQLitePCL or SQLite-WinRT
SQL statements
Thin wrapper around the SQLite C API
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 (customer != null)
{
var Id = _customer.Id;
var Name = _customer.Name;
}
if (SQLiteResult.DONE == statement.Step()) {
customer = new Customer() {
Id = (long)statement[0],
Name = (string)statement[1] };
}
}
}
…and others!
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>();
}
}
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; }
}
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();
string sql = @"CREATE TABLE IF NOT EXISTS 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);
}
}
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:
1. Reference SQLite for Universal App Platform extension SDK
(as normal)
2. Copy SQLite.cs and SQLiteAsync.cs from a Windows 8.1
project
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
<SDKReference…>
• Copy SDK from C:\Program Files (x86)\Microsoft
SDKs\UAP\v0.8.0.0\ExtensionSDKs to \libs folder in solution root
<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>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{12973612-88B5-4E3E-8805-B862CDEAAE1D}</ProjectGuid>
…
</Project>
• A Developer's Guide to Windows 10:
SQLite Local Database
https://channel9.msdn.com/Series/ADevelopers-Guide-to-Windows-10/10
EF Core 1.0
New Platforms
Full .NET Framework
ASP.NET Core
Windows 10 UWP
Mac
Linux
New Data Stores: Relational & nonrelational
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
“Code First” data model
Define entities
Ne zaboravite ispuniti upitnike.
Čekaju vas vrijedne nagrade!