Sergii Baidachnyi

Blog about technologies

Archive for the ‘Windows Phone’ Category

Universal Applications: be ready for Windows 10 (part 2)

leave a comment »

In the previous post we started to discuss features and approaches to build Universal Applications. I am going to show that already today you may build applications which will be ready for Windows 10. And today we are going to discuss XAML.

Full Screen and Snap mode

When Microsoft introduced Windows 8, Windows Runtime and Modern UI patterns, there were three things which developers needed to know about applications: all Modern UI applications work in full screen mode; 1024×768 is minimal supported resolution for Windows 8 devices; for resolutions 1360×768 and more Windows 8 allows to show applications in Snap mode with fixed width in 320 pixels. Based on these assumptions many developers designed interfaces for their applications in 1024×768 resolution using these parameters like minimal amount of available space for application. In case of Snap mode, many developers ignored it and tried to avoid to design something for 320×768 resolution. Frankly speaking I didn’t like Snap mode as well. Usually I showed a message like this: “Application doesn’t work in Snap mode. Please, move the application to Full screen mode to continue”. This messages helped me to pass certification.

But everything is changing and Windows 8.1 added some more pixels to Snap mode. Today, default width of Snap mode for Windows 8.1 is 500 pixels. This amount is harder to ignore and that’s more important – Windows 10 allows to run Modern UI applications in window mode like legacy desktop applications.

image

So, if you are going to create the best UX in your application you should think about different resolutions in advance. Windows 8.1 already doesn’t support events which let the user see that application is in Snap mode, instead, Windows proposes the SizeChanged event. This event is related to Page and you can easy get access to page width and height in order to understand the current size and change layout according to it. The event handler can look like this:

void Page_SizeChanged(object sender, SizeChangedEventArgs e) 
{
if (e.NewSize.Width <= 500)
{
. . . .
}
else if (e.NewSize.Width < 1024)
{
. . . .
}
else
{
. . . .
}
}

So in order to guarantee the best UX in Windows 10 you should think about smaller resolutions. But there is a trick: if you already implement application’s layouts for small resolutions, can you apply it for Windows Phone application – I believe, so.

Therefore, in case of XAML and layouts you can think about resolutions only because both platforms support almost the same set of controls.

ViewState manager

Right now, we are ready to change layouts depending on width of the window. So, it’s time to think how to make it.

The best way to change layouts is using ViewStateManager there. You can use it in XAML to define different visual state groups. Each group can contain Storyboard with animations inside. You can use these animations to hide or show some controls, change ItemTemplate, change controls’ properties etc. It’s easy to declare several groups for different resolutions and, thanks to animations, specify different look for each layout.

<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="DefaultLayout">
. . . .
</VisualState>
<VisualState x:Name="Layout500">
. . . .
</VisualState>
<VisualState x:Name="Layout1024">
. . . .
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>

As I mentioned before, you can change Visability properties, assign new ItemTemplate value etc.

<ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemListView" 
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="itemListView"
Storyboard.TargetProperty="ItemTemplate">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource smallItemTemplate}"/>
</ObjectAnimationUsingKeyFrames>

Onc, you defined all needed visual states, you can implement code, which allows to change visual state based on windows size. You can do it in SizeChanged event handler using this line of code:

VisualStateManager.GoToState(this, "Layout500", true);

I believe that we can finish for today but I am going to continue the series and next time we will discuss DPIs and images.

Written by Sergiy Baydachnyy

03/11/2015 at 6:16 AM

Universal Applications: be ready for Windows 10 (part 1)

leave a comment »

Several Days ago Microsoft made a first look at Windows 10 App platform. Of course, it’s great to have one developer platform and one core but we still have two months before Build. Therefore, many developers wonder, if they can do something right now to be ready for Windows 10. That’s why I decided to make a series of posts about Universal Applications to help developers start porting their applications right now. In order to do it I am going to describe several topics, which are most important for Universal application development for Windows 8.1 and Windows Phone 8.1. So, let’s start with templates and directives.

Universal Apps Template

