Devices + Services: Near Realtime Sensor Data with Windows Azure Mobile Services, .NET MicroFramework, Pusher and ASP .NET MVC

It’s no surprise to people around me that I have a strong desire to code more, so I did just that on a Saturday several weeks back and here is what I built – a new devices + services scenario using a Gadgeteer, the .NET MicroFramework, Windows Azure Mobile Services and Pusher and Windows Azure Web Sites.

Device1

Lets build this:

WP_20130213_003

and get some live graphs that look like this – note up to you to do some better styling :)

graphs2 – see it live here

The idea I set out with was to open up the power (and ease) of Windows Azure Mobile Services to embedded devices that can run .NET MicroFramework.  The scenario I come up with was to capture some sensor data, insert it into a Mobile Service to store the data for historical purposes and also provide a near real time stream of data for clients such as your web browser using Pusher one of our Windows Azure Store Partners.

Capturing Sensor Data

For this scenario I am using the GHI Gadgeteer FEZ Spider and I have already installed all the pre-req software from GHI   An embedded device that runs the .NET MicroFramework and has a bunch of plug and play sensors for rapid prototyping.  To collect the sensor data is quite straight forward

use the designer to wire up your sensors

GadgeteerDesigner

The following code block will show how to open the network and capture sensor data in this case light, humidity and temperature – is quite straight forward and resides within Program.cs.

With that we have now captured our sensor data which is good, but to be useful to me I wanted to store this data off the device. To do this I decided to use Windows Azure Mobile Services

Storing the Sensor Data in Mobile Services Ok the first thing that you will need to do is Create a Mobile Service. Within the Windows Azure Portal Click New+  

plus-new

Select Compute, Mobile Service, Create

Create

Provide a subdomain name for your Mobile Service. This will be the endpoint that your device writes sensor data to and complete the wizard

createMobileService

Once your Mobile Service is provisioned.  Click on it and select the Data Tab and click Add a Table AddATable

Call this table SensorReading and save

SensorReading

Great, with that done we now have a Windows Azure Mobile Service ready to receive our data from our embedded device.  Interestingly Windows Azure Mobile Services already has client SDKs for Windows Store, Windows Phone and iOS apps.  If your an Android dev support for Android coming soon – giggidy. 

All of these client SDKs consume the REST API that Mobile Services provides for you out of the box.  One of the powerful things that the client SDKs offer is a really simple client API for consuming these services for things like data storage and Auth. 

My goal was to provide something that gives a similar experience to .NET MicroFramework devs because hey if you’re already writing software for embedded devices which is hard enough why shouldn’t you get an easy backend too? I invested a Saturday afternoon on this and provided a quick v-slice for the Insert operation.  To do this I took the Windows Phone Client SDK for Mobile Services and started porting it to .NET MicroFramework.  Man I must say I feel for you .NET MicroFramework devs:

  • no<Generics>
  • no LINQ
  • no JSON Serialization
  • limited Reflection capability – where did the GetProperties method go in .NET MF, I noticed PropertyInfo was there but couldn’t actually find GetProperties?

It was like coding back in the dark ages .NET 1.1 ah yes I remember those days. Quite  a wakeup call of how far we have really come!  So needless to say the Saturday afternoon was longer and not as productive as expected, sort of typical right?  Anyhow I got out a partial port that provides Insert functionality and a quick and pretty dirty JSON Serializer.  So here is what it looks like to use it to insert data to your Mobile Service. First we’ll need to add a reference to the (unofficial) Microsoft.Azure.Zumo.MicroFramework assembly. You can find the class library for this in the Where’s teh codez section towards the end

References

Now create a class SensorReading.cs, this will be the entity you will insert in your Mobile Service

To interact with our mobile service lets now create a new instance MobileServicesClient in your Program.cs

One thing you will note here is that I have not looked into how https is handled in the .NET MF so I am just using the http protocol for writing up to the Mobile Service I still need to investigate support for https on .NET MF. Now lets update temperatureHumidity_MeasurementComplete to create a new sensor reading and store insert it into your Windows Azure Mobile Service (backed by a Windows Azure SQL Database)

That’s it pretty easy right! You’ll note from an API consumer perspective that its pretty close to the experience you get for the Win Store and WP client SDKs minus the fact that I didn’t write a JSON Deserializer yet so I am not currently rehydrating the entity that was passed to the Mobile Service with the updated Id or updated properties…

So now that I had my sensor readings being stored in Windows Azure Mobile Services I wanted to look at how I could visualize this data.

Sending the sensor data to listening clients using Pusher

