SlideShare ist ein Scribd-Unternehmen logo
1 von 77
Advanced MVVM
Development in Windows 8
SILVERLIGHTSHOW.NET WEBINARS SERIES
GILL CLEEREN
www.snowball.be – gill@snowball.be - @gillcleeren
About me…
• Gill Cleeren
   –   .NET Architect @Ordina
   –   Pluralsight trainer
   –   Microsoft Regional Director
   –   Silverlight MVP / Telerik MVP
   –   Speaker
   –   Visug user group lead
   –   Author
   –   Blog: www.snowball.be
   –   Email: gill@snowball.be
   –   Twitter: @gillcleeren
Agenda

•   Thinking about Modern UI
•   MVVM Overview
•   Building Blocks
     – Commanding
     – ViewModel Locator
     – Messaging
•   Application architecture
•   Navigation and window management
•   Data access and repositories
•   Data binding to Windows 8 controls
•   Working with contracts
     – Share
•   Working with tiles updates
     – Local
     – Push notifications
•   Lifecycle and state management
•   Unit testing the VMs and services
You can win!

Complete the post-webinar survey and win!


        3 free ebooks of choice
   from SilverlightShow Ebook Shelf!

   My ebooks ’Connecting Windows 8
  Apps with Services’ and ‘Windows 8
 and the Future of XAML’ are also there.
Some practical stuff
• Ask questions through Q&A window
  – We’ll answer them after the session or by personal
    mail
• A link to the video recording will be sent to you
THINKING ABOUT MODERN UI
(AKA THE TECHNOLOGY FORMERLY KNOWN AS METRO)
Modern UI is different

• Content before chrome
• Full screen apps
   – Snap view and filled view
• Orientation and rotation
• Windows are now “pages”
• New ways of interacting with an app
   – App bar
   – Charms/Contracts
• Lifecycle and tiles
• …
MVVM and Modern UI
• Currently most Modern UI apps are built in XAML

• MVVM is supported in WPF, Silverlight, Windows Phone…

• Core concepts of XAML are universal
   – Data binding, commands, DataContext…

• Each technology has some specifics
   – Navigation, controls, lifecycle management, background tasks…

• BUT knowledge can be easily leveraged
   – Even to non-XAML based technologies (HTML5 with Knockout
     JS)
It’s a great idea…
to build Windows 8 apps
using MVVM!



We’ll show you how!
MVVM OVERVIEW

For those who might not grasp every concept…
Hello MVVM
• MVVM is an
  architectural
  pattern
   – Based on MVC
     pattern
   – In turn based on
     PresentationMode
     l by Fowler
   – Introduced by
     John Gossman
     (WPF dude)       I <3
                      XAML
Hello MVVM
• Leverages
  power of XAML
  framework
  – Data binding
  – Commanding
Hello MVVM
• Became popular
  with Silverlight
  – Also applicable
    in
     • WPF
     • Windows Phone
       7 and 8
     • Windows
       8/WinRT
Woot, I can finally
   build my code        Here’s the design.
without the designer    Now let me go and
 messing things up!    play with my iPhone.
What we all did when we were
              young…
• Watch Eddy Murphy arrive in America…
• Tom Selleck’s moustache was closely
  monitored
• Record ourselves…
• Shoot ducks (and try shooting the damn dog)
What we all did when we were
               young…
• And write code in code-behind… Lots of it.


                    View


                    XAML


                 Code-Behind
                                  Data Model
                Event Handlers
Meanwhile, in 2013, things have
              changed.
• Not necessarily any better though…
Writing testable code however, is
becoming the norm. Finally. Courtesy
              of MVVM.
              View

              XAML


           Code-Behind

                  Data-binding   Change
                  and            notification
                  commands
           View Model

            State +                     Data Model
           Operations
BUILDING BLOCKS OF MVVM
The View
• Represents the user interface that the user will
  see
• Can be a page, user control or Data Template
• Keep it simple
   – Clean code-behind
   – Only visual logic (all the rest should go in the
     ViewModel)
• Should never contain anything that is to be tested
   – Model-related
The ViewModel
•   An abstraction of View, definition of what can be shown on screen
•   Glue between View and Model
     – Implements INotifyPropertyChanged
•   Contains
     – State properties: data
     – Operations: commands
     – Validation support
•   Should not contain “view properties” such as Color
     – Use converters for this
•   Often wraps or “re-models” the model for the View to use
•   Must be testable
•   No control references!
•   Often, 1 ViewModel per View
     – Can be 1-to-many or many-to-1
•   Manages the flow of the application
•   Interacts with the model
The Model
• Data model, service reference/proxy
  classes, DTO…
  – Very often, an extra layer is added on top of the
    generated proxy classes
