You are on page 1of 233

Microsoft Azure

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)

• The Cloud Foundation


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

Error ErrorHandler ErrorInfo

Handling 1 *

errorDetctor errorHandler machineManagerErrorHandler

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


To learn more about IDesign Method refer to IDesign site or


participate in one of Juval Lowy’s Architecture Master Class
http://www.idesign.net
Event Health
 Diagnostics
 Machine Health
View Control Monitoring Security
UI Application Utilities

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

RESTful Service Contract


Manager

Business Logic Layer

Engine Engine

External
Systems DB (Oracle)/
(Search - Endeca, Storage
Back Office) Accessors
Accessors

External Systems Data

30
Analysis Phase

Analysis Phase
Analysis Realization & Validation
A user compares products

Home page MVC App


Product Manager Inventory Engien Comparision Engine User Manager
Controller

Compare Selected
Compare Products Get User Context
Products

Get Products Get Products


To Define
user
comparision
Compare Products defaults
Compare Products
With Template

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

resilient & manage


You scale, make
Data Data Data Data

management by vendor
Scale, resilience and 

Runtime Runtime Runtime Runtime

management by vendor
Middleware Middleware Middleware Middleware

Scale, resilience and 



O/S O/S O/S O/S

Managed by vendor
Virtualization Virtualization Virtualization Virtualization

Servers Servers Servers Servers

Storage Storage Storage Storage

Networking Networking Networking Networking


Cloud Computing Architecture
Introduction to Cloud Architecture
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
Less worries about the foundation – Better application quality!!!

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

Scaling Out: LB Over VM Instances


Distribute the load across machines taking into account machine
health state
Configuring the Load Balancer:
Automatically with Azure App Fabric and Amazon Elastic Beanstalk
Manually with Amazon Elastic Load Balancing (ELB) 

and Azure Endpoint LB

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

Visual Studio Application Operational


Online Insights Scheduler Automation Insights Key Vault

Integration
Analytics

Hybrid
& IoT

Media & CDN


Machine Stream BizTalk Media
HDInsight Learning Analytics Data Factory Event Hubs Services Service Bus Backup Site Recovery Services
& Mobile

& 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

Virtual Cloud Service Virtual Traffic Application


Machines Services Batch Fabric RemoteApp Network ExpressRoute Manager DNS Gateway
& Storage
Data

Blobs Tables Queues Files Data


Storage SQL Database Search DocumentDB Redis Cache StorSimple Data Lake Warehouse
Azure Compute Instance Options

SSD Storage Most Memory


Highest Value >50,000s of IOPS
Faster CPUs Fastest CPUs

Premium
Storage

Highest Value Largest Scale-up


Virtual Machine Standard Storage
Azure Storage Page Blobs, 3 copies
High durability
VHD disks, 1 TB per disk (64 TB
total)
500 IOPs per disk
Availability Sets

Availability set
SLA High Availability
Hardware and Software
SQL Server
Primary
SQL Server Windows and Linux
Secondary

Virtual Machine Virtual Machine

SLA 99.95
Load Balancing

Internal and External PORT 80


VM1
LBHTTP
/healthcheck.aspx
TCP/UDP
ACLs PORT 80 LB VM2
PORT 80
/healthcheck.aspx
LBHTTP
Client Affinity

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

Get Started with Storage Account


Get Started with Blob Storage
Azure Blob Storage Concepts

http://<account>.blob.core.windows.net/<container>/<blobname>

Account Container Blob Pages/ Blocks

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

Create your first Azure SQL database


Cloud Storage - Table Storage
Not RDBMS
No relationships between entities
NoSql
Entity can have up to 255 properties - Up to 1MB per entity
Mandatory Properties for every entity
PartitionKey & RowKey (only indexed properties)
Uniquely identifies an entity
Same RowKey can be used in different PartitionKey
Defines the sort order
Timestamp - Optimistic Concurrency
Strongly consistent
Get Started with Table Storage
Table Storage Concepts

Account Table Entity

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

Query against Schema-Free JSON

Multi-Document transactions

Tunable, High Performance

Designed for cloud first

Get started with the


