Matthew Baxter-Reynolds - Booting Metro-style Apps


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Must say *SPECIFICALLY* - must really hit thisNuggets of information - “First of all… <concept> <more info>” *beat* - “Secondly…” *beat* - “Next…” *beat* - “And finally”Musicality of the voice
  • Metro has been around a while…In BUILD last year we got WinRT…The naming is somewhat confused…Metro-style primarily about iPad-clone…
  • WinDiv, notDevDiv…
  • Cutting off things you can’t use…Cutting off things you shouldn’t use…
  • Fighting a battle on two fronts…
  • Matthew Baxter-Reynolds - Booting Metro-style Apps

    1. 1. Booting Metro-style Apps Matthew Baxter-Reynolds May 2012 @mbrit | Slides: 1
    2. 2. Objectives • Get you up and running Metro-style apps… – Understand the new process model proposed by Metro-style – Specifically, build an app with…  A simple XAML user interface  Demonstrates asynchronous programming  Handles JSON and HTTP  Stores data in with SQLite databasesTwitter: @mbrit | Slides: 2
    3. 3. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: 3
    4. 4. Bits you’ll need • Source code for this tutorial can be found at: – troStyle • Use the link at the bottom of each slide to get a copy of these slidesTwitter: @mbrit | Slides: 4
    5. 5. What is Metro-style?Twitter: @mbrit | Slides: 5
    6. 6. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: 6
    7. 7. What is Metro-style? • Metro-style is the name of the new process model used for packaging and executing applications for Windows 8 and Windows RT – WinRT is the API – Build the UI in XAML/C# or HTML5/JavaScript  …or DirectX/C++ – Sandboxed/restricted – Distributed through the Microsoft StoreTwitter: @mbrit | Slides: 7
    8. 8. WinRT • WinRT… – Just happens to be happening along with Windows 8/Windows RT  It’s part of a far broader strategy to replace Win32 – It’s COM, but only more so  Integrates beautifully with .NET  For example, XAML controls are now WinRT unmanaged controls, but you wouldn’t know it  Shares the .NET metadata file formatTwitter: @mbrit | Slides: 8
    9. 9. “.NET Core” • You have to use a cut-down profile of .NET – Precedent for this:  .NET Compact Framework, Silverlight for Windows PhoneTwitter: @mbrit | Slides: 9
    10. 10. XAML vs HTML5 • Two user interface tracks – …well, “three” if you include DirectX with C++ – XAML and C# – HTML and JavaScript • We’re going to be concentrating on XAML – Most likely path of least resistance in the short term – How good is the HTML5 tooling likely to be? – Better for us all if we can get it over to a good HTML5 offeringTwitter: @mbrit | Slides: 10
    11. 11. Special project templates Distinct set of templates for Metro-styleTwitter: @mbrit | Slides: 11
    12. 12. Special referencing References are shown as “packages” Reflector shows a special Windows reference. This is actually WinRTTwitter: @mbrit | Slides: 12
    13. 13. Limited options “.NET Core” is just one thingTwitter: @mbrit | Slides: 13
    14. 14. Building a user interfaceTwitter: @mbrit | Slides: 14
    15. 15. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: 15
    16. 16. “StreetFoo” • I have a service up on AppHarbor that we’re going to consume – It contains reports of problems with a user’s local environment…  e.g. graffiti, broken paving slabs, dumped rubbish – It has a “REST-like” API  Intentionally “non-beautiful” – Operations…  Register user, logon, get reports for logged on user – @mbrit | Slides: 16
    17. 17. XAML • The XAML implementation is not .NET – Hence why it’s not called “WPF” – It’s COM-based – Most of the types are the sameTwitter: @mbrit | Slides: 17
    18. 18. XAML for non-Silverlight/non-WPF developers • XAML is very different from HTML… – Like HTML, XAML is declarative – XAML is not document-centric  With XAML when you position things, other things don’t move out of the way – Styling is rudimentary, compared to CSS3 – XAML is an object-graph expressed as XMLTwitter: @mbrit | Slides: 18
    19. 19. XAML for non-Silverlight/non-WPF developers (2)Twitter: @mbrit | Slides: 19
    20. 20. Model View View-Model (MVVM) • Preferred pattern for XAML – No out-of-the-box implementation – Calburn.Micro and MVVM Light expected to get strong in this space • Components: – Model: Your actual domain data  e.g. a database made up of “Customers” and “Invoices” – View: The markup that defines your view  i.e. some XAML – View-model: A combination of old-school controller logic, and a subset of your domain data  e.g. a single customer and their related invoicesTwitter: @mbrit | Slides: 20
    21. 21. Data binding • As the view is not supposed to contain logic, expectation is that you use binding expressions in the XAML • The Page class’ DataContext property is used to associate a view-model – The view-model must support notification:  Windows.Foundation.Collections.IObservableMap  Windows.UI.Xaml.Data.INotifyPropertyChangedTwitter: @mbrit | Slides: 21
    22. 22. Command binding • In proper implementations, XAML is supposed to use “command binding” to wire up control events to handlers… – As opposed to the “Visual Basic” model of a special handler method – These are any class that supports System.Windows.Input.ICommand – Expose the command out from the view-model as a property and use the Binding expression in XAML as normal – (But it’s overkill for today so we’re skipping it!)Twitter: @mbrit | Slides: 22
    23. 23. Data binding out-of-the-box • By default, new VS11 Metro-style app templates give you a class called LayoutAwarePage – Basic idea is to deal with snapping the view to the edge of the screen – …but it also provides a DefaultViewModel out of the box  DefaultViewModel signals changes via IObservableMap – We can use DefaultViewModel, if we ignore the fact it’s supposed to be a different class  Not perfect, but OK for todayTwitter: @mbrit | Slides: 23
    24. 24. Using data binding out-of-the-box Created by VS on project inception Setup the model when we start Expose properties for each model value We’ll need to build these magic methodsTwitter: @mbrit | Slides: 24
    25. 25. Using data binding out-of-the-box (2) Use the built-in XAML extension to declare bindings Remember to specify TwoWay to set values from the UI back into the view-modelTwitter: @mbrit | Slides: 25
    26. 26. Using data binding out-of-the-box (3) Use the fantastic CallerMemberName attribute so that you don’t have to muck about with names and keys Defer to the provided-for-you DefaultViewModel for storage Change notifications will be sent when you set valuesTwitter: @mbrit | Slides: 26
    27. 27. Event handling • As you might expect…Twitter: @mbrit | Slides: 27
    28. 28. Exercise: Building a logon form • Build a new application that captures logon details… – Create a logon form – Create an ad hoc view-model using the LayoutAwarePage class’ DefaultViewModel that stores the username and password – Display the contents of the Username and Password properties  Use Windows.UI.Popups.MessageDialog to do thisTwitter: @mbrit | Slides: 28
    29. 29. Summing upTwitter: @mbrit | Slides: 29
    30. 30. Making an HTTP requestTwitter: @mbrit | Slides: 30
    31. 31. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: 31
    32. 32. StreetFoo server requests • JSON up, JSON down • Use isOk value to check for errors – error value is always set is not • This is the Register request/response: – @mbrit | Slides: 32
    33. 33. StreetFoo API key • You’ll need an API key… – Visit and grab one – Needs to be sent up with every request  apiKey value  (You an see that in the JSON from before)Twitter: @mbrit | Slides: 33
    34. 34. A word about HTTPS • Although all AppHarbor hosted sites expose SSL, it doesn’t work properly with the Consumer Preview drop – Always use HTTP todayTwitter: @mbrit | Slides: 34
    35. 35. Asynchronous calls • Accepted practice on mobile is not to block the UI thread – For example, in the HTML space…   • Anything that we do in Metro-style has to use async calls appropriatelyTwitter: @mbrit | Slides: 35
    36. 36. Task Parallel Library (TPL) • All of WinRT’s async stuff is based on the Task Parallel Library (TPL) – Introduced with .NET 4.0 – Used for scheduling parallel operations – Slightly overkill for async handling – Quite lovely  …plus ever-so much better than .NET’s previous effort – Quite complicated to explain…Twitter: @mbrit | Slides: 36
    37. 37. Task Parallel Library (2) • Base currency is the Task – It’s just a unit of workTwitter: @mbrit | Slides: 37
    38. 38. Task Parallel Library (3) • You can add continuation handlers to Task instances – (Which are callbacks, essentially) You’re more likely to see something like this, thoughTwitter: @mbrit | Slides: 38
    39. 39. Task Parallel Library (3) • The final piece of magic is the Result… – Use Task<T> to indicate you want a resultTwitter: @mbrit | Slides: 39
    40. 40. Updating the UI from a worker thread • A wrinkle to all this is that because we’re on a worker thread, we need to marshal control back to the UI to change it – System.Threading.SyncronizationContext.Current should be the way to do this  (But I couldn’t get that working properly for today)Twitter: @mbrit | Slides: 40
    41. 41. Updating the UI from a worker thread (2) • Here’s an extension method for Page that will marshal a delegate over to the UI thread…Twitter: @mbrit | Slides: 41
    42. 42. JSON • JSON support in WinRT is different to .NET – No more JavaScriptSerializer – Use:  Windows.Data.JsonObject o Stringify, Parse o AddValue (with JsonValue.CreateXxxValue) o GetNamedString  Windows.Data.JsonArray o Need to be explicit about parsing arraysTwitter: @mbrit | Slides: 42
    43. 43. Exercise: Calling a server • Modify your app to have a Register page – You’ll need Username, Email, Password, and Confirm fields  Use the DefaultViewModel as before  Add a button to Logon form and use Frame.Navigate to go to the Register page – Have the Register page call the server…Twitter: @mbrit | Slides: 43
    44. 44. Exercise: Calling a server (2) • Make the server call – Create a JsonObject with the values you want to send – Use:  System.Net.HttpWebRequest.CreateHttpRequest  Configure it to send a POST verb  Use GetRequestStreamAsync to get a Task, then use ContinueWith to provide a callback  Use System.Encoding.UTF8.GetBytes to turn the JSON into bytes  Send the bytes  Use GetResponse to get an HttpWebResponse object back  Read the values, parse them using JsonObjectTwitter: @mbrit | Slides: 44
    45. 45. Summing upTwitter: @mbrit | Slides: 45
    46. 46. Using SQLiteTwitter: @mbrit | Slides: 46
    47. 47. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: 47
    48. 48. Local persistence • For most platforms, this story is pretty good: – iOS – baked in SQLite, native driver or Core Data – Android – baked in SQLite, native driver – BlackBerry – baked in SQLite, native driver • Windows Phone and Metro-style? – *crickets*Twitter: @mbrit | Slides: 48
    49. 49. SQLite and Windows • Various methods for using SQLite on Windows Phone and in Metro-style – The main library for both is sqlite-net  – SQLite has committed to providing first-class support for WinRT  Current implementation not in the main branch  We have to access it through a not-yet-supported branchTwitter: @mbrit | Slides: 49
    50. 50. Linking in SQLite • Create a new project • Add sqlite-net files: – – Take ~/src/SQLite.cs and ~/src/SQLiteAsync.cs and put them in your project • Add sqlite3.dll: – – Take ~/bin/sqlite3.dll – Save somewhere on your machine – “Project – Add item”, and point at sqlite3.dll  Don’t add a project reference!Twitter: @mbrit | Slides: 50
    51. 51. Linking in SQLite (2)Twitter: @mbrit | Slides: 51
    52. 52. sqlite-net Micro-ORM • What you might expect from a Micro-ORM • Original version had a synchronous API – An asynchronous API is now available – Two separate connection classes for clarity  SQLiteConnection  SQLiteAsyncConnection – Async version uses a custom connection pool and the standard TPL • In Metro-style, the database goes into the correct folder automaticallyTwitter: @mbrit | Slides: 52
    53. 53. sqlite-net Micro-ORM (2) • Entities defined with attributes:Twitter: @mbrit | Slides: 53
    54. 54. sqlite-net Micro-ORM (3) • Main operations: – CreateTableAsync<T> – InsertAsync – UpdateAsync – DeleteAsync – Table<T> (preps retrieval query)  …followed by ToListAsync, FirstAsync, or FirstOrDefaultAsync  Database only accessed when you call one of the retrieval methodsTwitter: @mbrit | Slides: 54
    55. 55. Create table and insert Special factory for creating connections TPL used for making calls Once you’re in a worker thread, it’s OK to use “await”Twitter: @mbrit | Slides: 55
    56. 56. Querying data All this does is change the query – the database isn’t touched until we call ToListAsyncTwitter: @mbrit | Slides: 56
    57. 57. Objective • Modify the application so that it can… – Call the server and get a list of reports from the StreetFoo service – Store those reports in a SQLite database – Loaded the cached reports from SQLite and display them on a view • We’ll now clarify those points!Twitter: @mbrit | Slides: 57
    58. 58. StreetFoo Report Data • Example:Twitter: @mbrit | Slides: 58
    59. 59. What you’re aiming for This is the default template, so we don’t need to do much with the viewTwitter: @mbrit | Slides: 59
    60. 60. Sample data • To create sample data: – Go to and click “Create Sample Data” – You’ll need your API key and the username of a user on your account to do thisTwitter: @mbrit | Slides: 60
    61. 61. Process flow • Ideally, we want to make a network call to refresh our cache and always use the cache for display purposes – (Because if we can support running offline, we should) Cache Update View-model Engine Response Display Request SQLite StreetFoo View ServerTwitter: @mbrit | Slides: 61
    62. 62. Getting reports from the server • etReportsByUser.ashxTwitter: @mbrit | Slides: 62
    63. 63. Modeling the reportTwitter: @mbrit | Slides: 63
    64. 64. Managing SQLite databases • Each application is likely to have two databases – A system database for storing settings  (We’re not seeing that today)  e.g. “StreetFoo-system.db” – A user database, bound into the actual user’s account  An easy way to do this is to use the username  e.g. string.Format(“StreetFoo-user-{0}.db”, Username);Twitter: @mbrit | Slides: 64
    65. 65. The “Logon” method • When we logon, we need to ensure the user’s database is created… – Create an AppRuntime class to manage this – Add a Logon method…Twitter: @mbrit | Slides: 65
    66. 66. Updating the cache • Create a service proxy that will call the GetReportsForUser method on the server – Don’t forget to pass up the logon token • This will return you back a set of reports… – Use JsonArray to parse the JSON – Transform each one into a ReportItem – Use the NativeId to find an existing instance…  Update the existing one if there  Insert a new one if not there – Bonus points  Remove obsolete entriesTwitter: @mbrit | Slides: 66
    67. 67. Remember this?Twitter: @mbrit | Slides: 67
    68. 68. Displaying lists • Use the Items Page template type to create a new grid…Twitter: @mbrit | Slides: 68
    69. 69. Report listing view-model Use ObservableCollection so XAML knows to update the grid when the list changes Set the ItemsSource to be the Reports value in the view-modelTwitter: @mbrit | Slides: 69
    70. 70. Exercise: Download reports and display them on a grid • Update the application to… – Initialise a SQLite database on successful logon – Download JSON containing the reports from the server – Update the local SQLite-based cache of reports – Load the cached reports and put them on the gridTwitter: @mbrit | Slides: 70
    71. 71. Summing upTwitter: @mbrit | Slides: 71
    72. 72. The End Matthew Baxter-Reynolds Independent software development consultant, speaker, author and trainer @mbritIdea icon: The Noun ProjectBeaker icon: The Noun ProjectFloppy disk icon: Mike Wirth, from The Noun ProjectAperture icon: P.J. Onori, from The Noun ProjectBarking dog icon: The Noun ProjectApprove icon: from The Noun Project Twitter: @mbrit | Slides: 72