• Validation logic
• Data access
• No reference to ViewModel
Linking the View and the ViewModel
• Data binding is the glue but…
• A view needs to “find” its ViewModel
   – ViewModel is the DataContext
• Can be static or dynamic
   – Static: View creates ViewModel and sets it as DataContext
   – Dynamic: at runtime, View selects its ViewModel or vice-
     versa
• 2 options:
   – View-First: ViewModel gets created because View is
     created
   – ViewModel-First: ViewModel is created and View gets
     selected
Locator pattern
• Implemented through a class that contains all
  VMs as properties
• An instance is then made available as Resource
• All Views can bind, no code needed in View
  – Clean way
  – Not good since all VMs need to be known upfront
• Property for each available VM
• Not easy if more than one instance exists of a
  View
  – In this case, some form of IOC is recommended
Commands
      • MVVM-based code have no event handlers in
        code-behind
      • How to handle events happening in the UI?
            Commands
            Based on Command pattern

In object-oriented programming, the command pattern is a behavioral
       design pattern in which an object is used to represent and
encapsulate all the information needed to call a method at a later time.
      his information includes the method name, the object that
       owns the method and values for the method parameters.
Commands
• WinRT has the ICommand interface
  – Execute()
  – CanExecute()
  – CanExecuteChanged event
            public interface ICommand
            {
                      event EventHandler CanExecuteChanged;

                     bool CanExecute(object parameter);
                     void Execute(object parameter);
            }
Commands
• Way to create commands:
  – Write ICommand implementation
  – Create instance on VM
  – Bind Command property of control to this
    instance
• Works only on some controls
• Rest needs to use behaviors
Behaviors

• Block of code that we can attach to XAML element
• Promotes reuse
• Useful in MVVM scenarios on controls that don’t
  support commanding
   – Avoids having code in code-behind
• Supported by Blend
• Not supported by Windows 8 
   – Neither are triggers
   – EventToCommand is therefore not available by default


   – The community has the answer!
Using EventToCommand as a behavior

• Take a look at WinRtBehaviors on CodePlex/NuGet
  (Joost van Schaik)
    <TextBlock Text="TextBlock" FontSize="48">
      <WinRtBehaviors:Interaction.Behaviors>
        <Behaviors:EventToBoundCommandBehavior Event="Tapped"
          Command="{Binding TestCommand}"
          CommandParameter="{Binding TestProperty, Mode=TwoWay}"/>
      </WinRtBehaviors:Interaction.Behaviors>
    </TextBlock>


• Works through Attached behaviors
   – Attached dependency property
Communication between VMs

                 View Model    View Model




    View Model                              View Model




    View Model                              View Model




                  View Model   View Model
Messaging
                                                                       View
      View                                                             XAML
      XAML
                                                                       Code-
     Code-                                                             Behind
     Behind

                                                                     View Model
   View Model                                                                                 Data Model
                                                               State + Operations
                           Data Model
State + Operations
   Message

                Publish
                messages                                                                  View
                                                                                          XAML

                                                                                         Code-
                                                      Subscribe to                       Behind
                                                      messages

                                                                                       View Model
                                   Event Aggregator
                                          Message                                   State + Operations
APPLICATION
ARCHITECTURE
From the ground up!
• Core principles for a testable and maintainable
  architecture
  – Separation of concerns
     • “A new class doesn’t cost a thing”
  – Repositories
  – Loose coupling
  – Dependency injection
  – Unit testing and mocking
CONTOSO COOKBOOK: FRESHLY
BAKED USING MVVM



DEMO
THE CONTAINER
The container
• Loose coupling is achieved through dependency injection
• Dependencies are instantiated and maintained through container
• MVVM Light comes with SimpleIOC
   – Not very extended when it comes to managing lifetime of objects
• NuGet offers alternatives
   – MetroIOC
   – TinyIOC
   – AutoFac
• Can be used to manage
   –   ViewModels
   –   Views
   –   Services
   –   …
Abstraction for the container
• Avoid making direct calls to your container
  from code
• Instead, introduce an abstraction layer for
  your container
• Code not dependent on container
• If container changes, only one class needs
  changing
THE CONTAINER: METROIOC
NAVIGATION AND
WINDOW MANAGEMENT
Navigation
• Windows 8 apps use “new” screens to convey
  information
  – Not many controls and content on screen
  – Navigation == content
  – Result is that we often have to navigate using
    more clicks/taps
• Navigation is based on concept of pages
  – Forward and backward navigation support
Pages and Frames
• Windows 8 apps know pages: this is the “window”, top-
  level control
   – Used as Views in MVVM scenario
   – No visible chrome
• Frame will host pages
   – One page at a time
   – Performs navigation from page to page
      • Frame.Navigate()
      • Frame.GoBack()
   – Single Frame is created at application level
      • First view gets loaded after splash screen
      • Extended splash screen is MVVM view as well
