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.

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.

Support orientation with a listbox and rotate animation on windows phone 7

Support orientation with a listbox and rotate animation on windows phone 7

Today I will show how to simply implement a windows phone 7 app that supports orientation with transition. I will also go through a common issue with the list box control.

Setting up the project

For this post I’ll use the default DataBoundApplication, I will also use the transition provided by the brand new Silverlight for windows phone toolkit (second, released in November 2010) : http://silverlight.codeplex.com/releases/view/55034.

Well, let’s do basics. Create a new DataBoundProject :

Default DataBoundApplication
Default DataBoundApplication

First, let’s make our app support the various transition provided by the toolkit. First, add a reference to Microsoft.Phone.Controls.Toolkit and go to the App.xaml.cs file:

[csharp]
// /App.xaml.cs
//…
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;

// Create the frame but don’t set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new TransitionFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;

// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;

// Ensure we don’t initialize again
phoneApplicationInitialized = true;
}
//…
[/csharp]

Then edit the main page to support both orientations. Go to the first tag and edit the SupportedOrientation property to PortraitOrLandscape :

[xml]
<!–MainPage.xaml–>
<phone:PhoneApplicationPage
x:Class="WindowsPhoneDataBoundApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!– … –>
[/xml]

Now we have an app that can support orientation and transition. Let’s activate the rotate transition when we change the orientation.

Support rotation on orientation change

I will derive from the PhoneApplicationPage class in order to create a new one that can rotate automatically, and then I will change all my pages for them to derive the new class and thus inherit the new auto-rotation behavior.

So, we need to create our AutoRotatePage class. I override the OnOrientationChange method so when it occurs we perform a rotation transition:

[csharp]
public class AutoRotatePage : PhoneApplicationPage
{
/// <summary>
/// This varialb eis needed in order to now what was the previous orientation
/// and then choose the proper rotation mode
/// </summary>
private Nullable<PageOrientation> _previousOrientation = null;

/// <summary>
/// When the orientation changes perform a rotate transition
/// </summary>
/// <param name="e"></param>
protected override void OnOrientationChanged(OrientationChangedEventArgs e)
{
base.OnOrientationChanged(e);

if (_previousOrientation == null)
return;

RotateTransition transitionElement = new RotateTransition();

// counter clockwise rotation
if (_previousOrientation == PageOrientation.LandscapeRight &&
e.Orientation == PageOrientation.PortraitUp ||
_previousOrientation == PageOrientation.PortraitUp &&
e.Orientation == PageOrientation.LandscapeLeft ||
_previousOrientation == PageOrientation.LandscapeLeft &&
e.Orientation == PageOrientation.PortraitDown ||
_previousOrientation == PageOrientation.PortraitDown &&
e.Orientation == PageOrientation.LandscapeRight)
transitionElement.Mode = RotateTransitionMode.In90Counterclockwise;
// clockwise rotation
else if (_previousOrientation == PageOrientation.LandscapeLeft &&
e.Orientation == PageOrientation.PortraitUp ||
_previousOrientation == PageOrientation.PortraitDown &&
e.Orientation == PageOrientation.LandscapeLeft ||
_previousOrientation == PageOrientation.LandscapeRight &&
e.Orientation == PageOrientation.PortraitDown ||
_previousOrientation == PageOrientation.PortraitUp &&
e.Orientation == PageOrientation.LandscapeRight)
transitionElement.Mode = RotateTransitionMode.In90Clockwise;
// 180 rotation
else
transitionElement.Mode = RotateTransitionMode.In180Clockwise;

var transition = transitionElement.GetTransition((PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual).Content));
transition.Completed += delegate { transition.Stop(); };
transition.Begin();

_previousOrientation = e.Orientation;
}

/// <summary>
/// When leaving the page, clearing the orientation
/// </summary>
/// <param name="e"></param>
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);

_previousOrientation = null;
}

/// <summary>
/// When comming to the page, initiate the orientation
/// </summary>
/// <param name="e"></param>
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);

_previousOrientation = Orientation;
}
}
[/csharp]

You may notice that I always keep track of the previous orientation. It is very important because I use it to know if I need to perform a clockwise or a counter clockwise transition. Thus I use the OnNavigatedFrom and OnNavigatedTo method in order to set and clean my previous orientation value. I also do it this way for another reason.
If you are in the main page on a portrait up orientation and then go to the detail view and changhe the orientation to landscape. The detail view will rotate, but when you’ll go back the main page will detect a change in the orientation and then perform an unneeded rotate transition. In order to avoid that, I use the navigation methods to clean the previous orientation variable so that the OnOrientationChange methods can behave properly.

