Sergii Baidachnyi

Blog about technologies

Archive for the ‘Windows 8’ 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

Internet of Things: My first experience with Galileo 2 (part 1)

with 2 comments

Published on MSDN Blog. Please, visit it for more great articles from Canadian DX team.

I didn’t feel so excited since that time, when I bought my first PC – ZX Spectrum. It was a new world, which required strong programming knowledge as well as ability to make research. And today I will open a door to one another new world, where I will try to integrate my programming knowledge with new types of hardware in order to build many new devices. Let’s begin.

First of all, in order to create a new hardware we need to buy some stuff like a board, sensors and wires. Because I have a good experience with Microsoft platform and Visual Studio, I have selected Intel Galileo 2 board, which is supported by Microsoft and it is compatible with Arduino boards, so you will able to find some stuff like sensors, shields, breadboards anywhere. At this time, I don’t have an idea about my future devices, so, I decided to buy a board as well as several starter kits. Finally, I bought my Galileo 2 board, SunFounder 37 modules Arduino Sensor Kit and Sunfounder Project Super Starter Kit.

clip_image002

I used Amazon in order to buy this stuff but you can use any online store. Additionally, I have visited Fry’s Electronics last week and I was too surprised that you may buy a board as well as many of these sensors and components there. There was a huge selection of kits for building own robots, sensors and wires. Probably, there is a special shop in Canada but I am a newcomer in Canada right now. So, please, recommend a good place here and it will help many Canadian developers.

Additionally, you will need a network cable, a microSD card (16 Gb should be enough) and microUSB to USB cable. The last one is used for all modern phones, so it should not be a problem but I forgot to buy a microSD, so I needed to find a nearest Staples in order to buy it. Pay special attention that in order to deploy your application, you need a network cable, which will connect your computer and your board.

Ok, right now, we have a board and some stuff, so we are ready to test the board. In order to use Windows as well as Visual Studio there, you will need to sign a special Windows Developer Program for IoT, which is available here: http://www.windowsondevices.com. You will need to use your Live ID, fill the registration form and right after your application is approved you will get access to Connect site, there you will be able to download all needed software.

In order to set up everything you will need three packages there: WIM image of the operation system, which you will deploy to your board (microSD card); apply-bootmedia.cmd file, which you will use to deploy the operation system; MSI package, which include some tools like Galileo Watcher and Visual Studio integration package.

In order to setup your PC you will need to launch the MSI package and enable Telnet features there. Later we will use Telnet in order to kill processes and get some information from the board. In order to enable Telnet features just go to “Program and Features” in the “Control Panel” and call “Turn Windows Features on or off” window.

clip_image004

Right now it’s time to setup your board. In order to do it you need to deploy Windows image to microSD card. Apply-BootMedia.cmd is able to do it for you. Just run the following command in the Command Prompt window (with Administrator permissions):

apply-bootmedia.cmd -destination {YourSDCardDrive} -image {.wimFile} -hostname mygalileo -password admin

Your card will be ready in 2-3 minutes.

clip_image006

Right now, we are ready to run something on Galileo. So, put your microSD card to the slot on the board, use the network cable to connect your Galileo board and turn on your board. Pay attention that Intel provides a universal power supply unit with different connectors. So you will able to use your board anywhere despite of voltage of the local system.

Usually it takes Galileo 2 2-3 minutes in order to start Windows there. During this process you will see blinking LED, which is marked as SD. When LED finishes blinking, your board is ready to communicate with your computer. The second way to understand that the board is ready – launch Galileo Watcher, which will show IP address of your board, MAC address, name and information about state of your board.

clip_image007

Using the Galileo Watcher you are able to monitor the state of your board as well as to launch some stuff like window in browser, which will show existing processes.

Pay attention that if you will use Visual Studio or Telnet in order to connect your board, you will need to provide the name and password there. We provided our password below and the default name is administrator. But, in many cases, you will need to provide the full name of the user like localhost\administrator or mygalileo\administrator, especially, if your computer is in a domain.

Finally, you may launch Visual Studio and create your first project for Galileo 2.

clip_image009

Microsoft provides a ready to go template, which we will discuss next time. Just try to start it on Galileo. If deployment is successful you will see that one more LED is blinking in infinity loop on your board.

