Every time I create a new app, I have to spend at least 10-15 minutes just to remove all the clutter that the guys who created them put in. Probably they thought than an average developer won’t be smart enough to figure out that THIS IS APPLICATION TITLE, DUDE!!1 And why do you need a backing field for each and every control on the page? Arrgh.

My favorite is that vital ‘phoneApplicationInitialized‘ variable. Just, look at this code (I’ve changed the order of class members and removed some unrelated calls, but that doesn’t matter):

private bool phoneApplicationInitialized = false;
 
public App()
{
    InitializeComponent();
    InitializePhoneApplication();
}
 
private void InitializePhoneApplication()
{
    if (phoneApplicationInitialized)
        return;
 
    RootFrame = new PhoneApplicationFrame();
    RootFrame.Navigated += CompleteInitializePhoneApplication;
    RootFrame.NavigationFailed += OnNavigationFailed;
 
    // Ensure we don't initialize again
    phoneApplicationInitialized = true;
}

So its value is modified only inside InitializePhoneApplication method that is called only from the class constructor. That first condition check never returns and there is no way to ‘initialize again’.

Anyway, I decided to create my own reusable page and application definition templates to save some time. Obviously, they may not suit your needs, so think about them as a reference or an alternative to the predefined templates.

App template

<Application
    x:Class="$namespace$.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">

    <Application.Resources>
        <system:String x:Key="ApplicationTitle">APPLICATION TITLE</system:String>
        
        <!-- Page margins -->
        <Thickness x:Key="PageHeaderPanelMargin">12,17,0,28</Thickness>
        <Thickness x:Key="PageNameLabelMargin">9,-7,0,0</Thickness>
        <Thickness x:Key="PageContentPanelMargin">12,0</Thickness>
        
        <Style x:Key="DefaultPageStyle" TargetType="phone:PhoneApplicationPage">
            <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilyNormal}"/>
            <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeNormal}"/>
            <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
            <Setter Property="SupportedOrientations" Value="Portrait"/>
            <Setter Property="Orientation" Value="PortraitUp"/>
            <Setter Property="shell:SystemTray.IsVisible" Value="True"/>
        </Style>
    </Application.Resources>
    
    <Application.ApplicationLifetimeObjects>
        <shell:PhoneApplicationService />
    </Application.ApplicationLifetimeObjects>
</Application>

Page template

    <phone:PhoneApplicationPage
    x:Class="$namespace$.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Style="{StaticResource DefaultPageStyle}"
    mc:Ignorable="d"
    d:DesignHeight="800"
    d:DesignWidth="480">

    <Grid Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel Margin="{StaticResource PageHeaderPanelMargin}">
            <TextBlock
                Text="{StaticResource ApplicationTitle}"
                Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock
                Text="page name"
                Margin="{StaticResource PageNameLabelMargin}"
                Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <Grid
            Grid.Row="1"
            Margin="{StaticResource PageContentPanelMargin}">
            
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>

You can also download zipped templates ready for importing into Visual Studio.
Just place them into “%my_docs%Visual Studio TemplatesItemTemplatesSilverlight for Windows Phone”.

Application and Page

Async sequential workflows

Posted on Apr 26, 2012 in and tagged ,

В последнее время всё чаще приходится сталкиваться с задачами, требующими выполнения последовательных асинхронных операций. Примером может служить загрузка файлов на мобильном устройстве. Учитывая что телефон может работать на слабом мобильном соединении, нам вряд ли удастся получить прирост производительности от параллельной загрузки. Да и стандартный класс WebClient, представленный в BCL не очень дружит с concurrent operations (точнее вообще не дружит). Создавать новый экземпляр на каждый запрос кажется идейно неправильным, так что попробуем обойтись одним веб-клиентом, обрабатывающим множество последовательных запросов.

Для начала – тривиальная синхронная реализация (которая конечно же не будет работать на WP7 из-за отсутствия синхронных методов у WebClient‘а):

public IEnumerable<string> Handle(IEnumerable<Uri> requests)
{
    var client = new WebClient();
 
    foreach (var request in requests)
    {
        yield return client.DownloadString(request);
    }
}

Разработчику, использующему асинхронную версии, скорее всего захочется узнать о моменте завершении загрузок. Не будем плохими мальчиками/девочками и отбросим мысли о EAP и ручном CPS. Довольно очевидным решением будет представить наши ожидающие загрузки файлы в виде потока событий при помощи observables. К сожалению, WebClient использует EAP для своих асинхронных операций, поэтому код становится чуть более неопрятным:

public IObservable<string> HandleAsync(IList<Uri> requests)
{
    var client = new WebClient();
    var subject = new Subject<string>();
    var enumerator = requests.GetEnumerator();
 
    
    Action takeNext = () =>
    {
        if (enumerator.MoveNext())
        {
            client.DownloadStringAsync(enumerator.Current);
        }
        else
        {
            subject.OnCompleted();
        }
    };
 
    client.DownloadStringCompleted += (s, e) =>
    {
        if (e.Error != null)
        {
            subject.OnError(e.Error);
        }
        else
        {
            subject.OnNext(e.Result);
            takeNext();
        }
    };
 
    takeNext();
 
    return subject;
}

В обоих случаях мы по сути описываем корутины, передающие управление в момент окончания обработки запроса. В синхронной реализации компилятор разворачивает yield в конечный автомат, генерирующий поток ответов, в асинхронной мы создаём его самостоятельно через замыкание на enumerator и итерацию внутри обработчика события DownloadStringCompleted. Те, кто уже использует async/await, могут переложить часть забот по описанию автомата на компилятор:

public async void HandleTaskAsync(IList<Uri> requests, Action<IObservable<string>> setObservable)
{
    var subject = new Subject();
    setObservable(subject);
 
    var client = new WebClient();
 
    foreach (var request in requests)
    {
        var response = await client.DownloadStringTaskAsync(request);
        subject.OnNext(response);
    }
}

Однако и в этом случае не обошлось без некоторых костылей – чтобы передать observable вызывающему методу, приходится использовать дополнительный параметр Action. Можно было бы воспользоваться интерфейсом IProgress, но для целостности будем рассматривать только IObservable.

Можно заметить, что на самом деле все эти 3 реализации очень похожи и отличаются лишь способом вызова континуаций (на следующей кликабельной картинке одинаковыми цветами отмечены аналогичные участки кода для каждого варианта).

Вернёмся к нашей асинхронной реализации с использованием observables. Хотелось бы всё-таки сделать её более обобщённой чтобы мы могли использовать использовать её подобно другим функциям высшего порядка из ObservableExtensions. Если ограничиться только EAP, то у любой задачи с последовательными асинхронными операциями есть:

  • функция run: T -> unit, запускающая операцию для очередного элемента входной последовательности
  • событие окончания выполнения операции completed: (object * TEventArgs) -> unit
  • параметрический тип TEventArgs, как правило содержащий информацию о результате выполнения операции или о произошедшей ошибке

Следовательно, можно написать следующую функцию:

public static IObservable<TResult> SelectFromAsyncEventPattern
    <TSource, TResult, TDelegate, TEventArgs>(
    this IEnumerable<TSource> source,
    Action<TSource> run,
    Func<EventHandler<TEventArgs>, TDelegate> conversion,
    Action<TDelegate> subscribe,
    Action<TDelegate> unsubscribe,
    Func<TEventArgs, TResult> mapResult,
    Func<TEventArgs, Exception> mapException)
 
    where TEventArgs: EventArgs
{
    var enumerator = source.GetEnumerator();
    var subject = new Subject<TResult>();
    var convertedHandler = default(TDelegate);
 
    Action takeNext = () =>
    {
        if (enumerator.MoveNext())
        {
            run(enumerator.Current);
        }
        else
        {
            subject.OnCompleted();
            unsubscribe(convertedHandler);
        }
    };
 
    EventHandler<TEventArgs> handler = (s, e) =>
    {
        var exception = mapException(e);
        if (exception != null)
        {
            subject.OnError(exception);
            unsubscribe(convertedHandler);
        }
        else
        {
            var result = mapResult(e);
            subject.OnNext(result);
            takeNext();
        }
    };
 
    convertedHandler = conversion(handler);
    subscribe(convertedHandler);
 
    takeNext();
    return subject;
}

На первый взгляд сигнатура может показаться не очень понятной и дружелюбной. В частности, пришлось ввести ещё один параметрический тип TDelegate и параметры conversion, subscribe и unsubscribe для обобщения события завершения операции (подобно методу Observable.FromEventPattern из Rx). В остальном код практически идентичен изначальной асинхронной реализации – подписываемся на событие, при каждом срабатывании сообщаем подписчикам о новом значении, аналогично уведомляем их при ошибке или после обработки всех элементов входной последовательности.

Пример использования:

public IObservable<string> HandleAsync(IList<Uri> requests)
{
    var client = new WebClient();
 
    return requests.SelectFromAsyncEventPattern
        <Uri, string, DownloadStringCompletedEventHandler,
            DownloadStringCompletedEventArgs>(
        client.DownloadStringAsync,
        handler => (s, e) => handler(s, e),
        x => client.DownloadStringCompleted += x,
        x => client.DownloadStringCompleted -= x,
        x => x.Result,
        x => x.Error);
}

