I’m leading a parallel life

June 28, 2009

So, I’ve just started looking at a new .NET language from Microsoft called Axum (available here). At this point you might be tempted, as I originally was, to complain that there’s no need for Microsoft to produce yet another language. After all, we have perfectly servicable languages in C#, VB.NET and (for the linguistically adventurous) F#. Why on earth is Microsoft wasting its time on another language?

Well, it turns out that there’s a very good reason for them to be looking into creating a new one. Axum fits a niche that, while other languages could do what it does, these other languages weren’t originally designed for. Axum is designed for applications that require parallel task exection. As it is designed to create parallel applications, the language offers first class constructs for achieving parallelisation.

The Axum documentation, sparse as it is at the moment, identifies that some tasks are easily amenable to parallelisation because the tasks are independent of each other, and require little synchronisation; other applications have dependencies that require coordination. Axum, as a language, allows us to arrange the coordination between these components in a way that closely matches the way we would conceive of the solutions.

I said, before, that other languages offer us the ability to parallize tasks, so it’s hard to see what Axum brings to the ball, so to speak. Well Axum removes one feature that normally causes problems for developers creating parallel applications if they aren’t careful. It removes the ability for components to share or mutate state from other threads. It provides an isolation model that promotes a disciplined access to shared state, and encourages its use from the start rather than being added as an afterthought.

At this stage, I must stress that Axum is an experimental language, similar enough to C# not to be daunting. This similarity, though, could also cause problems at first glance because it’s so easy to try and do things the C# way, which is not always the Axum way.

Without further ado we’re going to write our first Axum application. It’s a variation of the Hello World described in the Axum Programmers Guide. Assuming you’ve downloaded and installed Axum in either Visual Studio 2008 or Visual Studio 2010, select File > New > Project > Axum > Windows > Console Application. Call the application HelloAxum and click OK. You’ll now get some boilerplate code which you’re going to replace with:


using System;
agent HelloAxum : Microsoft.Axum.ConsoleApplication
{
  override int Run(string[] args)
  {
    Console.WriteLine("Hello Axum");
  }
}

The first thing to note about this application is that it has full access to .NET features, such as the BCL or Console.WriteLine.

Second, we’ve defined our unit of work as an agent rather than a class. An agent is conceptually similar to an actor (in fact Axum is well suited to being mapped out with UML). Agents represent autonomous elements that communicate using messages and so on. Here’s my first problem with Axum; why not call it an actor? Why define a new term here? It just feels a natural fit, for me, to use actor here rather than agent.

Anyway, terminology quibbles aside, agents are very different to developing using OOP. These differences are by design and are there for very good reasons. Agents don’t provide public methods or exhibit state, so you can’t modify fields externally. This means that you can’t call an agent method directly, so you might be tempted to think that methods are useless here. What you can do and what you do, in fact, do, is send a message to the agent and arrange for the agent to get back to you with a response when it is apropriate.

In our sample application we derive from a ConsoleApplication agent which provides the basis for working with console applications.

At this stage, you may be feeling distinctly underwhelmed. After all, we’ve not really done any parallel processing. It’s time to mix things up a bit and do some parallel work. Let’s actually create a couple of agents and pass messages between them. Along the way, we’re going to learn some of the terminology in Axum starting with channels and ports.

Remember that we said that we couldn’t reach into agents? Well, how do we set or get this data? The ability to do this lies in channels – which (in OO terms) defines the interface that our decoupled agents will communicate through. The ports, on a channel, define the inputs and outputs.
In order to define a channel, we use the channel keyword. Here’s a simple channel:


channel HelloAxumChannel
{
  input string Name;
  output string Text;
}

When you use a channel data goes in, cunningly enough, into the inputs and is returned via the outputs. Notice that the channel doesn’t actually tell you how it does it – it only tells you what it does. Now let’s add the implementation.


agent HelloAgent : channel HelloAxumChannel
{
  public HelloAgent()
  {
    string item = receive(PrimaryChannel::Name);

    PrimaryChannel::Text <-- string.Format("Hello {0}", item);
  }
}

