WAMS

Getting productive with WAMS: How to handle erroneous push channels

WAMS

As I wrote already in my former article ‘Getting productive with WAMS- about the mpns object (push data to the user’s Windows Phone)’, I needed to add some more detailed error handling to the mpns object on my Mobile Service.

There are two error codes that appear frequently: 404 (Not Found) and 412 (Precondition Failed).

The 404 error code

happens when the push channel gets invalid. Reasons for that can be uninstall or reinstall of the app, or also a hard reset of the users device. In this case, we are following the recommendation of Microsoft to stop sending push notifications via this channel.

There might be several ways, but I prefer to work with SQL queries.  This is how I delete those channels within error: function(error):

if (error.statusCode === 404)
{
 var sqlDelInvalidChannel = "DELETE from pushChannel WHERE id = " + channel.id;
 mssql.query(sqlDelInvalidChannel, {
 success: function(){
	console.log("deleted invalid push channel with id: " + channel.id);
	},
	error: function(err)
	 {
           console.log("there was a problem deleting push channel with id: " + channel.id + ", " + err)
         }
});

As you can see, this is a very simple approach to get rid of those invalid channels.

The 412 error code

needs some more advanced handling. Microsoft recommends to send the push notification as normal, but the code recommends a delay of 61 minutes to resend. Also, with some research on the web, I found out that often the 412 will turn into a 404 after those 61 minutes (at least I found a lot of developers stating this). This is why I went with a different approach. I am going to wait those 61 minutes, and do not send a push notification to those devices.

For that, I do a simple trick. I am saving the time the error shows up in my push channel table, as well as the  time after those 61 minutes. On top, I use a Boolean to determine if the channel is in the delay phase.

Here is the simple code for that, again within error: function(error):

if (error.statusCode === 412)
{
	var t = new Date();
	var tnow = t.getTime();
	var tnow61 = tnow + 3660000;

	var sqlSave412TimeStamp = "UPDATE pushChannel SET Found412Time=" +  tnow + ", EndOf412Hour=" + tnow61 + ", IsPushDelayed = 'true' WHERE id=" + channel.id;

	mssql.query(sqlSave412TimeStamp);
}

Now if my script runs the next time over this push channel, I need to check if the push channel is within the delay phase. Here’s the code:

if (channel.IsPushDelayed === true)
{
	var t = new Date();
	var tnow = t.getTime();
	var EndofHour = channel.EndOf412Hour;
	var tdelay = EndofHour - tnow;

	if (tdelay > 0)
	{
	 console.log("push delivery on id: " + channel.id + " is delayed for: " + (Math.floor(tdelay/1000/60)) + " minutes");
	}
	else if (tdelay < 0)
	{
	 var sqlDelete412TimeStamp = "UPDATE pushChannel SET Found412Time=0 , EndOf412Hour= 0, IsPushDelayed = 'false' WHERE id=" + channel.id;
	 mssql.query(sqlDelete412TimeStamp);
	}
}

As you can see, I am checking my Boolean that I added before. If it is still true, I am writing a log entry. If the time has passed already, I am resetting those time values to 0 respective the Boolean to false.

The script will now check if the push channel is still a 412 or turned in to a 404, and so everything starts over again.

Other error codes

There might be other error codes as well. I did not see any other than those two in my logs, but for the case there would be another, I simply added this code to report them:

else
{
 console.error("error in Toast Push Channel: " + channel.twitterScreenName, channel.id, error)
}

This way, you can easily handle push channel errors in your Mobile Service.

If you have other error codes in your logs, check this list from Microsoft to determine what you should do: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff941100(v=vs.105).aspx#BKMK_PushNotificationServiceResponseCodes

Note: there might be better ways to handle those errors. If you are using such a way, feel free to leave a comment with your approach.

Otherwise, I hope this post will be helpful for some of you.

Happy coding!

Posted by msicc in Azure, Dev Stories, 0 comments

Getting productive with WAMS: about the mpns object (push data to the user’s Windows Phone)

WAMS

When it comes to Mobile Services, there are a lot of things you can do with the user’s data. One of them is to update the Live Tiles of their apps as well as send them Toast Notifications. To understand how the mpns (Microsoft Push Notification Service) is working, please see the image below and read this article on MSDN: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402558(v=vs.105).aspx

mpns graph

Windows Azure has a pretty basic example to get the Live Tiles updated: http://www.windowsazure.com/en-us/develop/mobile/tutorials/push-notifications-to-users-wp8/. However, this example sends the data from the app to Azure and directly back to the user’s device. It is a good start if you want to understand how it works, but it does not reflect the most common scenario: the server is fetching data with the app closed on the users device.

The most important part: getting a valid push channel from the Push Client Service

Now that we know how the push notification service works, we need our Windows Phone app to acquire a valid push channel. This is done by a few lines of code in App.xaml.cs. First, we need a globally declared push channel:

public static HttpNotificationChannel pushTileChannel { get; set; }

With this global variable we are now able to get a valid push channel into our app and to our Mobile Service:

public static void AcquirePushChannel()
        {
                  pushTileChannel = HttpNotificationChannel.Find("msicc-test");

                if (pushTileChannel == null)
                {
                    pushTileChannel = new HttpNotificationChannel("msicc-test");

                    pushTileChannel.Open();

       //this binds the push notification to your live tile       
       pushTileChannel.BindToShellTile();

       //this binds the push notification to toasts
       pushTileChannel.BindToShellToast();

 }        

                IMobileServiceTable<pushChannel> pushChannelTable = App.MobileService.GetTable<pushChannel>();
                var channel = new pushChannel { Uri = pushTileChannel.ChannelUri.ToString() };
                pushChannelTable.InsertAsync(channel);
           }

The Find(“desiredNameOfChannel”) method creates or finds a channel exclusive to your app and should be the same for all of your users. The Open() method finally opens the connection from your app to the Push Client Service. To automatically receive the updates for Tiles and Toast, we use the BindToShellTile() and BindToShellToast() methods.

Important for images:

You need to allow the url(s) the images can be from. To this, you need to add the desired uri in the BindToShellTile() method. If you have more than one uri the images come from, just create a Collection of Uri and add them to the BindToShellTile() method  overload. Please note that only the top level domain needs to be allowed (specifying folders is not supported).

public static Collection<Uri> allowedDomains = 
            new Collection<Uri> { 
                                                new Uri("https://yourmobileservice.azure-mobile.net"), 
                                                new Uri("https://yourseconduri.com/") 
                                              };

pushTileChannel.BindToShellTile(allowedDomains);

But that’s not all. We need to add the push channel uri  also to our Windows Azure table to update the users data. This what the last three lines of codes are for. I highly recommend to separate the push channel table from your user data table, to be able to operate easily on this table. In order to avoid duplicate channels (which can be very annoying for users and yourself), we should update our server side data script:

function insert(item, user, request) {

   var channelTable = tables.getTable('pushChannel');
        channelTable
            .where({ uri: item.uri })
            .read({ success: insertChannelIfNotFound });
        function insertChannelIfNotFound(existingChannels) {
            if (existingChannels.length > 0) {
                request.respond(200, existingChannels[0]);
            } else {
                request.execute();
            }
        }
}

This way, you are all set up for updating your app’s Live Tile and for Toast Notifications. But until now, our Mobile Service does not send any data to our app.

How to update Live Tiles and send Toast Notifications from Mobile Services

Once our server side code has fetched all data, we certainly need to update our user’s Live Tiles or even send Toast Notifications. We are able to send the following types of Tiles and Notifications:

The FlipTile is the coolest of all and has the most options you can use. That’s why I choose it over the ‘normal’ Tile. To get the data out to our users, we are using this code:

//call the push channel table

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

//send toast and Tile:

channelTable
    .where({user:userid})
    .read({
        success: function(channels){
            channels.forEach(function(channel) 
                {
                    push.mpns.sendToast(channel.uri, {
                        text1: ToastText1,
                        text2: ToastText2
                        }, {
                    success:function(pushResponse) {
                        console.log("Sent toast: ", channel.id, pushResponse);
                    },
                    error: function (error){
                        console.error("error in Toast Push Channel: " +  channel.id, error)
                    }
                });
                push.mpns.sendFlipTile(channel.uri, {
                     backgroundImage: backgroundImage,
                     backTitle: backTitle,
                     backContent: BackContent,
                     smallBackgroundImage: SmallBackgroundImage,
                     wideBackgroundImage: WideBackgroundImage,
                     wideBackContent:  WideBackContent,

                }, {
                    success:function(pushResponse) {
                        console.log("Sent tile:" ,  channel.id, pushResponse);
                    },
                    error: function (error){
                        console.error("error in Push Channel: "  channel.id, error)
                    }
                });
            });
        }
    });

Like you can  see, we are using quite a few fields in the mpns object payload. You can click on the types above to see which fields are supported on each type.

Images that you send to your users are sent need to be a valid url to the image. The maximum size is 80 KB. If your Images are bigger, they will not be sent!

The mpns object has both a ‘success’ and an ‘error’ callback. The error callback is automatically written to the log. However, it is very hard to identify which id is causing the error in this case. That’s why you should implement it in the way I did above. This way, you know exactly which id is causing an error and which id received their update correctly.

We are also able to add some extra functions to respond to the success and error callbacks. I still need to do this on my WAMS, and I will write about the measures I took in the different cases once I did it (I only started using Azure a few month ago, so I am also still learning). If you are interested, here is a list with all possible response codes for the mpns object: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff941100(v=vs.105).aspx#BKMK_PushNotificationServiceResponseCodes

Conclusion

Like you see, Windows Azure Mobile Services allows us to send out updates to the user very easy within less than an our for setting it up. There are a few things we need to take into account – in fact, most of this points took me a lot of time to find out (as it is the first time I use push in general). As always, I hope this post is helpful for some of you.

Until the next post, happy coding!

Posted by msicc in Azure, Dev Stories, windev, 0 comments

Getting productive with WAMS: how to set up a timeout before running code in an interval

WAMS

I truly love Windows Azure Mobile Services, as it provides an easy way to connect Windows Phone apps to the cloud and also manages Live Tiles and Toast Notifications via Push. This way, we don’t have an impact on the users battery life by running background agents.

However, scheduled scripts are only able to run in predefined time windows, with 15 minutes at lowest.

It may happen that you want to run your script in shorter intervals, as I am currently implementing into mine.

The functions:  setTimeout() and setInterval()

The difference between those two is pretty simple:

  • setTimeout() is running the function included only once after the time in milliseconds has passed
  • setInterval() is running the function included in an interval set up in milliseconds until it gets stopped

Knowing this, it is pretty simple to set up those two functions each for itself:

setTimeout(function() { 
//code to run 
}, time in milliseconds);

setInterval(function() {
//code to run
}, time in milliseconds);

I highly recommend to declare an interval as a variable. If you won’t do that, the interval will run forever as you never can stop it!

But what if we need first a timeout and then an interval?

That is the problem I was trying to solve over the last two days. I was playing around with all kinds of code constellations to achieve this goal. And I found a solution.

We need to set up a few things to achieve that goal:

  • global variables for the number of runs and the interval
  • a function that only proves if the interval is still valid to run or needs to be stopped
  • our function that should be run in an interval

In my example, I want the code to be executed five times, then the interval should be stopped (cleared). I achieve this goal with a pretty simple if/else clause, like you can see:

if (NumberOfRuns < 6)
{
        console.log("interval ran " + NumberOfRuns + " times");
        doSomething();
        }
        else
        {
        //stoping the interval       
        clearInterval(Interval);
        console.log("interval stopped!");
}

As this is a sample script, I use the function doSomething() to be executed. This represents your code that should be executed if the interval is still valid. Only important thing: counting up the number of runs every time the function is hit.

    //counting up the number of runs with every call of the function
    NumberOfRuns++;

    //your code runs here

And in our starting point (the function that has the same name like your script), we finally declare the the timeout as well as we start to count:

   //setting the NumberofRuns to 1 as after timeout the first run starts
   NumberOfRuns = 1;
   console.log("start")

   //settings timeout to call the function that proves if the interval is still valid
   setTimeout(function(){
       //interval has to be defined in this scope, otherwise it will not be accepted
       //we also need a variable for the interval to be able to stop the interval
       Interval = setInterval(RunInterval, 5000);
       console.log("timeout is over");
   },15000);

First, we start our counter with 1, as after the timeout the code will be executed for the first time. I added also some logging functions, so you can prove everything is running fine.

The content of the global variable “Interval” has to be declared within the timeout, otherwise we will not be able to set the interval for our function.

Once you figured all the points above, it is pretty easy to implement this into your running script.

If you want to play around with this and see what the log looks like, here is the full WAMS scheduler script:

//declaring global variables
var NumberOfRuns;
var Interval;

//function to execute in interval
function doSomething()
{
    //counting up the number of runs with every call of the function
    NumberOfRuns++;

    //your code runs here
}

//this function proves if the the interval is still valid
function RunInterval()
{
     if (NumberOfRuns < 6)
        {
        console.log("interval ran " + NumberOfRuns + " times");
        doSomething();
        }
        else
        {
        //stoping the interval       
        clearInterval(Interval);
        console.log("interval stopped!");
        }
}

//main script function (start)
function TestIntervalScript() 
{
   //setting the NumberofRuns to 1 as after timeout the first run starts
   NumberOfRuns = 1;
   console.log("start")

   //settings timeout to call the function that proves if the interval is still valid
   setTimeout(function(){
       //interval has to be defined in this scope, otherwise it will not be accepted
       //we also need a variable for the interval to be able to stop the interval
       Interval = setInterval(RunInterval, 5000);
       console.log("timeout is over");
   },15000);
}

And here is a screen shot from the desired log file:

Screenshot (192)

As I am still pretty new to JavaScript,  there might be also other ways to achieve this. Feel free to leave a comment if you have anything to add/improve on this code.

And as always, I hope this is helpful for some of you when playing around with Windows Azure Mobile Services.

Happy coding!

Posted by msicc in Azure, Dev Stories, 0 comments

Getting productive with WAMS: respect time zone offset for every single user

time_Azure

In my second post about WAMS I will show you how to respect the time zone of every user.

If you have users that are from all over the world, they have all different time zones. Your Mobile Service script runs always at UTC time, and every user gets the same date & time if you send them push notifications or update a live tile for example. Users don’t want to calculate the time zone differences, so we need to handle that for them.

UTC time is the time since 01/01/1970 00:00 in milliseconds. If we know this, it is somewhat easy to show users their local date and time.

Let’s have a look at the Windows Phone code.

To get the local time zone in our Windows Phone app, we only need three lines of code:

TimeZoneInfo localZone = TimeZoneInfo.Local;
DateTime localTime = DateTime.Now;
TimeSpan offsetToUTC = localZone.GetUtcOffset(localTime);

As you can see, we are getting the local time zone first. This is essential as this one is UTC based. Then we are creating a TimeSpan on our actual DateTime object to get the offset. To make this TimeSpan working on our Azure Mobile Service, which uses JavaScript, we need to convert it to milliseconds. That is the value that has an equal value on all programming languages.

useritemLookUp.TimezoneOffset = offsetToUTC.TotalMilliseconds;

This is the final line of code, which is used to update our user’s item in our SQL table row (for example).

Let’s have a look at the Azure code.

The code is similar to our Windows Phone part. First, we need to fetch the time zone offset from our SQL table:

var sql = "select * from users";

mssql.query(sql, {
        success: function (results) {
            if (results.length > 0) {
                for (var i = 0; i < results.length; i++) {
                    userResult = {
                                        TimeZoneOffset: results[i].TimezoneOffset,
                                        }

TimeZoneOffset = userResult.TimeZoneOffset;

This way, we can run through our whole table on an Azure Script and calculate the correct time, which is pretty easy to achieve:

var d = new Date();
var locald = new Date(d.getTime() + TimeZoneOffset);

These two lines generate the local time in Milliseconds for the specific user entry. You don’t have to worry whether a user is before or after UTC, it will always calculate the correct time.

If you want to use it for example to show the updated time to your users, you can format the time like I described earlier in this post.

That’s all about respecting local time for your users with Windows Azure and Windows Phone.

Happy coding everyone!

Posted by msicc in Azure, Dev Stories, 0 comments

Getting productive with WAMS: how to update data for a specific row in a table

WAMS.png

Like I promised, I will share some of the Azure goodness I learned during creating my last app.

This post is all about how to update a specific table entry (like a user’s data) in a Azure SQL table from an Windows Phone app.

First, we need to make sure that there is some data from the user we want to update. I used the LookupAsync () method to achieve that.

IMobileServiceTable<userItems> TableToUpdate = App.MobileService.GetTable<userItems>();
IMobileServiceTableQuery<userItems> query = TableToUpdate.Where(useritem => useritem.TwitterId == App.TwitterId);

var useritemFromAzure = await query.ToListAsync();
var useritemLookUp = await TableToUpdate.LookupAsync(useritemFromAzure.FirstOrDefault<userItems>().Id);

If we want a specific entry, we need a search criteria to find our user and fetch the id of the user’s table entry. In my case, I used the Twitter Id for the query as every user has this on my project.

Now that we have the table row id, we can easily update the data of this specific row with the UpdateAsync() method.

We need to declare which columns should be updated and asign the values to it first. After that, we simply call the UpdateAsync() method.

useritemLookUp.TwitterId = App.TwitterId;
useritemLookUp.LastCheckedAt = DateTime.Now;
useritemLookUp.OSVersion = "WP8";
useritemLookUp.AppVersion = App.VersionNumber;

await TableToUpdate.UpdateAsync(useritemLookUp);

Please note that you need a items class/model to create the update data (which you should have already before thinking about updating the data).

You should wrap this code in a try{}/catch{} block to be able to react to the Exceptions that possibly can be thrown and display a matching message to the user.

That’s already all about updating a specific row in a WAMS SQL table.

As always I hope this post is helpful for some of you.

Happy coding!

Posted by msicc in Azure, Dev Stories, 1 comment