Using the Windows Phone Runtime to mix C++ and C# code

In Windows Phone 7,  you will typically define your UI in XAML and write the code in C#. If you’re an advanced XAML coder, you might want to harness the power XAML bindings to limit the amount of code you’ll have to write, and define as much as possible in XAML. If you’re a game developer, you might opt for the XNA framework, in that case you UI will be written from scratch. In any case, regardless of the UI framework you decide to use, your business logic will be coded in C#.

The reason why C# is required comes from the constraint that in WP7, your application is confined run on top of the CLR (Common Language Runtime). The CLR concept is very similar to a Java virtual machine :  the code is converted to an intermediary language that the virtual machine will execute. The CLR environment is commonly called the “managed” mode. The managed mode comes with many great advantages, most notably garbage collection and reflection.  C# is a managed language.

That changed in Windows Phone 8! In addition to the managed framework, developers can write in “native” code. Native code, in comparison with managed code, does not run on top of a virtual machine, but is compiled directly into machine code. As you might expect, native code typically execute slightly faster than managed code. On WP8, native code is written in C or C++.

It is possible to glue pieces of native code with pieces of managed code, thanks to the Windows Phone Runtime framework. The framework takes care of the magic required to convert objects across managed and native runtimes. This Nokia developer wiki gives a quick tutorial how to get started with the Windows Phone Runtime, while this article C++ support from Windows Phone 8 goes into deeper details.

There are some limitations how one passes objects back and forth between managed and native runtimes, and while the “Windows Phone Runtime Component”  code template shipping with Visual Studio provides all the necessarily plumbing to call a Native object from a Managed object, it may not be that obvious how to call a managed object from a Native object. For example, when a developer needs to call from C++ the functionality only provided by  .NET, like modifying live tiles, send a SMS, … The same wiki article provides a solution for such a scenario.

Of course, it’s not because you can that you should!  Stick with C#, unless you really need that little extra speed improvement. Or if you have a C++ library that does a great job and just do not want to convert it to C#: that would be such a waste of your time.

 

 

Here + Leap Motion

You might have heard from the tech news outlets about the Leap Motion. If you haven’t yet, you will soon. It’s a black box about half the size of an average mouse (computer, not actual) that sits on your desk and tracks the 3D movement of your hand (actual, not computer). Essentially, it’s like an XBox Kinect but instead of tracking limb movements, it tracks fingers. These devices are being released mid-July but the here.com team were lucky enough to get into the developer preview program so that we could integrate the Leap with here.com.
Continue reading

Hot stuff: Nokia Asha design guidelines!

Want to know how the Asha UI looks like and read the UX documentation? Well, aren’t you lucky: here’s the link!

The Nokia Asha design guidelines provide a comprehensive set of UI component descriptions and UI patterns. For app icons, templates and guidelines are of course included. And to make things as simple as they can get, there’s also a UX checklist.

Stay tuned for more updates on the Asha UI in this blog. And don’t forget to check the Event calendar for Asha UI webinars!

Happy developing,
Sanna

Creating Asha Web Apps with Brunch and Jade

Asha web apps?

Asha web apps are a lightweight application development framework for creating apps for low end Nokia devices (Asha series and earlier). While JME is the most popular technology for creating apps for Asha, web apps are a reasonably quick and convenient way to expose content on the web – basically, your garden variety front ends for restful services, spiced by some simple navigation.

Since Asha devices don’t have local javascript execution, javascript is executed on proxy server. “Normal” web pages execute all javascript on the proxy, but Asha web apps provide some “shortcuts” for doing simple DOM manipulation (add/remove css classes, set values in input fields) without the proxy roundtrip. Check out “MWL” library for details.

Standard workflow

Normally, you use Eclipse to develop and test Asha web apps. Nokia provides the “Nokia Web Tools” IDE for this; it’s a rather mainstream Eclipse based IDE, spiced with webkit based “local” simulator (that runs javascript locally), and the “cloud” simulator that runs Javacript on the real Nokia proxy servers (but still renders the DOM on the webkit based simulator).

While this is fine for most web developers, there are lots of us relentlessly looking to optimize our workflows, to make it little more efficient, little more fun (or more tolerable, depending how bad an aversion you have for Javascript and HTML) and little more readable and maintainable.

For this kind of developer, there are tools like CoffeeScript, Brunch, Jade, SASS, LESS, HAML. In this exposition we’ll use CoffeeScript, Brunch and Jade.

CoffeeScript is a language that compiles to idiomatic and readable/debuggable JavaScript. It makes producing JavaScript more tolerable for people used to modern languages without semicolons, `function` keywords
and a selection of other nastiness that plagues JavaScript.

JADE is a language that compiles to HTML.

