Tag Archives: Windows 8

SQLiteWinRT: Now BLOB columns and Windows 8.1 supported

I’ve posted some updates to the SQLite WinRT API at http://sqlwinrt.codeplex.com. The SQLite WinRT API offers lightweight Windows Runtime (WinRT) APIs you can use to access the most common SQLite database functionality by using SQL statements, rather than a LINQ-style API.

Support for Windows 8.1

One change is to add an implementation for Windows 8.1. So if you download the source code now (there’s no msi or NUGet package for this as yet), you’ll get three projects which are the WinRT components for Windows 8.0, Windows 8.1 and Windows Phone 8.0. Make sure you have installed the SQLite SDK for your target platform on the Tools – Extensions and Updates menu and then Just include the appropriate project in your own solution, and you’re good to go. See my earlier post for an introduction to programming with the API: http://andywigley.com/2013/06/06/sqlite-winrt-database-programming-on-windows-phone-and-windows-8/

Namespaces Standardised

The other relatively minor change is that I’ve standardised the namespace used to SQLWinRT for all platforms. It just makes it a little easier to share code across platforms that way. That does mean that the blog post referenced in the previous paragraph shows code using the old SQLiteWinRTPhone namespace – though the sample accompanying that post has been updated.

Support for BLOB columns

There is a major update in functionality though – support for BLOB columns, which was requested to help store byte arrays – or Images – directly in the database.

You can define a table in the database with a BLOB column using code similar to this:

// Get a reference to the SQLite database
db = new SQLiteWinRT.Database(ApplicationData.Current.LocalFolder, "sqliteblobdemo.db");

await db.OpenAsync();

string sql = @"
    CREATE TABLE IF NOT EXISTS
        Pictures(Id     INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                 Name   VARCHAR(140),
                 Image  BLOB);";
await db.ExecuteStatementAsync(sql);

Then, to store a record in this table, you could do something like:

private async void Insert_RecordAsync(string description, BitmapImage image)
{
    string sql = @"INSERT INTO Pictures (Name, Image) VALUES (@name, @image)";
    var db = await App.GetDatabaseAsync();
    using (var statement = await db.PrepareStatementAsync(sql))
    {
        // Convert BitmapImage to byte array
        byte[] imagebytes = ConvertToBytes(image);
        // .. and from that to an IBuffer
        Windows.Storage.Streams.IBuffer imagebuffer = imagebytes.AsBuffer();

        // set the statement parameters
        statement.BindTextParameterWithName("@name", description);
        statement.BindBlobParameterWithName("@image", imagebuffer);

        await statement.StepAsync();
    }
}

private byte[] ConvertToBytes(BitmapImage bitmapImage)
{
    byte[] data = null;
    using (MemoryStream stream = new MemoryStream())
    {
        WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
        wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
        stream.Seek(0, SeekOrigin.Begin);
        data = stream.GetBuffer();
    }

    return data;
}

Here’s an example to read data out again:

    protected override PictureViewModel CreateItem(SQLiteWinRT.Statement statement)
    {
      // Read the image from the BLOB column
        Windows.Storage.Streams.IBuffer blobBuffer = null;
        if (statement.GetColumnType(2) != ColumnType.Null)
        {
            blobBuffer = statement.GetBlobAt(2);
        }

        // Convert IBuffer back to a BitmapImage
        byte[] pictureBytes = blobBuffer.ToArray();

        var bitmapSource = new BitmapImage();

        using (MemoryStream ms = new MemoryStream(pictureBytes))
        {
            bitmapSource.CreateOptions = BitmapCreateOptions.None;
            ms.Seek(0, SeekOrigin.Begin);
            bitmapSource.SetSource(ms);
        };

      var c = new PictureViewModel(
        statement.GetIntAt(0),
        statement.GetTextAt(1),
        bitmapSource);

      return c;
    }

Here’s a complete sample app you can study to help implement this functionality in your own apps:

Sample code SQLiteBlobSample.zip

BOMbin’ the L (aka Wierd Errors with XmlWriter)

[Title from a track on Come Find Yourself– Fun Lovin’ Criminals]

Have you experienced strange errors when working with XML generated by an XMLWriter? If so, this post may be helpful to you. I just spent a few hours trying to figure out why I was getting a weird error when I was sending some XML to the Windows Azure Notification Hubs client api (post on that coming up, just as soon as I have my sample working).

There’s a page here Get Started with Notification Hubs with tutorials on using this technology with Windows Store C#, Windows Phone, Android and iOS clients. In the Windows Phone tutorial, it walks through creating a Windows Phone client (needless to say) and a console app which simulates your backend logic that you use to send Tile, Toast or Raw notification messages to the mobile clients. In the instructions for the console app it includes the following:

In your Program class add the following method:

private static async void SendNotificationAsync()
{
    NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
    string toast = "<?xml version="1.0" encoding="utf-8"?>" +
        "<wp:Notification xmlns:wp="WPNotification">" +
           "<wp:Toast>" +
                "<wp:Text1>Hello from a .NET App!</wp:Text1>" +
           "</wp:Toast> " +
        "</wp:Notification>";
    await hub.SendMpnsNativeNotificationAsync(toast);
}

Make sure to insert the name of your hub and the connection string called DefaultFullSharedAccessSignature that you obtained in the section “Configure your Notification Hub.” Note that this is the connection string with Full access, not Listen access.

Then add the following line in your Main method:

SendNotificationAsync();
 Console.ReadLine();

Easy enough! So, using this as my guide, I created my own app that followed these principles, the main difference being that instead of creating a string with the XML payload in it, I thought I’d use an XmlWriter instead, because that’s neater:

        private static string prepareToastPayload(string text1, string text2)
        {
            MemoryStream stream = new MemoryStream();
            XmlWriterSettings settings = new XmlWriterSettings() 
                                            { 
                                                Indent = false,
                                                Encoding = Encoding.UTF8   
                                            };
            XmlWriter writer = XmlWriter.Create(stream, settings);
            writer.WriteStartDocument();
            writer.WriteStartElement("wp", "Notification", "WPNotification");
            writer.WriteStartElement("wp", "Toast", "WPNotification");
            writer.WriteStartElement("wp", "Text1", "WPNotification");
            writer.WriteValue(text1);
            writer.WriteEndElement();
            writer.WriteStartElement("wp", "Text2", "WPNotification");
            writer.WriteValue(text2);
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();

            return Encoding.UTF8.GetString(stream.ToArray());
        }

Wierd exception

When I ran this, I got the following exception:

