Matthew Baxter-Reynolds - Booting Metro-style Apps

2,002 views

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,002
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
4
Comments
0
Likes
2
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 http://programmingmetrostyle.com/Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 2
    3. 3. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 3
    4. 4. Bits you’ll need • Source code for this tutorial can be found at: – https://github.com/mbrit/ProgNet2012BootingMe troStyle • Use the bit.ly link at the bottom of each slide to get a copy of these slidesTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 4
    5. 5. What is Metro-style?Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 5
    6. 6. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 10
    11. 11. Special project templates Distinct set of templates for Metro-styleTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 11
    12. 12. Special referencing References are shown as “packages” Reflector shows a special Windows reference. This is actually WinRTTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 12
    13. 13. Limited options “.NET Core” is just one thingTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 13
    14. 14. Building a user interfaceTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 14
    15. 15. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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 – http://streetfoo.apphb.com/Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 18
    19. 19. XAML for non-Silverlight/non-WPF developers (2)Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 26
    27. 27. Event handling • As you might expect…Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 28
    29. 29. Summing upTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 29
    30. 30. Making an HTTP requestTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 30
    31. 31. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: – http://streetfoo.apphb.com/Handlers/HandleRegister.ashxTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 32
    33. 33. StreetFoo API key • You’ll need an API key… – Visit http://streetfoo.apphb.com/ 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 34
    35. 35. Asynchronous calls • Accepted practice on mobile is not to block the UI thread – For example, in the HTML space…  http://www.html5rocks.com/en/tutorials/file/filesystem/  http://api.jquery.com/jQuery.ajax/ • Anything that we do in Metro-style has to use async calls appropriatelyTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 36
    37. 37. Task Parallel Library (2) • Base currency is the Task – It’s just a unit of workTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 44
    45. 45. Summing upTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 45
    46. 46. Using SQLiteTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 46
    47. 47. Sections What is Metro-style? Making HTTP Building a UI Using SQLite requestsTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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  https://github.com/praeclarum/sqlite-net – SQLite has committed to providing first-class support for WinRT  Current implementation not in the main SQLite.org branch  We have to access it through a not-yet-supported branchTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 49
    50. 50. Linking in SQLite • Create a new project • Add sqlite-net files: – https://github.com/praeclarum/sqlite-net – Take ~/src/SQLite.cs and ~/src/SQLiteAsync.cs and put them in your project • Add sqlite3.dll: – https://github.com/mbrit/sqlite-metrostyle – 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: http://slidesha.re/JIywtS 50
    51. 51. Linking in SQLite (2)Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 52
    53. 53. sqlite-net Micro-ORM (2) • Entities defined with attributes:Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 55
    56. 56. Querying data All this does is change the query – the database isn’t touched until we call ToListAsyncTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 57
    58. 58. StreetFoo Report Data • Example:Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 59
    60. 60. Sample data • To create sample data: – Go to http://streetfoo.apphb.com/ 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 61
    62. 62. Getting reports from the server • http://streetfoo.apphb.com/Handlers/HandleG etReportsByUser.ashxTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 62
    63. 63. Modeling the reportTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 66
    67. 67. Remember this?Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 67
    68. 68. Displaying lists • Use the Items Page template type to create a new grid…Twitter: @mbrit | Slides: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 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: http://slidesha.re/JIywtS 70
    71. 71. Summing upTwitter: @mbrit | Slides: http://slidesha.re/JIywtS 71
    72. 72. The End Matthew Baxter-Reynolds Independent software development consultant, speaker, author and trainer http://mbrit.com/ @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: http://slidesha.re/JIywtS 72

    ×