WinRT: How to properly implement ISupportIncrementalLoading with navigation

BestComparator is about to publish its new Windows 8 application, and I ran into a really weird and frustrating issue when implementing ISupportIncrementalLoading.

Supporting infinite scrolling pagination

The best way to support infinite scrolling, is to use a GridView or a ListView and bind it an ObservableCollection that implements the ISupportIncrementalLoading.

You will probably end with a class like this one:

public class PaginatedCollection : ObservableCollection, ISupportIncrementalLoading
{
    private Func<uint, Task<IEnumerable>> load;
    public bool HasMoreItems { get; protected set; }

    public PaginatedCollection(Func<uint, Task<IEnumerable>> load)
    {
        HasMoreItems = true;
        this.load = load;
    }

    public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
    {
        return AsyncInfo.Run(async c => {
            var data =  await load(count);

            foreach (var item in data) {
                Add(item);
            }

            HasMoreItems = data.Any();

            return LoadMoreItemsResult() {
                Count = data.Count,
            };
        });
    }
}

Then you can simply create a bindable collection for your GridView or ListView in you ViewModel this way:

// in your view model
Items = new PaginatedCollection(async count => {
    var result = // your logic to load more items asynchronusly
    return result;
});

At binding time, the control will automatically detect that you binded a ISupportIncrementalLoading collection and will automatically call the LoadMoreItemsAsync when needed.

The incomprehensible AccessViolationException

Everything seems to work fine but if you happen to navigate in and out of a page using this interface you might get this exception for apparently no reason: AccessViolationException. You will get no stack trace to debug. Basically, the platform crash at a very low level around the C++ layer. Apparently, the asynchronous loading get bugged when you leaved the page and it is destroyed.

The almost easy workaround

I was stuck on this issue for quite a long time. I event though of manually implementing the infinite scrolling the way I did it in wp7, which I was not found of because it was quite hack (I was listening to the compress state of the scroller in order to detect when the end of the list was reached). Then I got the idea of caching the pages at a low level using the NavigationCacheMode of the Page control. It is simply done in the LayoutAwarePage constructor:

public LayoutAwarePage()
{
    NavigationCacheMode = NavigationCacheMode.Enabled;
    // the rest of the logic…
}

By doing so, you tell the framework to keep the page in the memory and directly use it when navigating forth and back to the page. This way, because the page still lives in memory, your asynchronous request to get more items continues to behave properly when navigating.

The hidden issue behind page caching

But, the fix is not complete yet. By using page caching, it is not properly regenerated when you navigate to a page already loaded but with a different context. Let’s take an example: BestComparator has a homepage listing different categories of products. When selecting the smartphones category, you navigate to a CategoryPage with the id of the category as a parameter. This was the smartphones category is completely fetched with its corresponding products. But if you go back to the homepage and then navigate to the laptops category, the framework will use the previously cached CategoryPage which was loaded with smartphones… and won’t trigger the load of the laptops.

The fix here is quite subtle, what you need to do is to trigger the LoadState procedure not only when the page is new, but also when navigating forward, mimicking the windows phone 7 navigation system. Just go to the OnNavigatedTo method of the LayoutAwarePage and add in the first line a test concerning the NavigationMode:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Returning to a cached page through navigation shouldn't trigger state loading
    if (this._pageKey != null && e.NavigationMode == NavigationMode.Back) return;
    // The rest of the logic...
}

And here it is, you completely support infinite scrolling with no bug, and won a nice page caching strategy on the way.

Wrap up

The new interface ISupportIncrementalLoading provided in WinRT can be very useful but its behavior when asynchronously loading items and navigating is quite bugged. What you have to do is activate a Page caching strategy and don’t forget to tweak the loading state process and everything should run smoothly.

Advertisements

Meet Readr7: A new Google Reader client for windows phone 7

Meet Readr7: A new Google Reader client for windows phone 7

As you may know, I am currently developing a Github client for windows phone 7, named Gi7. It is not complete yet even if it is functional. During that development, a friend of mine asked me for a Google Reader client.