This agent waits for a message to arrive on the Name port (the receive statement). Once this is received, it sends a message to the Text port on the PrimaryChannel (the PrimaryChannel is a public property on the channel that gives access to the channel being implemented). It then sends a message to the Created port. Now, received is a blocking operation, meaning that it waits until a message arrives on that port. Now, let’s do something with this – let’s actually “instantiate” this agent and pass a message to it.


public domain Program
{
    agent HelloAxum : Microsoft.Axum.ConsoleApplication
    {
        override int Run(string[] args)
        {
            var proc = HelloAgent.CreateInNewDomain();

            Console.Write("Enter your name:");
            string value = Console.ReadLine();
            proc::Name <-- value;
           
            string outputText = receive(proc::Text);
            Console.WriteLine(outputText);
            Console.ReadKey();
        }

    }
}

In order to instantiate our agent, we use CreateInNewDomain. Once it’s been created we pass messages into it using <–. Again, this process waits for a message from our agent in proc::Text. That’s it – we’ve got a parallel application. (Here it is in all it’s glory):


using System;
using Microsoft.Axum;
using System.Concurrency.Messaging;

namespace AxumApplication1
{
    public domain Program
    {
        agent HelloAxum : Microsoft.Axum.ConsoleApplication
        {
            override int Run(string[] args)
            {
                var proc = HelloAgent.CreateInNewDomain();

                Console.Write("Enter your name:");
                string value = Console.ReadLine();
                proc::Name <-- value;
               
                string outputText = receive(proc::Text);
                Console.WriteLine(outputText);
                Console.ReadKey();
            }

        }
    }
   
    channel HelloAxumChannel
    {
        input string Name;
        output string Text;
    }
   
    agent HelloAgent : channel HelloAxumChannel
    {
        public HelloAgent()
        {
            string item = receive(PrimaryChannel::Name);
           
            PrimaryChannel::Text <-- string.Format("Hello {0}", item);
        }
    }
}

So, do I like Axum? Well, yes I do – I’ve only just begun to scratch the surface of what it can do here; look for more from me in future blogs. I only hope that it actually goes somewhere – I’d hate to see the project die for lack of interest. Obviously, you know my love of WPF, so I’d also like Axum to provide first class WPF integration. I’m watching Axum with interest.


Binding Passwords

June 10, 2009

Those who’ve been following my blog and conversations with the WPF Disciples know that I love the databinding power of WPF, and in almost all cases I’m a very happy bunny. There is one stain in the awe inspiring goodness that is bound applications, and that’s the PasswordBox. Superficially, this control looks like a textbox, but there is a problem when you write MVVM applications and rely on binding the way I do; you can’t bind to it. Yes, you heard it right, you can’t bind with a PasswordBox.

There’s a good reason for this lack of binding – PasswordBox.Password is not a Dependency Property, ostensibly because this would result in the password being stored in clear text in memory, which is a potential security concern. If, however, you aren’t too worried about this potential security breach, there is a workround. Good news, folks – the following class (taken from my forthcoming Twitter client Songbird) is a way to perform binding with the PasswordBox.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace SongBird.Infrastructure
{
    /// <summary>
    /// This class adds binding capabilities to the standard WPF PasswordBox.
    /// </summary>
    public class BoundPasswordBox
    {
        #region BoundPassword
        private static bool _updating = false;

        /// <summary>
        /// BoundPassword Attached Dependency Property
        /// </summary>
        public static readonly DependencyProperty BoundPasswordProperty =
            DependencyProperty.RegisterAttached("BoundPassword",
                typeof(string),
                typeof(BoundPasswordBox),
                new FrameworkPropertyMetadata(string.Empty, OnBoundPasswordChanged));

        /// <summary>
        /// Gets the BoundPassword property.
        /// </summary>
        public static string GetBoundPassword(DependencyObject d)
        {
            return (string)d.GetValue(BoundPasswordProperty);
        }

        /// <summary>
        /// Sets the BoundPassword property.
        /// </summary>
        public static void SetBoundPassword(DependencyObject d, string value)
        {
            d.SetValue(BoundPasswordProperty, value);
        }

        /// <summary>
        /// Handles changes to the BoundPassword property.
        /// </summary>
        private static void OnBoundPasswordChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox password = d as PasswordBox;
            if (password != null)
            {
                // Disconnect the handler while we're updating.
                password.PasswordChanged -= PasswordChanged;
            }

            if (e.NewValue != null)
            {
                if (!_updating)
                {
                    password.Password = e.NewValue.ToString();
                }
            }
            else
            {
                password.Password = string.Empty;
            }
            // Now, reconnect the handler.
            password.PasswordChanged += new RoutedEventHandler(PasswordChanged);
        }

        /// <summary>
        /// Handles the password change event.
        /// </summary>
        static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox password = sender as PasswordBox;
            _updating = true;
            SetBoundPassword(password, password.Password);
            _updating = false;
        }

        #endregion

    }
}

