Windows Phone performance analysis & optimization during TechDays

.Net, Silverlight, Windows Phone No Comments »

In about 2 weeks now, I’ll have the chance to be part of the French TechDays in Paris as a speaker. This year, I’ll own a session called “Windows Phone performance analysis & optimisation” with my colleague Charlotte.

The agenda looks like the following:

  • why performance analysis ?
  • device vs emulator
  • leveraging WP7 threads
  • using the VS profiler for WP7
  • tips and tricks

During the session we will use a “real” app we’re working on for a few months now (I’ll share more details after the session). We have some cool tips that haven’t been shared anywhere before, so if performance is a topic of interest for you, stat tuned !

Click on the following image for a link to the TechDays website:

I’m planning to share the most of the content of this session on my blog soon after the event.

Don’t hesitate to stop by and say hi…

Property change notifications when using SQL CE on Windows Phone 7.1

Windows Phone 4 Comments »

I wanted to share a quick syntax trick I’m using to send property change notifications in a Windows Phone 7.1 application. As you already know, the Mango release of Windows Phone introduce local database storage using SQL Compact Edition and Linq-To-SQL.

In the MSDN documentation Local Database Best Practices for Windows Phone, you can find the following recommendation:

Minimizing Memory Usage

LINQ to SQL change tracking works by maintaining two copies of each object (…)

By default, LINQ to SQL will create the two copies of the object when the objects are materialized. Frequently, however, only a handful of objects in the materialized collection will actually get modified within a specific transaction. In this case, there is no reason to keep a second copy of the object.

The INotifyPropertyChanging interface allows the application to notify the DataContext when it is modifying a property that will ultimately be submitted as an update to the database. The DataContext can use that notification as a trigger to create the copy. This way, only the items that are actually changing need to be duplicated.”

It means that to optimize memory usage, your model class should implement both the INotifyPropertyChanged and INotifyPropertyChanging interface. Memory usage is an important aspect, especially on mobile device ! On the Windows Phone platform the certification requires your app to use less than 90MB of memory.

So you’ll probably end up creating a base class for all your model, maybe something like this EntityBase:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class EntityBase : INotifyPropertyChanged, INotifyPropertyChanging
{
    public event PropertyChangedEventHandler PropertyChanged;
    public event PropertyChangingEventHandler PropertyChanging;
 
    protected void RaisePropertyChanged(string propertyName)
    {
        if (propertyName == null)
            throw new ArgumentNullException("propertyName");
 
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
 
    protected void RaisePropertyChanging(string propertyName)
    {
        if (propertyName == null)
            throw new ArgumentNullException("propertyName");
 
        if (this.PropertyChanging != null)
            this.PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
    }
}

And you’ll define a property like the following

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public string Title
{
    get
    {
        return this.title;
    }
    set 
    { 
        if(this.title != value)
        {
            this.RaisePropertyChanging("Title");
            this.title = value;
            this.RaisePropertyChanged("Title");
        }
    }
}

Because I’m not a big fan of this syntax (property name is duplicated, and it’s easy to use either the first call or the second one…), I tried to find another solution. Here is my proposal

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public string Title
{
    get
    {
        return this.title;
    }
    set 
    { 
        if(this.title != value)
        {
            using (this.NotifyChange("Title"))
            {
                this.title = value;
            }
        }
    }
}

This syntax is based on the using operator and the IDisposable interface. The IDisposable interface used to be implemented by objects which must explicitly release resources when they are no longer needed. But you can use it for any other reason and benefit the using operator !

Here is the additional code in my EntityBase class:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
protected IDisposable NotifyChange(params string[] propertyNames)
{
    return new PropertyChange(this, propertyNames);
}
 
private class PropertyChange : IDisposable
{
    private ModelEntityBase entity;
    private readonly string[] propertyNames;
 
    public PropertyChange(ModelEntityBase entity, string[] propertyNames)
    {
        this.entity = entity;
        this.propertyNames = propertyNames;
 
        foreach (var propertyName in propertyNames)
        {
            this.entity.RaisePropertyChanging(propertyName);                    
        }
    }
 
    public void Dispose()
    {
        foreach (var propertyName in propertyNames)
        {
            this.entity.RaisePropertyChanged(propertyName);                    
        }
 
        this.entity = null;
    }
}

Not that if setting your property might invalidate other properties as well, you can give more than one parameter to the NotifyChange method.

Hope this helps !

 

 

MVVM Framework explorer updated

Silverlight, Windows Phone, WPF 1 Comment »

I just updated my MVVM frameworks explorer Silverlight application. You can find the updated application here.

Here is the top 5 of MVVM frameworks supporting WPF, Silverlight and Windows Phone 7:

  1. MVVM Light (61k downloads)
  2. nRoute (19k downloads)
  3. Caliburn Micro (18k downloads)
  4. Simple MVVM toolkit (5k downloads)
  5. Catel (5k downloads)

When enough ViewModel is enough

Silverlight, Windows Phone, WPF 9 Comments »

In the last few years, we’ve seen the WPF and Silverlight community embracing the MVVM methodology. As one of the early adopters of MVVM (one of my first post about the subject was late 2008), I’ve seen the pattern evolving both in the web community and with developers I’ve met in my daily life.

Today, I’d like to share with you a simple concept I try to stick to when I’m doing WPF, Silverlight or Windows Phone 7 development. It can be summarized as “Enough ViewModel is enough”.

The simple idea behind this slogan is that there ARE stuff which are view-related and SHOULD NOT be embedded in the ViewModel layer. I’ve seen too many developers going the “100% viewmodel way” which means for them absolutely no code-behind without any dispensation.

For example, I came across this code. It’s the ViewModel layer associated to a simple view where the user fills various input and has immediate feedback about the progress (like “75% of the fields are completed”). If by the way you’re interested in implementing this behavior you can check out this article I wrote on CodeProject)