As long as I am also using Google Reader and there is not really nice free app that is better than the mobile website, I decided to take au pause in the development of Gi7 to start a new app named Readr7. Hopefully the app is smaller and I shall continue the development of Gi7 soon.

What it does

Stream
Stream

The Readr7 app just does what a light Google Reader client should do.
– You can login and logout from your Google account.
– Then you have all your unread items with abstracts. They are automatically marked as read when scrolling the feed.
– You can of course access a configuration panel to selected folder and choose to see also marked as read items.
– Just tap on an item to open IE or make a long tap to manually mark as read/unread.
– Last but not least, if you pin the app to your home, the tile will be updated every 30 minutes with your unread items count.

About the development

As usual, I published the code to Github here. It shares some stuffs and concepts with the Gi7 app. You can of course get the code and contribute to the repo.

The code is almost finished. I just need to review some design (get a logo for instance), and bugs. About the last point, it is very important for me to get some external feedback, especially from developers who may run into error I did not though about and thus help be debug some issues.

About Google Reader, the bad thing is that it doesn’t have any official API. You can find some doc, but things may change without any advance notice. Whatever, the best doc I found is here: http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI.

As usual, I used my favorite tools:
RestSharp for fast access to the Google Reader API with easy json deserialization
MVVM light toolkit for easy use of the MVVM pattern
Silverlight Toolkit for Windows Phone that I recompiled for mango

Last but not least, I add a post build instruction to copy the xap file to the root of the solution so that you can directly download the last app version on github.

Meet Gi7 : A new github app for Windows Phone 7

Meet Gi7 : A new github app for Windows Phone 7

As you may know, I am not only a Symfony2 developer. I also enjoy a lot coding C#, especially Silverlight on the Windows Phone platform. Most of the time, I try to keep working on both technologies because they bring me complementary knowledge about good practices and design patterns. Also it prevents me from getting bored too fast on a project.
I am currently finishing my internship where I have a Silverlight 4 project using RIA Services, Prism and other cool stuffs. Thus I am looking into a new Silverlight project which is a Windows Phone 7 application called Gi7.

Gi7, the project

Gi7 is a github client for windows phone 7 that is also hosted on github.
As a matter of fact, I hope to get some help, feedback about some part of the code. I tried to make of the best practices I know, but I know things are still not perfect. Also I am not a so good UI designer, and I could use some help on the subject.
What it does
Github 7 intends to be a complete mobile application view of github. You should consult everything you need, but also post comments, accept pull request, follow users, edit a repo or a file…
It should also have a non logged part (which is not the case right know) to browse the gits and users.
For the moment you can do some nice things:
– Login/logout
– Read your news feed, get your stats, followers, followings, owned and watched repos

Homepage - newsfeed
Homepage - newsfeed
Homepage - profile
Homepage - profile



– Consult another’s user profile, with stats, followers, followings and repos

User - details
User - details
User - repos
User - repos

User - users
User - users



– Consult a repo with stats, commits, pull requests and issues

Repo - details
Repo - details
Repo - commits
Repo - commits
Repo - pull requests
Repo - pull requests



– Read a commit (in heavy dev)

The development

Actually I started the development last week on my free time, and it is going at a fast pace. I intend to have an almost full featured application around the end of august.
The application is built for the 7.1 version of windows phone 7 (aka. Mango) so that it already supports all the features of the new sdk. I make use of the MVVM light Toolkit and the RestSharp library.
Technically, I heavily make use of the MVVM design pattern with some Dependency Injection. I intend to make Gi7 a cutting-edge project while keeping things lightweight.
The Gi7 app has already nice development features, such as:
– auto caching of images.
– a Github client that automatically cache every requests and provide a very easy way to de-serialize the json api responses. Also the clients interface is very easy to bind to a view model.

Get involved, get the app

Again, I am looking for contributors and feedback about the application. Feel free to fork me, report issues, submit pull requests or ask for new functionalities: https://github.com/michelsalib/Gi7.
I intend to submit the app to the marketplace when the mango is officially released.

Force validation of RIA entities

Force validation of RIA entities

As I am currently developing a Silverlight Application using RIA Services (and Prism), I ran into some little tricks that can really help the developer’s life.

