Tech Blog

Jay's Technical blog

Nokia Create – Submission Tips

23 October 2013
Jay Kimble

[WARNING! This is an archived post and as such there may be things broken/missing here.. you have been warned.]

I just wanted to fire off a quick post on entering the Nokia Create contest as there are a few things that can get you.

First of all, you will need to do a video of your app. It must be less than 2 minutes long. If you are doing the NFC Mission (which I did), you’ll need to demo outside of the emulator (since the emulator doesn’t support testing NFC). We filmed my app’s demo at a recent community event (where someone else had a Lumia 1020). My video was (of course) slightly too long, so I had to edit it. I bought Magix Movie Edit Touch for Win8 which worked great for me; it allowed me to remove some extraneous video and apply transitions making things seem smoother. There are some limitations on what video formats are supported (so pay attention.. .MP4 is what I used).

Assuming that your app is already in the store, you will need to fill out the submission form. When it comes to uploading the video, upload the file to skydrive, and get a read-only link to the file (don’t waste your time trying to upload video, as it must have a size limitation of some sort as I tried this 3 times and failed). I tried to do this with DropBox first, but for some reason it told me that the file format was wrong.. Other cloud-based file sharing services may work, but I know that SkyDrive works.


Socket Communicator Intro

17 October 2013
Jay Kimble

[WARNING! This is an archived post and as such there may be things broken/missing here.. you have been warned.]

With my Proximity Helper (intro post here) I quickly discovered that socket communications are a little more involved. After searching around I found a couple extensions methods in the “big complicated wp proximity sample on MSDN” (the code I have criticized as being way too complex for a sample app).

Background

The reason why sockets are a little more complex is because when you are reading from the socket’s stream, you need to tell it how many bytes you want to ready. The easy answer around this is that when you are writing to the stream you pass the size of the data you are writing to the stream first, so when you are reading data, you first read how big the next set of data is. I say data here, because you could be reading a byte array or a long or a double or a date, etc. This also means that as you are reading things need to stay in the proper order (you have to read things in the same manner they are written… so if I write a byte, long, and a byte array, then I need to read those things back in the same order from the other phone).

Anyway, the methods I grabbed have to do with writing a uint, reading a uint, writing a int, reading a int, writing a string, and reading a string. Length of a string is stored as a uint.. so my intention for my apps is to write a JSON or XML string to the socket stream and reading a string (on the other side). This makes things fairly easy to send structured information back and forth. To make things easier for me, I put everything into 2 methods (one for reading and one for writing).

Setup

Setup is easy. If you are using my ProximityHelper and set it up using the intro post, then you are done already (you already copied the necessary class). If not then head to the ProximityToy’s respository, and get the latest code (or navigate to the “ProximityToy\Helpers” folder online). The file you need to add to your project is the “ProximityToy\Helpers\SocketCommunicator.cs.” Once you’ve done that you are ready to go.

Code.. Show Me the Code

First of all you will need to instantiate a SocketCommunicator, and it’s easy to do that. Simply do this:

// If you are using the ProximityHelper you could replace the "socket" argument
/// with "ProximityHelper.Default.Socket"
var socketCommunicator = new SocketCommunicator(socket);

You are now ready to communicate. BTW, SocketCommunicator implements IDisposable so when you are done with it you will want to call “socketCommunicator.Dispose” or use it in a using like this (this is great for quick data exchanges):

using(var socketCommunicator = new SocketCommunicator(socket)) {
// Communication code goes here
} // Dispose is called when execution reaches here

Let’s see how we would send a uint and a string:

int someInt = -1;
UInt32 myUInt = 100;
// Single API call for all the supported types
//(only Int32, UInt32, and String are currently supported)
// send Int32
await socketCommunicator.SendAsync(someInt);
// Send UInt32
await socketCommunicator.SendAsync(myUInt);
// Send String
await socketCommunicator.SendAsync("Some text value");
// Send a json string
await socketCommunicator.SendAsync("{'id':1, 'name':'Dev Theologian', 'isValid':true }");

By sending json, you can see how we could basically get every type of covered, and even send complex types.

Now we need to see how to read all this stuff back in:

var someInt = await socketCommunicator.ReceiveAsync<Int32>();
var myInt = await socketCommunicator.ReceiveAsync<UInt32>();
var myMessage = await socketCommunicator.ReceiveAsync<String>();
var jsonString = await socketCommunicator.ReceiveAsync<String>();
// Next steps would be to either deserialize the json or parse and read the values

