How to develop Windows 8.1 Apps with Windows Azure Mobile Services

If your just getting started developing your first Windows 8.1 application or if you are already a pro this recent session I gave down in New Zealand is worth a watch. I pulled it together when I was starting to feel a little bored of slide heavy presentations so instead I took a hands on approach and limited the deck to about 8 slides and spent the majority of the hour in Visual Studio. It was a fun session and I covered a lot of common scenarios you will encounter when building connected Windows 8.1 apps with Mobile Services including:

  • Getting started with an Azure Mobile Service backend
    • Creating your first mobile service
    • enabling Source control
    • npm install
  • Building Geospatial apps – how to implement
    • Where am I
    • Save a point of interest to your backend
    • Perform radial search of points of interest nearby
  • Auth – how to secure your applications
  • Media – how to implement
    • Media capture on the device
    • Securely uploading your media to Windows Azure Blob Storage using a Shared Access Signature
  • Notifications and Live Tiles – how to implement
    • Discussion on Push notifications verse Periodic notifications and when to choose which
    • Implement Push Notifications with the new Push Wizard in the VS 2013 tooling for Mobile Services
    • Implement Periodic notifications with Custom API

I hope you enjoy the session as much as I did, enjoy! nick

You can also watch it on Channel 9

Updated NotificationsExtensions WnsRecipe Nuget to support Windows 8.1 templates now available

A short post to let you know that I have just published the updated NotificationsExtensions WnsRecipe Nuget with support for the new notification templates that were added in Windows 8.1.

Here is a short demonstration of how to use it to send a new TileSquare310x310ImageAndText01 template with the WnsRecipe Nuget Package

Install the package using Nuget Package Manager Console. (Note you could also do this using Manage package references in solution explorer)

install-package WnsRecipe

Add using statements to the NotificationsExtensions namespace

using NotificationsExtensions;
using NotificationsExtensions.TileContent;

New up a new WnsAccessTokenProvider and provide it your credentials configured in the Windows Store app Dashboard

private WnsAccessTokenProvider _tokenProvider = new WnsAccessTokenProvider("ms-app://", "");

Use Tile Content Factory to create your tile template

var tile = TileContentFactory.CreateTileSquare310x310ImageAndText01();

tile.Image.Src = "https://nickha.blob.core.windows.net/tiles/empty310x310.png";
tile.Image.Alt = "Images";
tile.TextCaptionWrap.Text = "New Windows 8.1 Tile Template 310x310";

// Note you really should not do the line below :), 
// instead you should be setting the required content 
// through property tile.Wide310x150Content so that users
// get updates irrespective of what size tile they have pinned to Start
tile.RequireWide310x150Content = false;  

//Send the notification to the desired channel
var result = tile.Send(new Uri(channel), _tokenProvider);

and here is the output
310x310tile

Enjoy, Nick Harris

How to implement Periodic Notifications in Windows Store apps with Azure Mobile Services Custom API

I blogged previously on how to make your Push Notification implementation more efficient.  In this post I will detail an alternative to Push, that is Periodic Notifications, which is are a poll based solution for updating your live Tiles and Badge content (Note that it can’t be used for Toast or Raw). It turns out if your app scenario can deal with only receiving notifications every thirty minutes or more that this is a much easier way for you to update your tiles.  All you need to do is configure you app for periodic notifications, and point it at a service API that will return the appropriate XML template for the badge or tile update in your app whether you are using WCF, Web API or others this is quite an easy thing to achieve.  In this case I will demonstrate how you can implement this using Mobile Services.

Let’s start with the backend service by creating a Custom API.  To do this all you need to do is select the API tab in the Mobile Services portal.

MobileServices_CustomAPITab Next provide a name for your endpoint and set the permissions for get to everyone

MobileServices_CustomAPIDialog

Next define the return XML return payload for your custom API.  You can see examples of each different Tile templates here

exports.get = function(request, response) {
    // Use "request.service" to access features of your mobile service, e.g.:
    //   var tables = request.service.tables;
    //   var push = request.service.push;
 
    response.send(200, ''+
                            ''+
                                ''+
                                    ''+
                                    '@ntotten enjoying himself a little too much :)'+
                                ''+
                            ''+
                        '');
};

    Note:

  • If you are supporting multiple tile sizes you should sending the whole payload in for each of the varying tile sizes
  • This is just an example  – you really should be providing dynamic content here rather than the same tile template every time

