XBAPs Part 2: Consuming WCF services from an XBAP

Introduction

One of the big improvements to XBAPs in .NET 3.5 is the ability to consume WCF services. Nowadays Service Oriented Architectures (SOAs) are very popular and used almost everywhere. This all makes sense, as SOA is very scalable, and for many cases it is the best approach to take for a project; so why not enable SOA for XBAPs as well. To tell you the truth, you could consume WCF services from XBAP in .NET 3.0, yet the XBAP had to have Full Trust, and not Partial Trust, which usually spells trouble. Anyway we don’t have to worry much about this now because .NET 3.5 enables XBAPs to consume WCF services even in Partial Trust. Read more about this and it’s limitations here.

Setting up our workspace

Ok so let’s start by creating a simple WCF service. Open Visual Studio and create a WCF service by clicking File > New > Project and then select Web > WCF Service application

NewWCF

I am not going to cover the basics of how to create a WCF service, yet by default the WCF Service Visual Studio template creates a simple service for us already (called IService). So yes, if you hit F5 and run the service you will already have a service up and running. Once we have our simple service let’s create a Simple XBAP in the same solution (in order to do this please refer to my previous post).

Now that we have both the WCF service and the XBAP how are we going to make them communicate? Well, thanks to Visual Studio this is super simple. All you have to do is Right click the XBAP project, select the “Add Service Reference” option and a Dialog will pop up:

AddServiceReference

Please Note: If you do not run the service you will get an error while expanding the Tree nodes of the service in this Dialog. If the service is not running Visual Studio cannot get the Metadata of the service, since this is just another EndPoint of the service. In order to run the service just Right Click on Service1.svc and select View in Browser.

Ok, now that we added the Service Reference, Visual Studio will go to work and generate a Proxy class for us. We will use this proxy class to communicate with the WCF service. By default the Proxy class is called <Name of service>Client so in our case it will be called Service1Client. This proxy class will have a method for every OperationContract we have in our service. You can also choose to create an Async version of the service. In order to do so just right click the Service1 (in the XBAP project that got created when we added the Service Reference) and select Configure Service Reference.

ChangeTheServiceToHaveASYNC

In this dialog check the Generate Async operations checkbox and Visual Studio will add an async version of the OperationContracts for you (Thank you VS… we love you :) )

The first error you’ll see

Ok now that we have everything set up lets do a simple button in our XBAP and in the Click event handler call a method. Something like this….

   1: private void Button_Click(object sender, RoutedEventArgs e)
   2: {
   3:     Service1Client client = new Service1Client();
   4:     MessageBox.Show(client.GetData(1));
   5: }

Let’s hit F5 and run our XBAP and see what happens.

AND BAMMMM a big ugly exception is thown.

InvalidOperationException

The WSHttpBinding with name WSHttpBinding failed validation because it contains a BindingElement with type System.ServiceModel.Channels.SymmetricSecurityBindingElement which is not supported in partial trust

which in VS looks like this

WCFError

Yet I promised you guys that WCF is supported in Partial trust XBAPs…. And it is, it’s just that the default WCF EndPoint is not :) By default a WCF Service has it’s EndPoint set up as WsHTTPBinding which is not supported in Partial trust XBAPs. In order to fix this Right click the app.config of your service and select “Edit WCF Configuration” (if this option is not available go to Tools > WCF Service Configuration Editor then select open and specify the path of your App.config. Once you have the app.config opened in the editor Expand the Bindings Node and select the node under that. Open the Security tab and choose None as security level.

ChangeSecurityLevelOfBinding

Once that’s done run the app again.

The Second error you’ll see

And this time it’s a SecurityException saying

Request for the permission of type ‘System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.

SecondError

In order to fix this Go to the XBAP project Properties and select Debug tab. Select the Start External Program option and enter the following exe path “C:\WINDOWS\System32\PresentationHost.exe” and in the Command Line arguments text field enter the following

-debug <Path of XBAP> –debugSecurityZoneUrl <URL of service>

in my case it was

-debug “D:\net resources\My Blog\XBAPAndWCF\XBAPClient\bin\Debug\XBAPClient.xbap” -debugSecurityZoneUrl http://localhost:53265/Service1.svc

[Update]

Thanks to Mark Smith I discovered a new an easier way of doing this. All you have to do is

1) Open XBAP project properties

2) Select Security tab

3) Advanced button

4) Check “Grant application access to site of origin” (should be checked already)

5) Type in the URL into the textbox where the web service is running

Security

We have to do this so that we set up an envirorment for the XBAP just like it is running from the same URL of the service.

Conclusion

And there you have it. Now you should be armed and ready to start doing XBAPs that consume WCF service.

Download sample application

My wish came true…. I can now use DataBinding in a ConverterParameter

WARNING: This solution uses reflection so it cannot be used in XBAP or applications running with Partial Trust.

One of the things I hear often in forums and also lately on the WPF Disciples mailing list is, “How come I cannot use binding in ConverterParameters?” or “My personal pet peeve is the ConverterParameter. Ah if I could only bind it to something in my ViewModel!!”

So let’s start by seeing why you cannot use binding for a ConverterParameter. The simple answer to that would be, a ConverterParameter is not a DependencyProperty thus you cannot use Binding. Yet the following question would be, WHY isn’t it a DependencyProperty?? Well there are a few things we must have a look at here. First of all the Binding class is not a DependencyObject. Secondly the BindingBase class seals itself when the binding activates, this means that once the Binding is activated you cannot change any properties. If you try to do so you get a nice InvalidOperationException saying “Binding cannot be changed after it has been used”.

