Professional Documents
Culture Documents
Introduction To The Microsoft Azure Cloud
Introduction To The Microsoft Azure Cloud
Development
Alon Fliess
Chief Software Architect
alonf@codevalue.net
http://blogs.microsoft.co.il/blogs/alon
Agenda
About
Cloud Concepts & Benefit
Azure Infrastructure and Services
Azure App Service
Mobile Services & Mobile Apps
Universal Windows Platform
App development
Introduction to XAML
Application Lifecycle
Advanced features
Summary
About Me
Alon Fliess:
Chief Software Architect & Co-Founder at CodeValue Ltd.
More than 25 years of hands-on experience
Microsoft Regional Director & Microsoft MVP
Active member of several Patterns & Practices councils
Renowned speaker at both international and domestic events
About CodeValue
A leading software company
~130 employees: more than 120 technology experts
Provides high quality software development solutions
Turn-Key projects
Software development and consultation
Tailor-made courses and training
Fields of expertise include:
Desktop & LOB applications
Cloud Computing
Advanced Mobile & Web Technologies
User Experience (UX) & User Interface (UI)
Application Lifecycle Management (ALM) and DevOps
Embedded & IoT
About OzCode
An innovative debugging extension for Visual-Studio
Simplify & visualize complex statements
Compare objects and collections
Search and filter collections
Focus on relevant data
http://oz-code.com
Israeli Azure Developer Community
Curious about Azure? Join us!
Meet every two months at Microsoft Ra’anana
Next meeting – December 2015
http://www.meetup.com/IsraeliAzureDevelopers
https://www.facebook.com/IsraeliAzureDevelopers
A Full Stack Developer
Full Stack Development includes:
Analysis of business needs
Architecture & Design
Server, Network, and Hosting Environment
Data Modeling
Business Logic
API Layer
User Interface, Client Logic, User Experience
Web, Desktop, Mobile
7
A Full Stack Developer
It is almost impossible to be an expert over every facet of the
development stack
However with great tooling and good foundation – one can build a full
system
17
Architecture 101
Decomposition
Is this a good design?
18
Decomposition
Is this a good design?
Decomposition
Decomposition
20
The cost of the software development process
module
development
cost
Module
Integration
Cost
cost
21
number of modules
Cohesion
The degree to which a module performs one and only one
function
Strive for high cohesion
Module can be:
Assembly (DLL)
File
Class
Method
WinRT/COM component
Any reusable element
22
Coupling
The degree to which each program module relies on each
one of the other modules
Low coupling often correlates with high cohesion, and vice
versa
Low coupling is
A sign of a well-structured computer system
Good design
When combined with high cohesion
supports high readability, maintainability, extendibility, and reusability
23
Fan-In Fan-Out and Stable Module
One way to examine module stability (i.e. Low coupling and
High Cohesion) is by looking at its Fan-In Fan-Out and other
dependencies
Fan-In: The number of users for the module
Fan-Out: The number of modules that the current module is
being used with
A Stable module is a module that has high fun-in and low
fan-out
This module can be easily reused
24
Cross Cutting Concerns
Logging
Authentication and Authorization (Identity & Security)
Error Handling
Communication & Hosting
Admin
Report
Caching
Configuration
Validation
…
The Two Views of The System
The software solution can be viewed from two angles:
The Static View
The components and the possible relationships between them
UML class diagram & component diagram for example
The Dynamic View
The flow of operation, request or transaction in the system
UML sequence and activity diagram for example
26
Machine Manager
ErrorHandler ErrorInfo
1 *
Create
error
ErrorMessage
NotifyNewError
GetErrorInfo
Service A
NewError
ErrorDetector * 1 ErrorHandler
ClearError
CheckErrorStatus
* 1
Destroy
*
Error ErrorInfo
Creates
27
IDesign Method
IDesign method provides a methodology that assists in:
Assembly Allocation
Run-Time Process Allocation
Identity Management
Call Authentication and Authorization
Transaction Flow
.
Command Health .
Engine Engine .
Pub/Sub
Reports
Device
Accessor
Support
Device A Device B
29
Based on Idesign Methd
B&H Android/
iOS and Future B&H B2C Site
Apps
Engine Engine
External
Systems DB (Oracle)/
(Search - Endeca, Storage
Back Office) Accessors
Accessors
30
Analysis Phase
Analysis Phase
Analysis Realization & Validation
A user compares products
Compare Selected
Compare Products Get User Context
Products
Get Comparision
Template
Build Comparision
Table
Return Comparision
Table
Phase
Architecture Summary
Understand the requirements
Understand the constraints
Low Coupling
High Cohesive
Balance of Size & Number of Components
Cloud Computing
Why the Cloud?
Rapidly setup environments to drive business priorities
Scale to meet peak demands
Increase daily activities, efficiency and reduced cost.
Introduction to Cloud Computing
Cloud Computing - A Game Changing Technology
Infinite shared resources & services
Infrastructure is not a limiting factor
No need to equip for peak-load requirements
Elasticity on demand
Anytime, anywhere
Efficient scalability and high availability
Suitable pricing models
Pay for what you use
Cloud Computing
Evolution of Computing - The Next (Current) Big Thing
Virtualization and Abstraction
Details are abstracted from consumers
Reduces complexity
Not necessarily the Internet, can be on premises
Private cloud
Automation, Monitoring, Deployment
Reduce cost, shift risk, shorten time-to-market, focus on
business functionality
37
Less Worries
Focus on functionality
Let others take care of:
Resource management
Security
Environments (staging, production)
High availability, scalability, load balancing
Fault tolerance
OS - installation, licensing, updates, patches
Network
Maintenance
38
You scale, make resilient and manage
On Premises
Applications
(as a Service)
Infrastructure
Managed by vendor
You manage
Platform
(as a Service)
41
Cloud Application Architecture
High Scale, High Availability, High Maintainability – to
the Extreme!
The Cloud technology enables cloud scale applications with much less effort
Answers many of the non-functional requirements and the cross-cutting concerns out of
the box!
Enables elastic, theoretically endless scale
Surfaces more concerns:
More geographic options
Promotes “design for failure” (be prepared for VM shutdown)
Promotes Agility (continued integrations/deployments)
42
Architect for High Availability
Remove any single-point-of-failure throughout your application
Make sure you have redundant services
Distribute services and data across geographies
Extreme monitoring & automatic responses
Elastic scaling
Self healing mechanisms (Azure Fabric Controller, AWS Elastic Beanstalk)
Long latency is a failure!
Make sure your services respond quickly even on load
Spawn more instances, buy better QoS resources (I/O, CPUs, Memory, Network)
Load balance to reduce the pressure
Have a storage only based failover web site for web applications
43
Load Balancing Servers
A single system can exceed its resource limit
CPU, Memory, IO, Network Connections
Use the best VM size to best fit the load among these resources
44
Multi-Tenancy
One Application to Rule Them All!
The cloud provides many benefits
You develop and deploy to the cloud
Staging/Production cloud environments
Cloud management & monitoring
You’d like to share those effort for all
of your customers
A Multi-tenant application is one application that serves many
isolated application instances
Beware of privacy
45
Azure Architecture Blueprints
Microsoft Azure
48
Microsoft Azure – 17 Regions Worldwide in Mid 2015
Azure
footprint
Data Centers
Regional Partners
Microsoft Azure (Mid 2015)
>80% >300k
More than
1,000,000
Fortune 500 using Azure Active websites SQL Databases in Azure
>30 TRILLION
storage objects >500 MILLION
AAD users
>1.65
>3 >13
MILLION MILLION
requests/sec BILLION
authentication/wk Developers registered
with Visual Studio Online
Microsoft Azure Services
Management
Marketplace
Developer
…
Services
Integration
Analytics
Hybrid
& IoT
& Access
Identity
Web
App Web App Mobile App API App Logic App API Notification Mobile Azure Active Multi-Factor
Service Management Hubs Engagement Directory Authent CDN
Networking
Compute
Availability set
SLA High Availability
Hardware and Software
Windows and Linux
SLA 99.95
Load Balancing
56
PaaS Services
There are many PaaS services such as:
Application & Web site deployment to an existing VM Image
Authentication, Identity & Access Control
Application Services
Web, Mobile, Logic
Cloud Containers
Docker, Service Fabric
Databases (SQL & No SQL)
Content Delivery Network (CDN)
Messaging, Queues & Service Bus
Distributed Cache
Business Workflows
Video (Media) Transcoding &
Streaming
Business Analytics, BI & Reporting
HPC & Big Data
IoT event streaming
Compute Continuum
IaaS PaaS
VM Service
VMs App Service
Extensions Fabric
Ultimate Rapid
Control Development
Cloud Storage - Azure BLOB Storage
BLOB – Binary Large OBject
Storage for any type of entity such as binary files and text
documents
Distributed File Service (DFS)
Scalability and High availability
BLOB file is distributed between multiple server and replicated at
least 3 times
60
Blob Operations
REST
Cloud Storage - SQL Azure
SQL Server in the cloud
No administrative overheads
Shared or Reserved (Dedicated) Hardware
High Availability
pay-as-you-grow pricing
Familiar Development Model
64
Cloud Storage - DocumentDB
A fully managed, highly scalable, queryable, schema-free document database,
delivered as a service, for modern applications
Multi-Document transactions
68
Types of microservices
Stateless microservice
Has either no state or it can be retrieved from an external store
There can be N instances
e.g. web frontends, protocol gateways, Azure Cloud Services etc.
Stateful microservice
Maintain hard, authoritative state
N consistent copies achieved through replication and local persistence
e.g. database, documents, workflow, user profile, shopping cart etc.
69
Cluster: A federation of machines
Node
Node Node
Node
Node
Node
3-Tier service pattern
Load Balancer
Load Balancer
73
Microservices placement and failover
Node 100 Node 101 Node 102 Node 103 Node 104 Node 105
P S P P S P
S S S S S
P S
S P S S S S
S S S S
S
Get Started
Learn more about the Reliable Actors APIs
Learn more about the Reliable Services APIs
Get Started:
Reliable Actors: The canonical HelloWorld walk-through
scenario
Reliable Services: Getting Started with Microsoft Azure
Service Fabric Reliable Services
PaaS - Azure App Service
Azure App Service: One Integrated Offering
Example:
Create a tweet when a file is saved to Dropbox
Introduction Video
Tutorial
API App – Create, Consume and Host API
Dozens of built-in APIs for popular SaaS
An ecosystem of APIs for any need
Create and publish custom, reusable APIs
Visual Studio tooling with one click publish and remote debugging
Automatic client SDK generation for many languages
Tutorial
Intro
Video
Built-in API Connectors
Connectors
• Box • QuickBooks • Azure Web Jobs
• Chatter • SalesForce • Yammer
• Delay • Sugar CRM • Dynamics CRM
• Dropbox • SAP • Dynamics AX
• Azure HD Insight • Azure Service Bus • Hybrid Connectivity
• Marketo • Azure Storage
• Azure Media Services • Timer / Recurrence
• OneDrive • Twilio
• SharePoint • Twitter
• SQL Server • IBM DB2
• Office 365 • Informix
• Oracle • Websphere MQ
Windows Xamarin
REST API
iOS PhoneGap
Android Sencha
HTML 5/JS Facebook Twitter Microsoft Google Azure Active
Directory
Offline
sync
SQL Database
TableController
BYOD
DTO
DataManager
DTO
Table Storage
Device Mobile Service/App
MongoDB
Azure SQL DB
Out-of-the-box implementation
Easily store relational data
Fully integrated with Mobile Services
Azure Table Storage
Azure Table Storage is a highly-scalable cost-effective key-value data
store
NoSQL
Every item is addressable by combination of:
Partition Key
Row Key
Store non-relational data
.NET backend only
Azure Blob Storage
Storing Blobs in a database is inefficient
BLOB storage is much cheaper and scalable
Can manually integrate the backend (C#/JavaScript) with Blob
storage to store blobs
Only store a reference to the blob (URI) in the DB
Existing SQL Database
TableController
System
DTO Existing
Properties
DataManager Tables Table
DTO Model
AutoMapper
On-Premise SQL Database
Hybrid Connections
Hybrid
Connection
Manager 1433
https://Mobileservice.azure-mobile.net/tables/*
R
G
E
S
A
T
Valid
APP T
User ID
+
Token
E A
W P
A I
Y
Enterprise Authentication
Use Azure Active Directory
Extend line-of-business to mobile
Bring turn-key login experience with corporate credentials to mobile
developers
Enable applications built around organizational structures
Offline Access & Synchronization
Offline Data Sync
The best mobile apps handle network interruptions gracefully
Adding offline sync to an app is usually hard
With Azure Mobile App, it’s easy
Why Use Mobile Offline Sync?
Improve app responsiveness by caching server data locally on the
device
Make apps resilient against intermittent network connectivity
Allow end-users to create and modify data even when there is no
network access
Sync data across multiple devices
Detect and handle conflicts when the same record is modified by
more than one client
Mobile Services/Apps Resources
Official Documentation
Azure Mobile Apps @BUILD 2015
Migration from Azure Mobile Services to Azure Mobile Apps
Microsoft Azure Training Kit
Azure DevCamp
Microsoft Virtual Academy
Push Notifications
Push is Transforming Businesses
Send Notification
3. Your backend connects to PNS and requests push
2
Your code has to map between logical users and 3 Platform
device handles Notification
Service
4. PNS pushes notification to device
5
Send Notification
3. Backend sends request to Notification Hub using a tag Client app PNS
Notification Hub manages scale
Notification Hub maps logical users/groups to device
handles
4 5
4. Notification Hub delivers notifications to matching 2
devices via PNS
Windows 10
Windows Core
Windows Core
if (Frame.CanGoBack)
{
// Setting this visible is ignored on Mobile and when in tablet mode!
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
AppViewBackButtonVisibility.Visible;
}
Desktop, Windowed mode:
Or provide your own on-canvas Back Button
UI Designer and XAML
Fundamentals
UI Designer and XAML Fundamentals
Visual Studio
UI Designer
Toolbox
Document Outline
Properties View
Device Emulator
What is XAML?
Basic XAML
Type Converters
Markup Extensions
Naming Elements
XAML Rules
Summary
UI Designer
Visual Studio UI Designer
provides quick and easy way to
produce rich UI interface
Drag and drop UI controls from
the toolbox into the designer
The UI designer provides an easy
way to select, resize, align,
transform and more, using only
the mouse
The UI designer generates XAML
and automatically updated when
XAML changes
Toolbox
The toolbox groups UI controls
available at design time
3rd party and custom controls are also
available from the toolbox
Simple drag and drop a control from
the toolbox to the designer canvas
Element from the toolbox can be also
drag and drop directly into XAML
Controls can be searched within the
search box and can be sorted
Additional groups can be created
Device View
The device view provides an easy way to change page layout properties
Page orientation: Landscape or Portrait
screen resolutions:
Document Outline
The document outline view displays
the logical tree of UI elements, each
element name or type and an icon of
the element’s type
Each element in the hierarchy can be
design-time locked and hidden
The document outline is very useful to
navigate between UI elements,
especially in complex XAML files
Properties View
The properties view provides an easy
a rapid way to:
Search for an element’s property by its
name
Set simple property value using plain
text
Set complex property value using
designers
Easily select color brushes, styles, font
size, transformations and more
Register element’s events
Arrange properties in groups
Create data bindings
Reset to default values
What is XAML?
XML based language
Enable separation of UI and behavior (code)
Windows Phone related tools emit XAML
XAML allows
Creation of objects
Setting of properties
Connection to events
Custom behaviors
XAML cannot call methods directly
XAML vs. Code
Anything that can be done in XAML can be done in
code
But not vice versa
XAML is usually shorter and more concise than the
equivalent code
Thanks to type converters and markup extensions
XAML should be used for initial UI
Code will handle events and change items
dynamically
Simple XAML Example
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK" />
Windows.UI.Xaml.Controls.Button b = new
Windows.UI.Xaml.Controls.Button();()
b.Content = "OK";
<Button>
<Button.Content> <Button>
<Rectangle Fill="Blue"/> <Rectangle Fill="Blue"/>
</Button.Content> </Button>
</Button>
Collection Items
List (IList)
<ListBox>
<ListBox.Items>
<ListBoxItem Content="Item 1"/>
<ListBoxItem Content="Item 2"/>
</ListBox.Items>
</ListBox>
Dictionary (IDictionary)
<ResourceDictionary>
<SolidColorBrush x:Key="br1" Color="Aqua" />
<Rectangle x:Key="rc1" Fill="Brown" />
</ResourceDictionary>
Summary of XAML Rules
XML Element – create a new instance
XML attribute – set a property or register an event
Type converter may execute
Type.Property – set a “complex” property
ContentProperty attribute – no need to specify
Type.Property
Property of type IList or IDictionary
Add child elements (XAML calls appropriate Add method)
Need a x:Key in case of a dictionary
Parsing and Using XAML
Visual Studio compiles the XAML file to BAML (Binary XAML) and
embeds it as a resource
The BAML is parsed at runtime and the object tree created by the
InitializeComponent method of the parent’s element class
[GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
Code
Canvas.SetLeft(cmdOK, 30);
Canvas.SetTop(cmdOK, 20);
cmdOK.SetValue(Canvas.LeftProperty, 30);
cmdOK.SetValue(Canvas.TopProperty, 30);
Routed Events
UWP events are not implemented via the default .NET event
implementation
Routed events implemented similarly to dependency properties
Routing strategies (RoutingStrategy enum)
Bubbling event – upwards the tree
Tunneling event – downward the tree
Direct event – only on the source element
Declared with the static EventManager.RegisterRoutedEvent
method
Element Lifetime Events
Initialized (ordinary event, not a routed event)
Fired when the control properties have been set according to its XAML, but
styles and data binding have not been applied yet
The IsInitialized property is true
Loaded
Occurs after the entire window has been initialized and styles and data
binding have been applied
The IsLoaded property is true
Unloaded
Occurs when the specific element has been released, either because the
parent window has been closed or the element has been removed from its
container
Binary Resources
The resources that can be used by any .NET application
Usually store bitmaps, icons, etc.
Packaging
Embedded inside an Assembly
Loose files that are known to the application at compile time
Loose files that are not known to the application at compile time
May be localized
Defining Binary Resources
Binary resources can be embedded using Visual Studio by adding the
resource and selecting an action type
Resource
Embedded inside the assembly
Content
Remains as a loose file, but an AssemblyAssociatedContentFile attribute is
added with the relative path of the file
Don’t use the Embedded Resource action! (UWP can’t use such
resources)
Accessing Binary Resources
Binary resources that are added to the project as Content or
Resource can be referenced easily, even if loose files are involved (as
long as they are in the folder of the executable or a subfolder)
VerticalAlignment
Width
LayoutTransform
FlowDirection
Element Size
Width and Height properties (from FrameworkElement)
Control the exact size of the element
Default value is Double.NaN
Meaning: be as large as it needs to be
usually a bad idea to use these properties
Prevents smart resizing by panel
Reasonable only in a Canvas
MinWidth, MinHeight, MaxWidth, MaxHeight properties
Defaults are 0 (MinWidth, MinHeight), Double.PositiveInfinity
(“Infinity” in XAML) (MaxWidth, MaxHeight)
More Size Properties
Read only properties
DesiredSize
Set indirectly by elements to report their desired size to their parent
Internally used by panels
RenderSize
The actual size the element is rendered with
ActualWidth, ActualHeight
Just the components of RenderSize (RenderSize.Width, RenderSize.Height)
Margin and Padding
Both of type Thickness (value type)
Maintains the properties Left, Top, Right, Bottom indicating distance
from the corresponding edge
Margin (from FrameworkElement)
The amount of space to add around the element
Padding (from Control, and Border)
The amount of space to add around the content of the control
In XAML, can supply one, two or four numbers
Visibility
Visibility of elements is determined by the Visibility property
(from UIElement) of the Windows.UI.Xaml.Visibility
enumeration
Visible
The element is rendered and participates in layout
Collapsed
The element is invisible and does not participate in layout
Element Positioning
Element position is determined by the containing panel policy
Simple X,Y is not the usual case
Elements can indicate their position constraints or preferences to
their containing panel
Alignment
Alignment indicates what should be done with any extra space given
to an element
HorizontalAlignment
Left, Right, Center, Stretch
VerticalAlignment
Top, Bottom, Center, Stretch
192
(C)2015 by Pavel Yosifovich
Application Events (2)
SessionEnding
Windows session is ending (e.g. log off or shutdown)
Can cancel the shutdown by setting
SessionEndingCancelEventArgs.Cancel to true (otherwise WPF calls
Application.Shutdown)
Activated
Occurs when a top level window in the application is activated when the
user switches from another application
Also occurs the first time a window is shown
Deactivated
Occurs when the user switches to another application
193
(C)2015 by Pavel Yosifovich
Application Events (3)
DispatcherUnhandledException
Occurs when an unhandled exception is about to terminate the application
Only on the current (UI) thread
Can be used to log the error, show a nice dialog to the user, etc.
Can also “cancel” the exception and continue running by setting the
property DispatcherUnhandledExceptionEventArgs.Handled
to true
Must be careful – difficult to guarantee the application is in a valid state to continue
194
(C)2015 by Pavel Yosifovich
Application Shutdown
Application shutdown is controlled by the ShutdownMode property
OnLastWindowClose (default) – application shuts down when the last top
level window is closed
OnMainWindowClose – application shuts down when the main window
closes
OnExplicitShutdown – the application does not shut down even if all
windows are gone
Calling Application.Shutdown must be used
This call can be used regardless of the setting of the ShutdownMode property
195
Data Binding
What is Data Binding?
Data in UWP can reference any .NET object
Data binding means tying two arbitrary objects
Typical scenario is a non-visual object (or collection) to a visual
element
Any changes to the non-visual object are reflected in the visual
element (and optionally vice versa)
Data Binding Concepts
Source
The data object to bind to
Property Path
The property on the source object to use
May be a nested property, an array element or an indexer
Target
The target object to modify
Must be a dependency property
Binding Mode
Typically one way or two way (target update source)
Using Data Binding
Typically done in XAML using the {Binding} markup extension
The Binding class is the workhorse behind the scenes
Set on the target property
Can be done programmatically in code
Common scenario is when building custom controls
Binding Direction
The Binding object allows specifying how the target / source
properties are updated
Mode property (of type enum BindingMode)
UpdateSourceTrigger Meaning
PropertyChanged The source is updated whenever the target changes
LostFocus The source is updated when the target property’s element loses focus
Explicit The source is updated only when the method
BindingExpression.UpdateSource is called
Default Depends on the target property
(FrameworkPropertyMetadata.DefaultUpdateSourceTrigger property)
Binding to Objects
Source
Reference to the source object
RelativeSource
Sets the source based on the “location” of the target in the layout tree
Useful in data and control templates
DataContext
Used by default if Source or RelativeSource is not specified
Searches up the element tree if not found on target element
Change Notifications
An object must notify when one of its properties changes
By defining the property as a dependency property
Or by implementing the INotifyPropertyChanged interface
Raise the PropertyChanged event
The DataContext
Sometimes many elements bind to the same object
Perhaps with different properties
The object may be specified as the DataContext property on any
common parent element
Whenever the Source or RelativeSource properties are not
specified in the Binding, a data context object is searched up the
element hierarchy
If found, becomes the binding source object
Can be used programmatically without the need to create the source
object in XAML
Data Templates
A data template is a piece of UI that describes how to display a
source object
Various elements have properties of type DataTemplate just for
this
ContentControl has a ContentTemplate property
ItemsControl has a ItemTemplate property
HeaderedContentControl and HeaderedItemsControl have a
HeaderTemplate property
With data binding, the source object is automatically set to the
current object that is being rendered
Value Converters
A value converter can completely alter the way the source is
interpreted into the target
Often used to match source and target that are of incompatible
types
E.g. show a red background when the price of a book is greater than
50
A value converter implements the IValueConverter interface
Create an instance of the converter as a resource and use in a
binding expression
public interface IValueConverter {
object Convert(object value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture);
}
Converter Parameters
The “parameter” object is null by default
Can be set using the ConverterParameter property of the Binding object
Not “bindable” in itself!
The culture info supplied is by default set to “en-US”
A type converter exists that can be used via the ConverterCulture
property of the Binding object (e.g. “fr-CA”, “he-IL”)
The return value can be Binding.DoNothing, which cancels the
binding operation
Data Template Selectors
A way to replace a data template completely
Cannot be done in XAML alone
Derive a class from DataTemplateSelector
Override the SelectTemplate method
Set the ItemTemplateSelector property on the ItemsControl
element to an instance of the custom template selector
Data Template Selector Example
<Window.Resources>
<local:AlternateTemplateSelector x:Key="tmpselect" EvenTemplate="tmp1" OddTemplate="tmp2" />
<DataTemplate x:Key="tmp1">
<TextBlock Margin="2" Background="Red" Foreground="White" FontSize="20" Text="{Binding}"/>
</DataTemplate>
<DataTemplate x:Key="tmp2">
<TextBlock Margin="2" Background="Yellow" Foreground="DarkBlue" FontSize="15" Text="{Binding}"/>
</DataTemplate>
</Window.Resources>
<ListBox Name="list" ItemTemplateSelector="{StaticResource tmpselect}"
HorizontalContentAlignment="Stretch"/>
Commands,
Properties, Methods,
Behaviors Properties
Model
Model
View ViewModel Model
Events
MVVM Participants
Model
Business logic and data
May implement change notification for properties and collections
View
Data display and user interactivity
Implemented as a Page, UserControl, DataTemplate or custom control
Has little or no code behind
ViewModel
UI logic and data for the View
Abstracts the Model for View usage
Exposes commands (ICommand) to be used by the View
Implements change notifications
Maintains state for the View (communicates via data binding)
The View
Provides the user interface and interaction
The DataContext property points to the View Model
Updated using property changes from the ViewModel
Binds to commands (on ICommandSource elements) provided by
the ViewModel
The ViewModel
Exposes properties the View binds to
Can be an adapter if some functionality missing from Model classes
Exposes commands to be invoked by the view
Maintains state for the View
Implements change notifications (INotifyPropertyChanged)
Uses ObservableCollection<T> that already implements
INotifyCollectionChanged
The Model
Responsible for business logic and data, e.g.
Data Transfer Objects (DTO)
POCOs (Plain Old CLR Objects)
Generated entity objects
Generated proxy objects
May provide change notifications
Provides validation if appropriate
Introduction to Commands
Handling routed events and executing some code is fine for simple
applications
Sometimes the same code needs to execute from unrelated events
(e.g. mouse click, keyboard shortcut, menu item, toolbar)
Maintaining UI state (e.g. enabled/disabled) becomes difficult
Higher level functionality, such as an undo / redo system is not
possible
Solution: use commands (the “Command” design pattern) with
some support from UWP
The Command
A command is an object implementing the
System.Windows.Input.ICommand interface