Windows Phone 8 unveiled: all the new features for developers

Finally Windows Phone 8 is here! After the first official Windows Phone 8 presentation, that occurred on 20th June in San Francisco, Microsoft has released during the BUILD conference the SDK, unveiling all the developer and consumer features that were still unknown.

Unlike with the previous versions of the OS, this time Microsoft has released directly the RTM version: in this post we’ll talk the new feature that are available in the final version of Windows Phone 8 and that will be installed on the new devices that will be available in the next weeks. You can download the new tools from the following link and it’s available in many languages, even if, as for every other development technology, I suggest you to install the English tools.

Before starting, I would like to highlight that Microsoft is going to apply a big promotion to everyone that will register as a developer in the Windows Phone Dev Center in the next 8 days: in 30-45 days you’ll receive a refund of 91 $ on your credit card, this means that the total price of the subscription will be 8 $ instead of the usual 99 $ fee.

New tools, new emulator and new requirements

The new SDK is aligned with the latest Microsoft technologies: it’s based on Visual Studio 2012 (as with the old SDK, the Express version will be installed if you don’t already have a professional one) and it requires Windows 8 to run. Both products needs to be in RTM release: Windows 8 Release Preview and Visual Studio 2012 RC are not supported.

The Windows 8 requirement has been introduced due to the new emulator, that is now a Hyper-V virtual machine: Hyper-V is the Microsoft virtualization technology that, prior to Windows 8, was available only in the server editions of Windows. Now it’s available also in the “consumer” version of the OS, so the emulator can take advantage of it.

This new requirement, anyway, won’t make old computer’s owners very happy: Hyper-V, to run properly, requires your CPU to support SLAT (Second Level Address Translation), which is a technology available only in the latest CPUs models (for example, talking about the Intel world, it’s available on processors that belong to the i3 family and later, the old Core 2 Duo is not supported). In the following article you’ll find a procedure that, using the utility CoreInfo that is part of the SysInternals suite, will help you to discover if your CPU is supported.

The Windows Phone 8 SDK requires the final Window 8 release, that is available on the market since a few days (even if partners, MSDN and TechNet subscribers have access to the RTM since 15th August): if you’re not one of them, you can install the 90 days evaluation version that is available here. I suggest you to install it in a separate partition: in fact this 90 days trial can’t be converted in a full version, but you’ll be forced to install it from scratch. For this reason, it’s not a good idea to install it as a main operating system.

Another important new feature is that now the emulator is split into three virtual machines, one for every supported resolution: one of the new Windows Phone 8 features (already announced in June) is that two new resolutions are available other than the original one (that is 480×800, called WVGA). These new resolutions are 768×1280 (WXGA) and 720×1280 (720p).

Other than this new feature, the emulator should be familiar to every Windows Phone developer: it’s a virtual machine, that can take benefit of the computer’s hardware to simulate, for example, touch screen, video acceleration and microphone recording. One difference you’ll notice immediately (other than the shiny new start screen) is that, this time, the OS image is not restricted, but it contains all the data and applications that are available in a regular device. The Windows Phone 7 emulator, instead, contained a minimal OS image, with just Internet Explorer and a bunch of fake data to test launchers and choosers. This new OS image has been introduced since, as you will learn reading this post, now developers have more options to integrate their apps with the operating system.

image

There are many news to discover also in Visual Studio 2012: the first you’ll notice when you create a new Windows Phone project is that you’ll be able to develop applications both for Windows Phone 7 and 8 (like, with the previous SDK, developers were able to develop apps for Windows Phone 7.0 and 7.5). This is a very important feature, because Windows Phone 8 is able to run Windows Phone 7 application, but the opposite is not true. So, if you want to keep your application compatible with both worlds, you’ll need to maintain two different Visual Studio projects (with, maybe, a common codebase): thanks to this retro compatibility, you’ll be able to maintain both your apps with just one environment, that is Visual Studio 2012.

Another nice addiction is the Simulation Dashboard, which is a new tool (available in the Visual Studio’s Tools menu) that can be used to simulate some real phone behaviors, like the strength of the cellular signal, the speed of the data connection (3G, 4G, etc.), the lock screen activation or the incoming of a reminder.

image

One new feature that is really appreciated is the new manifest visual editor: with the Windows Phone 7 SDK developers had to manually edit the manifest (which is a XML file) to edit the information, change the required images or set the capabilities. Now, instead, you can use a visual editor that looks very similar to the one available when you develop Windows 8 applications: the good news is that it isn’t a specific Windows Phone 8 feature, but you can take advantage of the new editor also when you develop Windows Phone 7 applications. Anyway, even if it’s a nice addiction, the visual editor is still not perfect: some changes (like registering an application in the Pictures hub) still requires to be applied manually.

image

 

Do you remember the nice tools that have been added with the Windows Phone 7.5 SDK to simulate location, accelerometer and to take screenshot? They are still there, with a nice addiction: now, to grab a screenshot, you don’t need anymore to set the emulator zoom to 100%, but the image is automatically scaled at the correct resolution. Plus, you can find a new section with the details of the network configuration of the emulator.

A new development platform

After the June announcement, one of the most interesting discussion about Windows Phone 8 has been about the new development platform: during the June event Microsoft has generically spoke about XAML and C# / VB.NET, without directly mentioning Silverlight. Every developer took this information as a sign that Windows Phone 8 would have been aligned with Windows 8 and that it would have be used WinRT as a runtime instead of Silverlight.

The real truth is somewhere in the middle: Windows Phone 8 is effectively based on a WinRT subset, but the XAML isn’t native like in Windows 8, but it’s managed like in Silverlight. This means that the XAML we wrote for our Windows Phone 7 application is 100% compatible with Windows Phone 8 and can be reused with no changes. For example, you’ll be able to use also behaviors, that is a feature that, instead, is missing in the Windows 8 XAML.

