Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Windows (RT and Phone) and Sqlite (Part 3)

This is the third part in a series on using Sqlite across both Windows RT and Windows Phone. To catch up I suggest you take a look at parts 1 and 2:

Windows (RT and Phone) and Sqlite (Part 1)

Windows (RT and Phone) and Sqlite (Part 2)

Just to recap, here is my list of goals:

- Blendable: My project has to be designable in Blend at all times!

- Sqlite: I want to use sqlite to store relational data across both Win8 and WP applications

- PCL: I want to be able to do all my data access from a portable class library

- Objects Not SQL: I want to be able to read and write objects, rather than write sql statements

So far the PCL support has been non-existent. In this post we’re going to look at adding support so that you can access data from within your portable class library. When I thought to do this I figured it’d be an easy job of creating a bunch of interfaces and a factory, or two. It wasn’t too hard but there was a bit more to it than I expected. We’ll start with using the sqlite-winrt library, and I suspect it might be in part 4 of this series when I return to sqlite-net.

The primary problem we have is that our PCL can’t access any libraries that are winrt or wp specific. Since Sqlite-winrt is essentially two libraries, one for winrt and one for wp, this means we can’t access them directly from within our PCL. However, if we were to have an interface, declared in a PCL, that is implemented by each platform, then we can simply pass the implementation into our PCL and it’s none the wiser (standard DI stuff really). This means step one has to be to provide a PCL interface and a subsequent implementation for each platform:

Interfaces

The interfaces were relatively easy to define, considering you can open a .winmd in tools like ILSpy and you’ll be able to see the internal interfaces declared in sqlite-winrt. I’ve only included the interfaces for IDatabaseFactory and IDatabase here. The rest are included in the attached source code at the end of this post. These interfaces need to be declared in a stand alone portable class library (they could be in your application pcl but that would remove any possible reuse between projects)

public interface IDatabaseFactory
{
    Task<IDatabase> CreateInstance(string file);
    Task<IDatabase> CreateInstance(string folder, string name);
}
 
public interface IDatabase:IDisposable
{
    string Path { get; }
    Task OpenAsync();
    Task OpenAsync(SqliteOpenMode openMode);
    Task<IStatement> PrepareStatementAsync(string cmd);
    Task ExecuteStatementAsync(string cmd);
    long GetLastInsertedRowId();
}

 

Proxy Implementations

For each platform we need to implement these interfaces. Essentially the implementation is just going to proxy calls through to the sqlite-winrt library for the respective platform. For example, here is the implementation of the IDatabaseFactory interface.

public class DatabaseFactory : IDatabaseFactory
{
    public async Task<IDatabase> CreateInstance(string file)
    {
        var proxy = new DatabaseProxy();
        var sf = await StorageFile.GetFileFromPathAsync(file);
        proxy.Instance = new Database(sf);
        return proxy;
    }
 

public async Task<IDatabase> CreateInstance(string folder,

string name)

    {
        var proxy = new DatabaseProxy();
        var sfolder = await StorageFolder.GetFolderFromPathAsync(folder);

var sf = await sfolder.CreateFileAsync(name,

CreationCollisionOption.OpenIfExists);

        proxy.Instance = new Database(sf);
        return proxy;
    }
}

 

You might be thinking “really, I need to implement it twice?” Well the good news is that you only need to write the code once. sqlite-winrt has the same set of apis for both Windows 8 and Windows Phone, so whilst you do indeed need to create a class library for each platform, you can actually share the code between the projects (simply add the code file as a linked file using “Add as Link” in Visual Studio).

Application PCL

In the portable class library for your application you can now access Sqlite. The only thing your PCL needs is a reference to an implementation of the IDatabaseFactory interface. In the following code for simplicity we’re doing this with a public property on the DataAccessClass but in a real application you might want to use a DI framework to inject this as required.

public class DataAccessClass
{
    public IDatabaseFactory Factory { get; set; }
 
    public async Task<string> DoSomeDatabaseStuff(string dbPath)
    {
        // Create a new SQLite instance for the file 
        using (var db = await Factory.CreateInstance(dbPath))
        {
 
            // Open the database asynchronously
            await db.OpenAsync(SqliteOpenMode.OpenReadWrite);
 
            try
            {
                await db.ExecuteStatementAsync
("CREATE TABLE Cities (rowid INTEGER PRIMARY KEY ASC, CityName TEXT);");
                await db.ExecuteStatementAsync
("INSERT INTO Cities (rowid, CityName) VALUES (1, 'Perth');");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                // Table exists....    
                // TODO: Improve this so we're not throwing an exception 
                // for a common case!
            }
                
 
 
            // Prepare a SQL statement to be executed
            var statement = await db.PrepareStatementAsync
("SELECT rowid, CityName FROM Cities;");
 
            // Loop through all the results and add to the collection
            if(await statement.StepAsync())
            {
                return statement.GetIntAt(0) + ": " + statement.GetTextAt(1);
            }
            return null;
        }
    }
}

 

Assigning a Platform Implementation

The last thing you need to do, before you start accessing sqlite (eg calling the DoSomeDatabaseStuff method) is to pass in the platform specific IDatabaseFactory implementation. As I mentioned you can do this using your favourite DI framework. In the following snippet I’m simply assigning it in the code behind of our sample application (not an ideal way to do it but super simple for demonstration of the concept!). The following code is from the MainPage.xaml.cs file in the Windows Phone application

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
 
    await CreateCitiesDatabase();
}
 
private async Task CreateCitiesDatabase()
{
    // Get the file from the install location  
    var file =
        await
        ApplicationData.Current.LocalFolder.CreateFileAsync
        ("cities.db", CreationCollisionOption.OpenIfExists);
 
    var dal = new DataAccessClass();
    var factory = new DatabaseFactory();
    dal.Factory = factory;
 
    var data = await dal.DoSomeDatabaseStuff(file.Path);
    Debug.WriteLine(data);
}

 

And there you have it…. accessing code from within your PCL. So let’s do another recap of our goals:

- Sqlite: Tick!

- PCL: Tick! We fixed this

- Objects Not SQL: Fail (still but this solution will suit some people)

- Blendable: BAM! Fail. Doh! my solution is no longer Blendable.

Unfortunately we’ve broken our ability to design our application in Blend. This is hit and miss, if you get to this point and everything is still Blendable then you’re luckier than me. The good news is that there is a fix and it has nothing to do with us writing more code, or changing our existing code.

FIX: Install Visual Studio Update 3 Note – it is currently at RC, so whilst it is probably quite stable and safe to install, you do so at your own risk. If you’re risk adverse, you may want to wait until it RTMs.

With that fix in place, the only thing let is using Objects Not SQL. More on that in the next post.

Download Solution

Windows (RT and Phone) and Sqlite (Part 2)

In part 2 of this series we’re going to look at the second option that I presented on the use of sqlite which was to use the sqlite-net wrapper.

Just to recap, here is my list of goals:

- Blendable: My project has to be designable in Blend at all times!

- Sqlite: I want to use sqlite to store relational data across both Win8 and WP applications

- PCL: I want to be able to do all my data access from a portable class library

- Objects Not SQL: I want to be able to read and write objects, rather than write sql statements

For a more detailed understanding of these goals, check out Part 1.

