10 wp7 local database

3,899 views

Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

10 wp7 local database

  1. 1. Windows Phone 7<br />Li Jingnan / Wang Tao<br />2011-7-15<br />1<br />
  2. 2. 2 days<br />2<br />
  3. 3. ethos<br />http://www.ethostechnologies.com/<br />One of the 1st ISVs for cloud computing in Europe and China.<br />Cloud computing development partner with Microsoft in Greater China Region.<br />Invited to speak about Azure at several Microsoft events.<br />
  4. 4. about<br />anytao| Ethos<br /><ethos:Member<br /> id = “Wang Tao”<br /> msn = anytao@live.com<br />weibo = http://weibo.com/anytao<br />runat = “Senior System Architect”<br />/><br />Jason | Ethos<br /><ethos:Member<br /> id = “Li Jingnan”<br /> msn = zengnami@hotmail.com<br />weibo= http://weibo.com/jn1981<br />runat = “SE”<br />/><br />
  5. 5. about<br />http://book.anytao.net<br />
  6. 6. 10 Local Database<br />Wang Tao / 2011-07-15<br />
  7. 7. session outline<br />LINQ to SQL<br />LINQ to User Data<br />overview<br />architecture<br />code-first development<br />implementation details<br />queries<br />inserts, updates, deletes…<br />database schema upgrades<br />performance and best practices<br />overview<br />end-user consent<br />supported account types<br />implementation details<br />querying contacts<br />querying appointments<br />performance and best practices<br />
  8. 8. LINQ to everything<br />LINQ<br />Objects<br />XML<br />SQL<br />User Data<br />OData<br />7<br />Mango<br />
  9. 9. complex schema<br />numerous relationships and constraints<br />example: shopping list<br />7 tables<br />100s of records<br />5 foreign keys<br />
  10. 10. Reference Data<br />Huge amounts of static reference data<br />Example: dictionary app<br />3 tables<br />1 table with 500k rows<br />
  11. 11. web service cache<br />Cloud Service<br />fetch reference data from cloud<br />cache it locally<br />combine with user-specific data<br />Windows Phone<br />Service Cache<br />User Data<br />
  12. 12. user data<br />filter contacts<br />birthdays in the next month<br />query all appointments<br />find an available time for a meeting<br />Filter<br />
  13. 13. database support<br />
  14. 14. local data storage: overview<br />apps store private data in Isolated Storage<br /><ul><li>settings and properties in the app dictionary
  15. 15. unstructured data in Isolated Storage files
  16. 16. structured data in database files</li></ul>App Root Folder<br />Install<br />Package Manager<br />Creates root folder<br />sandboxed to App<br />DB<br />Database<br />File (r/o)<br />App Data Folder<br />Creates/Manages<br />files and settings<br />App<br />WP7 Isolated Storage APIs<br />DB<br />Application<br />Settings File<br />Application<br />Files<br />Database file<br />
  17. 17. architecture<br />Your App<br />Custom Data Context<br />App Objects<br />var query = fromw indb.Wines<br />wherew.Country== “USA"<br />selectw.Name;<br />System.Data.Linq<br />Identity Management<br />Change Tracking<br />Update Processing<br />Object Materialization<br />.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}<br />select Name<br />from Wines<br />where Country = “USA”<br />Microsoft.Phone.Data.Internal<br /> Core ADO.NET (System.Data)<br />SQL CE DB<br />SQLCE ADO.NET Provider (System.Data.SqlServerCe)<br />
  18. 18. code first development<br />Design time<br /><ul><li>Create object model: wines, varietals, vineyards, etc.
  19. 19. Decorate objects with attributes for persistence</li></ul>Varietals<br />Wines<br />Vineyards<br />WineMakers<br /><ul><li>Create DataContextreference to database
  20. 20. Translate object model into a database file
  21. 21. Submit API persists changes to DB</li></ul>Run time<br />Database upgrade<br /><ul><li>Create new objects to enable new features
  22. 22. Use upgrade APIs to change DB</li></li></ul><li>database creation: example<br />// Define the data context.<br />publicpartialclassWineDataContext: DataContext<br />{<br />publicTable<Wine> Wines;<br />publicTable<Vineyard> Vineyards;<br />publicWineDataContext(stringconnection) : base(connection) { }<br />}<br />// Define the tables in the database<br />[Table]<br />publicclassWine<br />{<br />[Column(IsPrimaryKey=true]<br />publicstringWineID{ get; set; }<br />[Column]<br />publicstringName { get; set; }<br />……<br />}<br />// Create the database form data context, using a connection string<br />DataContextdb = newWineDataContext("isostore:/wineDB.sdf");<br />if (!db.DatabaseExists()) db.CreateDatabase();<br />
  23. 23. queries: examples<br />// Create the database form data context, using a connection string<br />DataContextdb = newWineDataContext("isostore:/wineDB.sdf");<br />// Find all wines currently at home, ordered by date acquired<br />varq = from w indb.Wines<br /> wherew.Varietal.Name == “Shiraz” && w.IsAtHome == true<br />orderbyw.DateAcquired<br /> select w;<br />
  24. 24. Inserts/Updates/Deletes<br />Your App Code<br />It’s all about the DataContext<br />Changes made against the DataContext first<br />Changes persisted by calling SubmitChanges()<br />SubmitChanges<br />LINQ to SQL determines change set and submits to DB<br />DataContext<br />DB<br />
  25. 25. inserts/updates/deletes<br />update<br />insert<br />WinenewWine= newWine<br />{<br />WineID= “1768",<br />Name = “Windows Phone Syrah",<br />Description = “Bold and spicy"<br />};<br />db.Wines.InsertOnSubmit(newWine);<br />db.SubmitChanges();<br />Winewine= <br />(fromw indb.Wines<br /> wherew.WineID== “1768"<br />select w).First();<br />wine.Description= “Hints of plum and melon";<br />db.SubmitChanges();<br />
  26. 26. inserts/updates/deletes<br />delete<br />varvineyardsToDelete= <br />fromVineyards v in db.Vineyards<br />wherev.Country== “Australia”<br />select v;<br />db.Vineyards.DeleteAllOnSubmit<br />(vineyardsToDelete);<br />db.SubmitChanges();<br />Foreign key constraint will cause exception here if Wines associated with the Vineyards are not deleted first<br />
  27. 27. inserts/updates/deletes<br />varvineyardsToDelete= fromVineyards v indb.Vineyards<br /> wherev.Country== “Australia"<br />select v;<br />foreach (Vineyards v invineyardsToDelete)<br />{<br />db.Wines.DeleteAllOnSubmit(v.Wines);<br />}<br />db.Vineyards.DeleteAllOnSubmit(vineyardsToDelete);<br />db.SubmitChanges();<br />
  28. 28. database schema upgrades<br />DatabaseSchemaUpdater allows for simple upgrades on your existing DB<br />It offers the ability to add<br />Tables<br />Columns<br />Indices<br />Associations/foreign keys<br />All schema updates are transactional<br />More complex schema upgrades require full DB migration<br />
  29. 29. Database Schema Upgrades<br />Create a new DatabaseSchemaUpdater<br />MyDerivedDataContext context = newMyDerivedDataContext("foo.sdf");DatabaseSchemaUpdaterdbUpdater = context.CreateDatabaseSchemaUpdater();<br />Add a new table tied to the Product class<br />dbUpdater.AddTable<Winemaker>();<br />Add a Region column to the Customer table<br />dbUpdater.AddColumn<Vineyard>(“YearEstablished");<br />Execute upgrade<br />dbUpdater.Execute();<br />
  30. 30. performance and best practices<br />keep change sets small<br />Submit early and often to avoid data loss on app termination<br />use background threads<br />Non-trivial operations will impact app responsiveness if done on UI thread<br />optimize read-only queries<br />Set ObjectTrackingEnabled to minimize memory usage<br />use secondary indices for properties which you query often<br />
  31. 31. performance and best practices<br />populate large reference data tables in advance<br />Create a simple project to prepopulate data in emulator<br />Pull out database file using Isolated Storage explorer<br />when to use a database…<br />expect some impact to startup time and memory usage from incorporating a DB<br />stick to IsolatedStorageSettings or basic files for small data sets<br />
  32. 32. user data<br />
  33. 33. new and updated APIs in “Mango”<br />Chooser Tasks related to user data<br />EmailAddressChooserTask<br />PhoneNumberChooserTask<br />AddressChooserTask<br />Microsoft.Phone.UserData for direct access<br />Contacts<br />Appointments<br />
  34. 34. AddressChooserTask<br />privateAddressChooserTaskaddressChooserTask;<br />// Constructor<br />publicMainPage()<br />{<br />this.addressChooserTask= newAddressChooserTask();<br />this.addressChooserTask.Completed += new<br />EventHandler<AddressResult>(<br />addressChooserTask_Completed);<br />}<br />privatevoidaddressChooserTask_Completed(objectsender, AddressResulte)<br />{<br />if(null == e.Error && TaskResult.OK == e.TaskResult)<br /> {<br />... = e.DisplayName;<br />... = e.Address;<br />}<br />}<br />
  35. 35. Microsoft.Phone.UserData<br />Important points<br />Contacts and Appointments APIs are read only<br />Third party social network data cannot be shared<br />
  36. 36. Contacts/Appointments Data Shared<br />
  37. 37. contacts: hello, world!<br />Contactscontacts = newContacts();<br />contacts.SearchCompleted+= newEventHandler<ContactsSearchEventArgs>((sender, e) =><br /> {<br />...= e.Results;<br /> });<br />// E.g. search for all contacts<br />contacts.SearchAsync(string.Empty, FilterKind.None, null);<br />state<br />// E.g. search for all contacts with display name matching "ja"<br />contacts.SearchAsync("ja", FilterKind.DisplayName, null);<br />filter expression<br />(not a regex)<br />Filter kind: name, email , phone or pinned to start)<br />
  38. 38. appointments: hello, world!<br />Appointmentsappointments = newAppointments();<br />appointments.SearchCompleted+= newEventHandler<AppointmentsSearchEventArgs>((sender, e) =><br /> {<br />... = e.Results;<br /> });<br />// E.g. get next appointment (up to 1 week away)<br />appointments.SearchAsync(DateTime.Now,<br />DateTime.Now+ TimeSpan.FromDays(7),<br /> 1, null);<br />start date and time<br />end date and time<br />Maximum items to return<br />state<br />
  39. 39. performance and best practices<br />be responsible<br />your privacy policy should cover how you use the user’s contact information<br />keep out of the way<br />users have widely varying contact list sizes <br />your UI should handle delays gracefully <br />don’t let data get stale<br />data returned is a snapshot<br />refresh state when reasonable<br />
  40. 40. demo<br />35<br />/ linq to sql<br />/ datacontext<br />/ CRUD<br />/ user data<br />04 user manager<br />
  41. 41. practice<br />36<br />a todo list<br />
  42. 42. thank you<br />37<br />thank youwww.anytao.com<br />
  43. 43. 38<br />

×