Xamarin Test Cloud Presentation by the Virtual Xamarin Users Group
Atlanta Xamarin UG - Using Mobile Services
-
Upload
john-garland -
Category
Software
-
view
88 -
download
2
Transcript of Atlanta Xamarin UG - Using Mobile Services
Consulting/Training
Putting the Cloud in Your PocketUsing Azure Mobile Services
Consulting/Training
John Garland
Microsoft MVP Windows Platform Development
Member Microsoft Azure Insider
Azure Mobile Services Advisory Board
Author Windows Store Apps Succinctly
Co-Author Programming the Windows Runtime by Example
MCPD Azure, Windows Developer, Windows Phone
MCTS Silverlight
@dotnetgator
Wintellect Principal Consultant
Consulting/Training
consulting
Wintellect helps you build better software, faster,
tackling the tough projects and solving the software
and technology questions that help you transform
your business.
Architecture, Analysis and Design
Full lifecycle software development
Debugging and Performance tuning
Database design and development
training
Wintellect's courses are written and taught by some of
the biggest and most respected names in the Microsoft
programming industry.
Learn from the best. Access the same training
Microsoft’s developers enjoy
Real world knowledge and solutions on both current
and cutting edge technologies
Flexibility in training options – onsite, virtual, on
demand
Wintellect is the only company that offers the combined value of world class consulting services along with
onsite, virtual and on-demand developer training. We help companies build better software, faster, helping you
maximize and protect your consulting and training investments through ongoing knowledge transfer.
who we are
About Wintellect
Consulting/Training
Cloud and mobile are in fact one and the same.
The mobile devices that users are flocking to are useless
without the cloud.
And the cloud…is just a theory until you have a device that's
both powerful enough to run apps that can take advantage
of it and mobile enough that those apps are with you all the
time, and working on your behalf.
Paul Thurrott
Will IT Ever Buy into “Mobile First, Cloud First”?
4/29/2014
http://j.mp/1jjFzs2
Consulting/Training
Putting “The Cloud” Into Your Apps
Platform API Strategies
Roaming Storage APIs – Device independence, but
locked into a platform
Storage Service Strategies
Storage Platform SDK’s – (eg OneDrive) Device and
platform independence
Limited to just data, no processing
“Backend as a Service” (BaaS) Strategies
Beyond just storage
Add services, logic, etc.
So where can I get some Cloud for my app?
Consulting/Training
What Is Microsoft Azure?
STORAGE
StorageBlobs StorageTables
ANALYTICS
Ingest, persist and process millions of events per second from millions of devices.
EventHubs
Ingest data from multiple disparate sources and process it into a valuable, trusted cloud-based data warehouse.
DataFactory
Process data streams in real-time to discover and react to trends.
StreamAnalytics
Mine historical data with compute power to predict future trends or behavior.
MachineLearning
Provision and integrate big data easily with tools including Microsoft Office. Based on Apache Hadoop.
HDInsightRedisCache
Make applications scale and be more responsive under load by keeping data closer to application logic.
Store and retrieve millions of JSON objects from a highly scalable, NoSQL document database.
DocumentDB
Seamlessly extend on-premises primary storage, backup, and disaster recovery with no end user or application changes.
StorSimple
Manage relational data with built-in high availability.
SQLDatabase
Set up a \\server\share in the cloud supporting the SMB 2.1 protocol. Access it from your cloud applications.
Files
Save bandwidth costs and ship an encrypted hard drive to Microsoft to transfer data to or from blob storage.
Import/Export
Store data in this schema-less, NoSQL key/attribute store. Access using REST or OData protocols.
Store and retrieve unstructured binary data, up to 500 terabytes per account. Access via REST protocol.
COMPUTE DATAWEBNETWORKING
APIManagement
MOBILE
Run large, scaled-out parallel and HPC workloads. Cloud-enable applications to offload compute jobs into the cloud.
Batch
Deploy Windows client apps in the cloud, run them remotely, and access them from any device.
RemoteApp
Create and scale internet-facing web roles and worker roles that perform background tasks.
CloudServices
Get full control over a server in the cloud, and maintain it as your business requires.
VirtualMachines
Provision and manage VPNs in Azure and securely link to your on-premises IT infrastructure.
VirtualNetwork
Connect on-premise and cloud datacenters directly through dedicated, non-internet lines.
ExpressRoute
Traffic Manager
Load-balance incoming global traffic across multiple services running in multiple datacenters.
Get started with web apps for free. Scale as you go. Build using a range of tools and languages.
Websites
Add backend capabilities to mobile apps, with native client support on most device platforms.
MobileServices
Publish APIs to developers, partners and employees securely and at scale.
Deliver millions of cross-platform push notifications from any application backend, on-premises or in the cloud.
NotificationHubs
Provide search in your website or application without having to set up or manage your own search index.
Search
Catalog of Services
Azure is an open and flexible cloud platform that enables you to quickly build, deploy, and manage applications
across a global network of Microsoft-managed datacenters.
You can build applications using any language, tool, or framework. And you can integrate your public cloud
applications with your existing IT environment.
Consulting/Training
What is Azure Mobile Services?
Worry less about data and authentication, and focus on your app.
SCRIPTS
TableSchedules
Custom API
SOURCE CONTROL
Windows Phone
iOS
Android
SQL DB Table Blob Mongo DB
STORE DATA IN THE CLOUD
USER AUTHENTICATION
PUSH NOTIFICATIONS
Facebook Twitter Microsoft Google
GCMAPNS
Active Directory
Notification Hubs
WNS & MPNS
Windows Store
iOS
Android
HTML 5/JS
:-)
LOAD BALANCER
Baidu Amazon Kindle
Consulting/Training
Xamarin – C# Everywhere
Azure Mobile Services
C# Implementation
Server
Client
Azure Mobile Service Client Libraries (C#)
Consulting/Training
Getting Started with Azure
Introducing Mobile Services
Data Storage
Server-Side Logic
Authentication & Authorization
Real-Time Communication with SignalR
Prices & Tiers
Agenda
Consulting/Training
Visit the Azure Home Page
http://azure.microsoft.com
Get an Azure Subscription
Trials
Education, Startup Discounts available
MSDN and MS-Partner Benefits
Download the Azure SDK & Visual Studio Tools
Can I do this from a Mac / can I do it from Xamarin Studio
Not really…you are working with a VS project
The Node.js version of Mobile Services is fair game for using non-VS tooling
Getting Started with Azure
Consulting/Training
https://portal.azure.com/https://manage.windowsazure.com
Azure – A Tale of 2 Management Portals
Does Not Yet Support Mobile Services
Consulting/Training
A factory for creating REST APIs that can access several back-end services:
Provisioning and Management of Storage
Server-Side Business Logic with Source Control Integration
Authentication & Authorization
Push Notification Integration
Scheduled Script Execution
The Two Parts of Azure Mobile Services
Client libraries
Simplify using the REST APIs provided by the server
Client-side tooling (WAB, Offline Data Sync with SQLite)
Source code for the client libraries is available on GitHub:
http://github.com/WindowsAzure/azure-mobile-services
Consulting/Training
Getting Started with Azure Mobile Services Projects & the Azure Portal
Consulting/Training
Out of the box support for SQL Azure, Azure Tables, Mongo DB
For SQL Azure
Access via EF6 Code-First
Automapper support is included to provide DB Entity to DTO Conversions
Use DB Migrations for schema updates
3 Steps: Data Model, Data Context, Data Controller
Data is exposed as “Tables”
Data Storage
Consulting/Training
Data Model
public class {Model Class Name} : EntityData
{
public String SomeValue { get; set; }
etc…
}
Data Context
public class {Context Class Name} : DbContext
{
public {ctor} : base(connection string name) { }
public DbSet<{Model Class Name}> SomeItems { get; set; }
etc…
}
Working with SQL Server Data (1 of 2)
Id (string), Version (byte[])
CreatedAt, UpdatedAt, Deleted
Normally “MS_TableConnectionString”
Must match name in portal config
Consulting/Training
Data Controller
public class {Controller Class Name} : TableController<{Model Class Name}>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
var context = new {Context Class Name}();
DomainManager = new EntityDomainManager<TodoItem>(context, Request, Services);
}
Controller Methods:
GetAllItems(), GetItem(id), PatchItem(id, Delta<> patch), PostItem(item), DeleteItem(id)
}
Working with SQL Server Data (2 of 2)
Consulting/Training
Working with Storage on the Server
Consulting/Training
With the .NET client library, apps can either use strongly typed data objects or dynamic JSON objects
With strongly-typed data, object/table and property/column names can be aliased
Using the DataTable attribute or the JsonProperty attribute
Table operations include
Query(where, skip/take, orderby/thenby)
Lookup (find by id)
Insert
Update
Delete
Consuming Data Tables (.NET apps)
Consulting/Training
private MobileServiceClient ms = new MobileServiceClient(
"https://{Site Name}.azure-mobile.net/",
“{Application Key}");
[DataTable(“{Table Name}"]
private class {Table or Custom Type Name}
{
public String Id { get; set; }
[JsonProperty(PropertyName=“{column name}")]public String OtherData { get; set; }
etc…
}
IMobileServiceTable<{DataType}> table = ms.GetTable<{DataType}>();
Interacting with Data Tables (.NET apps)
Optional configuration
Optional configuration
Optional value
Consulting/Training
Query
IMobileServiceTableQuery<{DataType}>query = table.CreateQuery();
Fluent Operations – return IMobileTableServiceQuery<T>:
Where, OrderBy/OrderByDescending/ThenBy/ThenByDescending,Skip/Take, IncludeTotalCount, WithParameters
Execution Operations – return results:
ToEnumerableAsync/ToListAsync (return all results)
ToCollectionAsync/ToIncrementalLoadingCollection(Win81/WP81) (support pagination/incremental loading)
var values = await query.Where(x => x.Field == value).ToCollectionAsync();
* Note – While IMobileServiceTable<T> includes several query methods, it simply delegates from table.{operation} to table.CreateQuery().{operation}
Table Query Operations (.NET apps)
Consulting/Training
Lookup by Id
var item = await table.LookupAsync(id);
Insert, Update, Delete
await table.InsertAsync(newItem);
await table.UpdateAsync(item);
await table.DeleteAsync(item);
Table Operations (.NET apps)
Note – after insert, the Id
property value is updated
Consulting/Training
// Uses JSON.NET
var entry = new JObject {{“FieldOne”, value1},{“FieldTwo”, value2}
};
var returnedItem = await ms.GetTable(“TableName”).InsertAsync(entry);
var addedItemId = ((JObject)returnedItem)["id"].Value<Int32>();
Just JSON Also Works (.NET apps)
Consulting/Training
Working with Storage from the Client
Consulting/Training
3 Execution Models for Server Code
Table Controller Methods (CRUD)
Custom API REST Endpoints
Scheduler Jobs
Services property provides access to Log, Push, Settings, Properties
Functionality can be extended with NuGet or other Assembly
references
Server-Side Business Logic
Consulting/Training
Server-Side Business Logic
Consulting/Training
Authentication & Authorization
Out of box support
Microsoft Account, Twitter, Google, Facebook, Azure Active Directory
“Secret Values” stored on the server in the Portal, behind the firewall
Custom Authentication Extensibility
Authentication Flows
Server-Flow: Server (Mobile Services) manages the authentication process
Client-Flow: Client authenticates on its own, passes token to server
Consulting/Training
[AuthorizeLevel(AuthorizationLevel.Application)]
public class TodoItemController : TableController<TodoItem>
{
[AuthorizeLevel(AuthorizationLevel.User)]
public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
{
var user = (ServiceUser)User;
item.UserId = user.Id;
AuthN – Server Side
Controlled with AuthorizeLevel attribute
Can be scoped to Controller class or individual methods
Levels: Anonymous, Application, User, Administrator
Access authenticated user through (ServiceUser)User property
Consulting/Training
Server Flow
var accountType = MobileServiceAuthenticationProvider.MicrosoftAccount;
var user = await App.MobileService.LoginAsync({Account Type or Name});
var userId = user.UserId;
AuthN – Client Side (.NET)
Provider-specific ID value Account Type (MobileServiceAuthenticationProvider)
MicrosoftAccount,
Twitter,
Facebook,
Google,
WindowsAzureActiveDirectory
Name matches a custom authentication provider name
Client Flow
var token = { Use auth provider supplied API to retrieve an Auth token }
var user = await App.MobileService.LoginAsync({Account Type or Name}, token);
Consulting/Training
Using Authentication & Authorization
Consulting/Training
Library to simplify adding real-time communication over HTTP to applications
Uses WebSockets when available, falls back to other techniques when it isn’t.
More information:
http://www.asp.net/signalr
http://signalr.net/
In Mobile Services
Access Control – Same AuthorizeLevel on hub methods, or use config options’ SetRealtimeAuthorization to apply to all methods
Scaling – With Basic or Standard tiers (support scale-out), Azure Service Bus is automatically wired up as the backplane for syncing the service instances
SignalR
Consulting/Training
Add the NuGet Package
install-package Microsoft.AspNet.SignalR
Initialize SignalR
SignalRExtensionConfig.Initialize();
Sending Messages
var hubContext = Services.GetRealtime<SettingsHub>();
hubContext.Clients.All.testFunc(param1, param2);
hubContext.Clients.{filter}.{call}({arguments});
Using SignalR on the Server
All, Caller, Others, Client(connectionId),
AllExcept(connectionIdList), Group(Name),
OthersInGroup(groupName), User
Dynamic, matches client-side
Consulting/Training
Add the NuGet Package
install-package Microsoft.AspNet.SignalR.Client
Create a Connection, Generate a Proxy, and Start the Connection
var hubConnection = new HubConnection({Uri});
var proxy = hubConnection.CreateHubProxy({HubName});
await hubConnection.Start();
Receiving Messages
connection.On<type>(“message-name”, (type) =>{…code…})
Sending Messages
proxy.Invoke(“method-name”, “param”)
var result = await proxy.Invoke<{resultType}>(“method-name”, “param”)
SignalR on the Client
Type is optional, if server is
not sending parameters
Consulting/Training
SignalR
Consulting/Training
AuthN
Client-Flow Authentication
Custom Scopes
Custom Authentication Provider
Other
Notification Hub Templates
Resource Broker for Azure Storage Access
Integration With Azure API Management (Apiphany)
Key Features
Push Notification with Notification Hubs
Offline Sync in the Client
Data
Support for Hybrid Connections
Integration with SQL Azure Auditing
Using Mongo, Azure Tables
Using Custom Data Store
Other Topics
Consulting/Training
Pricing and Scaling Options
Free Instance Basic Instance Standard Instance
Price Free (up to 10 services/month) $14.99/unit/month $139.99/unit/month
API Calls 500K/mo (prorated daily) 1.5M/unit/month (pr. daily) 15M/unit/month (pr. daily)
Active Devices 500 devices/day Unlimited
Scale 1 unit (no AutoScale) Up to 6 units Unlimited units
Notifications Free Tier included (up to 1M) Basic Tier Incl (up to 10M) Standard Tier Incl (up to 10M)
Scheduled Jobs 1 scheduled job
1 execution/hour
Up to 10 scheduled jobs
50K job executions
Up to 10 scheduled jobs
500K job executions
Other 60 CPU minutes/day
165 MB outbound data/day
SQL Database 1 20 MB database (free for 12 months) can be created per subscription, pay for other DB tiers
Dev/Test Production Deployment
Consulting/Training
Pricing and Scaling Options – Notification Hubs
Free Instance Basic Instance Standard Instance
Price Free
for 1 million pushes
$10 base charge / month
for 10 million pushes
+ $1 for 10M-100M
+ $1 for 100M+
$200 base charge / month
for 10 million pushes
+ $10 for 10M-100M
+2.50 for 100M+
Broadcast size Up to 3,000 tags, up to 10,000 devices per tag Unlimited devices & tags
Active Devices Unlimited
Other Queryable Audience
Scheduled Push
Telemetry
Bulk Import
Multi-Tenancy
Consulting/Training
Code Samples:
Windows:
http://j.mp/MobileServicesWindowsStoreSamples
Windows Phone:
http://j.mp/MobileServicesWindowsPhoneSamples
iOS:
http://j.mp/MobileServicesIOSSamples
Android:
http://j.mp/MobileServicesAndroidSamples
Videos:
Channel 9 mini-videos:http://j.mp/MobileServicesChannel9Series (38)
Build 2014: http://j.mp/MobileServicesBuild2014 (3)
TechEd NA: http://j.mp/MobileServicesTENA2014 (3)
Documentation:
Tutorials / Resources: http://azure.microsoft.com/en-us/develop/mobile/
Team Blog(s):
http://blogs.msdn.com/b/azuremobile/ (prior to 7/8/2014)
http://azure.microsoft.com/blog/
Resources
Consulting/Training
Thank You