wph304. announcement linq to sql linq to user data

43
New Windows Phone Data Access Features Sean McKenna Program Manager Windows Phone Application Platform Microsoft Corporation WPH304

Upload: alaina-beryl-rodgers

Post on 24-Dec-2015

270 views

Category:

Documents


0 download

TRANSCRIPT

New Windows Phone Data Access Features

Sean McKennaProgram ManagerWindows Phone Application PlatformMicrosoft Corporation

WPH304

During this Session You have a Chance to Win a Windows Phone

announcement

Session Outline

OverviewArchitectureCode-first development

Implementation detailsQueriesInserts, updates, deletes…Database schema upgrades

Performance and best practices

OverviewEnd-user consentSupported account types

Implementation detailsQuerying contactsQuerying appointments

Performance and best practices

LINQ to SQL LINQ to User Data

LINQ to Everything

LINQ

Objects XML SQLUser Data

7 Mango

OData

Complex Schema

Numerous relationships and constraintsExample: shopping list

Seven tablesHundreds of recordsFive 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

Reference Data

Huge amounts of static reference dataExample: dictionary app

Three tablesOne table with 500k rows

Words

PK WordId

Word Pronunciation Definition AlternateSpellings Origin

Favorites

PK FavoriteId

FK1 WordId

History

PK HistoryItemId

FK1 WordId AddedDate

Web Service Cache

Fetch reference data from cloudCache locallyCombine with user-specific data

Windows Phone

Service cache

User data

Cloudservice

User Data

Filter contactsBirthdays in the next month

Query all appointmentsFind an available time for a meeting

Filter

demo

Mobile Wine CellarManage your wine collection on the go Fetches reference data from wine.com Odata serviceStores user information in local database Queries contacts and appointments for planning wine tasting

Database Support

Local Data Storage: Overview

Apps store private data in Isolated StorageSettings and properties in the app dictionaryUnstructured data in Isolated Storage files Structured data in database files

ApplicationSettings file

AppCreates/managesfiles and settings

Applicationfiles

App Data Folder

Package Manager

App Root Folder

WP7 Isolated Storage APIs

Install

DB

Database file

Databasefile (r/o)

Creates root foldersandboxed to App DB

Architecture

.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”

Your AppCustom

data context

App objects

System.Data.Linq

Identity management

Change tracking

Update processing

Object materialization

Microsoft.Phone.Data.Internal

Core ADO.NET (System.Data)

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

SQL CE DB

Objects, Objects, Objects…

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

// 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 stringDataContext db = new WineDataContext("isostore:/wineDB.sdf");if (!db.DatabaseExists()) db.CreateDatabase();

Database Creation: Example

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;

DB

DataContext

Name Little Penguin

Varietal Pinot Noir

AtHome False

Name Little Penguin

Varietal Pinot Noir

AtHome True

Inserts/Updates/Deletes

It’s all about the DataContextChanges made against the DataContext firstChanges persisted by calling SubmitChanges()

SubmitChangesLINQ 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

Inserts/Updates/Deletes

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();

Insert Update

Inserts/Updates/Deletes

Delete

var 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

Inserts/Updates/Deletes

var vineyardsToDelete = from Vineyards v in db.Vineyardswhere v.Country == “Australia"

select v;

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

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

Database Schema Upgrades

DatabaseSchemaUpdater allows simple upgrades on your existing DBSupports adding

TablesColumnsIndicesAssociations/foreign keys

DatabaseSchemaVersion available for tracking upgradesSchema updates are transactional

Database Schema Upgrades

WineDataContext wineDC = new WineDataContext(App.WineDBConnectionString);

DatabaseSchemaUpdater dsu = wineDC.CreateDatabaseSchemaUpdater();

if (dsu.DatabaseSchemaVersion == 1){

dsu.AddColumn<Wine>("BottleType");dsu.DatabaseSchemaVersion = 2;

dsu.Execute();}         

Performance and Best Practices

Think about the size of your change setsLots of submits will impact performance but limit data loss

Use background threadsOperations on UI thread impact app responsiveness

Optimize read-only queriesSet ObjectTrackingEnabled to minimize memory usage

Performance and Best Practices

Populate large reference data tables in advanceCreate a simple project to prepopulate data in emulatorPull out database file using Isolated Storage explorer

Use the right tool for the jobDatabase for large or complex data setsIsolatedStorageSettings/basic files for small data

Performance and Best Practices

Use a version column on your entitiesUp to 30x improvement in update performance

Use secondary indices for properties which you query oftenImplement INotifyPropertyChanged for efficient change tracking

Avoid creating object copies until needed

demo

Best PracticesINotifyPropertyChangingSecondary indexesVersion column

User Data

New and updated APIs in “Mango”

Chooser Tasks related to user dataEmailAddressChooserTaskPhoneNumberChooserTaskAddressChooserTask

Microsoft.Phone.UserData for direct accessContactsAppointments

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; }}

Contacts and Appointments

Important pointsContacts and Appointments APIs are read onlyThird party social network data cannot be shared

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

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);

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

Performance and Best Practices

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

Keep out of the wayUsers have widely varying contact list sizes Your UI should handle delays gracefully

Don’t let data get staleData returned is a snapshotRefresh state when reasonable

demo

Invite Friends for a Wine Tasting

THANK YOU!

Sean [email protected]

Win a Windows Phone Contest

QUESTIONS?

Go to the WPC Information Counter

at the TLC

HAT CONTEST*

How do you enter?Enter by visiting the Windows Phone booth, accepting a free Windows Phone branded hat, and wearing that hat during the Event

How am I selected?Each day of the event, a Windows Phone representative will randomly select up to 5 people who are observed wearing their Windows Phone branded hat

SESSION CONTEST*

During each Windows Phone session the moderator will post a question; the first person to correctly answer the question and is called on by the moderator will potentially win

* Restrictions apply please see contest rules for eligibility and restrictions. Contest rules are displayed in the Technical Learning Center at the WPH info counter

Windows Phone ResourcesQuestions? Demos? The latest phones?

Visit the Windows Phone Technical Learning Center for demos and more…

Business IT resources

blogs.technet.com/b/windows_phone_4_it_pros

Developer resources

create.msdn.com

Experience Windows Phone 7 on-line and get a backstage pass

www.windowsphone.com

Q&A

Scan the Tag to evaluate this session now on myTech•Ed Mobile

Resources

www.microsoft.com/teched

Sessions On-Demand & Community Microsoft Certification & Training Resources

Resources for IT Professionals Resources for Developers

www.microsoft.com/learning

http://microsoft.com/technet http://microsoft.com/msdn

Learning

http://northamerica.msteched.com

Connect. Share. Discuss.

Complete an evaluation on CommNet and enter to win!

© 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.