Sergii Baidachnyi

Blog about technologies

Archive for the ‘Microsoft Azure’ Category

How to cook Azure Mobile Apps (node.js): “50 records” limit and lazy loading

leave a comment »

Code is available here: https://github.com/sbaidachni/XamarinMobileAppsDemo

In the previous posts we discussed how to create and setup node.js Azure Mobile Apps backend and how to start using .NET Standard libraries with Xamarin applications. Now, I am waiting for my next flight, and it’s time to build a basic interface using Xamarin.Forms.

I am going to work with records from the SalesLT.Product table. So, I need to make sure that my backend contains the MS_TableSchema application setting with the SalesLT value there, and my Product.json file contains autoIncrement property in true due to integer primary key there.

But there is one more problem: as we discussed in the first post, Azure Mobile Apps (node.js) service requires id name for the primary key rather than ProductID. In general, it’s not easy to change any column name, and even in our simplest case, we cannot do it using just sp_rename. You will be able to see that the database contains lots of dependencies to ProductID. So, I would recommend to create a new view rather than redesign the whole database. We will be able to work with the view like with the table, and we will be able to define new names for our columns.

CREATE VIEW [SalesLT].[vProductList]

WITH SCHEMABINDING

AS

SELECT

    p.[ProductID] as id,

    p.[Name],

. . . . .

      p.version,

      p.createdAt,

      p.updatedAt,

      p.deleted

FROM [SalesLT].[Product] p

Prior to create the view, you have to make sure that SalesLT.Product already contains version,createdAt, updatedAt and deleted columns. You can simply create Product.json and Product.js in your backend environment to force the framework to create these columns for you and after that you can rename Product.js and Product.json to vProductList. Once you finish, you will be able to use Easy Tables functionality and review your data in the portal:

clip_image002

Of course, if you create any additional column in the view, you will fail because views don’t allow you to alter associated tables.

Let’s go back to our Xamarin application and implement something simple.

I will not implement a really perfect MVVM approach, but we will need to create some classes in any case. First of all, we need to create a class that will represent our table. It’s exactly a model and we will implement all needed properties there. You can manage name-column relationships using attributes, but if you use identical to your db names in your class, you have to do almost nothing. So, you can find my class below:

vProductList.cs

You can see that I used vProductList as a class name and Id, Name, ProductNumber, Color and Size are my columns from the table.

Now, we need to implement a view-model class that will prepare all data to show UI. I am going to use an ObservableCollection to store our items to make sure that our UI will be updated automatically in the case of new items there. I am using the singleton approach to make sure that we have just one view-model in time and I will implement the Product class that will satisfy our needs better, compare to our vProductList. Of course, the Product class doesn’t have any specific things now, but later we will be able to add some UI-related features to it.

MainPageViewModel.cs

You can see that we use MobileServiceClient class to get a reference to our service, and once we need some data, I am using ToListAsync to download everything. At the same time you can find that I am using a strange property RecordCounts. It’s still not clear why I need it, but later we will be able to see why it’s important if you want to show all data from your table.

Let’s implement our UI:

MainPage.xaml

You can see that there is a ListView that just displays Id and Name fields from the table. Additionally, there is a label that shows number of records that we just downloaded.

Below you can find associated with the UI code:

MainPage.xaml.cs

We are just getting a reference to our view-model and download data once our UI is appearing.

Let’s start our application and you will be able to see that the UI displays just 50 records:

clip_image004

It’s happened because node.js implementation doesn’t allow you to get all records. By default, you can get just 50 records, but there is the pageSize parameter that you can provide in your app.js file.

clip_image006

In any case, if you change the parameter, you will be able to download fixed number of records only. That’s why we need to implement something on the client side to display everything.

In order to do it we can use ItemAppearing event handler for our ListView. The ItemAppearing event fires for every item before it will be displayed. We cannot guarantee exactly when, be it will fire in advance. So, we can use this event to download more and more records, implementing some sort of lazy loading approach. Just look at the following code:

protected async void ListView_ItemsAppearing(object sender, ItemVisibilityEventArgs e)

{

var itemTypeObject = e.Item as Product;

if (model.Items.Last() == itemTypeObject)

{

await model.LoadDataAsync();

}

}

You can see that if ItemAppearing fires for the last element in the list, we will be able to download more. The most important thing there that if ListView implements RecycleElement caching strategy, we will download more elements just if a user scrolls the list far enough.

If you run the application, you will be able to see that there 100 or 150 records in the list (depends on your monitor and other parameters), but once you start scrolling down, the list will download more and more items (by 50 records in our case).

So, now you know how to deal with big table and aware about “50 records” limit. Next time we will discuss how to implement continues integration with GitHub.

Written by Sergiy Baydachnyy

09/14/2017 at 12:25 AM

Posted in Microsoft Azure, Xamarin

Tagged with ,

How to cook Azure Mobile Apps (node.js): Xamarin and .NET Standard

leave a comment »

In the previous post we discussed how to setup Mobile Apps in node.js, and it’s time to start developing a simple client application. I will use Xamarin and C# programming language, because Xamarin is the coolest technology right now that allows me to develop applications for all modern devices.

My application is not very complex, so, I will use Xamarin forms to develop it just once for all platforms not digging to any platform specific features.

You can create your application on Mac or Windows using Visual Studio for Mac or Visual Studio 2017 (2015). In my case I am sitting at Kelowna airport with my Windows computer, so, I will use Visual Studio 2017 Update 3.

Pay attention that Visual Studio allows you to create Xamarin Forms application using Shared Project or PCL templates. It’s strange, but Shared Project is the default option, and I would like to recommend changing it to PCL. Later, you will be able to use .NET Standard rather than PCL just moving your code to a .NET Standard library project.

clip_image002