DocumentDB .NET SDK
PaaS - Azure Service Fabric
Battle-hardened for over 5 years
Skype for
Azure Business
Document Intune
DB Hybrid Ops
Azure Core
Infrastructure 800k
billions devices
thousands of transactions
machines /week
Event
Hubs
Bing Cortana
Azure SQL 20bn events/
Database 500m evals/ day
sec
Power
BI 1.4 million
databases
What is a Microservice?
Is (logic + state) that is independently versioned, deployed, and
scaled
Has a unique name that can be resolved
e.g. fabric:/myapplication/myservice
Interacts with other microservices over well defined interfaces and
protocols like REST
Remains always logically consistent in the presence of failures
Hosted inside a “container” (code + config)
Can be written in any language and framework
node.js, Java VMs, any EXE
Developed by a small engineering team

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

Clusters can scale to


1000s of machines
Node
Node

Node
3-Tier service pattern

Load Balancer

• Scale with partitioned


storage Front End
(Stateless
Web)
• Increase reliability with
queues

• Reduce read latency


Stateless
with caches Middle-tier
Compute

• Manage your own


transactions for state
Cache
consistency

• Many moving parts each


managed differently Queues Storage
Stateful services: Simplify design, reduce latency

Load Balancer

• Application state lives in


the compute tier Front End
(Stateless
Web)
• Low Latency reads and
writes

• Partitions are first class


Stateful
for scale-out Middle-tier
Compute

• Built in transactions

• Fewer moving parts


data stores used for analytics and disaster recovery
Stateful Microservices are Reliable and Consistent

Each service is backed by replica set to make its


internal state reliable
All replicas are logically consistent – meaning all
replicas see the same linearized order of read and
write operations to initial state
Read-Write quorums are supported and are
dynamically adjusted
Replica set is dynamically reconfigured to account for
replica arrivals and departures

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

Web Apps Mobile Apps


Web apps that scale 
 Build Mobile apps 

with your business for any device

Logic Apps API Apps


Automate business process Easily build and consume APIs
across SaaS and on-premises in the cloud
Azure App Service
A new offering, consolidating and replacing existing services:
Azure Web Sites, Azure BizTalk Services, Azure Web API Authoring,
Azure Mobile Services
Create web and mobile experiences that share data access
and business logic
Automate business processes with logic apps
Build custom APIs or consume connectors from Marketplace
One common billing model for all of your App Services
Use a common Gateway to authenticate
Logic App – Easy Automation and Integration
No code designer for rapid creation
Dozens of pre-built templates to get started
Out of box support for popular SaaS and on-premises apps
Use with custom API apps of your own
Biztalk APIs for expert integration scenarios

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

Offline Sync Data connections Backend code

SQL Tables Mongo O365 API Apps

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

iOS OSX Android Windows Kindle In-App


Chrome
Azure Mobile App / Mobile Services
A Turnkey Backend for Employee Mobile Apps
Deliver Native & Cross Platform Apps
Enable Corporate Single Sign-On
Integrate w/ O365 and On-Premise Enterprise Systems
Connect To Any Data Source
Enable Offline and Real-Time Sync
Leverage Your Existing Skills with .NET Web API
Supported Platforms

Windows 8.x Windows HTML5 &


Windows 10 iOS Phone 8/10 Android Javascript
Azure Mobile Apps vs. Azure Mobile Services
Mobile Services – in classic portal
Mobile Apps – preview portal
When Mobile Apps is GA, will have all the features of Mobile
Services

Your investment is safe!


Azure Mobile App is still in preview
New features will go into Mobile Apps
Azure Mobile Services is still supported
After GA, Microsoft to offer a seamless migration experience
JavaScript vs .NET
JavaScript
Based on server side scripts
Node.JS Scripts
Intercept CRUD requests to tables
Passes through to SQL by default
Fully customizable logic flow
Edit in Azure Portal or via GIT integration
Currently (October 15) limited support in the new Mobile App
.NET
Based on ASP.NET Web API 2
Full .NET support
Intercept CRUD requests to tables
Custom APIs available using Web API 2
Fully customizable logic flow
Standard VS tooling & support
Local debugging
Standard MS Deploy to Azure
Data Storage
New Data Model

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

Device Mobile App/Service SQL Azure/BYOD

AutoMapper
On-Premise SQL Database
Hybrid Connections

Microsoft Azure Your Enterprise

Hybrid
Connection
Manager 1433

Connection string points


to My-Database:1433 My-Database
The REST API

Base REST API Endpoint URL


https://Mobileservice.azure-mobile.net/tables/*

Data Operations and their REST Equivalents