Here’s a brief getting started walk through for sqlite-net .

- You’ll need to start by installing the SQLite for Windows and SQLite for Windows Phone extensions. If you’re only interested in supporting one of the platforms then you just need to install the extensions for that platform.

Links
SQLite for Windows Runtime
SQLite for Windows Phone

- You can either use these links to the extensions, or you can search the Visual Studio gallery from within Visual Studio. Go to Tools –> Extensions and Updates; search Online for SQLite. You’ll need to restart Visual Studio after installing both extensions.

- Create both a Windows Phone and a Windows 8 project within the same solution.

- For Windows Phone you’ll need an additional library that acts as a bridge between the native and managed world. This is the sqlite-net-wp8 library – Just because it’s on git, you don’t need to clone it; simply click the Zip download button to take a copy of the library.

image

- Unblock and extract the sqlite-net-wp8 library and copy the project into your solution folder.

- Add the sqlite-net-wp8 project into your solution.

- Add a reference from your Windows Phone project to the sqlite-net-wp8 project

- Add a reference to the SQLite for Windows Runtime extension to your Windows 8 project

image

- Next, you need to add sqlite-net from nuget – install this into both Windows 8 and Windows Phone projects. You should see it add both Sqlite.cs and SqliteAsync.cs files to these projects. These files project an easy to use, linq style, wrapper around Sqlite (remember our Objects not Sql goal!)

image

- Open the project properties page for the Windows Phone project by double-clicking on the properties node in Solution Explorer. Add USE_WP8_NATIVE_SQLITE to the Conditional compilation symbols for All Configurations and All Platforms via the Build tab.

image

- We’re almost there, we just need to write some code. Add the following code to the MainPage.xaml.cs pages (remembering to add the appropriate using statements).

public static string DB_PATH = Path.Combine(

Path.Combine(ApplicationData.Current.LocalFolder.Path,

"sample.sqlite"));

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
 
    using (var con = new SQLiteConnection(DB_PATH))
    {
        con.BeginTransaction();
        con.CreateTable<Person>();
        con.Insert(new Person { Name = "Nick", Age = 15 });
 
        var people = con.Table<Person>().ToArray();
        Debug.WriteLine(people.Length);
        con.Commit();
    }
}
 
public class Person
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

 

- At this point we have all the bits we need but you’ll probably find when you attempt to run either application you’ll run into build errors to do with the supported architectures. You’ll need to alter the build configuration (right-click on the solution in Solution Explorer and select Configuration Manager). Remember you need x86 for the emulator and ARM for debugging on a real device (and the store).

image

With the correct configuration set, you should be all good to go to continue using sqlite

So, how did we go with our goals

- Blendable: Tick! We haven’t done anything to break this requirement

- Sqlite: Tick! Again, we’re using Sqlite

- PCL: Fail – Again, we don’t have a PCL – we’ll need another wrapper to make this happen

- Objects Not SQL: Tick! Woot! we’re stepping in the right direction now with working with objects

Stay tuned for the next instalment when we look at fixing the PCL issue.

Windows (RT and Phone) and Sqlite (Part 1)

Increasingly the projects that we’re undertaking at Built to Roam and Pixel and Sons span both Windows Phone and Windows 8 (aka WinRT). For anyone who’s worked across these platforms you’ll be aware that they’re similar, yet frustratingly different, requiring a significant amount of rework when building applications for both. We’ve attempted to minimise this through the use of both MVVM and Portable Class Libraries. The former allows us to have view models that work across both platforms, the latter allow us to house those view models (and a large proportion of our application logic) in a reusable library that is shared (without the need to recompile) between both our Windows 8 and Windows Phone applications.

One of the areas that we’ve avoided to date is the need to store data using an actual database (across both platforms). We’ve had Windows Phone projects where we’ve used Linq to Sql or the managed wrapper for sqlite; for other projects we’ve chosed to store either xml or json to a flat file on disk. This post is about the learnings taken from a relatively frustrating week trying to see how Microsoft has delivered (or hasn’t delivered) on their announcement last year to support sqlite across both Windows Phone and Windows 8.

Firstly, let me talk about my goals:

- Blendable: My project has to be designable in Blend at all times!

- Sqlite: I want to use sqlite to store relational data across both Win8 and WP applications

- PCL: I want to be able to do all my data access from a portable class library

- Objects Not SQL: I want to be able to read and write objects, rather than write sql statements

Let’s go through these in detail:

Blendable

You might think this a silly requirement when referring to data access. However, I have this as a prerequisite for any library or component that I’m considering. If it ain’t Blendable, it doesn’t make it through the door. I work with some awesome designers who actually know how to work with XAML. I don’t want them hand crafting it, or ideally opening VS, as this just lowers their productivity.

Sqlite

Well duh! Although actually it’s not such a silly requirement – in a lot of cases there is a massive trade off between flat files (super simple) and database (quick but frustrating to work with). More often than not, flat files win as we’re not scanning large number of items by index or doing large complex joins (that’s server stuff, typically).

PCL

I want to reuse an entire library without recompiling across both Windows 8 and Windows Phone, not just share code with # conditional compilation blocks.

Objects Not SQL

Seriously, this is like writing apps in HTML v’s XAML (oh wait, people still do this….let me think of a better example). Writing data access by hand crafting sql statements is for muppets, particularly on a client device where you shouldn’t be doing massive heavy lifting. Do this, and you should be considering which mainframe you’re going to be maintaining in 5 years time. Get with the program, use some object to sql mapper that doesn’t mean you’re writing sql code for client applications.

 

I think I’ve been pretty clear on my goals, so lets get into it and look at the options:

1) Use the existing managed sqlite library that was created for Window Phone 7.

(this one has been discounted as I don’t believe we’re after a managed implementation of sqlite as we’re not going to get the level of performance we really want)

2) Use sqlite-net (in conjunction with sqlite-net-wp8, a native to managed wrapper layer for Windows Phone)

3) Use the recently announced sqlite-winrt across on codeplex

I’m sure there might be other options but these are the ones I’ll be covering in these posts. This post we’ll actually take a look at the third option, sqlite-winrt, which has recently been announced on the Windows Phone developer blog.

Sqlite-Winrt: SQLite WinRT wrapper for WinRT (ie Window8 and Windows Phone)

Here are the steps I went through in my quick exploration:

- Go to the sqlite-winrt project on codeplex: http://sqlwinrt.codeplex.com

- Switch to the source code tab (there’s no actual releases yet) and click the download button

image

- When prompted save the zip file, then open windows explorer and “unblock” the zip file (right-click on file, select properties, click unblock button)

- Unzip the downloaded file and attempt to open the solution by double-clicking the .sln file (currently SqliteWinRTComponents.sln).

*** At this point I get a “failed to open project” notice from Visual Studio because I haven’t installed both the SQLite for Windows and SQLite for Windows Phone extensions. If you’re only interested in supporting one of the platforms then you just need to install the extensions for that platform, and simply ignore the error since it is just pointing out it can’t load one of the projects.

Links
   SQLite for Windows Runtime
   SQLite for Windows Phone

- Restart and Reload solution if you had to install one or more of the extensions

- At this point you should double-check you can build both projects. You can’t run anything because you only have two libraries (one for WinRT and one for Windows Phone)

