net backend heterogeneous data hybrid connections offline sync xamarin aad authentication visual...
TRANSCRIPT
What’s New in Mobile Services & Notification Hubs
Miranda LunaElio Damaggio
@MLunes90@ElioDamaggio
DEV-B330
AgendaMobile Services UpdatesAAD authentication.NET backend Data Access & Offline SyncHybrid ConnectionsAPI Management
Notification Hubs UpdatesMobile Push Notifications 101Notification Hubs with Mobile ServicesTargeted notifications with tagsSecure tags when pushing to usersSecure push notificationsPush-to-sync
Questions & Resources
Mobile Services
Mobile Services Investment Areas
1. Consumer-Facing Apps in Organizations2. Employee-Facing Apps in Organizations
What’s New
.NET backendHeterogeneous data Hybrid ConnectionsOffline syncXamarin
AAD AuthenticationVisual StudioAPI ManagementNotification HubsSencha
AAD Authentication
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
Make AAD users a first-class concept in Mobile Services, with push-to-user and per-user data
Active Directory Authentication Library (ADAL)
Facilitates login to AAD-protected resources
Provides single sign-on to multiple enterprise resources
Available for Windows Store, iOS, and Android
1) Client app uses ADAL to initiate login, user enters credentials which are sent to AAD
2) AAD returns an Access Token / Refresh Token pair for the mobile service to ADAL
3) The client passes the Access Token to the mobile service, exchanges for the Mobile Services token for a continued session
Basic ADAL + Mobile Services Flow
3
2
1
1) Mobile Service passes Access Token to AAD along with a requested resource URI and its Client ID / Client Secret
2) AAD sends back an Access Token / Refresh Token pair for the remote resource
3) Mobile Service talks to the remote resource on behalf of the logged-in user
Access resources on behalf of the user
1 2
3
.NET Backend
Backend for Your Employee or Consumer app in seconds Your Backend Logic via .NET Web APITurn-key Mobile Backend Capabilities
Secure data store/query/page with heterogeneous backendsAzure Active DirectorySupport occasionally connected apps
Local debuggingFlexible data modelClient SDKs
iOS, Android, Windows, WinPhone, Xamarin, PhoneGap, Sencha
Integration With Your On-Premise Enterprise Systems, O365We Manage, Run, and Monitor your backend for you
Mobile Services .NET
source
Mobile Servicescompatible WebAPIcontrollers
git
WebDeploy
Commit hook: Build project
WebsiteXDRIVE\site\wwwroot
Mobile Servicescompatible WebAPIcontrollers
Web.config
C:\...\MobileServices
Mobile Servicesruntime
Web.config
website root
load
User database:EF code-first migrationsor custom migrations
App settingsinjected here
Data Access & Offline Sync
New data model (“greenfield”)
TableController
DataManagerDTO
DTO
Mobile ServiceDevice
SQL Database
BYOD
MongoDB
Table Storage
Existing data model (“brownfield”)
TableController
DataManagerDTO
DTO
Mobile ServiceDevice
Model
AutoMapper
Azure SQL db/BYOD
ExistingTables
SystemPropertiesTable
Offline support
TableController(with optimistic concurrency)
Mobile ServiceDevice
SQL Database
BYOD
MongoDB
Table Storage
SQLite
Explicit Push/Pull
Conflict resolution
Store table operations in local data store
push changes from local data store on device to mobile servicepull changes from mobile service to local data store on the device
SQL-lite out of the box local data store defined by an interface so use whatever you’d like
Offline Support
PushAsyncpush is executed on whole context, not specific tablessupports relationships between entities on client side
PullAsynceither pull all or a subset of items from remote table pull triggers a push; ensures pull doesn’t introduce data inconsistency
PurgeAsyncClear local cache to update the data which the app no longer needspurge triggers a push; ensures info is saved to server before removing from local store
Offline Methods
Handling Offline Conflicts1.var localTable = client.GetSyncTable<TodoItem>();2.var remoteTable = client.GetTable<TodoItem>();3.await localTable.PullAsync();4. 5.var firstItem = (awaitlocalTable.Take(1).ToEnumerableAsync()).FirstOrDefault();6.var firstItemCopy = newTodoItem7.{8. Id = firstItem.Id,9. Version = firstItem.Version,10. Text = firstItem.Text,11. Complete = firstItem.Complete12.};13. 14.firstItemCopy.Text = "Modified";15.await remoteTable.UpdateAsync(firstItemCopy);16.AddToDebug("Updated the item on the server");17. 18.firstItem.Text = "Modified locally";19.await localTable.UpdateAsync(firstItem);20.AddToDebug("Updated the same item in the local table");21. 22.AddToDebug("Number of pending operations: {0}", client.SyncContext.PendingOperations);23.await client.SyncContext.PushAsync();
Hybrid Connections
Fastest way to consume on-premises resources in a Mobile Services app
without saving those assets to the cloud without changing any codewithout requiring a WCF service
Connect to any on-premises resource that uses a static TCP port
SQL Server, MySQL, Oracle, Sharepoint, HTTP Web APIs, custom web services
Create a new Hybrid Connection within BizTalk Services for free.
No prior BizTalk knowledge or skills required
Hybrid Connections
BizTalk Services Hybrid Connections
Microsoft Azure Your Enterprise
Hybrid Connections Manager
Connection string points to
My-Database: 1433
My-Database
Port: 1433
Hybrid Connection
API Management
Build & Host
Publish & Manage
Mobile Services
Web Sites
API Management
WINDOWS AZURE API
DEVELOPER PORTAL
ADMINPORTAL
PROXY
MCROSOFT AZURE
API MANAGEMENT
PUBLISHER / ADMIN
DEVELOPERS
APPS
BACKEND
Can be hosted anywhere: public
cloud or on-premises
API Management Features
ADAPTFormats, protocols, URIs, aggregation
EXPOSEDiscovery, packaging, subscriptions, docs
PROTECTAuthorization, quotas, rate limits, request validation
UNDERSTANDUsage, health, latency, activity, trends
MANAGE Lifecycle, versioning, monitoring
Notification Hubs
Push Notifications
What’s New
Kindle (ADM) supportTag ExpressionsVisual Studio integrationMobile Services integrationNew push-based pricingBulk registration mgmt. APIsXamarin
Push Notifications
Push 101Use Notification Hubs from Mobile ServicesNotification Hubs
Target notifications with tagsSecure tags when pushing to usersSecure pushPush to sync
Push 101
Mobile push is everywhere
Reservation changes, Deals, Back-officeTravel/Hospitality/Airlines
SMS replacement, Deals, Back-officeBanking/Insurance
Orders, Product UX,Back-officeDiscrete manufacturing/Auto
Prescriptions, Appointments,LOB (maintenance)Healthcare
Breaking newsNews/Media
Offers, Orders, Back-officeRetail
Push notification lifecycle
Registration at app launch1. Client app contacts Platform Notification Service, to retrieve
current channel (e.g. ChannelURIs, device tokens, registrationIds)
2. App updates handle in back-end
Sending Notification3. App back-end send notification to PNS4. PNS pushes the notification to the app on the device
Maintenance5. Delete expired handles when PNS rejects them
PlatformNotification
Service
App back-end
Challenges of push notifications
Platform dependency• Different communication protocols (e.g. HTTP vs TCP, xml vs json)• Different presentation formats and capabilities (alerts vs tiles vs toasts vs badges)
Routing• PNS’ provide a way to send a message to a device/channel• Usually notifications are targeted at users or interest groups (e.g. employees assigned to a
customer account)• App back-end has to maintain a registry associating device handles to interest groups/users
Scale• App back-end has to store handles for each device high storage and VM costs• Broadcast to millions of devices with low latency requires parallelization (DB ad VM)
Advantages of using Notification Hubs
X-plat: from any back-end to any mobile platformBackend can be on-prem or in the cloud, .NET/Node/Java/PHP/Node/anything. Support Windows Phone/Windows/iOS/Android and Kindle Fire.
No need to store device information in the app back-endNotification Hub maintains the registry of devices and the associations to users/interest groups
Routing and interest groupsTarget individual users and large interest groups using tags
Personalization and localizationKeep your back-end free of presentation concerns like localization and user preferences using templates
Broadcast at scale, multicast, unicastPush notifications to millions of devices (across platforms) with a single call
TelemetryRich telemetry available through portal or APIs
Using Notification Hubs
One-time set up1. Create a Notification Hub
Register2. The client app retrieves its current handle from the
PNS3. Client app creates (or updates) a registration on the
Notification Hub with the current handle
Send Notification4. The app back-end sends a message to the Notification
Hub5. Notification Hub pushes it to the PNS’
APNsWNS
Notification Hub
App back-end
iOS app Windows app
MPNS
GCM
ADM
MICROSOFT CONFIDENTIAL – INTERNAL ONLY
Some snippetsRegister Send
Windows / Windows Phoneawait hub.RegisterNativeAsync(channel.Uri);
iOS[hub registerNativeWithDeviceToken:deviceToken
tags:nilcompletion:^(NSError* error) { … }];
Android / Kindlehub.register(regid);
.NETvar toast = @“<notification payload>";hub.SendWindowsNativeNotificationAsync(toast);
Node / Mobile ServiceshubService.wns.sendToastText01(null, { text1: 'Hello from Node!' }, function (error) { … });
Tags
Tags as interest groups1. Client app can register with a set of tags2. Tags are simple strings (no pre-provisioning is required)3. App back-end can target all clients with the same tag
You can use tags also forMultiple type of interest groups, e.g.
Follow bands: tag “followband:Beatles”Follow users: tag “followuser:Alice”
Tag devices with a user id
Notification Hub
App back-end
Tag:”Beatles”Tag:”Wailers”
Tag:”Beatles”
MICROSOFT CONFIDENTIAL – INTERNAL ONLY
Some snippetsRegister
Windows / Windows Phoneawait hub.RegisterNativeAsync(channel.Uri, new string[] {"myTag", "myOtherTag"});
iOS[hub registerNativeWithDeviceToken:deviceToken tags:@[@"myTag", @"myOtherTag"] completion:
^(NSError* error) {…
}];
Android / Kindlehub.register(regid, "myTag“, "myOtherTag");
Tag expressions
Social “All my group except me”group:id && !user:id
Events Touchdown event is send to everybody following either teamFollowteam:A || Followteam:B || followplayer:1 || followplayer:2 …
Hours Send notifications at specific times. E.g. Tag with timezone, @12pm in Seattle send:timezone:PST && follows:thaifood
Versions & platforms Send a reminder to update to your first Android app version:version:1.0 && platform:Android
Case StudiesBing (news, finance, sports, …)
Sochi 2014
Preinstalled on windows
Millions of devices
Millions of notifications/day
Minutes to delivery
Interest groups(countries, disciplines, athletes)
Localized notifications
Million devices(iOS, Android, WP)
Million notifications
10s
3+ <2
100s
3+ 150+
Sochi 2014 Results App Localized for each user’s
language, country and time zone
Segmented and personalized push based on event type, sport, and athlete preferences
Social and current as a result of Facebook and Twitter integration, refreshed content and merchandise
Notification Hubs & Mobile Services
Powered by Notification HubsAccess broadcast at scale, push to user and interest groups, localization templates and more…
No more Channels tableSimple two steps process to push notifications, no data handling
1 Unit of Notification Hubs included for freeNode.js and .NET
New push engine for Mobile Services
From Mobile Services
Maintains Notification Hubs’ surfaceCall register to register tags from the device
Push from your scripts
push.wns.sendToastText04( null, { text1: ‘Hello!’ }, { success: function() { console.log("Sent push"); } });
MobileService.Push.RegisterNativeAsync(channel);
Secure tags for push to users
Register from your back-endWhen tags have to be secured
When devices register, they can register for any tagSometimes tags have to be secure (e.g. using ‘{userId}’ as tag)App back-end can authenticate the user before registering the device
When back-end has to modify tagsTags change as a result of:• Actions on different devices (e.g. adding a tag from the web app)• Other user’s actions (e.g. a manager adding an employee to a work group)
Tags are derived from analytics or other user data
Registering from the back-end
Identify your device1. Cannot use ChannelURIs/device tokens/…2. Keep long-living NH registration ids in device storage
Register3. First time only,
a) Request registration id from hub, andb) Store it on device storage
4. CreateOrUpdate device registration (@ every app start)
5. Back-end can verify and/or add tags (e.g. performing auth)
Notes6. Nothing is stored in the app back-end7. Do not use device SDK
(risk: multiple registrations for each device)
Notification HubApp back-
end
{id}
upsert({id}, channel, tags)
createId()
Back-end driven tag updates
Use a tag to identify user1. Back-end usually refers to users and not devices2. Register devices with a tag like ‘userid:{id}’
Back-end updates tags3. Retrieve device registration(s) by userid4. Update tags
Note5. No device information in app back-end6. Back-end only refers to users
Notification HubApp back-
end
getByTag(userid)
update(tags)
Super easy with Mobile Services (.NET)Login the user in the deviceRegister from the device
Implement registration callback to inject user tag
Push to user
await App.MobileService.GetPush().RegisterNativeAsync(channel.Uri);
public class AddAADUser : INotificationHandler{ public void Register(ApiServices services, HttpRequestContext context, NotificationRegistration registration) { registration.Tags.Add("aaduser:" + context.Principal.Identity.Name); }}
services.Push.SendAsync(msg, "aaduserid:" + context.Principal.Identity.Name);
Secure Push
Secure push & Rich push
Deliver content directly from BE1. Rich media (images, videos, html, …)2. Retrieve the content securely from BE
NotesPlatform dependentSecure push has to use a long lived auth token on app
App back-end
Notification HubDownload m
edia/msg
Push to sync(no sensitive info)
Push to Sync
Push to Sync
Updates app state1. Does not show a message to the user
Example: music app2. User changes playlist on desktop3. Back-end sends a ‘push-to-sync’ notifications to user’s
devices4. Phone receives push and starts downloading new song5. User finds the new song already on their phone!
Platform-dependentWindows/Windows Phone (only lock-screen apps / 8.1)iOS (only since iOS 7)Android/Kindle
App back-end
Notification Hub
Download new song
Push to sync
Add new song
Telemetry
Telemetry, security, and scaleTelemetry
Portal dashboard and programmatic access for all outcomes exposed by PNS’.
SecurityRole-based security available to restrict access to hub for:• Device registration management rights• Sending rights• PNS credentials rights
ScaleGuidance for very high scale depends on specific scenariosAny audience <5million devices and <5million pushes per day can use a single hub
PricingCurrent
Private Preview For unicast/1-to-1 push notifications at high volume (>300M/mo) Email [email protected] for details
Free Basic Standard
Price (/mo) Free $20/unit/mo $199/unit/mo
Active Devices 500/namespace Unlimited Unlimited
Pushes 100K/unit/mo 500K/unit/mo 5 M/unit/mo
Scaling N/A 9 units Unlimited
Azure Mobile
Microsoft is making a massive investment to provide an end-to-end story for cross-platform mobile app development and
management
Mobile ServicesNotification HubsAPI ManagementBizTalk Hybrid ConnectionsIntuneAzure AD
with more to come…
What we hope you take away…
Breakout Sessions
Related content
Find Me Later At.. . . Server, Cloud & Tools Expo Booth
5/12 1:15-2:30 DEV-B307 Announcing Hybrid Connections: Building Amazing Hybrid Web Sites and Mobile Apps in Minutes
5/12 4:45-6:00 DEV-B317 Mobile Line-of-Business Applications in Microsoft Azure
5/13 3:15-4:30 DEV-B330 What’s New in Mobile Services and Notification Hubs
5/14 1:30-2:45 DEV-B345 High-Volume, Low-Latency Mobile Push Notifications
5/14 3:15-4:30 DEV-B351 Introduction to API Management on Microsoft Azure5/15 8:30-9:45 DEV-B382 Microsoft Azure API Management Master Class5/15 1:00-2:15 DEV-B343 Building Microsoft Azure Mobile Services w/ Visual
Studio
Mobile Dev Center
Track resources
Notification Hubs Dev Center
Channel 9 Videos
Azure Fridays
azure.microsoft.com/mobile
azure.microsoft.com/documentation/services/notification-hubs/
channel9.msdn.com/Series/Windows-Azure-Mobile-Services
channel9.msdn.com/Shows/Azure-Friday
Visit the Developer Platform & Tools BoothHaving a friend buy your coffee?Yea, it’s kind of like that.
MSDN Subscribers get up to $150/mo in Azure credits.
Stop by the Developer Platform and Tools booth and visit the MSDN Subscriptions station to activate your benefits and receive a gift!
http://aka.ms/msdn_teched
3 Steps to New Gear! With Application Insights
1. Create a Visual Studio Online account http://visualstudio.com
2. Install Application Insights Tools for Visual Studio Online http://aka.ms/aivsix
3. Come to our booth for a t-shirt and a chance to win!
VSIP QR Tag Contests Visit our booth to join the hunt for cool prizes!
ResourcesMicrosoft Engineering Stories
How Microsoft Builds Softwarehttp://aka.ms/EngineeringStories
Visual Studio Industry Partner Program
Meet Our New Visual Studio Online Partners or Join Now.http://vsipprogram.com
Visual Studio | Integrate
Create Your Own Dev Environmenthttp://integrate.visualstudio.com
Development tools & services for teams of all sizeshttp://www.visualstudio.com
Complete an evaluation and enter to win!
Evaluate this session
Scan this QR code to evaluate this session.
© 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.