This DZone Refcard is brought to you by...
Love being connected, all over again
The experience is elegant. The platform is powerful. One free download gives you the tools to build new, or tweak existing, Silverlight and XNA applications and games for Windows® Phone 7. Discover the possibilities.
http://create.msdn.com brought to you by... #135
CONTENTS INCLUDE:
n Overview
n The MVVM Design Pattern MVVM Explained n MVVM on Windows Phone A Formula for Elegant, Maintainable Mobile Apps n MVVM Project Templates n VVM Commands By Colin Melia n Hot Tips and more... Visit refcardz.com
OVERVIEW
If you are developing a Silverlight application for the Windows Phone, then this Refcard is probably for you. For all but the most trivial of applications, the Model-View-ViewModel (MVVM) pattern provides a solid pattern to follow for building a well- structured and maintainable application. Microsoft has taken that message seriously with Windows Phone by basing three of the Model
four Visual Studio application project templates on the MVVM The Model is the object model for the application. It can also Get More Refcardz! Refcardz! Get More pattern. This card provides an explanation of the MVVM pattern, be the ‘layer’ for data and/or business logic that are completely how it’s supported and how to follow it on Windows Phone. devoid of UI features and any dependency on the platform UI As a side benefit, the content is almost entirely applicable libraries or runtime. It can hold state and/or perform processing to Silverlight desktop, web, slate and Windows Presentation on the state relevant to the business/problem domain. The data Foundation (WPF) applications as well. or the operations performed on the data may be dealt with entirely in process memory (e.g., the current value of rolled dice), Why MVVM on Windows Phone? or they may be retrieved, stored and processed remotely using MVVM is an architecture pattern introduced by John Gossman a data repository/service (e.g., a database or web service) with in 2005 specifically for use with WPF as a concrete application the model in memory representing a subset of the available data of Martin Fowler’s broader Presentation Model pattern. (e.g., specific customer records). Implementation of an application, based on the MVVM patterns, uses various platform capabilities that are available in some By creating a Model that is not bound to a single platform, form for WPF, Silverlight desktop/web, and on Windows it is easier to share the data model across Silverlight, WPF Phone with a little help from other libraries. Many commercial Hot and WP7 platforms with the potential for reuse of model applications, including Microsoft Expression products, were Tip documentation, direct code or even binary libraries. built following MVVM. Recommend basing MVVM development on Silverlight 3 to The benefits of MVVM are listed as follows and can be largely ease code sharing with WP7, Silverlight 3/4 and WPF 4. summed up in the phrase “Separation of Concerns”. View • Modular architecture: given good inter-layer interface definitions, components can be built and well tested independently. The View is a ‘layer’ that represents and handles all the UI elements, including both displayed UI (e.g., classic ‘buttons’ and • Loose coupling: with one-way dependencies, changes to one layer don’t require the other to be changed, rebuilt or retested. more sophisticated displays) and UI-user interactions (e.g., screen touch, button press, etc.). • Role separation: responsibilities and expertise can be focused (e.g., designers can build UI without needing to write code). There can be several Views over the same data with varying • Tool friendly: the design of the pattern and the capabilities of the detail, depth or representation (e.g., summary + details, order +. platform mean that different tools best suited to the skills of the user order + order line items, charting). can be used. These tools include Visual Studio for developers and Blend for UI designers. • Maintainability: as with other patterns, a well-structured design makes it easier to make modifications when updates or upgrades are done. • Less coding: the separation also leads to areas of development with less code, which means less room for error; it also means less regression testing when changes are made. • Testability: the pattern enables automated unit testing of code and minimizes the need for UI-based testing. The MVVM pattern is not a set of all-or-nothing rules that Hot one must strictly adhere to. It may not be appropriate for Tip all applications, especially small ones where implementing MVVM may require too much overhead.
MVVM EXPLAINED Get the free tools
Introduction The MVVM pattern encourages developers to build their application as three layers with the dependencies shown. The MVVM Design Pattern
DZone, Inc. | www.dzone.com 2 The MVVM Design Pattern: A Formula for Elegant, Maintainable Mobile Apps
One of the capabilities a platform needs to enable the MVVM MVVM pattern, select File->New Project in Visual Studio, select pattern well is the ability to create UI declaratively with text instead “Silverlight for Windows Phone” from the Installed Templates of code. Those declarations can include parts that ‘bind’ visual and then select one of the template types. To build from scratch, elements to data available in the Model, such that value or list select “Windows Phone Application” or see the section below changes stay in sync between the View and Model data. This about MVVM support in other templates. minimizes or replaces imperative code for settings values between the View elements and data in the Model. Also, since code in Model The Model is based on a CLR type from a simple value type as the UI can be difficult to test (with automation), this reduces or a property… eliminates the amount of UI-updating-related code to be tested. The concept of binding can also be used to bind a user-driven public int Value { get; set; } event to an action to be performed against the data in the Model. …to a more complex set of nested classes, e.g., Contact…
Creation of a View declaratively also opens up the possibility that public enum PhoneType someone with good design/interactivity sensibilities can design { Work, the View (perhaps with a more designer-focused tool) without Home, coding/library expertise and somewhat independently from the Mobile } software developer. public class PhoneNumber { ViewModel public String Number { get; set; } public PhoneType PhoneType { get; set; } While a View can be bound to the data in the Model or actions } public class Contact against that data, in practice this is not done directly but via { another ‘layer’ called the ViewModel or VM. It is a “Model of public String Name { get; set; } public List
For the latest release of the free Windows Phone developer private void OnPropertyChanged(String PropName) { Hot tools, go to http://create.msdn.com/. A complete guide to if(PropertyChanged != null) building and deploying a simple MVVM-based WP7 application PropertyChanged(this, new PropertyChangedEventArgs(PropNa Tip me)); for the marketplace is available - http://bit.ly/WP7Die. }
public event PropertyChangedEventHandler PropertyChanged; To start creating a Windows Phone application based on the }
DZone, Inc. | www.dzone.com 3 The MVVM Design Pattern: A Formula for Elegant, Maintainable Mobile Apps
Remember that the integer named Value is the Model data in public partial class MainPage : PhoneApplicationPage this class. When the property setter method for Value is called, it { public MainPage() checks to see if there is a change. If so, calls the helper method { that will inform the View (if bound to that object and property) this.DataContext = new CustomerVM(); InitializeComponent(); that something has changed. } } If a Model contains a collection of items that can change and the UI must update to reflect those changes, the collection must 2. Per View/page creation in the page/UserControl XAML, for example with implement the INotifyCollectionChanged interface. Alternatively, this XML namespace at the top of the View page… use the Generic ObservableCollection
public class MyValuesVM : INotifyPropertyChanged {
DZone, Inc. | www.dzone.com 4 The MVVM Design Pattern: A Formula for Elegant, Maintainable Mobile Apps
The example also shows different data binding options (below) with Build on these templates and create custom Visual Studio TwoWay being applicable to a TextBox where the updated should Hot be transferred back to the ViewModel to set the Model data. templates for increased team productivity - Tip http://msdn.microsoft.com/en-us/library/6db0hwky.aspx. Mode Effect in MVVM Quick Guide to the MVVM Project Templates OneTime ViewModel property value copied to View element upon initialization. Seldom used, but could help performance. The information in the previous sections together with the following guide to MVVM pattern use in the provided OneWay ViewModel property value copied to View element upon templates should help bring clarity to basic use of MVVM on (default) initialization and when ProperyChanged event called. Windows Phone. TwoWay Same as one way, plus value copied back from View element to ViewModel property – triggering event various by visual element • A single instance of the ViewModel called MainViewModel (incorporating Model data) is created using the singleton pattern and type. exposed as the ViewModel property on the App object in the App. xaml.cs file. View – Collection Binding • The ViewModel class is defined under the ViewModels folder. It When the ViewModel exposes model data as a collection, use a has a collection of ItemViewModel objects implemented using control in the View that derives from ItemsControl (e.g., ListBox) ObservableCollection. and set the ItemsSource to the collection. The control creates a • MainPage is the primary View and its DataContext is set in code to sub-visual tree for each object in the collection and automatically App.ViewModel in the page’s constructor in MainPage.xaml.cs. sets its DataContext to the item object. ItemsControls have an • For the Databound Application, the DataContext for the DetailsPage ItemTemplate property, which can be set in XAML to a collection View is set in code to an item in the App.ViewModel.Items collection of XAML visual elements (including the bindings) to represent in the page’s constructor in DetailsPage.xaml.cs. visually each object in the collection, for example: Consider separating Models, Views and ViewModels into
event EventHandler CanExecuteChanged; } Hot Use Converts (vs. conversion in ViewModel) if they are Tip reusable and relate to UI on one end, not for transforming The Execute() method is self explanatory. The CanExecute() business data. method is provided so that a visual element bound to the object can query whether execution is currently possible and potentially update itself visually to indicate the state. MVVM PROJECT TEMPLATES The CanExecuteChanged event should be raised by the ViewModel whenever the ability execute or not has changed. Project templates based on MVVM Three of the project templates included with the free Windows On the interaction side, there needs to be a way to connect user Phone developer tools, as indicated, are based on MVVM. interactions with exposed commands. Silveright controls have events to which code-based event handlers can be attached, but this is UI code that is hard to test. In the Silverlight platform for the desktop/web, the controls derived from ButtonBase (e.g., Button) have a Command property which can be bound to the ICommand-based object properties on the ViewModel, and the Button works with the ICommand interface as one would expect. However, these are not implemented in Silverlight 3 and Silverlight for Windows Phone.
DZone, Inc. | www.dzone.com 5 The MVVM Design Pattern: A Formula for Elegant, Maintainable Mobile Apps
MVVM Light OTHER MVVM LIBRARIES In addition to no direct ICommand support in Windows Phone for controls to bind to commands, exposing potentially many command objects, with each one as a private class nested inside Using MVVM Libraries the ViewModel class can be quite time-consuming and verbose. As shown, the MVVM Light toolkit (for WP7, Silverlight and WPF on CodePlex) is easy to start with and also includes other features: While it’s technically possible to improve these two issues by creating helper classes (to make exposing commands easier) • A ViewModelBase class and creating Behaviours (to bind UI events to commands) that • Messenger system for inter-ViewModel communication can be used in code, XAML and XAML-based tools like Blend, it • Visual Studio project and item templates makes sense to use available third-party libraries to accelerate this process. • Visual Studio code snippets One such library is part of the MVVM Light toolkit available from To ease implementation, consider inheriting ViewModels GalaSoft - http://www.galasoft.ch/mvvm/installing/manually/ or Hot from a library base class (or create one), including use NuGet. Tip support for the INotifyPropertyChanged interface inheritance/implementation and helper functions. To use MVVM Light libraries to easily expose commands in a concise way: Caliburn Micro 1. Add a reference to Galasoft.MvvmLight.WP7.dll, Galasoft.MvvmLight. Extras.WP7.dll & System.Windows.Interactivity.dll that come in the toolkit Calibrun Micro is a small but powerful micro-framework for WP7, Silverlight and WPF on CodePlex that supports MVVM 2. In the ViewModel class file, add: development including these features:
using GalaSoft.MvvmLight.Command; • ActionMessages – for flexible binding of UI actions to ViewModel methods (achieving what Commands do) 3. Expose a property of type RelayCommand on the ViewModel: • Bootstrapper & ViewLocator – for pattern configuration and handing out ViewModels to Views public RelayCommand MyCommand { get; private set; } • Screens and Conductors – for tracking active screens and selections 4. Create a private method that performs the command Prism private void DoMyCommand() Prism 4 is a free library from Microsoft Patterns & Practices group { // Do command for WP7, Silverlight and WPF, originally concerned with building } composite application. It includes a WP7 library with helpful features (including MVVM support): 5. In the ViewModel constructor, instantiate the command so that it calls the private method when Execute() is called on ICommand by the UI. • Commands with DelegateCommand – similar to RelayCommand in MVVM Light. private void DoMyCommand() • Pub/sub eventing { // Do command • Run-time data template selection } • Application Bar helpers 6. Optionally, add a second lambda expression to the RelayCommand constructor that will be checked when CanExecute() is called on • UI Interaction Helpers ICommand by the UI. Read the in-depth Windows Phone 7 Developer Guide from 7. If necessary, call RaiseCanExecuteChanged() on the command object when the ability to execute the command changes, so that bound UI Hot Microsoft Patterns & Practices to see Prism is a use in knows to call CanExecute() to update any visual cues. Tip sample MVVM-based application - 8. Repeat steps 3 to 7 for each command to be exposed. http://msdn.microsoft.com/en-us/library/gg490765.aspx To use the libraries to bind control events (e.g., a single touch that is equivalent to a left mouse button down) to exposed BLENDABILITY commands in XAML (while writing no code): 1. Add the MVVM Light namespace at the others at the top of the XAML Making WP7 MVVM applications ‘blendable’ The free tools for Windows Phone include a version of Blend that xmlns:i=”clr-namespace:System.Windows.Interactivity;assembly=System. can be used for design. Blend has a UI optimized for UI design, Windows.Interactivity” xmlns:mvvmextra=”clr-namespace:GalaSoft.MvvmLight. over coding. Command;assembly=GalaSoft.MvvmLight.Extras.WP7” If a developer produces ViewModel and Model classes, a UI 2. Add this XAML like this inside the control’s element designer can then produce interactive UI in Blend and bind to the ViewModel, producing XAML in the project that can then be
DZone, Inc. | www.dzone.com 6 The MVVM Design Pattern: A Formula for Elegant, Maintainable Mobile Apps
• If possible, use the full ViewModelLocator pattern to allow switching HttpWebRequest/Response class, or service proxy class inc. at design-time to mock ViewModels with design data or mock Models OData proxies) or if data is stored locally, this would involve injected into the ViewModel. If that route doesn’t suit, then at least consider using design data (see below). classes under System.IO and System.IO.IsolatedStorage or third- party databases (e.g., Sterling DB or Perst). If properties are serializable, it may be convenient to just serialize the ViewModel Hot To detect if the application is in a designer tool, use and Model state using classes under System.Xml.Serialization. Tip System.ComponentModel.DesignerProperties.IsInDesignTool Having an application-instance-based object with one or more ViewModel properties may provide a convenient ViewModel Design Data ‘hub’ for all the pages in your application. The project templates in the tools that support MVVM also show examples of design-time data under the SampleData folder. Tombstoning Since XAML can fundamentally be used to declare objects and An application may have volatile session-specific Model data (e.g., properties, it can be used to declare sample ViewModels (including data entry in progress and not yet saved) and/or View Model UI nested object/collection properties). By using the d:DataContext state that can be lost if the application is ‘tombstoned’ (de-activated (with the design-time namespace prefix) in XAML (see MainPage. by the OS to preserve foreground application performance or to xaml in the Data Bound application), the DataContext can be set perform another task and possibly never re-activated). on the page or sub-element to use the static sample data. ViewModels should subscribe under PhoneApplicationService to A designer using Blend to build UI on top of ViewModel the Deactived event and use its Current.State dictionary to save this transient state on Deactivated and load back (if necessary/ classes provided by a developer can use a feature in Blend available) in both the ViewModel constructor and the Activated Hot that automatically generates XAML sample data based on Tip event, the transient data along with any non-session-specific data. the class properties of the ViewModel or Model as well as See more on tombstoning on MSDN: generate XAML sample data based on XML files. http://msdn.microsoft.com/en-us/library/ff817008(v=VS.92).aspx
PERSISTENCE When using MVVM with TextBox controls Hot bound to data, use something like the Prism Data persistence Tip UpdateTextBindingOnPropertyChanged class in XAML A ViewModel should wrap the action of saving/loading data to ensure all Text changes are transferred through the it represents (which may be delegated to a Model class). binding prior to a tombstone or Application bar event.
This may use a web service (using the WebClient class, the
ABOUT THE AUTHOR RECOMMENDED BOOKS Colin Melia is the Principal Architect for Ace of Clouds Programming Windows Phone 7 is a free e-book from as well as a speaker, trainer, author, user group leader, Charles Petzold and the Windows Phone 7 team. This academic advisor, CTO, and company director. He has book is divided into 3 parts: basic concepts of Windows expertise creating rich UI with WPF/Silverlight, cloud Phone 7, Silverlight, and XNA 2D. development with Azure, mobile development on Windows Phone, and business intelligence with SQL Server. He has in-depth knowledge of core technologies such as .NET, OData, WCF, WF, LINQ, and WIF. READ NOW http://www.charlespetzold.com/phone/
#82
CONTENTS INCLUDE:
■ Browse our collection of over 100 Free Cheat Sheets About Cloud Computing ■ Usage Scenarios Getting Started with dz.com ■ Underlying Concepts ■ Cost ... ® efcar ■ #64 Data Tier Technologies . Cloud Computing omply brought■ Platform to you Management by and more... e. C . Collaborat
isit r isit AldonChange By Daniel Rubio V
dz! also minimizes the needCONTENTS to make designINCLUDE: changes to support ABOUT CLOUD COMPUTING one time events. ■ HTML Basics dz.com ■ Upcoming Refcardz HTML vs XHTML Web applications have always been deployed on servers Automated growth & scalable technologies ■ Validation connected to what is now deemed the ‘cloud’. Having the capability■ to support one time events, cloud efcar
e Refcar Useful Open Sour computing platforms also facilitate the gradual growth curves ■ Page Structur #84 However, the demands and technology used on such servers ce T faced by web applications.■ ools isit r Key Structural Elementse Elements and mor : has changed substantiallyBy Paul in recent M. years, Duvall especially with V
gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involving specialized equipment Continuous Integration: CONTENTS INCLUDE Microsoft. (e.g. load balancers and clusters) are all but abstractede... away by Patterns and Anti-Patternse changes dz! RichFaces ■ e at Every Change About Continuous Inte terns orkspace to isolat relying on a cloud computing platform’s technology. Cor ■ Build Softwar Description e in a Private W epository HTML BASICS These companies have long deployedntrol r web applications
■ Patterns and Anti-patol Develop softwar rging and to manage dz.com n that adapt and scale to large user bases, making them In addition, several cloud computing platforms support data e Patter fi les to a version-co ■ HTML ersion Contr HTML and XHTML ar V ore... orkspaceknowledgeableCommit allin manyline aspects to minimize r meelated to cloud computing. tier technologies that exceed the precedent set by Relational ■ Build Management Private W hat utilizes multiple e Refcar HTML is used as the graphical user interface in client-side
Develop on a main Database Systems (RDBMS): Map Reduce,e the foundationweb service of APIs,all web development. efcar ■ Build Practices and m Repository active code lines e within a system t ts of work pr TION This Refcard will introducear to you to cloud computing, with an etc. Some platformsograms support written lar gein JavaScript.scale RDBMS Server deployments. The sr By CSS3 e Mainline Developing softw by task-oriented uni and Java also r c attribute describes wher Andy Harris Get Mor emphasis on these providers, so you can better understand oftwar codelines and the alt attribute describes alternate text that is displayed if
ask Level Commit isit r isit ce code changes ol as the output mechanism.eceive data The fr emer what it is a cloudganize computing sour es as aplatform T can offer your web the image is unavailable.
V ocess of building s Codeline Policy Or ce without likewise use HTML and XHTML as their visual-side engine. languages HTML like PHP e the image Get Mor om web pages and use HTML s version contr applications.it and submit chang h unique name e from sour CLOUD COMPUTING PLATFORMS AND ABOUT CONTINUOUS INTEGRAoject’ was once a very loosely-defi Nested tags file can be found,
e.com Task-Level Comm Label the build wit ies to build softwar re minimum UNDERLYING CONCEPTS
dz! dz! gration (CI) is the pr oblem ging Ajax technologies T standar ags can be (and fr committed to a pr USAGE SCENARIOSAutomate all gurationactivit pendencies to the ba dization, but as it has become mor Continuous Inte ve Label Build manual confi same deployment need for standar ned language with very little cannot overlap, so zon onment , a solution to a pr e-installed tool de equently ar NoSQL target envir Amazon EC2: Industry standard software and virtualization b> with every change. oblem) Automated Build Reduce pr whether you chooseds tohas write become HTML mor or XHTML, understanding e) nested inside each other ns (i.e., ineffecti .d deployment, use the is fi epository via patterns (i.e. Pay onlyncies what you consumeAR or EAR) in each Amazon’s cloudthe curr computing platform is heavily based on ne. r For each tagged e important, the
x” the particulare solutions pr thatuce Web application deployment until a few years agoonment was similar ent standar e appar is not legal, but e Refcar e Minimal Depende package (e.g. W dent libraries get envir industry standarthat willd simplifysoftwar alle and your virtualization other web coding. technology Fortunately. HTML ontext) and edanti-patter to “fi s ar ent. Regar HTML VS XHTML . T CI can be explained t can fi le that all tar ds will help you pr ags Binaryto Integrity most phone services:Centralize plans all depen withte alloted resources, with an and XHTML ar Get Mor Get appear to befects. bene They aresults when compa The various resources consumed by web applicationsly, continually (e.g. Every page (HTML or XHTML shar ded r Perform a Private velopment team individual operating system sinstances. Browser manufactur adverse ef Staged Builds Repository tion Build periodical common.) All ar s Integration bandwidth, memory, CPU) are tallied on a per-unit basis oduce uninten om CI server to de web developers came up with clever workar pr Private Build Perform an Integra edback fr extension. HTML e essentially plain text ers added many competing estandar than anybody term Continuouis Refcard (starting from zero) by all major cloud computingy occur platforms. As a user of Amazon’s EC2 cloud computinges certain platform, elements you inare result is a lack of standar the pattern. ation pr ch as Send automated fe ith builds based on assignedocessor an operating systemfi in the same way as on all hosting l use of the Integration Build ors as soon as the les should not be cr The latest web standar d and test” cycle, th er documentation w e.com Continuous Integr clude concepts su While the conventionaefers to the “buil Generate develop otion of CI to in expands on the n DZone, Inc. Cloud Computing 140 Preston Executive Dr. Suite 100 Cary, NC 27513 DZone communities deliver over 6 million pages each month to 888.678.0399 more than 3.3 million software developers, architects and decision 919.678.0300 makers. DZone offers something for everyone, including news, Refcardz Feedback Welcome tutorials, cheat sheets, blogs, feature articles, source code and more. [email protected] “DZone is a developer’s dream,” says PC Magazine. $7.95 Sponsorship Opportunities Copyright © 2011 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, [email protected] Version 1.0 without prior written permission of the publisher.