- Add a Windows Phone application

- Add a reference to the SQLiteWinRTPhone library to your Windows Phone application.

- Update the MainPage.xaml.cs file to include the following code:

using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using SQLiteWinRTPhone;
using Windows.Storage;
 
namespace SqliteWPTest
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
 
            await CreateCitiesDatabase();
        }
 
        private async Task CreateCitiesDatabase()
        {
            // Get the file from the install location  
            var file =
                await
                ApplicationData.Current.LocalFolder.CreateFileAsync
              ("cities.db", CreationCollisionOption.OpenIfExists);
 
            // Create a new SQLite instance for the file 
            using (var db = new Database(file))
            {
 
                // Open the database asynchronously
                await db.OpenAsync(SqliteOpenMode.OpenReadWrite);
 
                await db.ExecuteStatementAsync
("CREATE TABLE Cities (rowid INTEGER PRIMARY KEY ASC, CityName TEXT);");
 
                await db.ExecuteStatementAsync
("INSERT INTO Cities (rowid, CityName) VALUES (1, 'Perth');");
 
                // Prepare a SQL statement to be executed

var statement = await db.PrepareStatementAsync

("SELECT rowid, CityName FROM Cities;");

 
                // Loop through all the results and display them
                while (await statement.StepAsync())
                    MessageBox.Show(statement.GetIntAt(0) + ": " + statement.GetTextAt(1));
            }
        }
    }
}

 

- Ok, you’re good to run (at least on the emulator) This will work the first time through but fail the next because it attempts to create the Cities table multiple time. I’ll leave it to you to refine the code.

- You might also want to run on a device. When I switched targets to Device I got the following error when attempting to debug:

image

- To fix this, right-click on your solution in Solution Explorer and select Configuration Manager. Change the Active solution platform to ARM.

image

- Rinse and repeat for WinRT. Make sure you reference the correct SQLite wrapper (Resharper caught me out here and automatically added a reference to the phone wrapper). Also, you’ll need to change MessageBox to use the MessageDialog class.

The question is now how did we go on our goals:

- Blendable: Tick! We haven’t done anything to break this requirement

- Sqlite: Tick! We’ll we’re using SQLite, right! You can validate this by copying the db file out of isolated storage onto your host computer and using a tool like sqlitebrowser to open it

- PCL: Fail – not a PCL in sight. The code is tightly coupled with the Sqlite wrappers. Looks like we’re going to have to add another indirection layer here to get this to work….

- Objects Not SQL: Fail. Hmmm, I’m not going any further here. I can see this as being useful for those wishing to write raw sql but for me, I’m going to invest time elsewhere.

 

That’s enough sqlite for one day. I’ll be back with part 2 where we’ll look at sqlite-net and how you can use this to give you objects instead of sql. Part 3 will look at how we can fix the lack of PCL support (for both sqlite-winrt and sqlite-net).

Windows Phone App Manager

We’ve been working closely with the local enterprise sales team at Microsoft around the opportunities to use Windows Phone in the enterprise. Personally I think this is where Windows Phone is going to absolutely rule the roost – integration into Exchange, Sharepoint, Office apps, and of course device management through your favourite MDM solution. Something that comes up early in this discussion is “how do I build a company hub for my organisation?” Well we’ve recently released the first version of the Windows Phone App Manager to the Windows 8 store.

 

image

Windows Phone App Manager app for Windows in the Windows Store

http://apps.microsoft.com/webpdp/app/bcc487fc-d810-4c83-ab17-e58785478a8f

Learn more about Windows Phone App Manager by Built to Roam Pty Ltd and download it from the Windows Store

 

We’ve also been working on a getting started guide – this is particularly important with this release as we’re still working through refining the UX so make it easier for companies to build their company hub.

Update: The Windows Phone App Manager has been updated to include the ability to specify floors, rooms and internal directions using NFC.

Windows Phone Developer Workshop

Adelaide Windows Phone 8 Developers Workshop Fri/Sat, May 3rd and 4th

Calling all SA Adelaide based Mobile developers, Microsoft and Nokia are delighted to announce that we’ve have extended the Windows Phone 8 Developer series of workshops to now include Adelaide.

Windows Phone 8 is a huge step forward, not only maintaining compatibility with existing Windows Phone apps, but embraces a number of core Windows 8 technologies, bringing significant performance improvements, support for managed and native C++ development, in app purchase, wallet, NFC, developer access to the Bluetooth and speech APIs, and more. See Windows Phone 8 developer platform highlights.

This two day workshop is scheduled for Friday May 3rd and Saturday May 4th. The first day is a presentation day that will get you up to speed with the Windows Phone 8 developer platform. Day two (Saturday) is a hands on labs day to guide you through the experience of building Windows Phone apps.

REGISTER

Day 1 - Presentation Day

Day 2 - Hands on Labs Day

Authentication Issues with Windows Azure Mobile Services

Here are just a couple of gotchas I ran into whilst setting up a Windows Azure Mobile Service to accept login requests from all four providers: Microsoft Account, Facebook, Twitter, Google.

Firstly, grab the site url for your mobile service – On the Dashboard tab the “Mobile Service Url” is on the right under “quick glance”

image

 

Microsoft Account (Instructions)

image

- The name of my application contained words that weren’t allowed. This includes trademarked words such as “Windows Phone”. Unfortunately this meant that when I attempted to set the Redirect URI  and hit Save, nothing appears to happen – the error is not visible as it’s on a different tab. Solution was to change the Application name, then hey presto it works.

 

Google (Instructions)

image

- Make sure you set the type to Web application

- When I created the client id I could only set the site/hostname. You actually need to go back and edit the settings to set the redirect uri to “https://[your mobile service].azure-mobile.net/login/google (note the /login/google at the end)

 

Facebook

image

- Check the website with Facebook login, and specify the site URL

 

Twitter

image

- You need to specify both the website url and the callback uri

 

Hopefully this helps someone get up and running in less time than it took me!

Built to Roam Offices and Staff

It’s been an whirlwind start to the new year for Built to Roam. We’ve just got back from the US and so I thought it’d be a perfect opportunity to share some of the exciting things that are in the pipeline for Built to Roam this year:

New Office

That’s right, we’re stepping out and now have an awesome office space located in North Sydney. This will allow us to be more productive and have a suitable work space for the team as we grow.

New Staff

Yes, you read it right, we’re growing. We’re super happy to have Dave Lasike (and more apps) join us at Built to Roam.  There is so much interest in Windows Phone and Windows 8 that we’re going to need all hands on deck this year to make sure we continue to deliver amazing apps for both platforms.

New Business

In the past building amazing apps typically meant working with an external design team, whether internal to the customer we’re working with or another design studio. This has meant on a number of occasions working with the team at Automatic Studio, lead by the Metro Modern UI wizard, Shane Morris. We’re super proud to announce that we’ve worked together again, this time in the form of a new design and development agency, Pixel and Sons

New Opportunities

If you thought last year was exciting with the release of Windows Phone 8 and Windows 8, you’re not alone. With momentum building for both platforms, this year will see a number of big name brands appear across the whole ecosystem. Our advice is don’t get left behind, make sure you contact us so that we can assist you take advantage of these new platforms and extend the reach of your product set.