Remember after you are done communicating to make sure that you call Dispose on your instance of the SocketCommunicator class.

I also expose the DataReader and DataWriter instances that are ultimately being used, so if you want to do something outside of what my utility exposes, you can of course interact with these objects.

Finally, just as a reminder, you can get the single class you need right here: SocketCommunicator.cs.


WP8 Proximity Simplified

17 October 2013
Jay Kimble

[WARNING! This is an archived post and as such there may be things broken/missing here.. you have been warned.]

This blog post will cover the setup of my ProximityHelper class in your apps and help you implement the various scenarios for making proximity connections. You may want to read my introductory post on proximity and WP8 (which also includes my reasons for creating this “mini” library).

My class makes it easy to set up peer-to-peer (bi-directional) socket connections without having to implement the glue necessary to get the connection off the ground. It handles both the scenarios where you want a tap connection and the ones where you need to browse for a connection.

Setup

Setup is fairly easy. Go to the respository for Proximity Toy and grab the latest files. You need to copy the ProximityResources.* files from under the “ProximityToy\Resources” folder. Additionally copy the “ProximityToy\Helpers” folder  (and subfolders) to your the project (this will get the ProximityHelper class AND the SocketHelper class which will be covered in another blog post; it will also get the UI components that we use to connect to a client during a “polling for clients” scenario). Finally you need the “Coding4Fun.Toolkit.Controls” library from Nuget (we use this to display dialogs in your app).

Implementing Scenarios

If you look at Proximity Toy you see that I have 3 different scenarios. These are roughly the scenarios we need to implement. Proximity Toy uses the words “client” and “server” which is the not best choice of words I have for what is happening. A “server” either polls or initiates the “tap.” The “client” responds to a connection request (initiated by one of these methods). These are not the best uses of the words as once the “conversation” is initiated then the both sides can send and receive asynchronously to the other side. [Maybe “initiator”/”responder” is a better set of names].

Connect (Client) scenario

The “Connect (Client)” sets up a situation where one phone is really listening for a connection and will respond to the connection (client responds to a connect requests). Proximity Helper will actually prompt the user to make sure it’s OK to connect to the other phone (it also identifies the “DisplayName” which is provided to ProximityHelper by “server” phone). You initiate this scenario in code like this:

// In your code make "Client Polling" something meaningful to the other user (like a user name for instance)
ProximityHelper.Default.DisplayName = "Client Polling";
// false below indicates that this is not a server (so monitor for connections)
var result = await ProximityHelper.Default.GetConnectionAndSocket(false);
if(result) {
// ******************************************************
// Do your communication here using ProximityHelper.Default.Socket
// ******************************************************
}
// At some point when you are done with the connection, do this to close it
// NOTE: this might not be in the same routine, just make sure you close the connection before you exit
ProximityHelper.Default.CloseConnection(true);


Connect By Tap scenario

The “Connect By Tap” sets up an NFC initiated (2 phones tapping) connection. In the conversation, the phone using this setting is the “server.” You call code that looks like this (it’s very similar to the last example):

// Again, make "Server Non-Polling" something meaningful to the other user (like a user name)
ProximityHelper.Default.DisplayName = "Server Non-Polling";
// The first parameter (true) in the signature below puts the system in "server" mode where NFC is on, and
// we are awaiting some event that makes this phone aware of a client
// The second parameter (false) tells the Helper that we don't want to poll for clients. If this phone doesn't
// support NFC then this setting will be automatically toggled to true to poll
// (Remember our goal here is to dumb down the mechanism and make it easy to create a connection)
var result = await ProximityHelper.Default.GetConnectionAndSocket(true, false);
if (result)
{
// ******************************************************
// Do your communication here using ProximityHelper.Default.Socket
// ******************************************************
}
// After you are done communicating, close the connection (and the communication) down.
// NOTE: this might not happen in this routine
ProximityHelper.Default.CloseConnection(true);

 
Don’t forget that if the phone doesn’t have NFC and you put it into non-polling server mode, we will still poll because non-polling server mode doesn’t make sense on a phone without NFC.

Connect (Polling Server) scenario