The following code is simplified to the sake of the article:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class ViewModel
{
    // data field acts as the model object behind the VM layer
    private Data data;
 
    // missing code...
    // public properties used by the view using databinding
 
    public ViewModel()
    {
        // very simplified for this article...
        this.data = new Data();
        this.data.SelectedValuesChanged += new EventHandler(data_SelectedValuesChanged);
    }
 
    public void UpdateProgress()
    {
        // some code...
    }
 
    void data_SelectedValuesChanged(object sender, EventArgs e)
    {
        this.UpdateProgress();
        this.Initialize();
    }
 
    public void Initialize()
    {
        var item = this.data.GetItem("id1");
        if (item != null)
        {
            item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
            item.SelectedValuesChanged += new EventHandler(item_SelectedValuesChanged);
            foreach (var value in item.Values)
                value.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
        }
 
        item = this.data.GetItem("id2");
        if (item != null)
        {
            item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
            item.SelectedValuesChanged += new EventHandler(item_SelectedValuesChanged);
            foreach (var value in item.Values)
                value.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
        }
    }
 
    void item_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        this.UpdateProgress();
    }
 
    void item_SelectedValuesChanged(object sender, EventArgs e)
    {
        this.UpdateProgress();
    }
}

The idea is simple, as soon as the user changes a value in the View, we must compute the current progress. Because the ViewModel have several levels, we end-up having to register to every single PropertyChanged event which leads to cumbersome code. By the way, this code can also creates memory leaks since we register a lot of event handlers without removing them, but that’s another discussion…

Here is my way to solve this problem:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public partial class View : UserControl
{
    private readonly ViewModel viewmodel;
 
    public View()
    {
        InitializeComponent();
 
        this.viewmodel = new ViewModel();
 
        this.AddHandler(
            FocusManager.LostFocusEvent,
            new RoutedEventHandler(this.OnLostFocus),
            true);
    }
 
    private void OnLostFocus(object sender, RoutedEventArgs e)
    {
        this.viewmodel.UpdateProgress();
    }      
}

What is wrong with this way ? The View has code-behind ? That’s not a big deal: the code is more readable, maintainable. It makes also more sense: when a view-related operation occurs (in this case, focus has changed), update the progress.

The simple message I’d like to spread is the fact that there is nothing wrong with the fact to have sometime, a little bit of code-behind in your view if that facilitates your architecture. There is no need to create a complicated infrastructure with behaviors, commands or bindings just to keep the view empty if that does not make sense.

Another great example in a real application is available in the Advanced MVVM book by Josh Smith.

 

Mix11: Windows Phone 7 news

Windows Phone 1 Comment »

Today is Mix day ! After yesterday keynote about HTML5, IE10 preview and other web stuff, it’s time for serious Silverlight and Windows Phone announcements !

Today’s keynote starts with Joe Belfiore talking about the update process for the NoDo update of WP7. As you know this update was not delivered “properly”, but at least we know have a good communication from Microsoft about that (you can for exemple check-out the Where’s my phone update website)