Windows Phone 8 Jumpstart Content and Samples

  • Videos via Channel 9

Mod 01a: Introducing Windows Phone 8 Development Part 1
Mod 01b: Introducing Windows Phone 8 Development Part 2
Mod 02: Designing Windows Phone 8 Apps
Mod 03: Building Windows Phone 8 Apps
Mod 04: Files and Storage on Windows Phone 8
Mod 05: Windows Phone 8 Application Lifecycle
Mod 06: Background Agents
Mod 07: Tiles and Lock Screen Notifications
Mod 08: Push Notifications
Mod 09: Using Phone Resources in Windows Phone 8
Mod 10: App to App Communication in Windows Phone 8
Mod 11: Network Communication in Windows Phone 8
Mod 12: Proximity Sensors and Bluetooth in Windows Phone 8
Mod 13: Speech Input in Windows Phone 8
Mod 14: Maps and Location in Windows Phone 8
Mod 15: Wallet Support
Mod 16: In-App Purchasing
Mod 17: The Windows Phone Store
Mod 18: Enterprise App Architecture
Mod 19: Windows Phone 8 and Windows 8 Cross Platform Development
Mod 20: Mobile Web

Samples

Windows Phone 8 JumpStart- Contoso Cookbook Step 1, Initial Layout

Windows Phone 8 JumpStart- Contoso Cookbook Step 2, Styles and Alignment

Windows Phone 8 JumpStart- Contoso Cookbook Step 3, Design Time Data

Windows Phone 8 JumpStart- Contoso Cookbook Step 4, Data Binding

Windows Phone 8 JumpStart- Contoso Cookbook Step 5, List Templates

Windows Phone 8 JumpStart- Contoso Cookbook Step 6, Page Navigation

Windows Phone 8 JumpStart- Contoso Cookbook Step 7, Application Bar

Windows Phone 8 JumpStart- Contoso Cookbook Step 8, Landscape Orientation

Windows Phone 8 JumpStart- Contoso Cookbook Step 9, Screen Resolutions

Windows Phone 8 JumpStart- Contoso Cookbook Step 10, Localization

Windows Phone 8 JumpStart- Contoso Cookbook Step 11, Page Transitions

Windows Phone 8 JumpStart- Module 4 Storage Demos

Windows Phone 8 JumpStart- Module 5 Application Lifecycle Demo

Windows Phone 8 JumpStart- Module 6 Background Agents Demo

Windows Phone 8 JumpStart- Module 7 Tiles and Lockscreen Notifications Demos

Windows Phone 8 JumpStart- Module 8 Push Notifications Demos

Windows Phone 8 JumpStart- Module 9 Using Phone Resources Demos

Windows Phone 8 JumpStart- Module 10 App to App Communication

Windows Phone 8 JumpStart- Module 11 Networking Demos

Windows Phone 8 JumpStart- Module 12 NFC and Bluetooth Demos

Windows Phone 8 JumpStart- Module 13 Speech Demos

Windows Phone 8 JumpStart- Module 14 Location and Maps Demos

Windows Phone 8 JumpStart- Module 15 Wallet Demos

Windows Phone 8 JumpStart- Module 16 In-App Purchasing Demo

Windows Phone 8 JumpStart- Module 17 Windows Phone Store Demos

Windows Phone 8 JumpStart- Module 19 Windows Phone 8 & Windows 8 Cross Platform

Windows Phone 8 JumpStart- Managed App Calling Native Library

Windows Phone 8 JumpStart- PhotoSnap

Windows Phone 8 JumpStart- Location Tracker

Windows Phone 8 SDK - Deploying Multiple Enterprise Applications

I’ve already talked about the basics of enterprise application deployment with Windows Phone 8, which you can find in the following two posts.

Windows Phone 8 SDK- Enterprise Application Deployment

Windows Phone 8 SDK- Enterprise Applications (part 2)

In this post we’re going to look at how you can start to manage and deploy multiple enterprise applications. Of course, there will be some organisations who use an MDM provider (for example Silverback) which will facilitate the deployment of applications to specific groups of employees. However, there will be some organisations that elect not to use an MDM, and yet still want to deploy multiple enterprise applications. For this you can use some of the new APIs in Windows Phone 8 to enumerate installed applications and prompt for installation of applications.

Let’s put this in a bit of context – a common starting point is to roll out a company hub style application. By this we mean a simple enterprise application (ie signed by the enterprise for internal distribution) which might list internal news, relevant links and a list of other enterprise applications that are available for installation. The company hub might also require the user to enter credentials in order to personalise these items (eg present only applications that the user should have access to)

image

If the user clicks on these applications there are a number of ways that the company hub can install the selected application. Assuming that the application is stored on a remote server you can simply launch the uri pointing to the xap file.

private void InstallAppClick(object sender, RoutedEventArgs e)
{
    var url = new Uri("http://mydomain.com/myapp.xap");
    Launcher.LaunchUriAsync(url);
}

Whilst this will work, assuming that the enterprise certificate that the application has been signed with is already installed on the device, it doesn’t provide a great experience for the user. Another alternative is to use the AddPackageAsync method on the InstallationManager.

private async void InstallAppClick(object sender, RoutedEventArgs e)
{
    var url = new Uri("http://mydomain.com/myapp.xap");
    var status = InstallationManager.AddPackageAsync("MyApp", url);
    status.Progress += UpdateProgress;
    await status;
}
private void UpdateProgress(IAsyncOperationWithProgress<PackageInstallResult, uint> asyncinfo, uint progressinfo)
{
    // Update UI with progress
}

The return value from the AddPackageAsync method can be used to retrieve installation progress information that can be displayed within the company hub whilst the application is being installed.

Both these alternatives download the xap in clear form from the remote server. Whilst this might be ok if the user is on an intranet, it’s not a great solution if you want to make applications accessible to remote users (which you would hope would be the case since they’re mobile….). In this case you really need to ensure the application is encrypted or protected somehow to prevent the applications from being decompiled. The script for signing the applications does not provide any level of protection – it simply invokes a native compile of the dlls and then signs both dlls and xap. As such you should consider applying your own level of protection, which in turn means we need an alternative method to install the applications via the company hub.

One solution is to package the other applications into the company hub. Each application needs to be created and then signed using the enterprise certificate. They’re then added to the company hub project with the build action property set to Content – this ensures they’re packaged with the company hub. Once the company hub has been installed the user can select one of the applications packaged with the company hub for installation. Since the application isn’t downloaded there is no way to intercept it, so no further protection is required. This method again uses the AddPackageAsync but this time with a uri that points to a file packaged with the company hub (progress reporting has been omitted for brevity). Alternatively you can also use the Launcher.LaunchFileAsync with a reference to the file but again this doesn’t report on the installation progress.

private async void InstallAppClick(object sender, RoutedEventArgs e)
{
    var file = await StorageFile.GetFileFromApplicationUriAsync(new System.Uri("ms-appx:///myapp.xap"));
    var fullSystemPath = new Uri("file://" + file.Path);
    await InstallationManager.AddPackageAsync("MyApp", fullSystemPath);
}

One thing to note here is the slightly unusual path syntax that is required by the AddPackageAsync method. It will not work with either a relative uri or a uri starting with ms-appx or ms-appdata.