Visual Studio creates 4 projects in one solution and three of these projects contain platform-specific code for supported platforms (iOS, Android and UWP), but the last one is exactly Xamarin.Forms based portable class library. Almost all time we will work with this library, but on the first step we need to add a reference to Mobile Apps SDK for each of our projects. Therefore, I would recommend to select Manage NuGet Packages for the solution rather than for a particular project and find Microsoft.Azure.Mobile.Client library:

clip_image004

The process is not complicated, but there is a surprise: we will not be able to install the latest version of the library exactly to Xamarin.Forms project:

clip_image006

The latest version supports .NET Standard (at least 1.4) and we can easy add it to our Android, iOS or UWP applications (because Xamarin added support for it some time ago), but you cannot add it to your PCL (Xamarin.Forms part). Of course, you can say that I could avoid this problem using Shared Project approach. Yes, I could do it as well as I could create lots of “spaghetti” #if #else code and got a problem with IntelliSense and so on, but I want to stay with “a separate library” approach and there are several ways to fix the problem:

· I will start with some suicidal ways like: you can use REST API directly. It’s really great way to increase your income if anybody pays you for number of code lines, but in my case, it’s not true;

· Some guys like to recommend using the previous version of the library. Talking about “previous” they tell about 3.0.1 that was published couple versions ago. I am not sure what there is changed since 3.0.1, but I believe that they didn’t publish new couple versions “just because”. That’s why I would not recommend using this approach as well;

· Finally, you can migrate your library to .NET Standard;

Let’s stay with the last approach and see, how we can make the migration.

It’s funny, but you could do the migration process just clicking a button. Using Visual Studio 2017 Update 3 I could not find any button. If you visit PCL project settings, you still will be able to select a profile for PCL and you will see a message about .NET Standard benefits, but the button is disappeared. Probably, it was a reason to do that. At the same time, I am sure that yesterday I could see the button in Visual Studio for Mac.

clip_image008

Because we don’t have any button, we need to create one more project based on .NET Standard library template manually:

clip_image010

Opening project settings you can select any .NET Standard version for the project. Just pay attention that Visual Studio 2017 Update 3 will not install .NET Standard 2.0 automatically and you will need to install it manually from Microsoft web site, but Update 4 installer should include 2.0 version.

clip_image012

But don’t be in a hurry because .NET Standard 2.0 is just released, and it will be supported by Xamarin in next major update only. In fact, the problem even is not Xamarin, but in UWP platform that works based .NET Standard 1.4. You can find this information looking at the following page: https://docs.microsoft.com/en-us/dotnet/standard/net-standard

clip_image014

Microsoft is going to support .NET Framework 2.0 for UWP projects since Fall Creators Update, but it doesn’t mean that you will be able to target .NET Standard 2.0 and earlier UWP releases at the same time.

Therefore, if you want to avoid any previews, alfas and insider releases at this time, you need to stay with .NET Standard 1.4, at least for next couple months.

Once the project is created, we can move all our files from Xamarin.Forms PCL project to .NET Standard library project and remove initial Class1.cs. Thanks to Galaxy you can use Drag and Drop to copy all your files and folders. So, if you already have lots of files in the PCL, it should not be challenging.

Now, it’s time to remove your PCL, and you can rename your .NET Standard library using “old” PCL name. It will not help you to avoid problems with dependencies for your iOS, Android and UWP projects, and you should target your .net standard library from each of them.

The last thing that we need to do is adding reference to Microsoft.Azure.Mobile.Client and Xamarin.Forms libraries. The first package will not generate any problems this time, but I cannot say the same about the second one. Xamarin.Forms 2.3.4 still is not .NET Standard library.

Of course, the next release (2.3.5) already supports .NET Standard, but it’s still in preview. At the same time, if you want to test new features, you can check “Include prereleases” box in NuGet package manager and use a prerelease for 2.3.5 or even 2.4.0.

clip_image016

Both releases support .NET Standard, but the second one supports even .NET Standard 2.0. But if you want to use .NET Standard 2.0 for all projects, including UWP, you will need to install Visual Studio 2017 Update 4 Preview, the latest Windows 10 Insider Preview and the latest UWP SDK insider preview. I can use both options on my computer, but today we are working with components that are in production right now. So, we need to think about how to use the current Xamarin.Forms release.

It’s not the biggest problem because .NET Standard supports type forwarding and other stuff to target old libraries and we can use Xamarin.Forms, but we need to make some modifications in our project file: just open your .csproj for editing and add <PackageTargetFallback>portable-net45+win8+wpa81+wp8</PackageTargetFallback> right after TargetFramework:

clip_image018

It will tell the compiler that if it cannot add a reference due to a problem with the target platform, it’s OK and it should be ignored.

That’s all. Now, we can recompile our solution and even start initial projects using real devices or emulators.

Of course, once a new version of Xamarin.Forms is released, we will be able to use it as a .NET Standard library, but the previous approach will work fine for any other PCL assembly. Counting that there are huge number of existing PCLs, it’s important to know how to use them.

One more thing. If you still targeting Silverlight (WP) using Xamarin, you may need to add a special library to enable compatibility for it:

clip_image020

Next time we are going to start using our Mobile Apps and we will discuss lazy loading and 50 records limit.

Written by Sergiy Baydachnyy

08/30/2017 at 8:05 AM

How to cook Mobile Apps (node.js): table schemas, primary keys and existing tables

leave a comment »

In this post I am going to discuss how to start developing a Xamarin client application that should be connected to an existing database. As a backend I am going to use Azure Mobile Apps, because the service can minimize our work on server side and provides lots of useful features. But to get all benefits from the service, you need to know some tricks that it’s not easy to find in standard tutorials.

