Dec
15
2011

Shortening namespace declarations in XAML files

Vue sur la tête de la femme couchée de la terrasse de la villa cannelleThis afternoon I was working on Innoveo Skye Editor which is a WPF application written in C#.

The application is using Telerik RadControls for WPF.

I was facing the issue of having more and more namespace declarations like the following for RadInput and Rad:

 

<Window x:Class="skyeEditor.View.Dialogs.ProductSettingsDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:RadInput="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Input"
        xmlns:Rad="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls"

Searching for a solution I thought of ASP.NET in which you can declare in the web.config things like that:

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="MyNamespace" />

My goal was to have one namespace declaration for example telerik and be able to use it in all my XAML files without having to declare too much.

So I started an online discussion with Laurent Bugnion who has always shown me the good direction, which in this case is the

XmlnsDefinitionAttribute Class

Followed by an article from Sandino Di Mattia about “A Guide to Cleaner XAML with Custom Namespaces and Prefixes (WPF/Silverlight)”.

Using the idea I was able to add the following to the AssemblyInfo.cs of my own project:

[assembly: XmlnsDefinition("telerik",
                           "Telerik.Windows.Controls",
                           AssemblyName = "Telerik.Windows.Controls")]

[assembly: XmlnsDefinition("telerik",
                           "Telerik.Windows.Controls",
                           AssemblyName = "Telerik.Windows.Controls.Input")]

[assembly: XmlnsDefinition("telerik",
                           "Telerik.Windows.Controls",
                           AssemblyName = "Telerik.Windows.Controls.Navigation")]

[assembly: XmlnsDefinition("telerik",
                           "Telerik.Windows.Controls",
                           AssemblyName = "Telerik.Windows.Controls.RibbonView")]

And then my XAML file declaration looks like that:

<Window x:Class="skyeEditor.View.Dialogs.ProductSettingsDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"

And I can use everywhere for all Telerik RadControls for WPF with the prefix telerik

<telerik:RadComboBox ItemsSource="{Binding ProductNodeLabels}"
                        SelectedItem="{Binding SelectedProductNodeLabel}"
                        Margin="0,0,0,5" />

A little step but a nice improvement!

Nov
12
2011

Fixing ReSharper inspection Results used from XAML

Rocher du diamant depuis la grande anse du diamantFinishing this week sprint I decided to inspect some code using ReSharper 6.1 EAP and I started to give ReSharper a chance to help me find some of broken code.

When I started I had some of the following inspection results. It is clearly showing that some properties wasn’t identified as used in a WPF binding.

So ReSharper proposed to make the property private which for sure was not ok for me has I knew it was used.

Some time ago I started to assign some design DataContext to be able to navigate from View to my ViewModel just by pressing Go to Declaration (CTRL-B in IDEA scheme) in ReSharper.

<UserControl x:Class="skyeEditor.View.StatusBarView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:ViewModel="clr-namespace:skyeEditor.ViewModel"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance Type=ViewModel:StatusBarViewModel}">

This for sure helps ReSharper code inspection as you can see on the following screenshot

Now I can navigate from View to ViewModel, can avoid to have developer deleting properties that are sued in XAML bindings, but I can also get an idea of where a ViewModel property is used by using ReSharper Find Usage (Alt-F7). I see right away that the StatusBarView.xaml is using the property ShowActivityProgress.

So don’t forget to add the d:DataContext into your XAML !

Jun
11
2010

From WPF functional Unit Tests to Specifications using MSpec and White

I am in the train back home and wanted to try out quickly to migrate our WPF functional tests written has Unit Tests to BDD Specifications.

Here is the code I started from, pure Unit Test using NUnit and White

[Test]
public void Opening_Valid_VersionZip()
{
    OpenAndWait("Product.zip");

    Assert.That(MainWindow.Title.Equals("Product.zip - Innoveo Skye® Editor"));
    Assert.That(Status.Text.Equals("product"));
    Assert.That(ProductTree.Nodes.Count >= 1);
    Assert.IsFalse(SplashScreen.Visible);
    Assert.IsTrue(SaveButton.Enabled);
    Assert.IsTrue(ActivateButton.Enabled);
}

