Sergii Baidachnyi

Blog about technologies

Archive for September 2014

Azure Mobile Services: Sending notification from server-side

with one comment

Mobile Service API vs Notification Hub API

In the previous article, we got basic knowledge about Notification Hub and described some methods, which will help to communicate with it. Today, I am planning to show how to build a simple Windows Runtime application as well as a simple frontend application for sending notifications.

I am not going to make something virtual. So, I will try to reproduce the application, which I mentioned at the article about Notification Hub vs Native development. It will be Universal application, which will show last information about soccer games and will allow to receive notifications “from the field”.

But before we start to write some code we should select a method to communicate with Notification Hub. As I showed in the previous article, we are able to communicate with Notification Hub directly or we can use the Mobile Service infrastructure. These ways are similar but in our case we need to store the archive of messages in Azure because the application should show old messages as well as new ones. That’s why we need to create a table for messages on Azure side. Additionally, we need to create a service, which will help to update the table and we need to think about the security. Therefore, if we use Notification Hub directly, we still need to implement many things but if we use Mobile Services, it can help us and we can avoid additional work. The most important feature of Mobile Services is an infrastructure for data management. Thanks to Mobile Services, we have a simple way to create tables, manage data inside, write own business logic, which will work as a trigger for operations like inserting, deleting etc. Additionally, Mobile Service infrastructure supports some security mechanisms.

Pay special attention that Mobile Service API doesn’t allow to send notifications outside Mobile Services infrastructure. That’s why tables and triggers are the most important part of the story. In fact our backend will work with a table, it will just send new data in order to insert it to table but a trigger will help to broadcast of our notifications to registered devices.

Tables

Therefore, we should start our development with the tables. In our case, we will need just one table, which should store our messages. In order to create this table, you can use Azure Management Portal and you will need to set Name and permissions for available actions like insert, delete, update and select. Because we will modify data in the table from our backend only and we are planning to show our archive to all clients without special permissions, we may configure our table to use Application Key for Update, Delete and Insert actions and use Everyone permission for Select action.

clip_image002

When you click OK, your table will be ready for your data. However, we did not create any columns yet. If you open Columns tab, you will find several pre-created columns.

clip_image004

We may create more columns using the Add Colum button but we don’t need to do it because all tables have Dynamic schema by default.

clip_image006

Dynamic schema is available for Media Services with JavaScript backend and allows to create all needed columns based on received data in JSon format. So, if you send data, which will require new columns, they will be created “on the fly” and there is recommendation to disable dynamic mode in the production mode. Because we are using JavaScript, we will finish with table and move our attention to business logic.

How to send notifications from the server

Business logic is very simple. Let’s open Insert trigger for our table and modify the initial code in the following way:

function insert(item, user, request)

{

    request.execute(    

    {

        success: function()

        {          

            push.mpns.sendToast(null,

            {

                text1:item.text

            }, 

            {

                success: function (pushResponse) {

                    console.log("Sent push:", pushResponse);

                }

            });

            request.respond();

    }}

 );

}

 

In this code we kept the execute method of the request object but we added a parameter. It’s an anonymous method, which helps to send our notifications. In order to do it we are using push object, which includes several properties like mpns, wns, awns, gcm. These properties contain references to the objects, which can help to send notifications to different notifications servers from Microsoft, Google and Apple. Because we already have some code for Windows Phone (Silverlight) application, I decided to use mpns object but I will show wns as well in the next article.

The method sendToast is very simple and it allows us to send a message to particular device that broadcasts our message. We are using broadcasting in our example. That is why we use a null value as the first parameter. If method returns success, we will put a record about it in Mobile Service log. Log is a very important feature in when we are using JavaScript because it allows to find mistakes in the code. For example, I made several mistakes and Log showed these errors for me.

clip_image008

“Operator” application

Right now, we are ready to create code which will send messages to the client. Of course, I cannot share partner code inside ASP.NET portal. So I created a simple console application.

static void Main(string[] args)