This is where things get pretty sweet. I wanted to visualize my sensor data in a graph as it arrived in my Mobile Service. Recently we announced a new Windows Azure Store partner – Pusher a  WebSocket Powered Realtime Messaging Service.  Within the Windows Azure Store you can quickly provision a Pusher account and utilize it from Mobile Services within minutes as follows.

Press New+

plus-new

Select Store

NewStore

Select the Pusher add-on

StorePusher

Walk through the remainder of the Wizard to select your plan and get your keys

PusherPlan

Note: if the Windows Azure Store is currently not available in your region you can sign up directly on Pusher.com

Next in the Windows Azure Portal select your SensorReading table and click the script tab and set the dropdown to Insert. This will allow us to write code, called Server Scripts, that will be executed every time our Gadgeteer inserts data into our SensorReading table in Mobile Service.

insertscript

Next we replace the insert code of our script to do two things save the data to our database and then use Pusher subscription to send our sensor data as it is received to all listening clients.

 

Graphing the data received via Pusher in a web client running on Windows Azure Web Sites

So now we had our sensor data collected, inserted and stored in Mobile Services and then pushed using pusher to any listening clients.  What I wanted was a web client to visualize the data in a graph as it arrived. You can learn how to create a free Windows Azure Website using ASP.NET MVC and deploy it to Windows Azure here – http://www.windowsazure.com/en-us/develop/net/tutorials/get-started/

The following code shows how you can write a quick, not so pretty code+UI wise,  graph that will receive the sensor data live via Pusher and update the graph.  To do this I am using jqplot and the Pusher JavaScript library. First add your script references to _Layout.cshtml

Then add your jquery.jqplot.min.css to your /Content folder. Next we need to Update our Home/Index.cshtml view to listen/bind to our Pusher Channel and then redraw our jqplot graph as data is pushed directly from Pusher.

If you read through the code you will see pretty clearly that the Pusher implementation is 3 lines of code only – to me this is extremely cool. Itty bitty amount of code, phenomenal cosmic power!

So that’s it now we have live graphs on our website, you can checkout a running version of this code and it live graphs that I deployed to a Windows Azure Web Site here – http://microframework.azurewebsites.net

How much does it cost

Everything that I did here can be done for free with Windows Azure Windows Azure Free Trial and/or the great free tier offerings for Windows Azure Web Sites, Windows Azure Mobile Services and Pusher.

Where’s teh codez?

This is unofficial, is not supported – I did it in my free time and it Works on my machine! :)  disclaimers all being said I really hope that this does open up a lot of doors for you for building out a whole new range of devices + services scenarios using Windows Azure and our Store Partners You can download the .NET MF lib and sample code from this github repo

Summary

I hope this has opened the door to great new devices+services scenarios you can build out for your .NET MicroFramework solutions. With few lines of code and powerful services like Windows Azure Web Sites, Windows Azure Mobile Services and Pusher you can make working in the emerging embedded devices + services space a lot easier then it has been in the past. Please do let me know if you have built something awesome in this space on the Twitterz @cloudnick

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

Announcing the Windows Azure Boost for Imagine Cup

WinAzure_rgb_Cyan_S

Windows Azure is a suite of powerful cloud services that can help your app projects in a variety of ways. If your Imagine Cup team is thinking about exploring Windows Azure, the decision just got a lot easier thanks to the Windows Azure Boost!

At our worldwide finals next July in St. Petersburg, our first place winners who include Windows Azure in their project can earn an extra $1,000 or $3,000 for their team!

We actually have two Windows Azure Boosts. Our first boost is for those teams using Windows Azure Cloud Services, Websites, or Virtual Machines. Use any or all of those technologies and your team could win $1,000! Our second Boost is for using Windows Azure Mobile Services. Incorporate that into your project and your team could win $1,000 for it. And best of all, you can go for the double shot: if your team wins both Boosts you’ll get $3,000!

So if you’re submitting a project to the Windows Phone Challenge, for example, consider using Windows Azure Mobile Services in your project. If you’re our top winner in that challenge, your team will earn an extra thousand dollars thanks to the Windows Azure Boost. Add Windows Azure Cloud Services, Websites, or Virtual Machines and your winning team would get the double shot of $3,000!

(This is open to all competitions and challenges except the Windows Azure Challenge, since that would be redundant.)

We’re really looking forward to seeing your great projects in St. Petersburg. And if your project uses Windows Azure, your team could earn the thousand-buck boost or even the double shot for three thousand.

To get you started, here are some links to help you out:

Good luck and happy coding! Official rules for the Windows Azure Boost are here.

Nick Harris | Imagine Cup Windows Azure Challenge Captain | @cloudnick

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