Yet, the WPF platform is very flexible so I decided to start digging into it and see what I can come up with (obviously always consulting the WPF KING OF KINGS, Dr.WPF).

The first idea…

My first idea was to create a MarkupExtension that spits out an instance of an object that has a Dependency Property that you can bind with (some sort of Proxy that can update the Binding and specify a new value). So your XAML would look like this

{Binding ElementName=checkbox1, Path=IsChecked, Converter={StaticResource conv}, ConverterParameter={code:BindableParameter {Binding ElementName=checkbox2, Path=IsChecked}} }

Yet this failed miserably because of a simple yet hard problem in the design I had. You cannot get the BindingExpression of that binding because the BindingExpression is not constructed yet. I could get the Binding instance but the Binding instance alone is nothing without the BindingExpression since you can update a binding by calling the UpdateSource method of the Binding expression.

Back to the drawing boards…. and finally the Solution

So let’s have a look at what we want to achieve. We want to

1. Let the User Specify a Binding for a ConverterParameter somewhere in the XAML
2. Make sure that when a value of the ConverterParameter changes the original Binding gets updated.

In order to solve problem 1, I decided to go to my best friend, AttachedProperties. Basically the idea is that you set an attached property that specifies the value of a ConverterParameter of a specific binding. So the XAML would look something like this

   1: <ToggleButton Content="I am bound to the checkbox" x:Name="toggle"
   2:      code:BindableParameter.BindParameter="{code:BindableParameter ToggleButton.IsChecked, Binding={Binding ElementName=checkbox2, Path=IsChecked}}"
   3:      IsChecked="{Binding Converter={StaticResource conv}, ElementName=checkbox1, Path=IsChecked}"/>

In the attached property you specify what Binding you want to target by supplying the DependencyProperty to which the original Binding is applied. In this case the original Binding is for the IsChecked property of the ToggleButton. Then you can simple specify the Binding you want for the ConverterParameter by setting the Binding property of the BindableParameter markup extension.

Now that you have supplied this information, the BindableParameter can do some tricks for you. Basically once you specify the BindParameter attached property the BindableParameter will get a BindingExpression for the original binding and make sure to set the ConverterParameter when ever needed. Have a look at the PropertyChanged event handler of the BindParameter Attached property.

   1: private static void OnBindParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   2: {
   3:     FrameworkElement element = d as FrameworkElement;
   4:     if (element == null)
   5:         throw new InvalidOperationException("BindableParameter can be applied to a FrameworkElement only");
   6:
   7:     BindableParameter parameter = (BindableParameter)e.NewValue;
   8:     element.Initialized += delegate
   9:     {
  10:         parameter.TargetExpression = BindingOperations.GetBindingExpression(element, parameter.TargetProperty);
  11:         parameter.TargetBinding = BindingOperations.GetBinding(element, parameter.TargetProperty);
  12:
  13:         //update the converter parameter 
  14:         InvalidateBinding(parameter);
  15:     };
  16: }

As you can see, in the above code, all we are doing is get the instance of the BindingExpression and storing it in an instance variable(TargetExpression). Same goes for the Binding, storing it in the TargetBinding. Now that we have all this information we can do Step 2 (Make sure that when a value of the ConverterParameter changes the original Binding gets updated)

In the Property Changed event handler of the Binding we must force the BindingExpression to update and change the value of the converter parameter. This can be done quite easily one would say but there are 2 main problems.

Problem 1. How to make the binding work for the BindableParamater?? The BindableParameter is not in the LogicalTree because it is just a DependencyObject thus the Binding that you set will not be valid. In order to overcome this issue we can do a little trick with the Freezable class. If we make the BindableParameter inherit from the Freezable it gets the inheritance context thus Binding is now valid. For more info on this technique visit Dr. WPF blog

Problem 2. How can we change the value of ConverterParameter if the Binding is sealed (remember? the Binding class will throw an InvalidOperationException if we try to change a property of the Binding). This problem required me to do some hard core disassembling of the Binding class and I found out that each Property Setter of the Binding class has a call to a method CheckSealed. This method looks like this

   1: internal void CheckSealed()
   2: {
   3:     if (this._isSealed)
   4:     {
   5:         throw new InvalidOperationException(SR.Get("ChangeSealedBinding"));
   6:     }
   7: }
   8:

So what we must do is to get the _isSealed Field info by reflection and change it’s value to false, then change the ConverterParameter and finally put the _isSealed value back to true so that WPF does not notice us playing tricks on him :)
Once we do that we are free to change the value of the ConverterParameter and we can Refresh the Binding

Something like this

   1: private static void InvalidateBinding(BindableParameter param)
   2: {
   3:     if (param.TargetBinding != null && param.TargetExpression != null)
   4:     {
   5:         //this is a hack to trick the WPF platform in thining that the binding is not sealed yet and then change the value of the converter parameter
   6:         bool isSealed = (bool)isSealedFieldInfo.GetValue(param.TargetBinding);
   7:
   8:         if (isSealed)//change the is sealed value
   9:             isSealedFieldInfo.SetValue(param.TargetBinding, false);
  10:
  11:         param.TargetBinding.ConverterParameter = param.ConverterParameterValue;
  12:
  13:         if (isSealed)//put the is sealed value back as it was...
  14:             isSealedFieldInfo.SetValue(param.TargetBinding, true);
  15:
  16:         //force an update to the binding
  17:         param.TargetExpression.UpdateTarget();
  18:     }
  19: }