System.ArgumentException: The payload is not in accepted XML format. The first node should be Tile/Toast. If want to send raw notification, please set “X-NotificationClass” to “3” in header.rn   at Microsoft.ServiceBus.Notifications.RegistrationSDKHelper.DetectMpnsTemplateRegistationType(String body, String errorMsg)rn   at Microsoft.ServiceBus.Notifications.MpnsNotification.OnValidateAndPopulateHeaders()rn   at Microsoft.ServiceBus.Notifications.Notification.ValidateAndPopulateHeaders()rn   at Microsoft.ServiceBus.Notifications.NotificationHubManager.BeginSendNotification(Notification notification, Boolean testSend, AsyncCallback callback, Object state)rn   at Microsoft.ServiceBus.Notifications.NotificationHubManager.<>c__DisplayClass1.<SendNotificationAsync>b__0(AsyncCallback c, Object s)rn   at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl(Func`3 beginMethod, Func`2 endFunction, Action`1 endAction, Object state, TaskCreationOptions creationOptions)rn   at System.Threading.Tasks.TaskF
actory`1.FromAsync(Func`3 beginMethod, Func`2 endMethod, Object state)rn   at Microsoft.ServiceBus.Common.Parallel.TaskHelpers.CreateTask[T](Func`3 begin, Func`2 end)… in c:\Development\AzurePushNotificationsDemo\NotificationSenderUtility\NotificationSenderUtility.cs:line 139

Now as it turns out, the error message here is rather misleading. “The first node should be Tile/Toast” seems to be referring to the expected XML format if you are sending toast messages using the (very useful) template capability of Notification Hubs, which allows you to send a generic message to Notification Hubs just once, and it will build the appropriate payloads for your actual clients, whether they are Windows Phone, Windows 8, Android or iOS, all of which have different payloads. But “The payload is not in accepted XML format” is a bit more interesting and forced me to take a look at the XML I was generating.

And here it gets really confusing. I swapped out the XmlWriter code and replaced it with just simply setting a string variable directly, similar to the original tutorial – that works! So what is different about the string generated by my prepareToastpayload method? I then put the two methods one after the other and stored the results in two different string variables which I then examined when stopped at a breakpoint – identical!! So, what gives?

Examining the string bytes

Of course, the strings WEREN’T identical, despite what the Visual Studio debugger was showing me! A bit of a web search led me to this useful post by Jon Skeet, author of the book “C# In Depth”. His post Strings in C# and .NET includes a warning about the Visual Studio debugger not showing you the whole story, and he includes some useful code for dumping the bytes of a string to output. I plugged in the suggested methods and the output revealed the following at the beginning of the XML string I was sending to SendMpnsNativeNotifiactionAsync():

image

Aha! What are these (Possibly non-printable) xFEFF bytes at the start? Next web search was for FEFF and I came upon a few posts explaining that hex FEFF is something called a BOM or Byte Order Mark, which is something that is usually inserted into UTF-8 encoded files that are stored on disk, which XML parsers can look for to figure out how to interpret the file contents. However, if you are formatting XML to send as payload in a web service call as we are here, then you don’t want it. Best post that explain this is a six year old blog by Rick Strahl, XmlWriter, Strings and Byte Order Marks .

Un-BOMbin’ the L

Rick gives the solution as well. It’s actually very difficult to stop the XmlWriter for outputting XML without a BOM, but you can get it to behave by creating a custom UTF-8 encoding where you can specify you don’t want a BOM by passing false into an override of the constructor, and then use that in your XmlWriterSettings object:

        private static string prepareToastPayload(string text1, string text2)
        {
            // Create encoding manually in order to prevent
            // creation of leading BOM (Byte Order Mark) xFEFF at start
            // of string created from the XML
            Encoding Utf8 = new UTF8Encoding(false); // Prevents creation of BOM
            MemoryStream stream = new MemoryStream();
            XmlWriterSettings settings = new XmlWriterSettings() 
                                            { 
                                                Indent = false,
                                           //   Encoding = Encoding.UTF8    !!NO-> adds Unicode BOM to start
                                                Encoding = Utf8,    // Use manually created UTF8 encoding
                                            };
            XmlWriter writer = XmlWriter.Create(stream, settings);
            writer.WriteStartDocument();
            writer.WriteStartElement("wp", "Notification", "WPNotification");
            writer.WriteStartElement("wp", "Toast", "WPNotification");
            writer.WriteStartElement("wp", "Text1", "WPNotification");
            writer.WriteValue(text1);
            writer.WriteEndElement();
            writer.WriteStartElement("wp", "Text2", "WPNotification");
            writer.WriteValue(text2);
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();

            var payload =  Encoding.UTF8.GetString(stream.ToArray());
            DisplayString(payload); // Inspect bytes
            return payload;
        }

Conclusion

So there you have it. Once you know what the problem is – an unwanted BOM – it’s quite easy to find posts that discuss it and give you a solution. But many developers who are having difficulty with XML they have created in code will not know what the problem is they are trying to fix. No amount of studying the code, from inspecting strings in Visual Studio, or quite likely the exception message will tell you that maybe there is a hidden and unwanted character at the start of the generated XML. For you, hopefully this post will help you find a solution.

SQLite-WinRT: Support for NULL columns added

Small update to the SQLite WinRT wrapper we published at http://sqlwinrt.codeplex.com a few months ago. This update adds support for storing NULL values into a row through the new methods BindNullParameterAt(int index) and BindNullParameterWithName(string name) added to the Statement class.

The following code sample shows how to store a null value into a column in a row, and then how to check if a null value has been returned to you in the data returned from a SELECT:

var db = new SQLiteWinRTPhone.Database(
    ApplicationData.Current.LocalFolder, "sqlite.db");

await db.OpenAsync();

string sql = @"
    CREATE TABLE IF NOT EXISTS
        Customer(Id     INTEGER PRIMARY KEY NOT NULL,
                    Name   VARCHAR(140),
                    NullableInt INTEGER);";

await db.ExecuteStatementAsync(sql);

try
{
    sql = @"INSERT INTO Customer(Id, Name, NullableInt) 
            VALUES (@id, @name, @nullInt);";
    using (var custstmt = await db.PrepareStatementAsync(sql))
    {
        custstmt.BindIntParameterWithName("@id", 11);
        custstmt.BindNullParameterWithName("@name"); 
        custstmt.BindNullParameterAt(3);
        await custstmt.StepAsync();
    }
}
catch (Exception ex)
{
    var result = Database.GetSqliteErrorCode(ex.HResult);
    Debug.WriteLine("INSERT failed with error " + result);
} 

// Right now read the rows out again
try
{
    sql = "SELECT Id, Name, NullableInt FROM Customer;";
    using (var custstmt = await db.PrepareStatementAsync(sql))
    {
        // Use StepAsync to execute a prepared statement
        while (await custstmt.StepAsync())
        {
            var Id = custstmt.GetIntAt(0);
            var Name = "NULL";
            if (custstmt.GetColumnType(1) != ColumnType.Null)
            {
                Name = custstmt.GetTextAt(1);
            }
            int? NullableInt = null;
            if (custstmt.GetColumnType(2) != ColumnType.Null)
            {
                NullableInt = custstmt.GetIntAt(2);
            }
            Debug.WriteLine("Got Customer: " + Id + " " 
                + Name + " NullableInt: " 
                + (NullableInt.HasValue ? NullableInt.Value.ToString() : "null"));
        }
    }
}
catch (Exception ex)
{
    var result = Database.GetSqliteErrorCode(ex.HResult);
    MessageBox.Show("SELECT failed with error " + result);
} 

Notice that you use BindNullParameterxxx to store a null value – using BindTextParameterWithName(string name, string value) and passing a NULL for the value doesn’t work and causes an exception to be thrown.

Notice also that to check if a column returned to you contains NULL, you use the Statement.GetColumnType(int index) method to find out if the column type is ColumnType.Null.

So, please go and download the source code again from https://sqlwinrt.codeplex.com/SourceControl/latest – sorry, no NuGet package for this. Please give it a try and give us any feedback. For more on how to use the wrapper, see my earlier post SQLite-WinRT: Database programming on Windows Phone and Windows 8.

SQLite Using NULL Demo code: SQLiteNULLdemo.zip

Beware the perils of async/await in application lifecycle event handlers (in fact in *any* event handlers)

Many developers are, quite rightly, adopting the use of async and await when writing Windows Phone and Windows 8 Store apps. It’s the right thing to do, as it allows long-running operations such as network calls and file i/o to complete efficiently without any risk of inadvertently locking up the UI thread and creating a poor user experience by freezing the screen responsiveness. In fact, in Windows 8 Store apps, it’s the *only* way to do these operations because in the .NET API for Windows Store apps, the old synchronous methods have been removed and only the new async versions are available. On Windows Phone 8, the developer has the choice of using the old Window Phone 7-style APIs, or in many cases newer async alternatives, such as the WinRT Windows.Storage APIs for file operations.

However, we’re seeing a lot of postings in the forums saying that their app only works intermittently, or works fine in debug but then fails intermittently when deployed. Quite often, the reason for this is that the developer has inadvertently called some async methods in a ‘fire and forget’ fashion, and what they are seeing is a synchronization problem; they assume that some async code has completed, and some code elsewhere is trying to use the result value from the async method before the async method has completed. The result, a null reference exception or incorrect behaviour because some object is not fully populated.

The problem with async/await in Application_Launching and Application_Activated

I accidently encountered this problem when I was building a simple demo for the last Windows Phone 8 JumpStart video series. OK, it was a dumb demo, but demos are often dumb because you want to keep them simple so as not to distract from the main point you are trying to make. This demo was to show how to program with the new Windows.Storage apis, so in my App class Application_Launching event handler I had code that read some data out of a file and saved the string into a public property called LogData:

    public partial class App : Application
    {
        ...

        // This is shared amongst all the pages
        // It is the contents of the log itself, as a large string
        public string LogData;

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private async void Application_Launching(object sender, LaunchingEventArgs e)
        {            
            // Warning - this async method may not complete before this event handler method completes and other
            // events fire. Be careful not to assume completion of the logic in this method in other event handler code.
            this.LogData = await LoadFromLocalFolderAsync();
        }

        public async static Task<string> LoadFromLocalFolderAsync()
        {
            string theData = string.Empty;

            // There's no FileExists method in WinRT, so have to try to get a reference to it
            // and catch the exception instead
            StorageFile storageFile = null;
            bool fileExists = false;
            try
            {
                // See if file exists
                storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
                    new Uri("ms-appdata:///local/CaptainsLog.store"));
                fileExists = true;
            }
            catch (FileNotFoundException)
            {
                // File doesn't exist
                fileExists = false;
            }

            if (!fileExists)
            {
                // Initialise the return data
                theData = string.Empty;
            }
            else
            {
                // File does exist, so open it and read the contents
                Stream readStream = await storageFile.OpenStreamForReadAsync();
                using (StreamReader reader = new StreamReader(readStream))
                {
                    theData = await reader.ReadToEndAsync();
                }
            }

            return theData;
        }

And in MainPage.xaml.cs, OnNavigatedTo, the code gets the value of LogData from the App class and sets the Text property of a TextBlock to the string to show the contents of the file on the screen. Logic elsewhere in the app writes content into the file, so on startup you should always see the current contents of the file shown on the screen on application launch.

        protected override void  OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
             base.OnNavigatedTo(e);
            
            // When we navigate to the page - put the log text into the display
            completeLogTextBlock.Text = ((App)App.Current).LogData;
        }