Action HTTP Verb URL Suffix
Create POST /TodoItem
Read GET /TodoItem?$filter=id%3D42
Update PATCH /TodoItem/id
Delete DELETE /TodoItem/id
Demo
Authentication & Authorization
Social Authentication
Authenticate against Microsoft Account, Twitter, Facebook,
Google
Table level permissions for each CRUD operation
Everyone
Anyone with the Application Key
Only Authenticated Users
Only Scripts and Admins
More granular control with server side code
User Level: Admin, Authenticated, Anonymous
User Id: Id or undefined if not authenticated
Social Authentication

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

Broadcast breaking news to Send notifications based on


millions of customers using account changes or actions
their preferences

Engage customer to improve Increase employee


your brand, customer productivity and
satisfaction, and business responsiveness
metrics
Push Notification 101
Register device handle at app launch
1. Client app retrieves handle from Platform 

Notification Service (PNS) 1

2. Client app sends handle to your custom backend 4

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

Maintain backend device handles


5. Notification Hub deletes expired handles when PNS 

rejects them 6
6. Notification Hub maintains mapping between logical 
 2 3
users/groups and device handles App back-end Notification
Hub
Advantages of Notification Hub
X-plat: one API to notify on any mobile platform
Backend can be on-prem or in the cloud, .NET, Java, PHP, Node, you
name it
Support iOS, Android, Windows Phone, Windows, Kindle
Avoid storing device information in your tables
Work with logical users and segments
Personalization and localization
Templates
Broadcast at scale, multicast, unicast
Rich Telemetry
Get Started with Windows App
Blog Post
Demo
SignalR
SignalR
A library for ASP.NET developers
Simplifies the process of adding real-time web functionality to
applications
Stock tickers
Notifications
Any real-time server to client information
SDKs are available in various platforms
Azure Mobile Services allows integrating SignalR communication
Easily integrate web based clients
.NET Backend Only
http://www.asp.net/signalr
http://www.asp.net/signalr/overview/deployment/using-signalr-with-azure-web-
sites
Azure Mobile Services SignalR Support
Summary
Windows Universal Platform
2-in-1s
 Classic 
 Desktops 

Phone Phablet Small Tablet Large Tablet (Tablet or Laptop) Laptop & All-in-Ones

Windows 10

Surface Hub Xbox Holographic IoT


PC XBox
Mobile Surface Hub

Devices +IoT HoloLens

Multiple
Universal
device
Apps
families
Reuse Existing
Adaptive 
 Code
User Interface
Natural
 One Store +

One SDK + One Dev Center
User Inputs Tooling

One Universal Windows Platform


Universal Windows Platform
One Operating System
One Windows core for all devices
One App Platform
Apps run across every family
One Dev Center
Single submission flow and dashboard
One Store
Global reach, local monetization 

Consumers, Business & Education
Universal Windows Platform
A single API surface
A guaranteed API surface
The same on all devices

Universal Windows Platform

Windows Core

Desktop Phone Xbox


Device Device Device
Windows app
A single app package
Running on any device
Testing for capabilities
Adjusting to devices Windows App

Universal Windows Platform

Windows Core

Desktop Phone Xbox


Device Device Device
Demo
Hello UWP
World
Handling Page Navigation
Shell-drawn back button for Mobile and Tablet
Desktop, Windowed mode: 

Opt-in, shell-drawn back button on Title Bar

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";

Visual Studio UI designer generates XAML on each