The other important thing that you’ll notice is that, in order to maintain compatibility with Windows Phone 7, many APIs and classes are duplicated: for example, to access to the application storage you can use the old classes (like IsolatedStorageFile, that belongs to the namespace Microsoft.Phone.Storage) or the new API ApplicationData.Current.LocalFolder, that belongs to the Windows.Storage namespace and that can be used using the new async / await pattern and that works exactly like in the Windows 8 world.

The same happens with some controls: for example, in the SDK you can find the old Bing Maps control and the new Nokia Maps control, which can take benefit of all the new enhancements and features.

The other important news, already announced in June, is that now you can develop application using native code (C++ and DirectX), even if some features (like background tasks) are supported only using managed languages like C# and VB.NET. This feature will be very appreciated by games developers, that now will be able to port games from other platform without having to rewrite them from scratch using the XNA framework.

And, speaking about XNA, I have a sad news for XNA developers: Windows Phone 8 doesn’t support anymore XNA as a game development platform. You can still use it, but you have to develop a Windows Phone 7 application: this means that you won’t be able to take advantage of the new Windows Phone 8 features in your XNA games. The new official platform to develop games, both for Windows 8 and Windows Phone 8, is C++ with DirectX support.

Another sad news is for web developers: unlike the full WinRT runtime, that supports WinJS, a projection to write native applications using HTML and Javascript, Windows Phone 8 doesn’t support native development using web languages. Anyway, you can take advantage of the new Internet Explorer 10 based web control, that will allow platforms like PhoneGap to support much more features than in the past. You’ll even find a template dedicated to HTML 5, but I would like to underline that there is no WinJS support: the template simply creates a Windows Phone application with an embedded WebBrowser control.

The WinRT runtime for Windows Phone

The new WinRT runtime is definitely one of the most interesting new features in Windows Phone 8 from a developer’s point of view: now, thanks to this common base, you’ll be able to port your applications to Windows 8 and vice versa much more easily than you actually do in Windows Phone 7, since a lot of code should be rewritten due to the API differences between WinRT and Silverlight.

As already anticipated, the Windows Phone 8 APIs are split into two containers: the Microsoft.Phone namespace, that contains all the old APIs and some of the new ones that can be used with the old approach, and the Windows namespace, that contains all the native WinRT APIs and that has the same structure of the full runtime for Windows 8. The biggest difference with the old APIs is that all the WinRT classes and methods are based on the async / await pattern: in Windows Phone 7 the standard pattern to manage asynchronous method was to provide an event handler that was called when the async operation was completed. With the new WinRT APIs every asynchronous method returns a Task<T> object, that allows to write asynchronous code that looks like synchronous and that’s easier to write and to understand.

Pay attention that, to keep the compatibility with the Windows Phone 7 world, not every class supports this new pattern: for example, the HttpWebRequest and WebClient classes (that are used to perform network operations) don’t provide methods that returns a Task object, unlike in the Windows 8 world.  Luckily, thanks to the Task APIs, it’s easy to write one or more extension methods that can avoid this limitation.

Speaking about compatibility, it’s nice to see that old libraries will still work in Windows Phone 8: you’ll able to reuse your favorite toolkits and libraries, at least until they will be ported to Windows Phone 8, to take advantage of all the new features.

The WinRT subset available in Windows Phone 8 looks, from an architectural point of view, like the Silverlight Runtime for Windows Phone: the Windows Phone team took the full Silverlight runtime and created a subset, by removing the not needed stuff (for example, the print APIs) and adding support for specific phone features (like launchers, or GPS and sensors support). WinRT for Windows Phone is pretty much the same: the team took the full WinRT runtime and removed some not needed APIs (like the ones to interact with the charm bar) and added new ones (like the one to manage the Back button).

Here is a more detailed list of the main differences between the full runtime and the Windows Phone subset:

  • Input: there is no support to gestures, but just to raw data.
  • Launchers and choosers: it’s available a subset of the original APIs, since the phone offers limited interaction than a tablet or a regular computer. For example, the FileOpenPicker can be used just to access photos, since there’s no file system access.
  • Core: in the Windows Phone ecosystem there’s only one CoreWindow and only the Launch contract is supported (that is used to start the application), while in Windows 8 you have access to many contracts (like Search or Share).
  • In App Purchase: the in app purchase APIs are pretty much the same, except that Windows Phone 8 support consumables, that are items that can be purchased more than once during the application lifetime.
  • Sensors: inclinometers APIs are not supported, since this kind of sensor is not available on phones.
  • Storage: the APIs to access to the local storage are the same, but in Windows Phone 8 temporary storage and roaming storage (that contains data that is synced between different devices using the Microsoft account) are not supported. They are available, but you’ll get a NotSupportedExceptionif you try to use one of them.
  • Device communication: unlike in Windows 8, it’s not possible to set up a direct connection between different devices using Wi-Fi connection. This feature, anyway, is available using the new NFC and bluetooth APIs.

What about controls?

There aren’t many news about controls, but the new features are really a nice addiction: the first news is that Panorama and Pivot controls have been removed from the APIs and now are stored directly in the phone memory. This should solve all the performance problems that you can actually experience using these controls in a Windows Phone 7 application.

The other news is that the LongListSelector control, that is actually part of the Silverlight Toolkit, has been promoted as an official control: its purpose is to create lists of data that are easier to navigate, thanks to jump lists that allow the users to quickly jump from a group of item to another.

Tile, notifications and lock screen

In the June event Microsoft has revealed just one of the Windows Phone 8 consumer features: the new start screen, which now fit all the screen size and supports three tile sizes: 159×159 (small), 336×336 (medium) and 691×336 (large).

As developers we can use the different sizes to display different information: for example, the native Mail application displays just a counter when the tile is set to small or medium, while it displays a preview of the last unread mail when it’s set to large.