And there it is …. I can now use binding for a ConverterParameter and the XAML looks like this

   1: <Window.Resources>
   2:    <code:DummyConverter x:Key="conv"/>
   3: </Window.Resources>
   4: <StackPanel>
   5:    <CheckBox x:Name="checkbox2" Content="I am the parameter for the converter"/>
   6:    <CheckBox x:Name="checkbox1" Content="I am bound directly"/>
   7:
   8:    <ToggleButton Content="I am bound to the checkbox" x:Name="toggle"
   9:                  code:BindableParameter.BindParameter="{code:BindableParameter ToggleButton.IsChecked, Binding={Binding ElementName=checkbox2, Path=IsChecked}}"
  10:                  IsChecked="{Binding Converter={StaticResource conv}, ElementName=checkbox1, Path=IsChecked}"/>
  11: </StackPanel>

Hope you enjoy this …..

DOWNLOAD SOURCE CODE

kick it on DotNetKicks.com

NameScope, my name is Marlon you know….

Introduction

Did you ever wonder why you can have the same name registered for different parts of your XAML? Here is an example (notice the name “border” in different parts of the XAML)

   1: <ContentControl Content="Hello world" x:Name="border">
   2:     <ContentControl.ContentTemplate>
   3:         <DataTemplate>
   4:             <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
   5:                 <StackPanel>
   6:                     <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
   7:                     <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
   8:                 </StackPanel>
   9:             </Border>
  10:         </DataTemplate>
  11:     </ContentControl.ContentTemplate>
  12:
  13:     <ContentControl.Template>
  14:         <ControlTemplate TargetType="ContentControl">
  15:             <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" x:Name="border" >
  16:                 <StackPanel>
  17:                     <TextBlock Text="I am a ControlTemplate" HorizontalAlignment="Center"/>
  18:                     <ContentPresenter />
  19:                 </StackPanel>
  20:             </Border>
  21:         </ControlTemplate>
  22:     </ContentControl.Template>
  23: </ContentControl>

As you can see the XAML above border is registered 3 times. This is possible because of WPF Namescopes. Basically the Window(that I am using to put the ContentControl in) has it’s own NameScope the DataTemplate also has it’s own and also the ControlTemplate (some actually implement the INameScope interface themselves).

Namescopes are a very important concept that one must understand. Why? Let me give you an example.

   1: <StackPanel>
   2:     <ContentControl Content="Hello world" x:Name="border">
   3:         <ContentControl.ContentTemplate>
   4:             <DataTemplate>
   5:                 <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
   6:                     <StackPanel>
   7:                         <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
   8:                     <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
   9:                     <CheckBox x:Name="checkbox" Content="Checkbox here" />
  10:                 </StackPanel>
  11:                 </Border>
  12:             </DataTemplate>
  13:         </ContentControl.ContentTemplate>
  14:     </ContentControl>
  15:
  16:     <ToggleButton Content="Toggle button bound to checkbox" IsChecked="{Binding ElementName=checkbox, Path=IsChecked}"/>
  17: </StackPanel>

The XAML above has a ContentControl that has a ContentTemplate with a CheckBox and a Toggle button that is trying to bind to that checkbox. The binding is using ElementName to try to find the checkbox yet that will NOT be successful because the “checkbox” is registered in a different NameScope (remember a DataTemplate has it’s own NameScope!)

Namescope and Animations

Another scenario where NameScopes are heavily used are animation. When you create a Storyboard you specify a Storyboard.TargetName attached property to specify which element you want to animate. Something like this….

   1: <Window.Resources>
   2:     <Storyboard x:Key="animation" >
   3:         <DoubleAnimation To="50" AutoReverse="True" RepeatBehavior="Forever"
   4:                        Storyboard.TargetName="button"  Storyboard.TargetProperty="Height"/>
   5:     </Storyboard>
   6: </Window.Resources>
   7:
   8: <Window.Triggers>
   9:     <EventTrigger RoutedEvent="FrameworkElement.Loaded">
  10:         <BeginStoryboard Storyboard="{StaticResource animation}"/>
  11:     </EventTrigger>
  12: </Window.Triggers>
  13:
  14: <StackPanel>
  15:     <ContentControl Content="Hello world" x:Name="border">
  16:         <ContentControl.ContentTemplate>
  17:             <DataTemplate>
  18:                 <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
  19:                     <StackPanel>
  20:                         <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
  21:                     <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  22:                     <CheckBox x:Name="checkbox" Content="Checkbox here" />
  23:                 </StackPanel>
  24:                 </Border>
  25:             </DataTemplate>
  26:         </ContentControl.ContentTemplate>
  27:     </ContentControl>
  28:
  29:     <ToggleButton Content="Toggle button bound to checkbox" Height="25" x:Name="button"/>
  30: </StackPanel>