Nokia partnership

  • Marco Argenti, Head of Dev Experience comes on stage
  • Nokia is “working very hard” to deliver the very first WP7 device

General

  • update is schedule for the fall
  • all existing phones and new phones will get the update
  • 16 additional languages will be supported
  • more countries where we can create apps (from 30 to 38)
  • more countries where we can buy apps (from 16 to 35)

Marketplace / Search

  • better apps list: filter by letters (like with the contacts)
  • new search button to search for a particular app
  • better marketplace
    • more information with less confusion (music and apps are no longer mixed)
    • search for podcasts
    • new “related” pivot item when seeing an app for related app
  • we can integrate an app with the search feature of the phone

Web Experience

  • the update include IE9
  • the core engine is the same code base that the one we found desktop : including HW acceleration
  • address bar is moved to the bottom
  • support background audio for HTML5: you can leave IE and keep listening to the music !
  • tabbed UI for navigating between tabs
  • support for H264 video

Platform

  • improved panorama and pivot control
  • improvements for live tiles
  • access to the ring tones settings (set a music files as ring tone programmatically)
  • TCP/IP sockets
  • SQL database
  • more launchers and choosers
  • data access to the contacts and calendars on the phone
  • better integration with the sensors on the phone (like RAW camera access)
  • Skype coming to the platform this fall (leveraging many of those new features)
  • pin live tiles with deep link to our apps (which would launch the app and give the link as parameter)
  • Silverlight 4 features support
  • applications can now contains both Silverlight and XNA content

Multitasking

  • Spotify coming to WP7 using new multitasking capabilities
  • fast-app switching
  • use “live agents” to prevent battery life

Tooling

  • new version of tools will be available next month !
  • new capabilities in the emulator: simulate accelerometer and location sensors right from the emulator

  • new profiling support

Performance

  • scrolling: totally smooth scrolling without any changes in our applications !
  • image decoding
  • garbage collection
  • memory usage

Conclusion

  • A lot of new features available to developers + Silverlight 4 features coming to the phone
  • An development experience which is definitively the best out on the market for mobile development
  • Microsoft is listening to our feedback
  • Update is schedule for this fall !
  • New version of the tools next month

 

 

 

Tap N Match a cool WP7 game ! Vote on Facebook !

Events, Silverlight, Windows Phone 4 Comments »

Today I need help from all my readers across the globe ! Please vote for our TapNMatch WP7 game here

Microsoft France is organizing since a couple of months a Windows Phone 7 contest in order to create cool applications. Applications are demonstrated using a short video which is posted on Facebook. The goal is to have the maximum number of “Like” in order to be selected for the final.10 applications are going to be selected, and on October 7th, each selected developers will have to present very quickly (2min) its application in front of an amazing jury made of Steve Ballmer and CEOs of french companies.

A coworker and I have been working on a Windows Phone 7 game called Tap N Match created using Silverlight. The goal of the game is to associate “targets” which have a number either by creating pairs (5;5) or sequences (1;2). Here is quick description of the game:

  • best scores are recorded in the cloud using Windows Azure
  • use of the Bing APIs in order to determine the country of the player when posting a new score
  • use of the Pivot control

Here is the presentation of our application on YouTube:

In order to vote for our application:

  1. Go to : http://www.facebook.com/Developpeurs.net
  2. “Like” this page
  3. Go to the video of my game : http://www.facebook.com/Developpeurs.net#!/video/video.php?v=434150728926
  4. “Like” my video :-)

Thank you very much for your help !

[WP7] Sound effect in a Silverlight Windows Phone 7 application

Windows Phone 8 Comments »

A coworker and I are currently working on a simple Silverlight game for the Windows Phone 7 platform. In order to give some feedback to our end-user, we decided to add sound effects. Here is a very short post about how we did that.

The first thing is to reference the Microsoft.Xna.Framework assembly in your project. This assembly is needed to access the low-level sound component of XNA right from your Silverlight application. You also need to have your sound effect in a WAVE format file.