This Jade:

        doctype 5
	html(lang="en")
	  head
	    title= pageTitle
	  body
	    h1 Jade - node template engine
	    #container
	      if youAreUsingJade
	        p You are amazing
	      else
	        p Get on it!

Compiles to this html:

<h1>Jade - node template engine</h1>
<div id="container">
 
You are amazing
 
</div>

As you can see, this makes it easier to “see forest from the trees”, as the eye is not misdirected by stream of redundant characters and endless <div>’s.

Brunch is an “assembler” for HTML5 applications. It picks up all the pieces you have (CoffeeScript files, JADE templates, etc.) and produces a runnable web application out of that. It can watch the files on the background, compiling CoffeeScript files to JavaScript the second you save them, running unit tests immediately, refreshing the browser in real time etc.

We use Brunch as the “skeleton” of our Asha web application.

Getting started

Prerequisites: This flow has been tested on Linux and Windows. Have to install Node.js, git, the usual stuff every self respecting web developer has set up on day one. Anecdotal evidence suggests it’s a good idea to compile Node.js from source instead of using the packaged versions, if you are lucky enough to be on Linux.

We clone the basic scaffolding from github and install the dependencies:

 

$ git clone git@github.com:vivainio/awa-brunch.git awa-helloworld
$ cd awa-helloworld/
$ npm install
npm http GET https://registry.npmjs.org/javascript-brunch
npm http GET https://registry.npmjs.org/css-brunch
npm http GET https://registry.npmjs.org/uglify-js-brunch
npm http GET https://registry.npmjs.org/clean-css-brunc
.. etc ..
This install Brunch, CoffeeScript compile and lots of other packages with npm.

Let’s take a look at the project structure:


ville@ville-tp:~/p/awa-helloworld$ tree app
app
├── assets
│   ├── config.xml
│   ├── icon.png
│   ├── index.html
│   └── s40-theme
│   ├── css
│   │   ├── s40-theme.css
│   │   ├── single_landscape.css
│   │   └── single_portrait.css
│   ├── images
│   │   ├── arrow-close.png
│   │   ├── arrow-open.png
│   │   ├── back_40x40.png
│   │   ├── button-bg_40x40.png
│   │   ├── close_40x40.png
│   │   ├── grid_40x40.png
│   │   ├── option-menu_titlebar.png
│   │   ├── refresh_40x40.png
│   │   ├── search_40x40.png
│   │   ├── tab_bg.png
│   │   └── title-bar.png
│   └── js
│   ├── s40-theme.js
│   └── screensize.js
├── index.jade
├── README.md
├── templates
│   └── mainlist.jade
├── testCs.coffee
└── testJs.js

 

Now, we start “brunch watch” that compiles the application in real time as we edit the files, and for added convenience launches a webserver serving on :3333:


ville@ville-tp:~/p/awa-helloworld$ brunch watch --server
26 Apr 22:03:48 - info: application started on http://localhost:3333/
26 Apr 22:03:48 - info: compiled in 115ms
26 Apr 22:03:49 - info: compiled in 206ms

 

The resulting application that we can deploy, or preview in browser, gets generated in awa-helloworld/public directory:

 

ville@ville-tp:~/p/awa-helloworld$ tree public
public
├── config.xml
├── icon.png
├── index.html
├── javascripts
│   ├── app.js
│   ├── templates.js
│   └── vendor.js
├── js
│   └── templates.js
└── s40-theme
├── css
│   ├── s40-theme.css
│   ├── single_landscape.css
│   └── single_portrait.css
├── images
│   ├── arrow-close.png
│   ├── arrow-open.png
│   ├── back_40x40.png
│   ├── button-bg_40x40.png
│   ├── close_40x40.png
│   ├── grid_40x40.png
│   ├── option-menu_titlebar.png
│   ├── refresh_40x40.png
│   ├── search_40x40.png
│   ├── tab_bg.png
│   └── title-bar.png
└── js
├── s40-theme.js
└── screensize.js

 

“Sources” under app/ directory were processed to produce these files; .coffee files were compiled and concatenated to “app.js”, index.jade was converted to index.html, and so on.

There is one extra directory we didn’t show yet, the “vendor” directory:


ville@ville-tp:~/p/awa-helloworld$ tree vendor/
vendor/
├── jade_runtime.js
└── README.md

If you are using JavaScript libraries like jQuery, you would just copy it under vendor/ and all of them get automatically concatenated to vendor.js. This makes the app fast to load as it reduces the amount of separate files to download. For production, Brunch can also minify the Javascript files to further reduce page weight. jade_runtime.js is here to support *precompiled Jade templates*

Shut up and show it running

In the interest of making things as “familiar” and frictionless as possible, we will preview the application in standard Chrome browser instead of Nokia Web Tools. So we launch Chromium and disable web security to prevent CORS from cramping our style and killing our Ajax requests:

	$ chromium-browser --disable-web-security http://localhost:3333