The above code would execute as expected, the ToggleButton named “button” would start animating it’s height when the window is Loaded. But what if you want to animate something in the DataTemplate? If you try to create a Storyboard in the Resources section of the window to animate the Checkbox  named “checkbox” you would get an InvalidOperationException saying ‘checkbox’ name cannot be found in the name scope of ‘NamescopeExample.Window1′. This is because the checkbox lives in a different NameScope from the storyboard. One thing you can do is to move the Storyboard in the DataTemplate.Resources so that the storyboard would be created in the same Namescope of the checkbox. Something like this

   1: <DataTemplate>
   2:     <DataTemplate.Resources>
   3:         <Storyboard x:Key="checkboxAnimation" RepeatBehavior="Forever">
   4:             <ColorAnimation To="Red" AutoReverse="True"
   5:                 Storyboard.TargetName="checkbox" Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"/>
   6:         </Storyboard>
   7:     </DataTemplate.Resources>
   8:     <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="5" Margin="20" x:Name="border">
   9:         <StackPanel>
  10:             <TextBlock Text="I am a DataTemplate" HorizontalAlignment="Center"/>
  11:         <ContentPresenter Content="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  12:         <CheckBox x:Name="checkbox" Content="Checkbox here" Background="Black" />
  13:     </StackPanel>
  14:     </Border>
  15:     <DataTemplate.Triggers>
  16:         <EventTrigger RoutedEvent="FrameworkElement.Loaded">
  17:             <BeginStoryboard Storyboard="{StaticResource checkboxAnimation}"/>
  18:         </EventTrigger>
  19:     </DataTemplate.Triggers>
  20: </DataTemplate>

Namescope and C# code

But what if you are creating elements in code… One would say out “Easy… Just set the name property” like so….

   1: ToggleButton button = new ToggleButton();
   2: button.Height = 25;
   3: button.Content = "Toggle Button";
   4: button.Name = "button";
   5: container.Children.Add(button);

No no no and NO…. This does not work! Setting the Name property of the control will not register that Control to the NameScope. So how to do it? Easy.. have a look

   1: ToggleButton button = new ToggleButton();
   2: button.Height = 25;
   3: button.Content = "Toggle Button";
   4: NameScope.GetNameScope(this).RegisterName("button", button);
   5: container.Children.Add(button);

All you have to do is, first find in which NameScope you want to register the element (in this case I want to add it to the Window NameScope), secondly register the element to that NameScope by using the RegisterName method of the INameScope interface.

You can even use the RegisterName method of the FrameworkElement. For example if I want to add a Button to a StackPanel, you can ask the StackPanel to register the name of the Button. In my case I could have done like this

   1: ToggleButton button = new ToggleButton();
   2: button.Height = 25;
   3: button.Content = "Toggle Button";
   4: container.RegisterName("button", button);
   5: container.Children.Add(button);

Some other tips and related articles…

If you have an element in the Resources section you will not be allowed to set a name for that element. One way of enabling that element with a name is by using the RegisterName method of the NameScope class as explained above (you might want to set the name for animations for example).

You might want to also implement your own NameScope by implementing the INameScope interface. I saw a very clever solution by doing such a thing, by WPF super hero Andrew Smith.

Josh Smith the WPF Rock star and his Element Spy is also a brilliant article that must be read..

kick it on DotNetKicks.com

AvalonControlsLibrary DatePicker refactored

Recently I received some requests from people to support some more styling for the DatePicker control. The initial idea for the DatePicker was to create a “lookless” control and then users would create a ControlTemplate to change the look and feel of the control (which is still 100% possible, see here for more info). Yet sometimes users do not want to totally change the look of the control, sometimes it’s more a matter of changing colors and minor things like that. So I decided to make the DatePicker support some more styling so that users don’t need to create a new ControlTemplate for the DatePicker if they only need to change minor things in the DatePicker UI.

As you can see in the image above I added 5 new properties for styling the control. All of these properties are optional and if they are not set, a default value will be set for you.

DayCellTemplate

This property accepts a DataTemplate where the user can specify how each Day cell should look. The DataTemplate is fed with a DayCell object as DataContext. The DayCell class has the following properties which you can use in the DataTemplate

Property Name Type Description
DayNumber int Represents the Day number
MonthNumber int Represents the Month number
YearNumber int Represents the Year number
IsEnabled bool Flag that indicates if the item falls out of the MinDate and MaxDate range
IsInCurrentMonth bool Flag that indicates if the item is in the current selected month

Here is a sample DataTemplate for the DayCellTemplate.

<DataTemplate>
    <Border Name="border">
        <TextBlock Text="{Binding DayNumber}" Name="dayCell"/>
    </Border>
    <DataTemplate.Triggers>
        <!--This trigger is to do some thing with the template when an item is selected-->
        <DataTrigger Binding="{Binding RelativeSource={
                                RelativeSource AncestorType={x:Type ListBoxItem}},
                                Path=IsSelected}"
                     Value="True">
            <Setter Property="Background" Value="Blue" TargetName="border"/>
        </DataTrigger>
        <!--This is for those dates that fall out of the MinDate and MaxDate.-->
        <DataTrigger Binding="{Binding IsEnabled}" Value="False">
            <Setter Property="Background" Value="Gray" TargetName="border"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding IsInCurrentMonth}" Value="False">
            <Setter Property="Foreground" Value="Gray" TargetName="dayCell"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

So basically the DayCellTemplate will give you a lot of flexibility in terms of what you can do with the UI of the DatePicker because you can make the Day cell look however you want without the need of re building the whole UI for the control.

DayHeaderTemplate

The DayHeaderTemplate is again another DataTemplate, this time it will be a DataTemplate for the Header Day cell which basically is the Text -> Sun, Mon, Tue etc.. The DataTemplate that you set as being the DayHeaderTemplate will be passed a string object as DataContext that contains the Text for the Header (ex. Mon, Tue etc..) Here is an example of a DataTemplate that can be applied for the DayHeaderTemplate property.

