10 wp7 local database

38
Windows Phone 7 Li Jingnan / Wang Tao 2011-7-15 1

Upload: tao-wang

Post on 21-May-2015

3.529 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: 10 wp7   local database

Windows Phone 7

Li Jingnan / Wang Tao2011-7-15

1

Page 2: 10 wp7   local database

Windows Phone Microsoft Corporation.

2 days 9:00 Introduction Anytao

10:30 Build a Silverlight Application Jason

13:00 Application Bar Anytao

14:30 Panorama and Pivots Jason

16:00 Launcher and Chooser Jason

9:00 Isolation Storage Anytao

10:30 Application Lifecycle Jason

13:00 Push Notification Anytao

14:30 Multitasking Jason

16:00 Local Database Anytao

9:00 Design Apps Using Expression Blend and Metro Jason

10:30 Marketing your Windows Phone Application Jason

13:00 Working with Azure Anytao

2

Page 3: 10 wp7   local database

Windows Phone Microsoft Corporation.

ethos

http://www.ethostechnologies.com/

One of the 1st ISVs for cloud computing in Europe and China.

Cloud computing development partner with Microsoft in Greater China Region.

Invited to speak about Azure at several Microsoft events.

Page 4: 10 wp7   local database

Windows Phone Microsoft Corporation.

about

anytao | Ethos

<ethos:Member id = “Wang Tao” msn = [email protected] weibo = http://weibo.com/anytao runat = “Senior System Architect”/>

Jason | Ethos

<ethos:Member id = “Li Jingnan” msn = [email protected] weibo = http://weibo.com/jn1981 runat = “SE”/>

Page 5: 10 wp7   local database

Windows Phone Microsoft Corporation.

abouthttp://book.anytao.net

Page 6: 10 wp7   local database

10 Local Database

Wang Tao / 2011-07-15

Page 7: 10 wp7   local database

Windows Phone Microsoft Corporation.

session outlineLINQ to SQL

overview architecture code-first development

implementation details queries inserts, updates, deletes… database schema upgrades

performance and best practices

LINQ to User Data

overview end-user consent supported account types

implementation details querying contacts querying appointments

performance and best practices

Page 8: 10 wp7   local database

Windows Phone Microsoft Corporation.

LINQ to everything

LINQ

Objects XML SQLUser Data

7 Mango

OData

Page 9: 10 wp7   local database

Windows Phone Microsoft Corporation.

complex schema

numerous relationships and constraints

example: shopping list 7 tables 100s of records 5 foreign keys

ItemReferenceData

PK ItemId

ItemName ItemDescriptionFK1 CategoryId

Categories

PK CategoryId

CategoryName

Lists

PK ListId

ListName

ListItems

PK ListItemId

ListItemNameFK1 ListId Quantity Category DescriptionFK2 StoreId

Stores

PK StoreId

StoreName StoreLocationLat StoreLocationLong StoreAddressLine1 StoreAddressLine2 StoreAddressCity StoreAddressState StoreAddressCountry StoryAddressZip

Favorites

PK FavoriteItemId

FavoriteItemName FavoriteItemCategory FavoriteItemQuantity FavoriteItemDescriptionFK1 FavoriteItemListId FavoriteItemPhoto

History

PK HistoryItemId

HistoryItemName HistoryItemCategory HistoryItemQuantity HistoryItemDescriptioin HistoryItemDateAddedFK1 HistoryItemListId HistoryItemPhoto

Page 10: 10 wp7   local database

Windows Phone Microsoft Corporation.

Reference Data

Huge amounts of static reference data

Example: dictionary app 3 tables 1 table with 500k rows

Words

PK WordId

Word Pronunciation Definition AlternateSpellings Origin

Favorites

PK FavoriteId

FK1 WordId

History

PK HistoryItemId

FK1 WordId AddedDate

Page 11: 10 wp7   local database

Windows Phone Microsoft Corporation.

web service cache

fetch reference data from cloud

cache it locally combine with user-specific

data

Cloud Servic

e

Windows Phone

Service

Cache

User Data

Page 12: 10 wp7   local database

Windows Phone Microsoft Corporation.

user data

filter contacts birthdays in the next

month query all appointments

find an available time for a meeting

Filter

Page 13: 10 wp7   local database

Windows Phone Microsoft Corporation.

database support

Page 14: 10 wp7   local database

Windows Phone Microsoft Corporation.

local data storage: overview

apps store private data in Isolated Storage settings and properties in the app

dictionary unstructured data in Isolated Storage

files structured data in database files

ApplicationSettings File

AppCreates/Managesfiles and settings

ApplicationFiles

App Data Folder

Creates root folder

sandboxed to App

Package Manager

App Root Folder

WP7 Isolated Storage APIs

Install

DB

Database file