What could possibly go wrong? Well, plenty as it turns out! The first time you run this app, the screen is empty which is to be expected because the file is empty. But then you use the app to enter some text which is written to the file, then close the app. Launch again, and where you would expect to see some text displayed, the screen is still empty! What gives?

Exploring execution of Async methods

To show why this went wrong, let’s look at a simple console app to explore the two ways you can execute an async method.

using System;
using System.Threading.Tasks;

namespace AsyncSynchronizationProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            new TheClassThatDoesWork().DoTheWork();

            Console.ReadKey();
        }
    }

    class TheClassThatDoesWork
    {
        public async void DoTheWork()
        {
            Console.WriteLine("TRACE Calling SomeLongProcedure Async");
            await SomeLongProcedureAsync();
            Console.WriteLine("TRACE Returned from SomeLongProcedure Async");

            Console.WriteLine();

            Console.WriteLine("TRACE Calling SomeLongProcedure Fire and forget");
            SomeLongProcedureAsync();
            Console.WriteLine("TRACE Returned from SomeLongProcedure Fire and forget");
        }

        private Task SomeLongProcedureAsync()
        {
            var task = Task.Run(() =>
                {
                    Console.WriteLine("TRACE Starting SomeLongProcedure work");
                    System.Threading.Thread.Sleep(1000); // Simulate a long running operation
                    Console.WriteLine("TRACE Completed SomeLongProcedure work");
                });

            return task;
        }
    }
}

When you run this app, you see the following console output:

asyncdemo1

In this sample, the long running method, Task SomeLongProcedureAsync() simply sleeps for 1s to simulate executing some lengthy code. In the method DoTheWork(), we just call the async method twice, once using await and once without. We write to the console output to show what is happening. I’m sure it is no surprise to most of you, that when we call using await, the caller waits until the long-running work has completed before continuing execution itself:

TRACE Calling SomeLongProcedure Async
TRACE Starting SomeLongProcedure work
TRACE Completed SomeLongProcedure work
TRACE Returned from SomeLongProcedure Async

and when we call without using await, it works in a fire-and-forget fashion, and the caller continues execution without waiting for the task to complete:

TRACE Calling SomeLongProcedure Fire and forget
TRACE Starting SomeLongProcedure work
TRACE Returned from SomeLongProcedure Fire and forget

TRACE Completed SomeLongProcedure work

This is pretty basic stuff about calling async methods. So why is this relevant?

Dangers of making event handlers async

Let’s look at another example. This one is still a console app, but has four classes, Program which just hosts the Main method of the console app, App, PhoneApplicationService and MainPage – I have named the last three the same as key classes in a Windows Phone app for reasons which hopefully will become obvious.

using System;
using System.Threading.Tasks;