Next configure you’re app to point at your Custom API through the package.appxmanifest

VisualStudio2013_PackageManifestPeriodicNotifications

Run your app, ensure your app is pinned to start in the right dimension for the content you are returning e.g

Windows_PinLargeTile

Pin your tile and wait for the update after app has been run once.

Windows_LargeTileUpdatedByPeriodicNotification

Job done! – the tile will be updated with the content from your site with the periodic update per your package manifest definition.

Enjoy, Nick Harris

BUILD 2013 session recap

//BUILD 2013 was an awesome event! this post is a little late (I had a bunch more events back to back right after this one and I am finally digging out :) . Although late this content is still extremely relevant if you are building Connected Mobile Apps. If your interested in building mobile apps you should checkout some of the content I contributed to build this year.

Keynote Demo of Windows Azure Mobile Services

For //BUILD 2013 I was fortunate enough to be on point for delivering the Day 2 Windows Azure Mobile Services keynote content. If you have not watched this keynote I would recommend you check it out – the Windows Azure Mobile Services Demo starts about 31mins 30 seconds in

Watch the direct from Channel9 here

Build Connected Windows 8.1 Apps with Mobile Services

Want less slides and more live action? Me too! Come join me in this session where you’ll learn how to develop XAML/C# Windows Store apps that take advantage of Mobile Services as a cloud backend. During this session we’ll leverage a number of the Windows Runtime APIs used for Geolocation, Media capture and Notifications. Following this I’ll demonstrate how you can take advantage of Mobile Services to store your geospatial data, media, send notifications and auth users of your service using popular social identity providers.

Download slides and/or watch direct from Channel9 here

Enjoy, Nick Harris

Building Mobile Apps with Windows Azure Content from BUILD 2012

//BUILD 2012 was an awesome event! this post is a little late.  Although late this content is still extremely relevant if you are building Connected Mobile Apps. Here are a couple of sessions you should watch:

Keynote Demo of Windows Azure Mobile Services
During //BUILD 2012 I was fortunate enough to be to be on point for delivering the day 2 Mobile Services keynote demo app Event Buddy.  If you have not watched this keynote demo I would recommend you check it out – the Mobile Services Demo starts about 10mins 30 seconds in


Direct Video link on Channel9.  Event Buddy is now also available as a Code Sample that you can download here.

Developing Mobile Solutions on Windows Azure – Part I

Watch Josh take a Windows Phone 8 + Windows Store application and light it up with cloud services to handle data, authentication and push notifications – right before your eyes with Windows Azure Mobile Services. Almost all demo and no slides, this session is designed to take you from zero to Mobile Services here in 60 minutes.

You can also watch this video directly on Channel 9 here.
Developing Mobile Solutions on Windows Azure – Part I

In addition to this I also presented with fellow baldy – Chris Risner.  In this session we took the output of Part I  from Josh and demonstrated how you could extend your existing applications to support common scenarios such as geo-location, media, and cloud to device messaging using services from Windows Azure.   Here a summary of the content of this presentation that I humbly grabbed directly from a prior post by Chris

  • We took pictures and uploaded them to Blob Storage.  For this we used a web service layer, running in Windows Azure Websites, to get a SAS (Shared Access Signature) which allowed us to securely upload to blob storage.
  • We then got the location of the device and used that information to geo-tag the pictures we just uploaded.
  • We added a web page to our web service which allowed a user to select a geographical area on a map and request a push notification be sent to anyone that had taken a picture inside of it (this used the Bing Maps API and Queues from Windows Azure Storage)
  • We deployed a worker role to Windows Azure Cloud Services which would check the queue and then figure out who should be notified (using Entity Framework’s geospatial support) and sent out the actual push notifications to both the Windows 8 and Windows Phone 8 clients.

Here is the direct link to watch on Channel 9 and Chris has also made the code available here
Enjoy,

Nick Harris

New Windows Azure Mobile Services Getting Started Content

This post is a cross post of my post on the official Windows Azure Blog

It’s been less than five months since we introduced the first public preview for Windows Azure Mobile Services and in this short time we have seen continual additions to the Mobile Service offering including:

  • SDKs for Windows Store, Windows Phone 8 and iOS apps
  • Auth using Microsoft Account, Facebook, Google and Twitter
  • Push Notification support via WNS, MPNS and APNS
  • Structured storage
  • Scheduler to execute tasks on a schedule e.g aggregating feeds, sending notifications, crunching data
  • Deployment in North Europe, East and West US datacenters