DB DatabaseFile (r/o)

Page 15: 10 wp7   local database

Windows Phone Microsoft Corporation.

architectureYour App

Custom Data

Context

App Objects

System.Data.Linq

Identity Manageme

nt

Change Tracking

Update Processing

Object Materializatio

n

Microsoft.Phone.Data.Internal

Core ADO.NET (System.Data)SQLCE ADO.NET Provider

(System.Data.SqlServerCe)

SQL CE DB

.Call System.Linq.Queryable.Select( .Call System.Linq.Queryable.Where( .Constant(Table(Wines)), '(.Lambda #Lambda1)), '(.Lambda #Lambda2)) .Lambda #Lambda1(db.Wines $w) { $w.Country == “USA" } .Lambda #Lambda2(w.Country $w) { $w.Name }

var query = from w in db.Wines where w.Country == “USA" select w.Name;

select Namefrom Wineswhere Country = “USA”

Page 16: 10 wp7   local database

Windows Phone Microsoft Corporation.

code first development

Design time

Create object model: wines, varietals, vineyards, etc.

Decorate objects with attributes for persistence

Run time

Create DataContext reference to database

Translate object model into a database file

Submit API persists changes to DB

Database upgrade

Create new objects to enable new features

Use upgrade APIs to change DB

Varietals Wines

Vineyards WineMakers

Wines

PK WineID

Name Description RetailPriceFK2 VarietalIDFK1 VineyardID

Vineyards

PK VineyardID

Name Latitude Longitude Country

Varietals

PK VarietalID

Name

Winemaker

PK WinemakerID

FirstName LastName

Page 17: 10 wp7   local database

Windows Phone Microsoft Corporation.

database creation: example // Define the data context.

public partial class WineDataContext : DataContext

{

public Table<Wine> Wines;

public Table<Vineyard> Vineyards;

public WineDataContext(string connection) : base(connection) { }

}

// Define the tables in the database

[Table]

public class Wine

{

[Column(IsPrimaryKey=true]

public string WineID { get; set; }

[Column]

public string Name { get; set; }

……

}

// Create the database form data context, using a connection string

DataContext db = new WineDataContext("isostore:/wineDB.sdf");

if (!db.DatabaseExists()) db.CreateDatabase();

Page 18: 10 wp7   local database

Windows Phone Microsoft Corporation.

queries: examples

// Create the database form data context, using a connection stringDataContext db = new WineDataContext("isostore:/wineDB.sdf");

// Find all wines currently at home, ordered by date acquiredvar q = from w in db.Wines

where w.Varietal.Name == “Shiraz” && w.IsAtHome == true orderby w.DateAcquired select w;

Page 19: 10 wp7   local database

Windows Phone Microsoft Corporation.

DB

DataContextName Little

Penguin

Varietal Pinot Noir

AtHome False

Name Little Penguin

Varietal Pinot Noir

AtHome True

Inserts/Updates/Deletes

It’s all about the DataContext Changes made against

the DataContext first Changes persisted

by calling SubmitChanges() SubmitChanges

LINQ to SQL determines change set and submits to DB

Name Little Penguin

Varietal Pinot Noir

AtHome False

Your App Code

Name Yellow Tail

Varietal Pinot Noir

AtHome True

Page 20: 10 wp7   local database

Windows Phone Microsoft Corporation.

inserts/updates/deletesinsert update

Wine newWine = new Wine{

WineID = “1768",Name = “Windows Phone Syrah",Description = “Bold and spicy"

};

db.Wines.InsertOnSubmit(newWine);

db.SubmitChanges();

Wine wine = (from w in db.Wines where w.WineID == “1768" select w).First();

wine.Description = “Hints of plum and melon";

db.SubmitChanges();

Page 21: 10 wp7   local database

Windows Phone Microsoft Corporation.

inserts/updates/deletesdeletevar vineyardsToDelete =

from Vineyards v in db.Vineyardswhere v.Country == “Australia”select v;

db.Vineyards.DeleteAllOnSubmit(vineyardsToDelete);

db.SubmitChanges(); Foreign key constraint will

cause exception here if Wines associated with the Vineyards are not deleted first

Page 22: 10 wp7   local database

Windows Phone Microsoft Corporation.

inserts/updates/deletesvar vineyardsToDelete = from Vineyards v in db.Vineyards

where v.Country == “Australia" select v;

foreach (Vineyards v in vineyardsToDelete){ db.Wines.DeleteAllOnSubmit(v.Wines);}

db.Vineyards.DeleteAllOnSubmit(vineyardsToDelete);db.SubmitChanges();

Page 23: 10 wp7   local database

Windows Phone Microsoft Corporation.

database schema upgrades DatabaseSchemaUpdater allows for simple upgrades

on your existing DB It offers the ability to add

Tables Columns Indices Associations/foreign keys

All schema updates are transactional More complex schema upgrades require full

DB migration

Page 24: 10 wp7   local database

Windows Phone Microsoft Corporation.

Database Schema Upgrades Create a new DatabaseSchemaUpdater

MyDerivedDataContext context = new MyDerivedDataContext("foo.sdf");DatabaseSchemaUpdater dbUpdater = context.CreateDatabaseSchemaUpdater();

Add a new table tied to the Product class

dbUpdater.AddTable<Winemaker>();

Add a Region column to the Customer table

dbUpdater.AddColumn<Vineyard>(“YearEstablished");

Execute upgrade dbUpdater.Execute();

Page 25: 10 wp7   local database

Windows Phone Microsoft Corporation.

performance and best practices

keep change sets small Submit early and often to avoid data loss on app

termination use background threads

Non-trivial operations will impact app responsiveness if done on UI thread

optimize read-only queries Set ObjectTrackingEnabled to minimize memory usage

use secondary indices for properties which you query often

Page 26: 10 wp7   local database

Windows Phone Microsoft Corporation.

performance and best practices

populate large reference data tables in advance Create a simple project to prepopulate data in emulator Pull out database file using Isolated Storage explorer

when to use a database… expect some impact to startup time and memory

usage from incorporating a DB stick to IsolatedStorageSettings or basic files for small

data sets

Page 27: 10 wp7   local database

Windows Phone Microsoft Corporation.

user data

Page 28: 10 wp7   local database

Windows Phone Microsoft Corporation.

new and updated APIs in “Mango” Chooser Tasks related to user data

EmailAddressChooserTask PhoneNumberChooserTask AddressChooserTask

Microsoft.Phone.UserData for direct access Contacts Appointments

Page 29: 10 wp7   local database

Windows Phone Microsoft Corporation.

AddressChooserTaskprivate AddressChooserTask addressChooserTask;

// Constructorpublic MainPage(){ this.addressChooserTask = new AddressChooserTask(); this.addressChooserTask.Completed += new

EventHandler<AddressResult>( addressChooserTask_Completed);

}

private void addressChooserTask_Completed(object sender, AddressResult e){ if (null == e.Error && TaskResult.OK == e.TaskResult) {

... = e.DisplayName;

... = e.Address; }}

Page 30: 10 wp7   local database

Windows Phone Microsoft Corporation.

Microsoft.Phone.UserData

Important points Contacts and Appointments APIs are read

only Third party social network data cannot be

shared

Page 31: 10 wp7   local database

Windows Phone Microsoft Corporation.

Contacts/Appointments Data Shared  Contact

Nameand Picture

Other contact data

Appointments/Events

Windows Live Social YES YES YES

Windows Live Rolodex(user created and SIM import)

YES YES n/a

Exchange accounts(corporate plus Google, etc.)

YES YES YES

Operator Address Books YES YES n/a

Facebook YES NO NO

Other networks in the People Hub (e.g., Twitter)

NO NO NO

Page 32: 10 wp7   local database

Windows Phone Microsoft Corporation.

contacts: hello, world!Contacts contacts = new Contacts();

contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>((sender, e) => { ... = e.Results; });

// E.g. search for all contactscontacts.SearchAsync(string.Empty, FilterKind.None, null);

filter expression(not a regex)

Filter kind: name, email , phone or pinned to start)

state

// E.g. search for all contacts with display name matching "ja"contacts.SearchAsync("ja", FilterKind.DisplayName, null);

Page 33: 10 wp7   local database

Windows Phone Microsoft Corporation.

appointments: hello, world!Appointments appointments = new Appointments();

appointments.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>((sender, e) => { ... = e.Results; });

// E.g. get next appointment (up to 1 week away)appointments.SearchAsync(DateTime.Now, DateTime.Now + TimeSpan.FromDays(7), 1, null);

start date and time

Maximum items to return

stateend date and time

Page 34: 10 wp7   local database

Windows Phone Microsoft Corporation.

performance and best practices be responsible

your privacy policy should cover how you use the user’s contact information

keep out of the way users have widely varying contact list sizes your UI should handle delays gracefully

don’t let data get stale data returned is a snapshot refresh state when reasonable

Page 35: 10 wp7   local database

Windows Phone Microsoft Corporation.35

demo04 user manager

/ linq to sql/ datacontext/ CRUD/ user data

Page 36: 10 wp7   local database

Windows Phone Microsoft Corporation.36

practicea todo list

Page 37: 10 wp7   local database

Windows Phone Microsoft Corporation.37

Click to add picturethank youthank youwww.anytao.com

Page 38: 10 wp7   local database

Windows Phone Microsoft Corporation.

© 2011 Microsoft Corporation.

All rights reserved. Microsoft, Windows, Windows Vista 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