namespace AsyncSynchronizationProblemWithEvents
{
    class Program
    {
        static void Main(string[] args)
        {
            var phoneAppService = new PhoneApplicationService();
            var app = new App(phoneAppService);
            
            phoneAppService.DoTheWork();

            // When the PhoneApplicationService has completed, construct a MainPage instance
            var mainPage = new MainPage();
            // Call methods on it
            mainPage.OnNavigatedTo();

            Console.ReadKey();
        }
    }

    class App
    {
        private PhoneApplicationService appService;

        public App(PhoneApplicationService applicationService)
        {
            appService = applicationService;
            // Subscribe to the PhoneApplicationService lifetime event(s)
            appService.ApplicationLaunching += Application_Launching;
        }

        async void Application_Launching(object sender, EventArgs e)
        {
            Console.WriteLine("TRACE Event handler - Calling SomeLongProcedure Async");
            await SomeLongProcedureAsync();
            Console.WriteLine("TRACE Event handler - Returned from SomeLongProcedure Async");
        }

        private Task SomeLongProcedureAsync()
        {
            var task = Task.Run(() =>
            {
                Console.WriteLine("TRACE Starting SomeLongProcedure work");
                System.Threading.Thread.Sleep(1000); // Simulate a long running operation
                Console.WriteLine("TRACE Completed SomeLongProcedure work");
            });

            return task;
        }
    }

    class PhoneApplicationService
    {
        public event EventHandler ApplicationLaunching;

        public void DoTheWork()
        {
            // Here we do some stuff...

            // Call any subscribers to our event(s)
            if (ApplicationLaunching != null)
            {
                ApplicationLaunching(this, new EventArgs());
            }
        }
    }

    class MainPage
    {
        public void OnNavigatedTo()
        {
            Console.WriteLine("TRACE Starting MainPage OnNavigatedTo");

            // Do some work here too...

            Console.WriteLine("TRACE Completed MainPage OnNavigatedTo");
        }
    }
}

If you study this app, you will see that the Main method creates instances of PhoneApplicationService, creates an instance of App and passes the PhoneApplicationService instance into its constructor, and finally creates an instance of MainPage and calls its OnNavigatedTo method. This is, of course, exactly what happens when you start a Windows Phone app. When you run it, the output looks like this:

asyncdemo2

There is clearly something odd going on here: the trace messages from the execution of SomeLongProcedure are output, but right in the middle, the calls to MainPage OnNavigatedTo appear. What’s going on?

Inside the App constructor, we hook the ApplicationLaunching event of the PhoneApplicationService instance so that in the event handler we can do some setup work when the app launches, and this of course is where we call the long-running async method:

        async void Application_Launching(object sender, EventArgs e)
        {
            Console.WriteLine("TRACE Event handler - Calling SomeLongProcedure Async");
            await SomeLongProcedureAsync();
            Console.WriteLine("TRACE Event handler - Returned from SomeLongProcedure Async");
        }

We are using the await keyword inside this event handler, so of course we mark it with the async modifier as normal. So at first glance, the developer expects this code to execute and for the event handler code to wait for completion of SomeLongProcedureAsync() before continuing execution, which in this case is simply to write a message to the console. If we look at the output, that is indeed what happens:

TRACE Event handler – Calling SomeLongProcedure Async
TRACE Starting SomeLongProcedure work

TRACE Starting MainPage OnNavigatedTo
TRACE Completed MainPage OnNavigatedTo

TRACE Completed SomeLongProcedure work
TRACE Event handler – Returned from SomeLongProcedure Async

But as you can see from the trace output, the MainPage OnNavigatedTo method is executed before the Application_Launching event handler has completed, even though it was clearly invoked by the Main function after the PhoneApplicationService.DoWork() method was invoked, which is the method that fires the Application_Launching event:

        static void Main(string[] args)
        {
            var phoneAppService = new PhoneApplicationService();
            var app = new App(phoneAppService);
            
            phoneAppService.DoTheWork();

            // When the PhoneApplicationService has completed, construct a MainPage instance
            var mainPage = new MainPage();
            // Call methods on it
            mainPage.OnNavigatedTo();

            Console.ReadKey();
        }

The problem of course, is that there is no way of awaiting the completion of an event handler, so when the DoWork() method fires the Application_Launching event, it does so in a fire and forget fashion, just the same as in the calling of SomeLongProcedureAsync() without using the await keyword, as we demonstrated in the first example. During execution, code executes sequentially until we hit the await keyword inside the Application_Launching event handler, at which point the wonders of the Task Parallel Library ensure that execution of the Task continues without blocking the original context and control returns immediately to the caller (PhoneApplicationService.DoTheWork() in this case). 

If the Application_Launching event handler had returned async Task instead of async void: 

async Task Application_Launching(object sender, EventArgs e)

(which is not possible with event handlers) and if it had been called using the await keyword, then  DoWork() would have awaited completion of the Application_Launching event handler logic before continuing, in which case, MainPage.OnNavigatedTo() would not have been called before the Application_Launching logic had completed. You can only await completion of methods that return Task or Task<T> and since this is impossible with event handlers, you can never await their completion. Hence there is every chance that your MainPage OnNavigatedTo logic will execute before your Application_Launching or Application_Activated logic has completed, although it is actually hit or miss, which is why so many developers report intermittent failures.

The Solution?

Of course, this is not a new problem. Any time you execute code asynchronously from your application lifecycle event handlers, whether using async/await or other asynchronous programming techniques, there is a real chance that you will have to implement some kind of synchronisation logic to ensure that your page logic does not try to access objects before your startup logic has set them up. Using older async coding technologies, this was perhaps a little more obvious to the developer, but many devs use the new Task-based async methods without thinking too deeply about it. It just works – or at least seems to until you hit a timing-related problem such as the one I’ve described here.

In the simple demo I described at the beginning of this article, the solution was simple. Instead of exposing the data fro the app in a public property of the App class, I created a new ViewModel class to host it and used XAML databinding to bind the TextBlock on MainPage to a property of the ViewModel. When the Application_Launching logic completed, it updated the ViewModel instance, and through the wonders of INotifyPropertyChanged, the MainPage UI updated with the correct data.