<DataTemplate>
    <Border Background="Yellow">
        <TextBlock Foreground="Lime" Text="{Binding}"/>
    </Border>
</DataTemplate>

MonthBackButtonStyle/MonthForwardButtonStyle

These two properties are the styles for the back and forward month navigation buttons of the DatePicker. Basically you can apply a style for the Back and Forward button in any way you like. So you may decide even to create a ControlTemplate for these two buttons which would be quite easy. Something like this….

<Style TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border BorderBrush="Pink" Width="20" BorderThickness="2">
                    <TextBlock Text="<" FontWeight="Bold"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

MonthSelectorStyle

Last but not least is the MonthSelectorStyle property. This property enables you to set a style for the Months drop down list aka ComboBox. Since here we are setting a scyle for a ComboBox a user has full control over that combobox. One can decide to do a ControlTemplate for the ComboBox or maybe just set an ItemTemplate for the elements inside it… Here is a style that I used in the demo app of the DatePicker…

<Style TargetType="ComboBox">
    <Setter Property="Background" Value="Yellow"/>
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="ComboBoxItem">
                <Setter Property="Background" Value="Yellow"/>
            </Style>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Foreground="Red" Text="{Binding}"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Conclusion

I think that with the introduction of these properties the DatePicker control will be much more easy to use and re style. Again I would suggest that if you need to totally re arrange the look of this control the best way would be to use a ControlTemplate and change the whole look of the control, yet if all you need is to change some colors and other minor things, these new properties will help you out in the process.

The new version of the DatePicker will be available in the AvalonControlsLibrary v3, yet I know you can’t wait until you get your hands on this so I created a demo app for you :D

I am open to suggestions as usual! Please let me know if there is something missing or something that you would like to have in YOUR AvalonControlsLibarary DatePicker :)

And as my friend Sacha Barber says – “It’s all good!” :D

Download Demo Project

kick it on DotNetKicks.com

Creating a File Explorer in WPF using MVC+M

Introduction

In my previous article I explained how one can use the Mediator Pattern together with the MVC Pattern to structure the code in a very neat way. If you did not read my previous article I would suggest that you do, since I am basing this post on the assumption that readers already read that post.

I am writing this post because some friends from WPF Disciple suggested that I use a better example for the MVC+M. I agree 100% with them since the example that I did in my previous post was not the best one I could pick up…

Today I’ve got a new problem that I want to solve using the MVC+M. As the title of the post suggest, we are going to build a File Explorer and hopefully it will look something like this.

Yea, that’s where AvalonControlsLibrary and all other projects of mine live :D

This application is very simple to explain because I would assume that everyone reading this post has used a File Explorer. Basically we have a TreeView that shows the directories and when a directory is selected the list of files in that directory show up on screen.

The Problem

The problem is that we do not have a fixed list of objects. The list is generated on the fly. If we had to load all directories in memory we would have a big performance hit + I don’t want to imagine the memory consumption. So for the TreeView I used the Flyweight Design Pattern. I will not go into details of this pattern since it is not the purpose of this post, but to summarize, each node loads a dummy child so that the user can expand the items. Once an item is expanded the TreeView controller loads the child directories of the directory being expanded.

You’ll say “OK… But what does this have to do with the Mediator?”. The Mediator comes in handy for our second problem. When an item is Selected the list of files show up in the file list (on the right hand side of our application).

So the problem here is, we have a Dynamic Hierarchal List + we have a Treeview (which does not have an IsSynchronizedWithCurrentItem property that can make the underlying ICollectionView notify us with the currently selected item). Speaking of which we now don’t even have one ICollectionView, instead we have one for each level.

How can we tell the File List Controller that an item is selected without coupling it with the Tree View Controller?

The Solution (or at least, how I would do this…)

In such a case the Mediator is key, because the mediator will make the communication between the 2 controller very easy and loosely coupled. Let me first introduce the entities we have here

Views

- DirectorySelectorView

- FileSelectorView

Controllers

- DirectorySelectorController (mentioned above as TreeView contoller)

- FileSelectorController (mentioned above as File List Controller)

Model

- FileSystemDataService

OK so lets’ do this… And guess what we are going to do this in 3 steps once again.

Step 1 – Publish the Directory Selected message via the Mediator
Step 2 – Register the FileSelectorController to receive a notification for the Directory Selected message.
Step 3 – Handle the Directory Selected message in the FileSelectorController and get the files to display.

Lets now talk in C#. The following is the code to do the above mentioned 3 steps.

Step 1

//event handler for the selecting changed
void ItemSelected(object sender, RoutedEventArgs e)
{
    TreeView treeView = (TreeView)e.OriginalSource;
    //Send a message that an item is selected and pass the object selected
    Mediator.NotifyColleagues(
        Messages.DirectorySelectedChanged, treeView.SelectedItem);
}

Step 2

public FileSelectorController()
{
    Mediator.Register(this, new[]
    {
        Messages.DirectorySelectedChanged
    });
}

Step 3

public override void MessageNotification(string message, object args)
{
    switch (message)
    {
        case Messages.DirectorySelectedChanged:
            //load all files for the directory specified
            LoadFiles((DirectoryDisplayItem)args);
            break;
    }
}

That’s all folks …. Download the full source code to see all the rest…

Some Side notes to keep in mind

