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

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

How to handle WNS Response codes and Expired Channels in your Windows Azure Mobile Service

When implementing push notification solutions for your Windows Store apps many people will implement the basic flow you typically see in a demo then consider their implementation as job done. While this works well in demos and apps that are running at a small scale with few users those that are successful will likely want to optimize their solution to be more efficient to reduce compute and storage costs. While this post is not a complete guide I am providing it to at least give you enough information to get you thinking about the right things.
A few quick up front questions you should ask yourself are:

  • Is push appropriate? Should I be using Local, Scheduled or Periodic notifications instead?
  • Do I need updates at a more granular frequency then every 30 minutes?
  • Am I sending notifications that are personalized for each recipient or am I sending a broadcast style notification with the same content to a group of users?

A typical implementation

If you figured out push is the right choice and implemented the basic flow it will normally look something like this:

 

  1. Requesting a channel
  2. using Windows.Networking.PushNotifications;
    …
    var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    
  3. Registering that channel with your cloud service
  4. var token = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null);
    string installationId = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(token.Id);
    
    var ch = new JObject();
    ch.Add("channelUri", channel.Uri);
    ch.Add("installationId", installationId);
    
    try
    {
       await App.pushdemoClient.GetTable("channels").InsertAsync(ch);
    }
    catch (Exception exception)
    {
       HandleInsertChannelException(exception);
    }
    
  5. Authenticate against WNS and sending a push notification
  6. //Note: Mobile Services handles your Auth against WNS for your, all you have to do is configure your Store app and the portal WNS credentials.
    
    function SendPush() {
        var channelTable = tables.getTable('channels');
        channelTable.read({
            success: function (channels) {
                channels.forEach(function (channel) {
                    push.wns.sendTileWideText03(channel.uri, {
                        text1: 'hello W8 world: ' + new Date().toString()
                    });
                });
            }
        });
    }
    

And for most people this is about as far as the push implementation goes. What many are not aware of is that WNS actually provides two useful pieces of information that you can use to make your push implementation more efficient – a Channel Expiry time and a WNS response that includes both notification status codes and device status codes using this information you can make your solution more efficient. Let’s take a look at the first one

Handling Expired Channels

When you request a channel from WNS it will return to you both a channel and an expiry time, typically 30 days from your request. Consider that your app over time is popular but you do have users that over time end up deciding either to not use your app for extended periods or delete it all together. Over time these channels will hit their expiry date and will no longer be of any use and there is no need to a) send notifications to these channels and b) keep these channels in your datastore. Let’s have a look at a simple implementation that will cleanup your expired channels.

Using a Scheduled Job in Mobile Services we can perform a simple clean of your channels but first we must send the Expiry to your Mobile Service. To do this you must update step 2 of the above implementation to pass up the channel expiry as a property in your JObject – you will find the channel expiration in the channel.ExpirationTime property. For my channel table I have called this Expiry.

Following that once you have created your scheduled push job at say an interval of X (I am using 15 minutes) you can then add a function that deletes the expired channels similar to the following

function cleanChannels() {
    var sql = "DELETE FROM channels WHERE Expiry < GetDate()";
    mssql.query(sql, {
        success: function (results) {
            console.log('deleting expired channels:', results)
        },
        error: function (error) {
            console.log(error);
        }
    });
}

As you can see there is no real magic here and you probably want to handle UTC dates – but in short it demonstrates the concept that the expired channels are not useful for sending notifications so delete them, flag them as deleted or anything else that keeps them out of the valid set that you will push to… moving on

Handling the WNS response codes

When you send a notification to a channel via WNS, WNS will send a response. Within this response are many useful response headers. Today i’ll just focus on X-WNS-NotificationStatus but it’s worth noting that you should also consider X-WNS-DeviceConnectionStatus – more details here

Let’s look at a typical response:

{
headers:
{ ‘x-wns-notificationstatus': ‘received’,
‘x-wns-msg-id': ‘707E20A6167E338B’,
‘x-wns-debug-trace': ‘BN1WNS1011532′ },
statusCode: 200,
channel: ‘https://bn1.notify.windows.com/?token=AgYAAACghhaYbZa4sqjJ23pWp3kGDcEOEb3JxxdeBahCINn15fc11TiG0mlTpR5heYQmEaQrgZc3TSSwoUllW9s4Lsn3eyvSn19DcrX%2bOvSOY4Bq%2bPKGWbdy3mjTmaRi2Yb1dIM%3d’
}

Of interest in this response is X-WNS-NotificationStatus which can be one of three different states:

  • received
  • dropped
  • channelthrottled

As you can probably guess if you are sending notifications when you are either throttled or dropped it is probably not a good use of your compute power and as such you should really handle channels that are not returning received status in a fitting way. Consider the following when the scheduled job runs delete any expired channels and send notifications to channels in (the status of received) OR (that are not in the status of received AND that last had a push sent over an hour ago). This can be easily achieved by tracking the X-WNS-NotificationStatus every time a notification is sent. Code follows:

function SendPush() {
    cleanChannels();
    doPush();
}

function cleanChannels() {
    var sql = "DELETE FROM channel WHERE Expiry < GetDate()";

    mssql.query(sql, {
        success: function (results) {
            console.log('deleting expired channels:', results)
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function doPush() {
    //send only to received channels OR channels that are not in the state of received that last had a push sent over an hour ago 
    var sql = "SELECT * FROM channel WHERE notificationStatus IS NULL OR notificationStatus = 'received' 
                    OR ( notificationStatus <> 'received'
                           AND CAST(GetDate() - lastSend AS float) * 24 >= 1) ";

    mssql.query(sql, {
        success: function (channels) {
            channels.forEach(function (channel) {

                push.wns.sendTileWideText03(channel.uri, {
                    text1: 'hello W8 world: ' + new Date().toString()
                }, {
                    success: function (response) {
                        handleWnsResponse(response, channel);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
        }
    });
}

// keep track of the last know X-WNS-NotificationStatus status for a channel
function handleWnsResponse(response, channel) {
    console.log(response);

    var channelTable = tables.getTable('channel');

    // http://msdn.microsoft.com/en-us/library/windows/apps/hh465435.aspx
    channel.notificationStatus = response.headers['x-wns-notificationstatus'];
    channel.lastSend = new Date();

    channelTable.update(channel);
}

That’s about it I hope this post has helped you to start thinking about how to handle your Push Notification implementation beyond the basic 101 demo push implementation

Enjoy, Nick Harris

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

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

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

 

Windows Azure at Seattle Interactive Conference

Hi All, Come join the team and I to learn about Windows Azure @

Technical Content, Technical Experts

The Cloud Experience track at SIC is for experienced developers who want to learn how to leverage the cloud for mobile, social and web app scenarios. No matter what platform or technology you choose to develop for, these sessions will provide you with a deeper understanding of cloud architecture, back end services and business models so you can scale for user demand and grow your business.

Register today using the promo code “azure 200″ and attend SIC for only $150 (a $200 savings).

Attend a full day of technical sessions and learn more about leveraging the cloud for mobile, web and social scenarios. View the list of confirmed Cloud Experience speakers. Sessions include:

  • Great Mobile Apps Make Money – Intro to Cloud Experience Track
  • Mobile + Cloud, Building Mobile Applications with Windows Azure
  • Zero to Hero: Windows Phone, Android, iOS Development in the Cloud
  • Building Web Applications with Windows Azure
  • Building Social Games on Windows Azure

Cloud Experience speakers and technical experts will be available to provide technical assistance and resources for developing, deploying and managing mobile, social and web apps in the cloud.