Be careful with Debug.Assert

What is wrong with this code?

Debug.Assert(Marshal.ReleaseComObject(this.decoder) == 0, "Ensure it's released properly");

I foolishly wrote this line of code only to find (luckily) that FxCop was telling that the private field decoder was never referenced. How could that be I thought? The “Find All References” command yields this line in its results, it must be a bug I thought.

Of course after thinking about it for a second I realized that I was running FxCop against the Release version of my assembly, then I remembered that the method Debug.Assert has the Conditional attribute on it so that it doesn’t get compiled in release mode, doh!

The ConditionalAttribute actually allows you to tell the compiler that calls to this method are to be completely ignored unless the current configuration matches the parameter. It’s very handy but also very tricky! Be sure that there are no side effects in your assert expression.

Here is the modified version of the code.

int refrernceCount = Marshal.ReleaseComObject(this.decoder);
Debug.Assert(refrernceCount == 0, "Ensure it's released properly");

Simple synchronization with Iterators in C#

One of the most common complaints I hear about Silverlight is it’s Async only networking capbilities. It’s not that people hate Async it’s that they hate how it affects the synchronous flow of their code. We’re used to code that is written where A –> B –> C but when it’s async it might be completely out of order. Continuation Passing Style is one nice way to accomplish a synchronous flow of code while actually being asynchronous in execution, however this imposes on us some extra syntax that can appear very verbose and visually confusing. Here is an example:

Action C = () => Console.WriteLine("C!");
Action<Action> B = b =>
{
    Console.WriteLine("B!");
    b();
};
Action<Action> A = a =>
{
    Console.WriteLine("A!");
    a();
};

A(() => B(() => C()));

If you imagine that each of these methods are performing their work (e.g. calling Console.WriteLine) asynchronously and then calling in the passed in method when their asynchronous work was complete this would be a Continuation Passing Style. Not at all logically synchronous.

A few times now I’ve heard people say that it was possible to do multi-threading in C# using iterators in such a way that it could look nicer than the CPS (Continuation Passing Style) method. Specifically a video on the Power Threading library and Miguel de Icaza’s latest blog post.

Watching and reading these makes sense to me but I just couldn’t quite wrap my brain around it. Looking into Jeffery Richters Power Threading library didn’t help too much either I’m afraid. It’s probably really awesome but I couldn’t understand what was going on very easily. The API is pretty verbose and the samples are dense. That’s ok but I like to start things out a little slow, so I created a very basic sample of how to do something asynchronous and synchronize it all easily for the caller with an iterator.

Here is the method that does the real work:

public IEnumerator<int> DoWork(ISynchronizer synchronizer, params string[] urls)
{
    yield return urls.Length;

    foreach (string url in urls)
    {
        WebClient client = new WebClient();
        client.DownloadStringCompleted += (o, e) =>
        {
            Console.WriteLine("{0}: {1}", e.UserState, e.Result.Length);
            synchronizer.Set();
        };
        client.DownloadStringAsync(new Uri(url), url);
        yield return 1;
    }
}

This feels pretty synchronous I guess. Foreach url, print out some string. When this method is done printing out all of the URLs then our work is done. The flow is logically synchronous (except for that wonderful DownloadStringCompleted lambda) but you could imagine how it might be possible for the WebClient to do the same thing if it wanted to.

This method gets effectively turned into a Finite State Machine by the C# compiler. If I look at it in Reflector I can see some really gnarly code I’m glad I didn’t have to write myself! So now to synchronize this. Here is my actual application:

Example e = new Example();
Synchronize.Run(
    s => e.DoWork(s,
    "http://www.justnbusiness.com",
    "http://www.codeplex.com",
    "http://www.google.com"));

Console.WriteLine("Done!");
Console.ReadKey(true);

Which yields the results:

http://www.justnbusiness.com: 43210
http://www.google.com: 6290
http://www.codeplex.com: 34070
Done!

Notice how codeplex.com is returning after google.com even though it is earlier in the list but “Done!” is still happening last.

