How to measure rendering time in a WPF application ?

WPF 5 Comments »

Last week, a colleague of mine asked me an interesting question: “I’m filling a control with content and I’d like to measure the time needed to render my control. How can I do that ?”

The first approach is to measure the elapsed time needed to instantiate and populate the control from C# code. We can use the StopWatch class to have a precise and easy to use measuring tool.

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
Stopwatch sw = new Stopwatch();
sw.Start();
 
for (int i = 0; i < 5000; i++)
{
  // here is the operation that fills the control
  this.canvas.Children.Add(new Rectangle());
}
 
sw.Stop();
MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");

However this approach will not give good results because we’re not taking into account the time needed to render elements in the visual tree. This is because elements are not rendered when you call the Add methods (for example in a Canvas) but when the visual tree is fully loaded.

A much better approach is to use the Dispatcher and request it to process an action at a priority right bellow the Render priority which is the Loaded priority:

dispatcherpriority

Using this trick, we ensure that all rendering actions have been completed. We can use the following code to do that:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Stopwatch sw = new Stopwatch();
sw.Start();
 
for (int i = 0; i < 5000; i++)
{
  // here is the operation that fills the control
  this.canvas.Children.Add(new Rectangle());
}
 
this.Dispatcher.BeginInvoke(
  DispatcherPriority.Loaded,
  new Action(() =>
  {
    sw.Stop();
    MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");
  }));

Hope this helps !

Analyzing events usage using a R# plugin

.Net, Tools 4 Comments »

As you might already know, even if the .Net framework has a garbage collector, you can easily create memory leaks in your application.

The most common way to create a leak is to register to an event handler on a object that has a longer lifetime than the object where the handler is defined. The problem can also occurs by using static class such as EventManager (for more information see this blog post). Some .Net developers have been working on a way to go round the problem using Reflection, Weak Reference and other cool stuff. You can check out for example this excellent article on Code Project.

However, if you cannot change the way your declare events (because of internal policies in the company or because you don’t have the source code), you must be very carefull about the way you manage your events.

I’ve been working lately on a Resharper plugin that helps detecting events that are never unsubscribed. Basically, what is does is the following:

resharper_plugin

I’d like to have feedback from you .Net developpers, about whether you find such a plugin useful or not.

  • How do you deal with the event memory leak problem ?
  • Would you like to use my plugin ?
  • Would you like me to release it on a open source platform ?
  • What other kind of possible leaks are you thinking about to enhance the plugin ?

Please write a comment to let my know what you think. Thank you for your feedback !

French article about MVVM posted !

WPF 1 Comment »

It’s finally online after a long work.I hope my french readers will enjoy it:  http://japf.developpez.com/tutoriels/dotnet/mvvm-pour-des-applications-wpf-bien-architecturees-et-testables/

Here is the abstract translated to english:

“Inch by inch, the WPF technology is being adopted by .Net developers as a development platform for next generation user interfaces. This changeover is taking time and complicated because WPF changes principles that are well known until now in the process of designing a user interface. The Model-View-ViewModel methodology helps formalize WPF developement by giving guidance that leads to apps cleary architectured, testable, and by optimizing the workflow between developer and designer.”

XAML guidelines: interviews of WPF masters

WPF 1 Comment »

Getting back to work this morning, I opened my Google Reader to have a look at the RSS feeds I’m reading.

I found a nice video on Channel9: “XAML Guidelines, Part 2”. The first episode, where Jaime Rodriguez interviews 3 people from Identity Mines is also available on Channel9 (unfortunately, the sound is rather poor on this episode…).

This time, Jaime meets up with Unni Ravindranathan from the Expression Blend team. During the shot, they open the Blend source code project inside Blend (sounds nice isn’t it :p). Unni explains the structure of the project, their conventions, how resources are used, etc.

I think Blend is an application we can learn a lot from. If you’re also interested to understand what architecture Blend uses, you can check out this post from Paul Stovell.