Execute Scheduled Scripts with the New Windows Azure Mobile Services Scheduler

In this post I will demonstrate how you can poll twitter on a scheduled basis for tweets directed at an alias and then use this information to send a Push Notification in the form of a Tile update.  But first lets talk about What’s new for Windows Azure Mobile Services

What was Announced Today!

Today, Scott Guthrie announced  updates to Windows Azure Mobile Services which allows developers to take advantage of the cloud to build and deploy modern apps for Windows 8 and iOS.  Whether you are a developer building for the Windows Store, Windows Phone 8, iPhone, or iPad, Mobile Services provides an easy, streamlined process for backend elements like storing structured data, configuring user authentication via Windows Live, Facebook, Twitter, and Google, and incorporating push notifications.

If you are building a mobile application Windows Azure Mobile Services can help in the following ways:

  • Rapid Development: configure a straightforward and secure backend for Windows 8 and mobile applications in less than five minutes.
  • Create modern mobile app with built in support and new added capabilities:
  • (NEW)Scheduled Scripts: run a server script on a pre-set schedule or on-demand which enables several key scenarios including:
    • aggregating data from Twitter, RSS feeds, or any external web services
    • executing background code efficiently, such as process/resize images, performing complex calculations, or sending emails
    • schedule sending push notifications to customers to ensure they arrive at the right time of day
  • (NEW) Command-line support: use the Windows Azure cross platform command line tools to easily create and manage mobile services
  • (NEW) Availability in Europe: create Mobile Services in the North Europe region in addition to the US East and US West regions

Getting Started with Scheduled Scripts with the Windows Azure Mobile Services Scheduler

In this section I will demonstrate how you can poll twitter on a scheduled basis for tweets directed at an alias and then use this information to send a Push Notification in the form of a Tile update.  This is a simplified version of Yavor’s post here – if you want to see how you can filter tweets and take this a bit further jump over to Yavor’s blog and check it out.

    1. Create the scheduler job that will send push notifications to registered clients every 15 minutes with the latest Twitter updates for a particular twitter handle.
    2. Specify a name for the job and make sure the schedule frequency is set to every 15 minutes. Click the check mark to create the job.

    1. Select the created job from the job list.
    2. Select the Script tab and paste the code snippet below that both polls Twitter and then composes a push notification to update your start screens tile using push.wns.*
      function CheckFeed() {
      getUpdatesAndNotify();
      }
      var request = require('request');
      function getUpdatesAndNotify() {
      request('http://search.twitter.com/search.json?q=@cloudnick&rpp=2',
      function tweetsLoaded (error, response, body) {
      var results = JSON.parse(body).results;
      if(results){
      results.forEach(function visitResult(tweet){
      sendNotifications(tweet);
      });
      }
      });
      }
      function sendNotifications(tweet){
      var channelTable = tables.getTable('Channel');
      channelTable.read({
      success: function(channels) {
      channels.forEach(function(channel) {
      push.wns.sendTileWideSmallImageAndText04(channel.uri, {
      image1src: tweet.profile_image_url,
      text1: '@' + tweet.from_user,
      text2: tweet.text
      });
      });
      }
      });
      }
      view raw gistfile1.js hosted with ❤ by GitHub
    3. Once you paste the script into the editor, click the Save button to store the changes to the script.
    4. In Visual Studio, press F5 to build and run the application.  This will ensure your channel URI is up to date and will ensure the Default Wide tile is now on your Start screen
    5. Go back to the Windows Azure Management Portal, select the Scheduler tab of your mobile service, and then click Enable in the command bar to allow the job to run

.

  1. To test your script immediately rather than wait 15 minutes for it to be scheduled, click Run Once in the command bar.
  2. Return to the start screen and see the latest update on your application tile

Summary

In this post you learnt how you can use the Windows Azure Mobile Services Scheduler to execute scripts on a scheduled basis.  We used scheduled scripts to poll twitter every 15 minutes and send a push notification in the form of a Live Tile to our windows store apps with the latest tweets at an alias.

Here are some related resources you should checkout:

You can get started today with 10 Mobile Services for FREE

 

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

Blog Series: Sending Windows 8 Push Notifications using Windows Azure Mobile Services

Sending Windows 8 Push Notifications using Windows Azure Mobile Services

Recently we announced the preview of Windows Azure Mobile Services. In this blog series I will detail how to build a Windows Azure Mobile Service to send push notifications of varying types to your Windows 8 applications.

This series will walk through creating a push notification scenario using WNS and Windows Azure Mobile Services.