control picked from the toolbox
XAML Can be visually viewed in the UI designer
XAML Namespaces
The default XAML namespace is assigned a value that
is mapped to some of the runtime namespaces contain
UI elements
Other XAML namespaces may be mapped to custom
namespaces and other runtime namespaces
The “x” namespace is mapped to a special
namespace, contains XAML parser specific types
XAML namespace can be defined on each element
level
XAML Example
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1"
Margin="12,0,12,0">
<Button x:Name="buttonOk"
Width="200"
Height="200"
Content="OK"
Click="buttonOk_Click" />
</Grid>
Elements and Attributes
Elements with type names only designate object
creation (via the default constructor)
Attributes indicate property or event values
Event values are event handlers (methods) names
Complex properties are designated using a
<Type.Property> element
XAML Example
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button x:Name="buttonOk"
Width="200"
Height="200"
Content="OK"
Click="buttonOk_Click" >
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1“
StartPoint="0.5,0">
<GradientStop Color="#FFB2D9FF" Offset="0.004"/>
<GradientStop Color="#FFB0D8FF" Offset="1"/>
<GradientStop Color="#FF0A85FF" Offset="0.571"/>
</LinearGradientBrush>
</Button.Background>
</Button>
</Grid>
XAML And Code Behind
A root element, usually Page or UserControl classes, can
have code behind file
The name of the code behind file is correlated to the XAML
file name
For example: MainPage.xaml and MainPage.xaml.cs
The code behind full class name is specified from XAML using
the x:Class directive
<Page
x:Class="UWPDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UWPDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Image x:Name="image" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="Fill"
Opacity="0.5"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" " Height="61" Width="127"/>
</Grid>
Child Elements
Child elements (that are not property elements)
can be one of
The Content property of the object
A property adorned with the attribute
Windows.UI.Xaml.Controls.ContentPropert
y
Collection items
The object implements IList or IDictionary
A value that can be type-converted
Content Property
A single property that is designated with the
ContentProperty attribute on the type
Allows shortening the markup

<Button Content="OK" <Button>


> OK
</Button> </Button>

<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;

Uri resourceLocator = new Uri("ms-appx:///MainPage.xaml");


Application.LoadComponent(this, resourceLocator,
ComponentResourceLocation.Application);
{
Naming Elements
Elements can be named using the x:Name XAML
attribute
The code-behind file will contain a field with that
name
Elements deriving from FrameworkElement contain
a Name property that can be used in code to locate
elements
x:Name and Name cannot be set on the same element
XAML Keywords
Keyword Valid on Meaning
x:Class Root element The class that derives from the
element type
x:ClassModifier Root element, must The class visibility (public by
be used with x:Class default)
x:FieldModifier Element, must be Visibility of the field created behind
used with x:Name the element
x:Key Element that its Key in a dictionary
parent implements
IDictionary
x:Name Element The element’s name, used for a
field name for that element
Summary
XAML is mainly used to create a Windows Phone app
user interface
It declaratively allows object creation, property and
event assignment
A code-behind file will usually contain the procedural
logic
Sharing with designers is easier
Tools such as Expression Blend generate XAML that is
immediately usable
Basic Concepts
Agenda
Logical and Visual Trees
Dependency Properties
Attached Properties
Routed Events
Attached Events
Resources
Summary
Logical Tree
A tree of elements/controls making up the user interface

<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

HorizontalAlignment Margin Element/Control


Padding
Height Content

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

<StackPanel TextBlock.FontSize="20" Margin="4">


<Button HorizontalAlignment="Left" Background="Red">Left</Button>
<Button HorizontalAlignment="Center" Background="Orange">Center</
Button>
<Button HorizontalAlignment="Right" Background="Yellow">Right</Button>
<Button HorizontalAlignment="Stretch" Background="Lime">Stretch</
Button>
</StackPanel>
Content Alignment
Similar to element alignment
What to do with extra space when the content is smaller than
its control
HorizontalContentAlignment
VerticalContentAlignment

<StackPanel TextBlock.FontSize="20" Margin="4">


<Button HorizontalContentAlignment="Left" Background="Red">Left</Button>
<Button HorizontalContentAlignment="Center" Background="Orange">Center</
Button>
<Button HorizontalContentAlignment="Right" Background="Yellow">Right</
Button>
<Button HorizontalContentAlignment="Stretch" Background="Lime">Stretch</
Button>
</StackPanel>
Flow Direction
The FlowDirection property indicates the flow of layout
LeftToRight (the default)
RightToLeft
The RightToLeft setting reverses the meaning of “left” and
“right”
Layout Panels
Layout panels derive from the abstract
Windows.UI.Xaml.Controls.Panel class
Maintain a Children property of type
UIElementCollection (its ContentProperty)
Each child element can be a panel as well
Allows creation of complex and adaptive user interfaces
UWP provides several built in panels
Custom layout panels can be created as well
UWP Layout Panels
Main layout panels
Canvas
Arranges children in a 2D coordinate system
StackPanel
Arranges children in a horizontal or vertical “stack”
DockPanel
Arranges children horizontally or vertically to each other towards the edges
WrapPanel
Arranges children continuously horizontally or vertically, flowing to the next
row/column
Grid
Arranges children in a flexible grid
Example: The StackPanel
Stacks its elements in a vertical or horizontal “stack”
Orientation property
Vertical (default) or Horizontal
Alignment is ignored in the direction of stacking
The Grid
The most versatile and useful panel
Usually used as the top-level panel
Visual Studio and Expression Blend windows/user controls start this
way
Arranges its children in a multi-row and multi-column way
Their sizes and number can be manipulated in interesting ways
Somewhat similar to an HTML table
Creating a Grid
For rows
Set the RowDefinitions property
Add a RowDefinition object for each row
Set any special properties
For columns
Set the ColumnDefinitions property
Add a ColumnDefinition object for each column
Set any special properties
For each element
Set the Grid.Row and Grid.Column attached properties (default is
0, 0)
Sizing Rows and Columns
By default, all rows are of equal height and all columns are of equal
width
Can change the height of a row using the RowDefinition.Height
property
Can change the width of a column using the ColumnDefinition.Width
property
Each one of type GridLength
The unit is controlled by the GridUnitType property
Auto – size as required by content
Pixel – size is the number specified
Star – size is a weighted proportional (default)
“*”, “2*”, etc. in XAML
Spanning
A row may span more than one column and vice versa
Can be set by the Grid.RowSpan and Grid.ColumnSpan attached properties
Default for both is 1
What is a Control?
Controls are elements capable of receiving focus and handling
input
Behavior is the distinction, not looks
Many controls are available “out of the box”
Custom controls can be created
User controls that wrap one or more controls and expose higher level
properties
Custom controls that derive from an existing control and extend its
functionality
Example: Static Text
The TextBlock Element
The Text property
Font related properties
FontSize, FontFamily, etc.
TextAlignment, TextTrimming, TextDecorations
An optional collection of “inlines”
Replacement for the Text property
Inheriting from the abstract Inline class
Hyperlink, Bold, Run, Span, Underline, Italic,
LineBreak
Example: TextBlock

<TextBlock FontSize="16" Margin="4">


<Run Text="Hello" />
<Bold>
Hello
<Italic>Hello</Italic>
</Bold>
<LineBreak />
<Hyperlink>Go to my web site</Hyperlink>
<LineBreak /><LineBreak />
<Underline>This line is underlined</Underline>
<LineBreak />
<Span FontSize="20">
Hello in Bigger Font
</Span>
</TextBlock>
Other Controls
The Application Object
Every UWP application is represented by an instance of
Windows.UI.Xaml.Application
A singleton
The static property Application.Current returns that
instance
The Visual Studio wizard creates a XAML file for the
application
Useful for application level resources
Also can set the StartupUri property to indicate which window to
show on startup
Application Events (1)
Startup
Called after Application.Run is called before the main window is
shown
Can access command line arguments through the
StartupEventArgs.Args property
Can also be used to create a window explicitly (and calling
Window.Show) without relying on the StartupUri property
Exit
Application is being shutdown (for whatever reason)
Can set the exit code that is returned to the OS
Cannot cancel the shutdown process

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)