Today, I am going to discuss, how to use Mobile Apps in the case if you already have a database. Yes, Mobile App allows you to create a database from scratch using a graphical interface, but usually it’s not the case. I participated in lots of projects last year, and we always had a database in advance or designed it a few days before any client application. I know, it can hurt some client developers, but in many cases Xamarin app is not the centerpiece of your project. 

Before to create any database, I want to note couple things. 

First, you can develop your code for Mobile Apps in JavaScript or in C#. I like C# and don’t like JavaScript, but in the case of JavaScript/node.js implementation, you should do/know almost nothing to implement your backend. In the case of C#, you will need to generate lots of code, know Entity Framework details, and Azure Portal will provide limited number of features. In fact, C# and node.js implementations are fully different and if I don’t need to create a complex enterprise application I will always select node.js. If you want to use C# rather than JavaScript, this post will not be useful for you at all.

Second, Microsoft still supports an old implementation of the mobile backend called Azure Mobile Service. It’s not available in the new Azure portal, but there are still lots of content about it. I found that some developers continue to use Mobile Service term and it generates some messy. Try to use Mobile App everywhere. It’s the latest implementation under Azure App Service umbrella.

Ok. Let’s try to create a new database using SQL Azure. In order to have some tables and data, I would recommend selecting AdventureWorkLT database. It’s possible to do from the Azure portal. So, you can simple select New->Databases->SQL Database, and  you will be able to select the database from the “select source” field in the wizard:

image

Once you create your database, add a firewall rule to connect it from your SQL Management Studio or Visual Studio, you can note two things there:

  1. There are several schemas rather than just dbo one. It’s very important, because dbo is the default schema in Mobile Apps, and if we want to get some data from SalesLT.Product table, we have to deal with SalesLT schema;

image

  1. You can note that all tables contain primary keys of the int data type. In the case of the Product table we have ProductID as the key. It’s a very important note because some people likes to tell that you have to use guid as a data type for keys. I don’t think so, but we even should not discuss this question since we ALREADY HAVE a database that was designed by Microsoft as an example. I just want to connect my Xamarin app to it.

image

That’s all with the database and now we can create an instance of Mobile App:

image

It’s a trivial task and you should not select any specific parameters on this step.

Once you have your database and an instance of Mobile App, you can connect it together. To do it, you need to open Data Connections tab from the Mobile App dashboard and add a new connection:

image

Azure portal is clever enough to list your database. So, you should not provide any connection strings manually. You can see that a default name for the connection string is MS_TableConnectionString. DON’T TOUCH IT! Exactly this name is hardcoded in many places. 

In fact, using Add data connection tab, you are creating a new connection string that is available from the Application Settings tab. Therefore, Data Connections tab is just an easier way to create MS_TableConnectionString parameter, but you can use Application Settings as well and we are going to use this tab for some additional parameters:

image

Now, it’s time to select a programming language. In the case of C#, you can close the portal and just create all code in Visual Studio, but in our case, we want to use the portal and node.js. So, we have to initialize our empty hosting space with the right environment. It’s possible to do if you select Easy Tables tab:

image

Just click Initialize App and all needed components will be installed to your hosting space. Now, Easy Tables tab allows you to create new tables in the existing database and you can note that it doesn’t display our existing tables. Let’s try to understand, how to show our SalesLT.Product table in the list. To do it, I will just create a new table and check what is happening with my hosting space:

image

To create a new table, you can provide a table name and some security parameters for different operations with the table. 

Now, you can use Mobile App dashboard to open App Service Editor to review all available code in your hosting space:

image

You can see that for our faketable we have two files faketable.js and faketable.json. The first file imports azure-mobile-apps module and creates a table object, and the second one contains some parameters for the table:


{ 
  "softDelete" : true, 
  "autoIncrement": false, 
  "insert": { 
    "access": "anonymous" 
  }, 
  "update": { 
    "access": "authenticated" 
  }, 
  "delete": { 
    "access": "anonymous" 
  }, 
  "read": { 
    "access": "anonymous" 
  }, 
  "undelete": { 
    "access": "anonymous" 
  }}

Both files contain important information for our research. Now, we can see that there is a module that contains implementation for the backend, and if we check the module, we can find it on github: https://github.com/Azure/azure-mobile-apps-node. So, node.js implementation for Azure Mobile Apps IS IN OPEN-SOURCE. It’s great because we can find some answers there. The second file allows us to tune the backend behavior a little bit providing some parameters per table. 

In fact, in order to connect a table to our service from our database, we need to create these two files. Let’s make the experiment and create product.json and product.js files with the same content as faketable.js and faketable.json. Of course, if you go back to Easy Table, you will not be able to see any Product table due to some problems. In order to understand all these problems let’s look at faketable structure:

image

You can see that the backend created five columns for the table and the table was created in the dbo schema. So, to make our table available we have to manage several things:

  • Table schema

  • Additional columns

  • Primary key that is GUID rather than int

In the case of columns createdAt, updatedAt, version and deleted you should nor care too much. Once we fix all other problems, the framework will add all columns automatically and we will not loose our existing data. Of course, if you suddenly have some columns with the same names, you are in trouble, but it’s a very rare case.

Let’s fix the table schema. In our case we have SalesLT rather than dbo. To understand how to change the table schema for all tables, I would recommend to open node.js implementation on github: https://github.com/Azure/azure-mobile-apps-node. You can open environment.js in src/configuration/from subfolder and check all available parameters there. One of the parameters is MS_TableSchema that you can provide from the Application Settings tab on Azure portal. 

* @param {string} MS_TableSchema Default schema name for sql tables. Can override in table config

image

Therefore, we can specify SalesLT schema for the project. 

Now, you should be able to see Product table in the list, but it will not work due to the problem with the key. By default the key is GUID, but in our case it’s int and we are not going to change it because it will lead to huge amount of problems. In fact, Mobile Apps allow us to use int, but we need to configure it. In order to understand where to make all needed changes, I would recommend to check /src/data/mssql/statements/createTable.js on github. There is some code:

