Download presentation
Presentation is loading. Please wait.
Published byCornelia Oliver Modified over 9 years ago
2
Andy Wigley APPA Mundi @andy_wigley http://bit.ly/andywigley andy.wigley@appamundi.com New Data Features in “Mango”: SQL Server Compact and User Data Access
3
LINQ 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 Session Outline
4
LINQ to Everything
5
Complex Schema Numerous relationships and constraints Example: Shopping List – 7 tables – 100s of records – 5 foreign keys
6
Reference Data Huge amounts of static reference data Example: dictionary app – 3 tables – 1 table with 500k rows
7
Web Service Cache Fetch reference data from cloud Cache locally Combine with user-specific data Cloud Service Windows Phone
8
User Data Filter contacts – Birthdays in the next month Query all appointments – Find an available time for a meeting Filter
9
Local Database Storage
10
Database Support
11
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 Application Settings File App Creates/Manages files and settings Application Files Iso Store Folder Creates root folder sandboxed to App Package Manager App Data Folder WP7 Isolated Storage APIs Install DB Database file DB Database File (r/o)
12
Architecture Custom Data Context App Objects Identity Management Change Tracking Update Processing Object Materialization 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 Name from Wines where Country = “USA”
13
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
14
Database Creation: Example // Define the data context. public partial class WineDataContext : DataContext { public Table Wines; public Table 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();
15
Queries: Examples // Create the database form data context, using a connection string DataContext db = new WineDataContext("isostore:/wineDB.sdf"); // Find all wines currently at home, ordered by date acquired var q = from w in db.Wines where w.Varietal.Name == “Shiraz” && w.IsAtHome == true orderby w.DateAcquired select w;
16
DB NameLittle Penguin VarietalPinot Noir AtHome False NameLittle Penguin VarietalPinot 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 NameLittle Penguin VarietalPinot Noir AtHome False NameYellow Tail VarietalPinot Noir AtHome True
17
Inserts/Updates/Deletes Insert 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();
18
Inserts/Updates/Deletes Delete var vineyardsToDelete = from Vineyards v in db.Vineyards where v.Country == “Australia” select v; db.Vineyards.DeleteAllOnSubmit (vineyardsToDelete); db.SubmitChanges();
19
Programming SQL Server Compact
20
Relationships Express one-many, one-one and many-many relationships using EntitySet and EntityRef columns In the relational database, a child table has a column – the Foreign Key - that stores the unique ID of a record in the parent table
21
Example: Parent Object [Table] public class Contact : INotifyPropertyChanged, INotifyPropertyChanging { // Fields private EntitySet leads = new EntitySet (); [Association(Storage = "leads", OtherKey = "ContactID")] public EntitySet Leads { get { return this.leads; } set { InvokePropertyChanging(new PropertyChangingEventArgs("Leads")); this.leads.Assign(value); InvokePropertyChanged( new PropertyChangedEventArgs("Leads")); }
22
Example: Child Object [Table] [Index (Name="ContactID_Idx", Columns="ContactID", IsUnique=false)] public class Lead : INotifyPropertyChanged, INotifyPropertyChanging { private EntityRef contact; [Column] public long ContactID {get; set; } [Association(Storage = "contact", ThisKey = "ContactID", IsForeignKey=true)] public Contact Contact { get { return this.contact.Entity; } set { InvokePropertyChanging(new PropertyChangingEventArgs("Contact")); this.contact.Entity = value; InvokePropertyChanged(new PropertyChangedEventArgs("Contact")); if (value != null) this.ContactID = value.ContactID; }
23
Deletes Delete var vineyardsToDelete = from Vineyards v in db.Vineyards where v.Country == “Australia” select v; db.Vineyards.DeleteAllOnSubmit (vineyardsToDelete); db.SubmitChanges();
24
Delete Child Objects First var 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();
25
Entity Relationships Foreign Keys
26
Database Schema Upgrades DatabaseSchemaUpdater allows simple upgrades on your existing DB Supports adding – Tables – Columns – Indices – Associations/foreign keys Schema updates are transactional
27
Database Schema Upgrades WineDataContext wineDC = new WineDataContext(App.WineDBConnectionString); DatabaseSchemaUpdater dsu = wineDC.CreateDatabaseSchemaUpdater(); if (dsu.DatabaseSchemaVersion == 1) { dsu.AddColumn ("BottleType"); dsu.DatabaseSchemaVersion = 2; dsu.Execute(); }
28
Schema Upgrades
29
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
30
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 Use the right tool for the job – Database for large or complex data sets – IsolatedStorageSettings or basic files for small data sets
31
User Data
32
New and updated APIs in “Mango” Chooser Tasks related to user data – EmailAddressChooserTask – PhoneNumberChooserTask – AddressChooserTask Microsoft.Phone.UserData for direct access – Contacts – Appointments
33
AddressChooserTask private AddressChooserTask addressChooserTask; // Constructor public MainPage() { this.addressChooserTask = new AddressChooserTask(); this.addressChooserTask.Completed += new EventHandler ( addressChooserTask_Completed); } private void addressChooserTask_Completed(object sender, AddressResult e) { if (null == e.Error && TaskResult.OK == e.TaskResult) {... = e.DisplayName;... = e.Address; }
34
Contacts and Appointments Important points – Contacts and Appointments APIs are read only – Third party social network data cannot be shared
35
Contacts/Appointments Data Shared Contact Name and Picture Other contact dataAppointments/Events Windows Live SocialYES Windows Live Rolodex (user created and SIM import) YES n/a Exchange accounts (corporate plus Google, etc.) YES Operator Address BooksYES n/a FacebookYESNO Other networks in the People Hub (e.g., Twitter) NO
36
Contacts: Hello, World! Contacts contacts = new Contacts(); contacts.SearchCompleted += new EventHandler ((sender, e) => {... = e.Results; }); // E.g. search for all contacts contacts.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);
37
Appointments: Hello, World! Appointments appointments = new Appointments(); appointments.SearchCompleted += new EventHandler ((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 state end date and time
38
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
39
Accessing User Data
40
Q&A
41
© 2008 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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.