In order to kill the process you will need to start Telnet and use the following commands:

· tlist – in order to see all existing processes

· kill <process ID> – in order to kill selected process

Probably I wrote enough for the first part. In the next article we will try to understand, what is Galileo and how to create a simple scenarios there.

Written by Sergiy Baydachnyy

11/07/2014 at 9:00 PM

Posted in IoT, Microsoft, Windows 8

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

Kinect, Unity 3D and Debugging

with one comment

In this article, I was planning to make additional investigation of Kinect 2.0 SDK but I found a better theme – Debugging of Unity 3D applications using Visual Studio. Because I am not a professional developer in Unity 3D yet, I never thought about debugging of Unity 3D applications. But in the last article, I wrote about my first experience in Kinect and Unity integration and, frankly speaking, I had a headache during preparation of my demo. It happened due to the lack of ability to debug my demo scripts. Of course, Kinect 2 SDK was new for me, so I used many Debug.Log methods in order to understand what was happening with my variables.

I know that Mono Develop allows to debug Unity scripts but I don’t like this tool. So, I did not debug my scripts for some time and returned to this idea only two days ago. I was very surprised that there is an easy way to enable Debugging tools in Visual Studio. In order to do it you need to download and install Visual Studio Tools for Unity.

These tools were created by SyntaxTree team, which was bought by Microsoft in June-July this year. At once Microsoft announced availability of the tools for all developers for free and the first Microsoft version of them was presented in the end of July. The tools are integrated with Visual Studio 2010, 2012 and 2013 versions, so you can use them with older version of Visual Studio.

I have Visual Studio 2013, so I simply installed the package and enabled debugging in my project.

In order to enable debugging in an existing project you need to import package to it. If you install the tools successfully, you will find a new menu item there.

clip_image002

If you create a new project you will be able to add the package right in Create New Project dialog.

clip_image003

The package will add some scripts to your project, which will extend your standard menu. Additionally, the package contains some components that will support communication channel between Visual Studio and Unity.

clip_image004

In my case, I imported the package successfully, so I opened project in Visual Studio in order to start debugging. It was pretty simple, I just put some breakpoints there and clicked the F5 hot key in order to start debugging. Visual Studio switched to the Debug mode and I returned to Unity in order to start my application there. After that, I just clicked Start button in Unity and, finally, I was moved to Visual Studio in order to see a fired breakpoint.

clip_image006

You will be able to click and unclick Play (Pause) button as many time as you want. It will restart your game or just pause it but it will not affect Visual Studio which will stay in the Debug mode. If you want to exit the Debug mode in Visual Studio, you should just click Stop Debugging there.

To summarize, I spent a minute but I got a very powerful tool for my future Unity projects.

Written by Sergiy Baydachnyy

10/05/2014 at 10:30 AM

Kinect 2 and Unity 3D: My first experience

with 6 comments

Several days ago, I got my first Kinect 2 for Windows devices in order to prepare my presentation for Developer Day event in Ukraine together with Dmytro Mindra. Right now, I already have some experience about Kinect and I am going to share it in my blog.

Before we create some code, we will need to download Kinect for Windows SDK 2.0. This SDK is in Public Preview now but it allows to create Windows Store applications (previous version didn’t allow it), so I was happy to install this version of SDK. I found it here: http://www.microsoft.com/en-us/download/details.aspx?id=43661.

Once SDK was installed I was able to review some examples and tools. I would recommend to use SDK Browser, that can be found in the following directory C:\Program Files\Microsoft SDKs\Kinect\v2.0-PublicPreview1409\Tools\SDKBrowser. This is a very useful tool, which will show you the entire SDK structure like tools, examples and link to docs.

clip_image002

I would recommend to use the Body Basic-XAML example in order to understand that your Kinect works fine or you may use Kinect Studio in order to do some experiments with the sensorJ Because my Kinect was working fine I could start to think about some demos.

Kinect is a very powerful device and you can use it in many ways as a sensor for your home robot or as a part of your security system but the most popular way of Kinect usage is for entertainment. It allows to create many good games and many of such games are already available for Xbox. At same time I don’t have any desire to create a game in C++/DirectX and I was trying to find a solution for Unity 3d because it is one of the best game engines and I like Unity 3d.