pkType = tableConfig.autoIncrement ? 'INT' :
 

It’s just the beginning of the line, but you can see that this line is setting up the primary key type. It’s clear that it will be int if autoIncrement property from Product.json is true.

Therefore, we fixed almost all problems, but we still have one left: the primary key MUST have “id” name. If you open src/data/mssql/statements/insert.js on github, you can find something like this:

sql += util.format('SELECT * FROM %s WHERE [id] = SCOPE_IDENTITY()', tableName);
 

You can see that id is hardcoded inside the query. I really don’t know why it was implemented in this way, but it’s something that you cannot modify it in any config file. Of course, it’s possible to assign own commands, but I am not sure if you want to implement own data provider. Additionally, it’s possible to modify existing code and redeploy it, but it’s not easy as well. The fastest way to fix the problem, it’s renaming our ProductId to id:

EXEC sp_rename 'SalesLT.Product.ProductID', 'id', 'COLUMN';  
 

It’s not the best way, because you have to check all your stored procedures, modules and other client applications. So, it will not work in enterprise. 

Now you can use Easy Tables to see all data, and all additional columns will be created.

That’s all for today and next time we will discuss how to develop a basic Xamarin application, but there are still some things to research, which you can do yourselves: find a way to work with app.js in order to use more parameters (including schema); try to understand if it’s possible to modify table schema per table (schema parameter in table config file); how to modify the code to use any primary key name.

Written by Sergiy Baydachnyy

08/22/2017 at 9:08 AM

Posted in Microsoft Azure, Xamarin

Tagged with

Azure services and Internet of Things

leave a comment »

I just finished several posts about Galileo board for beginners. In those posts I showed how to create simple projects, which help us to collect data from sensors. But there still is a question: what we should do with collected data there. That’s why in this post I want to show several cloud services, which will help you to collect and analyze data from many devices at the same time in order to be ready to present consolidated data for users.

Of course I am going to talk about Azure because Azure provides not just base services like VM hosting, WebSites, SQL Azure etc. but several specific services, which are ready for solutions based on “micro” devices – devices which might contain many different boards and sensors around the World.

Queue

I will start with most simple Storage service component like Queue, which was presented in the beginning of Azure era and which is important for some scenarios in Internet of Things area.

Queue supports REST API and works fine in IoT projects which have just one event publisher or just one event consumer and if you don’t need to implement any special algorithm for access data in queue.

For example, you design a device, which plays music in restaurants or bars. Everybody may order favorite music using smartphone, tablet, terminal at the bar etc. But the device can play just one composition at the same time. So, you will have a queue there with orders inside and each element will contain some expiration time as well. In these case you have just one consumer device and it doesn’t require any special algorithm for selecting messages.

You can design one more device, which will provide the next number in line to government officials. This device increases internal counter, provides a new number, prints tickers with the number and puts a given number to the queue. Each official has a table – one more device, which connects to the queue and takes the next number from the queue. In this case we have just one publisher but many consumers (several agents with own tables).

So, there are many scenarios where queue is good enough. You can find REST API documentation for queue using this link.

Pay special attention that there are very strong requirements for queue. You should use low case symbols only. I forget about it from time to time and then it takes some time to find a mistake.

Event Hub

If you have many publishers and consumers at the same time, a simple queue will not work fine.

Imagine cashiers at the food store. Usually each cashier has his own line and there is a chance to increase number of cashiers in real time etc. There is no ways to use just single queue. At the same time it’s too hard and expensive to use many queues, because you need to implement lots of code, which will create queues dynamically and manage elements there. In other words you will need super queue.

Probably it was a good idea to create something like super queue with much own code inside but today we have Event Hubs.

Event Hubs is a special service which supports messaging scenarios with many event publishers and many consumers at the same time.

clip_image002

Thanks to partitions, consumer groups and offsets it’s possible to implement any scenarios there. Of course, you can use Event Hubs in scenarios, which work with Queue as well. In this case you will use a universal approach.

Of course, Event Hubs like Queue and other services, support REST API as well.

Mobile Services

In some scenarios you might want to notify users about some events using standard Push notification services. In this case, it’s easy to use Azure Mobile Services. I already wrote a series about Azure Mobile Services. So, if you are interested in some aspects of it, you can read my series.

Tables and Blobs

Of course, previous services allow to use events in order to communicate between publishers and consumers. But in many scenarios you are required to store a lot of data from sensors. For example, you can create a device, which will collect data about pollution in the area. Your device is not going to send any events. Instead, you are going to use this data to analyze the situation for many years. So, you need a storage but Queue and Event Hubs cannot works like a storage.

Since usually devices send much non-relationship data, you will use non-SQL storages. In case of Azure you can use Tables and Blobs.

Tables allow to store data in table format and you can store hundred thousands terabytes there. But Tables have two disadvantages there. First of all in order to store data from sensors, your device need permanent access to Internet. Of course, you can preserve data to a local file but in this case it’s better to send to Azure file itself. The second disadvantage is related to format of data. You can store text data there but in case of images, videos etc. you need to return to files. So, usually, in IoT scenarios you will use Blobs instead of Tables.

Blobs allow to store any files inside and support REST API as well. So, usually you will preserve sensor data to a file and send it to Blobs based on your own scenario.

Stream Analytics

So, we already have some services which help with events and storage but we still need a way to analyze stored data. A new Azure service, called Stream Analytics, will help you to implement this task as well.

Stream Analytics can use Event Hubs and Blobs like a source for analysis. So, it is able to get and prepare all the needed data from your analysis. After that Stream Analytics provides query language, which helps you to implement your own algorithm in order to prepare data for analysis. Finally, stream analytics can upload all your results to new blobs, Event Hubs, SQL Azure database, which could be used as a source for many analysis tools.