One of the common needs is to force the validation of all fields of an exposed entity in one time, and not just one field just after it has been updated.
This is very important especially when you want to insure our object is strictly validated before submitting changes.

The trick is to create a ValidationContext and manually validate the whole object. The thing to be careful of is not to forget to update the ValidationErrors list of the entity.

[csharp]
public static void Validate(this Entity entity)
{
// prepare the result
var validationResults = new List<ValidationResult>();
// create a validation context
var validationContext = new ValidationContext(entity, null, null);
// validate
Validator.TryValidateObject(entity, validationContext, validationResults);
// reset the validation errors of the entity
entity.ValidationErrors.Clear();
foreach (var error in validationResults)
entity.ValidationErrors.Add(error);
}
[/csharp]

As you can see, I made this method as an extension to the Entity type. So that you can easily use it on every entity you have.

A map picker for windows phone 7

A map picker for windows phone 7

For my end of study project, I am developing a windows phone 7 app with a team. We are using the geolocation features and recently needed a way for the user to select a place on the map.

Thus I made an implementation of a map picker, let’s see it.

New project
Let’s create a new project and simple change the basic grid to a map control.

New project, map instead of grid
New project, map instead of grid

[xml]
<!– /MainPage.xaml –!>

xmlns:my="clr-namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"
<!– … –!>
<my:Map x:Name="MapControl" Grid.Row="1"/>
[/xml]

I also like to make some improvements to the map, let’s customize it. We also need to add a pushpin that will designate the selected place:
[xml]
<!– /MainPage.xaml –!>

<my:Map x:Name="MapControl" Grid.Row="1"
LogoVisibility="Collapsed" ScaleVisibility="Visible"
CopyrightVisibility="Collapsed" ZoomBarVisibility="Visible">
<my:Pushpin Name="Pushpin" />
</my:Map>
[/xml]

Support selection
In order to make the map tappable, I use the toolkit for windows phone 7 that you can find in codeplex: http://silverlight.codeplex.com/releases/view/55034. Don’t forget to add a reference.

You can add the tappable behavior like that:
[xml]
<!– /MainPage.xaml –!>

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
<!– … –!>
<my:Map x:Name="MapControl" Grid.Row="1"
LogoVisibility="Collapsed" ScaleVisibility="Visible"
CopyrightVisibility="Collapsed" ZoomBarVisibility="Visible">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener Tap="GestureListener_Tap"/>
</toolkit:GestureService.GestureListener>
<my:Pushpin Name="Pushpin" />
</my:Map>
[/xml]

Now, you can go to the code behind. We need here to translate the screen position where the use tap and translate it to a geolocation:
[csharp]
// /MainPage.xaml.cs

private void GestureListener_Tap(object sender, GestureEventArgs e)
{
// get the tapped position relative to the map
var point = new Point(e.GetPosition(MapControl).X, e.GetPosition(MapControl).Y);
// get the geolocation of that position
var location = MapControl.ViewportPointToLocation(point);

// move the pushpin
Pushpin.Location = location;
}
[/csharp]

The thing here is that the gesture event returns the X and Y position relative to the top left of the screen. You first need to get the position relative to the map control, and then ask the map to translate it to a geolocation (longitude and latitude).
With this location you can move the pushpin to the selected place.

Selected place
Selected place

Display the selected address
Now that the user can pick a position on the map, I would like to tell him the address he selected. In order to do that we will use the Bing API located at this url: http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc/mex.

You will also need to get a Bing API key here: https://bingmapsportal.com/.

Now you can add the service reference:

Service reference
Service reference

In our code we just need to code the ReverseGeocode method on the service using the location and the API key:
[csharp]
// /MainPage.xaml.cs