Another new feature is templating support, similar to the one that is available in Windows 8 (even if with a smaller range of choices). Basically, as a developer, you can choose to use one of the three available tile templates and interact with it at runtime: once you’ve set it, you can’t change it, unless you release a new version of the application.

Let’s take a look to the available templates:

Flip is the standard template, that is available also in Windows Phone 7. Basically, you can set some information both on the front and on the rear of the tile which, periodically, flips to show both sides.

image

Cycle is a new template that allows up to 9 images to be cycled in the tile. The images can be fixed (and set in the manifest file) or can be dynamically changed at runtime. You can see an example of this template also in Windows Phone 7 in the Pictures hub tile, where random images from your library are cycled.

image

Iconic is a template that can be used to create tiles with the same look and feel of some native applications, like Mail or Messages. You can set an icon, some text, a background color and an optional counter.

image

 

As in Windows Phone 7, all these tiles templates can be updated with push notifications, both local or remote.

One feature that, personally, I love in Windows Phone 8 is that now notifications can also be used to update the lock screen, exactly like some native applications do. There are two ways to update the lock screen:

  • by showing an icon with a counter (like Mail does to show the number of unread mails)
  • by showing a text (like Calendar does to show the next appointment)

 

As a developer you’ll be able to write applications that, using notifications, can update these information on the lock screen: obviously, the user has total control over it and, from the Settings hub, can choose which applications are able to show a counter (up to 5) or a text (just one) in the lock screen.

The best part is that the effort to implement this feature is minimum: you’ll just have to register the application by adding a new declaration in the manifest file and you’re done. In fact, the lock screen counter is based on the same notifications that are used to update a tile: if you send a tile notification that changes the value of the Count property, this value is displayed both in the tile and in the lock screen. The only other requirement is that you’ll have to provide a 24×24 icon, that will be displayed in the lock screen near the counter.

And it’s not over yet: there’s another new feature connected to the lock screen, that is the capability to register an application as a wallpaper provider. Once you’ve done that (the user will be asked to confirm) you’ll be able to change the lock screen wallpaper, even periodically by using a background agent. Windows Phone 8 includes an already built in wallpaper provider: Bing. When you activate it, the lock screen is periodically updated with the image of the day that is posted periodically on Microsoft’s search engine’s home page.

From a developer point of view, before starting to use the lock screen APIs you’ll have to register your application as a provider by adding a declaration in the manifest file, like you did for the lock screen notifications.

All these new features have been grouped with the name of Live Apps, that refers to applications that, other than using live tiles, are able to interact with the lock screen.

Maps

The collaboration between Nokia and Microsoft is going to take a big step forward with Windows Phone 8, since Bing Maps has been completely replaced by Nokia Maps. This way, all the Windows Phone users will take benefit of all the Nokia features, like offline maps.

For developers there’s also a new map control, that replaces the Bing Maps one and that provides better performances and features. The Bing Maps control is still there, but it’s deprecated: it’s been maintained just for compatibility with Windows Phone 7.

The downside of this control is that, especially for advanced scenarios (like layers, pushpins and so on), has many differences with the Bing Maps one, so if you want to migrate your application to use the new control you’ll probably have to rewrite a lot of code.

Speech API

This is absolutely one of the most interesting new features in Windows Phone 8: the platform already has a good built in support for voice commands, for example to execute actions (like calling a contact) and to write text without using the keyboard (like the voice-to-sms feature).

Now, as a developers, you’ll be able to introduce speech functionalities in your application:

  • Voice commands support, so that you can execute actions by using the voice (for example, performing an operation or navigating to a specific page).
  • Text-to-speech, both to convert voice in text and vice versa.

 

The voice commands features is based on special XML files, called VCD files, that stores for every information command all the required information, like the keyword to activate it and the navigation command to issue. You can intercept a voice command in the same way you intercept deep links when you use multiple tiles: in the OnNavigatedTo event (that is raised when the user lands to a page) you’ll have to check if the NavigationContext contains one or more parameters query string parameters.

Wallet

Wallet is another Windows Phone 8 feature that was announced in June: it’s a new native application that can be used to store payment information, like credit cards, debit cards or membership cards. The data is encrypted, so it can be stored safely: in some countries (like in United States) you’ll be able to link a secure SIM with the Wallet application, in order to make payments directly with your phone using the NFC chip.

As developers we’ll be able to interact with the Wallet application by adding new cards, deals or items to the transaction history.

In-app Purchase

Also this feature was very awaited from developers: the capability to make purchases within an application, for example to buy a subscription or unlock some features.

Microsoft has always allowed in-app purchase, but without providing its own payment infrastructure: developers were forced to implement their own backend to manage payments and transactions. Now in-app purchase is fully integrated with the new Windows Phone Dev Center (the old AppHub), so that you’ll be able to create new items to purchase, choose the price and differentiate it according to the market, exactly like you do with a regular application.

Within the application, thanks to the new APIs, you’ll be able to get the list of the available items and to allow the user to buy one or more of them: all the transactions will be directly managed by Microsoft, using the same architecture provided to purchase apps and music in the Marketplace.

One of the features that is different from Windows 8 is the concept of consumables: in Windows Phone 8 you can create some in app-purchase items that can be purchased multiple times (while the standard items can be purchased just once and the purchase status is replicated on every device on which you have installed the app).

Proximity

Under the keyword proximity Microsoft has included many APIs that allow Windows Phone 8 devices to interact with other near devices using both new and old technology. The new one is NFC (Near Field Communication), a chipset that allows two devices to communicate simply by putting them very closely. This is a new Windows Phone 8 feature, since old devices don’t have this chip. One of the most interesting NFC features is that is able to interact both with passive and active devices. Passive devices are chips that can be inserted in a sticker or in a magazine, for example, and that can be used to send small amount of data, like the URL of a website. Active devices are other smartphones or tablets: in this case, one of the most powerful NFC features is that can be used to pair a device using bluetooth simply by putting them at a close distance, without having to do the manual pairing using a PIN. Since Bluetooth is a more stable and faster technology, it can be used to exchange bigger data (like an image) or to establish the communication required to play a multiplayer game.

