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 :-)

 

 

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 !

 

 

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

 

 

 

TechDays 2011: Rx talk, slides and source code

Rx, Silverlight, Windows Phone, WPF 3 Comments »

As promised, here is a blog post which shares source code and slides for the Rx talk I gave during last TechDays in Paris. I animated this session with my co-worker Charlotte and with Mitsu.

Download slides here.
Download source code here.

Demo1: Drag’n'drop in a WPF application

The goal was to implement a basic drag’n'drop functionality in a WPF application. The Rx query looks like the following:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var query = from mouseDown in this.image.GetMouseLeftButtonDownObservable()
            let downPosition = mouseDown.EventArgs.GetPosition(this)
            let rect = new Rect(downPosition.X - 10, downPosition.Y - 10, 20, 20)
            let delta = mouseDown.EventArgs.GetPosition(this.image)
            from mouseMove in this.GetMouseMoveObservable()
                .Select(ea => ea.EventArgs.GetPosition(this))
                .SkipWhile(p => rect.Contains(p))
                .DoOnce(p => this.onMouseEnter.Begin(this.image))
                .Select(p => p.Offset(delta))
                .TakeUntil(this.GetMouseLeftButtonUpObservable())
                .Finally(() => this.onMouseLeave.Begin(this.image))
            select mouseMove;
 
query.Subscribe(p => this.image.SetPosition(p));



Demo2: online Twitter search and Bing map geolocalization

This time, the goal was to query Twitter asynchronously and to geolocalize the associated Tweets. The Rx query:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
this.textbox.GetTextChangedObservable()
    .DistinctUntilChanged((ea) => this.textbox.Text)
    .Throttle(TimeSpan.FromMilliseconds(300))
    .ObserveOnDispatcher()
    .Do(ea => this.ShowLoadingIndicator())
    .Select(ea => TweeterHelper.Search(this.textbox.Text))
    .Switch()
    .ObserveOn(Scheduler.Dispatcher)
    .Select(page => TweeterHelper.ParseTwitterSearch(page))
    .Subscribe((tweets) =>
                    {
                        this.HideLoadingIndicator();
                        this.listbox.ItemsSource = tweets;
 
                        TweeterHelper.LocalizeTweets(this.map, tweets);
                    });



Demo3: using the accelerometer in a Windows Phone 7 application

The last demo was about the usage of the accelerometer in a Windows Phone 7 application. Here is the relevant Rx query:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
private void MoveEllipse(IObservable<Acceleration> accelerationObservable)
{
    accelerationObservable
        .SlidingBuffer(2)
        .Select(accCouple => new Acceleration(accCouple.First(), accCouple.Last()))
        .ObserveOnDispatcher()
        .Do(acc => this.textBlock.Text = acc.ToString())
        .Scan(new Point(x0, y0), (point, acc) => point.Move(acc).ClipTo(horizontalInterval, verticaInterval))
        .Subscribe(p => this.ellipse.SetCenter(p));
}

Doing this session was a really great experience ! I’d like to thank Charlotte and Mitsu for doing it with me. Also, I’d like to thank all users who came to the presentation !

TechDays 2011: Rx talk in Paris

Rx, Silverlight, Windows Phone, WPF 3 Comments »

During the next 3 days, the “Palais des Congrès” in Paris will hosting the TechDays 2011. For the very first time, I’ll have the chance to be part of it as a speaker for a talk about Rx (Reactive Extensions).

The session will take place in room 241, tomorrow Thursday 8, from 1pm to 2pm. Here is the link to the session’s description (in French).

I’ll share presentation slides and source code by the end of the week :-)

MVVM Framework Explorer update and top MVVM Frameworks

Silverlight, Windows Phone, WPF 2 Comments »

A couple of days ago I received an email from Geert van Horrik, a developer working on a new MVVM Framework called Catel. Geert asked me to update my MVVM Framework Explorer app in order to include his new framework. Here is the resulting updated app (click to launch):

Besides adding this new framework, I updated the download count for each framework, which allowed me to do some statistics. Here are the download progression for the most popular MVVM frameworks between July 2010 and January 2011:

Framework July 2010 January 2011 Progression
Calcium 7486 9963 33%
Caliburn 27012 36392 35%
Cinch 9865 15206 54%
CoreMVVM 3373 4419 31%
MEFedMVVM 905 2074 129%
MVVM Foundation 5759 7656 33%
MVVM Helpers 674 1571 133%
MVVM Light 11601 30111 160%
NitoMVVM 446 1098 146%
nRoute 7638 13724 80%
Onyx 2027 2195 8%
WAF 12255 30673 150%

Top progression during the last 6 months:

  1. MVVM Light (by Laurent Bugnion): +160%
  2. MVVM Helpers (by Mark Smith): +133%
  3. MEFedMVVM (by Marlon Grech): +129%
  4. WAF (by Jurgen Berchtel): +150%

Top downloaded frameworks:

  1. Caliburn (by Rob Eisenberg): +36 000 downloads
  2. MVVM Light (by Laurent Bugnion): +30 000 downloads
  3. WAF (by Jurgen Berchtel): +30 000 downloads

Congratulations to their respective authors.

Calcium 7486 9963 33%
Caliburn 27012 36392 35%
Cinch 9865 15206 54%
CoreMVVM 3373 4419 31%
MEFedMVVM 905 2074 129%
MVVM Foundation 5759 7656 33%
MVVM Helpers 674 1571 133%
MVVM Light 11601 30111 160%
NitoMVVM 446 1098 146%
nRoute 7638 13724 80%
Onyx 2027 2195 8%
WAF 12255 30673 150%
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in