Developers are like artists. Everyone has his own style. For example, right now the Mediator implementation that I did, is using an interface driven design where you have an interface IColleague and the mediator notifies the colleagues passing the message that is being sent. One can implement a Mediator that uses strongly typed delegate so that you can avoid doing the switch statement (in the MessageNotification method) and implementing the IColleague interface for each controller. So the implementation of such a Mediator would look like this

Register( IDictionary<string, Action> callbacks);

The Colleague that want to register simple do the following

Register( new Dictionary<string, Action>
{
     { Messages.SelectionChanged, delegate(object obj){ //DoSomething here  } }
}

This would totally eliminate the switch statement and the ICollegue interface…

One thing that I have been discussing with some friend from WPF Disciples is, What about big systems? Would big systems have to define loads of Messages?

The answer (at least how I see it from previous experiences working with this pattern) is NO. Why? Because the messages would be only for the controllers part. The other parts of the system would not need such a thing because if the controllers can talk together, the other entities would not need to. If we take the example of the File Explorer, the Views do not need to communicate because the controllers are synchronizing with each other. The views are just reading the data from the controllers. The model does not need this system either because the model will just give data that is being requested from the controller. So, please do not misinterpret this and use this system all around because you would create a MONSTER!

Josh Smith, also pointed out a very good point. What about memory leaks? If controllers do not unregister from the mediator once that the contoller is disposed than the controller would still exist in memory. This is a fact! I did not implement an unregister in the mediator because till now I only had controllers that do not get disposed throughout the application life cycle. Yet to implement an unregister would be just a piece of cake. All you have to do is to ask the mediator to remove the reference to a specific controller when the contoller is being disposed.

Besides the Mediator, there are loads of other ways of doing this, yet I decided to stick to this one because currently I feel that this pattern is given me the flexibility I need.

Conclusion

I like how this works because I feel that I can have a loosely coupled and high cohesion code base.

Loosely coupled, because the controllers know nothing about each other and I can just disable or reuse one of them at any point in time.
High cohesion, because knowing that I can make controllers communicate in an easy way, I create controllers that have one responsibility.

Credits

Thanks to all WPF Disciples for the brilliant discussion
My friend Karl Agius for even some more discussions

Download the full source code of the Demo application.

kick it on DotNetKicks.com

More than Just MVC for WPF

Introduction

First of all I am assuming that the readers already know how to use the MVC design pattern for WPF (or at least read about it and understand the concept). If not I would suggest that you read this brilliant post by Josh Smith. I am writing this article because recently I found a problem when using the MVC in WPF and I think I found a neat solution. Well I said that “I” found the solution, that is not true. The pattern that I am going to talk about is called the Mediator Pattern and I found it in the Gang of Four book that I was reading recently. I decided to mix the 2 patterns together and the result was beautiful code.

Warning: This article is a bit long. Readers can fall fast asleep :D

Problem Definition

The way I see it, Views must be as small as possible and handle only one specific job. Let’s do a practical example. Let’s say we have an application that displays a list of products. The application also lets you click on a specific product and the details of that product would show on the side. A search feature is also provided in this application. So our application would look something like this (I coloured the different sections of the app to make them more obvious)

Let me introduce the Entities that we have here

Controllers (These are simple class nothing more)

- ProductListController

- ProductDetailsController

- SearchController

Views (These are all User Controls)

- ProductListView

- ProductDetailsView

- SearchView

All views create an instance of the related Controller and set the Controller instance as the DataContext. By doing this the View can data bind to the properties of the Controller and also the Controller can handle routed command and routed events from the View since the Controller is now in the WPF logical tree. In this way the View has 0 lines(excluding the InitializeComponents) of code in the code behind file and all logic is inside the Controller class. By doing this you can easily Unit Test the logic and also Designers can use tools such as Expression Blend without having any problem because the logic is handled in the controller class and not in the view itself. Just like MVC in Web so to speak. Imagine commands in WPF as being the Routed URL for the controller to handle.

One may say “Wow, that’s a lot of classes” but hey if you want to be flexible, scalable and have code reusability that is the way to go. If not, then go ahead and put everything in one class but the result will be strongly coupled entities that are not reusable. Sometimes this is perfectly acceptable and so YES go ahead and do that. But let’s say you need to do a Search feature in another page. With MVC you can just re-use the search view and search controller in the other page.

In the MVC for WPF (or better in one of the implementations), there is a strong use of Routed Commands (sometimes one may use also Routed Events, well at the end of the day a RoutedCommand is just a Routed Event + the Command Pattern nothing more). The problem with Routing Commands is that the communication is always done from child to parent in the logical tree. In the application above there is a need of something different. Basically the Controllers need a way how to communicate. Yet we do not want that the Controllers know about each other because if that was so why not create 1 View and 1 Controller. We must ensure that no coupling is made between the controllers.

In the sample application above the ProductListController is handling the SelectionChanged event of the ProductListView. ProductListController needs to communicate this to the ProductDetailsController so that it updates the data that is currently being shown in the ProductDetailsView.

The question is how can you achieve this?

The Mediator Pattern to the rescue

The Mediator pattern can be described as a ChatRoom. In a Chat room there are Colleagues (the persons in the Chat Room) and via the Mediator (the chat room itself) they exchange messages. The same can be applied for our Controllers. There would be 1 Mediator and all Controllers communicate to each other via the Mediator. In simple english the Colleagues would be the Controllers.

The following is the Class Diagram for the application I mentioned above

The interface for the Mediator would look something like this

The signature of the methods would look like this

/// <summary>
/// Registers a Colleague to a specific message
/// </summary>
/// <param name="colleague">The colleague to register</param>
/// <param name="messages">The message to register to</param>
void Register(IColleague colleague, IEnumerable<string> messages);

/// <summary>
/// Notify all colleagues that are registered to the specific message
/// </summary>
/// <param name="message">The message for the notify by</param>
/// <param name="args">The arguments for the message</param>
void NotifyColleagues(string message, object args);

The IColleague interface is an interface that all Controllers implement and looks like this

The Signature for the MessageNotification would look like this

/// <summary>
/// Notification from the Mediator
/// </summary>
/// <param name="message">The message type</param>
/// <param name="args">Arguments for the message</param>
void MessageNotification(string message, object args);

Aha…. but Marlon how does this solve the Problem ??!!??

With the Mediator pattern Controllers can send messages to each other without knowing of each other. Let’s do an example to try and make this more clear. Lets use the problem that I described above.

ProductListController is handling the SelectionChanged event of the ProductListView. ProductListController needs to communicate this to the ProductDetailsController so that it updates the Data that is currently being shown in the ProductDetailsView”

All we need to do is 3 things

- 1.0 ProductDetailsController registers to the SelectProduct message (the message is just a constant string defined in a common class named Messages)

- 1.1 ProductDetailsController updated the Selected Product when this message is sent.

- 2.0 ProductListController sends a message via the Mediator that a new product has been selected

Code for 1.0

public ProductDetailsController()
{
    //register to the mediator for the SelectProduct message
    Mediator.Register(this, new string[]
    {
        Messages.SelectProduct
    });
}

Code for 1.1

/// <summary>
/// Notification from the Mediator
/// </summary>
/// <param name="message">The message type</param>
/// <param name="args">Arguments for the message</param>
public override void MessageNotification(string message, object args)
{
    switch (message)
    {
        //change the CurrentProduct to be the newly selected product
        case Messages.SelectProduct:
            CurrentProduct = (Product)args;
            break;
    }
}

This will set the CurrentProduct property of the ProductDetailsController to be the new product that has been selected (the product object has been sent via the Code in 2.0). The CurrentProduct property of the ProductDetailsController is being data bound in the view. When the CurrentProduct is set the property raises a PropertyChanged notification, so that the binding is updated with the new value.

Code for 2.0

//event handler for the selection changed
void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Notify that the selected item has changed
    if(e.AddedItems != null && e.AddedItems.Count > 0)
        Mediator.NotifyColleagues(Messages.SelectProduct, e.AddedItems[0]);
}

And this is what I call the MVC + M

hehe… Funny name but for me this is doing miracles. I am currently using this in one of my projects at work and I can confirm that this absolutely works. One may say but this application could have been done with other thing that WPF offers, and I agree 100%. The example application that I used in this post can be easily implemented by putting the list of data in the Model and binding to it (like in MVVM). For the selection part, you can use the Current item of the ICollectionView and everything would work. Yet when you need to do more than just “Select item and data changes somewhere else” than the MVC + M comes useful.

Conclusion

MVC + M is a neat mix of the MVC pattern with the Mediator pattern. The MVC makes things much easier to test and much more isolated and controlled. The Mediator makes communication between Controllers possible in a loosely coupled manner. For me this works really well and I hope that it will do the same for your applications. Download the source code to have a look at my humble implementation.

Any comments, questions and suggestions are as usual most welcome…

P.S I am sorry if this post was a bit long but I didn’t manage to make it any shorter.

See also Part 2

Download the Source code of the Sample Application

kick it on DotNetKicks.com

WPF Treeview root node

Unfortunately the WPF native treeview or treeview items do not expose a property to determine which item is the root node in the treeview. I needed such a feature and thought to put it on my blog…

What is a treeview?
Well believe it or not a TreeView is just an Items Control nothing more. Yes, an ItemsControl that creates TreeViewItems as it’s Item Containers. The TreeViewItems are also ItemsControl so a recursive data structure is formed and the TreeViewItems generate there own child nodes.

Today I will not go into details of how the treeview and ItemsControl work… For more info on this visit Dr.Wpf Blog. I will discuss more how I implemented the root nodes for the treeview.

So an ItemsControl has a very special method that one can override to do some custom logic, “PrepareContainerForItemOverride“. The following is the signature of the method

protected override void PrepareContainerForItemOverride(
    DependencyObject element, object item)

Basically this method gets called whenever an item (in our case a TreeViewItem) is being created and decorated with a DataTemplate (if set). In this method we can set a property of the TreeViewItem to identify the item as a root node.Ok, lets start. First we need to sub class the Treeview control. Once we did that we need a way how to attach information to the TreeViewItems… HMMM.. what better could do this then Attached Properties. Once we have all this, we need to set the attached property to True for the root nodes and we are done :) …. something like this

public class MyTreeView : TreeView
    {

        public static bool GetIsRootNode(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsRootNodeProperty);
        }

        public static void SetIsRootNode(DependencyObject obj, bool value)
        {
            obj.SetValue(IsRootNodeProperty, value);
        }

        public static readonly DependencyProperty IsRootNodeProperty =
            DependencyProperty.RegisterAttached("IsRootNode", typeof(bool),
            typeof(MyTreeView), new UIPropertyMetadata(false));

        protected override void PrepareContainerForItemOverride(
            DependencyObject element, object item)
        {
            SetIsRootNode(element, true);
            base.PrepareContainerForItemOverride(element, item);
        }
    }