К сожалению, компилятору не удаётся выполнить автоматический вывод типов, поэтому приходится указывать их вручную. Однако такой код всё равно выглядит лучше множественных вложенных континуаций.

Посмотреть и скачать примеры кода можно на Bitbucket.

How to generate error log from nested exceptions.

Posted on Apr 24, 2012 in and tagged

Working on error logging for my new application I’ve realized that I always use the same pattern when it comes to converting actual exceptions into a text form. And since I started posting rare code snippets that I write down all the time on Gist recently, there will be a number of ‘sharing code’ blog posts in the foreseeable future.

The code is rather simple, it traverses down the entire nested exception hierarchy and populates StringBuilder with the appropriate error information. There is a slightly different workflow for AggregateException – we want to flatten its InnerExceptions collection.

public string GetExceptionLog(Exception exception)
{
    return UnwrapExceptionTextLoop(new StringBuilder(), 0, exception);
}

private string UnwrapExceptionTextLoop(StringBuilder sb, int level, Exception e)
{
    if (e == null)
    {
        return sb.ToString();
    }

    for (int i = 0; i < level; i++)
    {
        sb.Append(">>");
    }

    var aggregate = e as AggregateException;

    sb.AppendFormat("{0} - {1} [{2}] {3}", e.GetType(), aggregate == null ? e.Message : String.Empty, e.StackTrace, Environment.NewLine);

    if (aggregate != null)
    {
        return String.Join(Environment.NewLine,
            aggregate.InnerExceptions.Select(inner => UnwrapExceptionTextLoop(sb, level + 1, inner)));
    }

    return UnwrapExceptionTextLoop(sb, level + 1, e.InnerException);
}

Let’s put on a simple method that throws several exceptions:

public void TestMethod()
{
    try
    {
        try
        {
            throw new Exception("Inner exception");
        }
        catch (Exception ex)
        {
            throw new Exception("Outer exception");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ErrorHelper.GetExceptionLog(ex));
    }
}

And here is the result (I’ve omitted the large stack trace information):

System.Exception - Outer exception [   at Client.App.TestMethod()..] 
>>System.Exception - Inner exception [   at Client.App.TestMethod()..]

Pretty straightforward, but just in case.. Here is the snippet:

SharpZipLib for WP7 NuGet package

Posted on Apr 16, 2012 in and tagged ,

I really got used to NuGet in the last year and I have almost completely forgotten what is ‘manually adding library file reference’ (can’t say I regret about that). So I was a bit disappointed when I found out that the well-known SharpZipLib NuGet package can’t be used with WP7 projects. However, there is a nice SL/WP7 port version of this library on codeplex (seems that it is abandoned though – no updates in ~2 years, but it works). It was not available to the fellow NuGetters.. until now. Use

Install-Package SharpZipLib-WP7

There is also a package mirror at BitBucket. Happy zipping!

Task Commands revisited

Posted on Feb 23, 2012 in and tagged , , , ,

Half a year ago I blogged about using TPL with MVVM in a test-friendly way. My solution turned out to be pretty handy, though it was far from being perfect. In this post I will describe what was wrong with the initial implementation and can we slightly improve it.

Looking at that solution right now, I wonder why did I decide to use event async pattern (providing the ExecuteCompleted event) in the first place. The intention was to notify the caller about completion of the asynchronous operation. That is what System.Threading.Task is used for this days, isn’t it? So the obvious solution is to expose the ExecuteAsync() method returning the Task instance on the command class. Here is the source of the updated AsyncRelayCommand:

public class AsyncRelayCommand<T> : ICommand {
    private readonly RelayCommand<T> _internalCommand;
    private readonly Func<T, Task> _executeMethod;
 
    public event EventHandler CanExecuteChanged
    {
        add { _internalCommand.CanExecuteChanged += value; }
        remove { _internalCommand.CanExecuteChanged -= value; }
    }
 
    public AsyncRelayCommand(Func<T, Task> executeMethod, Predicate<T> canExecuteMethod)
    {
        if (executeMethod == null)
        {
            throw new ArgumentNullException("executeMethod");
        }
 
        _executeMethod = executeMethod;
        _internalCommand = new RelayCommand<T>(_ => { }, canExecuteMethod);
    }
 
    public AsyncRelayCommand(Func<T, Task> executeMethod)
        : this(executeMethod, _ => true) { }
 