The “Connect (Polling Server)” does everything that the last one does except that it also sets up to poll for “clients” to connect to when it finds one (or more) it will prompt (via a dialog using the ConnectPrompt user control in “Helpers\UI”) the user for a “client” to try a connection with. Once a “client” has been selected the “client” phone will prompt if it’s ok to connect, and if it is then a socket is retrieved. The code to do this looks like this (if you’ve been paying attention it should be easy to guess what it looks like):

// Again, make "Server Polling" something meaningful to the other user (like a user name)
ProximityHelper.Default.DisplayName = "Server Polling";
// The first parameter (true) in the signature below puts the system in "server" mode where NFC is on, and
// we are awaiting some event that makes this phone aware of a client
// The second parameter (true) tells the Helper that we want to poll for clients.
//
// BTW, in most cases this is what you will want to do for the server
var result = await ProximityHelper.Default.GetConnectionAndSocket(true, true);
if(result)
{
// ******************************************************
// Do your communication here using ProximityHelper.Default.Socket
// ******************************************************
}
// After you are done communicating, close the connection (and the communication) down.
// NOTE: this might not happen in this routine
ProximityHelper.Default.CloseConnection(true); // Note: true clears the list containing available clients

 

Client Tap scenario

There is also a fourth scenario that is hidden from the UI where we handle an NFC Tap for connection. In this last situation what happens is that the app on one phone is set in one of the “server” modes, and the other phone is not running the app; when the phones are tapped the phone not running the app will prompt the user to open the app or ignore; when they open the app, it launches with a querystring to your main page. We won’t go into the deep details on this, but ProximityHelper can respond to this type of situation and will automatically set up the connection for you. In most cases you want to respond to a tap and instantly get a connection. Here’s the code for that:

private async void handleTap(NavigationEventArgs e)
{
// We still set the DisplayName
// (by now you should know that you want this to be something that is meaningful)
    ProximityHelper.Default.DisplayName = "Client Tap";
// We pass this routine the NavigationEventArgs as well as a bool value.
// A false for the the bool value indicates we want to just detect that we got the
// tap QueryString.
// A true here indicates that if there was a tap Querystring to go ahead and set up
// a connection           
// True is your most likely value
    var wasTapConnection = await ProximityHelper.Default.DetectTap(e, true);
if(wasTapConnection)
    {
// ***************************************************************
// Do your communication here using ProximityHelper.Default.Socket
// ***************************************************************

										
// At some point when you are done communicating, do this to close down the connection
        ProximityHelper.Default.CloseConnection(true); // true indicates clearing list of
// available clients
    }
}

Customization Opportunities

I did want to mention again that if you don’t like my Prompt for client classes you can make changes by editing the xaml of the “Proximity\Helpers\ProximityUI\ConnectPrompt.xaml” file. The big thing to remember is that we are using a little bit of XAML binding (nothing too tricky). Basically we bind the ClientList to the ItemSource of the peerList control (it’s a listbox in our example, but it could be a different type of control entirely if you like); This the ClientList collection includes an IsSelected value that we use to set visibility (using a Converter), so you can use the same thing. Text blocks in the individual rows are bound to the DisplayName property.

Additionally all the static text is stored in the “ProximityTool\Resources\ProximityResources.resx” file. It is also localizable as a result.

Final thoughts

You now have a library that will make things simple for making Proximity style connections. You are ready for my SocketHelper discussion (look for it later today or early tomorrow). [If you are impatient you can dig into the getData and sendData methods in the codebehind of the MainPage.xaml file to see how this works]. Again the sample project (and helper files) can be found at the Proximity Toy’s Repository.

Proximity and WP8 - Introduction

16 October 2013
Jay Kimble

[WARNING! This is an archived post and as such there may be things broken/missing here.. you have been warned.]

About 3 weeks ago, I decided to add what I called “NFC” to my WP8 Friend GPS App (currently called “Where U @?”, but with the next release will be called “Friend Pilot”). This started a journey for me where I had to wrap my head around the whole Proximity library. What I found was that the topic is somewhat confusing. It is not helped by the samples that are out there from Microsoft. I mean there are good examples, BUT those examples assume the type of interaction you are looking to create use BOTH MVVM and IAsync handlers (the former I can follow, the latter hurts my brain, and for the person just learning the mountain is pretty high just to learn how to use the Proximity library). [The one talk I found on the topic using the aforementioned complex/advanced code didn’t help with the reference to “magic happens” (which in his case meant that you tap and things just automatically happen for you.. this is untrue.. you have to call things to make “magic happen”, so therefore it’s not magical to the developer)].