Now the same functional test written as a BDD specification using MSpec

[Subject("OpenVersionZip")]
public class when_user_open_valid_versionzip : MainWindowViewSpecs
{
    Establish context = () => {};

    Because of = () => OpenAndWait("Product.zip");

    It should_display_mainwindow_title_correctly = () =>
        MainWindow.Title.ShouldEqual("Product.zip - Innoveo Skye® Editor");

    It should_display_status_correctly = () =>
        Status.Text.ShouldEqual("product");

    It should_display_the_product_tree = () =>
        ProductTree.Nodes.ShouldNotBeNull();

    It should_hide_the_splashscreen = () =>
        SplashScreen.Visible.ShouldBeFalse();

    It should_enable_save_button = () =>
        SaveButton.Enabled.ShouldBeTrue();

    It should_enable_activate_button = () =>
        ActivateButton.Enabled.ShouldBeTrue();
}

And the output in ReSharper MSpec plugin

4687909611_49a4e5a71a_o[1]

Which one do you prefer? I personally have made my choice.

Jan
28
2010

White’s tip for your automated WPF functional tests

When you build automated WPF functional test using White in which you need to open a file through a Windows open file dialog, you will be confronted with the following issue. Windows open file dialog remember the last path with which you opened a file.

So you might have some unit tests that are green for a while which starts to be red for no apparent reasons.

The solution I came to is as this.

First I use Visual Studio, Copy to Output Directory, to copy the needed file to the output directoy in which your software will be started by the unit tests, e.g. for notValidVersionZip.zip

4309956698_b62daf51f5_o[1]

So now I am sure that the needed file is in the same path than the application. I then also need to be sure that when the application start the Windows open file dialog it points to this path. In the past implementation I was just using a filename and was lucky enough the path used by the Windows open file dialog was the correct one.

To get to the correct path is easy. We just navigate to the correct path using the Windows open file dialog in an automated way. The correct path is the path in which the application as been started, so you can get it like that:

  1. /// <summary>
  2. /// Gets the current path.
  3. /// </summary>
  4. /// <returns></returns>
  5. private static string GetCurrentPath()
  6. {
  7.     return Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
  8. }

We have the correct path and we still need to automate the Windows open file dialog to navigate to that path. We can do this like that:

  1. protected void Open(string filename)
  2. {
  3.     OpenButton.Click();
  4.  
  5.     var openModalWindow =
  6.         MainWindow.ModalWindow("Please choose a Zip file", InitializeOption.NoCache);
  7.     Assert.IsNotNull(openModalWindow);
  8.  
  9.     var splittedPath = GetCurrentPath().Split(new[] { '\\' });
  10.  
  11.     foreach (var pathPart in splittedPath)
  12.     {
  13.         openModalWindow.Enter(pathPart);
  14.         openModalWindow.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RETURN);
  15.         openModalWindow.WaitWhileBusy();
  16.     }
  17.  
  18.     openModalWindow.Enter(filename);
  19.     openModalWindow.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RETURN);
  20. }

Basically we split the path into it different path parts that White will enter into the dialog followed by a enter. Don’t forget to use the method WaitWhileBusy() after each enter, otherwise it will be too fast and sometime your test will not go to the correct path and then will not find the file.

Finally White enter the filename followed by enter and the file is opened.

Nice!

If you are using like me ReSharper to run your unit tests don’t forget to set it up to run tests from Project output folder.4309993844_8d9e828f8c_o[1]

Jan
28
2010

Automated WPF functional tests using White

I’d like to introduce a tool that I have added for a month or two in my toolset. This tool is White from ThoughtWorks. Here is the description of White:

White: Automate windows applications

White supports all rich client applications, which are Win32, WinForm, WPF and SWT (java).
It is .NET based and hence you wouldn't have use proprietary scripting language. You can use your favourite .NET language, IDE and tools for developing tests/automation programs.
White provides consistent object oriented API for all kinds of applications. Also it hides all the complexity of Microsoft's UIAutomation library and windows messages (on which it is based).
(While WHITE is completely ready to be used, the documentation is still work under progress. Please do point out the areas which needs documentation.)

When I found White with it’s version 0.19, I was a bit skeptical about the state of this piece of software. But it is really ready to be used.