Here are some notes I took while watching the video:

  • Blend is shipped with 2 themes: Expression Light & Expression Dark
  • Blend resources are stored in (only !) 3 resources dictionaries
  • Resources are categorized into Colors, Brushes and Styles
  • Blend defines a set of margins and thicknesses that are used in the entire application to ensure a consistency across the different layouts
  • By convention, Name and Key properties are always defined first in the XAML
  • Properties might be spitted over several lines, if this is the case; properties are grouped together by types (style, size, appearance…)
  • Blend 3 will add extensibility and improve XAML code generation:
      - Name will always be the first property
      - Better control over how the XAML is formatted
  • Name everything versus name nothing? Blend names almost everything, it helps UI automation
  • Static resources versus dynamic resources? No big performance impact, Blend mostly uses dynamic resources
  • When design time doesn’t work fine in Blend
      - An exception can occur when Blend is creating the control because the running process is Blend itself and not the application we are creating
      - Add tests to check if code is running in design mode (you can use System.ComponentModel.DesignerProperties.GetIsInDesignMode(DependencyObject) method)
      - Debug Blend process by attaching an instance of Visual Studio to Blend
  • Blend is a big application:
      - 300 000 lines of XAML
      - 500 000 lines of C#

If you want more information about fixing error that we can have in Blend (while the application works properly at run time), you can check out this post of Jaime.

StyleCop + Resharper = StyleCop for Resharper addin

General 1 Comment »

If you’re a .Net developper then you MUST use ReSharper. I you don’t, I suggest you to have a look at this very nice video demonstrating some of the feature of this Visual Studio addin. If you also like having a clean C# code, then you might also use Microsoft StyleCop tool.

I just found this a very cool Resharper plugin that allows Microsoft StyleCop to be run as you type, generating real-time syntax highlighting of violations:

The StyleCop for Resharper plugin is hosted on CodePlex and is free. I think it’s a must have for any .Net developer. Its author really did a good work :-)

kick it on DotNetKicks.com

Microsoft StyleCop vs Agility

General No Comments »

When I write code, I try to keep it as clean as possible by following rules that I define and use in all my project. Those rules can be the ordering of elements within a class, or the way I choose name for my properties and methods…

Microsoft created a tool that analyzes C# source code in order to enforce a set of style and consistency rules : it’s StyleCop (available for free to download). StyleCop defines a lot of rules, for example:

  • Element must begin with an upper case letter
  • Field name must begin with a lower case letter
  • Prefix local calls with the “this” prefix

It is possible to enable or disable each rules separately, and this is what most users will do. Running StyleCop on one of your project can lead to thousands of warning. You can then choose which rules you want to keep enabled.

I started to use StyleCop the project I’m working on at job about one week ago. After disabling some of the rules I didn’t wanted to fix yet, I found a rules that was giving me a lot of warnings:

  • ALL elements must be documented

Hmm… This means that each single method or properties in my project must have a documentation… Well, if documentation is good lets start writing documentation everywhere. I though I will take a couple of classes per day, and write the entire documentation. I started with opening one of my class, and found this method:

?View Code CSHARP
1
2
3
4
5
public void OpenDocument(IDocument document)
{
// ...
 
}

StyleCop wasn’t happy because there wasn’t any documentation, so I wrote one:

?View Code CSHARP
1
2
3
4
5
6
7
8
/// <summary>
/// Open a document
/// </summary>
/// <param name="document">IDocument to open<param>
public void OpenDocument(IDocument document)
{
// ...
}

Then, I don’t know why but I asked myself “what the hell this documentation is going to help the user of the class ???”. Because one month earlier I went to the AgileTour (a french event about Agile methods), I remembered the Agile Manifesto:

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

I was thinking a couple of minutes, and then I decided to remove the StyleCop rules about documenting EVERYTHING in my code. I think that would be a waste of time and that would preventing me to put good comments where it’s really needed such explaning an algorithm or why I choose this way over this other way to do the job.

I’m still using StyleCop to have a set of rules about the style of my code. But for now, that’s it ! I think it is very important to make the differenciation between documentation and comments. If documentation is needed because it will generate a document outside the application then it might be usefull. But if the documentation is written just to have it, I prefer forget about it.

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