Using it couldn’t be simpler, just add a reference to the namespace in your XAML, and update your PasswordBox with the BoundPasswordBox class. You’ve now got a bindable PasswordBox.


<PasswordBox
    Grid.Column="1"
    Grid.Row="2"
    Margin="5,5,5,5"
    password:BoundPasswordBox.BoundPassword="{Binding Path=Password,
        Mode=TwoWay,
        UpdateSourceTrigger=PropertyChanged}"
    VerticalAlignment="Center"/>

Please select your collection

May 21, 2009

In this post, I’d like to cover a fairly common scenario that I’ve received various bits of email about as WPF is becoming more and more popular with developers. A common requirement for a lot of developers is to have a ComboBox contain an entry at the top of the list prompting the user to select an item from the list. As the list is normally populated using a collection of some description it would seem, at first glance, that the only way to actually put a selection choice in is to actually modify the list somehow – and this is precisely the advice that several “professional developers” offer.

You can probably guess by the tone of the end of that previous paragraph that I don’t agree with this approach. It just smacks way too much of a hack to my liking. Rejoice though, WPF provides a neat way to get round this problem, and I’m going to demonstrate a limitation of one of the classes we use to get round the limitation.

Right, let’s start off by defining the class that we are going to display in the ComboBox. It’s a variation of our old faithful, the Person class.


namespace CompositeTest
{
  using System;
  using System.ComponentModel;

  /// <summary>
  /// This class defines the person.
  /// </summary>
  public class Person : INotifyPropertyChanged
  {
    private string _name;
    /// <summary>
    /// The name of the person.
    /// </summary>
    public string Name
    {
      get
      {
        return _name;
      }
      set
      {
        if (_name != value)
        {
          _name = value;
          OnChange("Name");
        }
      }
    }

    /// <summary>
    /// Raise change notifications.
    /// </summary>
    ///
<param name="property">The property to raise the
    /// notification on.</param>
    protected virtual void OnChange(string property)
    {
      PropertyChangedEventHandler handler = propertyChanged;
      if (handler != null)
      {
        handler(null, new PropertyChangedEventArgs(property));
      }
    }
    #region INotifyPropertyChanged Members

    private event PropertyChangedEventHandler propertyChanged;
    public event PropertyChangedEventHandler PropertyChanged
    {
      add { propertyChanged += value; }
      remove { propertyChanged -= value; }
    }

    #endregion
  }
}

As you can see, it’s a bog-standard POCO implementation, with no “goo” in place to handle a “magic” item.

Next, we define the XAML that we are going to use. Don’t worry about the complexity at the moment, as we’ll soon break it down to better understand what’s going on.


<Window x:Class="CompositeTest.Window1"
  xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>"
  xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>"
  Title="Selection Sample" Height="200" Width="300"
  xmlns:dt="clr-namespace:CompositeTest"
  x:Name="Window">
  <Window.Resources>
    <DataTemplate x:Key="PersonTemplate">
      <StackPanel>
        <TextBlock Text="{Binding Path=Name}" />
      </StackPanel>
    </DataTemplate>
    <ControlTemplate x:Key="ValidationTemplate">
      <DockPanel>
        <AdornedElementPlaceholder />
        <TextBlock Foreground="Red"
               FontSize="20"
               ToolTip="You must choose an item">*</TextBlock>
      </DockPanel>
    </ControlTemplate>
  </Window.Resources>
  <StackPanel>
    <ComboBox
      IsEditable="False"
      SelectedIndex="0"
      Margin="20"
      ItemTemplate="{StaticResource PersonTemplate}"
      Validation.ErrorTemplate="{StaticResource ValidationTemplate}"
      >
      <ComboBox.SelectedItem>
        <Binding Path="SelectedPerson"
             ElementName="Window"
             Mode="OneWayToSource">
          <Binding.ValidationRules>
            <dt:PersonValidation />
          </Binding.ValidationRules>
        </Binding>
      </ComboBox.SelectedItem>
      <ComboBox.ItemsSource>
        <CompositeCollection>
          <ComboBoxItem>Please select...</ComboBoxItem>
          <CollectionContainer
            x:Name="peopleCollection"
            x:FieldModifier="private"/>
        </CompositeCollection>
      </ComboBox.ItemsSource>
    </ComboBox>
  </StackPanel>