{

    MobileServiceClient MobileService = new MobileServiceClient(

                    "https://test-ms-sbaydach.azure-mobile.net/",

                    "<application key>");

    IMobileServiceTable<NotificationData> messageTable =

        MobileService.GetTable<NotificationData>();

    messageTable.InsertAsync(new NotificationData()

       { Text = "My first notification" }).Wait();

}

That is all. Now, we may create a more advanced application for Windows Runtime. I will show how to do it in the next article.

Written by Sergiy Baydachnyy

09/25/2014 at 6:05 PM

Posted in Microsoft Azure, Windows 8, Windows Phone

Tagged with

Azure Mobile Services: Creating a simple Notification Hub

with 5 comments

Lately I made a short overview of Notification Hub but the last article was mostly about some benefits of Notification Hub in comparison to “native” solution rather than its features. Today, I am planning to concentrate your attention on a step-by-step guideline, which will show how to use Notification Hub and will provide much more details about its particular features.

The first of all, we should understand that Microsoft has prepared several boxed solutions for common mobile scenarios, which are called Azure Mobile Services. However, Notification Hub service is NOT one of them. This service does not require Mobile Services and we are able to create it using App Services tab.

clip_image002

However, there will be several opportunities, if we associate Notification Hub and Mobile Services. That is why I propose to start with Mobile Services and if we will create ones, Notification Hub will be created automatically for us.

clip_image004

This step is very simple. You should select name (url), SQL Database and region. The Backend field helps to select right technology for backend coding and you can select between .NET (C# of course) and JavaScript options. I do not like JavaScript very much but I would recommend the JavaScript language for Notification Hub scenarios because you will not create much code due to limited number of them. Frankly speaking, there is one scenario only and it relates to registration process of new devices. Additionally, it is easy to deploy JavaScript registration script because Azure dashboard has special options as well as JavaScript editor, which should make you deployment process pretty simple. In any case, I am planning to show JavaScript as well as C# in the next article. Therefore, you can use any of those languages.

clip_image006

If you click OK, you will have your Mobile Service as well as Notification Hub inside in 1-2 minutes. There are several ways to open Hub dashboard but I like the Mobile Services tab because it allows to edit JavaScript registration script as well as to change permissions of registration endpoints. These permissions allow to setup additional security rules for endpoints, which will be used to register new devices. There are the following options:

· Everyone – all devices will be able to pass registration process. It’s OK for many scenarios because the registration activity itself will not allow to receive any notifications in case of wrong certificate (or client secret and package sid in case of Windows 8);

· Anybody with application key – this option allows to pass registration process for devices, which sent an application key in their requests. Pay attention, that this method will not guarantee any type security for apps because, in the most cases, developers store an application key inside their applications and key can be stolen very easy. If you want to add some security features, you should implement authentication mechanism inside your app;

· Only Authenticated Users – users require to authenticate via one of the supported authentication providers like Facebook, Twitter, Google, Microsoft Account and Azure Active Directory;

· Only Script and Admins – only script with master key as well as admin (via Management Portal) will be able to use the service;

Pay special attention that you will not see registration endpoints section, if you select .NET as a backend technology. If you use C#, you will be able to set permissions WebApiConfig.cs file.

clip_image008

We just discussed the security options and we mentioned application key and master key. They can be found on Mobile Service dashboard and you can easily regenerate these keys in case of leaks.

clip_image010

Of course, you should be aware of Media Services security options just in case of using Media Services client libraries but you can work with Notification Hub to avoid Media Services and it does not depend on whether your Notification Hub is integrated with Media Services in you subscription.

If you want work with Notification Hub directly, you may forget about application and master keys but you will need to apply the policies of Notification Hub. In order to understand these policies, let’s go to Notification Hub dashboard (Configure tab). You can find there several access policies and you are able to modify them or create new ones. We should use these policies in order to connect Notification Hub directly. Additionally, there are two keys for each policy, which should be used for connection strings. You can find all the connection strings on the Dashboard page of Notification Hub and you can select one of them based on existing permissions. Of course, if you need a connection string for client devices, which will listen to notifications only, you can use DefaultListenAccessSignature connection string. If you create backend service, which will send Notifications, you can use a connection string with Send permission etc.

clip_image012

Ok, I think that we can create a simple application, which will be able to receive our notifications. In order to do it I selected Windows Phone application (Silverlight) because this type of applications doesn’t require Store registration but it requires to turn on Enable unauthenticated push notifications checkbox on the Configure tab. It will allow to send up to 500 messages without certificate and this number is enough for testing.

Let’s open Visual Studio and create Windows Phone (Silverlight) application. It will use old type of notification services unlike Windows Runtime applications but it will not require a certificate as mentioned above.

We will try to communicate with Notification Hub directly as well as via Mobile Service. I will start with the direct method. In order to do this you should use NuGet tool to add WindowsAzure.Messaging.Managed assembly, which will help you to send data to our hub because I don’t want to create JSon code as well as work with WebRequest and WebResponse classes.

clip_image014

Right now, we are ready to add some code. Open App.xaml.cs file and change Application_Launching method in the following way:

private async void Application_Launching(object sender, LaunchingEventArgs e)

{

    var channel = HttpNotificationChannel.Find("MyPushChannel2");

    if (channel == null)

    {

        channel = new HttpNotificationChannel("MyPushChannel2");

        channel.Open();

        channel.BindToShellToast();

    }

 

    channel.ChannelUriUpdated +=

       new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>

    {

        var hub = new NotificationHub("test-ms-sbaydachhub",

            "<connection string>");

        await hub.RegisterNativeAsync(args.ChannelUri.ToString());

 

    });

}