Navigation and SOC
• Navigation is not the task of the ViewModel
• Navigation is not the task of the View
  … and most certainly not the task of the Model
               Then, whose task is it?
• Separate service that has link to Frame
• Called from ViewModels
   – Static
   – Dynamic
• NavigationService is injected in ViewModels through IOC
   – Easily mockable
   – No hard dependency on specific implementation in ViewModels
   – Often, single instance is created application-wide and passed through
     injection/container
Window management
• Windows 8 apps don’t use MDI interfaces,
  have separate windows though
  – Exception dialog
  – Confirmation window
  – Message dialog
• Managed through separate service
  – Called from ViewModels
• Again good news for testing and SOC
DEMO

NAVIGATION AND
WINDOW MANAGEMENT
DATA ACCESS AND REPOSITORIE
Repositories
• Abstraction between data persistence and data
  consumption code
  – Allows changing implementation of persistence code
    without changing consumer
  – Easier to test
  – Creates central location for all data access
     • Advantage in the case where data will be cached locally
• A repository often manages access to single
  resource collection
  – More than one entity type on single repository though
     • Parent-child relation
Data services
• Since repositories often work with a single
  entity, they are not a good hook for the
  ViewModels
  – Would make the ViewModel responsible for
    combining response of several repository reponses
• Create separate service for data acess
  – Per “unit of functionality”
  – Shared between ViewModels
• Often created application-wide through IOC
  container
  – Injected into ViewModels through DI
DATA ACCESS AND REPOSITORIES




DEMO
DATA BINDING TO WINDOWS 8
CONTROLS
Windows 8 and lists of data
• Data lists are everywhere
   –   RSS feeds
   –   Flickr images
   –   News updates
   –   Local file system enumerations
   –   …
• Microsoft has focused on creating controls that work with these
  lists
   –   GridView
   –   ListView
   –   FlipView
   –   Semantic Zoom
• Support data binding
   – Some require a little bit of help though!
GRIDVIEW IN MVVM
Semantic zoom done right
• Touch-based technique for presenting and
  navigating large sets of data in a single view
• Based on 2 modes
   – Low level: zoomed-in mode
      • Shows all data in a flat structure
   – High level: zoomed-out mode
      • Shows items in groups
• Typical uses:
   – Addressbook
   – Photo album
   – Product catalog
Using the semantic zoom control
• Contents can be anything that implements
  ISemanticZoom
  – ListView
  – GridView
  – Most of the time, you’ll use 2 GridViews
         <SemanticZoom>
           <SemanticZoom.ZoomedOutView>
             <!-- Put the GridView for the zoomed out view here. -->
           </SemanticZoom.ZoomedOutView>
           <SemanticZoom.ZoomedInView>
           <!-- Put the GridView for the zoomed in view here. -->
           </SemanticZoom.ZoomedInView>
         </SemanticZoom>
A typical semantic zoom
SEMANTIC ZOOM IN MVVM




DEMO
WORKING WITH CONTRACTS
Sharing in Windows 8
• Sharing used to go via clipboard or locally saving content
    – Sharing is in fact from one app to another

• Often time-consuming, sometimes confusing

• Windows 8 has the Share charm
    – Share contract works when tapping the Share charm

• Offers “lightweight, in context” sharing capabilities

• Sharing happens between 2 apps
    – Source app: app that wants to share data
    – Target app: app that can accept data as destination
    – An app can be both a source and a target
        • Can share with itself
Sharing in Windows 8
• Share pane (Win + H)
   – List of apps that can accept the data
      • Depends on the data being shared
   – Quicklinks

• Selected app normally opens a specific share view
   – Optimized to just handle the share operation
   – Closes after finishing the “sharing task”

• Sharing apps don’t have to know each other
   – Works through broker
   – Pub/sub model
Sharing between 2 apps

                  Register with
              DataTransferManager
              DataRequested event
Source app

Create data     DataRequested
 to share
                   All done!


                                            Activated
                                            for share
                                              target


                                    Target app
Sharing using MVVM
• Share source
  – Separate service will register with the
    DataTransferManager
  – Will also get in data to share when requested
  – ViewModel control this service but don’t directly
    interact with the DataTransferManager
• Share target
  – Separate View for the Share operation
  – Separate ViewModel for the Share view
  – Service can be used to complete the share operation
WORKING WITH CONTRACTS




DEMO
WORKING WITH TILES
Tiles
• Tiles can be updated in several ways
  – Local (from the app code)
     • Can only be used when the app is running
     • Useful for tile updates (not that useful for toasts)
  – Scheduled
     • Update at specific time
     • Useful for tiles and toasts
  – Periodic
     • Update at specific interval
     • Poll a cloud service for content
  – Push notifications
     • Updates are sent from the cloud
     • Ideal for updating the tile without the app being executed