For other solutions, you may need to implement some other mechanism. One example was shown me by Peter Torr of the Windows Phone Product Group and is shown in the sample app which you can download from my post on SQLite:  SQLite-WinRT: Database programming on Windows Phone and Windows 8 . That sample opens (and the first time, creates) the SQLite database in Application_Launching and when resuming from tombstoning in Application_Activated. That sample used an old-fashioned synchronisation primitive, a ManualResetEvent, as a flag that is only set when the application lifecycle logic has finished:

  public partial class App : Application
  {
    static SQLiteWinRTPhone.Database db;
    static ManualResetEvent DBLoaded = new ManualResetEvent(false);

    public static Task<SQLiteWinRTPhone.Database> GetDatabaseAsync()
    {
      return Task.Run(() =>
      {
        DBLoaded.WaitOne();
        return db;
      });
    }

    // Code to execute when the application is launching (eg, from Start)
    // This code will not execute when the application is reactivated
    private void Application_Launching(object sender, LaunchingEventArgs e)
    {
      LoadDatabase();
    }

    private async Task LoadDatabase()
    {
      // Get a reference to the SQLite database
      db = new SQLiteWinRTPhone.Database(ApplicationData.Current.LocalFolder, "sqlitedemo.db");

      await db.OpenAsync();

      string sql = @"CREATE TABLE IF NOT EXISTS
                                Customer (Id      INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                          Name    VARCHAR( 140 ),
                                          City    VARCHAR( 140 ),
                                          Contact VARCHAR( 140 ) 
                            );";
      string description = "Create Customer table";
      await ExecuteSQLStatement(db, sql, description);

      sql = @"CREATE TABLE IF NOT EXISTS
                                Project (Id          INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                         CustomerId  INTEGER,
                                         Name        VARCHAR( 140 ),
                                         Description VARCHAR( 140 ),
                                         DueDate     DATETIME,
                                         FOREIGN KEY(CustomerId) REFERENCES Customer(Id) ON DELETE CASCADE 
                            )";
      description = "Create Project table";
      await ExecuteSQLStatement(db, sql, description);

      // Turn on Foreign Key constraints
      sql = @"PRAGMA foreign_keys = ON";
      description = "Enable foreign key constraints";
      await ExecuteSQLStatement(db, sql, description);

      DBLoaded.Set();
    }

    private static async Task ExecuteSQLStatement(SQLiteWinRTPhone.Database db, string sql, string description)
    {
      try
      {
        await db.ExecuteStatementAsync(sql);
        Debug.WriteLine(description + " executed OK");
      }
      catch (Exception ex)
      {
        var result = SQLiteWinRTPhone.Database.GetSqliteErrorCode(ex.HResult);
        throw new ApplicationException(description + " Failed with error " + result);
      }
    }

The ManualResetEvent is declared unsignalled as a static field of the app class:

 static ManualResetEvent DBLoaded = new ManualResetEvent(false);

and is only set at the very end of the async Task LoadDatabase() method:

private async Task LoadDatabase()
{
  // Get a reference to the SQLite database
  db = new SQLiteWinRTPhone.Database(…);
 
await db.OpenAsync();
  …

  DBLoaded.Set();
}

The final key ingredient is a ‘gatekeeper’ method which must be called by every other method in the app that wants to access the database:

public static Task<SQLiteWinRTPhone.Database> GetDatabaseAsync()
{
  return Task.Run(() =>
  {
    DBLoaded.WaitOne();
    return db;
  });
}

This method waits for the DBLoaded semaphore to be set and does so on a Threadpool thread (through Task.Run()) so does not block the UI thread.

Calling async code from Application_Deactivated or Application_Closing

The guidance here is “don’t’”. If you write your apps carefully, you can be saving changes to persistent data as you go along, so you shouldn’t have anything to do in the application lifecycle events.

If you must, you can try doing something like this:

SomeAsyncMethod().AsTask().Wait()   

If the operation completes within the timeout period AND it doesn’t deadlock due to needing to pump the UI thread, it will work… but don’t count on it.

SQLite-WinRT: Database programming on Windows Phone and Windows 8

Today at TechEd North America in New Orleans, I am presenting a session on programming the SQLite database on Windows Phone 8. You can watch the video and download the slides from here: Support Your Demanding LOB Apps With SQLite and Windows Phone 8. The sample application I walked through is here:

[Updated 21-Oct-2013 – SQLite 3.8.2]

The session is a deep dive on the new SQLite-WinRT API that we released on Codeplex last week. This new API is a thin wrapper around the native database engine, sqlite3.dll and exposes the key methods of the database engine through a modern Windows Runtime API callable from C#, Visual Basic and C++ that is all async methods and which reports unexpected results by throwing exceptions. The code is all up at http://sqlwinrt.codeplex.com. There’s no download for this project – you just download the source code, which is a complete Visual Studio 2012 solution containing projects for Windows Phone 8 and Windows 8 Store App components.

Why another database API on Windows Phone?

That’s a valid question! After all, we already have the Local Database in the Windows Phone SDK which is a LINQ to SQL API where the underlying database is SQL Server Compact Edition 3.7-ish. And we also have the SQLite-NET API for accessing SQLite which also exposes a LINQ API for working with a SQLite database. The Local Database LINQ to SQL API is not available for Windows 8 Store App development so not a great choice if you want to share code between your phone and tablet/PC apps, but SQLite-NET is available for both phone and Windows 8, as is SQLite-WinRT – so why do we need this new API?

SQLite-WinRT is for those developers who prefer to work with SQL statements rather than the object-oriented layer that LINQ gives you. It is also for those coming to Windows Phone 8 or Windows 8 from other platforms who have worked with SQLite before probably programming with C/C++ – the methods exposed by the SQLite-WinRT API are very thin wrappers around the SQLite C/C++ API. It’s all about giving choice to our developers – we have heard feedback that not all developers like to work with a local database using LINQ, so this API is for them.

To give you a comparison, this is how you might select a Customer from the Customer table using SQLite-NET:

var db = new SQLite.SQLiteAsyncConnection(App.DBPath); 
var _customer = await (from c in db.Table<Customer>() 
                        where c.Id == customerId 
                        select c).FirstOrDefaultAsync(); 
if (customer != null) 
{ 
    var Id = _customer.Id; 
    var Name = _customer.Name; 
}

And this is how you would do the same thing in SQLite-WinRT:

using (var db = new SQLiteWinRT.Database(
    ApplicationData.Current.LocalFolder, "demo.db")) 
{ 
    await db.OpenAsync(); 
    using (var stmt = await db.PrepareStatementAsync(
                        "SELECT name, age FROM people")) 
    { 
        while (await stmt.StepAsync()) 
        { 
            var name = stmt.GetTextAt(0); 
            var age = stmt.GetIntAt(1); 
        } 
    } 
}

The choice is yours!

Getting Started with SQLite-WinRT

Start by installing the SQLite Extension SDK. This is the native dll, sqlite3.dll, which contains the database engine. To install this, in Visual Studio, on the Tools menu, open Extensions and Updates. In the left hand pane, select Online – Visual Studio Gallery, then enter SQLite into the search box. Select SQLite for Windows Phone and click the Download button to download and install the vsix package. (The same procedure works for the SQLite for Windows Runtime extension for Windows 8 Store Apps.)

image_thumb3

After you’ve installed that, the native sqlite3 dlls are installed into a folder under C:Program Files (x86)Microsoft SDKsWindows Phonev8.0ExtensionSDKsSQLite.WP80. That’s just for your information – you should never have to manually copy the sqlite3.dll from there in order to use the database

Warning: You will be prompted whenever an update is available for the SQLite database engine. When you install it, you will inadvertently ‘break’ SQLite-WinRT, in the sense that Visual Studio will be unable to open the project. That is because the project references the C:Program Files (x86)Microsoft SDKsWindows Phonev8.0ExtensionSDKsSQLite.WP803.7.17 path in a number of places, and when you upgrade SQLite, the version part of that path will change.
I will be adding a powershell script into the download to make it easy to update the SQLite-WinRT project file with the correct path, but if this happens to you before I do it, just edit the SQLiteWinRTPhone.vcxproj file (carefully!) to correct references to the old version and update them to pojnt at whatever new version you have installed.

Creating your Project

Create your C# or Visual Basic project as normal. Then go to http://sqlwinrt.codeplex.com and download the source code from there – remember there is no ‘official download’ for this Codeplex project.

image_thumb7

The source code for this project is a solution containing two projects, the SQLite-WinRT component for Windows Phone, and the same thing but for Windows 8 Store Apps. Copy the Windows Phone project and use ‘Add Existing Project…’ to add it into your solution, then add a reference to the SQLite-WinRT project from your C#/VB project. That’s all you have to do!

Remember, if Visual Studio cannot load the SQLite-WinRT project, it’s probably because the SQLite extension has been updated. Read the Warning a few paragraphs before to resolve this.

Creating a database

To create a database, you can use code such as this:

private void Application_Launching(object sender, LaunchingEventArgs e)
    {
      LoadDatabase();
    }

    private async void LoadDatabase()
    {
      // Get a reference to the SQLite database
      db = new SQLiteWinRT.Database(
          ApplicationData.Current.LocalFolder, "sqlitedemo.db");

      await db.OpenAsync();

      string sql = @"CREATE TABLE IF NOT EXISTS
                    Customer (Id      INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                Name    VARCHAR( 140 ),
                                City    VARCHAR( 140 ),
                                Contact VARCHAR( 140 ) 
                );";
      string description = "Create Customer table";
      await ExecuteSQLStatement(db, sql, description);

      sql = @"CREATE TABLE IF NOT EXISTS
                    Project (Id          INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                CustomerId  INTEGER,
                                Name        VARCHAR( 140 ),
                                Description VARCHAR( 140 ),
                                DueDate     DATETIME,
                                FOREIGN KEY(CustomerId) REFERENCES Customer(Id) 
                                    ON DELETE CASCADE 
                )";
      description = "Create Project table";
      await ExecuteSQLStatement(db, sql, description);

      // Turn on Foreign Key constraints
      sql = @"PRAGMA foreign_keys = ON";
      description = "Enable foreign key constraints";
      await ExecuteSQLStatement(db, sql, description);

      DBLoaded.Set();
    }

    private static async Task ExecuteSQLStatement(
        SQLiteWinRT.Database db, 
        string sql, 
        string description)
    {
      try
      {
        await db.ExecuteStatementAsync(sql);
        Debug.WriteLine(description + " executed OK");
      }
      catch (Exception ex)
      {
        var result = 
            SQLiteWinRTPhone.Database.GetSqliteErrorCode(ex.HResult);
        throw new ApplicationException(description + 
            " Failed with error " + result);
      }
    }

You can call this code from your Application_Loaded and Application_Activated event handlers. One particular thing I want to call out here: notice the last line of the LoadDatabase method:

DBLoaded.Set();

DBLoaded is a ManualResetEvent which is used to flag when the database opening logic has completed. It is declared at the top of my App.Xaml.cs class, along with a ‘Gatekeeper’ method called GetDatabaseAsync():

static SQLiteWinRT.Database db;
    static ManualResetEvent DBLoaded = new ManualResetEvent(false);

    public static Task<SQLiteWinRT.Database> GetDatabaseAsync()
    {
      return Task.Run(() =>
      {
        DBLoaded.WaitOne();
        return db;
      });
    }

The ManualResetEvent is created unset, and doesn’t get set until the last line of LoadDatabase(). All other database access code in my viewmodel classes makes a call to GetDatabaseAsync as the first thing it does. The DBLoaded.WaitOne() call in there blocks until DBLoaded is set, so this prevents any other database accessing code from executing until the LoadDatabase() method has completed.

Handling Errors

The SQLWinRT API throws exceptions when something goes wrong. Unfortunately, exceptions thrown in a WinRT component are not the most developer-friendly things ever devised. They are COMException objects, have no useful error text in them and just return to you a HResult. But you can get a meaningful error message if you call the handy GetSqliteErrorCode method which is used like this:

try
{
await db.ExecuteStatementAsync(sql);
}
catch (Exception ex)
{
var result = 
    SQLiteWinRT.Database.GetSqliteErrorCode(ex.HResult);
throw new ApplicationException("Failed with error " + result);
}

GetSqliteErrorCode() returns the – yes, you guessed it – SQLite error code, which mostly are self explanatory (such as ‘SQLITE_CONSTRAINT’) are documented at http://www.sqlite.org/c3ref/c_abort.html.

CRUD operations

Create

To create records in the database, use code similar to this:

try 
{
    // Connection already opened in app.xaml.cs - get reference     SQLiteWinRT.Database db = App.db;     using (var custstmt = await db.PrepareStatementAsync(
    "INSERT INTO Customer (Name, City, Contact) VALUES (@name, @city, @contact)"
      ))
    {         // NOTE that named parameters have a leading "@",":" or "$".         custstmt.BindTextParameterWithName("@name", customer.Name);
        custstmt.BindTextParameterWithName("@city", customer.City);         custstmt.BindTextParameterWithName("@contact", customer.Contact);
        // Use StepAsync to execute a prepared statement         await custstmt.StepAsync();     } 
} 
catch (Exception) 
{ … }