In this post I want to give some background behind Proximity so you can understand what is going on. I will follow this up with a post on using my ProximityHelper class, and then will come back and give a few more specifics on Proximity. Essentially I feel the topic has been covered, but doesn’t really lend itself to the beginner or even intermediate developer. I believe that much of the discussions here will also be helpful for Windows Store (C#/VB) development as my perusal of the WinRT framework shows the same Proximity classes.

My Goal

For me I wanted a simple interaction, while running my app on 2 phones (that have NFC), tap them together and exchange information. Additionally I wanted to have some way for a device without NFC to be able to connect and make an exchange of info as well (but I wasn’t sure this was possible originally). I suspect that this is what most people want to do.

Background

First of all, Microsoft’s ProximityFinder class (the heart of the ProximityLibrary) actually combines a number of technologies together into a single API (NFC --if available, Bluetooth, and regular 802.11x Wi-Fi). You don’t need to be a guru with any of these technologies. It just works (when you get everything set up and you don’t need to worry about the underlying technology being used). BTW, you do use this class in different ways to get a connection based on what you are trying to do (like if you are making your phone available for a connection or if you are actively looking for a connection).

Second, you need to understand that NFC is really just there to set up a connection on one of the other technologies. NFC is the “tapping” part of the exchange, but after that everything happens over either Bluetooth or 802.11x Wi-Fi.

Thirdly, once you make a connection you are given a socket (specifically a “StreamSocket”). At this point you have to implement your own protocol of sorts (which if that sounds hard.. it can be.. As a result of this I created a SocketHelper class that really grabs some of the code from one of the Microsoft Samples).

Finally, one of the side benefits I found out was that once you get things set up that once you set one phone up to connect, NFC can be used to both launch your app on the other phone AND create the connection. (This is very cool!)

More on NFC

Some of you may be wondering about NFC at this point. You may have looked at a sample and it looks like you could communicate between two devices, etc. The reality is that you can communicate with NFC this way, but the devices have to remain very close. Ultimately, I think NFC is best used for short messages between 2 devices where 1 way communication is all that you need. I am admittedly still just figuring out NFC, and there are topics like writing to an NFC tag, that I have yet to really press down on. I am planning an NFC helper as well..

Sample App

I wrote an app as a sample app to test all this out. It’s called Proximity Helper and (if it passes certification) should be in the Windows Phone Store today. It let’s you test out various scenarios with my library. It does talk about having a “client” and a “server” phone, but this isn’t entirely accurate. In my app’s case communication is done in a one way fashion. In reality Proximity allows for 2 way communication. If you want to look to see what all I am doing you can, of course, go look at the source for my sample at it’s repository.

Final Thoughts

This should lay a decent ground work for you to understand Proximity. I will be following this up with a couple more posts. One on how to use my ProximityHelper in your projects to start the communication between 2 apps; one on my SocketHelper and ways you can use it to create a simple protocol for communicating between 2 apps (hint: I’ll be using JSON strings); and finally a post on the technicals of Proximity.. how it works, etc.


WP8 App/Page Base Navigation Classes

15 October 2013
Jay Kimble

[WARNING! This is an archived post and as such there may be things broken/missing here.. you have been warned.]

On my utilities page, I need to document a few of the items. The next one up is my App/Page Base Classes which you can get here at it’s repository.

Background

I created this set of classes in response to a DVLUP challenge criteria (Fast App Switching). The main reason I created these was because I wanted to be able to easily handle the various types of navigation to my pages with minimal thinking on my part. With Fast App Switching, you detect that via the Application_Activated event in the application (it gets passed to you via an event argument object). For me the best solution was to indicate this via a property on the application, and then I needed to remember to clear that property once I had responded to it. This last part was what spawned the new mechanism. Essentially, I split the page’s OnNavigatedTo method into 3 separate methods (that need to be overridden in child pages). The 3 methods are:

  • OnNormalNavigatedTo – a normal page-to-page navigation (or app launch) where you need to do an initial load of data
  • OnResumedFromTombstone – indicates that the page is being launched after a tombstoning situation (where you need to reload the page’s state
  • OnFastSwitchedTo – indicates that the page is being launched after returning from the OS, but nothing needs to be reloaded

All of these methods are passed a single argument of type: NavigationEventArgs which is the normal argument passed to the OnNavigatedTo Event. You can of course override the OnNavigatedTo event (and remember to call base.OnNavigatedTo(e) so that the new overrides get called.

Installation

There is a bit of work to wire all this up. First of all you need to grab the 2 new class files and drop them into your project. Next go ahead and compile the project (BTW, these classes MAY also work in WP7 projects). Now you need to wire up the application class. You need to do 2 things.

Set the App.xaml.cs class to inherit from DTNet.StateAwareApplication instead of Application. That will look something like this:

namespace MyProject
{
publicpartialclass App : DTNet.StateAwareApplication
    {


Additionally, you need to change the Application_Activated override method a little. It should look like this

protectedoverridevoid Application_Activated(object sender, ActivatedEventArgs e)
        {
base.Application_Activated(sender, e);
// Add any additional code you need in this event here
        }


Next you need to modify the app.xaml file by changing the base class. You probably have something that looks like this:

<Application
x:Class="ProximityToy.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
<!--Application Resources-->
<Application.Resources>
<local:LocalizedStringsxmlns:local="clr-namespace:ProximityToy"x:Key="LocalizedStrings"/>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching"Closing="Application_Closing"
Activated="Application_Activated"Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>

 

You will need to add the DTNet namespace and change the “<Application” (or “</Application”)  to “<dtnet:StateAwareApplication “ (or “</dtnet:StateAwareApplication”). To convert the above xaml it would look like this:

<dtnet:StateAwareApplication
x:Class="ProximityToy.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:dtnet="clr-namespace:DTNet">
<!--Application Resources-->
<dtnet:StateAwareApplication.Resources>
<local:LocalizedStringsxmlns:local="clr-namespace:ProximityToy"x:Key="LocalizedStrings"/>
</dtnet:StateAwareApplication.Resources>
<dtnet:StateAwareApplication.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching"Closing="Application_Closing"
Activated="Application_Activated"Deactivated="Application_Deactivated"/>
</dtnet:StateAwareApplication.ApplicationLifetimeObjects>
</dtnet:StateAwareApplication>

See how event the resources change. This is all that needs to be done to the application file.

You need to make similar changes for every page. Here’s a sample Xaml page that (with nothing in it):

<phone:PhoneApplicationPage
x:Class="ProximityToy.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait"Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Gridx:Name="LayoutRoot"Background="Transparent">
</Grid>
</phone:PhoneApplicationPage>

We need to make this page reference the base class of the DTNet.StateAwareNavigationPage. We’ll do this just like we did for the App.xaml by adding the namespace reference and changing every occurrence of “<phone:PhoneApplicationPage” or “</phone:PhoneApplicationPage” to “<dtnet:StateAwareNavigationPage” or “</dtnet:StateAwareNavigationPage.” Here’s the xaml from above fixed:

<dtnet:StateAwareNavigationPage
x:Class="ProximityToy.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait"Orientation="Portrait"
shell:SystemTray.IsVisible="True"
xmlns:dtnet="clr-namespace:DTNet">

										
<!--LayoutRoot is the root grid where all page content is placed-->
<Gridx:Name="LayoutRoot"Background="Transparent">
</Grid>
</dtnet:StateAwareNavigationPage>

(the above example only had 2 text changes plus the namespace reference, but if you may have more references to “phone:PhoneApplicationPage” you will have to change them, so be aware).

Next you make the codebehind’s (aka PAGE.xaml.cs file) class derive from DTNet.StateAwareNavigationPage. This is pretty easy. You’ll also want to add the 3 new method overrides. It will look something like this:

// Using above this line
namespace MyProject
{
publicpartialclass MainPage:DTNet.StateAwareNavigationPage    
    {
protectedoverridevoid OnFastSwitchedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
        }
protectedoverridevoid OnResumedFromTombstone(System.Windows.Navigation.NavigationEventArgs e)
        {
        }
protectedoverridevoid OnNormalNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
        }

										
        // more code follows

 

Finally you will want to take the OnNavigatedTo Event (in your code) and remove the code placing it into the appropriate methods (you will probably create a method with the common code to reduce duplication of code). Finally delete the OnNavigatedTo Event (or at the least add a line that routine to call the base.OnNavigatedTo routine).

Just in case you missed this point, you do the page changes to every page you want to enable this functionality in.

Admittedly it is a lot of work for an existing project, but for a new one it’s not that bad. I have been meaning to create templates for this, but have never really had the time. Anyway, that’s it. Let me know what you think…

Just a reminder the 2 classes can be found on project’s repository.