This code will allow to receive Notification Channel from the MPNS and update the channel in our Notification Hub. That’s all. You can run the application on your phone and try to send a message. In order to send a message you can use the Debug tab on the Azure Management Portal.

clip_image016

If you want to use Mobile Services in order to register your device for notifications, you need to add Azure Mobile Service package to your project and change Application_Launching in the following way:

private async void Application_Launching(object sender, LaunchingEventArgs e)

{

    var channel = HttpNotificationChannel.Find("MyPushChannel2");

    if (channel == null)

    {

        channel = new HttpNotificationChannel("MyPushChannel2");

        channel.Open();

        channel.BindToShellToast();

    }

 

    channel.ChannelUriUpdated +=

       new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>

        {

 

            MobileServiceClient MobileService = new MobileServiceClient(

                "https://test-ms-sbaydach.azure-mobile.net/&quot;

 

            );

            await MobileService.GetPush().

               RegisterNativeAsync(channel.ChannelUri.ToString());

        });

}

Pay your attention that this code doesn’t use connection strings from Notification Hub but it will not work if you don’t set Everyone permission to the registration pipeline (or put an application key as a second parameter of MobileServiceClient constructor).

I think we can finish for today. In the next article I am planning to create a Windows Runtime application as well as an application for sending push notifications.

Written by Sergiy Baydachnyy

09/21/2014 at 10:21 PM

Azure Mobile Services: Notification Hub vs “native development”

with 6 comments

Probably, if you are reading this article, you are a new reader of my blog as I have had many posts before but they were in Russian only. However, in nearest future I will be required to switch my language from Russian and Ukrainian to English. That’s why I decided to do it sooner than later and here is my first post in English!:) I will be happy to hear any feedback from your side, which will improve my English and help me to feel good in future.

“Native development” scenario

I started to learn Microsoft Azure since the first announcement during Build conference in 2008 but the first real experience I got in 2010 only. At that time, Microsoft started to push a stable version of the platform to clients and we got several requests from our partners about technical support. During that time, I worked with the biggest Ukrainian media holding and helped to deploy several applications for Windows Phone 7 and one of them was related to Microsoft Push Notification Service.