The downside of this method is that you need to bundle all the other applications into the company hub, even if they’re not relevant to the current user. A better solution is to download an encrypted application from a remote server, decrypt it locally, and then install the application from isolated storage. In this post we won’t cover the first two steps, as this is up to the organisation as to how they wish to encrypt the application file and distribute the keys to the company hub application so it can decrypt the application file. The last step is actually similar to installing an application that is packaged with the company hub. However, this time the file is stored in isolated storage, which slightly changes the way the file path is constructed (you could also use new Uri(“ms-appdata://local/MyApp.xap”) rather than using the LocalFolder).

private async void InstallAppClick(object sender, RoutedEventArgs e)
{
    var storageFolder = ApplicationData.Current.LocalFolder;
    var file = await storageFolder.GetFileAsync("MyApp.xap");
    var fullSystemPath = new Uri("file://" + file.Path);
    await InstallationManager.AddPackageAsync("MyApp", fullSystemPath);
}

In this post you’ve seen how you can install additional enterprise applications from a company hub. In deciding which method to use you should consider both the sensitivity of the application logic and the risk of data being intercepted.

DNS Client for Windows and Windows Phone

Don’t ask why, but I needed to be able to do a dns record lookup for a srv record from a Windows Phone application. I went looking for a library that could do this and came up with Phone Net Tools (http://phonenettools.codeplex.com/) – this seems a great library but fairly rudimentary support for DNS queries. I also came across a great post by Rob Philpott on CodeProject (http://www.codeproject.com/Articles/12072/C-NET-DNS-query-component) – it’s a bit dated and for legacy technologies (I needed to upgrade everything to even run it!). Whilst this option seemed to be more painful to update the architecture seemed to lead itself to being extended to support srv records. The net effect is there is yet another library on codeplex, this one dedicated to doing DNS lookups from a Windows 8 or Windows Phone application.

At the moment I’ve only got the Windows Phone version uploaded to the Windows and Windows Phone DNS Library. It’s relatively simple to use:

// create a DNS request
var request = new Request();

var domain = "builttoroam.com";
var type = DnsType.MX;
var dnsServer = IPAddress.Parse("203.0.178.191");

// create a question for this domain and DNS CLASS
request.AddQuestion(new Question(domain, type, DnsClass.IN));

// send it to the DNS server and get the response
//Response response =

var resp = await Resolver.Lookup(request, dnsServer);
foreach (var answer in resp.Answers)
{
    Debug.WriteLine("{0}", answer.Record);   
}

Develop for Windows Phone and Windows using Portable Class Library

In the past I wasn’t a big fan of the Portable Class Library as I felt it imposed more restrictions than necessary and would constrain/frustrate developers more than it would actually solve a problem. However, in recent times a couple of things have happened that have made this whole experience a lot better.

Firstly, we no longer need to drag out VS2010 to do Windows Phone 7 development. The new Windows Phone 8 SDK plugs into VS2012 and allows for both WP7 and WP8 app development. This means that if you’re going to be targeting multiple versions of WP you can do so in the same solution.

Next, the release of Microsoft.Bcl.Async on nuget – ok, you’re probably thinking what’s that? Well a while ago Microsoft published the Async programming CTP. Whilst it had a go-live license and could be used in your Windows Phone 7 project it was a hassle to install in VS2010 (due to a weird set of dependencies which were broken with subsequent updates to VS) and didn’t support VS2012 at all. The Microsoft.Bcl.Async package is the replacement for the Async CTP, allowing you to do asynchronous programming in WP7 apps. Of course, both Win8 and WP8 support async programming out of the box.

Ok, on to using a Portable Class Library. The concept here is that you want to build a single, managed, library that can be referenced by applications targeting different platforms. Let’s walk through a simple example.

We’re going to start by creating three different applications within the sample solution: SimplePCLTestApp.WP7, SimplePCLTestApp.WP8 and SimplePCLTestApp.Win8. As the project names suggest the projects should be targetting WP7, WP8 and Win8 respectively. We’re then going to also create a Portable Class Library called SimplePCL. Note, when you go to create the PCL you’ll see a prompt similar to the following image. This allows you to specify which frameworks your going to be targeting. In this case we’ll take the default options as we’re not going to be building for XBox.

image

The next thing to do is to add the Microsoft.Bcl.Async nuget package into the WP7 and PCL projects. The following image illustrates the package that you’re after.

image

Unfortunately at the moment when you attempt to add this package it won’t give you the option to add it to the PCL. It appears there is some incompatibilities with the current version of the nuget package for Microsoft.Bcl.Async and the PCL. Luckily it’s relatively easy to fix manually:

> Unload the PCL project
> Right-click on the PCL project and select Edit SimplePCL.csproj
> Now, replace the following element

<ItemGroup>
  <!-- A reference to the entire .NET Framework is automatically included -->
</ItemGroup>

With

<ItemGroup>
<Reference Include="Microsoft.Threading.Tasks">
    <HintPath>..\packages\Microsoft.Bcl.Async.1.0.12-beta\lib\sl4-windowsphone71\Microsoft.Threading.Tasks.dll</HintPath>
  </Reference>
  <Reference Include="Microsoft.Threading.Tasks.Extensions">
    <HintPath>..\packages\Microsoft.Bcl.Async.1.0.12-beta\lib\sl4-windowsphone71\Microsoft.Threading.Tasks.Extensions.dll</HintPath>
  </Reference>
  <Reference Include="Microsoft.Threading.Tasks.Extensions.Phone">
    <HintPath>..\packages\Microsoft.Bcl.Async.1.0.12-beta\lib\sl4-windowsphone71\Microsoft.Threading.Tasks.Extensions.Phone.dll</HintPath>
  </Reference>
  <Reference Include="System.Runtime">
    <HintPath>..\packages\Microsoft.Bcl.1.0.11-beta\lib\sl4-windowsphone71\System.Runtime.dll</HintPath>
  </Reference>
  <Reference Include="System.Threading.Tasks">
    <HintPath>..\packages\Microsoft.Bcl.1.0.11-beta\lib\sl4-windowsphone71\System.Threading.Tasks.dll</HintPath>
  </Reference>
</ItemGroup>

> Save, and reload the PCL project

The last preparatory step is to add a reference to the PCL project to each of our applications. This is done as per normal by right-clicking the project, selecting Add Reference, and then selecting the PCL project from the solution node.

We’re now ready to start writing some code. We’ll rename Class1 to ExampleClass and add the following code:

public class ExampleClass:INotifyPropertyChanged {
    private string name;
    public string Name {
        get { return name; }
        set {
            if (Name == value) return;
            name = value;
            OnPropertyChanged();
        }
    }
 
    public event PropertyChangedEventHandler PropertyChanged;
   [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private readonly ManualResetEvent sleepEvent = new ManualResetEvent(false);
    public async Task UpdateName(string newName)  {
        await Task.Factory.StartNew(() =>
                                        {
                                            // This will sleep waiting for a signal that will never happen!
                                            sleepEvent.WaitOne(1000);

                                       });
    Name = newName;
   }
}

This simple class illustrates a couple of different things:

- The use of INotifyPropertyChanged – almost essential for view models, which you will probably want to share across projects if you’re using MVVM. Note the OnPropertyChanged method uses the CallerMemberName attribute, rather than the property name having to be specified when the method is called.

- The UpdateName method is an asynchronous method which launches a background task using Task.StartNew. This is to simulate some long running task (eg service call, or disk I/O). There is no support for Thread.Sleep in the PCL so we’ve used a workaround which involves waiting for a reset event that will never happen.

- The Name property is updated after the background task has completed. If this method was invoked on the UI thread then it’s safe to update the Name property, since the PropertyChanged event also needs to be invoked on the UI thread to prevent a cross threading violation.

We can then add the following code to the main page of each of our applications:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);


    var example = new ExampleClass();
    example.PropertyChanged+=ExamplePropertyChanged;
    example.Name = "Initial Name";
    Debug.WriteLine("-------------------------");
    await example.UpdateName("Updated Name");
    Debug.WriteLine("-------------------------");
}

private void ExamplePropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var ex = sender as ExampleClass;
    Debug.WriteLine(ex.Name);
}

Running this, in all cases, should yield the following Debug output (you may see some additional assembly/type loading information as well):

Initial Name
-------------------------
Updated Name
-------------------------

And there you have it. An example of how you can use a Portable Class Library to abstract our your platform independent code.

Windows Phone 8 SDK: Accessing Content from an SD Card

Before you get all excited and worked up about the fact that you can use an SD card with the new Windows Phone SDK there are a couple of limitations that you need to be aware of. Keep in mind that one of the primary scenarios that was being solved was the distribution of apps (errr, did I mention apps…. this is limited to Enterprise apps) and content, rather than being an extension to the device storage.

- You can only access file types that you’ve registered for (this excludes the standard file format – which is a bit nasty if you want your app to say process images or documents supplied on an SD card).

- You can only read from SD card.

Ok, with these limitations in mind, let’s take a shot at reading from an SD card.

First up, we need to get an SD card (oh and a real Windows Phone 8 device to work with) and put some content on it. In this scenario we’re going to use a sqlite database called mydata.sqlite. I simply inserted the Micro SD card, using an SD card adapter, into my laptop and copied across the existing sqlite file. I then inserted the card into my Windows Phone 8 device.

Next, I opened my Windows Phone 8 project and added a couple of nuget packages. These are only required if you’re using sqlite, if you’re using some other file type, you don’t need to worry about these packages.

wp7sqlite – This is a managed implementation of sqlite
sqlite-net – This is a super-easy wrapper that you can use in order to access the content.

image

Unfortunately, whilst these two packages were designed to work together, for some reason the versions that are in nuget are incompatible, requiring some minor modifications to get them to work. Luckily this is mostly a matter of replacing “out” with “ref” in a couple of methods.

The next thing to do is to declare our intent to a) read from the SD card and b) what file types we want to be able to access. Double-click the WMAppManifest.xml to open the designer, switch to the Capabilities tab and check the ID_CAP_REMOVABLE_STORAGE capability.