By the way the latest version 0.19 of White supports also Silverlight.

I had the need to automate some functional tests of a WPF application that I am working on. When such an application is growing it becomes more and more difficult to do functional tests manually, so it needs automation.

So what I was searching for was something that would let me write unit tests in C# with NUnit which automate a WPF application. It is not that I don’t want to learn another language but I needed to be efficient so I preferred to use something I knew. And what I have found is White.

I have tested it with the RadRibbonBar for WPF of Telerik and it works just great. btw Thanks to Telerik for the offered license, which my company Innoveo Solutions also ordered now.

If you are starting with automated functional testing I recommend you to read the Functional Testing. It explains step by step how to write automated functional tests with White. The basic can be also used with another tool.

It is funny to see you application running without you clicking around.

I still need to have this run by our build server, TeamCity. I have currently not done any investigation on that point. I plan to have those tests running at least nightly, but I have to see how the unit tests could be started on an environment with a desktop.

Oct
14
2009

MVVM Light Toolkit V2

At Innoveo Solutions we are using .NET and WPF for our Innoveo Skye® Editor application. Skye® Editor is a distribution channel editor targeting business people letting them edit and configure their insurance products.

From the beginning we have adopted the Model-View-ViewModel architecture. Having our solution growing we were facing the issue of having our ViewModels dependency growing too. Some ViewModel became too much dependent of others. This was obvious in our unit tests whose complexity to setup were growing too. It was time to find a solution to decouple the ViewModels.

The solution came out after a discussion with Laurent Bugnion, the famous author of MVVM Light Toolkit. At that time we used the V1 that already helped a lot in this decoupling.

Now with MVVM Light Toolkit V2 it is even better with the new Messenger API. What we also really appreciated in comparison to other frameworks is that it is really light and the ability to open and edit the user interface into Expression Blend.

So Thank you Laurent for this GREAT framework and I looking forward for V3!

I also would like to thank my managers at Innoveo Solutions who understand Open Source and the need to have people contributing to Open Source projects, even during their professional working time. A Win-Win situation and not just a one way benefit as often.

Apr
17
2009
Tools // WPF

Memory leak with WPF resources

I am working for a couple of months now with WPF and MVVM on an a business application using .NET Framework 3.5 SP1. Lately I faced a memory leak. Not the easy kind of memory leak with events handlers which keeps objects and its element tree alive, as explained here.

No it was something else ! I searched in our code for quite some time without finding anything.

My internet research brought me to a blog post from Ramon de Klein, “Memory leak with WPF resources (in rare cases)” which stated :

When does the problem occur?
The problem occurs in the following situation:

  1. A style is defined in the application’s ResourceDictionary.
  2. The style uses a control template that uses media effects (i.e. DropShadowEffect).
  3. The media effect should be referenced using a StaticResource.

We were matching the two first points and I tried the proposed fix:

You can force the effect to be frozen by specifying “PresentationOptions:Freeze=True”, but this is not common behavior.

The workaround is simple… Just add the Freeze attribute to all the effects that you don’t plan to modify at runtime.

But that didn’t made it.

I decided then to move the style definition from the application ResourceDictionary to the MainWindowView ResourceDictionary, which was for sure a better place for it. This to avoid the first point.

This worked! And we do not have this memory leak anymore. But as always when you fix one, some other popped up! But that’s another story.

How did I came to find the blog post from Ramon de Klein ?

With a perfect timing I got an offer from Red Gate to test their latest tool still in Early Access Program: ANTS Memory Profiler 5

You might watch a two parts video here (part1) and here (part2) and read about it here. You can even download a version from their forum, check it out.

First I used ANTS Memory Profiler 5 Timeline to see that the memory wasn’t released at certain points in which it should. The red line shows the Bytes in all Heaps and should go down after each vertical line (gray, blue and red)

Same result with Process Explorer, Memory usage going up without going down.

So we got on the screen the memory leak. Next step was to identify it.

Using Memory Profiler Class List, I browsed to the class that I new should be released, and proved it wasn’t: Live Instances is 3 and Instance Diff is +2. So at that time I knew that this class was maintained by something in memory.