Local updates using MVVM
• Again not the role of the ViewModel to
  update a tile/badge/toast
• Separate service is required
  – Can work with data access service to get
    information
  – Can work with navigation service to navigate to
    correct page and pass contextual information
  – Can be mocked out to be able to test in isolation
WORKING WITH TILES




DEMO
LIFECYCLE
AND STATE MANAGEMENT
Process lifecycle in Windows 8

             Launching                    Suspending
                         Running


    Not running/
    Not running                                  Suspended
     Terminated
                                   Resuming


                                   Termination
                                   App Close
                                   App crash
Process lifecycle management

• Managing state information is required
   – Suspended apps may not return and get terminated
   – Users expect to see the app in the same state they left it
   – Syncing state between multiple devices may be expected
   – The app could be updated to a newer version
   – While suspended, the app may be activated, triggering a different
     page
   – ...
• Can be done using
   – Application Data API
       • LocalSettings/LocalFolder
       • RoamingSettings/RoamingFolder
   – Via specific service then to repository
• It’s not the task of the ViewModel to manage this
   – A service has this responsibility
What should be saved?
• App data
  – Persistent across application reboots
  – Should be saved incrementally


• Session data
  – More temporary of nature
  – Saved mostly for suspending/termination
  – Includes often location within a multi-page app
LIFECYCLE
AND STATE MANAGEMENT
DEMO
UNIT TESTING THE
VMS AND SERVICES
Unit testing in MVVM
• Using MVVM goes hand-in-hand with unit testing
   – SOC: Because we use services for all external tasks,
     the VMs can be tested in isolation
   – DI: possible to pass mock services so that our test is
     not depending on external influences
• Difficult to test code that interacts directly with
  UI
• Mocking is recommended
   – Unit test not depending on external components
   – Supply a stub/fake
   – DI/abstraction layer is required
DEMO

UNIT TESTING THE
VMS AND SERVICES
Summary
• MVVM is great to use in your apps

• Services solve all your problems

• Learn it now!
Q&A
THANKS!
Advanced MVVM
Development in Windows 8
SILVERLIGHTSHOW.NET WEBINARS SERIES
GILL CLEEREN
www.snowball.be – gill@snowball.be - @gillcleeren

Weitere ähnliche Inhalte

Ähnlich wie Advanced MVVM in Windows 8

Building databound JavaScript apps with Knockoutjs
Building databound JavaScript apps with KnockoutjsBuilding databound JavaScript apps with Knockoutjs
Building databound JavaScript apps with KnockoutjsNish Anil
 
Understanding The MVVM Pattern (TechDays Belgium)
Understanding The MVVM Pattern (TechDays Belgium)Understanding The MVVM Pattern (TechDays Belgium)
Understanding The MVVM Pattern (TechDays Belgium)Laurent Bugnion
 
MVP Mix 2015 Leveraging MVVM on all Platforms
MVP Mix 2015  Leveraging MVVM on all PlatformsMVP Mix 2015  Leveraging MVVM on all Platforms
MVP Mix 2015 Leveraging MVVM on all PlatformsJames Montemagno
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patternsalkuzaee
 
Real World Windows Phone Development
Real World Windows Phone DevelopmentReal World Windows Phone Development
Real World Windows Phone DevelopmentIgor Kulman
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSJinkyu Kim
 
AngularJS UTOSC
AngularJS UTOSCAngularJS UTOSC
AngularJS UTOSCroboncode
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservicesAnil Allewar
 
Knockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockoutKnockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockoutAndoni Arroyo
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
 
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossFlavius-Radu Demian
 
MVVM for Modern Applications
MVVM for Modern ApplicationsMVVM for Modern Applications
MVVM for Modern ApplicationsJeremy Likness
 
MVVM - Model View ViewModel
MVVM - Model View ViewModelMVVM - Model View ViewModel
MVVM - Model View ViewModelDareen Alhiyari
 
Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts weili_at_slideshare
 

Ähnlich wie Advanced MVVM in Windows 8 (20)

Building databound JavaScript apps with Knockoutjs
Building databound JavaScript apps with KnockoutjsBuilding databound JavaScript apps with Knockoutjs
Building databound JavaScript apps with Knockoutjs
 
Understanding The MVVM Pattern (TechDays Belgium)
Understanding The MVVM Pattern (TechDays Belgium)Understanding The MVVM Pattern (TechDays Belgium)
Understanding The MVVM Pattern (TechDays Belgium)
 
MVP Mix 2015 Leveraging MVVM on all Platforms
MVP Mix 2015  Leveraging MVVM on all PlatformsMVP Mix 2015  Leveraging MVVM on all Platforms
MVP Mix 2015 Leveraging MVVM on all Platforms
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Real World Windows Phone Development
Real World Windows Phone DevelopmentReal World Windows Phone Development
Real World Windows Phone Development
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
 