Stream Analytics is still in preview mode but you can try it for free right now using trial accounts or your regular Azure account.

Therefore, as you can see, Azure supports full stack of needed services for IoT world and could be used with any IoT devices.

Written by Sergiy Baydachnyy

01/20/2015 at 11:10 PM

Posted in IoT, Microsoft Azure

Tagged with ,

Azure Mobile Services: Did we forget something?

leave a comment »

This is my last post about Azure Mobile Services. Last time we finished implementation of Windows client and I used all needed features for my application. You can read all posts about the topic at the following links:

Azure Mobile Services: Notification Hub vs “native development”

Azure Mobile Services: Creating a simple Notification Hub

Azure Mobile Services: Sending notification from server-side

Azure Mobile Services: Creating a Universal Application

Azure Mobile Services: Creating of Universal Application (part 2)

Azure Mobile Services: Visual Studio

I described a very simple application but what about other features of Azure Mobile Services. Frankly speaking, I used just half of all features there. Therefore, I decided to describe all other features in order to have a completed view of the topic.

Tags

This feature is related to Push Notification Hub but Azure Mobile Services encapsulate it as well. The idea is very simple – use a special tags in order to target right groups of users. For example, if you create a news site you can create a tag for each group of news and user might select just the groups that are interesting to him. I don’t like politics so much but somebody else might not like sports news etc.

Of course in order to implement this approach you need have a way to select tags during user registration process and you should have a method to broadcast messages only for selected tags. There is a good news – Mobile Service API supports tags. For example, in order to make registration using some tags you can use the following code:

await mobileService.GetPush().RegisterNativeAsync(channel.Uri,

new List<string>() {"sport", "movies", "Canada" });

In this example, three tags will be associated with user registration.

In order to send message to all users with tags movies, you can use the following code (C#):

await Services.Push.SendAsync(message, "movies");

Pay special attention that methods, which we use to send messages to users, usually allow to pass tag expression. Tag expression could be used for passing expressions based on tags, using logical operators like &&, || and !: "(tagA && !tagB)"

Templates

Templates are one more way to create personalized messages for users. For example, in order to send message from C# to Windows users, you may use the following code:

WindowsPushMessage message = new WindowsPushMessage();

message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +

@"<toast><visual><binding template=""ToastText02"">" +

@"<text id=""1"">football.ua</text>" +

@"<text id=""2"">" + item.Text + @"</text>" +

@"</binding></visual></toast>";

And if you form a message in this way, all your users will see the same message. However, in some cases you might want to pass parameters to your message based on user preferences. For example, if your application supports several languages you might want to send localized messages; if your application provides some data like mileage or temperature, your might want to use measurement system, which is understandable for users, etc.

Templates allow us to use parameters in XML or JSon messages (based on platform), which we usually form on server side. In case of templates, your server side should not form message from scratch. Instead, client application should register a message template including parameters and the name of the template. Server side will send just parameter to selected templates.

For example, if you create Windows application, your client can use the following code in order to register a template:

string xmlTemplate = @"<?xml version=""1.0"" encoding=""utf-8""?>" +

@"<toast><visual><binding template=""ToastText02"">" +

@"<text id=""1"">football.ua</text>" +

@"<text id=""2"">$(ru_message)</text>" +

@"</binding></visual></toast>";

await mobileService.GetPush().RegisterTemplateAsync(

channel.Uri, xmlTemplate, "langTemplate");

In this case, client application is registering a template with langTemplate name and with parameter ru_message. The second device might use en_message parameter instead of ru_message etc. It’s needed in order to get message in native language for device’s user. So, all devices will have the same template but with different parameters there.

In the next step, server side should form a message, which will contain the template name and all parameters. It allows Notification Hub to create unique messages for all devices based on registered templates and parameters. In order to prepare server side message you can use already prepared classes. For example, if you use C#, you can use the following code:

TemplatePushMessage mess = new TemplatePushMessage();

mess.Add("ru_message", "Сообщение");

mess.Add("en_message", "Message");

await Services.Push.SendAsync(mess);

Notification Hub will look at every registered template and send a message if template contains one of these parameters.

Jobs

Some applications, like Facebook for Windows Phone, send many notifications during predefined time period. For example, usually at 11 pm. I get messages about upcoming birthdays of my friends. Of course, it’s a good idea to have something on Azure side, which might send notifications on schedule basis and Azure Mobile Services support this feature.

Using Azure Mobile Services, you can schedule any code there. You may set up a single timeframe or create a complex schedule there and you can use Azure Management panel, if you are going to create JavaScript code or Visual Studio – if you are going to create C# code.

In case of JavaScript it’s easy to create something using Sheduler tab. Pay attention that there is a way to create a job, which will run on demand:

JavaScript code may have access to all objects, which we used before, including push object.

In case of C# you need to work with Visual Studio like we did at the previous post and you should create a class, which derives from SheduledJob class. ExecuteAsync method there will allow you to create any code inside.

Custom API

One more interesting thing in Azure Mobile Services is the ability to create a custom API. You can create a set of JavaScript server-side functions using Management panel:

In case of Visual Studio, you need to create a class, which derives from ApiController.

Because you code will be called using standard HTTP protocol, you may use one of the following methods there like GET, POST, PUT, PATCH, DELETE.

Rest API

In the first article about Azure Mobile Services I told that the service will work for any type of platforms and languages because there is REST API support. Of course, I like Windows 8 and Windows Phone applications, so I used ready to use libraries, which encapsulate all work with REST and JSON but you still able to use REST API. Frankly speaking, Microsoft provides libraries for many platforms and languages (like Java, JavaScript, Objective C etc.) but in some cases it’s better to use REST directly. You can find REST API documentation here.

Written by Sergiy Baydachnyy

01/08/2015 at 9:20 PM

Posted in Microsoft Azure

Tagged with

Azure Mobile Services: Visual Studio

with one comment

In my series I used JavaScript backend in order to handle insert operation. Thanks to that I was able to send broadcast notifications to all subscribers. In this example we had small amount of code and using of JavaScript looks reasonable despite of my love in .NET. But in many projects your code might be more complex and you might want to use Visual Studio and C# in order to develop it. Therefore in this post I want to show how to use Visual Studio in order to build our backend.

First of all in order to use C# on the backend, you must select .NET as a backend technology in new Mobile Service dialog.

image

You may use Visual Studio as well to create Mobile Service but I like management panel. I simply got used to use management panel for several years:)