Effectively what I did was simply create a method that iterates over each call to MoveNext() on the enumerator and gets the largest value yielded. Whatever the largest number is is how many times Set() should be called on the synchronizer before continuing on. Here is the Synchronizer code:

public delegate IEnumerator<int> SynchronizeMethod(ISynchronizer synchronizer);

public interface ISynchronizer
{
    void Set();
}

public static class Synchronize
{
    public static void Run(SynchronizeMethod method)
    {
        Syncrhonizer synchronizer = new Syncrhonizer();
        IEnumerator<int> enumerator = method.Invoke(synchronizer);

        while (enumerator.MoveNext())
        {
            int current = enumerator.Current;
            synchronizer.SetCurrent(current);
        }

        synchronizer.Wait();
    }

    private class Syncrhonizer : ISynchronizer
    {
        ManualResetEvent mre = new ManualResetEvent(false);
        int count;
        int max;

        public void SetCurrent(int current)
        {
            if (current > max)
                max = current;
        }

        public void Set()
        {
            count++;
            if (count >= max)
                mre.Set();
        }

        public void Wait()
        {
            mre.WaitOne();
        }
    }
}

You could envision nested calls to Synchronize.Run in order to synchronize multiple layers of tasks. This is a very simple approach and I could see how this could easily get more complicated. I’m interested in playing around with this a little more though.

If I was in Silverlight this wouldn’t work however. Silverlight won’t let you block the main thread with a ManualResetEvent. So you could probably create a RunAsync overload that accepts a callback to call. So you can free up the main thread.

Personally I’m not sure this is any better but it’s interesting. I’d really like to give it a try once for something more complicated to see how it holds up.

The Binding Markup Extension

Last week I wrote a post about Markup Extensions with the intention of providing some background information for the Binding Class. If you’re doing an WPF or Silverlight development the Binding class is very important to know about. Further more, as a developer working side by side with a designer most of the work of integrating the design and the code is done through data binding.

The Basics

The Binding class is a very common type of markup extension. Its purpose is to update elements in your UI with values defined at other locations. Most of the time these other data sources will be ViewModels you create but it is also possible to bind to other UI elements.

So, for example, suppose you have a Customer object with a Name property and you want to display that in a text box. The Xaml to do this would look like this:

<TextBox Text="{Binding Name}" />

Pretty simple. The Binding markup extension accepts a Path as its default parameter. If you wanted you could optionally specify the full parameter name as well.

<TextBox Text="{Binding Path=Name}" />

These two snippets are effectively the same.

The Binding extension uses reflection based on the string you specify for the path to drill down into your object. So optionally you could choose to display the length instead of the actual string of the name, for example.

<TextBox Text="{Binding Path=Name.Length}" />

Additionally you can access indexed values through the path with this syntax:

<TextBox Text="{Binding Path=Name[0]}" />

Which would give you the first character of the string instead of the full name. These last two snippets are actually more tricky than this though. Since a string is immutable the character indexer and Length properties are read-only and Binding expressions do not like to bind against read-only properties. In this case we would need to either switch our Mode to be OneWay or OneTime.

Modes

<TextBox Text="{Binding Path=Name[0], Mode=OneTime}" />

This will result in a TextBox loaded with the string representation of the length of the name it is bound to but editing the text box will not actually do anything other than change the text in the text box. There are 5 modes to be aware of.

  • TwoWay
  • OneWay
  • OneTime
  • OneWayToSource
  • Default

Most of these are pretty straight forward but, surprisingly, Default can actually be tricky. Different controls may have different modes as default so if your binding doesn’t seem to be setting a value in the direction you’re expecting try a different mode.

UpdateSourceTrigger

This is the name of another important property. It is an enum value indicating when your binding should update the source (your ViewMode, a Customer in this case). So if we are bound to the Name property of Customer then whenever we type in the TextBox, by default, the name will only be updated when the TextBox loses focus. That is because for the Text property of a TextBox the UpdateSourceTrigger is set to LostFocus. If we want real time updating we could writing our binding like this:

<TextBlock Text="{Binding Name}" />
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />

Now as we type in the TextBox the TextBlock will be immediately updated. There are 4 possible values for UpdateSourceTrigger.

  • Default
  • PropertyChanged
  • LostFocus
  • Explicit

The default behaves similarly to the Mode in that different properties for different controls might have a different value for default. You should note that these usually only matter for OneWay or TwoWay bindings and its also dependent upon your ViewModel being implemented correctly (i.e. it implements the INotifyPropertyChanged interface). I’ll discuss view models more in another post however.

Source

Another important property is the Source property. In this example so far I haven’t specified the Source therefore I have been using the default source. By default the source is the value of the controls DataContext property. So that means to get the snippets above to work I had to set the DataContext property to a Customer object. It is also useful to know that if a Controls DataContext is null then it will use its parents DataContext and so on. So for my example I set the root windows DataContext to a customer object which allowed me to use the above Binding syntax.

public MainWindow()
{
    this.InitializeComponent();
    this.DataContext = new Customer { Name = "Justin Chase" };
}

This is a very simplistic way to do this but it works. Additionally you could specify your Source using the Source property. Typically you would do this by pointing it to a resource defined in your resources.

<Window.Resources>
        <local:Customer x:Key="customer" Name="Justin Chase" />
    </Window.Resources>
    
    <Border HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel>
            <TextBlock 
                Text="{Binding Name, 
                Source={StaticResource customer}}" />
            <TextBox 
                Text="{Binding Name, 
                UpdateSourceTrigger=PropertyChanged, 
                Source={StaticResource customer}}" />
        </StackPanel>
    </Border>

This is effectively the same except I now have no code-behind. As a more robust solution to this problem in WPF you can use the ObjectDataSource which gives you capabilities to construct objects in Xaml with constructor parameters or through factory methods. There are still quirks but it’s worth looking into.

Alternately I could have set a parent controls DataContext with a Binding instead of setting the Source on every child Binding like this.

<Window.Resources>
    <local:Customer x:Key="customer" Name="Justin Chase" />
</Window.Resources>

<Border HorizontalAlignment="Center" VerticalAlignment="Center">
    <StackPanel DataContext="{Binding Source={StaticResource customer}}">
        <TextBlock 
            Text="{Binding Name}" />
        <TextBox 
            Text="{Binding Name, 
            UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Border>

It’s especially important to understand the Source property when you find yourself creating DataTemplates, because typically your DataContext is set from an unknown source and you will not be able to set the Source.

Converter and ConverterParameter

The Converter is a wonderful thing and is very simply to understand. The key to a good converter is the IValueConverter interface. Simply implement this and add your class to your Resources and you’re ready to convert! The converter simply converts a value to and fro as it passes through the Binding. I will write more details on this in another post.

The framework comes with a number of Converters but the only one I’ve ever found to be of any use is the System.Windows.Controls.BooleanToVisibilityConverter. But you will no doubt find the need to create many for yourself.

One cautionary note with converters, Converters are powerful but they can also be used to mask architectural problems with ViewModels. If you find yourself using a Converter for anything more than just changing something into a string and back you should probably take a step back and rethink things. I’m not saying you definitely have a problem but it’s worth thinking twice about. I will write in more detail about how to properly construct ViewModels in another post.

ElementName and RelativeSource

The element name is an alternative to the Source property. You either specify the ElementName or the Source but not both. If you specify the ElementName then you’re saying that you want to bind against the value of another control in your UI. The Path is essentially the same except you’re binding against a Control instead of a ViewModel. If you have a control that has a name specified with the x:Name attached property then that is the value you will want to put into the ElementName property.

<TextBlock 
    Text="{Binding Text,
    ElementName=tb}" />
<TextBox 
    x:Name="tb"
    Text="{Binding Name, 
    UpdateSourceTrigger=PropertyChanged}" />

Additionally you can set the RelativeSource property if you need to get to controls in a totally different branch of the control hierarchy or different properties of yourself. The value passed into the RelativeSource property is an Markup Extension, aptly named, RelativeSource. To acheive the same thing as above except using the RelativeSource property you could do this:

<StackPanel DataContext="{Binding Source={StaticResource customer}}">
    <TextBlock 
        Text="{Binding Children[1].Text,
        RelativeSource={RelativeSource 
            Mode=FindAncestor, 
            AncestorType={x:Type StackPanel}}}" />
    <TextBox
        Text="{Binding Name, 
        UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>

ValidationRules

I was struggling with what to write about in this section. I’ve decided to just be honest. My work with CSLA has caused me to come to the conclusion that the validation rules mechanism in WPF / Silverlight Binding expressions is simply inadequate. So basically what I’m saying to you is to simply not use it at all, it’s awful.

The main reason why I think you shouldn’t use it is because it’s completely predicated on the mechanism of throwing exceptions from within a property. Which is a pretty rude thing to due normally. Additionally it requires that you throw a specific WPF type of exception to trigger the validation failure rule… which tightly binds you to WPF. This is evil. And frankly, it’s easy to just write your own validation scheme that WPF / Silverlight is perfectly happy with. In CSLA we wrote a validation scheme that includes prioritization, dependency, asynchrony, severity and multiplicity. And it wasn’t even that hard…

So do yourself a favor and don’t even bother with the built-in validation mechanisms. Additionally, if I didn’t quite sell you with the rational approach, then be aware that the XAML required to write WPF style validation is so Flying Spaghetti Monster-awful that it makes me want to barf just looking at it.

StringFormat

This is a pretty cool little property that is relatively new to WPF that allows you to format the output of the bound text without having to actually write a custom converter. Essentially the string that goes into this property is the same string that you would put into a call to string.Format(…). The only difference is that if you want to put {0} at the beginning of the string you have to escape it with an extra {}… yeah I know. Its hideous but better than not having it… barely. Here is an example of the two usages:

<TextBlock 
    Text="{Binding Name.Length,
    StringFormat='Name Length: {0}'}" />
<TextBlock 
    Text="{Binding Name.Length, 
    StringFormat='{}{0:C}'}" />

IsAsync

Frankly… stay away from this one too. I’ve wanted to use this so many times but have always found the model to be overly simplistic. Asynchronous code is hard, there is no free pass and this just adds to the confusion. You might give it a try if you have some ultra simple scenario but don’t expect it to take you into a completely asynchronous UI.

Many others…

For a complete list of properties head to this site on MSDN http://msdn.microsoft.com/en-us/library/system.windows.data.binding_properties.aspx

Xaml Markup Extensions

Markup extensions for xaml are a lot of fun. There are a bunch of freebies that come with the framework but you can easily create your own as well. Here’s a brief list of common markup extensions that come with the framework:

  • Binding
  • TemplateBinding
  • StaticResource
  • DynamicResource

As a WPF developer you’ll probably run into these every day. Markup extensions are powerful and also very simple to master. If you’re not sure what I’m talking about here is a sample of what a markup extension looks like inside of Xaml:

<TextBlock Text="{Binding Name}" />

If we break it down there are only a few basic rules. The first section of the markup extension is the Type (as in .NET type) following that is a comma separated list of Properties and values. The first property name is optional, each markup extension may specify what the default property is and if a value appears first and without a property name it is assigned to that default property. So this means that the markup extension:

{Binding Name}

Is a class called “Binding” and has a default property, the value of which is “Name”. Also, it’s interesting to note that, like Attributes in C#, the “Extension” part of the type name is optional. If you create a markup extension called “TestExtension” you would reference it in Xaml as “{Test}”.

Also it is possible to use other markup extensions as values for properties. Therefore it’s possible to have a more complex markup extension such as:

{Test Name, Color={StaticResource color}}

For this markup extension there are two properties, one is default and is being assigned the value “Name” while the other is called Color and is being assigned a color from this controls resources.

To create your own markup extension you simply create a class than inherits from the abstract base class MarkupExtension. Here is an example of a custom markup extension for rotating images:

namespace WpfApplication1
{
    using System;
    using System.Windows.Markup;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    [MarkupExtensionReturnType(typeof(BitmapSource))]
    public sealed class RotateExtension : MarkupExtension
    {
        public RotateExtension() { }