Some time ago, I heard information about an add-in for Unity 3d but I had to spend much time in order to find it. I used several search systems, then I called Unity 3d guys and finally I found it in a very unusual place – on the Kinect for Windows SDK 2.0 download page. This link is collapsed by default and you need to expand System Requirements section in order to find it.

clip_image004

Pay attention that this add-in will work with Unity PRO version only, because the free version of Unity doesn’t support add-ins. Probably, there is a way to fix it for Windows Store applications because Non-Pro version allows to use add-ins for this type of applications but I will check it later and for now I use a Pro version.

If you download the add-in successfully, you will be able to find the unitypackage file as well as two examples inside of it. We already have a small game, which allows us to kill “friendly green men” with our battle stellar ship and we decided to implement some Kinect ready activities to make killing process funnier.

Finally, we can implement three steps, which will allow us to use our body during the game in killing process.

On the first step, we found our MonoBehaviour that was responsible for movement of our ship and we added some new code to it:

private KinectSensor _Sensor;

private BodyFrameReader _Reader;

private Body[] _Data = null;

This code should be clear but I will describe it. In order to get access to sensor we needed KinectSensor class, which allows to initialize our Kinect and provides needed sources. In our case, we needed access to BodyFrame source, so we created BodyFrameReader variable that we used in order to read data from the source. Finally, we created Body array in order to store our data from the source.

On the next step, we needed to initialize Kinect and open our reader. That’s why we implemented the following code:

void Start()

{

    _Sensor = KinectSensor.GetDefault();

    if (_Sensor != null)

    {

        _Reader = _Sensor.BodyFrameSource.OpenReader();

        if (!_Sensor.IsOpen)

        {

            _Sensor.Open();

        }

    }

}

We initialized the Kinect inside the very familiar method for Unity 3D developers and opened our reader there.

Finally, we realized a method, which was called from Update method of our Behaviour class. This method collected data from the sensor and calculated new position for the ship as well as fire ability:

horizontal = 0;

vertical = 0;

fireButton = false;

if (_Reader != null) {

       var frame = _Reader.AcquireLatestFrame ();

       if (frame != null) {

              if (_Data == null) {

                     _Data = new Body[_Sensor.BodyFrameSource.BodyCount];

              }

              frame.GetAndRefreshBodyData (_Data);

              int idx = -1;

              for (var i = 0; i < 6; i++) {

                     if (_Data [i].LeanTrackingState !=

                       TrackingState.NotTracked) {

                           idx = i;

                     }

              }

              if (idx > -1) {     

                     fireButton =

                        _Data [idx].Joints [JointType.HandLeft].Position.Y > 0;

                     horizontal = _Data [idx].Lean.X;

                     vertical = _Data [idx].Lean.Y;

              }

       }

       frame.Dispose();

}

This code is more complex and Dima said that I should not show it because it’s not optimal but, probably, you will create the same code for your first Kinect application for Unity 3DJ

So, in this code, we used the Reader to grab current (latest) body frame that was needed in order to found bodies data inside. Kinect 2 supports up to 6 bodies, so _Sensor.BodyFrameSource.BodyCount should return 6. Using the latest frame we filled Body array in order to aggregate data for each body in our frame. At this point we finished work with Kinect sensor and tried to analyze bodies data. But, if you have just one ship (in our case we had two) and you don’t have any specific interface for Kinect initialization, you will not know about location of real body in the array. That’s why we were trying to find a specific index of the body of a pilot. Because we used leans as a main control mechanism for our ship we checked every body and we were trying to find LeanTrackingState status. If we find a tracked body we fixed index of this body and recalculated position of the ship as well as the fire ability.

I think that we spent about 30 minutes for this example and our presentation was very funny. If you know Russian, you can find our video there: http://devday.in.ua. And I just cut a short video from our presentation there are two guys (me and Dima) were doing a strange things on the stageJ

In the next article I am planning to integrate Kinect with simple Windows 8 application and will discuss different sources of data.

Written by Sergiy Baydachnyy

10/03/2014 at 10:18 PM

Posted in Kinect, Windows 8

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