private void GestureListener_Tap(object sender, GestureEventArgs e)
{
// get the tapped position relative to the map
var point = new Point(e.GetPosition(MapControl).X, e.GetPosition(MapControl).Y);
// get the geolocation of that position
var location = MapControl.ViewportPointToLocation(point);

// move the pushpin
Pushpin.Location = location;
Pushpin.Content = "loading…";

// get the address
// prepare the request
var request = new ReverseGeocodeRequest()
{
Location = location,
Credentials = new Credentials()
{
ApplicationId = "Your bing API code here"
}
};
// prepare the service
var service = new GeocodeServiceClient();
service.ReverseGeocodeCompleted += service_ReverseGeocodeCompleted;
// make the request
service.ReverseGeocodeAsync(request);
}

void service_ReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e)
{
// if there is any address
if (e.Result.Results.Count > 0)
// use the first one
Pushpin.Content = e.Result.Results[0].Address.FormattedAddress;
// else show invalid position
else
Pushpin.Content = "Invalid";
}
[/csharp]

When the service answers our request, we can simply update the pushpin text with the address.

Address completion
Address completion

Wrap up
We just saw here how to support selection on the map control and give a fancy feedback to the user, showing a pushpin and filling the address using the Bing API. Thus we made a very nice Map Picker.

You can download the sources here : MapPicker sources.

Slides about .NET, Linq, Entity Framework, Windows Phone 7

Slides about .NET, Linq, Entity Framework, Windows Phone 7

I just uploaded some slides I made for the preparation of a scholarship project. I made a quick overview of .NET, C#, Linq, Entity Framework, Windows Phone 7… for people who already have experienced Java and/or C++.
It’s in French. Feel free to react and to post me your comments.


Je viens juste d’uploader des slides que j’ai faits pour la préparation d’un projet scolaire. J’y fait un rapide aperçu de .NET, C#, Linq, Entity Framework, Windows Phone 7… pour les personnes ayant déjà une expérience en Java et/ou C++.
N’hésitez pas à réagir et à poster vos commentaires.

How to properly implement a template in a ListBox with Windows Phone 7

How to properly implement a template in a ListBox with Windows Phone 7

One of the most common controls in Silverlight for Windows Phone 7 is definitely the ListBox.

Basic implementation
I order to implement a design for the ListBox items you may have seen the most common implementation:

[xml]
<!– from Scott Guthrie’s blog: http://weblogs.asp.net/scottgu/archive/2010/03/18/building-a-windows-phone-7-twitter-application-using-silverlight.aspx –>

<ListBox Height="521" HorizonalAlignment="Left" Margin="0,131,0,0" Name="listBox1" VerticalAlignment="Top" Width="476">

<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding UserName}" Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>

</ListBox>
[/xml]

As you may see, the template is directly included in the page’s xaml. In fact it works well, and it is pretty straight forward.

But there is two main issues with this implementation. First, the designer will not render it:

Designer rendering
Designer rendering

And secondly, you thus don’t have any way to factorize your code. Let’s say you want to render again an item the exact same way but somewhere else, you will have to copy the same code.

Better implementation
Now I will use another app that displays bank accounts.

Please, code better. And please factorize, and use personal user controls.

Create a new UserControl:

Create a new user control
Create a new user control

After that you can edit it like any other xaml file with a nice designer:

My new account control
My new account control

Do not forget to use the proper binding:

[xml]
<!– Account.xaml –>
<TextBlock Text="{Binding Name}" Foreground="{StaticResource PhoneAccentBrush}" FontWeight="ExtraBold" FontSize="32" VerticalAlignment="Top" />
<TextBlock Text="{Binding Number}" VerticalAlignment="Top" Margin="0,43,0,0" />
<TextBlock Text="{Binding Balance}" FontWeight="Light" FontSize="42" Margin="0,43,15,0" VerticalAlignment="Top" HorizontalAlignment="Right" />
<TextBlock TextAlignment="Right" Text="€" FontWeight="Light" FontSize="26" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,43,0,0" />
[/xml]

After that you can use your new control very easily:

[xml]
<!– Main page.xaml –>

<!– don’t forget to include the local namespace –>
xmlns:local="clr-namespace:MyApp"

<!– the list box using the proper template –>
<ListBox x:Name="MainListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<local:Account/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
[/xml]

You may also notice that all you custom User Controls are present in the tool box:

That is all. You now have every tool in hands in order to properly use the ListBox templating.