image

Close the manifest designer, right-click on the WMAppManifest.xml file and select Open With. Select XML (Text) Editor and hit Ok. You need to add a FileTypeAssociation element into the Extensions element. If Extensions doesn’t exist, you may need to create that too – it needs to sit after the Tokens element but before the ScreenResolutions element.

</Tokens>
   <Extensions>
     <FileTypeAssociation Name="sqlite" TaskID="_default" NavUriFragment="fileToken=%s">
       <SupportedFileTypes>
         <FileType ContentType="application/sqlite">.sqlite</FileType>
       </SupportedFileTypes>
     </FileTypeAssociation>
   </Extensions>
   <ScreenResolutions>

Now all that’s left is to write some code in order to access the content from the sd card. If you’re simply going to read from the files you can do so in situ. However, in this case we’re eventually going to want to write to the file, so we’re going to copy it to Isolated Storage first.

// Connect to the current SD card.
var sdCard = (await ExternalStorage.GetExternalStorageDevicesAsync()).FirstOrDefault();

var routeFiles = await sdCard.GetFileAsync("mydata.sqlite");
using (var source = await routeFiles.OpenForReadAsync())
using (
    var target = IsolatedStorageFile.GetUserStoreForApplication()
                                    .OpenFile("writeablecopy.sqlite", FileMode.Create, FileAccess.Write))
{
    await source.CopyToAsync(target);
}

var db = new SQLiteAsyncConnection("writeablecopy.sqlite");
var existing = await db.QueryAsync<MyDataObject>("select * from data");
var data = existing.ToArray();

Don’t forget you’ll want to add appropriate error detection and check that an SD card even exists before you attempt to read from it. For those following the sqlite portion, the MyDataObject class is a relatively simply class, the sqlite-net wrapper handles the conversion between the sqlite data and the .net types:

public class MyDataObject
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
}

Cancel My Newspaper Subscription: Would a Real Journalist Please Stand Up!