Binding Mode Meaning


OneWay The target property is updated by source property changes
TwoWay OneWay + the source property is updated by changes of the
target property
OneWayToSource Similar to OneWay, but from target to source
For source properties that are not dependency properties
OneTime Target is updated by the source the first time they are bound
Default Depends on the target property.
TwoWay for user settable properties, OneWay for everything
else.
This is the default value
Updates from the source property to the target property
happen immediately
In a TwoWay or OneWayToSource bindings, the source is
updated by the target based on the UpdateSourceTrigger
property
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"/>
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);
   }
}

var data = new List<int>();


Random r = new Random();
for(int i = 1; i < 100; i++)
   data.Add(r.Next(1, 100));
list.ItemsSource = data;
Styles
A style (instance of the Windows.UI.Xaml.Style class) is a
collection of dependency property setters (and triggers)
Usually defined as a resource
Can be applied to any element with the Style property
Any specific property changed by the element that conflicts
with the style takes precedence over the style setting
Style Example
<Page x:Class="Demo.StyleWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Style Demo" SizeToContent="WidthAndHeight">
<Window.Resources>
<Style x:Key="fancyButton">
<Setter Property="Button.Background" Value="Purple" />
<Setter Property="Button.FontSize" Value="20" />
<Setter Property="Button.FontWeight" Value="Bold" />
<Setter Property="Button.Foreground" Value="Yellow" />
<Setter Property="Button.Margin" Value="4" />
<Setter Property="Button.LayoutTransform">
<Setter.Value>
<RotateTransform Angle="15" />
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Margin="4">
<Button Content="Click Me" Style="{StaticResource fancyButton}" /
>
<Button Content="Hello" Style="{StaticResource fancyButton}" />
<Button Content="Me Fancy" Style="{StaticResource fancyButton}" /
>
</StackPanel>
</Page>
Restricting Style Usage
A style may be restricted to work on certain types using the
TargetType property
And on any derived types
In this case, the full property qualification is unnecessary