The other available technology is Bluetooth, that it’s always been one of the required chipset since the first Windows Phone release: anyway, in Windows Phone 7 Bluetooth is very limited since, as developers, we aren’t able to use it. Finally Windows Phone 8 has introduced many new APIs to the interact with the Bluetooth chipset and to exchange data with other devices.

Here are some scenarios covered by the Proximity APIs:

  • Communication between the same app installed on different devices, for example to join a multiplayer game.
  • Communication between different devices to exchange data using standard protocols, for example to send images, contacts and so on to another smartphone or a tablet.
  • Communication between a smartphone and a different hardware device, like a game controller or a training device.

Data sharing

This is one of the new features I like most, since it expands a lot the capabilities of our devices. Now third party apps are able to interact with other apps by sharing data. There are two ways to do that:

  • By registering an extension: an application can register one or more extensions (like .log, for example). If another applications tries to open a file with such an extension (using the method Windows.System.Launcher.LaunchFileAsync), our application is able to intercept it so that, for example, it can display it in a specific page. Pay attention that there are some native extensions (like Office files) that can’t be registered by a third party application.
  • By registering a protocol: an application can also register a protocol (for example, skype:/). If another application launches a URI request (using the method Windows.System.Launcher.LaunchUriAsync) our application is able to intercept it and collect the parameters attached to the URI.

 

The two features are very similar: they are registered in the same way (in the manifest file) and the data is intercepted by the same class. The only difference is that, in the first case, we’re talking about file sharing: the file is copied from the storage of the launching application to the storage of our application, so that we can work with it. In the second case we work just with plain strings: we can collect the query string parameters of the URL and interact with them.

One scenario that is actually not covered by data sharing is sending files back to the original application: you can’t do something like launching a file, opening it with another application, editing it and then returning back to the application that launched it.

Data sharing is strictly connected to another new feature, that is the capability to read data from the SD card: if the micro SD card (that is supported by some of the new generation devices) contains files which extension has been registered by the application, we can look for them and open them.

Geo location and background applications

Applications that use geo location services can now run in background, so that they can keep track of the user’s location if when they are not in foreground. In this case, the application uses a new lifecycle model: since the app is not suspended anymore, the current instance is always restored when you open it, regardless if you’re opening it using the Back button or the task manage or by tapping on its tile. Standard apps, instead, will continue to behave like in Windows Phone 7: the app is only restored by using the Back button or by using the task manager, launching it from the tile or from the app list will always open a new instance.

As developers, we will have to manage this new application lifecycle and some of the new APIs will help us to accomplish this task.

New camera features

There are many new features that photo applications can use to enhance the user experience: the two most interesting ones are lens apps and custom cloud services support.

Let’s start from lens apps: imagine a real professional camera, where you are able to change the lens to apply different effects to the photos. Lens apps are the same, just applied to the phone’s camera: lens apps are application that can apply various effects to the photos taken by the camera and that can be activated directly from the native camera app. This way, apps can provide a better experience to the user: prior to this feature, users were forced to use third party apps instead of the native one to apply custom effects, preventing them, for example, to use the dedicated button to start the camera. Now, instead, a user can simply launch the camera app in the standard way and then apply one of the available lens apps.

The other cool feature I’ve mentioned is custom cloud services support: in Windows Phone 7 users are able to automatically upload a photo, right after it’s taken, directly to one of the the built in services, like SkyDrive or Facebook. In Windows Phone 8 you can develop your own custom services, on which photos will be immediately uploaded.

Data Sense

Data Sense is a new application that is available in Windows Phone 8, that can be used to keep track of the data traffic made by the phone and, more specifically, by every single application that is installed. Plus, users are able to set the monthly traffic limit allowed by their plans: if the limit is reached, the phone will automatically turn off the data connection, in order to avoid surprises on the phone’s bill.

The Data Sense features can be used also from third party applications using an API, that can be used to check if the user is approaching the monthly limit. This way, we can change the behavior of our application according to this limit: for example, a RSS reader can decide not to download images if we’re approaching it.

The only downside of this feature is that mobile operators will be able to decided if Data Sense should be shipped or not with their phones: if not, developers will be able to use the Data Sense API just to identify the user’s connection (or, for example, if he’s using roaming or not), but they won’t have access to traffic limit information, since the user won’t have a way to set it.

A lot more!

There are many new features for developer that, for sure, we’ll cover in details in the next months. Here is a short preview:

  • New launchers and choosers: Windows Phone 8 features some new launchers (to interact with the new Nokia Map application) and choosers (you’ll surely appreciate the new chooser to save an appointment to the calendar).
  • VoIP: developers will be able to develop VoIP applications using a subset of the Windows Audio Sessions API (WASAPI). The most interesting feature is that VoIP apps will be able to deeply integrate with the operating system, so that you can launch a VoIP call, for example, directly from the detail page of a contact.
  • New media library APIs, that enhance the capabilities of what we can do with the files in the media library. There are still some limitations, but we have more flexibility than in the past.
  • Support for new languages: application can now support also bidirectional languages.

And what about consumers?