Knockout js
Knockout jsKnockout js
Knockout js
 
AngularJS UTOSC
AngularJS UTOSCAngularJS UTOSC
AngularJS UTOSC
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Knockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockoutKnockout implementing mvvm in java script with knockout
Knockout implementing mvvm in java script with knockout
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
 
Asp 1a-aspnetmvc
Asp 1a-aspnetmvcAsp 1a-aspnetmvc
Asp 1a-aspnetmvc
 
Aspnetmvc 1
Aspnetmvc 1Aspnetmvc 1
Aspnetmvc 1
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
 
MVVM for Modern Applications
MVVM for Modern ApplicationsMVVM for Modern Applications
MVVM for Modern Applications
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
MVVM - Model View ViewModel
MVVM - Model View ViewModelMVVM - Model View ViewModel
MVVM - Model View ViewModel
 
Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts Build Java Web Application Using Apache Struts
Build Java Web Application Using Apache Struts
 

Mehr von Gill Cleeren

Continuous integration and delivery with Xamarin and VSTS
Continuous integration and delivery with Xamarin and VSTSContinuous integration and delivery with Xamarin and VSTS
Continuous integration and delivery with Xamarin and VSTSGill Cleeren
 
Real world apps with Xamarin and MVVM
Real world apps with Xamarin and MVVMReal world apps with Xamarin and MVVM
Real world apps with Xamarin and MVVMGill Cleeren
 
Building your first iOS app using Xamarin
Building your first iOS app using XamarinBuilding your first iOS app using Xamarin
Building your first iOS app using XamarinGill Cleeren
 
Building your first android app using Xamarin
Building your first android app using XamarinBuilding your first android app using Xamarin
Building your first android app using XamarinGill Cleeren
 
Bootstrap: the full overview
Bootstrap: the full overviewBootstrap: the full overview
Bootstrap: the full overviewGill Cleeren
 
Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!Gill Cleeren
 
Building a community - BuildStuff Lithuania 2014
Building a community - BuildStuff Lithuania 2014Building a community - BuildStuff Lithuania 2014
Building a community - BuildStuff Lithuania 2014Gill Cleeren
 
C# everywhere: Xamarin and cross platform development
C# everywhere: Xamarin and cross platform developmentC# everywhere: Xamarin and cross platform development
C# everywhere: Xamarin and cross platform developmentGill Cleeren
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQueryGill Cleeren
 
Top 10 HTML5 features
Top 10 HTML5 featuresTop 10 HTML5 features
Top 10 HTML5 featuresGill Cleeren
 
Comparing XAML and HTML: FIGHT!
Comparing XAML and HTML: FIGHT!Comparing XAML and HTML: FIGHT!
Comparing XAML and HTML: FIGHT!Gill Cleeren
 
Why you shouldn't dismiss windows 8 for your lob apps
Why you shouldn't dismiss windows 8 for your lob appsWhy you shouldn't dismiss windows 8 for your lob apps
Why you shouldn't dismiss windows 8 for your lob appsGill Cleeren
 

Mehr von Gill Cleeren (13)

Continuous integration and delivery with Xamarin and VSTS
Continuous integration and delivery with Xamarin and VSTSContinuous integration and delivery with Xamarin and VSTS
Continuous integration and delivery with Xamarin and VSTS
 
Real world apps with Xamarin and MVVM
Real world apps with Xamarin and MVVMReal world apps with Xamarin and MVVM
Real world apps with Xamarin and MVVM
 
Hello windows 10
Hello windows 10Hello windows 10
Hello windows 10
 
Building your first iOS app using Xamarin
Building your first iOS app using XamarinBuilding your first iOS app using Xamarin
Building your first iOS app using Xamarin
 
Building your first android app using Xamarin
Building your first android app using XamarinBuilding your first android app using Xamarin
Building your first android app using Xamarin
 
Bootstrap: the full overview
Bootstrap: the full overviewBootstrap: the full overview
Bootstrap: the full overview
 
Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!Top 10 HTML5 features every developer should know!
Top 10 HTML5 features every developer should know!
 
Building a community - BuildStuff Lithuania 2014
Building a community - BuildStuff Lithuania 2014Building a community - BuildStuff Lithuania 2014
Building a community - BuildStuff Lithuania 2014
 
C# everywhere: Xamarin and cross platform development
C# everywhere: Xamarin and cross platform developmentC# everywhere: Xamarin and cross platform development
C# everywhere: Xamarin and cross platform development
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQuery
 
Top 10 HTML5 features
Top 10 HTML5 featuresTop 10 HTML5 features
Top 10 HTML5 features
 