</Window>

Obviously we want to put something in place to inform the user that they need to select a person from the list. A good way to do this is to put a validation rule into place, and that’s what we are going to do. Here’s the code:


namespace CompositeTest
{
  using System;
  using System.Windows.Controls;
  using System.Globalization;
  /// <summary>
  /// Validate the ComboBox to see whether or not the
  /// user has chosen a person.
  /// </summary>
  public class PersonValidation : ValidationRule
  {
    /// <summary>
    /// Validate the item to see if it's a ComboBoxItem or not.
    /// If it is a ComboBoxItem, this means that the user has
    /// chosen the please select item.
    /// </summary>
    /// <returns>A ValidationResult based on the test</returns>
    public override ValidationResult Validate(object value,
      CultureInfo cultureInfo)
    {
      if (value is ComboBoxItem)
        return new ValidationResult(false,
          "Selection is invalid");
      return new ValidationResult(true, null);
    }
  }
}

The validation logic is fairly simple. If the value is a ComboBoxItem, this means the user has chosen the Please select… option from the list. Any other selection means the user has chosen a Person from the list.

Now, let’s break the XAML down a little bit.


  <Window.Resources>
    <DataTemplate x:Key="PersonTemplate">
      <StackPanel>
        <TextBlock Text="{Binding Path=Name}" />
      </StackPanel>
    </DataTemplate>
    <ControlTemplate x:Key="ValidationTemplate">
      <DockPanel>
        <AdornedElementPlaceholder />
        <TextBlock Foreground="Red"
               FontSize="20"
               ToolTip="You must choose an item">*</TextBlock>
      </DockPanel>
    </ControlTemplate>
  </Window.Resources>

Here we’ve created a data template that we are going to apply to the combo box, and a control template that will be applied when there are validation failures. The use of AdornedElementPlaceHolder is an easy way to place the a decorated control relative to other items in your template.


    <ComboBox
      IsEditable="False"
      SelectedIndex="0"
      Margin="20"
      ItemTemplate="{StaticResource PersonTemplate}"
      Validation.ErrorTemplate="{StaticResource ValidationTemplate}"
      >

Here we’re hooking the item template to the data template, and the error template to the control template we talked about above.


      <ComboBox.SelectedItem>
        <Binding Path="SelectedPerson"
             ElementName="Window"
             Mode="OneWayToSource">
          <Binding.ValidationRules>
            <dt:PersonValidation />
          </Binding.ValidationRules>
        </Binding>
      </ComboBox.SelectedItem>

Whenever the selected item changes, the application is going to perform the validation that we defined in the PersonValidation class. If there’s a failure, the application will apply the validation template. Please note the ElementName element – I’ve defined this as a named attribute in the Window declaration.


      <ComboBox.ItemsSource>
        <CompositeCollection>
          <ComboBoxItem>Please select...</ComboBoxItem>
          <CollectionContainer
            x:Name="peopleCollection"
            x:FieldModifier="private"/>
        </CompositeCollection>
      </ComboBox.ItemsSource>
    </ComboBox>

We finally get to the magic. Where you may be tempted, in normal use, to just set the ItemsSource to a standard Binding, we need to use a CompositeCollection instead. This handy class allows us to put pretty much any type of data into the ItemsSource (within reason). To use it, we add a ComboBoxItem to the CompositeCollection that displays the text we want to appear at the top of the combo box.

