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…

ReSharper and code generation

Tools 2 Comments »

I don’t know why I’ve found this feature only today, but I wanted to share another great feature of ReSharper. Let say you need to implement a C# structure. You may start with the following code:

?View Code CSHARP
1
2
3
4
5
6
public struct ServerItem
{
    public string Id { get; private set; }
    public DateTime? Added { get; private set; }
    public int ChildCount { get; private set; }
}

Then you start thinking, “I need to setup a constructor…” You can do it manually, but you can also ask ReSharper do to the job for you. All you have to do is press ALT+Enter (this might depend on your configuration obviously…)

ReSharper will generate the constructor for you:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public struct ServerItem
{
    public ServerItem(string id, DateTime? added, int childCount)
        : this()
    {
        this.Id = id;
        this.Added = added;
        this.ChildCount = childCount;
    }
 
    public string Id { get; private set; }
    public DateTime? Added { get; private set; }
    public int ChildCount { get; private set; }
}

Fine. Then you remember that you also need to setup equality members properly… You have to override Equals, GetHashCode… This is not complicated but it can become cumbersome and it often feels like a waste of time. Here is the ReSharper way of doing this:

1. Press ALT+Enter

2. Choose “Equality members” and setup the code generation:

And BOOOM ! You’re done:

?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
public struct ServerItem
{
    public ServerItem(string id, DateTime? added, int childCount)
        : this()
    {
        this.Id = id;
        this.Added = added;
        this.ChildCount = childCount;
    }
 
    public string Id { get; private set; }
    public DateTime? Added { get; private set; }
    public int ChildCount { get; private set; }
 
    public bool Equals(ServerItem other)
    {
        return Equals(other.Id, this.Id) && other.Added.Equals(this.Added) && other.ChildCount == this.ChildCount;
    }
 
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
        {
            return false;
        }
        if (obj.GetType() != typeof(ServerItem))
        {
            return false;
        }
        return Equals((ServerItem)obj);
    }
 
    public override int GetHashCode()
    {
        unchecked
        {
            int result = (this.Id != null ? this.Id.GetHashCode() : 0);
            result = (result * 397) ^ (this.Added.HasValue ? this.Added.Value.GetHashCode() : 0);
            result = (result * 397) ^ this.ChildCount;
            return result;
        }
    }
 
    public static bool operator ==(ServerItem left, ServerItem right)
    {
        return left.Equals(right);
    }
 
    public static bool operator !=(ServerItem left, ServerItem right)
    {
        return !left.Equals(right);
    }
}

The code-generation features of ReSharper has been there for a long time… But because I just found out the power of them, I wanted to briefly showcased them in this post :-)

If you like typing XAML you will love ReSharper 6.1 !

Silverlight, Tools, Windows 8, Windows Phone, WPF 3 Comments »

Resharper is an amazing tool for any .Net developers. The latest version 6.1 has been released just a couple of weeks ago and I wanted to share with you a brief overview of the new workflow available in the XAML world !

Visual Studio 2010 introduced 2 new design time properties: d:DesignInstance and d:DesignData. Those properties can be used in order to specify a design time DataContext in order to have more help during the creation of a binding.

For example, when you create a binding using the Property dialog of VS2010 you can browse your DataContext to select the right property (image from this blog post from Karl Shifflet):

Resharper 6.1 is now able to use those metadata in order to improve the experience you have while typing XAML (which I personally do a LOT!). Here is how it works:

  • you create a new ViewModel with a simple property (this property has just get/set because we don’t need much more in the context of this post…)

  • you setup a binding in your view

At this point the ReSharper magic comes into play…

  • ReSharper warns you the DataContext is unknown

  • Offer the ability to fix this

  • Note that like in C#, you can very easily resolve namespace issues

  • Then notice that the warning is gone (the Title property is no longer underlined)

  • You can now add a new binding

  • You can then ask ReSharper to create the property in your ViewModel

  • Choosing the first option will get you to the ViewModel definition

Now that I’ve upgraded my installation to version 6.1, I think this is a must have !

That’s all for today ! Hope it helps :-)

 

 

Welcome 2012 and happy new year!

Events 1 Comment »

The beginning of the year always seems the appropriate time to take a step back and see what happened in the last few months… So let’s take a deep breath…

The last year has been a busy for me… At the beginning of February I had the chance to give a talk about Rx (Reactive Extensions) in Paris for the Microsoft TechDays with my colleague Charlotte and ex-Microsoftee Mitsu Furuta. It was my first talk in such an event and it was a very valuable and interesting experience.

Few weeks after that, I went to the US for the very first time. I was in Redmond for a week for the annual MVP Summit. I had a dinner with the WPF Disciples where I finally met in person some of the guys of the group. I also discovered the Microsoft campus in Redmond, had a dinner with members of the WPF team…