Comparing XAML and HTML: FIGHT!
Comparing XAML and HTML: FIGHT!Comparing XAML and HTML: FIGHT!
Comparing XAML and HTML: FIGHT!
 
Why you shouldn't dismiss windows 8 for your lob apps
Why you shouldn't dismiss windows 8 for your lob appsWhy you shouldn't dismiss windows 8 for your lob apps
Why you shouldn't dismiss windows 8 for your lob apps
 

Kürzlich hochgeladen

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Kürzlich hochgeladen (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Advanced MVVM in Windows 8

  • 1. Advanced MVVM Development in Windows 8 SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN www.snowball.be – gill@snowball.be - @gillcleeren
  • 2. About me… • Gill Cleeren – .NET Architect @Ordina – Pluralsight trainer – Microsoft Regional Director – Silverlight MVP / Telerik MVP – Speaker – Visug user group lead – Author – Blog: www.snowball.be – Email: gill@snowball.be – Twitter: @gillcleeren
  • 3. Agenda • Thinking about Modern UI • MVVM Overview • Building Blocks – Commanding – ViewModel Locator – Messaging • Application architecture • Navigation and window management • Data access and repositories • Data binding to Windows 8 controls • Working with contracts – Share • Working with tiles updates – Local – Push notifications • Lifecycle and state management • Unit testing the VMs and services
  • 4. You can win! Complete the post-webinar survey and win! 3 free ebooks of choice from SilverlightShow Ebook Shelf! My ebooks ’Connecting Windows 8 Apps with Services’ and ‘Windows 8 and the Future of XAML’ are also there.
  • 5. Some practical stuff • Ask questions through Q&A window – We’ll answer them after the session or by personal mail • A link to the video recording will be sent to you
  • 6. THINKING ABOUT MODERN UI (AKA THE TECHNOLOGY FORMERLY KNOWN AS METRO)
  • 7. Modern UI is different • Content before chrome • Full screen apps – Snap view and filled view • Orientation and rotation • Windows are now “pages” • New ways of interacting with an app – App bar – Charms/Contracts • Lifecycle and tiles • …
  • 8. MVVM and Modern UI • Currently most Modern UI apps are built in XAML • MVVM is supported in WPF, Silverlight, Windows Phone… • Core concepts of XAML are universal – Data binding, commands, DataContext… • Each technology has some specifics – Navigation, controls, lifecycle management, background tasks… • BUT knowledge can be easily leveraged – Even to non-XAML based technologies (HTML5 with Knockout JS)
  • 9. It’s a great idea… to build Windows 8 apps using MVVM! We’ll show you how!
  • 10. MVVM OVERVIEW For those who might not grasp every concept…
  • 11. Hello MVVM • MVVM is an architectural pattern – Based on MVC pattern – In turn based on PresentationMode l by Fowler – Introduced by John Gossman (WPF dude) I <3 XAML
  • 12. Hello MVVM • Leverages power of XAML framework – Data binding – Commanding
  • 13. Hello MVVM • Became popular with Silverlight – Also applicable in • WPF • Windows Phone 7 and 8 • Windows 8/WinRT
  • 14. Woot, I can finally build my code Here’s the design. without the designer Now let me go and messing things up! play with my iPhone.
  • 15. What we all did when we were young… • Watch Eddy Murphy arrive in America… • Tom Selleck’s moustache was closely monitored • Record ourselves… • Shoot ducks (and try shooting the damn dog)
  • 16. What we all did when we were young… • And write code in code-behind… Lots of it. View XAML Code-Behind Data Model Event Handlers
  • 17. Meanwhile, in 2013, things have changed. • Not necessarily any better though…
  • 18. Writing testable code however, is becoming the norm. Finally. Courtesy of MVVM. View XAML Code-Behind Data-binding Change and notification commands View Model State + Data Model Operations
  • 20. The View • Represents the user interface that the user will see • Can be a page, user control or Data Template • Keep it simple – Clean code-behind – Only visual logic (all the rest should go in the ViewModel) • Should never contain anything that is to be tested – Model-related
  • 21. The ViewModel • An abstraction of View, definition of what can be shown on screen • Glue between View and Model – Implements INotifyPropertyChanged • Contains – State properties: data – Operations: commands – Validation support • Should not contain “view properties” such as Color – Use converters for this • Often wraps or “re-models” the model for the View to use • Must be testable • No control references! • Often, 1 ViewModel per View – Can be 1-to-many or many-to-1 • Manages the flow of the application • Interacts with the model
  • 22. The Model • Data model, service reference/proxy classes, DTO… – Very often, an extra layer is added on top of the generated proxy classes • Validation logic • Data access • No reference to ViewModel
  • 23. Linking the View and the ViewModel • Data binding is the glue but… • A view needs to “find” its ViewModel – ViewModel is the DataContext • Can be static or dynamic – Static: View creates ViewModel and sets it as DataContext – Dynamic: at runtime, View selects its ViewModel or vice- versa • 2 options: – View-First: ViewModel gets created because View is created – ViewModel-First: ViewModel is created and View gets selected
  • 24. Locator pattern • Implemented through a class that contains all VMs as properties • An instance is then made available as Resource • All Views can bind, no code needed in View – Clean way – Not good since all VMs need to be known upfront • Property for each available VM • Not easy if more than one instance exists of a View – In this case, some form of IOC is recommended
  • 25. Commands • MVVM-based code have no event handlers in code-behind • How to handle events happening in the UI? Commands Based on Command pattern In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. his information includes the method name, the object that owns the method and values for the method parameters.
  • 26. Commands • WinRT has the ICommand interface – Execute() – CanExecute() – CanExecuteChanged event public interface ICommand { event EventHandler CanExecuteChanged; bool CanExecute(object parameter); void Execute(object parameter); }
  • 27. Commands • Way to create commands: – Write ICommand implementation – Create instance on VM – Bind Command property of control to this instance • Works only on some controls • Rest needs to use behaviors
  • 28. Behaviors • Block of code that we can attach to XAML element • Promotes reuse • Useful in MVVM scenarios on controls that don’t support commanding – Avoids having code in code-behind • Supported by Blend • Not supported by Windows 8  – Neither are triggers – EventToCommand is therefore not available by default – The community has the answer!
  • 29. Using EventToCommand as a behavior • Take a look at WinRtBehaviors on CodePlex/NuGet (Joost van Schaik) <TextBlock Text="TextBlock" FontSize="48"> <WinRtBehaviors:Interaction.Behaviors> <Behaviors:EventToBoundCommandBehavior Event="Tapped" Command="{Binding TestCommand}" CommandParameter="{Binding TestProperty, Mode=TwoWay}"/> </WinRtBehaviors:Interaction.Behaviors> </TextBlock> • Works through Attached behaviors – Attached dependency property
  • 30. Communication between VMs View Model View Model View Model View Model View Model View Model View Model View Model
  • 31. Messaging View View XAML XAML Code- Code- Behind Behind View Model View Model Data Model State + Operations Data Model State + Operations Message Publish messages View XAML Code- Subscribe to Behind messages View Model Event Aggregator Message State + Operations
  • 33. From the ground up! • Core principles for a testable and maintainable architecture – Separation of concerns • “A new class doesn’t cost a thing” – Repositories – Loose coupling – Dependency injection – Unit testing and mocking
  • 36. The container • Loose coupling is achieved through dependency injection • Dependencies are instantiated and maintained through container • MVVM Light comes with SimpleIOC – Not very extended when it comes to managing lifetime of objects • NuGet offers alternatives – MetroIOC – TinyIOC – AutoFac • Can be used to manage – ViewModels – Views – Services – …
  • 37. Abstraction for the container • Avoid making direct calls to your container from code • Instead, introduce an abstraction layer for your container • Code not dependent on container • If container changes, only one class needs changing
  • 40. Navigation • Windows 8 apps use “new” screens to convey information – Not many controls and content on screen – Navigation == content – Result is that we often have to navigate using more clicks/taps • Navigation is based on concept of pages – Forward and backward navigation support
  • 41. Pages and Frames • Windows 8 apps know pages: this is the “window”, top- level control – Used as Views in MVVM scenario – No visible chrome • Frame will host pages – One page at a time – Performs navigation from page to page • Frame.Navigate() • Frame.GoBack() – Single Frame is created at application level • First view gets loaded after splash screen • Extended splash screen is MVVM view as well
  • 42. Navigation and SOC • Navigation is not the task of the ViewModel • Navigation is not the task of the View … and most certainly not the task of the Model Then, whose task is it? • Separate service that has link to Frame • Called from ViewModels – Static – Dynamic • NavigationService is injected in ViewModels through IOC – Easily mockable – No hard dependency on specific implementation in ViewModels – Often, single instance is created application-wide and passed through injection/container
  • 43. Window management • Windows 8 apps don’t use MDI interfaces, have separate windows though – Exception dialog – Confirmation window – Message dialog • Managed through separate service – Called from ViewModels • Again good news for testing and SOC
  • 45. DATA ACCESS AND REPOSITORIE
  • 46. Repositories • Abstraction between data persistence and data consumption code – Allows changing implementation of persistence code without changing consumer – Easier to test – Creates central location for all data access • Advantage in the case where data will be cached locally • A repository often manages access to single resource collection – More than one entity type on single repository though • Parent-child relation
  • 47. Data services • Since repositories often work with a single entity, they are not a good hook for the ViewModels – Would make the ViewModel responsible for combining response of several repository reponses • Create separate service for data acess – Per “unit of functionality” – Shared between ViewModels • Often created application-wide through IOC container – Injected into ViewModels through DI
  • 48. DATA ACCESS AND REPOSITORIES DEMO
  • 49. DATA BINDING TO WINDOWS 8 CONTROLS
  • 50. Windows 8 and lists of data • Data lists are everywhere – RSS feeds – Flickr images – News updates – Local file system enumerations – … • Microsoft has focused on creating controls that work with these lists – GridView – ListView – FlipView – Semantic Zoom • Support data binding – Some require a little bit of help though!
  • 52. Semantic zoom done right • Touch-based technique for presenting and navigating large sets of data in a single view • Based on 2 modes – Low level: zoomed-in mode • Shows all data in a flat structure – High level: zoomed-out mode • Shows items in groups • Typical uses: – Addressbook – Photo album – Product catalog
  • 53. Using the semantic zoom control • Contents can be anything that implements ISemanticZoom – ListView – GridView – Most of the time, you’ll use 2 GridViews <SemanticZoom> <SemanticZoom.ZoomedOutView> <!-- Put the GridView for the zoomed out view here. --> </SemanticZoom.ZoomedOutView> <SemanticZoom.ZoomedInView> <!-- Put the GridView for the zoomed in view here. --> </SemanticZoom.ZoomedInView> </SemanticZoom>
  • 55. SEMANTIC ZOOM IN MVVM DEMO
  • 57. Sharing in Windows 8 • Sharing used to go via clipboard or locally saving content – Sharing is in fact from one app to another • Often time-consuming, sometimes confusing • Windows 8 has the Share charm – Share contract works when tapping the Share charm • Offers “lightweight, in context” sharing capabilities • Sharing happens between 2 apps – Source app: app that wants to share data – Target app: app that can accept data as destination – An app can be both a source and a target • Can share with itself
  • 58. Sharing in Windows 8 • Share pane (Win + H) – List of apps that can accept the data • Depends on the data being shared – Quicklinks • Selected app normally opens a specific share view – Optimized to just handle the share operation – Closes after finishing the “sharing task” • Sharing apps don’t have to know each other – Works through broker – Pub/sub model
  • 59. Sharing between 2 apps Register with DataTransferManager DataRequested event Source app Create data DataRequested to share All done! Activated for share target Target app
  • 60. Sharing using MVVM • Share source – Separate service will register with the DataTransferManager – Will also get in data to share when requested – ViewModel control this service but don’t directly interact with the DataTransferManager • Share target – Separate View for the Share operation – Separate ViewModel for the Share view – Service can be used to complete the share operation
  • 63. Tiles • Tiles can be updated in several ways – Local (from the app code) • Can only be used when the app is running • Useful for tile updates (not that useful for toasts) – Scheduled • Update at specific time • Useful for tiles and toasts – Periodic • Update at specific interval • Poll a cloud service for content – Push notifications • Updates are sent from the cloud • Ideal for updating the tile without the app being executed
  • 64. Local updates using MVVM • Again not the role of the ViewModel to update a tile/badge/toast • Separate service is required – Can work with data access service to get information – Can work with navigation service to navigate to correct page and pass contextual information – Can be mocked out to be able to test in isolation
  • 67. Process lifecycle in Windows 8 Launching Suspending Running Not running/ Not running Suspended Terminated Resuming Termination App Close App crash
  • 68. Process lifecycle management • Managing state information is required – Suspended apps may not return and get terminated – Users expect to see the app in the same state they left it – Syncing state between multiple devices may be expected – The app could be updated to a newer version – While suspended, the app may be activated, triggering a different page – ... • Can be done using – Application Data API • LocalSettings/LocalFolder • RoamingSettings/RoamingFolder – Via specific service then to repository • It’s not the task of the ViewModel to manage this – A service has this responsibility
  • 69. What should be saved? • App data – Persistent across application reboots – Should be saved incrementally • Session data – More temporary of nature – Saved mostly for suspending/termination – Includes often location within a multi-page app
  • 71. UNIT TESTING THE VMS AND SERVICES
  • 72. Unit testing in MVVM • Using MVVM goes hand-in-hand with unit testing – SOC: Because we use services for all external tasks, the VMs can be tested in isolation – DI: possible to pass mock services so that our test is not depending on external influences • Difficult to test code that interacts directly with UI • Mocking is recommended – Unit test not depending on external components – Supply a stub/fake – DI/abstraction layer is required
  • 74. Summary • MVVM is great to use in your apps • Services solve all your problems • Learn it now!
  • 75. Q&A
  • 77. Advanced MVVM Development in Windows 8 SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN www.snowball.be – gill@snowball.be - @gillcleeren