Next, we add a collection to the CompositeCollection using a CollectionContainer. In most of the samples you see of this on the web, it binds to a StaticResource and is perfectly happy. If you want to bind to a DataContext, however, you’re kind of stuffed – the CompositeCollection is not Freezable and, in order to bind to the data context, you have to have a chain of Freezable items. So, if you can’t do <CollectionContainer Collection=”{Binding}” /> in your XAML, what can you do?

Well, the answer is to do it in the code behind. All you need to do is set the Collection as in the following class (you need to expose the CollectionContainer to your code behind, hence the use of x:Name on it):


namespace CompositeTest
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Windows;
  using System.Windows.Controls;
  using System.Windows.Data;
  using System.Windows.Documents;
  using System.Windows.Input;
  using System.Windows.Media;
  using System.Windows.Media.Imaging;
  using System.Windows.Navigation;
  using System.Windows.Shapes;
  using System.Collections.Specialized;
  /// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>
  public partial class Window1 : Window
  {
    private List<Person> list = new List<Person>();
    public Window1()
    {
      InitializeComponent();

      BindData();
    }
    public object SelectedPerson { get; set; }
    private void BindData()
    {
      list.Add(new Person { Name = "Peter" });
      list.Add(new Person { Name = "Karl" });
      list.Add(new Person { Name = "Sacha" });
      list.Add(new Person { Name = "Bill" });
      list.Add(new Person { Name = "Josh" });

      peopleCollection.Collection = list;
    }
  }
}

Armed with this information, you can now provide Please select functionality in your applications without any real problems now.

Happy coding.

Download: WpfApplication1.zip.

When you download the source, you’ll need to remove the .doc extension.


Easy help with WPF

May 1, 2009

If, like me, you like your applications to provide Context sensitive help, you’ve probably had a play around with the ApplicationCommands.Help command. In order to simplify hooking your help into your application, I’ve written the following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using form = System.Windows.Forms;
using System.Windows.Media;

namespace HelpProvider
{
  /// <summary>
  /// This class provides the ability to easily attach Help functionality
  /// to Framework elements. To use it, you need to
  /// add a reference to the HelpProvider in your XAML. The FilenameProperty
  /// is used to specify the name of the helpfile, and the KeywordProperty specifies
  /// the keyword to be used with the search.
  /// </summary>
  /// <remarks>
  /// The FilenameProperty can be at a higher level of the visual tree than
  /// the KeywordProperty, so you don't need to set the filename each time.
  /// </remarks>
  public static class Help
  {
    /// <summary>
    /// Initialize a new instance of <see cref="Help"/>.
    /// </summary>
    static Help()
    {
      // Rather than having to manually associate the Help command, let's take care
      // of this here.
      CommandManager.RegisterClassCommandBinding(typeof(FrameworkElement),
        new CommandBinding(ApplicationCommands.Help,
          new ExecutedRoutedEventHandler(Executed),
          new CanExecuteRoutedEventHandler(CanExecute)));
    }

    #region Filename

    /// <summary>
    /// Filename Attached Dependency Property
    /// </summary>
    public static readonly DependencyProperty FilenameProperty =
      DependencyProperty.RegisterAttached("Filename", typeof(string), typeof(Help));

    /// <summary>
    /// Gets the Filename property.
    /// </summary>
    public static string GetFilename(DependencyObject d)
    {
      return (string)d.GetValue(FilenameProperty);
    }

    /// <summary>
    /// Sets the Filename property.
    /// </summary>
    public static void SetFilename(DependencyObject d, string value)
    {
      d.SetValue(FilenameProperty, value);
    }

    #endregion
   
    #region Keyword

    /// <summary>
    /// Keyword Attached Dependency Property
    /// </summary>
    public static readonly DependencyProperty KeywordProperty =
      DependencyProperty.RegisterAttached("Keyword", typeof(string), typeof(Help));

    /// <summary>
    /// Gets the Keyword property.
    /// </summary>
    public static string GetKeyword(DependencyObject d)
    {
      return (string)d.GetValue(KeywordProperty);
    }

    /// <summary>
    /// Sets the Keyword property.
    /// </summary>
    public static void SetKeyword(DependencyObject d, string value)
    {
      d.SetValue(KeywordProperty, value);
    }
    #endregion