This uses a SQL statement containing named parameters (@name, @city, @contact), which you prepare using PrepareStatementAsync() and which you ‘plug in’ the values using the BindtypeParameterWithName(string parametername, type value) method. An alternative is to use anonymous parameters (shown below when describing Update).

Notice that we use the StepAsync() method to execute a row-returning SQL statement. StepAsync may seem curious, but the SQLite C/C++ API method this wraps is called Step(), so that’s the name we adopt for our WinRT method.

IMPORTANT: Remember to dispose of your Statement objects when you’re done with them – a good way of doing that is to use the C# using statement, as shown above.

Read

To read objects, use a SELECT statement:

public async Task<CustomerViewModel> GetCustomerAsync(int customerId)
{
    CustomerViewModel customer = null;
    using (var readstmt = await App.db.PrepareStatementAsync(
                "SELECT Id, Name, City, Contact FROM Customer WHERE Id = " 
                + customerId))
    {
        if (await readstmt.StepAsync() == true)
        {
            var customer = new CustomerViewModel()
            {
                Id = readstmt.GetIntAt(0),
                Name = readstmt.GetTextAt(1),
                City = readstmt.GetTextAt(2),
                Contact = readstmt.GetTextAt(3)
            };
        }
    }
    return customers;
}

StepAsync() returns true if there is a row to return. The example above would reasonably be expected to return just a single row, but if you get multiple rows returned from the database, then you would loop around creating your in-memory objects (your viewmodel objects) and entering them into some collection until StepAsync() returns false.