Right now we are ready to use Visual Studio. In the first step we will create project based on Azure Mobile Service template. You need to provide name of your project/solution there.

image

In the second step you need to select some options. You should switch off Host in the cloud checkbox. If you forget to do it, Visual Studio will propose to create a new Mobile Service.

image

Once you click OK, Visual Studio will create a project for you, which contains several ready to use classes like TodoItem, TodoItemController etc. You can use this code in order to deploy TodoItem table to Azure Mobile Service.

I am not going to remove auto-created code but I would prefer my own names for table and columns. So, I will change TodoItem to NotificationData. You can use refactoring tools to change class name. Additionally, I will remove Complete property and change Text to text property. Last changes you may make using JsonProperty attribute as well.

public class NotificationData : EntityData
{
[JsonProperty("text")]
public string Text { get; set; }
}

Because EntityFramework and Web API already have all needed infrastructure for our service, we will concentrate our attention around the following questions:

· How to send broadcast notifications from our code;

· How to set permissions for operations with tables;

· How to create own code, which will handle registrations of new devices;

The simplest question there is sending notifications. You need to open TodoItemController.cs file and modify PostTodoItem method in the following way:

public async Task<IHttpActionResult> PostTodoItem(NotificationData item)
{
NotificationData current = await InsertAsync(item);

WindowsPushMessage message = new WindowsPushMessage();

message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
@"<toast><visual><binding template=""ToastText02"">" +
@"<text id=""1"">football.ua</text>" +
@"<text id=""2"">" + item.Text + @"</text>" +
@"</binding></visual></toast>";
try
{
var result = await Services.Push.SendAsync(message);
Services.Log.Info(result.State.ToString());
}
catch (System.Exception ex)
{
Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
}

return CreatedAtRoute("Tables", new { id = current.Id }, current);
}

You can see that there we used two classes there. WindowsPushMessages allows to create a toast message and ApiServices (Service instance) allows to send the message and put information to the log. Like in case of JavaScript we used ToastText02 template, which contains title and message there. So, we have the same code but in C#.

Let’s talk about permissions. In case of JavaScript we used Azure Management panel to set permissions but in case of C# we need to use attributes there. You need to use AutorizeLevel attribute in order to set the right permissions to methods on Controller class.

[AuthorizeLevel(AuthorizationLevel.Application)]
public async Task<IHttpActionResult> PostTodoItem(NotificationData item)
[AuthorizeLevel(AuthorizationLevel.Anonymous)]
public IQueryable<NotificationData> GetAllTodoItems()

Of course, this approach will work just for table operations but in case of JavaScript you had a chance to set authorization level using Azure Management panel. In case of C# you may set it in WebApiConfig.cs file. Just put the following line of code to Register method:

options.PushAuthorization = AuthorizationLevel.Anonymous;

In our example we didn’t change Registration pipeline but if you want to do it, you can implement INotificationHandler interface.

public class PushRegistrationHandler : INotificationHandler
{
public System.Threading.Tasks.Task Register(
ApiServices services, HttpRequestContext context, NotificationRegistration registration)
{
throw new NotImplementedException();
}

public System.Threading.Tasks.Task Unregister(
ApiServices services, HttpRequestContext context, string deviceId)
{
throw new NotImplementedException();
}
}

Implementation of the interface will be picked up automatically and you may run your own code there.

Finally, in order to test our solution, we need to deploy it. In order to do it just select Publish menu item from context menu and set up all needed parameters:

image

In order to simplify this process you can download Publishing profile from the dashboard already created service

image

Written by Sergiy Baydachnyy

01/06/2015 at 10:44 PM

Posted in Microsoft Azure

Tagged with

Azure Mobile Services: Creating of Universal Application (part 2)

with 2 comments

Interface of our application (continued)

It’s time to implement business logic of our application. Since data classes are not related to specific interface, I am going to use the shared project to create all needed classes. Let’s create Code folder there and DataClasses.cs code file inside. We will create two classes there.

One of these classes should describe our data table in Azure Mobile Service. We need to use table and column names there in order to avoid using attributes or any other mapping approaches. So, our class may look like this:

public class NotificationData
{
public string id { get; set; }
public string text { get; set; }
public DateTime __createdAt { get; set; }
}

The second class is a utility class. I am going to use it as a class for loading out data from Azure Mobile. So, we can use the following code there:

public class DataClass
{
public static async Task<ICollection<NotificationData>> LoadData()
{
MobileServiceClient client =
           new MobileServiceClient("https://test-ms-sbaidachni.azure-mobile.net/");
var table=client.GetTable<NotificationData>();
var query = (from item in table
orderby item.__createdAt descending
select item).Take(100);
var items = await query.ToCollectionAsync();

return items;
}
}

Because we allowed to get data from Azure Mobile for Everyone, we don’t use any keys there. But I am downloading just 100 records from our database. Later you may add one more method which will implement incremental downloading. You can use Skip(n) method there in order to skip already downloaded records: .Skip(n).Take(100).

In order to finish our work with the Shared project, I will create Assets folder there and put logo for my applications there.

Since we already implemented all business logic and our applications allow us to receive notifications, we may finish work with interface of our applications.