This doesn’t look at all what you would expect on the phone screen, because we haven’t specified a viewport size:

Chromium inspector has a handy feature of overriding the viewport size (Settings -> Overrides -> Device Metrics), so we use it to set the resolution to match Asha Full Touch devices (240 x 400):

Now, we have a low-fidelity representation of the phone experience! While this certainly wouldn’t satisfy an UI designer, it’s sufficient for a busy software developer that mostly needs to focus on the “logic” side of the web app.

Launching in NWT

Now is the time to get this running with “real” IDE, i.e. Nokia Web Tools. Launch NWT, do File -> New -> Import web app, select public/config.xml and launch the application in local preview:

Is this it?

There is more to show: how to utilize precompiled templates, how to inject the MWL library, and how Jade can help you create MWL UI “components” with reusable, encapsulated logic. These, and other things to smoothen the development flow will be covered in another blog post, as this already got way too long.

Make it big – why size matters.

Nowadays everything seems to be getting smaller; SIM cards, computers, prices for TVs, transistors, pixel sizes of video screens. So, why not also reduce the size of a font or icon to get more information into your app? Small graphics look sharp and crisp on small displays with very low pixel sizes. It’s very tempting.

The answer is simple: We are now getting to a saturation point—actually we have been there for a while. In this context, saturation means that relevant UI components will not benefit from higher resolution.

Continue reading

Use the PeerFinder API to launch applications via NFC

With the introduction of NFC on Windows Phone 8, the scenarios of device interaction become much more reachable to consumers and developers. By simply by tapping one WP8 device with another, we can perform a variety of tasks, like sharing a contact, photo, video, or app, pairing with Bluetooth, etc.

The Proximity API in WP8 provides two main classes for NFC related features: ProximityDevice and PeerFinder. ProximityDevice enables functionality like publish/subscribe for NFC messages to and from tags or another devices, while PeerFinder focuses on pairing two devices with a socket connection using NFC tapping or browsing without NFC involvement.

Launching an application from another device is one of the most important features that NFC provides. In most cases, launching the same application from another device is desired to enable further interactions on the same app context between two devices, such as multi-player games, messaging apps, media sharing, etc. Both ProximityDevice and PeerFinder can perform this task.

By using ProximityDevice, developers need to make a URI association for the app and then publish the custom URI to another device. This approach enables the app to interact with other applications as well. However, sometimes app developers do not want to disclose the interface to others due to confidentiality. In such cases, the URI association might not be the best option.

On the other hand, many developers have encountered issues where if both apps are running in the foreground on separate devices and either Fast App Resume (FAR) or BackgroundExecution is defined in the manifest, then passing the URI through NFC will not trigger the MapUri function to launch the desired page in the application. In such cases, the PeerFinder approach to launch the same app on another device becomes more reliable option for developers.

So, how do you launch the same app on another device using PeerFinder? The solution is pretty simple. Developers just need to include the following code in their application. As it requires NFC to make tapping gesture work, the application needs to have ID_CAP_PROXIMITY and ID_REQ_NFC defined in the manifest.

...
PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged;
PeerFinder.Start();
...
void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
{
//to-do
}

After PeerFinder is started on device A, then when another device (“B”) enters into proximity range, device B will behave according to the following rules:

  • Case 1: If device A has the app but device B doesn’t, device B will get a prompt to search for the app in the store as in the first illustration.
  • Case 2: If both device A and B have the app installed and the app is not yet launched on B, then B will get a prompt to launch the app as in the second illustration.
  • Case 3: If both device A and B have the app installed and both have launched the same app, then TriggeredConnectionStateChanged will get notified and further actions can be performed.

App not installed    App not installed and not launched

If the app needs a socket connection for further action between two devices, then it can check the TriggeredConnectState property in the  TriggeredConnectionStateChangedEventArgs passed in with the  TriggeredConnectionStateChanged event. Once the state is changed to TriggeredConnectState.completed, then the Socket property under TriggeredConnectionStateChangedEventArgs will be ready to use.

Some developers want to distinguish between normal application launching and launching by PeerFinder. This can be achieved by using the URI mapper and checking the URI passed. In the PeerFinder case, the URI passed to the MapUri function will look like this:

/MainPage.xaml?ms_nfp_launchargs=Windows.Networking.Proximity.PeerFinder:StreamSocket

Launching the same app on another device using PeerFinder does not require URI association, which implies that no other application can pretend to be the application by associating the same URI theme. This ensures that only the expected app is launched. It also resolves the issue mentioned above in the FAR or BackgroundExecution case. However, if developers want to share their application experiences with other applications, then using ProximityDevice with URI association is the proper option to choose.