Over the last 48 hours Microsoft has launched Windows Phone 8 (press kit here) and the developer tools, the Windows Phone 8 SDK. Unfortunately there seems to be a spate of bad journalist here in Australia. Rather than actually spending time the platform they insist on quoting other, somewhat biased, journalist. Specifically this piece by Ben Grubb at SMH (http://www.smh.com.au/digital-life/mobiles/windows-phone-8-cant-catch-big-two-20121030-28hed.html). Let’s drill in and see what Ben said quoted:

- First, he states that Microsoft is so far behind Android and iOS that it sees RIM as it’s main rival. This comment is completely out of context and he provides no actual basis. It’s a reality that RIM is the closest in market share, so of course they are the next target in terms of just acquiring market share. This in itself doesn’t mean that Microsoft isn’t looking to capture a much larger market share. If you look at device features, variety, developer platform/tools etc, Microsoft isn’t lagging. In terms of apps, there is a way to go before we get to where Android or iOS is but that’s a result of how long the platform has been around more than anything.

- Next, he says that analysts are saying Microsoft is wrong and has no hope…. Really, again who said this. If this is what you believe, then how about putting your name to this comment.

- It’s great that the only quotes from Microsoft is about how hard it is to compete in a market that’s heavily saturated by the incumbent platforms. Well duh! this isn’t news. How about giving us a run down on all the new features of Windows Phone 8, instead of boring us with the obvious.

- I’m not going to bore you with any more of the quotes, rather than any useful commentary that Ben could have offered if he’d actually bothered to use a Windows Phone 8 device. However I’ll leave you with one last example. Ben quotes Joseph Sweeney of IBRS who has made the comment that he didn’t “really see much new”. Hmmm, and adding a fifth row of icons on the iphone 5 was a ground breaking UI change was it. Here’s a list of some of the changes that are in Windows Phone 8 (I’ll leave it to you to work out whether you think they’re new or not):

* Live Tiles – this in itself is not new. However, apps can now take advantage of three different sizes, the ability to flip and cycle content through the tiles.

* Kid’s corner – an isolated area of the phone where kids can play without parents worrying about their data or wallet being compromised.

* Lock screen – an app can surface content and information directly to the lock screen

* VOIP – the integration of Skype (and other third party VOIP apps) is at a low level, making it ultra efficient (ie won’t drain your battery) and always on (so you can always receive chat and calls)

* Rooms – an area where you can share content with a group of people

* Wallet - I originally had this in here but the other smartphone platforms are all doing their own interpretation of this so it's not really new.

And this is just to cover some of the consumer features that I believe add to an already awesome phone platform. If you want to see an example of a journalist who has actually taken the time with a phone then read the following http://www.informationweek.com/byte/personal-tech/slick-windows-phone-8-an-acquired-taste/240012565

Windows Phone 8 SDK: Enterprise Applications (part 2)

In the previous post we used the XapSignTool directly in order to sign the enterprise application. One of the changes introduced to Windows Phone is the ability for the Windows Phone store to distribute precompiled applications, making them run that much quicker. In order to take advantage of this for your enterprise applications you need to run the MDILXAPCompile tool which ships with the SDK. Luckily, the team have also provided a powershell command making it dead easy to precompile and sign your application in one easy step.

Firstly, you’ll need to run powershell. Depending on how your system is setup you’ll probably want to run it as administrator as you may need to change the execution policy. If you’re familiar with powershell you can probably skip these steps.

Go to C:\Windows\System32\WindowsPowerShell\v1.0, right click on Powershell.exe and select Run as Administrator

If you run into errors running the powershell script, with an error referring to execution policy, you can adjust the policy as follows (warning this will allow any script to run):

Set-ExecutionPolicy -ExecutionPolicy Unrestricted

Change directories to the MDILXAPCompile tools folder within the SDK:

cd ‘C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\MDILXAPCompile\’

Run BuildMDILXap.ps1

.\BuildMDILXap.ps1 –xapfilename 'c:\temp\Provisioning\SimpleCompanyApp.xap' –pfxfilename 'c:\temp\companyappcert.p12' –password mypassword

The output should look like the following

image

Windows Phone 8 SDK: Enterprise Application Deployment

This is a step by step guide to preparing your organisation so that you can sign and deploy enterprise applications.

Certificate Acquisition

Get your Publisher ID/Symantec Id and Approver Email Address

First up you’re going to need your Publisher ID (also referred to as Symantec Id) and Approver Email Address.

These can both be retrieved from your Dev Center account (Must be Company account type)

image

- Type (Blue box): This has to be Company

- Symantec Id (Green box): This is your publisher Id or Symantec Id (as distinct from your Publisher GUID)

- Email (Purple box): This is not necessarily your approver email address

Click Edit (under Contact info) and scroll to bottom of page

clip_image002

- Email address (Blue box): This is the approver email address

Request Certificate

Navigate to https://products.websecurity.symantec.com/orders/enrollment/microsoftCert.do

Enter Publisher ID and Approver Email Address

clip_image004

Complete Billing information

clip_image005

clip_image007

Agree to terms

clip_image009

Confirmation of order completion

clip_image011

Approve your Certificate Request

You’ll need to monitor the approver email address for “Enterprise Code Signing Certificate Order Approval”. If this is someone else in the organisation you must warn them – if they receive this and accidentally click the “I Do Not Approve” option it will result in significant delays.

Click appropriate link to website to review and approve/reject order

clip_image013

Click “I Approve” button

clip_image014

Confirmation of approval

clip_image015

Retrieve your Certificate

You should receive confirmation email that the order has been approved.

clip_image016

Follow the link to retrieve the certificate. This should be done on the same computer and in same browser that the initial request was made.

clip_image018

clip_image020
Click Continue to retrieve the certifcate

Review certificates for the browser. Eg Firefox it’s in Options > Advanced > View Certificates

clip_image022

Click Backup and save the certificate (eg companyappcert.p12 or companyappcert.pfx) complete with private key (you need to set a password)

Open Certificate Manager management console (Start > Run > Certmgr.msc) and confirm that certificate exists and that the full Certification Path exists. This is a common error – only the leaf node is exported. Make sure you have the full path as illustrated in the screenshot below.

clip_image024

Signing and Deploying Applications

Create Application

Create your application as normal. When you want to deploy your application, take a copy of the XAP file that can be located in the \Bin\Release folder of your application.

Sign Application

Open “Developer Command Prompt for VS2012”.

Warning: Make sure you open the correct command prompt as not all of them have the same environment parameters set. This may prevent some of the tools running correctly.

Run the XapSignTool supplying the name of the XAP file as a parameter:

"C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\XapSignTool\XapSignTool.exe" sign /v c:\temp\Provisioning\SimpleCompanyApp.xap

Note:

/v Indicates verbose output – this will be necessary if you have multiple certificates that could be used for signing (which is more than likely)

The next step can be skipped if signing completed correctly. If there are multiple certificates found you’ll need to identify which one you want to use (hence the /v option so that it lists them)

clip_image025

Locate the Symantec Enterprise Mobile CA for Microsoft and copy the SHA1 Hash value (right-click command window and select Mark, select SHA1 value and press Enter to copy value).

Now run XapSignTool again with SHA1 hash value specified

"C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\XapSignTool\XapSignTool.exe" sign /v /sha1 XXXX……hash value….......XXXX c:\temp\Provisioning\SimpleCompanyApp.xap

clip_image027

If successfully run then the original XAP will be replaced by the signed XAP. This file can be hosted on a server for downloading directly to device. Should be protected by credentials and available only over SSL. Whilst it is signed it is not encrypted so can be decompiled.

Warning: The permissions on the file may be changed as part of this process. You may need to reset permissions on the file in order for it to be able to be downloaded to the device.

Generate Application Enrolment Token

From command prompt run AetGenerator (first parameter is the backed up certificate; second parameter is corresponding password).

"c:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\AETGenerator\AetGenerator.exe" companyappcert.p12 mypassword

clip_image028

Deployment of Application Enrolment Token

This can be emailed to the device as an attachment

clip_image030

Click on attachment to download. Once downloaded, click on attachment again to open.

clip_image031

Deployment of Signed Application

Open url of hosted XAP file in Internet Explorer

clip_image033

When prompted confirm installation by clicking Install. Application will then install silently (unlike Store that takes the user to where the application is installed in applications list).

clip_image034clip_image036

Windows Phone 8 SDK: Debugging your Application

Depending on whether your application targets WP7 or WP8 you’ll see different options in the devices dropdown. Since it is possible to run WP7 devices on both WP7 and WP8 devices you’ll see additional options for WP7 targeted applications (right image).

image_thumbimage_thumb1

In the same way that you should always test your application on both the emulator and a real device, for a WP7 application you should test on both the wp7 and wp8 emulators, and ideally both wp7 and wp8 devices. In fact with the new SDK the test matrix just got significantly larger as you need to also test the 720p emulator (I’m less worried about the WXGA emulator since in theory it should just scale up from WVGA – the only thing to watch is that images don’t pixelate).

If you didn’t already realise, the new emulator images are actual hyper-v virtual machines. This means that they will appear in Hyper-V Manager. Although, I wouldn’t recommend attempting to tweak the images via the manager!

image_thumb3

The Additional Tools window includes a Network tab, although in my case it’s a little confusing because there are four adapters. Whilst I haven’t been able to get Fiddler to work with the new emulators it does appear that lower level tools such as Wireshark can be used to monitor traffic – it’s useful to see what the IP address of the emulator is via the Network pane so that you can filter the traffic.

image_thumb5

In the Windows Phone 8 SDK there is another tool that can really assist with debugging applications and their behaviour when interrupted. The Tools menu contains a link to the Simulation Dashboard.

image_thumb8

The Simulation Dashboard (adjusts the currently selected emulator in the device dropdown) allows you to monitor the network speed and signal strength. It also lets you trigger the lock screen and a reminder.

image_thumb10

Being able to trigger a reminder will aid in debugging your application, or game, when it is partially obscured, rather than simply when the user navigates away from your application.

image_thumb7

Windows Phone 8: New Project Structure

In the previous post you would have seen that you can now select with a WP7 or WP8 target when creating a new project with the Windows Phone 8 SDK. With earlier SDK versions the choice of target platform made very little difference to the project structure. Now, there are some substantial differences that you should take note of. The following images illustrate the project structure for Windows Phone 7.1 (left) and Windows Phone 8 (right) projects.

imageimage

Here’s some of my observations:

- There is no splash screen image in the template. Actually WP8 does use the same splashscreen mechanism, requiring the file SplashScreenImage.jpg. You can also provide high resolution versions of the splash screen image which need to be named appropriately (see documentation for details). My guess is that because WP8 application start up so quickly (through a combination of improved runtime and precompilation of assemblies etc), the thinking is that the splash screen is not necessary any more.

- ApplicationIcon has been moved into the Assets folder, recognising that most developers like to organise images etc into a sub folder to make it easier to manage files within a project

- Background image has been replaced by a series of tile images (in the Assets\Tiles folder). WP8 supports small, regular and large tiles, as well as flip and cyclic templates. The series of tiles gives you a starting point to working with the different tile formats.

- AlignmentGrid (located in the Assets folder) is an overlay that you can display on any page to see if your controls/text align correctly. Alignment is an important aspect of fit and finish of an application, and is all too often neglected. The result is an application looks unfinished or off balance. You’ll see in MainPage.xaml that there is a element which you can uncomment in order to display this image. Note: IsHitTestVisible is set to False to ensure it doesn’t affect the way that your application operates. You should also take note of the comment in the XAML which indicates you may need to adjust the Margin depending on whether you have the SystemTray visible or not.

        <!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />—>

- AppResources/LocalizedStrings. With the new support for right-to-left text it’s become important for developers to know how to globalize/localize their applications. One step in Globalizing your application is moving string literals out into a resource file (ie AppResources.resx). These strings can be referenced via the wrapper class, LocalizedStrings, which is created as a static resource in App.xaml

<Application.Resources>
    <local:LocalizedStrings xmlns:local="clr-namespace:PhoneApp16" x:Key="LocalizedStrings"/>
</Application.Resources>

These strings can then be localized by creating appropriate resource files for each different language you want to support within your application. Depending on the language specified on the user’s Windows Phone, the most appropriate language will be used within the application.

One last observation is that the list of References has changed. Microsoft has recognised that developers shouldn’t have to add/remove assemblies that are part of the .NET Framework. As such, instead of seeing individual assemblies, developers now see just the frameworks that are references (see below image).

image

Windows Phone 8 SDK: Creating a New Application

It goes without saying that the starting point for any project is going to be the new project dialog. We are of course talking about Visual Studio 2012, where you’ll find all the Windows Phone 8 SDK goodness. What some people don’t realise is that you can do the same thing (ie create projects) in Blend. However, I find Blend to be obnoxious when it comes to file management and dealing with project structure. This is the one reason why I always start in Visual Studio – get your project/solution structure right, and then invite the designers into the room.

image_thumb1

New Project Dialog

The project templates in New Project Dialog, as you can see, haven’t changed much with the exception that in addition to a XAML/XNA template, there is also a XAML/Direct3D. With Windows Phone 8 we can now write native code to be part, or all, of our application or game.

image_thumb4

Native Code Project Templates

There are also a number of native project templates which you can use to create all or part of your project.

image_thumb6

Choosing the Target Platform

Most of the managed project templates you’ll be prompted to choose which platform you wish to target. Clearly if you’re making use of native code, you’ll only be able to target Windows Phone 8. One thing to note is that if you target Windows Phone 7.1 your application will run on both WP7 and WP8 devices but of course, you won’t be able to access any of the new functionality.

Why the iPhone 5 is a Fail

When the iPhone 5 came out I thought it about time that I experience how the other side lives; you know the side that seem to drool at any thing white and shiny (also known as ilunatics for participating in iqueues).  Most people who know me know how Microsoft-centric my world is but from time to time I do step out and try to familiarise myself with other platforms. With this in mind when I renewed my phone contract I signed up for an iphone 5, which of course came with a replacement nano-sim.

Ok, so here are just a few of my observations:

- Why a nano-sim? I don’t believe the space saving warrants being different from every other phone on the market. I had to spend two extra agonising days with the iphone, just because I couldn’t find a converter to go back up to a micro-sim.

- Why the new socket? Ok, not being in the land of white and shiny, I don’t really care that it’s changed. What I care about is the Apple have again defied the industry and gone with their own proprietary connector. Instead of using one of hundreds of micro-usb cables I have floating around, I have to use the white cable that came with the device, and I have to keep it in a locked box for fear on our cats chewing on them (they seem to hate Apple products and will chew on them at any opportunity).

- The apps rock! The one thing I have to say about the iphone is that the quality and depth of apps available is second to none. Whilst some haven’t been adapted to the new height of the iphone 5 they’re still of exceptional quality.

- The core platform does NOT rock When the iphone first came out the interface was revolutionary in the way that users interacted with the device. My comment, even back when the iphone 3 came out is that Apple had failed to innovate with the iphone; evolve, absolutely, innovate, not so. With iphone 4 and now 5 there is nothing that I’ve seen in the core platform that says to me “I’ve got to have that” If you compare the numerous Android devices on the market, the iphone 5 really just doesn’t lead the pack, in fact from a UX perspective it trails a poor third to both Android and Windows Phone.

- The Ads, Really??? I don’t know whether you’ve seen the new TV ads that talk about how they’ve optimised the height of the new iphone 5. I must admit I had to double-take as I thought it was a spoof initially, now I just feel embarrassed for Apple. They must really be scared if they’ve stooped so low. Don’t get me started on the ear buds (as if no other headphone manufacture has shaped their earbuds before, in fact shame on Apple for not having done this sooner) or the dancing ipods.

Lastly, before I sign off I want to make an interesting observation about the timing of the ipad mini v’s Windows 8. As you’re probably aware Apple made their announcement the day prior to Microsoft’s mega Windows 8 launch. It strikes me that Apple might have got this the wrong way round – by putting it the day before, it was almost forgotten the next day when Microsoft went to press. Had they done it the day after, wouldn’t they have taken the focus back from Microsoft back onto Apple. I’m no marketer but would have loved to have heard the logic about the timing of these events.

Don’t forget that next week is BUILD

Windows 8 Launch

For those not living under a rock you’ll have noticed that Windows 8 has been launched. Over the past month or so I’ve been involved in a couple of Windows 8 projects. All three projects made it into the store just in time for the launch events.

image_thumb[1]

With this interlude over, we’ll be back to more frequent Windows Phone updates….