In case of Windows 8 application I decided to use GridView control. We need to disable all “selection” and “click” functionality and show messages and dates there. Let’s review my code:

<Page.BottomAppBar>
<CommandBar>
<AppBarButton Label="Обновить" Icon="Refresh" Click="AppBarButton_Click"></AppBarButton>
</CommandBar>
</Page.BottomAppBar>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Image Source="Assets/football.png" Height="36" HorizontalAlignment="Left" Margin="120,30,0,10"></Image>
<GridView Name="myGrid" Grid.Row="1" Padding="120,40,100,80" SelectionMode="None" Visibility="Collapsed">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Width="450" HorizontalAlignment="Left" Height="100" Background="Gray" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding __createdAt}" Style="{StaticResource CaptionTextBlockStyle}" Foreground="Green" Margin="5"></TextBlock>
<TextBlock Text="{Binding text}" Grid.Row="1" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="Wrap" Margin="5"></TextBlock>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<ProgressRing Name="progressBox" IsActive="True" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100" Grid.Row="1" Visibility="Visible"></ProgressRing>
<TextBlock Name="errorBox" TextWrapping="Wrap" Text="Что-то случилось с сетью. Попробуйте загрузить данные снова." Visibility="Collapsed"
HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center"
Grid.Row="1" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>

<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Common">
<VisualState x:Name="Loading">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="errorBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="progressBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Visible" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Loaded">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="errorBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="progressBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Visible" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Error">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="errorBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Visible" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="progressBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>

</VisualStateManager.VisualStateGroups>
</Grid>

I know that it’s bigger than you imagined but it allows to show different parts of our interface based on different events in our application. We can divide this code in three parts.

In the first part we declared application bar control with refresh button there. I am going to use this button to allow user update interface in case user had opened application some time ago and it is still in the memory.

In the second part I declared Grid layout and some controls inside like GridView, Image and several textboxes with different messages. We are going to show GridView or massages based on situation.

In the last part I declared VisualStateManager control which allows to declare several custom states there. We will have three states:

· Loading – data is loading from Azure Mobile services;

· Loaded – data is loaded and ready to show;

· Error – we have problem with internet connection;

Depending on state, we are going to hide and show some parts of our interface.

Finally we need to implement some code, which will set state of our interface and this code will use our utility class in order to download data. I propose to use the following code inside MainPage.xaml.cs:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
LoadData();
}


private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
LoadData();
}


private async void LoadData()
{
try
{
VisualStateManager.GoToState(this, "Loading", false);
var items = await DataClass.LoadData();
myGrid.ItemsSource = items;
VisualStateManager.GoToState(this, "Loaded", false);
}
catch(Exception ex)
{
VisualStateManager.GoToState(this, "Error", false);
}
}

The most important method there is LoadData. We are using of this method in order to move interface to the right state and it allows us to download and bind data as well.

In case of Windows Phone we will have the same code and XAML but I will change GridView control to ListView and I need to change some margins there. So, I will show just a piece of code with some differences there:

<ListView Name="myGrid"  Grid.Row="1" Padding="10" SelectionMode="None" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,10">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding __createdAt}" Style="{StaticResource ListViewItemContentTextBlockStyle }" Foreground="Green"></TextBlock>
<TextBlock Text="{Binding text}" Grid.Row="1" Style="{StaticResource ListViewItemTextBlockStyle}" TextWrapping="Wrap" Margin="0,5,0,0"></TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Therefore, we developed applications for Windows Phone and Windows 8, which allow us to get notifications about football games using Windows Notification Service and these applications can show the latest messages as well.

image

Publishing the applications

In order to publish your applications, you need to change the icons there. It’s the hardest part for developers, so, if you are going to publish the real application, you need ask designers about icons. Right after you changed all default icons, you may create Store packages for Windows Phone and Windows 8 separately. You can make it using context menu by calling Store->Create App Package item. Of course, you need to have access to your Store account and you need to reserve applications names there but we made it in the previous post.

Some time ago, Microsoft required Privacy policy for all Windows 8 applications, which used Internet connection. In case of Windows Phone you needed to create a settings page, which allows user to switch off notifications in your application. Today, you don’t have to do it. Privacy policy is still required but just for applications, which collect and store personal data (we don’t collect anything about users). Notification settings for Windows Phone 8.1 applications will be generated automatically and user can change it in any time using Settings->notifications+actions menu item (it’s strange but your application will appear there just after the first notification only).

Therefore, you may upload your packages, fill description and other fields and submit your applications for review. Usually review takes about 2-3 days but in my case it took about 2 hours.

My applications are available here:

http://www.windowsphone.com/s?appid=ff9b0b08-0a11-4eba-9362-9a023650dcfd

http://apps.microsoft.com/windows/app/fooball-ua-messages/870b8ea4-1385-4193-ab27-9836dd216711

Written by Sergiy Baydachnyy

01/05/2015 at 7:58 PM

Posted in Microsoft Azure, Windows 8, Windows Phone

Tagged with

Azure Mobile Services: Creating a Universal Application

with one comment

Windows Notification Service and Windows Runtime

It’s time to start developing a real application, which will have a user-friendly interface, implement several types of notifications and be ready for the Store. I don’t have experience in Android and iOS development, so I will try to develop just Windows Phone and Windows 8 applications and I will publish them to the Microsoft Store.

In the previous posts, we developed a Windows Phone (Silverlight) application without a specific interface and we used Microsoft Push Notification Service (MPNS) in anonymous mode, which is good for testing only. Today we are going to use Windows Notification Service (WNS), which is supported by Windows Runtime.