In September I went to Anaheim (near Los Angeles) for //BUILD/. It was an amazing time. I’ve never seen so much enthusiast and it was truly amazing (maybe the Windows 8 slate distributed during the event is part of that!) It was also the occasion to meet new people.

In November, I went to Lyon for the MSDays as ATE (Ask The Expert) in order to discuss Windows 8 (and show the //BUILD/ slate):

Blog post activity has been also important and more varied (Windows Phone, Windows 8, WinRT…)

In 2012, I hope to do more work with Windows Phone. As an introduction to that, I’ll be speaking at the Microsoft TechDays in February on the subject “Performance analysis and optimization of Silverlight Windows Phone app”. I’ll write a blog post about this session very soon.

Happy new year to all my readers, and thank you for reading this blog and sharing your feeling in the comments!

Track memory usage of your Windows Phone 7.1 app in real time

Windows Phone 1 Comment »

Update January 17th: I just found out that Peter Torr released more than a year ago a similar helper class which is very nice. You can check out his solution here.

Memory usage is an important aspect, especially on mobile device. If you want to publish an app on the Windows Phone marketplace you must satisfy the Technical Certification Requirements: “5.2.5 Memory Consumption: An application must not exceed 90 MB of RAM usage, except on devices that have more than 256 MB of memory.”

In this post, I’m sharing a technique to track the memory usage of a WP7 app in real tile in every single page of the app. By adding only one line of code in your existing app, you’ll be able to display memory usage in all your pages (without any changes):

Download source code and example

How to integrate the component in your existing app?

  1. import the MemoryWatcher class in your existing project
  2. in the InitializePhoneApplication method, add a new line after the creation of the RootFrame:
?View Code CSHARP
1
2
3
4
5
// 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 PhoneApplicationFrame();
// Add the following line !
new MemoryWatcher(RootFrame) { IsDisplayed = true };

How it works?

During its initialization, the MemoryWatcher control will set an event handler to have a callback whenever the user navigates to a new page. When the new page is loaded, it checks if it can dynamically insert the MemoryWatcher control. This is done by checking the root UI element of the page and inserting the watcher control in it. Here is the full code of the MemoryWatcher 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
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
 
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
 
namespace MemoryWatcherDemo
{
    public class MemoryWatcher : ContentControl
    {
        private readonly DispatcherTimer timer;
        private readonly PhoneApplicationFrame frame;
        private const float ByteToMega = 1024 * 1024;
 
        public bool IsDisplayed { get; set; }
 
        public MemoryWatcher(PhoneApplicationFrame frame)
        {
            if (frame == null)
                throw new ArgumentNullException("frame");
 
            this.frame = frame;
            this.frame.Navigated += new NavigatedEventHandler(this.OnFrameNavigated);
            this.frame.Navigating += new NavigatingCancelEventHandler(this.OnFrameNavigating);
 
            this.timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
            this.timer.Tick += new EventHandler(this.OnTimerTick);
 
            // setup some basic properties to ensure the content will be visible
            this.Foreground = new SolidColorBrush(Colors.Red);
            this.VerticalContentAlignment = VerticalAlignment.Center;
            this.HorizontalContentAlignment = HorizontalAlignment.Center;
            this.Margin = new Thickness(0, -35, 0, 0);
        }
 
        private void OnFrameNavigated(object sender, NavigationEventArgs e)
        {
            if (!this.IsDisplayed)
                return;
 
            var page = this.frame.Content as PhoneApplicationPage;
            if (page != null)
            {
                Panel host = page.Content as Panel;
                if (host != null && !host.Children.Any(c => c is MemoryWatcher))
                {
                    this.timer.Start();
                    host.Children.Add(this);
                }
            }
        }
 
        private void OnFrameNavigating(object sender, NavigatingCancelEventArgs navigatingCancelEventArgs)
        {
            var page = this.frame.Content as PhoneApplicationPage;
            if (page != null)
            {
                Panel host = page.Content as Panel;
                if (host != null && host.Children.Contains(this))
                {
                    this.timer.Stop();
                    host.Children.Remove(this);
                }
            }
        }
 
        private void OnTimerTick(object sender, EventArgs e)
        {
            try
            {
                string currentMemory = (DeviceStatus.ApplicationCurrentMemoryUsage / ByteToMega).ToString("#.00");
                string peakMemory = (DeviceStatus.ApplicationPeakMemoryUsage / ByteToMega).ToString("#.00");
 
                this.Content = string.Format("Current: {0}MB Peak: {1}MB", currentMemory, peakMemory);
            }
            catch (Exception)
            {
                this.timer.Stop();
            }
        }
    }
}

Note:

  • The MemoryWatcher is looking for a Panel type in order to add itself to the list of children in the page. You might want to modify and improve this portion in order to better fit your needs.
  • The attached project targets Windows Phone 7.1, if you want to use the code in a 7.0 version, you should change the way the memory values are read (see this article for more details)

Enjoy the code and start tracking memory leaks :-)

