SlideShare a Scribd company logo
Windows Phone 7Li Jingnan / Wang Tao2011-7-151
2 days2
ethoshttp://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.
aboutanytao| Ethos<ethos:Member   id = “Wang Tao”   msn = anytao@live.comweibo = http://weibo.com/anytaorunat = “Senior System Architect”/>Jason | Ethos<ethos:Member   id = “Li Jingnan”   msn = zengnami@hotmail.comweibo= http://weibo.com/jn1981runat = “SE”/>
abouthttp://book.anytao.net
10 Local DatabaseWang Tao / 2011-07-15
session outlineLINQ to SQLLINQ to User Dataoverviewarchitecturecode-first developmentimplementation detailsqueriesinserts, updates, deletes…database schema upgradesperformance and best practicesoverviewend-user consentsupported account typesimplementation detailsquerying contactsquerying appointmentsperformance and best practices
LINQ to everythingLINQObjectsXMLSQLUser DataOData7Mango
complex schemanumerous relationships and constraintsexample: shopping list7 tables100s of records5 foreign keys
Reference DataHuge amounts of static reference dataExample: dictionary app3 tables1 table with 500k rows
web service cacheCloud Servicefetch reference data from cloudcache it locallycombine with user-specific dataWindows PhoneService CacheUser Data
user datafilter contactsbirthdays in the next monthquery all appointmentsfind an available time for a meetingFilter
database support
local data storage: overviewapps store private data in Isolated Storagesettings and properties in the app dictionary
unstructured data in Isolated Storage files
structured data in database filesApp Root FolderInstallPackage ManagerCreates root foldersandboxed to AppDBDatabaseFile (r/o)App Data FolderCreates/Managesfiles and settingsAppWP7 Isolated Storage APIsDBApplicationSettings FileApplicationFilesDatabase file
architectureYour AppCustom Data ContextApp Objectsvar query = fromw indb.Wineswherew.Country== “USA"selectw.Name;System.Data.LinqIdentity ManagementChange TrackingUpdate ProcessingObject Materialization.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}select Namefrom Wineswhere Country = “USA”Microsoft.Phone.Data.Internal Core ADO.NET (System.Data)SQL CE DBSQLCE ADO.NET Provider (System.Data.SqlServerCe)
code first developmentDesign timeCreate object model: wines, varietals, vineyards, etc.
Decorate objects with attributes for persistenceVarietalsWinesVineyardsWineMakersCreate DataContextreference to database
Translate object model into a database file
Submit API persists changes to DBRun timeDatabase upgradeCreate new objects to enable new features
Use upgrade APIs to change DBdatabase creation: example// Define the data context.publicpartialclassWineDataContext: DataContext{publicTable<Wine> Wines;publicTable<Vineyard> Vineyards;publicWineDataContext(stringconnection) : base(connection) { }}// Define the tables in the database[Table]publicclassWine{[Column(IsPrimaryKey=true]publicstringWineID{ get; set; }[Column]publicstringName { get; set; }……}// Create the database form data context, using a connection stringDataContextdb = newWineDataContext("isostore:/wineDB.sdf");if (!db.DatabaseExists()) db.CreateDatabase();
queries: examples// Create the database form data context, using a connection stringDataContextdb = newWineDataContext("isostore:/wineDB.sdf");// Find all wines currently at home, ordered by date acquiredvarq = from w indb.Wines	  wherew.Varietal.Name == “Shiraz” && w.IsAtHome == trueorderbyw.DateAcquired	  select w;
Inserts/Updates/DeletesYour App CodeIt’s all about the DataContextChanges made against the DataContext firstChanges persisted by calling SubmitChanges()SubmitChangesLINQ to SQL determines change set and submits to DBDataContextDB
inserts/updates/deletesupdateinsertWinenewWine= newWine{WineID= “1768",Name = “Windows Phone Syrah",Description = “Bold and spicy"};db.Wines.InsertOnSubmit(newWine);db.SubmitChanges();Winewine= (fromw indb.Wines wherew.WineID== “1768"select w).First();wine.Description= “Hints of plum and melon";db.SubmitChanges();
inserts/updates/deletesdeletevarvineyardsToDelete= fromVineyards v in db.Vineyardswherev.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/deletesvarvineyardsToDelete= fromVineyards v indb.Vineyards			wherev.Country== “Australia"select v;foreach (Vineyards v invineyardsToDelete){db.Wines.DeleteAllOnSubmit(v.Wines);}db.Vineyards.DeleteAllOnSubmit(vineyardsToDelete);db.SubmitChanges();
database schema upgradesDatabaseSchemaUpdater allows for simple upgrades on your existing DBIt offers the ability to addTablesColumnsIndicesAssociations/foreign keysAll schema updates are transactionalMore complex schema upgrades require full DB migration
Database Schema UpgradesCreate a new DatabaseSchemaUpdaterMyDerivedDataContext context = newMyDerivedDataContext("foo.sdf");DatabaseSchemaUpdaterdbUpdater = context.CreateDatabaseSchemaUpdater();Add a new table tied to the Product classdbUpdater.AddTable<Winemaker>();Add a Region column to the Customer tabledbUpdater.AddColumn<Vineyard>(“YearEstablished");Execute upgradedbUpdater.Execute();
performance and best practiceskeep change sets smallSubmit early and often to avoid data loss on app terminationuse background threadsNon-trivial operations will impact app responsiveness if done on UI threadoptimize read-only queriesSet ObjectTrackingEnabled to minimize memory usageuse secondary indices for properties which you query often
performance and best practicespopulate large reference data tables in advanceCreate a simple project to prepopulate data in emulatorPull out database file using Isolated Storage explorerwhen to use a database…expect some impact to startup time and memory usage from incorporating a DBstick to IsolatedStorageSettings or basic files for small data sets
user data
new and updated APIs in “Mango”Chooser Tasks related to user dataEmailAddressChooserTaskPhoneNumberChooserTaskAddressChooserTaskMicrosoft.Phone.UserData for direct accessContactsAppointments
AddressChooserTaskprivateAddressChooserTaskaddressChooserTask;// ConstructorpublicMainPage(){this.addressChooserTask= newAddressChooserTask();this.addressChooserTask.Completed += newEventHandler<AddressResult>(addressChooserTask_Completed);}privatevoidaddressChooserTask_Completed(objectsender, AddressResulte){if(null == e.Error && TaskResult.OK == e.TaskResult)   {... = e.DisplayName;... = e.Address;}}
Microsoft.Phone.UserDataImportant pointsContacts and Appointments APIs are read onlyThird party social network data cannot be shared
Contacts/Appointments Data Shared
contacts: hello, world!Contactscontacts = newContacts();contacts.SearchCompleted+= newEventHandler<ContactsSearchEventArgs>((sender, e) =>            {...= e.Results;            });// E.g. search for all contactscontacts.SearchAsync(string.Empty, FilterKind.None, null);state// E.g. search for all contacts with display name matching "ja"contacts.SearchAsync("ja", FilterKind.DisplayName, null);filter expression(not a regex)Filter kind: name, email , phone or pinned to start)
appointments: hello, world!Appointmentsappointments = newAppointments();appointments.SearchCompleted+= newEventHandler<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 timeend date and timeMaximum items to returnstate

More Related Content

PDF
10.Local Database & LINQ
PDF
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
PPTX
Advanced app building with PowerApps expressions and rules
PPTX
Using Access to Create Reports from Voyager (Microsoft Access with the Voyage...
PPTX
Bare-knuckle web development
DOC
exa_cer_g23
PDF
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
PDF
Remote code-with-expression-language-injection
10.Local Database & LINQ
TDC2017 | São Paulo - Trilha Java EE How we figured out we had a SRE team at ...
Advanced app building with PowerApps expressions and rules
Using Access to Create Reports from Voyager (Microsoft Access with the Voyage...
Bare-knuckle web development
exa_cer_g23
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Remote code-with-expression-language-injection

Viewers also liked (8)

PDF
Windows Phone 7 in azure
PPTX
09 wp7 multitasking
PPTX
12 wp7 marketing windows phone applications
PPTX
11 wp7 designing applicationsusingexpressionblend
PDF
Anytao 让windows phone应用在云端翱翔
PPTX
13 wp7 working with azure
PDF
01 windows azure platform overview
PPTX
Windows Azure Platform Overview
Windows Phone 7 in azure
09 wp7 multitasking
12 wp7 marketing windows phone applications
11 wp7 designing applicationsusingexpressionblend
Anytao 让windows phone应用在云端翱翔
13 wp7 working with azure
01 windows azure platform overview
Windows Azure Platform Overview
Ad

Similar to 10 wp7 local database (20)

PPTX
Windows Phone 8 - 7 Local Database
PPT
ADO.NET Data Services
PPT
Micro-ORM Introduction - Don't overcomplicate
PDF
Smart Client Development
PPT
Wcf data services
PPTX
MVP Cloud OS Week: 9 Sept, Track 1 Data Liberty
PPTX
MVP Cloud OS Week Track 1 9 Sept: Data liberty
PPTX
Ft10 de smet
PPTX
Data Access Tech Ed India
PPT
Ado.Net Data Services (Astoria)
PPTX
Data In Cloud
PPT
PPT
B_110500002
PPTX
Building nTier Applications with Entity Framework Services (Part 1)
DOC
10265 developing data access solutions with microsoft visual studio 2010
PPTX
Command Query Responsibility Segregation
PPT
Language Integrated Query By Nyros Developer
PPT
Introduction to Linq
PPTX
Getting started with entity framework
Windows Phone 8 - 7 Local Database
ADO.NET Data Services
Micro-ORM Introduction - Don't overcomplicate
Smart Client Development
Wcf data services
MVP Cloud OS Week: 9 Sept, Track 1 Data Liberty
MVP Cloud OS Week Track 1 9 Sept: Data liberty
Ft10 de smet
Data Access Tech Ed India
Ado.Net Data Services (Astoria)
Data In Cloud
B_110500002
Building nTier Applications with Entity Framework Services (Part 1)
10265 developing data access solutions with microsoft visual studio 2010
Command Query Responsibility Segregation
Language Integrated Query By Nyros Developer
Introduction to Linq
Getting started with entity framework
Ad

More from Tao Wang (17)

PDF
团队高效沟通的秘密
PDF
高效团队的秘密
PDF
Worktile 更好用的企业协作平台
PDF
Hello, Worktile Pro
PPTX
08 wp7 push notification
PPTX
08 wp7 push notification
PPTX
07 wp7 application lifecycle
PPTX
06 wp7 isolation storage
PPTX
03 wp7 application bar
PPTX
03 wp7 application bar
PPTX
05 wp7 launchers and choosers
PPTX
04 wp7 pivot and panorama
PPTX
02 wp7 building silverlight applications
PPTX
01 wp7 introduction
PDF
Azure 迁移之道
PPTX
Facebook and its development
PPTX
What is silverlight?
团队高效沟通的秘密
高效团队的秘密
Worktile 更好用的企业协作平台
Hello, Worktile Pro
08 wp7 push notification
08 wp7 push notification
07 wp7 application lifecycle
06 wp7 isolation storage
03 wp7 application bar
03 wp7 application bar
05 wp7 launchers and choosers
04 wp7 pivot and panorama
02 wp7 building silverlight applications
01 wp7 introduction
Azure 迁移之道
Facebook and its development
What is silverlight?

Recently uploaded (20)

PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Empathic Computing: Creating Shared Understanding
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Machine learning based COVID-19 study performance prediction
PDF
cuic standard and advanced reporting.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Electronic commerce courselecture one. Pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Empathic Computing: Creating Shared Understanding
MYSQL Presentation for SQL database connectivity
Dropbox Q2 2025 Financial Results & Investor Presentation
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Building Integrated photovoltaic BIPV_UPV.pdf
Review of recent advances in non-invasive hemoglobin estimation
Machine learning based COVID-19 study performance prediction
cuic standard and advanced reporting.pdf
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Electronic commerce courselecture one. Pdf
NewMind AI Weekly Chronicles - August'25 Week I

10 wp7 local database

  • 1. Windows Phone 7Li Jingnan / Wang Tao2011-7-151
  • 3. ethoshttp://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.
  • 4. aboutanytao| Ethos<ethos:Member id = “Wang Tao” msn = anytao@live.comweibo = http://weibo.com/anytaorunat = “Senior System Architect”/>Jason | Ethos<ethos:Member id = “Li Jingnan” msn = zengnami@hotmail.comweibo= http://weibo.com/jn1981runat = “SE”/>
  • 6. 10 Local DatabaseWang Tao / 2011-07-15
  • 7. session outlineLINQ to SQLLINQ to User Dataoverviewarchitecturecode-first developmentimplementation detailsqueriesinserts, updates, deletes…database schema upgradesperformance and best practicesoverviewend-user consentsupported account typesimplementation detailsquerying contactsquerying appointmentsperformance and best practices
  • 9. complex schemanumerous relationships and constraintsexample: shopping list7 tables100s of records5 foreign keys
  • 10. Reference DataHuge amounts of static reference dataExample: dictionary app3 tables1 table with 500k rows
  • 11. web service cacheCloud Servicefetch reference data from cloudcache it locallycombine with user-specific dataWindows PhoneService CacheUser Data
  • 12. user datafilter contactsbirthdays in the next monthquery all appointmentsfind an available time for a meetingFilter
  • 14. local data storage: overviewapps store private data in Isolated Storagesettings and properties in the app dictionary
  • 15. unstructured data in Isolated Storage files
  • 16. structured data in database filesApp Root FolderInstallPackage ManagerCreates root foldersandboxed to AppDBDatabaseFile (r/o)App Data FolderCreates/Managesfiles and settingsAppWP7 Isolated Storage APIsDBApplicationSettings FileApplicationFilesDatabase file
  • 17. architectureYour AppCustom Data ContextApp Objectsvar query = fromw indb.Wineswherew.Country== “USA"selectw.Name;System.Data.LinqIdentity ManagementChange TrackingUpdate ProcessingObject Materialization.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}select Namefrom Wineswhere Country = “USA”Microsoft.Phone.Data.Internal Core ADO.NET (System.Data)SQL CE DBSQLCE ADO.NET Provider (System.Data.SqlServerCe)
  • 18. code first developmentDesign timeCreate object model: wines, varietals, vineyards, etc.
  • 19. Decorate objects with attributes for persistenceVarietalsWinesVineyardsWineMakersCreate DataContextreference to database
  • 20. Translate object model into a database file
  • 21. Submit API persists changes to DBRun timeDatabase upgradeCreate new objects to enable new features
  • 22. Use upgrade APIs to change DBdatabase creation: example// Define the data context.publicpartialclassWineDataContext: DataContext{publicTable<Wine> Wines;publicTable<Vineyard> Vineyards;publicWineDataContext(stringconnection) : base(connection) { }}// Define the tables in the database[Table]publicclassWine{[Column(IsPrimaryKey=true]publicstringWineID{ get; set; }[Column]publicstringName { get; set; }……}// Create the database form data context, using a connection stringDataContextdb = newWineDataContext("isostore:/wineDB.sdf");if (!db.DatabaseExists()) db.CreateDatabase();
  • 23. queries: examples// Create the database form data context, using a connection stringDataContextdb = newWineDataContext("isostore:/wineDB.sdf");// Find all wines currently at home, ordered by date acquiredvarq = from w indb.Wines wherew.Varietal.Name == “Shiraz” && w.IsAtHome == trueorderbyw.DateAcquired select w;
  • 24. Inserts/Updates/DeletesYour App CodeIt’s all about the DataContextChanges made against the DataContext firstChanges persisted by calling SubmitChanges()SubmitChangesLINQ to SQL determines change set and submits to DBDataContextDB
  • 25. inserts/updates/deletesupdateinsertWinenewWine= newWine{WineID= “1768",Name = “Windows Phone Syrah",Description = “Bold and spicy"};db.Wines.InsertOnSubmit(newWine);db.SubmitChanges();Winewine= (fromw indb.Wines wherew.WineID== “1768"select w).First();wine.Description= “Hints of plum and melon";db.SubmitChanges();
  • 26. inserts/updates/deletesdeletevarvineyardsToDelete= fromVineyards v in db.Vineyardswherev.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
  • 27. inserts/updates/deletesvarvineyardsToDelete= fromVineyards v indb.Vineyards wherev.Country== “Australia"select v;foreach (Vineyards v invineyardsToDelete){db.Wines.DeleteAllOnSubmit(v.Wines);}db.Vineyards.DeleteAllOnSubmit(vineyardsToDelete);db.SubmitChanges();
  • 28. database schema upgradesDatabaseSchemaUpdater allows for simple upgrades on your existing DBIt offers the ability to addTablesColumnsIndicesAssociations/foreign keysAll schema updates are transactionalMore complex schema upgrades require full DB migration
  • 29. Database Schema UpgradesCreate a new DatabaseSchemaUpdaterMyDerivedDataContext context = newMyDerivedDataContext("foo.sdf");DatabaseSchemaUpdaterdbUpdater = context.CreateDatabaseSchemaUpdater();Add a new table tied to the Product classdbUpdater.AddTable<Winemaker>();Add a Region column to the Customer tabledbUpdater.AddColumn<Vineyard>(“YearEstablished");Execute upgradedbUpdater.Execute();
  • 30. performance and best practiceskeep change sets smallSubmit early and often to avoid data loss on app terminationuse background threadsNon-trivial operations will impact app responsiveness if done on UI threadoptimize read-only queriesSet ObjectTrackingEnabled to minimize memory usageuse secondary indices for properties which you query often
  • 31. performance and best practicespopulate large reference data tables in advanceCreate a simple project to prepopulate data in emulatorPull out database file using Isolated Storage explorerwhen to use a database…expect some impact to startup time and memory usage from incorporating a DBstick to IsolatedStorageSettings or basic files for small data sets
  • 33. new and updated APIs in “Mango”Chooser Tasks related to user dataEmailAddressChooserTaskPhoneNumberChooserTaskAddressChooserTaskMicrosoft.Phone.UserData for direct accessContactsAppointments
  • 34. AddressChooserTaskprivateAddressChooserTaskaddressChooserTask;// ConstructorpublicMainPage(){this.addressChooserTask= newAddressChooserTask();this.addressChooserTask.Completed += newEventHandler<AddressResult>(addressChooserTask_Completed);}privatevoidaddressChooserTask_Completed(objectsender, AddressResulte){if(null == e.Error && TaskResult.OK == e.TaskResult) {... = e.DisplayName;... = e.Address;}}
  • 35. Microsoft.Phone.UserDataImportant pointsContacts and Appointments APIs are read onlyThird party social network data cannot be shared
  • 37. contacts: hello, world!Contactscontacts = newContacts();contacts.SearchCompleted+= newEventHandler<ContactsSearchEventArgs>((sender, e) => {...= e.Results; });// E.g. search for all contactscontacts.SearchAsync(string.Empty, FilterKind.None, null);state// E.g. search for all contacts with display name matching "ja"contacts.SearchAsync("ja", FilterKind.DisplayName, null);filter expression(not a regex)Filter kind: name, email , phone or pinned to start)
  • 38. appointments: hello, world!Appointmentsappointments = newAppointments();appointments.SearchCompleted+= newEventHandler<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 timeend date and timeMaximum items to returnstate
  • 39. performance and best practicesbe responsibleyour privacy policy should cover how you use the user’s contact informationkeep 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
  • 40. demo35/ linq to sql/ datacontext/ CRUD/ user data04 user manager
  • 43. 38