An alternative form of SELECT allows you to extract data from the rowset returned from the database by using the column name, rather than the column position as the previous code sample did. You enable this behaviour by calling the Statement.EnableColumnsProperty() method. Then the results are returned as a Dictionary<string, string> which you key into using the column name:

using (var readstmt = await App.db.PrepareStatementAsync(
    "SELECT Id, Name, City, Contact FROM Customer WHERE Id = " 
    + customerId))
{
    // Enable the columns property
    statement.EnableColumnsProperty();

    if (await readstmt.StepAsync() == true)
    {
        // it isn't super useful as all columns are returned as text and must be parsed 
        var columns = statement.Columns;
        var customer = new CustomerViewModel()
        {
            Id = int.Parse(columns["Id"]),
            Name = columns["Name"],
            City = columns["City"],
            Contact = columns["Contact"]
        };
    }
}  

This does impose a slight performance overhead, and every value returns as a string, so you have to parse the string to get the correct value type, as shown here for the Id column.

Update

Update is simple enough. This sample uses anonymous parameters in the SQL statement, rather then the named parameters we saw when discussing the Insert operation. Note that anonymous parameters are 1-based, not 0-based like just about every other collection in .NET!

// See if the customer already exists
var existingCustomer = await GetCustomerAsync(customer.Id);
if (existingCustomer != null)
{
    using (var custstmt = await App.db.PrepareStatementAsync(
        "UPDATE Customer SET Name = ?, City = ?, Contact = ? WHERE Id=?"))
    {
        // NOTE when using anonymous parameters the first has an index of 1, not 0. 
        custstmt.BindTextParameterAt(1, customer.Name);
        custstmt.BindTextParameterAt(2, customer.City);
        custstmt.BindTextParameterAt(3, customer.Contact);
        custstmt.BindIntParameterAt(4, customer.Id);

        await custstmt.StepAsync();
    }
}

Delete

Delete is simple enough:

string sql = @"DELETE FROM Customer WHERE Id={0}";
sql = string.Format(sql, customerId);

// Can use ExecuteStatementAsync to run non row returning statements
await App.db.ExecuteStatementAsync(sql);

Summary

That’s an introduction to getting started with SQLite-WinRT. In the next posts, I will talk some more about Foreign Key constraints and about working with Read-only databases.

Async and Await for HTTP Networking, Part 2–HttpClient

In my previous post on this topic, Async and Await for Http Networking on Windows Phone, I described how you can use extension methods to create awaitable methods on the WebClient and HttpWebRequest APIs. Courtesy of Microsoft’s .NET Framework team, there have been more developments in this area – the creation of a portable implementation of the HttpClient API, until now available only for Windows 8 Store and .NET Framework 4.5 apps. This API will allow developers to consume HttpClient on Windows Phone 7.5 and higher, Windows Store apps, and .NET Framework 4.0 and higher.

Portable HttpClient for .NET Framework and Windows Phone

As they describe on their blog post here, the .NET Framework team have released a Beta release of the portable version of HttpClient, the modern networking API. The HttpClient library is a set of APIs for .NET which provide a flexible and extensible way to access all things exposed through HTTP. HttpClient exposes the new Task based asynchronous methods, which makes writing responsive and performant UI applications across all platforms a lot simpler.

This is particularly significant for anyone developing apps for both Windows Phone and Windows 8 as it allows you to standardise your networking code around HttpClient.  In addition it also enables other portable library developers who require networking support to use HttpClient while targeting all or a subset of the supported platforms.

To use it, first make sure you have got NuGet v2.1 or later installed (Go to Tools – Extensions and Updates). Then to use the HttpClient package, right click on your solution, go to the Manage Nuget Packages dialog, search for Id Microsoft.Net.Http, and make sure “Include Prerelease” is turned on.

Now you can go ahead and program against the HttpClient API. For example, here’s the code to access the OData feed for the Northwind sample feed at Odata.org:

HttpClient httpClient = new HttpClient();    
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
HttpResponseMessage response = null;
try
{            
    response = await httpClient.GetAsync(
        "http://services.odata.org/Northwind/Northwind.svc/Suppliers");

    response.EnsureSuccessStatusCode(); // Throws exception if bad HTTP status code
    Debug.WriteLine(response.StatusCode + " " + response.ReasonPhrase);

    string responseBodyAsText = await response.Content.ReadAsStringAsync();
    var feed = Newtonsoft.Json.JsonConvert.DeserializeObject<SupplierODataFeed>(responseBodyAsText);

    MessageBox.Show("Received payload of " + responseBodyAsText.Length + " characters");

    SuppliersList.ItemsSource = feed.d.results;
}
catch (HttpRequestException hre)
{
    MessageBox.Show("RespCallback Exception raised! Message:{0}" + hre.Message);
}

Using Compression with the Portable HttpClient

Anyone who knows me or has seen the Networking JumpStart video, will know that I am running a bit of  a crusade against the non-application of compression. Too many devs forget the simple fact that mobile apps on cellular networks (that’s not just Phone people – same for Windows 8 machines that have integrated cellular networking!) often find themselves trying to communicate over poor quality networks. Stack the cards in your favour, increase the chance of success and USE COMPRESSION!

Fortunately, many other people share my views on this. The excellent people at AdvancedREI have created the HttpClient.Compression NuGet package, based on original work by the super-excellent Morten Nielsen.

This is also a pre-release NuGet package. After you install that package, all you do is new up an instance of the CompressedHttpClientHandler and pass that into the constructor of HttpClient:

// Requires HttpClient.Compression NuGet package
var handler = new AdvancedREI.Net.Http.Compression.CompressedHttpClientHandler(); 

HttpClient httpClient = new HttpClient(handler); 

As long as your server is configured to serve up compressed content, you will receive data compressed over the wire and the handler will take care of decompression on receipt.

Download the sample code here

UK App Builders: Reward Program *One Day Special* and Bonus Rewards

Show us that you’re a game changer and collect points every step of the way to redeem rewards like a brand new Windows 8 RT Slate. Create the next app phenomenon by building your original and unique Windows Store and/or Windows Phone App.

Get recognised and rewarded for building your original apps. Further, get bonus rewards for migrating your Windows Phone app to Windows Store and vice versa or incorporating one or more Windows Azure Services.

Follow these 4 Simple Steps to Start Earning Points for your Awesome Apps:

1. Register yourself on the UK App Builder Reward Programme website.

2. Build & publish your original & unique app.

3. Claim points by telling us about the app you’ve published and we’ll award points to you accordingly.

4. Redeem your points for a range of fantastic prizes and gadgets.

Introducing Our First Ever One Day Special

On Tuesday 19 March 2013, we will be announcing a special one day deal for the Rewards Programme. To make sure you can take advantage of this special one day deal, publish your apps and ensure you claim your points before Thursday 14 March 2013 (less than 2 weeks away) so you will have your all of your eligible points in your account to use. You do not want to miss this one day special! Look out for the announcement for the One Day Special on Tuesday 19 March.