We are developers, it’s true, but probably we are Windows Phone users too. Which are the new features that have been introduced for consumers in the new platform, other than the shiny new start screen? Let’s see a brief list:

  • The latest versions of the Microsoft apps: Windows Phone 8 comes with the most recent technologies by Microsoft, like Office 2013, Internet Explorer 10 and XBox Music.
  • Kid’s corner: this is a very cool feature if you have children or kids that are used to play with your phone. Basically, this feature allows you to create a sandbox, that contains just the apps and the music that you have chosen as suitable for kids. This way, you can give the phone to your children without having to worry that they can use apps that aren’t suitable for them or that they can accidentally damage your data.
  • New accent color: now you can choose between up to 20 colors to customize your phone.
  • Offline maps: Bing Maps has been replaced by Nokia maps, with offline map support. This way you’ll be able to use maps even without a connection: this feature is very useful especially when you’re abroad and you can’t use your data connection due to high roaming charges.
  • MicroSD support:now the operating system supports external Micro SD cards, that can be used to store music, videos and pictures (no apps, they can be installed only in the main memory). Even if this feature is supported by the OS, it’s up to the manufacturer if to implement it or not (for example, the Nokia Lumia 820, since it has a removable back cover, supports Micro SD, while the bigger brother Lumia doesn’t).
  • Backup and restore:now you can backup your settings, the list of apps you’ve installed and your text messages, that can be restored if you buy a new Windows Phone 8 device or, for any reason, you have to reset your current one.
  • Native NFC support: other than being accessible from third party apps using the Proximiy APIs, the operating system itself supports NFC to share data between two devices (for example, to share photos).
  • OTA (Over The Air) updates: if Microsoft or the manufacturer release an update for the phone, now you don’t have anymore to connect it to your computer, you can download and install directly from your phone.
  • Rooms, that is a way to create special group of contacts, so that you can share calendars, photos or start a chat with.

The beginning of a new adventure

This is was a really long post: you’ll hardly see another post so long on this blog, but I thought that it didn’t make sense to split it in multiple parts. You are all eager to know the new stuff in Windows Phone 8, right? Smile And now the fun begins: in the next months I’ll surely cover in details all the new features and how to implement them in your application.

The only tip I can give you, at the moment, is to start installing the SDK, playing with the new emulator and, if you already are a Windows Phone developer, test your existing applications with it. The compatibility’s level is very high and, very likely, your app will run just fine, even better due to the performance improvements and to the higher specs of the new devices. But there can be some scenarios where the Windows Phone codebases has changed a bit, so your application can have some problems. Make sure that your app runs fine both in Windows Phone 7 and Windows Phone 8 and, if not, update it and publish it!

Posted in Windows Phone | Tagged | 4 Comments

Nokia Developer Champion

nokia developer champion

I don’t like to talk too much about my self, I prefer that the passion I put into the posts I write speaks for me (at least, this is what I hope!). But I’m so happy about this new award I’ve received that I would like to share it with everybody else and, especially, with the communities and the people I have the pleasure and the luck to cooperate with.

This award is gifted by Nokia and it’s called Nokia Developer Champion: its philosophy is similar to the Microsoft MVP program’s one, since it recognizes the effort spent to support people and communities about developing apps for Nokia devices (in my case, we’re talking about Windows Phone development). This is my profile page on the Nokia Developer Portal.

I would like to thank you everybody that made this possible and now… let’s continue my job and commitment about Windows Phone, hoping to be part of this amazing group for a long time Smile

Posted in Windows Phone | Tagged , | Leave a comment

Having fun with Azure Mobile Services – The Windows Phone application

Did you have fun using your Azure Mobile Service with your Windows 8 app? Good, because now the fun will continue! We will do the same operations using a Windows Phone application. As I already anticipated in the previous posts, actually there isn’t a Windows Phone SDK and the reason is very simple: Microsoft is probably waiting for the Windows Phone 8 SDK to be released, in order to proper support both its old and new mobile platform.

But we don’t have to worry: our service is a REST service that supports the OData protocol, so we can interact with it starting from now by using simple HTTP requests and by parsing the HTTP response.

To help us in our work we’ll use two popular libraries:

  • RestSharp, that is a wrapper around the HttpWebRequest class that simplifies the code needed to communicate with a REST service. Sometimes RestSharp tries to be “too smart” for my taste, as we’ll see later, but it’s still a perfect candidate for our scenario.
  • JSON.NET, that is a library that provides many useful features when you work with JSON data, like serialization, deserialization, plus a manipulation language based on LINQ called LINQ to JSON.

 

Let’s start! First you have to open Visual Studio 2010 (the 2012 release isn’t supported yet by the current Windows Phone SDK) and create a new Windows Phone project. Then, using NuGet, we’re going to install the two library: right click on the project, choose Manage NuGet Packages and look for the two needed libraries using the keywords RestSharp and JSON.NET.

The UI of the application will be very similar to the one we’ve used for the Windows 8 app, I’ve just replaced the ListView with a ListBox.

<StackPanel>
    <Button Content="Insert data" Click="OnAddNewComicButtonClicked" />
    <Button Content="Show data" Click="OnGetItemButtonClicked" />
    <ListBox x:Name="ComicsList">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0, 20, 0, 0">
                    <TextBlock Text="{Binding Title}" />
                    <TextBlock Text="{Binding Author}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

Insert some data

To insert the data we’ll have to send a HTTP request to the service, using the POST method; the body of the request will be the JSON that represent our Comic object. Let’s see the code first:

private void OnAddNewComicButtonClicked(object sender, RoutedEventArgs e)
{

    RestRequest request = new RestRequest("https://myService.azure-mobile.net/tables/Comics");

    request.Method = Method.POST;
    request.AddHeader("X-ZUMO-APPLICATION", "your-application-key");

    Comic comic = new Comic
                       {
                           Title = "300",
                           Author = "Frank Miller"
                       };

    string jsonComic = JsonConvert.SerializeObject(comic, new JsonSerializerSettings
                                                              {
                                                                  NullValueHandling = NullValueHandling.Ignore
                                                              });

    request.AddParameter("application/json", jsonComic, ParameterType.RequestBody);

    RestClient client = new RestClient();
    client.ExecuteAsync(request, response =>
                                     {
                                         MessageBox.Show(response.StatusCode.ToString());
                                     });

}