    #region Helpers
    private static void CanExecute(object sender, CanExecuteRoutedEventArgs args)
    {
      FrameworkElement el = sender as FrameworkElement;
      if (el != null)
      {
        string fileName = FindFilename(el);
        if (!string.IsNullOrEmpty(fileName))
          args.CanExecute = true;
      }
    }

    private static void Executed(object sender, ExecutedRoutedEventArgs args)
    {
      // Call ShowHelp.
      DependencyObject parent = args.OriginalSource as DependencyObject;
      string keyword = GetKeyword(parent);
      if (!string.IsNullOrEmpty(keyword))
      {
        form.Help.ShowHelp(null, FindFilename(parent), keyword);
      }
      else
      {
        form.Help.ShowHelp(null, FindFilename(parent));
      }
    }

    private static string FindFilename(DependencyObject sender)
    {
      if (sender != null)
      {
        string fileName = GetFilename(sender);
        if (!string.IsNullOrEmpty(fileName))
          return fileName;
        return FindFilename(VisualTreeHelper.GetParent(sender));
      }
      return null;
    }
    #endregion

  }
}

Using it couldn’t be simpler, set up the Filename in your XAML and add any keywords you need to search on against your FrameworkElement items. The advantage of this approach is that you can bind different parts of your UI to different helpfiles if you want.


<Window
  x:Class="HelpSample.Window1"
  xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>"
  xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>"
  Title="Window1" Height="300" Width="300"
  xmlns:help="clr-namespace:HelpProvider;assembly=HelpProvider"
  help:Help.Filename="MyHelpfile.chm"
  >
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition />
      <RowDefinition />
    </Grid.RowDefinitions>
    <TextBox help:Help.Keyword="MyKeyword" Grid.Row="0" Text="Keyword based search" />
    <TextBox Grid.Row="1" Text="No keyword" />
  </Grid>
</Window>

I hope this helps you as much, as it helps me.


Silverlight OverrideCursor

April 15, 2009

One of the really great things you can do with WPF is use Mouse.OverrideCursor to set the cursor for the entire application. This is useful, for instance, if you want your application to perform a lengthy operation, and have the cursor change to a wait cursor, for the duration of the operation. You’d normally do this like:


public void DoAReallyLongOperation()
{
  Cursor savedCursor = Mouse.OverrideCursor;
  try
  {
    PerformMyLengthyOperation();
  }
  finally
  {
    Mouse.OverrideCursor = savedCursor
  }
}

So far, so good. Now, of course, you’re going to run off to your Silverlight applications and do exactly the same for your lengthy operations, aren’t you? After all, Silverlight is a lightweight version of WPF, so surely this will be there for you to use.

Well no. Silverlight doesn’t support the OverrideCursor, but adding it shouldn’t be too hard should it? Well, it turns out that adding the OverrideCursor isn’t as easy as you’d think it would be. If you change the cursor on your page to a wait cursor, for instance, it will still be an IBeam when you move over a text box. This means that your code needs to traverse the visual tree looking for all of the child elements, and setting the cursor to the new cursor.

Edit: Since I posted this earlier today, an edge case was suggested that needed addressing. Basically, the code needs to be able to reset the text boxes back to the IBeam assuming that the OverrideCursor is set back.

The following class provides an attached property that should help greatly with this:


/// <summary>
/// Mouse handling class to simulate the OverrideCursor functionality in WPF.
/// </summary>
public class Mouse : DependencyObject
{
  #region Members
  private static Cursor _oldCursor;
  private static bool _isResetting = false;
  private static Cursor _overrideCursor;
  #endregion
  /// <summary>
  /// Recursively traverse the visual tree, setting the cursor as appropriate.
  /// </summary>
  ///
<param name="current">The element to iterate over.</param>
  ///
<param name="cursor">The cursor to set to.</param>
  /// <remarks>
  /// If the new cursor is the same as the stored original cursor,
  /// then we assume that this is a reset operation taking place.
  /// At this point, we reset the cursor to the original for the element,
  /// irrespective of what the Cursor states.
  /// </remarks>
  internal static void TraverseVisualTree(object current, Cursor cursor)
  {
    DependencyObject ob = current as DependencyObject;
    if (ob != null)
    {
      if (ob is FrameworkElement)
      {
        FrameworkElement element = ob as FrameworkElement;
        Cursor oldCursor = GetOldCursor(element);
        Cursor newCursor = cursor;
        // If this is a reset, then get the old cursor reference
        // back so that we can use this.
        if (_isResetting)
        {
          newCursor = oldCursor;
          SetOldCursor(element, null);
        }
        else
        {
          SetOldCursor(element, element.Cursor);
        }
        element.Cursor = newCursor;
      }
      int counter = VisualTreeHelper.GetChildrenCount(ob);
      for (int i = 0; i < counter; i++)
      {
        object depObj = VisualTreeHelper.GetChild(ob, i);
        TraverseVisualTree(depObj, cursor);
      }
    }
  }
  /// <summary>
  /// The OverrideCursor attached property.
  /// </summary>
  public static readonly DependencyProperty OverrideCursorProperty =
    DependencyProperty.RegisterAttached("OverrideCursor",
    typeof(Cursor),
    typeof(UserControl),
    new PropertyMetadata(null, OnCursorChanged));
  /// <summary>
  /// The OldCursor attached property.
  /// </summary>
  private static readonly DependencyProperty OldCursorProperty =
    DependencyProperty.RegisterAttached("OldCursor",
    typeof(Cursor),
    typeof(UserControl),
    new PropertyMetadata(null));
  /// <summary>
  /// Called when the cursor changes.
  /// </summary>
  private static void OnCursorChanged(DependencyObject source,
    DependencyPropertyChangedEventArgs e)
  {
    if (!(source is FrameworkElement))
      return;
    // If the "old" cursor is the same as the "new" cursor, the
    // code will reset each elements cursor back to its original value.
    _isResetting = (_oldCursor == e.NewValue);
    if (!_isResetting)
    {
      _oldCursor = e.OldValue as Cursor;
    }
    TraverseVisualTree(source, e.NewValue as Cursor);
  }
  /// <summary>
  /// Get the override cursor.
  /// </summary>
  ///
<param name="source">The object to get the override cursor for.</param>
  /// <returns>The populated override cursor.</returns>
  public static Cursor GetOverrideCursor(DependencyObject source)
  {
    return source.GetValue(OverrideCursorProperty) as Cursor;
  }
  /// <summary>
  /// Set the override cursor.
  /// </summary>
  ///
<param name="source">The object to set the cursor for.</param>
  ///
<param name="value">The cursor value to set.</param>
  public static void SetOverrideCursor(DependencyObject source, object value)
  {
    source.SetValue(OverrideCursorProperty, value);
  }
  /// <summary>
  /// Set the old cursor.
  /// </summary>
  ///
<param name="source">The object to set the cursor for.</param>
  ///
<param name="value">The cursor value to set.</param>
  private static void SetOldCursor(DependencyObject source, object value)
  {
    source.SetValue(OldCursorProperty, value);
  }
  /// <summary>
  /// Get the old cursor.
  /// </summary>
  ///
<param name="source">The object to get the old cursor for.</param>
  /// <returns>The populated old cursor.</returns>
  private static Cursor GetOldCursor(DependencyObject source)
  {
    return source.GetValue(OldCursorProperty) as Cursor;
  }
}

WPF on tour

April 3, 2009

For those who wonder how committed Microsofties are to giving out the good news about technologies like WPF or Silverlight, prepare to be amazed. My fellow disciples, and commited Microsofters, the awesome Mr Karl Shifflett and the amazing Jaime Rodriguez are going on tour. That’s right – coming to a country near you (hopefully), is the WPF LOB tour. If you want to know how you can use WPF the right way to create LOB applications, then you owe it to yourself to get yourself out to one of these events.

More info is available here.


Where did my StartupPath go?

March 23, 2009

So somebody has just asked where Application.StartupPath has disappeared in WPF. This is available in Windows Forms, but not available in WPF. A common technique to get the startup path is to use Assembly.GetEntryAssembly().Location, but there’s a problem with GetEntryAssembly if your app is fired off from an unmanaged application, such as a COM application for instance.