As I post each part I will update the links below and tweet as the post is available. So lets get started with Part 1 – Azure Mobile Services and Push Notifications an Overview

Part 1: Windows Azure Mobile Services and Push Notifications an Overview

What is Windows Azure Mobile Services?

Here is an info-graphic on the current Windows Azure Mobile Services stack I pulled together as part of a presentation I recently gave at TechEd.  It’s important to note that this info-graphic captures Mobile Services today and over time you will see the feature set of Mobile Services grow exponentially with subsequent releases.

 

 

 

 

 

 

 

 

 

 

The goal of Windows Azure Mobile Services is to make it incredibly easy for developers to add a cloud backend to their client apps be it a Windows 8, Windows Phone, iOS or Android application. To do this we provide a number of turn key features baked right into the Mobile Services experience. As the diagram depicts Mobile Services today provides:

  • Structured Storage
    • ability to store structured data to a SQL Database using dynamic schema without being concerned with writing underlying T-SQL.
    • If using single database apps are automatically partitioned by schema e.g AppX.Todoitem, AppY.Todoitem
    • If you want access to your data you are not locked out and can manage it in a number of ways including the Mobile Service Portal, SQL Portal, SQL Management Studio, REST API etc.
  • Server Logic
    • Service API: Mobile services automatically generates a REST API to allow you to perform CRUD operations from your client application on your structured storage
    • With Dynamic Schema (enabled by default), your Mobile Service will automatically add columns to tables as necessary to store incoming data.
    • Ability to author server side business logic directly in the portal that is executed directly within the CRUD operation pipeline
  • Auth
    • Makes it easy for your users to Authenticate against Windows Live. Other major identity providers are coming soon.
    • The REST API can be locked down using table level permissions using a simple drop down.  No complex code required.  Available permissions levels include: Everyone, Anyone with an Application Key, Only Authenticated Users, Only Scripts and Admins.  These permissions can be set individually on each table and can granularly control each CRUD operation of each table.
    • More granular control can be added using server side scripts and the user object
  • Push Notifications
    • Integrates with WNS to provide Toast, Tile and Badge Notifications.
    • WNS auth is made easy with the portal captures your WNS client secret and package SID
    • the server side script push.wns.* namespace  performs WNS auth for you and provides a clean and easy object model to compose notifications
  • Common tenants of Windows Azure Services
    • Scale
      • Compute – scale between shared and reserved mode, increase/decrease your instance count
      • Storage – ability to scale out your mobile service tenant(s) to a dedicated SQL DB. Ability to scale up your SQL DB from web through business to 150GB.
    • Diagnostics
      • View diagnostics directly in the portal including API calls, CPU time and Data Out
    • Logging
      • Console.* operations like console.log and console.error provide an easy means to debug your server side scripts.

Today we provide client libraries for Windows 8 to make consuming mobile services easy.  For more details on what client libraries (Windows 8, Windows Phone, iOS and Android) are supported at the time of reading please see: Mobile Services and Mobile Service Reference.

What are Push Notifications?

The Windows Push Notification Services (WNS) enables you to send toast, tile, badge and raw notifications from the cloud to your Windows Store applications even when your app is not running. Push notifications are ideal for scenarios when you need to target a specific user with personalized content.

The following diagram depicts the general Lifecycle of a push notifications via the Windows Azure Notification Service (WNS).  We’ll walk through the steps shortly but before doing so I thought it would be important to call out that as a developer implementing a push notification scenario all you need to do is implement those interactions in grey and the applications/services in blue.  Fortunately Mobile Services makes a great deal of this easy for you as you will see throughout the reset of this series. 

The process of sending a push notification boils down to three basic steps:

  • 1. Request a channel. Utilize the WinRT API to request a Channel Uri from WNS.  The Channel Uri will be the unique identifier you use to send notifications to your application.
  • 2. Register the channel with your Windows Azure Mobile Service.  Once you have your channel you can then store your channel and associate it with any application specific data (e.g user profiles and such) until your services decide that it’s time to send a notification to the given channel.
  • 3. Authenticate and Push Notification to WNS. To send notifications to your channel URI you are first required to Authenticate against WNS using OAuth2 to retrieve a token to be used for each subsequent notification that you push to WNS once you have this you can compose and push the notification to the channel recipient. The push.wns.* methods make this task exceptionally quick to accomplish compared to writing it all from scratch yourself.

All in all Windows Azure Mobile Services makes all these concepts and steps and incredibly simple to implement though its structured storage and push notifications features.  This series will walk through creating a push notification scenario using WNS and Windows Azure Mobile Services.

As I post each part I will update the links below and tweet as the post is available

Enjoy,

Nick