The first thing we do is to create a RestRequest, which is the RestSharp class that represents a web request: the URL of the request (which is passed as parameter of the constructor) is the URL of our service.

Then we set the HTTP method we’re going to use (POST, in this case, since we’re going to add some data do the table) and we set the application’s secret key: thanks to Fiddler, by intercepting the traffic of our previous Windows 8 application, I’ve found that the key that in our Windows Store app was passed as a parameter of the constructor of the MobileService class is added as a request’s header, which name is X-ZUMO-APPLICATION. We do the same by using the AddHeader method provided by RestSharp.

The next step is to create the Comic object we’re going to insert in the table: for this task please welcome Json.net, that we’re going to use to serialize our Comic object, that means converting it into a plain JSON string. What does it mean? That if you put a breakpoint in this method and you take a look at the content of the jsonComic variable, you’ll find a plain text representation of our complex object, like the following one:

{ 
    "Author" : "Frank Miller",
    "Title" : "300"
}

We perform this task using the SerializeObject method of the JsonConvert class: other than passing the Comic object to the method, we also pass a JsonSerializerSettings object, that we can use to customize the serialization process. In this case, we’re telling to the the serializer not to include object’s properties that have a null value. This step is very important: do you remember that the Comic object has an Id property that acts as primary key and that is automatically generated every time we insert a new item in the table? Without this setting, the serializer would add the Id property to the Json with the value “0”. In this case, the request to the service would fail, since it isn’t a valid value: the Id property shouldn’t be specified since it’s the database that takes care of generating it.

Once we have the json we can add it to the body of our request: here comes a little trick, to avoid that RestSharp tries to be too smart for us. In fact, if you use the AddBody method of the RestRequest object you don’t have a way to specify which is the content type of the request. RestSharp will try to guess it and will apply it: the problem is that, sometimes, RestSharp fails to correctly recognize the content type and this is one of these cases. In my tests, every time I’ve tried to add a json in the request’s body, RestSharp set the content type to text/xml, that it’s not only wrong, but actively refused by the Azure mobile service, since the only accepted content type is application/json.

By using the AddParameter method and by manually specifying the content type, the body’s content and the parameter’s type (ParameterType.RequestBody) we are able to apply a workaround to this behavior. In the end we can execute the request by creating a new instance of the RestClient class and by calling the ExecuteAsync method, that accepts as parameters the request and the callback that is executed when we receive the response from our service. Just to trace what’s going on, in the callback we simply display using a MessageBox the status code: if everything we did is correct, the status code we receive should be Created.

To test it, simply go to the Azure management portal, access to your service’s dashboard and go into the data tab: you should see the new item in the table.

Play with the data

Getting back the data for display purposes is a little bit simpler: it’s just a GET request, with the same features of the POST request. The difference is that, this time, we’re going to use deserialization, which is the process to convert the JSON we receive from the service into C# objects.

private void OnGetItemButtonClicked(object sender, RoutedEventArgs e)
{
    RestRequest request = new RestRequest("https://myService.azure-mobile.net/tables/Comics");
    request.AddHeader("X-ZUMO-APPLICATION", "my-application-key");
    request.Method = Method.GET;

    RestClient client = new RestClient();
    client.ExecuteAsync(request, result =>
                                     {
                                         string json = result.Content;
                                         IEnumerable<Comic> comics = JsonConvert.DeserializeObject<IEnumerable<Comic>>(json);
                                         ComicList.ItemsSource = comics;
                                     });
}

The first part of the code should be easy to understand, since it’s the same we wrote to insert the data: we create a RestRequest object, we add the header with the application key and we execute asynchronously the request using the RestClient object.

This time in the response and, to be more precisely, in the Content property we get the JSON with the list of all the comics that are stored in our table.  It’s time to use Json.Net again: this time we’re going to use the DeserializeObject<T> method of the JsonConvert class, where T is the type of the object we expect to have back after the deserialization process. In this case, the return type is IEnumerable<Comic>, since our request returns a collection of all the comics stored in the table.

Some advanced scenarios for playing with the data

In the next posts we’ll see some more operations we can do with the data: the mobile service we’ve created with Azure supports the OData protocol; this means that we can perform additional operations (like filtering the results) directly with the HTTP request, without having to get the whole content of the table first. We’ll see how to do it, in the meantime… happy coding!

Posted in Windows Phone | Tagged , , | Leave a comment

Having fun with Azure Mobile Services – Integrating with Windows 8

In the previous post we’ve introduced Azure Mobile Services and we learned how to configure and create them. If you’ve followed all the steps of the previous post, you should have now a service up & running that allows to interact with a table called Comics, that we’ve created to store information about our favourite comics.

In this post we’ll see how to interact with this service from a Windows 8 application: as I’ve anticipated in the previous post, Windows 8 is the easiest platform to integrate with our service, since Microsoft has released a specific SDK for Windows Store apps. This SDK basically hides all the web requests that, under the hood, are exchanged with the service and automatically serialize and deserialize our data.

The first thing, indeed, is to download the SDK from the following link. After you’ve installed it, it’s time to open Visual Studio 2012 and create a new Windows Store app (you can use the blank template, in this post we’ll simply learn how to communicate with our service, we won’t develop a real application with full graphic).

After installing the SDK you’ll find a library in the Windows – Extensions section of the Add new reference dialog: it’s called Windows Azure Mobile Services Managed Client and you simply have to double click on it to add it to your project.

image

 

As I already anticipated, the app will be very simple: no graphic, no user experience, just two buttons, one to store data and one to retrieve it and display it in a ListView. So let’s start by adding them in the XAML of our MainPage:

<StackPanel>
    <Button Content="Insert data" Click="OnAddNewComicButtonClicked" />
    <Button Content="Show data" Click="OnGetItemButtonClicked" />
    <ListView>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0, 20, 0, 0">
                    <TextBlock Text="{Binding Title}" />
                    <TextBlock Text="{Binding Author}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>

