Professional Documents
Culture Documents
Introduction To The Microsoft Azure - 2
Introduction To The Microsoft Azure - 2
Fundamentals
By Utkarsh Mishra
MSP INDIA
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
In this course we will:
Talk about modern architecture & design
See how the cloud provides the backend server side foundation and
tooling
See how Windows 10 provide the foundation and tooling for building
modern rich user interface clients
Running on IoT devices, phones, tablets and desktop
Windows 10 Motivation
Demo
One
Windows
Platform
Software Architecture
What an Architect Must Know
Understand the requirements
Understand the constraints
Low Coupling
High Cohesive
Balance of Size & Number of Components
The Architecture Process
Understand the requirements
Capture the main system building blocks
Provide the first abstraction
Validate the architecture concepts vs. the
requirements
Communicate the conceptual architecture with the
stakeholders
Refine the architecture
Capture the architecture decisions
documentation, modeling
Requirements & Constrains
Non-Functional requirements
Mainly architecture phase
Functional requirements
Mainly design phase
Constraints
Decision Helpers
Architecture Attributes
Performance
Localize operations to minimize sub-system communication
Security & Identity
Use a layered architecture with critical assets in inner layers
Provide Identity flow diagram for the whole system
Safety
Isolate safety-critical components
Availability
Include redundant components in the architecture
Maintainability
Use fine-grain, self-contained components
Scalability
Include redundant components and handle state
More Quality Attributes (*Ilities )
Stability Scalability
Backward compatibility Testability
Extensibility Composability
Reliability Demonstrability
Maintainability Deployability
Availability Efficiency
Security Learnability
Usability Manageability
Auditability Operability
Decomposition
Is this a good design?
17
Decomposition
Is this a good design?
18
Decomposition
Is this a good design?
Decomposition
Decomposition
20
The cost of the software development process
Optimal Number
Of Modules
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 Reuse:
Report • P&P Enterprise Libraries
Caching • 3 rd party/open source project (NuGet)
26
Machine Manager
Handling 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
Admin
Client
Diagnostics Archive
Manager Manager Logging
.
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&HB2C 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
esahP
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
Why the Cloud?
On Premises Infrastructure Platform Software
(as a Service) (as a Service) (as a Service)
You manage
Applications Applications Applications Applications
You scale, make resilient and manage
management by vendor
Scale, resilience and
Runtime Runtime Runtime Runtime
management by vendor
Middleware Middleware Middleware Middleware
Managed by vendor
Virtualization Virtualization Virtualization Virtualization
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
Azure: the color of the sky
on a clear summer's day
Wikipedia
48
Microsoft Azure – 17 Regions Worldwide in Mid 2015
Azure
footprint
Data Centers
Regional Partners
More than
Microsoft Azure (Mid 2015)
1,000,00
>80 > 300k 0
%
Fortune 500 using Azure Active websites
>1.6
SQL Databases in Azure
>30 TRILLION
storage objects >500 MILLION
AAD users
5
>3
MILLION
requests/sec
>13 BILLION
authentication/wk
MILLION
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
Premium
Storage
Availability set
SLA High Availability
Hardware and Software
SQL Server
Primary
SQL Server Windows and Linux
Secondary
SLA 99.95
Load Balancing
PORT 80 VM3
/healthcheck.aspx
LBHTTP
ARM – Resource Group
Container for multiple resources
Resources exist in one and only one resource group
Resource groups can span regions
Resource groups can span services
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
NDA Confidential
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
http://<account>.blob.core.windows.net/<container>/<blobname>
PIC01.JPG
images Block/Page
PIC02.JPG
contoso
Block/Page
videos VID1.AVI
60
Blob Operations
PutBlob
GetBlob
DeleteBlob
REST
CopyBlob
SnapshotBlob
Windows Azure
LeaseBlob
Storage
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
Name =…
Email = …
customers
Name =…
EMailAdd=
contoso
Photo ID =…
Date =…
photos
Photo ID =…
Date =…
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
A set of machines that
Service Fabric stitches Node
together to form a
cluster
Node Node
Node
3-Tier service pattern
Load Balancer
Load Balancer
• Built in transactions
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
• Chatter
• Delay
• Dropbox
• Azure HD Insight
• Marketo
• Azure Media Services
• OneDrive
• SharePoint
• SQL Server
• Office 365
• Oracle
• QuickBooks
• SalesForce
• Sugar CRM
Protocols
• SAP BizTalk Services
• Azure Service Bus
• HTTP, HTTPS • Batching / Debatching
•• Azure Storage
File • Validate
•• Timer
Flat File/ Recurrence • Extract (XPath)
•• Twilio
FTP, SFTP • Transform (+Mapper)
•• POP3/IMAP
Twitter • Convert (XML-JSON)
•• SMTP
IBM DB2 • Convert (XML-FF)
•• SOAP + WCF
Informix • X12
• EDIFACT
• Websphere MQ • AS2
• Azure Web Jobs • TPMOM
• Yammer • Rules Engine
• Dynamics CRM
Azure Web Apps
Rich monitoring and Share capacity across Web
alerting and Mobile
Traffic manager Staging slots
Custom CNAMEs Validate changes in your staging
environment before publishing
VNET and VPN to production
Backup and restore More DevOps features
Many VM size and Support for BitBucket and Visual
instance options Studio Online; seamless
integration with GitHub
In production A/B
testing Web Jobs
Auto load-balance
Azure Mobile App
Azure Mobile App
REST API
Mobile SDKs
Windows
User Authentication
Xamarin
iOS PhoneGap
Android Sencha
HTML 5/JS Facebook Twitter Microsoft Google Azure Active
Directory
Offline
sync Push Notifications
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
R
Provide
r
G
E
Token
S
Valid
APP
A
User ID T
+
Token
User ID + T
Auth
A
Token E
P
I
W
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
Client app
Send Notification
3. Your backend connects to PNS and requests push
Your code has to map between logical users and
2
device handles 3 Platform
Notification
4. PNS pushes notification to device Service
5
Maintain backend device handles
5. Your code must delete expired handles when
PNS rejects them App back-end
6. Your code must map between logical users and device
6
handles
Azure Notification Hub
Register device handle at app launch
1. Client app retrieves handle from Platform Notification Service
2. Client sends handle to your backend
Backend registers with Notification Hub using tags to
represent logical users and groups
1 4
Send Notification
3. Backend sends request to Notification Hub using a tag
Notification Hub manages scale
Client app PNS
Notification Hub maps logical users/groups to device
handles
4. Notification Hub delivers notifications to matching
4 5
devices via PNS
2
Windows 10
Multiple
Universal
device
Apps
families
Reuse Existing
Adaptive
Code
User Interface
Natural
One Store +
One SDK + One Dev Center
User Inputs Tooling
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;
<Page x:Class="UWPDemo.MainPage"
Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> StackPanel
<StackPanel>
<Button Content="OK" Background="Red" Margin="6"/>
Button ListBox
<ListBox Margin="6" >
<ListBoxItem Margin="2">
<Border BorderThickness="4"> ListBoxItem ListBoxItem
<TextBlock Text="Hello" FontSize="20" />
</Border>
</ListBoxItem> Border
<ListBoxItem Content="Item 2" />
</ListBox> TextBlock
</StackPanel>
</Page>
Visual Tree
The actual visual
objects making up a
logical tree
Generated from the
control templates
Traversing the Trees
The logical and visual trees can be examined using the static
classes System.Windows.LogicalTreeHelper and
Windows.UI.Xaml.Media.VisualTreeHelper
VisualTreeHelper
GetParent, GetChild, GetChildrenCount
LogicalTreeHelper
GetParent, GetChildren
Dependency Properties
Dependency properties are the workhorse of any
XAML based technology
Provide the basis for many of UWP’s features
E.g. data binding, animations, styles
Value may be provided by many entities, each with its own
priority
Highest active level wins out
Must be “registered” by calling the
DependencyProperty.Register method
Most UWP properties are dependency
Dependency Property Example
Can use the “propdp” Visual Studio code snippet for easier DP
declaration
public abstract class Shape : FrameworkElement {
public static readonly DependencyProperty FillProperty =
DependencyProperty.Register("Fill", typeof(Brush), typeof(Shape), new
FrameworkPropertyMetadata(null,
Che
FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender |
FrameworkPropertyMetadataOptions.AffectsRender));
ck
public Brush Fill {
get {
return (Brush)base.GetValue(FillProperty);
}
set {
base.SetValue(FillProperty, value);
}
}
}
Dependency Property Precedence
Property value coercion High
Animation
Local value (also resource or data binding)
TemplatedParent template properties
Triggers override property setters
Che
Implicit style
Style triggers
ck
Template triggers
Style setters
Default (theme) style
Triggers in the theme style override setters
Inheritance
Default value from property metadata Low
Attached Properties
Special kind of dependency properties
May be “attached” to objects of different types than the
declaring type
Declared with the static
DependencyProperty.RegisterAttached method
Che
Allows “context” properties
E.g. Canvas.Left for elements that happen to be in a Canvas
element
Can be set on any object
XAML
An attribute with Type.Property syntax is used
ck
In code
The type exposes a SetXxx and a GetXxx with the element reference
Attached Properties Example
XAML
<Canvas>
<Button x:Name="cmdOK" Canvas.Left="30"
Canvas.Top="20"
Content="OK" Padding="10" FontSize="26">
</Button>
</Canvas>
Che
Code
ck
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 Che
Direct event – only on the source element
Declared with the static
EventManager.RegisterRoutedEvent method
ck
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
Che
Occurs after the entire window has been initialized and styles and
data binding have been applied
ck
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
Che
Loose files that are not known to the application at compile time
May be localized
ck
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
Che
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)
ck
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)
<Button VerticalAlignment="Center" HorizontalAlignment="Center" >
Che
<StackPanel Orientation="Horizontal" >
<Image Source="apple.png" Width="48" Height="48" Margin="4"/>
<TextBlock Text="This is an Apple" FontSize="24"
ck
VerticalAlignment="Center" Margin="4"/>
</StackPanel>
</Button>
Logical Resources
Arbitrary named .NET objects, stored in the
Resources collection property of an element
Typically for sharing the resource among child objects
The FrameworkElement type define a Resources
Che
property (of type ResourceDictionary)
ck
Creating and Using Resources
Add a Resources property to some element
Usually a Page or the Application
Any child element can reference those resources
Add the objects with a x:Key attribute (must be unique in
this resource dictionary)
Che
Use the StaticResource markup extension with the
resource key name
ck
Resources Example
<StackPanel Margin="4" Orientation="Horizontal" TextBlock.FontSize="20">
<Button Margin="4" Content="1" Padding="4">
<Button.Background>
<LinearGradientBrush>
<GradientStop Offset="0" Color="Blue" />
<GradientStop Offset="1" Color="Yellow" />
</LinearGradientBrush>
</Button.Background>
</Button>
Che
<Button Margin="4" Content="2" Padding="4">
<Button.Background>
<LinearGradientBrush>
<GradientStop Offset="0" Color="Blue" />
<StackPanel
<GradientStopMargin="4"
Offset="1" Orientation="Horizontal"
Color="Yellow" /> TextBlock.FontSize="20">
ck
</LinearGradientBrush>
<StackPanel.Resources>
</Button.Background>
<LinearGradientBrush x:Key="back">
</Button>
<GradientStop
<Button Margin="4" Content="3" Padding="4">Offset="0" Color="Blue" />
<Button.Background> <GradientStop Offset="1" Color="Yellow" />
<LinearGradientBrush>
</LinearGradientBrush>
<GradientStop Offset="0" Color="Blue" />
</StackPanel.Resources>
<GradientStop Offset="1" Color="Yellow" />
<Button Margin="4" Content="1" Padding="4" Background="{StaticResource
</LinearGradientBrush>
back}" />
</Button.Background>
</Button> <Button Margin="4" Content="2" Padding="4" Background="{StaticResource
</StackPanel> back}" />
<Button Margin="4" Content="3" Padding="4" Background="{StaticResource
back}" />
</StackPanel>
Layout
Layout is the arranging of user interface elements within
some container
Older technologies (e.g. Windows Forms) mostly used exact
position and sizes
Limited in flexibility and adaptability
UWP provides several layout panels that can control
dynamically size and placement of elements
Elements may advertise their size and position needs
Size and Position of Elements
Element sizing and positioning is determined by the element
itself and its logical parent
A child element may request various settings
The parent panel does not have to comply
Element Layout Properties
Panel
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
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
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
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)
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"/>
public class AlternateTemplateSelector : DataTemplateSelector {
public string OddTemplate { get; set; }
public string EvenTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
return (DataTemplate)((FrameworkElement)container).FindResource(
(int)item % 2 == 0 ? EvenTemplate : OddTemplate);
}
}
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
private void OnGetData(object sender, RoutedEventArgs e) {
_cmdGet.IsEnabled = false;
var wc = new WebClient();
_text.Text = wc.DownloadString(new Uri("http://msdn.microsoft.com"));
_cmdGet.IsEnabled = true;
}
private async void OnGetData(object sender, RoutedEventArgs e) {
_cmdGet.IsEnabled = false;
var wc = new WebClient();
_text.Text = await wc.DownloadStringTaskAsync("http://
msdn.microsoft.com");
_cmdGet.IsEnabled = true;
}
Asynchronous methods
Marked with the async modifier
Must return void, Task or Task<T>
Avoid returning void
Does not allow callers to be notified of completion
Use await to cooperatively yield control
Are resumed when awaited operation completes
Can await anything that implements the “awaiter pattern”
Execute in the synchronization context of their caller
Depends on the implementing awaiter
Allow composition using regular programming constructs