Presentation is loading. Please wait.

Presentation is loading. Please wait.

While you are waiting, please install the Windows 10 phone emulators because the installation takes a while and we will be using them during the lab later.

Similar presentations


Presentation on theme: "While you are waiting, please install the Windows 10 phone emulators because the installation takes a while and we will be using them during the lab later."— Presentation transcript:

1 While you are waiting, please install the Windows 10 phone emulators because the installation takes a while and we will be using them during the lab later on. Go to Please ensure you have updated your VISUAL STUDIO 2015

2 Building UWP apps with SQLite
Medhat and I are excited to demon building UWP apps with the open source DB and Entity Framework. Medhat Elmasry and Peter Martin

3 Why use a Database? SQLite SQLitePCL Entity Framework 7 Tools Agenda
We will bring all up to speed on DB SOLite Open Source MS Supported EF7 And Tools

4 Why use a DB? Complex Schema
Numerous relationships and constraints Example: Shopping List 7 tables 100s of records 5 foreign keys DB creates relationships, reduces space and reduce complexity of the data Scale from development to test to production without changing the code

5 Why use a DB? Reference Data
Huge amounts of static reference data Supports large database servers Example: dictionary app 3 tables 1 table with 500k rows

6 4/23/2017 2:41 PM SQLite © 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.

7 Why SQLite? Worlds’ most popular database
Widely used on iOS, Android, Linux and Windows Data provider for .Net, Python, Mono… SQLite library can be reduced below 300 KiB Microsoft is a principle contributor to this open source project Public Domain Small, Fast, Reliable On mobile devices, it can be used for syncing with DB server Most popular DB as it is highly available International development team, you , me and anyone else The product moves forward with backward compatibility You can report bugs to this development team Run-time support windows desktop, phone, Macs, Linux and others It has low overhead hence you can deploy to mobile devices.

8 Features Rich Features Reliable
Embedded SQL in-process database engine Read/writes to ordinary disk files Supports multiple tables, indices, triggers and views Cross-platform: freely copy DB files between 32-bit & 64-bit Reliable Reputation for being very reliable Large automated test suite All transactions are natively ACID even if interrupted by system crashes or power failures Most popular – 32 and 64 bit open source on intel and ARM architectures Move DB is independent of source and destination environments, hence works the same on multiple platforms Start and end transaction are set by default at the beginning and the end of a project It may roll back may occur when you do not expect it

9 SQLite.org SQL Syntax C/C++ API Reference Source & tools download
Documentation SQL Syntax C/C++ API Reference Source & tools download

10 SQLite.org Professional Community Support Models
Proprietary SQLite Extensions Community 3 separate mailing lists help support SQLite SQLite Documents is available Community and Professional Support models

11 Installing the SQLite Library
Visual Studio Extension (.vsix) Install from Visual Studio Tools >> Extensions and Updates… Or download from

12 SQLitePCL The basics 4/23/2017 2:41 PM
© 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.

13 Errors identified at compile time.
Choice of .NET APIs SQLite-NET LINQ syntax Lightweight ORM SQLitePCL 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] }; } These are two separate APIs that a .NET developer can use to access SQLite. The one on the left uses LINQ The one on the right relies on raw SQL statements being sent from the app to the database. This is prone to errors. Errors identified at compile time. …and others!

14 Installing SQLitePCL Nuget package into your project
This is how you can install the SQLitePCL API in Visual Studio using the Nuget package manager.

15 SQLitePCL is really a thin wrapper around the SQLite ‘C’ API
Defining tables SQLitePCL is really a thin wrapper around the SQLite ‘C’ API Interact with the database using Raw SQL statements Parameterized queries and statements