The code should be simple to understand: with the first button we’re going to store some data in our service; with the second one we’re going to retrieve it and displaying it in the below ListView, which simply shows, one below the other, the title and the author of the comic.

Let’s prepare the application

Before starting to do some operation we’ll need to create the class that maps the data we have on our service: since we’ve created a Comic table, we’re going to create a Comic class with, as properties, the columns of our table. Here is the code:

public class Comic
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

The second thing to is to initialize the client we’re going to use to do operations with the service: we can do it, for example, in the constructor of our MainPage, by declaring it at class level (so that every method we’re going to write will be able to use it). Initializing the client is very simple:

MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/",
"your-application-key");

You’re going to use the class MobileServiceClient (it’s inside the Microsoft.WindowsAzure.MobileServices namespace) that, when it’s initalized, requires two parameters: the first one is the address of your service (the one we have chosen when we have configured our service), the second one is the secret application key. To get your key, simply open the Azure Management Portal and, in the home page of your Azure Mobile Service, choose the option Connect to an exisiting Windows Store app. In the window that will appear you will find, at step 2, the same code I’ve just written, but already filled with the correct data of your service. Just copy and paste it in your application and you’re done!

image

Insert some data

Now that we have the client available, we can start to see how to insert some data in our servie, by managing the event handler of the first button we’ve defined in the XAML. Here is the code:

private async void OnAddNewComicButtonClicked(object sender, RoutedEventArgs e)
{
    MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/",
                                                        "your-application-key");

    Comic comic = new Comic
                       {
                           Title = "Batman Year One",
                           Author = "Frank Miller",
                       };

    await client.GetTable<Comic>().InsertAsync(comic);

}

First we create a new Comic object, with a title and an author. Then, using the MobileServiceClient object, we get a reference to the Comic table and, in the end, we call the InsertAsync method by passing as parameter the comic object we’ve just created. This operation is awaitable (it can require some time to be executed, since it involves communications with a service over Internet), so we’re going to use the magic keywords async (in the event handler’s signature) and await (before the method, in order to await that the operation is ended before moving on).

If you go back to the Azure Management Portal and you access to your service’s dashboard, in the Data section you’ll find that the new item has just been added.

image

Using dynamic data to add columns to the table

If you remember what we did in the previous post, after we created our Comics table we’ve added some columns using the Azure management tool. At the same time, I also told you that this step wasn’t really necessary, thanks to a feature called dynamic data, that is able to add new columns to the table by simply adding an item that contains new properties other than the ones already stored.

Let’s see how to use it: first add a new property in your Comic class called Publisher; we’re going to use it to store the publisher’s name of the comic.

public class Comic
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string Publisher { get; set; }
}

Now let’s edit the button’s event handler to add a new Comic object: this time we’ll set also the Publisher’s property of the project before inserting it.

private async void OnAddNewComicButtonClicked(object sender, RoutedEventArgs e)
{
    MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/",
                                                        "your-application-key");

    Comic comic = new Comic
                       {
                           Title = "Watchmen",
                           Author = "Alan Moore",
                           Publisher = "DC Comics"
                       };

    await client.GetTable<Comic>().InsertAsync(comic);
}

Run this code and you’ll see that, despite the fact that you’re adding a Comic object with a property that is missing in the table, you won’t get any exception. Go back to the Azure dashboard and, in the Data section, you’ll find that a new column called Publisher has been added: obviously, you’ll find a value only for the item you’ve just added, while the previous one will have an empty value.

image

According to what we’ve learned about the dynamic data we could have avoided, in the last post, to create the columns using the Azure management tool: we could have simply inserted a Comic object with the Title and Author properties and the service would have done everything for us.

How to work with the data

At this time it shouldn’t be too hard to understand how to get the data we stored on our service: by using the GetTable<>() method we’ve just seen we get a reference to the table. This table object (which type is IMobileServiceTable<T>) allows to perform operations using LINQ, so that we can filter the data before actually making the request. To get the real data we can use one of the available methods: ToListAsync() or ToEnumerableAsync(), that returns a collection of the objects stored in the table.

Here are some examples of the operations you can do:

private async void OnGetItemButtonClicked(object sender, RoutedEventArgs e)
{
    MobileServiceClient client = new MobileServiceClient("https://myService.azure-mobile.net/",
                                            "your-application-key");

    //get all the comics
    List<Comic> allComics = await client.GetTable<Comic>().ToListAsync();

    //get all the comics which publisher is DC Comics
    List<Comic> filteredComics = await client.GetTable<Comic>().Where(x => x.Publisher == "DC Comics").ToListAsync();

    //get all the comics ordered by title
    List<Comic> orderedComics = await client.GetTable<Comic>().OrderBy(x => x.Title).ToListAsync();

    ComicsList.ItemsSource = allComics;
}

In these three examples you can see how to retrieve all the data, how to retrieve filtered data (all the comics with a specific publisher) and how to apply an order criteria to the results.

And if we want to manipulate the data already stored in the table? We can simply use:

  • the UpdateAsync method to update an item. We simply have to pass to the method the update object and, using the unique identifier (in our example, the Id property of the Comic class) the already existing item will be overwritten by the new one.
  • the DeleteAsync method to delete an item. In this case, we simply have to pass to the method the object to delete: the method will take care to find it in the table and to remove it.

We’ve reached our goal… for the moment

In this post we’ve seen how to integrate our new Azure Mobile Service with a Windows 8 application. In the next post we’ll do the same with a Windows Phone application: things won’t be so easy as we’ve seen in this post, due to the temporary lack of a SDK for Windows Phone, but don’t worry, we’ll have fun anyway Smile

Posted in Windows 8 | Tagged , , | 1 Comment