We have a couple of applications where our executable is fired off as a result of unmanaged processing – primarily when processing image data that’s been collected and checkpointed by some native code. We’ve found that GetEntryAssembly is null in this instance, whereas the following method works fine.

Now one way that you could add this in would be to add a reference to System.Windows.Forms into your project and then call it from there – however, there’s a way that you can do it without needing to go anywhere near WinForms just by adding a few lines of code. Here it is – in all its glory.


public static class Utility
{
  [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);

  private static string startupPath;
  private static HandleRef NullHandleRef = new HandleRef();

  public static string StartupPath()
  {
    if (startupPath == null)
    {
      StringBuilder buffer = new StringBuilder(260);
      GetModuleFileName(NullHandleRef, buffer, buffer.Capacity);
      startupPath = Path.GetDirectoryName(buffer.ToString());
    }
    new FileIOPermission(FileIOPermissionAccess.PathDiscovery, startupPath).Demand();
    return startupPath;
  }
}

As you can see, the code merely wraps up a call to GetModuleFileName, it’s that simple.

Note – since posting this, one of my fellow WPF Disciples handed over the following code which should work as well:


startupPath = (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).Location

Fun with fonts

March 13, 2009

So I’ve been playing around with the RichTextBox for WPF and decided that it would be a great idea to add font selection to the code. Obviously, this being WPF, I didn’t want to just list the fonts out, I wanted to list the fonts out in exactly the way they’d be displayed. In other words, I want the font name to be written out using the font itself. By now it shouldn’t come as a surprise to you that this is extremely easy to do in WPF.

First of all, it’s really easy to get a list of the fonts. .NET provides a handy little class cunningly enough known as InstalledFontCollection, so we’ll wrap that up in a handy list ready for use:


 

using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Drawing;

namespace FontManager
{
    public class InstalledFonts : List<FontFamily>
    {
        public InstalledFonts()
        {
            InstalledFontCollection fonts = new InstalledFontCollection();
            this.AddRange(fonts.Families);
        }
    }
}

This class just wraps up the installed font families into a handy dataprovider format. This is all about being nice and blend-friendly.

Next we want to define a usercontrol to display the fonts. Something to note about this control; we display the data in a virtualizing stack panel – if you don’t, you could end up waiting quite a while for the first display of the font.


<UserControl
    x:Class="FontManager.InstalledFontDisplay"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:drawing="clr-namespace:System.Drawing;assembly=System.Drawing"
    xmlns:m="clr-namespace:FontManager"
    xmlns:sys="clr-namespace:System.Collections.Generic;assembly=mscorlib"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Resources>
        <Style x:Key="FontStyle">
            <Setter Property="Control.FontFamily" Value="{Binding Name}" />
            <Setter Property="Control.FontSize" Value="16" />
        </Style>
        <DataTemplate x:Key="FontTemplate">
            <StackPanel VirtualizingStackPanel.IsVirtualizing="True">
                <TextBlock
                    Text="{Binding Name}"
                    ToolTip="{Binding Name}"
                    Style="{StaticResource FontStyle}" />
            </StackPanel>
        </DataTemplate>
        <ObjectDataProvider x:Key="FontProvider" ObjectType="{x:Type m:InstalledFonts}"/>
    </UserControl.Resources>
    <ComboBox
            VerticalAlignment="Top"
            ItemsSource="{Binding Source={StaticResource FontProvider}}"
            ItemTemplate="{StaticResource FontTemplate}" />

</UserControl>

That’s it – that’s all there is to displaying your font names in the appropriate font. It is so easy, and yet another reason to love WPF. Go on – you know you love it.


Onyx

March 2, 2009

So, there’s this guy called Bill Kempf who’s a fellow WPF Disciple. Now, Bill’s an extremely smart guy who’s come up with a framework that helps ease the pain when developing MVVM applications. If you are serious about developing robust WPF and Silverlight applications, then I can heartily recommend that you take a look at the Onyx framework.


MoXAML 2.4 Released

February 22, 2009

I’ve just uploaded the newest version of MoXAML Power Toys. MoXAML now includes a version of Scrubber that runs inside Visual Studio – Scrubber was introduced to the world by Robby Ingebretsen in his wonderful Kaxaml tool. Go on – beautify all the XAML in your projects with one simple menu option.