Watching the Memory Profiler Instance list, I could identity the different instances still in Memory and one wasn’t new, so a good candidate to look at:

Finally switching to the Memory Profiler Object Retention Graph, I could navigate up the graph to see that DropShadowEffect was maintaining a reference:

Up to my application RessourceDictionnary, as exaplained in point 1 from Ramon de Klein blog post, as you can see.

All those information gave me the opportunity to find the blog post from Ramon and led me to the solution.

This is the result of the fix I implemented, as you can see I have now only one Live Instance of the ProductViewModel class and an Instance Diff of –1. This shows that the object wasn’t retained in memory and cleaned correctly.

 

ANTS Memory Profiler 5 and Ramon de KleinMemory leak with WPF resources (in rare cases)” blog post was of great help to fix this memory leak. Thanks!

Thanks flies also to Stephen Chambers for the support with my questions on ANTS Memory Profiler 5.

Finally I would like to warmly THANKS Laurent Bugnion for his kind chats that helped a lot, as always!

Apr
17
2009
WPF

Attending the &quot;WPF FOR LOB&quot; TRAINING TOUR in London

Next month I will attend with my colleague Robert the “WPF FOR LOB” training Tour in London (5/15 -5/16). Our flights and hotel rooms are already booked. We fly from Zurich to London Heathrow on Thursday 14 Mai arriving at 20:15 in London and I fly back to Mulhouse on Saturday evening.

We will be at the conference hotel Radisson Edwardian Heathrow Hotel, where the training take place.

Jaime Rodriquez and Karl Shifflett have been organizing a “WPF FOR LOB” to provide 2 days of free WPF training for developers.

Overview
This two day training is designed to teach developers how to create Line of Business (LOB) applications using Windows Presentation Foundation (WPF). 

  • Day One is an introduction to the WPF graphics subsystem, the tools used to build WPF applications, and the core UI services: styling, data binding, templating, layout and input-
  • The second day begins with interop (Windows Forms and Win32)  and then quickly dives into LOB topics, including building applications using the Model-View-ViewModel pattern, creating unit testable applications,  implementing data validation, and error handling. 

After completion, attendees will have a solid understanding of WPF, its advantages over other Microsoft UI platforms, and how to use the M-V-VM pattern to create great WPF LOB applications.

Detailed Agenda

  • Day One:
    • Lap Around WPF
    • WPF Tools ( Blend, Visual Studio 2008)
    • Graphics Subsystem
    • Layout
    • WPF Fundamentals and new concepts
      • Application Model
      • Dependency Properties
      • Trees (logical & visual)
      • Events
      • Threading
      • Resources
    • Controls
    • Styling
    • Templating
    • Q&A with instructors at end of day
  • Day Two:
    • WPF integration with Win32 and Windows Forms
    • Data binding
    • Introduction to Model-View-ViewModel
    • Commanding in M-V-VM
    • Views, Navigation and Transitions
    • Data Validation
    • Error handling, Model dialogs, Logging
    • Unit Testing
    • MVVM & LOB tips and tricks
    • Q&A with the instructors

Read more here.

And the best of all is that it is absolutely Free.

Apr
19
2007
WPF

Mitsu's blog : WPF Book control

Mitsuru Futura one of the author on my website Tech Head Brothers just released an awesome demo of what you can achieve with WPF; the WPF Book Control.

And as he is a kind guy he provides also the source code.

More to come... ;-)

Link to Mitsu's blog : WPF Book control

About Laurent

Laurent Kempé

Laurent Kempé is the editor, founder, and primary contributor of Tech Head Brothers, a French portal about Microsoft .NET technologies.

He is currently employed by Innoveo Solutions since 10/2007 as a Senior Solution Architect, certified Scrum Master and Founding Member.

Founder, owner and Managing Partner of Jobping, which provides a unique and efficient platform for connecting Microsoft skilled job seekers with employers using Microsoft technologies.

Laurent was awarded Most Valuable Professional (MVP) by Microsoft from April 2002 to April 2012.

JetBrains Academy Member
Certified ScrumMaster
My status

Twitter

Flickr

www.flickr.com
This is a Flickr badge showing public photos and videos from Laurent Kempé. Make your own badge here.

Month List

Page List