Having fun with Azure Mobile Services – The setup

Azure Mobile Services is one of the coolest feature that has been recently added on top of Azure. Basically, it’s a simple way to generate and host services that can be used in combination with mobile applications (not only Microsoft made, as we’ll see later) for different purposes: generic data services, authentication or push notification.

It isn’t something new: these services are build on top of the existing Azure infrastructure (the service is hosted by a Web Role and data is stored on a SQL Database), they’re just simpler for the developer to create and to interact with.

In the next posts I’m going to show you how to use Azure Mobile Services to host a simple service that provides some data and how to interact with these data (read, insert, update, etc.) from a Windows 8 and a Windows Phone application. These services are simply REST services, that returns JSON responses and that can be consumed by any application. As you will see, interacting with Windows 8 is really simple: Microsoft has released an add-on for Visual Studio 2012 that adds a library, that can be referenced by a Windows Store app, that makes incredibly easy to do operations with the service.

Windows Phone isn’t supported yet (even if I’m sure that, as soon as the Windows Phone 8 SDK will be released, a library for this platform will be provided too): in this case we’ll switch to “manual mode”, that will be useful to understand how to interact with Azure Mobile Services also from an application not written using Microsoft technology (like an iOS or Android app). In this case, we’ll have to send web requests to the service and parse the response: as we’ll see, thanks to some open source libraries, it won’t be so difficult has it sounds.

Before starting to write some code, let’s see how to configure Azure Mobile Services.

Activating the feature

Of course, the first thing you’ll need is an Azure subscription: if you don’t have, you can subscribe for the free trial by following these instructions.

Then, you’ll need to enable the feature: in fact, since Azure Mobile Services are in a preview stage, they aren’t enabled by default. To do that, you’ll need to access to the Azure Account Management portal and open the Preview features section: you’ll see a list of the features that are available. Click on the Try now button next to the Mobile Services section, confirm the activation and… you’re ready! You should receive within a few minutes a confirm mail and the page should display the message You are active.

Creating the service

Now that the feature is enabled, we can start using it from the new Azure Management portal: press the New button and choose Create in the Mobile Services section. In the first step of the wizard you’ll be asked to choose:

  • A name for the service (it will be the first part of the URL, followed by the domain azure-mobile.net (for example, myservice.azure-mobile.net)
  • The database to use (actually, you’ll be forced to select Create a new SQL database, unless you already have other SQL Azure instances).
  • The region where the service will be hosted: for better performance, choose the closest region to your country.

 

image

 

The next step is about the database: in the form you’re going to set some important options.

  • The name of the database.
  • The server where to store the database (use the default option, that is New SQL Database server).
  • Login and password of the user that will be used to access to the database.
  • The region where the database will be hosted: for better performance, choose the same region that you’ve selected to host the service.

 

image

And you’re done! Your service is up and running! If you go to the URL that you’ve chosen in the first step you’ll see a welcome page. This is the only “real” page you’ll see: we have created a service, not a website, specifically it’s a standard REST service. As we’ll see in a moment, we’ll be able to do operations on the database simply by using standard HTTP requests.

Let’s create a table

To host our data we need a table: for this example, since I’m a comic addicted, we’ll create a simple table to store comics information, like the title, the author and the publishing year. Creating the table is the only part a little bit tricky: the Azure Mobile Service interface, as we’ll see later, provides built in functions just to create a table, without providing functionalities to change the schema and add new columns.

The first thing is to create the table by choosing the service with just created in the portal (in the Mobile services section), switching to the Data tab and pressing the Create button. You’ll be asked to give to the table a name and to set the permissions: by default, we’ll give full access to any application that has been authorized using the secret application key.

image

Now it’s time to move to the specific Azure tool to manage our SQL instance: in fact, by default, the table will contain just an Id field, already configured to be an identity column (its value will be auto generated every time a new row is inserted) and to act as the primary key of our table. In the management panel, click on the SQL Databases tab; you’ll find the database you’ve just created in the previous wizard. Click on the Manage button that is placed below: if it’s the first time you connect to this database from your connection, the portal will prompt you to add your IP address to the firewall rules: just say Yes, otherwise you won’t be able to manage it.

Once you’ve added it, you’ll see another confirmation prompt, that this time will ask you if you want to manage your database now: choose Yesand login to the account using the database credentials you’ve created in the first step.

Now you have full access to the database management and we can start creating our table: click on the database connected to your service (look for the name you’ve chosen in the second step of the wizard), then click on the Design tab and choose Create new table. If you’re familiar with databases, it should be easy to create what we need: let’s simply add some columns to store our information.

  • A title, which is a varchar with label Title
  • An author, which is another varchar with label Author

There’s another way to add new columns: by using dynamic data. When this feature is enabled (you can check it in the Configure tab of your mobile service, but it’s enabled by default), you’ll be able to add new columns directly from your application, simply by adding new properties to the class that you’re going to use to map the table. We’ll see how to do this in the next post.

As we’ve seen before, if we call the URL of our service (for example, http://myapp.azure-mobile.net) you’ll see a welcome page: to actually query our tables, we have to do some REST calls. To get the content of a table, we simply need to do a GET using the following URL.

http://myapp.azure-mobile.net/tables/Comic

If everything worked fine, the browser should return you a JSON response with the following format:

{"code":401,"error":"Unauthorized"}

This is the expected behavior: Azure Mobile Services require authentication, to avoid that everyone, just with the URL of your service, is able to access your data. By receiving this kind of error we have a confirmation that the table has been successfully created: otherwise, we would have received an error saying that the requested table doesn’t exist.

{"code":404,"error":"Table 'Comic' does not exist."}

Now that we have setup everything we need, we are ready to write some code: in the next posts we’ll see how to develop a Windows 8 and a Windows Phone application that is able to connect to our service.

Posted in Windows 8 | Tagged , , | Leave a comment