The client owned the biggest soccer portal in Ukraine and their technical staff wanted to implement a service, which could allow to notify all subscribers (primary WP and iOS) of the portal about some changes during live soccer games worldwide. I was not a pro in iOS applications, that is why I will describe the solution from Microsoft platform perspective but you can easily interpolate it to any other platform. So, it was not too hard to realize a simple Windows Phone application, which provided last news and allowed receiving Toast notifications but in case of server side, we expected several complex problems. The biggest problems were about hardware resources and Internet capacity. The portal has hundreds of thousands visitors during any kind of games and it was too hard to find some more servers as well as to guarantee quality of Internet channel to organize sending messages to Microsoft Push Notification Server to all subscribers during the same amount of time. That is why we decided to move server side of service to Azure.

In 2010 Microsoft already presented Cloud services (Web and Worker roles), Storage services (Tables, Blobs and Queue) and SQL Azure. We used them all. Let’s look a schema below, I will try to describe the solution in more details.

clip_image001

First, we implemented a web service (web role), which was able to store data from Windows Phone devices about Notification Channel URIs. The unique URI generates by Microsoft Push Notification service for the specific device and it could be used to send notifications to this device. So, if you have 100 devices, you should have 100 URIs to send message to each of them. In order to store information about URIs and users we used SQL Azure.

On the second step, we created a Web service (it was Web role but we can utilize the existent Web role from the previous step), which allowed to receive messages from an operator (a human on client side or something else). The messages contained some information about a game status, which should be send to subscribers. Of course, we could not use this Web service to deliver these messages to our subscribers, because it could take some time (up to several hours, in case of big number of subscribers) and we needed to send a response to the operator as soon as possible. That is why Web service stored new messages to Queue in Azure Storage. This structure is adopted to simultaneously access to messages inside and it works very well, if you use several instances of Worker role for processing of the messages.

On the last step, we created a Worker role, which was sending the messages to the subscribers. We were able to monitor the queue and increase or decrease number of instances of Worker role based on number of games, number of subscribers and number of messages in queue.

The proposed solution is stable and flexible but there are some disadvantages. From the first sight, the solution is too complex and you need to know several Azure features in order to realize it. From the second side, you should be aware of the price of separate services like Cloud, Storage, SQL Azure. These disadvantages could stop many developers from realizing of the simple and common solution like notification to clients applications. But it was just a background for “native development” on Azure. Since that time Microsoft have realized several good solutions in a box and one of them is Azure Mobile Services, which contains a Notification Hub component. Let’s look this component in details.

Introduction to Notification Hub

Notification Hub allows us to work without the knowledge of the details that are happening in the background. We are not aware about SQL Azure, Worker roles, Queues and client platform. We still can use Web role to manage authentication, to format messages etc.

clip_image002

In the simplest scenario, we just need the Notification Hub, which provide interfaces to sending messages via operator applications as well as to updating notification channel from client devices.

clip_image003

We just need to create a new Notification Hub service inside Azure account, configure it and the service will allow to subscribe unlimited number of devices as well as to send messages to them. Additionally, Notification Hub supports different types of client platforms like Windows platform, iOS, Android etc. In other words, Notification Hub is a black box, which allows us to realize client applications and “operator” applications only. Notification Hub is a ready to use common scenario, which was prepared by Microsoft.

Here are some features, which could be interesting for developers:

· Platform-agnostic – a developer can configure Notification Hub to send notifications to the most client on the market, like Windows 8, Windows Phone, iOS, Android, Kindle etc. At the same time there is API, which supports these platforms in order to make registrations of any type of devices;

· Tag support – a developer can send a message to subset of all subscribers using tags. For example, user can subscribe to news related to local soccer’s games only;

· Template support – you can personalize messages and localize them using templates. For example, the operator can send just one message with localized parameters and the Notification Hub will resend it based on different templates for different devices. Some of these devices will receive a message with text in Ukrainian but some of them will get message in English;

· Device registration management – you are able to integrate code to registration pipeline in order to preauthorize clients before registration. It is very important in case of paid services;

· Scheduled notifications – yes, you can schedule some notifications for specific time;

Therefore, you should be able to understand purpose of the Notification Hub. I am planning to show some features of the Notification Hub in next article.

Written by Sergiy Baydachnyy

09/03/2014 at 11:57 AM