XML and JSON (De)Serialization in WinRT

6. May 2012 2 comments

In some of my recent Metro/WinRT projects I had to save data to the disk. I decided to go for Xml-serialzation, because it’s human-readable, and flexible. Also it was perfect for the data I wanted to save (eg. metadata about a movie).

(If you want to do it on your own: System.IO and System.Xml.Serialization are the namespaces you need for XML (de)serialization.)

As I needed this in many projects, I composed a small library, containing a TCD.Serialization.XmlDeSerializer as well as a TCD.Serialization.JsonDeSerializer. Both have four static methods to serialize to/from Stream and string.

You can download a package with the sources and a ready-to-use dll.

NOTE: the methods aren’t fail-safe, so you might need to try{}catch{} them to handle exceptions. (For example if you want to serialize to a FileStream without write permission.)

Have fun and let me hear what you think =)

Categories: C#, WinRT Tags: , , , , , , ,

Performing long-running, timed operations on the UI thread

5. May 2012 Leave a comment

Recently I had to play timed sounds (morse code) in a WP7 applications. Sounds are required to be played on the UI thread, but as I had to time them, my UI thread got frozen. The reason was, that I used Thread.Sleep() to time the sound, which of course blocked the UI thread.

Today I figured out a way to do this long-running operation (many seconds..) without blocking the UI thread. You may know the Visual Studio Async CTP – it’s required to do the trick.

Let’s suppose we already have a method InvokeEvent() that plays the sound, changes a color or something like that.

Currently we execute this method in a pattern like this, causing the UI thread to be blocked:

void StartOperation()//invoke the event in a pattern
{
  for (int i=0; i<20; i++)//20 times
  {
    InvokeEvent();//play the sound, blink with the display or something like that
    Thread.Sleep(500);//this will block the current (UI) thread!
    InvokeEvent();
    Thread.Sleep(150);
  }
}

StartOperation() would be called by a Button_Click-Event handler, or similar.

To do this without blocking the UI thread, we need to avoid calling Thread.Sleep() on it.

So instead we create a Task that does this for us on a different thread. As Tasks can be awaited without blocking the UI thread, we can use it to pause execution of code.