Don’t forget about our Bonus Rewards

The bonus rewards are limited deals where you must fulfil the stated criteria. Once you have fulfilled the criteria, you will be notified by our team and delivery of your bonus reward will be arranged. The bonus reward is exactly that and it will not affect the balance of your points therefore, you will still be able to use your points to claim for your reward(s) of your choice. Nokia have generously sponsored the first set of bonus rewards. You have to be quick to take advantage of this special bonus reward.

Bonus Reward 1: Receive a Nokia Lumia 620 Windows Phone 8 Handset if you are one of the first 20 App Builders who accumulate 100 points from Windows Phone Apps published.

Bonus Reward 2: Receive a Nokia Lumia 920 Windows Phone 8 Developer Handset if you are one of the first 10 App Builders who accumulate 200 points for publishing Windows Phone apps.

UK Windows App Builder Reward Programme

www.appbuilder-rewards.co.uk

Show us that you’re a game changer and collect points every step of the way of your app building journey to redeem rewards like a brand new Lenovo Tablet 2. Create the next app phenomenon by building your original and unique Windows Store and/or Windows Phone app – and get recognised and rewarded for your hard work. Further, get bonus rewards for migrating your Windows Phone app to Windows Store and vice versa or incorporating one or more Windows Azure Services.

4 Simple Steps to Start Earning Points for your Awesome Apps

1. Register yourself on the UK App Builder Reward Programme website.

2. Build & publish your original & unique app.

3. Claim points by telling us about the app you’ve published and we’ll award points to you accordingly.

4. Redeem your points for a range of fantastic prizes and gadgets.

Build & publish an app between Monday 4th Feb 2013 and Tuesday 30th Apr 2013 to be eligible for points you can redeem for rewards. Here are the different ways you can earn points:

Points for Apps

Publish a New Windows Store App

50 Points

Publish a New Windows Phone App

25 Points

Bonus Points

Your Windows Store or Phone App incorporates one or more Windows Azure Services

+ 25 Points

Your app Windows Store app is migrated from Windows Phone or Windows Phone app is migrated from Windows Store

+25 Points

Example

For example, if you have built and publish a Windows Store app which was ported from an existing Windows Phone app and is hosted on Windows Azure, you will be eligible for up to 100 points for that app.

Windows Store App = 50 Points

+ Hosted on Windows Azure = 25 Bonus Points

+ Ported from Windows Phone = 25 Bonus Points

Total = 100 Points

To recognise your hard work, the more apps you publish, the more points you receive. The more points you get, the more exciting rewards you can claim. Here’s a brief selection:

Publish 1 Windows Phone App

Publish 1 Windows Store App

Publish 5 Windows Store apps + Windows Azure Services + Migrated from WP

Publish 10 Windows Store apps + Windows Azure Services + Migrated from WP

Get a XBOX360 Wireless Headset

Get a XBOX360 12 Months Gold Subscription

Get a Lenovo Tablet 2

Get a Two Night Deluxe Paris Cuisine Break for 2

In addition to the fantastic selection of rewards and experiences you can redeem using your points, we’re also offering some bonus rewards to give your journey to publishing great apps that extra boost.

For Windows Store Apps Builders

For Windows Phone Apps Builders

Receive one of the latest XBOX360 titles if you are one of the first 50 app builders who accumulate 150 points from publishing Windows Store Apps.

Receive a Nokia Lumia 620 Windows Phone 8 Handset if you are one of the first 20 App Builders who accumulate 100 points from Windows Phone Apps published (~windows phone apps)

Receive a copy Visual Studio 2012 Professional (with MSDN Subscription) if you are one of the first 5 app builders who accumulate 400 points from publishing Windows Store Apps.

Receive a Nokia Lumia 920 Windows Phone 8 Developer Handset if you are one of the first 10 App Builders who accumulate 200 points for publishing Windows Phone apps (~8 Windows Phone apps)

The UK App Builder Rewards Programme finishes on the 30th April so get your thinking caps on and we look forward to rewarding your awesome apps very soon.

UK App Builder Rewards Programme www.appbuilder-rewards.co.uk

UK Windows Phone App Developers–’Port Your App to Windows 8’ Competition!

Having just completed the Windows Phone 8 JumpStart, you might think I would be totally focused on helping our developer community to incorporate some of the great Windows Phone 8 features into their phone apps. Well I am Smile – but we also want to focus on the great opportunities awaiting Windows Phone developers if you port your Windows Phone app to Windows 8. As published Windows Phone app developers, you are well-placed with the skills and knowledge of app building you need to create great Windows 8 apps. If your Windows Phone app would work well on a Windows 8 slate or tablet, think about porting your app to Windows 8 now, and you could win great prizes in a promotion we are running up to Christmas!

The Windows Store is open and a new opportunity is here. This is perfect for you as a Windows Phone app builder as you can create even more immersive app experiences, reach more people on more devices, and make more money on your terms. Richard Walter’s Calculator2 app on Windows 8 is now approaching 100,000 downloads after porting it from Windows Phone. More importantly, you already have the development skills needed to make the most of Windows 8. Check out the resources to get started or drop your details and register for a free consultation about building a Windows 8 app. You can port your Windows Phone 7.1 Silverlight apps to Windows 8 XAML, and if you have a game built with XNA you can port those to Windows 8 using MonoGame – see this blog post series for details on how to do that.

If you publish your Windows Phone app on to Windows 8 Store before 25th December 2012, you will go into an exclusive prize draw where you will have the chance to win one of 2 x ASUS VivoTab RT slates. Simply drop an email to ukmsdn@microsoft.com with your contact details and the URL & screenshot of your app in the Windows Store and you will get in the draw. If you can publish more than one app then you increase your chances of winning as you can have one entry per app. Note that terms and conditions apply (see link at the end of this post).

Furthermore, if you get a Windows 8 app in store before Christmas Day (25 Dec, 2012), you will get additional chances of winning great prizes including Windows 8 Slates and PCs. Click here to learn more. We are giving away one amazing 32 GB Windows tablets every day up to Christmas – that’s one lucky winner drawn at random from those who publish a Windows 8 app during this period. We also have the best app competition where 10 x finalists will walk away with a Windows 8 Ultrabook, a Windows tablet and Nokia Lumia 920 Windows Phone 8 device.

I hope you can take advantage of this new and significant opportunity to take your apps from Windows Phone to Windows 8.

Andy

*Postponed* iOS to Windows 8 Live Event!

Windows 8 is all about simplicity, for that reason we have decided to cancel this weekend’s event and combine it with a global event that is taking place in Seattle on the 14th and 15th of December. This 2 day event will start at 5pm on the 14th and will be run by the Big Nerd Ranch, all sessions will be live streamed, so regardless of where you are you can take part.

You can register for the global event here – http://bit.ly/SGddLJ

We still plan to hold a UK based workshop in early 2013, and we’ll ensure you receive plenty of notice as to when this is taking place.