Since Windows Phone 8.1 announcement developers got a chance to use Windows Runtime for both platforms. It allows to use the same application model, the same set of controls, the same async/await patterns etc. Of course, there was partial support for Windows Runtime since Windows Phone 8.0 but there was no chance to forget Silverlight and use Windows Runtime only. Windows Phone 8.1 brought Windows Runtime to the new level and developers may forget about Silverlight.

Therefore, developers got a chance to develop applications for both platforms with minimum amount of work. Of course, you still need to compile your application for Windows Phone and Windows separately and you need to upload two (or more) packages to the Store but, in many cases, you may use the same code and it relates not just to business logic but to interface as well.

In order to help developers get better experience there, Microsoft introduced Universal Apps template in Visual Studio (Visual Studio 2013 Update 3 and later), which helps to create applications for both platforms at the same time.

clip_image002

In fact, when you are creating applications using this template, Visual Studio is creating three projects: Windows Phone project, Windows 8 project and Shared project.

clip_image003

The idea is very simple. All things that you are adding to the Shared Project will be precompiled to Windows and Windows Phone projects. Therefore you can put there common resources, business logic and XAML pages, if you believe that they are common for both projects.

Many developers believe that it’s all that you need to know about existing Universal Apps template and that the best way to make universal applications is creating business logic in a Shared project and different pages for Windows Phone and Windows. But this is not true and this approach will not help you to be ready for Windows 10.

Directives

If you are going to make real Universal applications you need to know how to build universal pages and page logic as well. So, I will start with directives, which should help you to tune your code for different platforms.

Of course, Windows Phone and Windows 8 have some differences. For example, Windows Phone supports just buttons and menu items in applications bar but Windows can present any containers there; Windows Phone contains hardware or software emulated back button but Windows doesn’t and so on. So, from time to time you need to create code snippets just for Windows Phone or Windows. You can do it using #if…#endif directive. It’s possible thanks to WINDOWS_APP and WINDOWS_PHONE_APP constants. Of course you can define your own constants but I recommend to use these ones because it should be clear for many developers and Visual Studio Intellisense mode already supports possibility to switch between two platforms based on these constants.

clip_image004

So, if you are going to create platform specific code, you can use the following lines:

#if WINDOWS_PHONE_APP

//your code

#endif

Next time I am going to discuss common XAML pages for both platforms.

Written by Sergiy Baydachnyy

03/10/2015 at 2:37 AM

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

Dev Center Benefits: How to join

with one comment

New life – new developer account in Microsoft Store.

I just moved to Vancouver, BC, so I decided to open my own account in order to publish some Windows Phone and Windows 8 applications. Today, you can pay $20 and get unlimited account there. But from the one hand, I still don’t have a local bank account in Canada, and from the other hand I already heard about a program, which provides some benefits for new developers, who don’t have Store account yet. That’s why I decided to start with https://devcenterbenefits.windows.com/ site.

As you can see, according to the program, every developer has a chance to get many benefits from Microsoft like consulting, priority support, gift cards etc. These are very cool benefits because thanks to them, every developer has a chance to increase quality of his applications as well as get some tools for promo. Probably, later, I will share my experience about each of these benefits but right now I found that I am able to get Free Dev Center account.

image

Of course, I clicked “Join Now” at once and passed several registration steps there.

In the first step you need to login with existing Live ID or to create a new one.

image

At once as you logged in, you need to accept the program agreement and click “Accept & Continue”.

image

In the next step you are able to submit links to your application in order to get upgrade to the next level of the Dev Benefits program. Because I just wanted to create a new account I skipped this step. You will be able to add your applications at any time, later.

image

Next step allows you to help Microsoft to understand who you are and what you are going to do on Microsoft platform. You can answer these questions or just skip this step.

image

Finally, my Dev Benefits account was created and I got access to my offers including free developer account.

image

Pay special attention there that in order to redeem your registration code, you need to agree that you will publish your first application in 90 days. So, if you are not ready to build your application right now, don’t click the button. If you redeemed you code but didn’t publish the application your offer could be expired (but I didn’t have a way to check it).

Therefore, I spent about 3 minutes in order to get my registration code. Additionally, I spent 2-3 more minutes in order to create my Store account using this code. And CREDIT CARD WAS NOT REQUIRED!

Written by Sergiy Baydachnyy

11/06/2014 at 4:55 AM

Posted in Microsoft, 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

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