So the most important part is where we set the Attached property IsRootNode to true (Please also note that by default the Attached property is set to false). You would be wondering, But wouldn’t this make all TreeViewItems root nodes???!!??? And the answer is, NO. Because the Treeview only generate root nodes. all other nodes are generated by the TreeViewItems themselves (Remember that the TreeViewItems are ItemsControl as well :)).

Once we have the property IsRootNode set we can restyle the TreeView as we want by using a Control Template. something like this

<ControlTemplate TargetType="TreeViewItem">
    <StackPanel Margin="10,2,0,0">
        <WrapPanel Name="item">
            <ToggleButton Name="expander"
                          IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                                              Path=IsExpanded}"
                          Content="+"/>
            <ContentPresenter x:Name="PART_Header"
                  ContentSource="Header" />
        </WrapPanel>
        <Border>
            <ItemsPresenter Name="children" Visibility="Collapsed" />
        </Border>
    </StackPanel>
    <ControlTemplate.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter TargetName="item" Property="Background"
                    Value="LightBlue"/>
        </Trigger>
        <Trigger Property="IsExpanded" Value="True">
            <Setter TargetName="children" Property="Visibility"
                    Value="Visible"/>
        </Trigger>
        <Trigger Property="HasItems" Value="False">
            <Setter TargetName="expander" Property="Visibility"
                    Value="Collapsed"/>
        </Trigger>
        <Trigger Property="local:MyTreeView.IsRootNode" Value="True">
            <Setter TargetName="item" Property="Background" Value="Silver"/>
            <Setter TargetName="item" Property="Height"  Value="50"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