Now, you just need to make your pages derive this new AutoRotatePage class.

[csharp]
// /MainPage.xaml.cs
// …
public partial class MainPage : AutoRotatePage
// …
[/csharp]

Don’t forget the xaml, after declaring the local namespace :

[xml]
<!–MainPage.xaml–>
<local:AutoRotatePage
x:Class="WindowsPhoneDataBoundApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
xmlns:local="clr-namespace:WindowsPhoneDataBoundApplication1"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

<!– … –>

</local:AutoRotatePage>
[/xml]

Now you can compile and test your application. Everything behaves properly.

Rotate transition
Rotate transition

Support a vertical stretch in the ListBox

Now you may want to align right some element of the list box, for example the detail textblock. Let’s do so.

Edit the concerned textblock in the xaml file:

[xml]
<!–MainPage.xaml–>
<!– … –>
<StackPanel Margin="0,0,0,17">
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" HorizontalAlignment="Right"/>
</StackPanel>
<!– … –>
[/xml]

You have now a right alignment of your elements:

Right Aligment on portrait
Right Aligment on portrait

But, if you go to the landscape mode, you will find an error in the layout.

right aligment on landscape fails
right aligment on landscape fails

You notice a gap between the detail text and the right border of the screen.

In order to fix this, you will need to create a new resource and apply it to the ListBox. Let’s got the App.xaml and declare it:

[xml]
<!–App.xaml–>
<!– … –>
<Application.Resources>
<Style x:Key="ListBoxTemplate" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentControl ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalContentAlignment="Stretch"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
<!– … –>
[/xml]

As you can see, my resource access to the ListBox items and set the HorizontalContentAlignment to stretch.

Now, apply it to the ListBox:

[xml]
<!–MainPage.xaml–>
<!– … –>
<ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="MainListBox_SelectionChanged" ItemContainerStyle="{StaticResource ListBoxTemplate}">
<!– … –>
[/xml]

You can go back to the main page on Landscape mode and observe the correct right alignment.

right aligment on landscape ok
right aligment on landscape ok

Wrap up

Now you have everything set to have a nice Windows Phone 7 app that support both orientation with nice transitions and a proper ListBox.

Newbie mistake in Silverlight UI threading

Newbie mistake in Silverlight UI threading

I just began my first development with Silverlight for windows mobile 7 and I rapidly ran into one of the most famous newbie mistake: the misuse of the UI threading.

At first I just wanted to make a basic app that load a webpage and display the string content. Thus a simple default project in which I add a simple text block is just enough:

A basic text block into the default layout
A basic text block into the default layout

My view is ready; let’s add some code to it. I just add ContentPanel_Loaded event and insert a simple http request that will load a webpage and update the text label:

[csharp]
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void ContentPanel_Loaded(object sender, RoutedEventArgs e)
{
// instantiate the web client
var client = new RestClient("http://google.fr&quot;);
// make the asynchronous request, assign the result to the textblock
client.ExecuteAsync(new RestRequest(Method.GET),
r => textBlock1.Text = r.Content);
}
}
[/csharp]

Actually I used the RestSharp library (RestSharp website) in order to easily make a asynchronous request. The important thing is that I threaded my request and when I get the result I display it in the textblock.

At first, it looks like it could work well but… when you run it throw a UnathorizedAccessException (“Invalid cross-thread access”). Basic mistake.

We need to know that Silverlight support multithreading but reserve the UI access to one specific thread. When we made the asynchronous request, it was in another thread that has no right to update the UI, thus we got the previous exception.

In order to fix this, we need to access to the authorized thread and make it update the textBlock.

[csharp]
private void ContentPanel_Loaded(object sender, RoutedEventArgs e)
{
var client = new RestClient("http://google.fr&quot;);
client.ExecuteAsync(
new RestRequest(Method.GET),
r =>
{
// access the dispatcher and give the action
Dispatcher.BeginInvoke(
new Action<string>(UpdateTextBlock),
r.Content);
});
}

// function that update the textBlock
void UpdateTextBlock(string result)
{
textBlock1.Text = result;
}
[/csharp]

Now, instead of directly update the textBlock, we tell the dispatcher to call the UpdateTextBlock function with the request string result. The dispatcher will automatically ask the UI thread to call the function, thus it is executed by the right thread.

The result in the emulator
The result in the emulator

You can find more information about this subject here: Dispastcher documentation.