Download source code and example

 

Meet me during the Microsoft Days in Lyon next Wednesday !

build, Events, Silverlight, Windows 8, Windows Phone, WPF No Comments »

Next Wednesday (November 9th), I’ll be at the Microsoft Days 11 as a member of the Ask The Expert team. I’ll be playing with the Samsung Slate I got at //BUILD/, discussing WPF, Silverlight, Windows Phone 7 and Windows 8.

Don’t hesitate to stop by and say hi if you’re coming to this event !

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 !

 

 

Running Windows 8 from a virtual environment

Windows 8 No Comments »

In the last few days I had many questions about the “good” way to run Windows 8 developer preview from a Virtual Environment. It turns out the Windows engineering team wrote a blog post last friday about that.

The popular options are the following:

Functional:

  • Hyper-V in Windows 8 Developer Preview
  • Hyper-V in Windows Server 2008 R2
  • VMware Workstation 8.0 for Windows
  • VirtualBox 4.1.2 for Windows

Non-functional:

  • Microsoft Virtual PC (all versions)
  • Microsoft Virtual Server (all versions)
  • Windows 7 XP Mode
  • VMWare Workstation 7.x or older

If you’re running Windows 8 developer preview in a virtual environment you probably should also take a look at the Windows 8: Tips and Tricks for mouse/keyboard users article on WinRumors.

Finally if like me you a bit disoriented by the lack of the classic Windows menu in the desktop mode, you should now that if you press the Windows key and start typing using your keyboard it will actually start filtering applications and show you those which match your search.

Enjoy your Windows 8 time !

BUILD: WinRT, Silverlight, WPF, XAML

Metro, Silverlight, Windows 8, WPF 4 Comments »

This blog post is part of my BUILD series.

I’m having a very busy week here in Anaheim ! I’m meeting many new people and had the chance to enjoy the conference from the inside. I’m also playing with this new Windows 8 slate Microsoft gave us ! I’m not going to do a blog post trying to summarize everything because there is just so much to say.I’m going to try to share my point of view on what I’ve seen here.

Our new platform

The original picture shown during the keynote to introduce the new platform was this one:

There has been a lot of confusion about that because of having XAML with C# in the Metro Style Apps without any reference to the CLR… Doug Steven did a pretty great job (blog post is here) by discussing with key people from the engineering team of Microsoft and creates this new more accurate picture:

Here is a quick summary:

  • there is only one CLR
  • .Net framework 4.5 is used in both Metro apps and Classic apps
  • it’s the same MSIL for Metro apps and Classic apps
  • in the Metro platform, we have a subset of the .Net framework (for example no OpenFileDialog…)

New opportunities

Before //BUILD we had already many choices to choose our development environment. we now have even more:

  • WPF and managed code for classic desktop apps
  • Silverlight in a web environment
  • Silverlight out of browser
  • WinRT + XAML for Metro apps
  • WinRT + HTML for Metro apps

I personally think that Silverlight in a web browser has not a great future. Microsoft just announced for example that the immersive version of IE will not run any plugins (so no Silverlight in the Metro UI) and we ‘ll know Microsoft is pushing HTML5 very strongly.

For classic desktop apps we have 2 options: WPF and Silverlight. Each of them has advantages and the choice we’ll have to do will depend on our constraints (deployment, business needs, connectivity…). I think there is room for the 2 platforms there.

For the Metro UI, you can choose between XAML and HTML. Microsoft told us they will keep a good feature parity between the 2 options. If you choose XAML and managed code you’ll be able to leverage a subset of the .Net framework.

I think another important aspect is that Metro will be available on Windows 8 only. Even though this new version of the OS might have a fast deployment rate (thanks to the slates), in many companies I don’t think it will be that fast.This, plus the fact that some LOB apps will not benefit the Metro UI leaves a lot of work to do in the desktop applications world (where we have both WPF and SL)… For WPF, we now have a new version coming in .Net 4.5. You can check out the new stuff here in the documentation.

In my next blog post I’m going to try to go deeper in the new WinRT/XAML world and see how it looks like for us, WPF and Silverlight developers.

 

BUILD: H-12

build No Comments »

This blog post is part of my BUILD series.

Just a quick update to share with you some pictures before the keynote starts (in about 12 hours now…).

This morning I had the chance to be part of the UX workshop organized by www.billyhollis.com and it was very cool. Billy did a great job trying to stimulate our right brain (developers used to be more left-brained)… He detailed various UI principles and showed a WPF application he worked on a couple of years ago (in 2008). We also had a nice tee-shirt:

Here are some other pictures I took today:

See you tomorrow ! Don’t forget that the keynote will be live-streamed at www.buildwindows.com

Keynote starts at 9:00 Pacific Time.

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