This post details wealth of new content we have recently released designed to help you get started with Windows Azure Mobile Services including Videos, Code Samples and Tutorials.

New Videos

We recently launched a new Windows Azure Mobile Services series to help people get started with Mobile Services.  Through this series you will learn how Mobile Services can:

  • Provide turnkey backend solutions that connect your mobile apps to the cloud within minutes
  • Store data off device and read it back into your apps
  • Add custom business logic utilizing server scripts
  • Implement user authentication in your apps using popular social identity providers such as Microsoft Account, Facebook, Twitter and Google.
  • Implement Push Notifications in your apps to keep your users up to date with your latest app content
  • Execute tasks on a schedule e.g aggregating feeds, sending notifications, crunching data etc.
  • Accelerate your mobile app development for Windows Store, Windows Phone 8 and iOS

Here are some quick links to the current videos within the series:

Scott Guthrie

Introduction to Windows Azure Mobile Services

Nick Harris

Creating your first app using the Windows Azure Mobile Services Quick Start

Nick Harris

Connecting your Windows Store app to Windows Azure Mobile Services

Nick Harris

Validate and Modify Data with Server Scripts in Windows Azure Mobile Services

Nick Harris

Getting Started with Authentication in Windows Azure Mobile Services

Nick Harris
Authenticate and Authorize users with Server Scripts in Windows Azure Mobile Services
Nick Harris
Add Push Notifications to your apps with Windows Azure Mobile Services
Nick Harris
Getting Started with the Windows Azure Mobile Services Scheduler
Josh Twist
iOS Support in Windows Azure Mobile Services
Chris Risner
Creating your first iOS app with the Windows Azure Mobile Services Quick Start

New Code Samples

In addition to the video series, we have released a number of code samples to the MSDN Code Gallery.  These samples demonstrate step-by-step how you can use the key functionality available within Windows Azure Mobile Services in your Windows Store apps.  Below is a list of the new code samples:

Geolocation sample end to end using Windows Azure Mobile Services  (New)

This sample provides an end to end location scenario with a Windows Store app using Bing Maps and a Windows Azure Mobile Services backend. It shows how to add places to the Map, store place coordinates in a Mobile Services table, and how to query for places near your location.

Enqueue and Dequeue messages with Windows Azure Mobile Services and Services Bus (New)

My Store – This sample demonstrates how you can enqueue and dequeue messages from your Windows Store apps into a Windows Azure Service Bus Queue via Windows Azure Mobile Services. This code sample builds out an ordering scenario with both a Sales and Storeroom and app.

 Capture, Store and Email app Feedback using Windows Azure Mobile Services  (New)

This sample shows how you can implement a Feedback charm option in your Windows Store application and submit the feedback to be both stored Windows Azure Mobile Services and emailed directly to you.

 

Upload File to Windows Azure Blob Storage using Windows Azure Mobile Services  (New)

This demonstrates how to store your files such as images, videos, docs or any binary data off device in the cloud using Windows Azure Blob Storage. In this example we focus on capturing and uploading images, with the same approach you can upload any binary data to Blob Storage.

 

Create a Game Leaderboard using Windows Azure Mobile Services (New)

The My Trivia sample demonstrates how you can easily add, update and view a leaderboard from your Windows Store applications using Windows Azure Mobile Services.

Event Buddy Sample – Storage, Auth and Push Notifications with Mobile Services  (New)

In this sample you will start with a disconnected Windows Store app that manages events & sessions. You will connect it to Windows Azure Mobile Service to provide structured storage, auth using Twitter or Facebook and push notifications.

 

Authenticate Microsoft Account, Facebook, Twitter and Google w/ Mobile Services (New)

This sample demonstrates how you can easily wire up your Windows Store application to require your users to Authenticate against well know social identity such as Microsoft Account, Facebook, Twitter and Google using Windows Azure Mobile Services.

 

Tile, Toast and Badge Push Notifications using Windows Azure Mobile Services (New)

This sample demonstrates how you can easily register a channel in Windows Azure Mobile Services and then send different types of push notifications such as tile, toast and badge notifications from a server side script to your client application.

 Raw Notifications using Windows Azure Mobile Services (New)

This sample demonstrates how you can easily send Raw push notifications to your Windows Store apps using Windows Azure Mobile Services.