        public RotateExtension(BitmapSource source)
        {
            this.Source = source;
        }

        public BitmapSource Source { get; set; }

        public double Angle { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IXamlTypeResolver resolver = (IXamlTypeResolver)serviceProvider
                .GetService(typeof(IXamlTypeResolver));
            IProvideValueTarget target = (IProvideValueTarget)serviceProvider
                .GetService(typeof(IProvideValueTarget));
            BitmapSource rotatedSource = null;
            if (this.Source != null)
            {
                RotateTransform rotation = new RotateTransform(this.Angle);
                rotatedSource = new TransformedBitmap(this.Source, rotation);
            }

            return rotatedSource;
        }
    }
}

Adding the MarkupExtensionReturnType attribute on the class is optional. You’ll need at least one public parameterless constructor and one optional constructor with your default parameter. Then just implement the ProvideValue method! The service provider contains (usually) at least the two services listed here. There is no guarantee they will be there but they are pretty much always there. My example applies a very simple RotateTransform to the bitmap before providing it. Here is the accompanying xaml.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    x:Class="WpfApplication1.MainWindow"
    x:Name="Window"
    Title="MainWindow">
    <Border HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel Orientation="Horizontal">
            <Image Source="img15.png" Stretch="None" />
            <Image Source="{local:Rotate img15.png, Angle=90}" 
                   Stretch="None" />
        </StackPanel>
    </Border>
</Window>

Notice the need to add the namespace “local:” to my extension. This is sort of unfortunate but necessary. I would recommend creating fairly terse names for you extensions to help save you some typing. Also notice that I could just use “img15.png”, which is the path of a file added to my project as a resource instead of trying to create some type of a bitmap source object. The xaml deserializer will realize that the optional parameter on my constructor is a BitmapSource and it will try to use the TypeConverter associated with that type to convert it before giving it to me. Type converters will be the topic of another blog post however.

EDIT:

Sorry folks I had to disable comments on this post due to tons of spam coming in from somewhere. Also, somehow the image above here got overwritten by an image from another post so I deleted it.

Expression Equality Comparer

I was just encountering an issue where I needed to get the distinct elements of two collections but not necessarily distinct instances. When trying to resolve this issue I found the convenient Linq method “Distinct”. By default it will return to you distinct instances but if you want to evaulate equality based on some other qualification then you’re stuck with creating a custom IEqualityComparer<T>. There may be something in the framework already that solves this problem but I couldn’t find it. So I created a really simple Expression based equality comparer and a corresponding enumerable extension method.

public static class Enumerable
{
    public static IEnumerable<T> Distinct<T>(
        this IEnumerable<T> items, 
        Expression<Func<T, T, bool>> equalityComparer)
    {
        ExpressionEqualityComparer<T> comparer = 
            new ExpressionEqualityComparer<T>(equalityComparer);
        return items.Distinct(comparer);
    }
}

public class ExpressionEqualityComparer<T> : EqualityComparer<T>
{
    private Func<T, T, bool> equals;
    public ExpressionEqualityComparer(
        Expression<Func<T, T, bool>> equals)
    {
        this.equals = equals.Compile();
    }

    public override bool Equals(T x, T y)
    {
        return equals(x, y);
    }

    public override int GetHashCode(T obj)
    {
        return base.GetHashCode();
    }
}

This allows you to call Distinct with an expression as a parameter which is used to evaluate equality rather than requiring you to create a custom comparer object every time. It calls its own GetHashCode() instead of the objects in order to ensure that different instances will still evaluate through the equality comparer. Here is an example of the usage.

Example[] c1 = new Example[] { 
    new Example { Id = 1, Name = "one" }, 
    new Example { Id = 2, Name = "two" } };
Example[] c2 = new Example[] { 
    new Example { Id = 2, Name = "two" }, 
    new Example { Id = 3, Name = "three" } };

var c3 = c1.Concat(c2).Distinct((e1, e2) => e1.Name == e2.Name);