<Style x:Key="fancyButton" TargetType="{x:Type


Button}">
<Setter Property="Background" Value="Purple" />
<Setter Property="FontSize" Value="20" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Yellow" />
<Setter Property="Margin" Value="4" />
<Setter Property="LayoutTransform">
<Setter.Value>
<RotateTransform Angle="15" />
</Setter.Value>
</Setter>
</Style>
Implicit Styles
With the TargetType property the x:Key attribute may be
omitted
The style will automatically apply to all elements of the
specified type
The exact type only (not a derived type)
Elements can still override properties or use a different style,
or clear the style by setting it to null
Commands and MVVM
Agenda
Introduction to the MVVM Pattern
Commands
UWP Command Support
Implementing Commands for MVVM
Simple MVVM Framework
Summary
The MVVM Pattern
Model – View – ViewModel
Based on similar principles of Model View Controller (MVC)
and Model View Presenter (MVP)
Natural pattern for XAML based applications
Data binding is key
Enables developer-designer workflow
Increases application testability

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

public interface ICommand {


   event EventHandler CanExecuteChanged;
 
   bool CanExecute(object parameter);
   void Execute(object parameter);
}
Commands for MVVM
MVVM frameworks typically provide a basic ICommand
implementation that uses a delegate
Class typically called DelegateCommand or RelayCommand
Other implementations possible
E.g. the CompositeCommand class from PRISM that holds a list of
commands
Using commands in MVVM
Some controls expose a Command and CommandParameter
properties that can be bound to a command exposed by the
ViewModel
ButtonBase, Hyperlink and MenuItem expose these
Technically part of the ICommandSource interface
Wiring the View and the View Model
The View’s DataContext must be set to its supporting
ViewModel
Some options
The View can create an instance of the right VM (even in XAML)
The ViewModel can be injected using some dependency injection
technique (e.g. Unity or MEF)
Use some global ViewModel locator object
A Main VM can be set explicitly on the main View, and other VMs can
be exposed as properties, which will be bound by child views
Summary
Commands allow high level segregation of tasks
The MVVM pattern is common in WPF to separate logic from
UI and increase testability
Asynchronous Operations
UWP, like other UI technologies, is mostly single threaded
Synchronous operations are easy to use, but long operations
may freeze the UI (“Not responding”)
Unacceptable user experience
Asynchronous operations on the UI thread can be scheduled
using the Dispatcher object responsible for that UI thread
Accessible using Dispatcher.CurrentDispatcher static property
if on the UI thread
Or by calling DispatcherObject.Dispatcher instance property
(which is inherited by all UWP elements)
Using the Dispatcher
An operation can be scheduled using the Invoke or
BeginInvoke methods
Accept at least a delegate and an optional DispatcherPriority
.NET 4.5 adds InvokeAsync variants
DispatcherPriority enumeration
Indicates the priority to process the operation
Lower priorities can assume higher priority operations have already
completed
Default is DispatcherPriority.Normal
Updating the UI
When doing work on a background thread (either explicitly
created or using the thread pool or task), some result may
need to update UWP elements
Accessing the object directly will cause an exception
Need to marshal the required operation to the UI thread using
the Dispatcher
Call Invoke (for synchronous invocation) or BeginInvoke/
InvokeAsync (for asynchronous invocation)
Specify a priority for the update operation (usually
DispatcherPriority.Normal)
Async Patterns in .NET
Asynchronous Programming Model (APM)
Existed since .NET 1.0
Event Asynchronous Pattern (EAP)
Introduced in .NET 2.0
Task Asynchronous Pattern (TAP)
New to .NET 4.5 and C# 5.0
Asynchrony with C# 5.0
Synchronous

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;

}

Asynchronous with C# 5.0

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

You might also like