Send Push Notifications at Periodic Interval with the Mobile Services Scheduler (New)

This sample demonstrates how you can offload work from your Windows Store app to be processed on a scheduled basis using Windows Azure Mobile Services. It shows how to create a Scheduled Script that polls a feed and send a Push Notification to update the tile with latest news.

For a full list please see the new Code Sample Page on Windows Azure

Tutorials

There are a number of great step-by-step tutorials that cover Getting Started, Data, Auth, Push Notifications, Services and Tools.  We recently added two new tutorials that demonstrate how to:

These tutorials are available for Windows Store, Windows Phone 8, and iOS apps.

I hope this new content combined with our offer of 10 FREE Mobile Services helps get you off to a flying start!  That’s all from me for now, if there is new content that you would like to see made available please feel free to reach out to me with your suggestions.

As always, please visit our forum if you have any questions and send any feedback to mobileservices@microsoft.com.

Happy Coding!

Nick Harris
@cloudnick | Blog

How to upload an Image to Windows Azure Storage using Mobile Services

This post details how to use the Windows Azure SDK for Node from Windows Azure Mobile Services to generate a Shared Access Signature (SAS) and then how to upload your Image (or any file) to Blob Storage directly from your Windows Store App using the Windows Azure Storage Client Library 2.0 for Windows Runtime (CTP)

Background

In my previous post How to Upload an Image using a Blob Storage SAS generated by Windows Azure Mobile Services I detailed:

  1. Why you should use a SAS to upload any binary data from client devices
  2. How you could generate your own SAS using Mobile Services Server Side scripts
  3. How you could use the HttpClient from a Windows Store app to upload your image using the SAS

With the recent inclusion of the Windows Azure SDK for Node in Mobile Services and the announcement of the Windows Azure Storage Client Library 2.0 for Windows Runtime (CTP) the process for performing Steps 2 and 3 are much easier.  This post will detail the updated approach.

Creating your Mobile Service

In this post I will extend the Mobile Services quick start sample. Before proceeding to the next section create a mobile service and download the quickstart as detailed in the tutorial here

Capturing the Image|Media

Our first task is to capture the media we wish to upload. To do this follow the following steps.

  • Add an AppBar to MainPage.xaml with a take photo button to allow us to capture the image
...
</Grid>
...
<Page.BottomAppBar>
<AppBar>
<Button Name="btnTakePhoto" Style="{StaticResource PhotoAppBarButtonStyle}"
Click="OnTakePhotoClick" />
</AppBar>
</Page.BottomAppBar>
...
</Page>
view raw gistfile1.cs hosted with ❤ by GitHub
  • Add the OnTakePhotoClick handler and use the CameraCaptureUI class for taking photo and video
using Windows.Media.Capture;
private async void OnTakePhotoClick(object sender, RoutedEventArgs e)
{
//Take photo or video
CameraCaptureUI cameraCapture = new CameraCaptureUI();
StorageFile media = await cameraCapture.CaptureFileAsync(CameraCaptureUIMode.PhotoOrVideo);
}
view raw gistfile1.cs hosted with ❤ by GitHub
  • Update the TodoItem class with some properties that will be required to generate the SAS
public class TodoItem
{
public int Id { get; set; }
[DataMember(Name = "text")]
public string Text { get; set; }
[DataMember(Name = "complete")]
public bool Complete { get; set; }
//Added below for blob sas generation in Mobile Services
[DataMember(Name = "containerName")]
public string ContainerName { get; set; }
[DataMember(Name = "resourceName")]
public string ResourceName { get; set; }
public string SAS { get; set; }
}
view raw gistfile1.cs hosted with ❤ by GitHub
  • Update the OnTakePhotoClick handler to insert the todoitem setting the ContainerName and resourceName for which we want a SAS generated
private async void OnTakePhotoClick(object sender, RoutedEventArgs e)
{
//Take photo or video
CameraCaptureUI cameraCapture = new CameraCaptureUI();
StorageFile media = await cameraCapture.CaptureFileAsync(CameraCaptureUIMode.PhotoOrVideo);
//add todo item to trigger insert operation which returns item.SAS
var todoItem = new TodoItem() {
ContainerName = "mypics",
ResourceName= media.Name,
Text = "NA",
};
await todoTable.InsertAsync(todoItem);
items.Add(todoItem);
//TODO: Upload image direct to blob storage using SAS
}
view raw gistfile1.cs hosted with ❤ by GitHub