The most important part of this ControlTemplate is the Trigger on the attached property local:MyTreeView.IsRootNode.Here we are making the RootNodes for the treeview look different from all other nodes…

Hope this post helps…. Please contact me if you need any help :)

Download the full source code

Input Prompt support in WPF

Intro

If you look at Vista User experience guide, one thing that is a must have is the Input Prompt. I think that this is very important to improve the user experience. Yet unfortunately this is not supported natively by WPF :(

But don’t worry because AvalonControlsLibrary is at the rescue :)

I had noting to do today so I decided to create this functionality and share it with you guys… You would say, aha; here comes Marlon with a new control. But NO. This is not a control as such. What I have created is a class with some attached properties that can be used to have the Prompt Input feature for any control (or better any control that would make sense such a feature). I choose the attached properties approach rather than creating a custom control for the simple reason to support any control that you wish to have an input prompt like the one displayed in the image below.

Input prompt

As you can see in the image above I am using the Input Prompt both for the TextBox and the ComboBox. And yes you can use it with any control that you want…

How to use this…

Well using this feature is quite easy, all you have to do is to set an attached property in your control. Something like this…

<TextBox local:InputPrompt.PromptText="Enter Search" />

[where local is the XAML namespace mapping]

In total there are 8 properties that you can set which are

  1. InputPrompt.PromptText – I guess you already figured this one out :D
  2. InputPrompt.PromptColor – This is a brush used as foreground for the Prompt Text (Default: Gray)
  3. InputPrompt.PromptFontFamily – The font family to use for the Prompt Text (Default: Arial)
  4. InputPrompt.PromptFontSize – The font size of the Prompt Text (Default: 12.0)
  5. InputPrompt.PromptFontStretch – The font stretch to use for the Prompt Text (Default: FontStretches.Normal)
  6. InputPrompt.PromptFontStyle – The font style to use for the Prompt Text (Default: FontStyles.Normal)
  7. InputPrompt.PromptFontWeight – The font weight to use for the Prompt Text (Default: FontWeights.Normal)
  8. InputPrompt.PromptBackColor – This is a brush that is used to color the background of the prompt (Default: Transparent)

Please note: You must set the InputPrompt.PromptText in order for this to work all the other properties are optional. Also you must have you control under an AdornerDecorator because the InputPrompt will draw the prompt text in an adorner.

If you use the Input Prompt with a textbox the input prompt will be much more intelligent. What do I mean by this? Basically the Input Prompt handles the Text Changed event of the TextBox and if the user enters no text the prompt re appears. The same happens if the TextBox looses focus and there is no text in it. I did this behaviour for the TextBox because this is the standard behaviour for an Input Prompt for textboxes.

How does this work behind the scenes

Well it’s quite simple. Basically an Adorner is placed on top of the control which sets the Attached properties and draws the InputPrompt.PromptText. Besides drawing the text this also draws a rectangle covering the surface of the control so that as soon as the user click the control(or better mouse down on the control), the adorner disappears and the control gets activated once again.

When the InputPrompt.PromptText is set for a TextBox, the input prompt will register to the LostFocus event and the TextChanged event and make sure to display the Prompt Text if the Text of the TextBox is to empty.

Conclusion

All this will be included in AvalonControlsLibrary v3 but I decided to upload a demo as a stand alone so that you can start using this immediately.

Hope you like this and as usual I am all ears for feedback and suggestions….

Thanks

Download Source Code and Demo App

kick it on DotNetKicks.com

Support for MinDate and MaxDate in DatePicker and TimePicker

I updated the sources for AvalonControlsLibrary v2 so that to support MinDate and MaxDate in the DatePicker.

Also added support for MinTime and MaxTime in TimePicker.

And while I was at it I also refactored the DateTimePicker to support these 2 properties.

The properties are DependencyProperties so you can easily databind to and do what every you like with them….

Great… now i should go to sleep :D

Downlaod the new version