Windows Runtime was introduced almost three years ago as a platform for Windows Store applications with Modern User Interface (Modern UI). It was presented as a new, native, object-oriented API for Windows 8, which helps to develop touch-enabled applications for ARM, x86 and x64 devices. At that time Windows Phone supported Silverlight only for business applications and developers had to develop different types of applications for Windows 8 and Windows Phone. Therefore, developers were waiting for Windows Runtime implementation for Windows Phone, and it was announced this year for Windows Phone 8.1. So, today, developers can share code between WP and Windows applications and use many of their features in the common way. One of these features is Windows Notification Service, which was shared between two platforms and substituted MPNS in WP.

In this post, we will use Universal Apps template to develop both types of applications and we will share as much code as possible. We will use WNS in order to send three types of notifications.

image

Before we will start coding, we should configure Windows Application Credentials in our Mobile Service (Push tab) but it requires Store registration. So, if you don’t have a Store account yet it’s right time to create it. In order to make an account you may visit the following site https://devcenterbenefits.windows.com/ and you will be able to get free access to Dev Center dashboard.

If you have an account in the Store, you should go to dashboard and try to submit a new Windows Store application (I know that we haven’t developed it yet). During the submission process, you will reserve application name and provide selling details. But we need the next step, which will help to generate client secret key for our application. Let’s click Live Service site link there.

image

You will be redirected to App Settings page, where you can find a Package SID, Client ID and Client secret.

image

This information is required to send notifications to registered devices. So, copy these keys and put them to identity tab of Media Services.

Additionally, I want to make several remarks here.

First of all, today we have a chance to associate our Windows Phone and Windows 8 applications. In this case they will use the same notification identities as well as many other features. In order to create the association, you need to visit Windows Phone dashboard and try to submit a new application. In the first step you will be able to select the name, which you already reserved in Windows Store. You should click “Associate app” button in order to make association between our Windows 8 and Windows Phone applications.

image

Right after you have reserved names for your applications in Windows Store and Windows Phone Store, you may download all needed information to your Visual Studio project as well. If you forget to do it, you will not be able to test your applications because they will not be able to receive notifications due to wrong package identity. In order to do it you may use the context menu for each of our projects.

image

Server-side for Windows Runtime application

We finished configuring Media Services but in order to enable server-side messages to registered devices we need to modify our Insert trigger. In the previous article, we implemented a simple JavaScript trigger, which was able to send notifications through MPNS. Let’s substitute MPNS to WNS. Additionally, I am going to add more notifications types like RAW and Tile notifications. RAW notifications allow to receive notifications when an application is active and it allows to update content of the application in real time. Tile notifications are used for application Tile update.

Below you can find code, which allows to send Toast notifications, Tile notifications we will add later.

function insert(item, user, request) 
{
request.execute(
{
success: function()
{
push.wns.sendToastText02(null,
{
text1:"Football.ua",
text2:item.text
},
{
success: function (pushResponse)
{
console.log("Sent push:", pushResponse);
}
});

request.respond();
}
}
);
}

When we used MPNS, we called just sendToast method but Windows 8.1 as well as Windows Phone 8.1 allow different presentations of Toast and Tile notifications. In this application, I decided to use ToastText02 template, which will show text1 as a title of notification (single line) and text2 as a body of notification (two lines on the screen). You can use any other format for your applications, which can be found here.

Interface of our application

Right now, we are ready to create our client application. At the first step, we should allow Toast capabilities in our application. We can make it in the manifest file of the application (Package.appmanifest). In order to do it you can use manifest designer (just click the manifest) but you should be very careful because Universal Apps template will not allow to create a single application for both platforms. Instead you will have two projects as well as two applications. That’s why you should make your modifications inside each manifest (inside both projects). Just click the application tab and set Toast capable to Yes.

image

Windows 8 and Windows Phone 8.1 don’t require to create own settings page in order to allow user to switch off/on notifications. Windows 8 will generate off/on option inside Settings charm and Windows Phone supports “notifications+actions” page under Settings menu.

On the next stage, we should add Windows Azure Mobile Services package using NuGet manager. We already did it in the previous posts. In this case, you should do it for both projects. Finally, we are ready to write some code.

We will start with code, which will request a notification channel for our device and will send the channel to our Mobile Services. Because you need to do it every time during the application launch, we will use App.xaml.cs file. By default, this file is shared between Windows Phone and Windows applications. We will not change this behavior because WP and Windows 8 application have the same application model and we will have shared code there.

In order to create a notification channel we will use PushNotificationChannel and PushNotificationChannelManager classes. MSDN says that we should store our notification channel after each request and compare a new channel to the old one in order to avoid sending duplicate to our server-side. However, I decided to avoid this practice. We will get notification channel for our application on every launch event and we will send it to MobileServices at once. We should understand that there might be problem with Internet, so, we will check possible exceptions related to it and, in case of an exception, we will continue to launch our application without any notifications or something else. This type of behavior is justified because we will upload old data on the next stage. So, we will have a chance to notify a user about problem with network. In any case, we cannot use notification channel as a guaranteed way for delivering our messages.

I propose the following method for receiving a notification channel and for registering it in Mobile Services:

private async void CreateNotificationChannel()
{
try
{
PushNotificationChannel channel;

channel = await PushNotificationChannelManager.
CreatePushNotificationChannelForApplicationAsync();

MobileServiceClient mobileService =
new MobileServiceClient("https://test-ms-sbaydach.azure-mobile.net/");

await mobileService.GetPush().RegisterNativeAsync(channel.Uri);
}
catch
{

}
}

Pay special attention that we don’t use application key on client side. So, you need to modify permission for registration script accordingly.

Right now, we can put the method call to the beginning of OnLaunched event handler and it will allow us to receive Toast notifications at once.

image

It’s time to implement business logic of our application but I leave it to the next post.

Written by Sergiy Baydachnyy

11/20/2014 at 8:02 PM

Posted in Microsoft Azure, Windows 8, Windows Phone

Tagged with

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/&quot;,

                    "<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