    void ICommand.Execute(object parameter)
    {
        if (parameter is T)
        {
            ExecuteAsync((T)parameter);
        }
 
        else throw new ArgumentException("Parameter should be of type " + typeof(T));
    }
 
    public Task ExecuteAsync(T parameter)
    {
        return _executeMethod(parameter);
    }
 
    public bool CanExecute(object parameter)
    {
        return _internalCommand.CanExecute((T)parameter);
    }
 
    public void RaiseCanExecuteChanged()
    {
        _internalCommand.RaiseCanExecuteChanged();
    }
}

The code is pretty straightforward, here are the key points:

  • Create an inner command that responds to CanExecute, RaiseCanExecute calls and handles subscriptions to CanExecuteChanged event (optional, since I am using MVVM Light with most of my projects, that’s an acceptable solution for me. However, you may easily implement your own commanding logic).
  • Introduce new ExecuteAsync method that returns Task instance.
  • Implement ICommand.Execute explicitly (I find it more consistent not to have Execute method in the AsyncRelayCommand class).

Side note: as I mentioned in the beginning, I find this command extension rather useful. It was successfully used in 5 own projects (both WP7 and WPF), and I hope you enjoy it too.

As usual, the source code is available at bitbucket (TaskCommands.v2.zip).

In the previous post I showed how to load the large SQL Server CE database on WP7. However, if you are working with a read-only reference database, deploying it to the phone or emulator may take up to several minutes. In this post I will try to explain how to save your nerves and time, making the regular development and debugging easier.

So for now, there are 2 options for deploying the database with your app:

  • Use Isolated Storage. Upload the database to the device with the help of ISETool. For ~50 mb database it takes 4 minutes on my laptop.
  • Pack it as the application content (setting Build Action to Content). In that case, the database is packed into the XAP file on your machine and then unpacked back on the device. While this approach is a bit faster then the first one, it still takes something about 1 minute to deploy your app, which I find unacceptable.

Note that the 1st option should be used only for Debug configurations. The only way to include the reference database when delivering the app to the users is by packing it into the XAP (you may, however, copy it to Isolated Storage upon the first launch, but I don’t see any sense why should you do so).

So I can’t fasten the packaging process, but I can upload my database to the Isolated Storage once and it will be preserved between the application deploys when debugging. When I need to release the application build, I will include the database to XAP file content. Sounds easy.

Being lazy motivates me to script the uploading routine. Here is a batch file that takes the IS snapshot with ISETool, adds the database file and restores the snapshot on the emulator:

set isePath="C:Program Files (x86)Microsoft SDKsWindows Phonev7.1ToolsIsolatedStorageExplorerToolISETool.exe"
set tempPath="C:TempDatabaseIS"
set dbPath="your_db_path"
set appId=your_app_id
%isePath% ts de %appId% %tempPath%
copy %dbPath% %tempPath%
%isePath% rs de %appId% %tempPath%

In the snippet above you need to replace your_db_path with the path to your .sdf file (relative to the script location) and your_app_id with Product Id of your application (you can find it WMAppManifest.xml file in the Properties subfolder of your project).

You will need another script file that will copy database to the emulator. The only difference is that you will use “xd” argument instead of “de” in lines 8 and 10.

Not hard so far, right?

Now we need to adjust the connection string, so that it points to the isolated storage in DEBUG configuration and to the content file otherwise.

#if DEBUG
    var source = "isostore:test.sdf";
#else
    var source = "appdata:/test.sdf";
#endif
    var connectionString = String.Format(
        "Data Source='{0}'; Max Database Size = 60; File Mode= Read Only;",
        source);

The last step – configuring the project file so the database file is not packed into XAP in DEBUG mode. Unfortunately, Visual Studio doesn’t allow you to specify conditions for files in the project, so you have to modify the project file manually.

Add the database file to the project and set its Build Action to Content.

Locate database file and change its build action

Save you solution, right-click the project file and select Unload Project, then right-click again and select Edit %ProjectName%.csproj.

Locate “test.sdf” string in the project file:

Change build condition for the database file

Add the Condition attribute the the Content node, so it looks like:

<Content Include="test.sdf" Condition="'$(Configuration)' == 'Release'">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

Here we specify that file test.sdf should be included in the project as Content only when the project configuration is set to ‘Release’.

Now you can reload the project in Visual Studio. You won’t see any changes in the Solution Explorer, but try building the solution – the database will be added to XAP only in Release configuration. Don’t forget to re-launch the deployment scripts every time you uninstall the application or debug it on the new phone.

Recently I ran into an issue when trying to load the large database (approx. 50 mb) from isolated storage on WP7. Whenever I tried to query the Data Context, I got the following SqlCeException:

The database file is larger than the configured maximum database size. This setting takes effect on the first concurrent database connection only. [ Required Max Database Size (in MB; 0 if unknown) = 0 ]

After some searching over the web, I found this blog post covering some details of that parameter.

The general work-around is adding ‘Max Database Size’ value (in megabytes) to the connection string, so it looks like:

var connectionString = "Data Source='isostore:DB.sdf'; Max Database Size = 60";

Now your app should be able to init the data context.

Building cool animated tiles with Rx

Posted on Nov 15, 2011 in and tagged ,

I have a small WP7 project called Summarize. It is a fun math-based game (check it out for free).

It has a nice effect of loading tiles. Several people has asked me how I have done it, so in this post I will cover how to build something similar on your own.

Let’s start with building the UI. We have the toolkit’s WrapPanel inside the ItemsControl and a simple TileControl with TextBlock displaying the tile number.

TileControl.xaml markup:

<UserControl 
    x:Name="UserControl"
    x:Class="AnimatedTilesSample.TileControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    Loaded="OnLoaded"
    Width="76" Height="76">
    
    <UserControl.Projection>
        <PlaneProjection RotationY="-180"/>
    </UserControl.Projection>
    
    <UserControl.Resources>
        <Storyboard x:Key="LoadedStoryboard">
            <DoubleAnimation 
                Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)"
                Storyboard.TargetName="UserControl"
                To="0"
                Duration="0:0:0.2"/>
            <ObjectAnimationUsingKeyFrames
                Storyboard.TargetProperty="UIElement.Visibility"
                Storyboard.TargetName="Text">
                <DiscreteObjectKeyFrame 
                    KeyTime="0:0:0.1">
                    <DiscreteObjectKeyFrame.Value>
                        <Visibility>Visible</Visibility>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>
    </UserControl.Resources>
    
    <Grid 
        x:Name="LayoutRoot"
        Background="{StaticResource PhoneChromeBrush}">
        <TextBlock 
            x:Name="Text"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Visibility="Collapsed"
            Style="{StaticResource PhoneTextTitle2Style}"
            Text="{Binding ., Mode=OneTime}"/>
    </Grid>
</UserControl>

In the code-behind we start the animation when the tile is loaded:

private void OnLoaded(object sender, RoutedEventArgs e)
{
    var sb = Resources["LoadedStoryboard"] as Storyboard;
    if (sb != null)
    {
        sb.Begin();
    }
}

MainPage.xaml markup:

<phone:PhoneApplicationPage 
    x:Class="AnimatedTilesSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
    xmlns:local="clr-namespace:AnimatedTilesSample"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait" >
     <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid x:Name="ContentPanel" Margin="12,0,12,0">
            <ItemsControl
                x:Name="Cells">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <toolkit:WrapPanel
                            Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <local:TileControl Margin="2"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
            
            <Button
                HorizontalAlignment="Left"
                VerticalAlignment="Bottom"
                x:Name="PlayAnimationButton"
                Content="Play animation"
                Click="PlayAnimationHandler"/>
        </Grid>
    </Grid>
 
</phone:PhoneApplicationPage>

Clicking the button generates the observable sequence producing values every 80 milliseconds. We use only the first 25 values and when the every next value is available, the appropriate tile is created and added to the list. Adding the tile starts its ‘loaded’ animation.

private void PlayAnimationHandler(object sender, RoutedEventArgs e)
{
    Cells.Items.Clear();
    PlayAnimationButton.IsEnabled = false;


    Observable.Interval(TimeSpan.FromMilliseconds(80))
        .Take(25)
        .ObserveOnDispatcher()
        .Finally(() =>
        {
            PlayAnimationButton.IsEnabled = true;
        })
        .Subscribe(x => Cells.Items.Add(x));
}

Because changes to ObservableCollection should occur only on the thread that it was created on, I used DispatcherObservable.ObserveOnDispatcher extension method that schedules all observer actions on the runtime dispatcher.

You can download sample app with sources here.

If you have changed the marketplace region as I described in the previous post and now you try updating applications that were installed in the old region, you are probably going to get the next error:

“We’re having a problem with this app or game because it no longer appears in your purchase history. This can happen if you’ve recently switched the gamertag associated with your Windows Live ID. We’re sorry, but you’ll need to buy this app or game again to continue using it.”

And now this application is stuck on your phone, you won’t be able neither to update nor to delete it.

The only work-around I’ve found so far is reinstalling the application through the web marketplace. So go to windowsphone.com/marketplace, search for your app and hit ‘Reinstall this app’ button.