16 SQLitePCL: Create database and tables
private void LoadDatabase() { // Get a reference to the SQLite database conn = new SQLiteConnection("sqlitepcldemo.db"); string sql TABLE IF NOT EXISTS Customer (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name VARCHAR( 140 ), City VARCHAR( 140 ), Contact VARCHAR( 140 ) );"; using (var statement = conn.Prepare(sql)) { statement.Step(); } } Here’s the syntax for creating a database table.

17 SQLitePCL: Insert // SqlConnection was opened in App.xaml.cs and exposed through property conn var db = App.conn; try { using (var custstmt = db.Prepare("INSERT INTO Customer (Name, City, Contact) VALUES (?, ?, ?)")) { custstmt.Bind(1, customerName); custstmt.Bind(2, customerCity); custstmt.Bind(3, customerContact); custstmt.Step(); } } catch (Exception ex) { // TODO: Handle error } Here’s an example for inserting data using a SQLite parameterized query.

18 SQLitePCL: Select public Customer GetCustomer(int customerId) { Customer customer = null; using (var statement = dbconn.Prepare("SELECT Id, Name, City, Contact FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); if (SQLiteResult.DONE == statement.Step()) { customer = new Customer() { Id = (long)statement[0], Name = (string)statement[1], City = (string)statement[2], Contact = (string)statement[3] }; } } return customer; } Here’s an example of retrieving a customer record from his/her ID. This also user parameterized queries.

19 SQLitePCL: Update // See if the customer already exists var existingCustomer = GetCustomer(customer.Id); if (existingCustomer != null) { using (var custstmt = dbconn.Prepare("UPDATE Customer SET Name = ?, City = ?, Contact = ? WHERE Id=?")) { // NOTE when using anonymous parameters the first has an index of 1, not  custstmt.Bind(1, customer.Name); custstmt.Bind(2, customer.City); custstmt.Bind(3, customer.Contact); custstmt.Bind(4, customer.Id); custstmt.Step(); } } This is how you can update a customer record, also using a parameterized query.

20 SQLitePCL: Delete public void DeleteCustomer(int customerId) { using (var statement = dbconn.Prepare("DELETE FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); statement.Step(); } } Here you are deleting a customer record also using a parameterized query. It is always easiest to delete stuff.

21 Relations Parent – Child relationship between records in one table and those in another Example: Each Customer has a collection of one or more Projects Relationship represented in the database by a column in the child object which stores the ID of the parent Foreign key constraints enforce the relationship and maintain db integrity

22 Creating foreign key constraints
With SQLiteWinRT, FK constraint is defined in the CREATE TABLE statement CREATE TABLE IF NOT EXISTS Project  (Id          INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,       CustomerId  INTEGER,              Name        VARCHAR( 140 ),                 Description VARCHAR( 140 ),                        DueDate     DATETIME,             FOREIGN KEY(CustomerId) REFERENCES Customer(Id)               );

23 Enforcing foreign key constraints
Defining a foreign key constraint on the table is not enough! Foreign key constraints are disabled by default (for backwards compatibility) Must be enabled at runtime using a PRAGMA // Turn on Foreign Key constraints   using (var statement = dbconn.Prepare(sql)) { statement.Step(); } You must set foreigh_keys ON to create relationships between tables

24 Other constraints Type Description SQLite-NET PRIMARY KEY Defines the column(s) of the primary key - 1 per table max Declare by using [PrimaryKey] attribute UNIQUE Column constraint enforces unique values in that column Declare by using [Unique] attribute NOT NULL Column constraint prevents null values No way of declaring with SQLite.NET CHECK Column or Table constraint: constraint expression is evaluated on every insert or update, and if ‘0’ returned, constraint fails See for more information

25 Indexes Index is created automatically for PRIMARY KEY columns
Important to create indices on foreign key columns or columns used to select records from large tables // Create index on Foreign Key column   INDEX IF NOT EXISTS fk_customer_project_idx  ON project (customerId) ASC"; using (var statement = dbconn.Prepare(sql)) { statement.Step(); }

26 Transactions, relations and other constraints
4/23/2017 2:41 PM Transactions, relations and other constraints © 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.

27 No changes can be made to the database except within a transaction
Transactions No changes can be made to the database except within a transaction Any command that changes the database will automatically execute within a transaction if one is not already in effect Transactions can be started manually using the BEGIN TRANSACTION statement Such transactions persist until the next COMMIT TRANSACTION or ROLLBACK TRANSACTION Transaction will also rollback if the database is closed

28 Manual transaction – SQLitePCL
SQLite-NET using (var statement = dbconn.Prepare("BEGIN TRANSACTION")) { statement.Step(); } // Execute one or more statements… using (var custstmt = dbconn.Prepare( "INSERT INTO Customer (Name, City, Contact) VALUES (?, ?, ?)")) { } using (var projstmt = dbconn.Prepare( "INSERT INTO Project (Name, Title, DueDate, CustomerId) VALUES (?, ?, ?, ?)")) { } // COMMIT to accept all changes or ROLLBACK TRANSACTION to discard pending changes using (var statement = dbconn.Prepare(“COMMIT TRANSACTION")) { statement.Step(); }

29 DEMO: UWP app with SQLitePCL
4/23/2017 2:41 PM DEMO: UWP app with SQLitePCL © 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.

30 Entity Framework 7 (EF7) 4/23/2017 2:41 PM
© 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.

31 New Platforms & New Data Stores

32 Full & Core .NET Frameworks ASP.NET 5 Supports:
EF7: New Platforms Full & Core .NET Frameworks ASP.NET 5 Supports: Traditional desktop application Windows 10 UWP devices Mac Linux

33 Relational & non-relational
EF7: New Data Stores Relational & non-relational Not a magic abstraction 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) See video

34 Same experience built over a new lightweight and extensible core
A developer who is familiar with EF 4, 5, 6 should find EF7 very familiar.

35 Same top level experience as EF6.x
EF7: New Core Same top level experience as EF6.x Still DbContext/DbSet etc. New core Core = metadata, change tracking, query pipeline, etc. Easier to replace/extend components Replace confusing APIs & behavior Optimized for memory and CPU usage Pay-per-play components

36 Frameworks that use SQLite
Azure App Service Mobile Apps Entity Framework 7 Easy to implement offline data sync uses SQLite for local data storage Lightweight ORM. Supports offline data sync using SQLite for local data storage See BUILD session Entity Framework 7

37 4/23/2017 2:41 PM DEMO: EF7 ProductId ProductName Description UnitPrice Quantity Category Supplier Product UnitName Unit CategoryId CategoryName Category 1 * © 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.

38 4/23/2017 2:41 PM SQLite Tools © 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.

39 sqlite3.exe Download command line tool from sqlite.org

40 Some popular ones include: SQLite Studio http://sqlitestudio.pl/
IDEs For those who prefer a GUI, see the list of IDEs at Some popular ones include: SQLite Studio SQLite Expert

41 Useful debugging tool

42 Transferring databases to desktop
For Desktop: go to %USERPROFILE%\AppData\Local\Packages\{PackageId} For Mobile: Windows Phone Power Tools for WP8.1 – Still works with Windows 10 devices Although you must install the VS2013 – Windows Phone 8.0 SDK to install a device connectivity DLL dependency.

43 DEMO: SQLite Studio

44 Where to Next SQLite http://sqlite.org Learn more about EF7
aka.ms/AboutEF7 See BUILD session Entity Framework 7 A developer’s guide to Windows 10

45 IT-IQ sponsoring beer & snacks at Boston Pizza
Good opportunity to meet with recruiters from


Download ppt "While you are waiting, please install the Windows 10 phone emulators because the installation takes a while and we will be using them during the lab later."

Similar presentations


Ads by Google