Generating a Shared Access Signature (SAS) using Mobile Services server-side script

In this step we add sever-side script to generate a SAS on insert operation of the TodoItem table.

To do this perform the following steps:

  • Navigate to your Mobile Service and select the Data Tab, then click on Todoitem

  • Select Script, then the Insert drop down

  • Add the following server side script to create the containerName and generate a blob SAS for the resourceName
var azure = require('azure');
var qs = require('querystring');
function insert(item, user, request) {
var accountName = '<replace with your storage account name>';
var accountKey = '<replace with your storage account key>';
var host = accountName + '.blob.core.windows.net';
var canonicalizedResource = '/' + item.containerName + '/' + item.resourceName;
//Must be lowercase
item.containerName = item.containerName.toLowerCase();
//Create the container if it does not exist
//we will use public read access for the blobs and will use a SAS to upload
var blobService = azure.createBlobService(accountName, accountKey, host);
blobService.createContainerIfNotExists(item.containerName, {publicAccessLevel : 'blob'}, function(error){
if(!error){
// Container exists now define a policy that provides write access
// that starts immediately and expires in 5 mins
var sharedAccessPolicy = {
AccessPolicy:{
Permissions: azure.Constants.BlobConstants.SharedAccessPermissions.WRITE,
//Start: //use for start time in future, beware of server time skew
Expiry: formatDate(new Date(new Date().getTime() + 5 * 60 * 1000)) //5 minutes from now
}
};
//Generate the SAS for your BLOB
var sasQueryString = getSAS(accountName,
accountKey,
canonicalizedResource,
azure.Constants.BlobConstants.ResourceTypes.BLOB,
sharedAccessPolicy);
//full path for resource with sas
item.sas = 'https://' + host + canonicalizedResource + '?' + sasQueryString;
}
else{
console.error(error);
}
request.execute();
});
}
function getSAS(accountName, accountKey, path, resourceType, sharedAccessPolicy) {
return qs.encode(new azure.SharedAccessSignature(accountName, accountKey)
.generateSignedQueryString(path, {}, resourceType, sharedAccessPolicy));
}
function formatDate(date){
var raw = date.toJSON();
//blob service does not like milliseconds on the end of the time so strip
return raw.substr(0, raw.lastIndexOf('.')) + 'Z';
}
view raw gistfile1.js hosted with ❤ by GitHub

Using the Windows Azure Storage Client Library 2.0 for Windows Runtime (CTP) to upload the Image directly to storage using the SAS

  • Download the Storage Client libraries for Windows 8 click here.
  • Extract and add a reference to Microsoft.WindowsAzure.Storage.winmd your client project
  • Update OnTakePhotoClick handler to update the image directly to blob storage using the CloudBlockBlob,UploadFromStreamAsync and the generated todoitem.SAS
...
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
...
private async void OnTakePhotoClick(object sender, RoutedEventArgs e)
{
//Take photo or video
CameraCaptureUI cameraCapture = new CameraCaptureUI();
StorageFile media = await cameraCapture.CaptureFileAsync(CameraCaptureUIMode.PhotoOrVideo);
if (media != null)
{
//add todo item to trigger insert operation which returns item.SAS
var todoItem = new TodoItem()
{
ContainerName = "mypics",
ResourceName = media.Name,
Text = "NA",
};
await todoTable.InsertAsync(todoItem);
items.Add(todoItem);
//Upload image direct to blob storage using SAS and the Storage Client library for Windows CTP
//Get a stream of the image just taken
using (var fileStream = await media.OpenStreamForReadAsync())
{
var sasUri = new Uri(todoItem.SAS);
//Our credential for the upload is our SAS token
StorageCredentials cred = new StorageCredentials(sasUri.Query.Substring(1));
CloudBlobContainer container = new CloudBlobContainer(new Uri(string.Format("https://{0}/{1}", sasUri.Host, todoItem.ContainerName)), cred);
CloudBlockBlob blobFromSASCredential = container.GetBlockBlobReference(todoItem.ResourceName);
await blobFromSASCredential.UploadFromStreamAsync(fileStream.AsInputStream());
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

Run the application

  • Hit F5 on the application and right click with your mouse to show the app bar
  • Press the Take Photo button
  • Observe that the SAS is returned from your Mobile Service

  • Check your storage account now has a great picture of a fully polished chrome dome capable of reflecting light far better then your average mirror :)

Enjoy,
Nick