Task MillisecondDelay(int ms)
{
  Task t = new Task(new Action(delegate{
  {
    Thread.Sleep(ms);//we're on the Task's thread, so we can block it!
  }));
  t.Start();
  return t;
}

The new StartOperation() method looks like this:

async void StartOperationAsync()//invoke the event in a pattern
{
  for (int i=0; i<20; i++)//20 times
  {
    InvokeEvent();//play the sound, blink with the display or something like that
    await MillisecondDelay(500);
    InvokeEvent();
    await MillisecondDelay(150);
  }
}

It can be called from any other method, marked with the async keyword. (In this case async void Button_Click)

NOTE: Calling an asynchronous method (like StartOperationAsync()) without awaiting it can be very helpful in certain scenarios (like saving data to the disk, without requiring it to finish before something else is executed).

 

have fun!

Making a reverse Autocomplete-TextBox on Windows Phone

13. April 2012 Leave a comment

I’m sure you’re familiar with autocomplete textboxes and maybe you’ve even used them in a project yourself. They provide a fast and easy way for the user to select something, but they lack one important feature: they don’t show what could be selected.

ReverseAutocompletePopup is a mixture between an autocomplete text box and the kind of popup you get when a ComboBox has more than five items. At first it displays all options in a ListBox and as you type non-matching ones are filtered out. (And brought back when you delete the text!)

revAutocompl

When working with it there’re a few things you need to have in mind:

The Popup control is no real navigation-thing, so you are in charge to handle OnBackKeyPress according to the guidelines! The Options for the controls are provided inside an ObservableCollection<Option> where Option is a simple class with two properties (string: Title, object Object). As I provide you with the sources, you can change this of course, but then you need to adjust the binding of the ListBox.ItemTemplate as well.

You can refer to the sample for more information on how to implement it.

Have fun^

Download ReverseAutocomplete sample/sources

Categories: C#, UI, Windows Phone Tags: , , , , ,

Running a synchronous method in an asynchronous context

8. April 2012 Leave a comment

In WinRT a significant portion of all native methods are asynchronous. Using an asynchronous method is very easy an can help you to speed up you application. The requirement to use an async method is that the calling method has an async modifier.

It’s easy to use async methods from a native API, but it can be useful as well to run synchronous operations off the UI thread. This should be done to prevent the UI thread from beeing blocked by time-consuming or resource-intensive operations like calculating ϖ or the answer to the ultimate question for the life, the universe and everything.

To show you how to run things like this asynchronously we take the following synchronous method:

private void synchonousMethod()
{
    do
    {
        i++;
    }
    while (i < Int32.MaxValue / 2);
}

This method obviously lacks the async and await keywords and it’s usual implementation would be something like this:

int i;
private void Button_Click_1(object sender, RoutedEventArgs e)
{
    i = 0;//reset i
    textBlock.Text += "starting...\r";
    synchonousMethod();
    textBlock.Text += i.ToString() + "\r";
}

(To test it just create a new C# Metro application, insert a Button and a TextBlock (called ‘textBlock’) into the XAML and attach the Click event…)

The Button_Click_1 event handler will run synchronously, freezing the UI thread for a few seconds.

An async implementation would look like this:

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    i = 0;//reset i
    Task timeConsumingOperation = Task.Run(new Action(synchonousMethod));
    textBlock.Text += "started task\r";
    await timeConsumingOperation;
    textBlock.Text += i.ToString() + "\r";
}

Notice the async and await keywords! When this event handler is executed the UI thread won’t be blocked. The ‘started task’ text will appear instantaneously as well. As the timeConsumingOperation (Task) is awaited, the UI thread will continue to run (you can still interact with the button, unlike the first case) and as soon as the synchronousMethod returns, the timeConsumingOperation will return too and the next line is executed.

You should be able to change the synchronousMethod (private void) into something like private int and use int foo = await timeConsumingOperation; to get back the result of a synchronous calculation or similar.

Have faith in async – you won’t be disappointed =p

Categories: C#, Software, WinRT Tags: , , , , ,

#WPdev – quick tips

31. March 2012 Leave a comment

Here you can find some tips for Windows Phone development. I’ll update the list over time..

Categories: C#, UI, Windows Phone Tags: , , ,

SettingsContractWrapper – the easy way to integrate w/ settings

26. March 2012 1 comment

In the previous post I introduced the Flyout control.

Now the most common use case for the Flyout controls is in the inegration with the settings contract.

Integrating with the settings contract is usually a two-step procedure. First you have to add a SettingsCommand to the charm and then attach a Flyout or similar to it. Now that you have a Flyout you could do that on your own, but with the SettingsContractWrapper it is even more fun.

To use it you  need to define one or more instances of SettingsEntry. This class holds the information required to set up the Flyout

Its constructor takes three arguments: Title, FlyoutDimension, Content.

The SettingsContractWrapper takes three arguments as well: Foreground, Background, SettingsEntries.

The required namespaces are ‘TCD.Windows8.Controls’ and ‘TCD.Windows8.Controls.Settings’.

As soon as you called the SettingsContractWrapper constructor you can forget about the settings contract integration. Just make sure that the UserControls you hand over to the SettingsEntries work well with the layout.

(There’s plenty of descriptions in the IntelliSense tooltips!)

Now download the SettingsSample and give it a try yourself!

Feel free to contact me if you have any questions!

cheers =)

Categories: C#, Metro, UI Tags: , , , , , ,

Flyout control for Windows 8 Metro (XAML/C#)

26. March 2012 2 comments

In Windows 8 Metro style apps there’s something called ‘Flyouts’. It’s a panel that slides in from the right. Sadly the control is not available to C#/VB developers. In this post Tim Heuer shows how to integrate with the settings contract using flyouts. Based on his code I developed a Flyout control for XAML/C# solutions. Here’s a list of what it can or can’t do:

It does:

  • light dismissal, back button
  • easy integration of ‘content’
  • swipe-in transition
  • custom color theme
  • ‘narrow’ and ‘wide’ mode

It does not:

  • theming of the BackButton
  • beeing attached to the left
  • construct it in XAML

I would like to provide you with a dll, but there’s a bug in the compiler (aka something I don’t understand yet) some stupid architechture thing in WinRT/XAML prevents me from doing so.

To use the Flyout control all you have to do is to add ‘Flyout.xaml’ to your project and reference the namespace:

using TCD.Windows8.Controls;

Then use it like this:

TextBlock sampleContent = new TextBlock() { TextWrapping = "Some stupid sample Text."};
Flyout f = new Flyout(new SolidColorBrush(Colors.White), new SolidColorBrush(Colors.Green), "Flyout", FlyoutDimension.Narrow, sampleContent);
f.Show();

This is what it looks like in the sample:

<screenshot from FlyoutSample>

You can download the sample application. It contains all you need to integrate it in your app.

That’s it! In the next post I’ll introduce the SettingsContractWrapper, that let’s you integrate with the settings contract in just a few lines of code!

Categories: C#, Metro, Software, UI Tags: , , , , ,
Follow

Get every new post delivered to your Inbox.