Then we created a simple action (from the Blend Behavior toolkit) which is a TargetedTriggerAction:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class SoundEffectAction : TargetedTriggerAction<FrameworkElement>
{
    public string Source
    {
        get { return (string)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }
 
    public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
        "Source", 
        typeof(string), 
        typeof(SoundEffectAction), 
        new PropertyMetadata(string.Empty));
 
    protected override void Invoke(object parameter)
    {
        if(!string.IsNullOrEmpty(this.Source)
        {
            var stream = TitleContainer.OpenStream(this.Source);
            if (stream != null)
            {
                var effect = SoundEffect.FromStream(stream);
                FrameworkDispatcher.Update();
                effect.Play();
            }
        }
    }
}

Using this action, we’re able to wire sound effect right in Blend which produces the following XAML code:

1
2
3
4
5
6
7
8
<Grid Margin="2">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonUp">
            <Actions:SoundEffectAction Source="Resources/Sounds/Click.wav" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <!-- rest of the xaml... -->
</Grid>

Simple, isn’t it ?

[WP7] Beta build of the Windows Phone 7 tools is available

Windows Phone No Comments »

I guess many Windows Phone 7 developers have been waiting for this news since many weeks. It’s finally official: the Beta build of the Windows Phone 7 tools is out. If you want to download the new version here is the link.

This new version has been released during WPC (Microsoft Worldwide Partner Conference). For more information, please check-out:

  • the post on the Windows Phone Developer Tools blog.
  • this post by Jaime Rodriguez about all breaking change between the April CTP Refresh and the Beta build
  • this post by the Blend team about the new features available in Blend
  • the release note

Here are a summary of the changes in this new version:

  • Despite HW acceleration effects have been removed from the platform (DropShadow and Blur effects are now no-op). This feature might come back later.
  • Compatibility with Blend 4 RTM
  • API near final
  • Various fixes

Note that panorama and pivot controls are coming in the next weeks… Grab you copy now and enjoy Windows Phone 7 development :-)

http://www.microsoft.com/downloads/details.aspx?FamilyID=c8496c2a-54d9-4b11-9491-a1bfaf32f2e3&displaylang=en

[WP7] Windows Phone 7 challenge for french readers !

.Net, Events, Silverlight, Windows Phone No Comments »

A couple of months ago, the french programming website www.developpez.com organized an event to discover Windows Azure programming (I wrote a blog post about it here).

A similar event has just been launched for Windows Phone 7 development at challenge-windowsphone7.developpez.com

(tr: “Let’s go !” “World cup ?” “No… Windows Phone 7 challenge by developpez.com !”)

The challenge is made of 6 steps:

  1. Tools : download and install the required tools
  2. Quizz : first basic quizz
  3. Silverlight development
  4. Silverlight and push notifications
  5. XNA
  6. Quizz : advanced quizz

Each winner will have the following gifts:

This kind of challenge is really helpful to discover a new technology the funny way ! I hope I’ll get my “I Love Windows Phone” tee-shirt to wear it this summer :-)

[WP7] Bug when using NavigationService in Windows Phone 7

Windows Phone No Comments »

The last couple of days, I’m playing with my favourite tools in order to build a simple WP7 demo application. I just encountered a weird problem which I wanted to share here… I’ll update this article as soon as I’ll get some feedback from Microsoft about this issue.

Note: this problem did not occur if you’re using the first CTP of the WP7 tools

To reproduce the bug:

  • Create a new Windows Phone 7 application in VS2010
  • Add a new page (use the default name: Page1)
  • In the MainPage, add the following XAML code:
1
2
3
<ListBox>
  <Button MouseLeftButtonDown="Handler"/>
</ListBox>
  • In the code-behind, add the following handler:
?View Code CSHARP
1
2
3
4
private void Handler(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
    this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
  • Run the application and click on the TextBlock
  • You’ll get an ArgumentException with the following StackTrace:

at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at MS.Internal.XcpImports.MethodPack(IntPtr objectPtr, String methodName, Object[] rawData)
at MS.Internal.XcpImports.UIElement_TransformToVisual(UIElement element, UIElement visual)
at System.Windows.UIElement.TransformToVisual(UIElement visual)
at System.Windows.Controls.ScrollViewer.OnManipulationStarted(ManipulationStartedEventArgs e)
at System.Windows.Controls.Control.OnManipulationStarted(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

Analysis:

It took me some time to reproduce this problem in a very simple application. At the very beginning, I though it has something do to with the EventToCommand behavior I was using (from the famous MVVM-Light framework of Laurent Bugnion) but after talking with Laurent it was clear it wasn’t the case.

The StackTrace seems to indicate a problem with the ScrollViewer of the ListBox…

Workaround:

Several possibilities seems to be working:

  1. Change the ListBox to an ItemsControl
  2. Or, change the event to ManipulationCompleted

I didn’t find the correct location in order to log this issue on Microsoft Connect. Pleas let me know if you have the URL

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in