Path Data, Prefixes and Known Colors

September 24, 2008

I previously wrote about some fixes I made to the Baml Viewer addin for Reflector. As always happens with these kinds of things, one thing led to another and I ended up finding a few more issues and felt compelled to debug/fix them. Tonight I checked in a few more changes:

  • Xml Namespace Mapping Prefixes – While debugging the first set of issues I noticed that the xml namespace mappings weren’t being included. So when a type name was displayed it excluded the prefix – e.g. ButtonChrome instead of theme:ButtonChrome.
  • PathData – A reader posted a comment mentioning that path data was always displayed as “???”. I guess this was a placeholder but the functionality was never implemented. This was a bit involved but the baml viewer will now display the path markup notation for the path data geometry. Note, the original value won’t necessarily round trip to the exact original markup but the resulting path should be the same. So if you used m (for a relative move) instead of M (for an absolute move), you may notice that M is output instead. The absolute points were likely calculated when the original path markup was parsed so the output will contain M (i.e. absolute offsets) and the points will be absolute instead of relative.
  • Known Colors – Solid color brush values are handled specially by the baml compiler. Previously the only known color that was handled was transparent. All other known colors were output using their ARGB values – incidentally without the leading # so if you tried to use the xaml it would give you an error. The baml viewer will now map these known colors back to the known color name.

I hope I don’t find any more issues :-) but if you find something interesting I may try to look into it as time allows.

Baml Viewer Fixes

September 23, 2008

I use Reflector everyday and I’ve always wanted to give something back to Lutz for making this great utility. One of the things I use within Reflector is the BamlViewer addin but it had some problems correctly displaying all the baml I’ve tried to view. In some cases it even crashed while parsing the resource.

Since the code was in CodePlex, I decided to try and fix these issues myself. Having done so I wanted to get these incorporated into the addin so someone else encountering the same issues could get the fixes. In order to check in these changes though you have to be a developer on the project so I contacted Lutz to see if he wanted to check them in. Reflector has recently been handed over to RedGate Software so he referred me to James Moore who aside from being a coordinator on that project also heads up the .Net developer tools division at RedGate. He kindly agreed to add me on as a developer to that project so this morning I checked in my fixes.

One more change that I’d like to make is that I’d like to get it to support displaying the xml namespace prefix. I have made some changes locally to address this so when I get a chance I’ll test it out more thoroughly, clean it up and get that checked in as well.

Accessing Enum members in Xaml

September 19, 2008

Sacha posted a nice article on how to get friendly names for enums. I’ve seen this kind of approach before using the Description attribute. One of the things that he does though is create a static method to obtain the list of enum members. You can however actually get the list with pure xaml as follows:

<ObjectDataProvider MethodName=”GetValues”
               ObjectType=”{x:Type sys:Enum}”
               x:Key=”DayOfWeekValues”>
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName=”sys:DayOfWeek” />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

And then you can wire it up to a combobox:

<ComboBox x:Name=”cboDayOfWeek” 
  ItemsSource=”{Binding Source={StaticResource DayOfWeekValues}}” />

The only problem though is that its verbose (as well as a little heavy for something that is just meant to return a static list). When I write a test app for a control I’m writing I tend to end up having a lot of these and it ends up cluttering the xaml. I was thinking about it and an alternative approach which combines the above as well as takes Sacha’s issue into account would be to write a markup extension that combines all this together.

    /// <summary>
    /// Markup extension that provides a list of the members of a given enum.
    /// </summary>
    public class EnumListExtension : MarkupExtension
    {
        #region Member Variables

 

        private Type _enumType;
        private bool _asString;

 

        #endregion //Member Variables

 

        #region Constructor
        /// <summary>
        /// Initializes a new <see cref=”EnumListExtension”/>
        /// </summary>
        public EnumListExtension()
        {
        }

 

        /// <summary>
        /// Initializes a new <see cref=”EnumListExtension”/>
        /// </summary>
        /// <param name=”enumType”>The type of enum whose members are to be returned.</param>
        public EnumListExtension(Type enumType)
        {
            this.EnumType = enumType;
        }
        #endregion //Constructor

 

        #region Properties
        /// <summary>
        /// Gets/sets the type of enumeration to return
        /// </summary>
        public Type EnumType
        {
            get { return this._enumType; }
            set
            {
                if (value != this._enumType)
                {
                    if (null != value)
                    {
                        Type enumType = Nullable.GetUnderlyingType(value) ?? value;

 

                        if (enumType.IsEnum == false)
                            throw new ArgumentException(“Type must be for an Enum.”);
                    }

 

                    this._enumType = value;
                }
            }
        }

 

        /// <summary>
        /// Gets/sets a value indicating whether to display the enumeration members as strings using the Description on the member if available.
        /// </summary>
        public bool AsString
        {
            get { return this._asString; }
            set { this._asString = value; }
        }
        #endregion //Properties

 

        #region Base class overrides
        /// <summary>
        /// Returns a list of items for the specified <see cref=”EnumType”/>. Depending on the <see cref=”AsString”/> property, the
        /// items will be returned as the enum member value or as strings.
        /// </summary>
        /// <param name=”serviceProvider”>An object that provides services for the markup extension.</param>
        /// <returns></returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (null == this._enumType)
                throw new InvalidOperationException(“The EnumType must be specified.”);

 

            Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
            Array enumValues = Enum.GetValues(actualEnumType);

 

            // if the object itself is to be returned then just use GetValues
            //
            if (this._asString == false)
            {
                if (actualEnumType == this._enumType)
                    return enumValues;

 

                Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
                enumValues.CopyTo(tempArray, 1);
                return tempArray;
            }

 

            List<string> items = new List<string>();

 

            if (actualEnumType != this._enumType)
                items.Add(null);

 

            // otherwise we must process the list
            foreach (object item in Enum.GetValues(this._enumType))
            {
                string itemString = item.ToString();
                FieldInfo field = this._enumType.GetField(itemString);
                object[] attribs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);

 

                if (null != attribs && attribs.Length > 0)
                    itemString = ((DescriptionAttribute)attribs[0]).Description;

 

                items.Add(itemString);
            }

 

            return items.ToArray();
        }
        #endregion //Base class overrides
    }

The markup extension has a Type property that can be used to indicate the enum type for which it should obtain the list. If you want it to return strings as opposed to the actual enum values and take the Description attribute into account, you just set the AsString property to true. So now the hookup is much simpler:

<ComboBox x:Name=”cboDayOfWeek”
  ItemsSource=”{Binding Source={local:EnumList {x:Type sys:DayOfWeek}}}” />

 

Note: I updated this code to use the DisplayName instead of the DescriptionAttribute after Mike Brown correctly pointed out that DisplayName is a more appropriate attribute for this scenario.

Updated: I reverted back to using the Description attribute since the DisplayNameAttribute’s usage does not allow its use on Fields. Thanks to John for pointing this out.

Hit Testing in WPF

September 16, 2008

There’s a lot that can be written about hit testing in WPF so I won’t try to cover everything but there are some subtleties that bear mentioning. A common issue that I see people encounter is that fact that the default background for many elements is null and null (at least in terms of hit testing) is treated separately from Transparent. Take the following snippet for example.

<Page
  <Page.Resources>
      <Style TargetType=”{x:Type Grid}”>
          <Style.Triggers>
              <Trigger Property=”IsMouseOver” Value=”True”>
                  <Setter Property=”Background” Value=”Yellow” />
              </Trigger>
          </Style.Triggers>
      </Style>
  </Page.Resources>
  <Grid> 
      <TextBlock
          Background=”Red”
          Text=”Test”
          TextAlignment=”Center”
          HorizontalAlignment=”Center”
          VerticalAlignment=”Center”
          Width=”100″ />
  </Grid>
</Page>
 
There is a trigger for the Grid that changes its Background to yellow when IsMouseOver is true. If you run this and move the mouse over the Grid without going over the TextBlock, the background of the Grid will remain the same. However, once you move the mouse over the TextBlock, the background of the Grid will change. Then something interesting happens – once the mouse leaves the TextBlock buts remains within the Grid the background of the Grid will remain Yellow. This basically comes back to the fact that the default background of the Grid is null. If you were to add a setter to the Style set the Background to Transparent (don’t set it explicitly or the mouse over won’t work since you’ll be providing a local value which will take predence over the style trigger) then the background would have changed to yellow as soon as the mouse entered the Grid.
 
     <Style TargetType=”{x:Type Grid}”>
          <Setter Property=”Background” Value=”Transparent” />
          <Style.Triggers>
              <Trigger Property=”IsMouseOver” Value=”True”>
                  <Setter Property=”Background” Value=”Yellow” />
              </Trigger>
          </Style.Triggers>
      </Style>

An interesting thing to note here is that the TextBlock doesn’t have this issue. So if you were to modify the original source and explicitly set the TextBlock’s Background to {x:Null} or not set it (since it defaults to null) and rerun the original test, you will find that the background of the Grid still changes to yellow when you go over the TextBlock (and not just when you go over the actual rendered text). The reason that this occurs is because the TextBlock explicitly overrides UIElement.HitTestCore and returns true if the specified point is within its rect. There are actually a few other elements that do this as well including ScrollViewer and InkCanvas. For TextBlock I think the main reason is that you probably don’t want the IsMouseOver changing as you move across the text in between characters but this is just a guess.

Another property that affects hit testing in WPF is the IsHitTestVisible. This property determines if the element and its descendants should be hidden from hit testing. I phrased it in this way because if you set IsHitTestVisible to false on the Grid in the sample above, it wouldn’t matter what the IsHitTestVisible state of the descendants is set to since the hit test that is performed to evaluate the IsMouseOver state is going to skip the Grid element and not traverse into its children.

Next time I’ll get to the real reason I started writing about hit testing today – to discuss the methods available for performing hit testing in code.

Getting Started with iTunes

July 19, 2008

I’ve been thinking about getting an iPod for a while but I’ve held off for one reason or another. Well my wife got me an iPod Nano for my birthday recently so I’ve been digging through my cd’s – many of which still haven’t been unpacked since we moved into the house a couple of years ago.

One of the first things I had to do was to install iTunes. I try to be careful about the applications I install on my system. I didn’t have any worries about malware or anything like that but one of the requirements for iTunes is to install QuickTime. I had gotten a bad taste from previous experiences using QuickTime so I was looking to avoid installing that if possible. Luckily I found some posts like this one that talk about using a QuickTime alternative with iTunes.

One of the things I really liked about the iPod was the cover flow display – both within iTunes but also within the iPod itself. The problem that I’ve found though (and apparantly others have as well) is that iTunes sometimes gets the wrong album artwork or fails to find the artwork. I searched around to try and find a solution and thought I had found one named iTunes Art Importer but most of the links I found were broken. When I had finally found the application and installed it, it didn’t work – every search I tried returned right away with a message that no matches were found. I did some more searching to try and find another utility when I came across another page where Garett Harnish modified iTunes Art Importer to work again – apparantly the original version was written against an older version of the Amazon web service.

I’m sure there are lots of utilities out there for iTunes but this is all I’ve needed so far. There’s even an SDK for it.

ElementName Binding In ToolTips (Borrowing a NameScope)

July 17, 2008

I had previously seen mention of the limitation that you cannot use ElementName binding within a ToolTip but I never bothered to investigate it since I didn’t have need to use it. Yesterday Josh asked me about it so I decided to look into it further. I’m going to deal with ToolTip here since that was the one he asked me about but I believe the same technique could apply to ContextMenu.

First let’s take a look at the various ways you can define a tooltip that uses ElementName in a binding and see which work.

<Window.Resources>
    <!– Shared tooltip –>
    <ToolTip x:Key=”sharedTT”>
        <TextBlock Text=”{Binding ElementName=txt, 
           Path=Text}” />
    </ToolTip>
</Window.Resources>
<DockPanel>
    <TextBox Text=”This is the tooltip text” 
            x:Name=”txt” DockPanel.Dock=”Top” />
   
    <!– 1 – explicitly provide a tooltip instance where
        the content is bound –>
    <Button Content=”Explicit ToolTip” DockPanel.Dock=”Top” >
        <ToolTipService.ToolTip>
            <ToolTip Content=”{Binding ElementName=txt, 
               Path=Text}” />
        </ToolTipService.ToolTip>
    </Button>
   
    <!– 2 – Set the tooltip to a binding –>
    <Button DockPanel.Dock=”Top” Content=”Binding”
           ToolTipService.ToolTip=”{Binding ElementName=txt, 
           Path=Text}”/>

 

    <!– 3- Set the tooltip to an object that tries to
        bind to an element outside the tooltip –>
    <Button DockPanel.Dock=”Top” Content=”Element ToolTip”>
        <ToolTipService.ToolTip>
            <TextBlock Text=”{Binding ElementName=txt, 
               Path=Text}” />
        </ToolTipService.ToolTip>
    </Button>

 

    <!– 4- Set the tooltip to an element that tries to bind
        to the value of another element within the tooltip –>
    <Button DockPanel.Dock=”Top” >
        <ToolTipService.ToolTip>
            <StackPanel>
                <TextBlock x:Name=”ttText” Text=”Foo” />
                <TextBlock Text=”{Binding ElementName=ttText, 
                   Path=Text}” />
            </StackPanel>
        </ToolTipService.ToolTip>
        Normal ToolTip
    </Button>

 

    <!– 5 – Bind to a ToolTip in Resources –>
    <Button DockPanel.Dock=”Top” 
           Content=”SharedResource ToolTip”
           ToolTipService.ToolTip=”{StaticResource sharedTT}”/>
</DockPanel>

Of all of these the only one that actually works is #2 where the ToolTip property is set to a Binding instance. Suprisingly, at least to me, is that even #4 where we are trying to bind to another element within the tooltip itself does not work.

In order to understand why these aren’t working, we need to understand how ElementName binding works. Basically, when an ElementName is used in a binding, the NameScope of the target object is used to locate the element with the specified name. If that element doesn’t have a NameScope specifically on it, the FrameworkElement.FindScope method continues up the logical tree and falls back to the inheritance context if there is no logical parent. The name scope is the object in which all named objects have been registered. So in this example, there is a NameScope created for the Window itself implicitly. Other objects also provide a namescope to prevent conflicts between names – e.g. ControlTemplate and Style. Actually in those cases, the objects themselves implement INameScope.

The ToolTip however is not part of the logical nor visual tree of the element on which it is being set. Instead, it is just the value of a property and as such it doesn’t have a way to reach the NameScope of the Window in which it was created. The reason that #2 worked is because we just set the value of the ToolTip property to a binding. Since that is a property set directly on the element, that binding has access to the namescope just as you can use in a binding for any other dependency property on the element.

So the issue we have to overcome is how to provide a way for the ToolTip to get to the NameScope of the Window. My solution was to set the NameScope of the ToolTip to a custom INameScope implementation that would get to the NameScope of the element for which the ToolTip was being used. To accomplish this, I defined a new attached property named BindableToolTip. When set, it would set the NameScope property of the tooltip (and create a tooltip if the value wasn’t a tooltip instance such as the case where you are just providing the elements that make up the content of the tooltip) to my custom INameScope implementation that would “borrow” the namescope of the element on which the tooltip was being set. I then set the real ToolTipService.ToolTip property to that tooltip instance.

I did hit one glitch along the way. The BamlRecordReader class which is used to process the compiled baml uses a stack to manage the namescopes it encounters. By the time that the BindableToolTip property change is invoked, the BamlRecordReader has already processed the ToolTip instance (through its PushContext method). So when it gets to the point where it wants to clean up its namescope stack (in its PopContext method), it finds that the tooltip now has a namescope and tries to pop an item off its stack which results in an exception because it tries to pop off more items then it pushed. To get around this, I remove the namescope from the tooltip in the Initialized event of the tooltip.

To use the new functionality, you would just replace any place you are setting the ToolTip property with the BindableToolTip property. After doing so with the sample above, every case now works. I’ve attached the sample project that defines and uses this new attached property.

Who set the DataContext?

July 14, 2008

In the course of the last month or so, several people have asked why the DataContext that they set on the form level wasn’t carried down deeper into their element tree. Since I haven’t seen any documentation going into this I’d like to go over when/why the DataContext may be explicitly set in the WPF framework.

The DataContext is an inherited property defined on FrameworkElement and on FrameworkContextElement (the latter is actually an AddOwner of the former but I’ll discuss AddOwner another day). Suffice it to say that if you set the DataContext on an element, it should/will get inherited by its descendant elements. So naturally some people will assume that if they set it on their Window/Page, that all elements within that Window/Page will get that DataContext value. Afterall they are not setting it anywhere else. Well, that is the problem. While they may not be setting it, the WPF framework does in certain situations and if you look at it you can understand why. So if anything, including within the WPF framework itself, sets the DataContext on one of the descandants of that Window/Page, then all its descandants will get its locally set DataContext instead of the one set on one of its ancestors.

Ok so when will the WPF framework actually set the DataContext? There are actually two situations that I know of in which a class in the WPF framework will set the DataContext and both relate to when it automatically generates an element for you. One is in the ItemsControl – or more accurately by the ItemContainerGenerator of an ItemsControl when a container element is generated for an element in the list. The other is in the ContentPresenter when an element is generated for its Content (e.g. based on a DataTemplate). This makes perfect sense since after all the element generated for the ItemsControl and the elements within the DataTemplate need to get access to the thing that that element is supposed to represent.

The reason this may not be noticed in normal usage is because inherited properties prefer the logical tree and therefore can “skip” over the elements that have had their DataContext set further up the visual tree between it and its logical parent. So for example, if you were to put a TextBlock into a ListBox:

    <Grid DataContext=”Foo”>
        <ListBox>
            <TextBlock Text=”{Binding}” />
        </ListBox>
    </Grid> 

At runtime, a ListBoxItem would be created to contain the TextBlock within the ListBox. The DataContext of that ListBoxItem is the TextBlock (i.e. the object it represents within the listbox). However, the DataContext of the TextBlock ends up being Foo since that is the DataContext of its logical parent (i.e. the ListBox) and would show “Foo” as its Text.

If the TextBlock were not a logical child of the listbox (e.g. if it were added to the listbox via its ItemsSource) then it would inherit the DataContext of its visual parent – which ultimately would come from the ListBoxItem.

    <Grid DataContext=”Foo”>
        <Grid.Resources>
            <x:Array x:Key=”arr” Type=”sys:Object”>
                <TextBlock Text=”{Binding}” />
            </x:Array>
        </Grid.Resources>
        <ListBox ItemsSource=”{StaticResource arr}” />
    </Grid> 

In this case, the TextBlock would have a Text value of “System.Windows.Control.TextBlock” – the ToString of the TextBlock itself since it is the DataContext of the ListBoxItem and therefore that is its DataContext.

PropertyDescriptor AddValueChanged Alternative

April 7, 2008

I’ve been meaning to write about this for a while since I’ve seen this approach mentioned lots of times on the newsgroups but have seen no mentions about the caveats. Just today I saw the same problem in some code from one of the disciples. The scenario is that you want to know when the value of a dependency property changes but you don’t have a one to one relationship with the object. For example, you have a list of items and you want to know when the IsSelected property of an item has changed.

The solution that I have seen given for this is to get to the PropertyDescriptor and use its AddValueChanged method to provide an EventHandler to receive a notification when the property has changed. Sometimes, the reply will mention/use DependencyPropertyDescriptor directly but its the same thing since that is just a derived PropertyDescriptor that provides additional information about the underlying DependencyProperty it represents. You  can get to this property descriptor in a few ways but the most common are to get it from the TypeDescriptor.GetProperties method or using the DependencyPropertyDescriptor.FromProperty.

The issue with this approach is that it will root your object so it will never get collected by the GC. There have been plenty of discussions about how hooking events (particularly static events) can root your object so I won’t go into great detail there. While it does not seem that you are hooking a static event in this case, in essence you are. When you add a handler to a property descriptor, that property descriptor stores the delegate in a hashtable keyed by the object whose property you are hooking. A delegate/handler is basically a pointer to a method on an object (or no object if its for a static method) so that means the property descriptor has a reference to your object as well as the object whose value you are watching (since that is the key into the hashtable). The property descriptors themselves are cached statically so the hashtable is kept around and therefore your object and the one you are watching are as well.

I personally like to use the Scitech memory profiler (or you can use the Microsoft CLR Profiler) when debugging memory leak issues but you can see the issue manifest itself pretty easily in this case. First we’ll do a benchmark to make sure that we can check whether the object was collected.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

If you run this code and check isAlive, you will see that it returns false indicating that the ListBoxItem was not referenced and was able to be collected. Now let’s try using the AddValueChanged method.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(ListBoxItem))["IsSelected"];
// the following yields the same pd
//PropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ListBoxItem.IsSelectedProperty, typeof(ListBoxItem));
prop.AddValueChanged(i, new EventHandler(this.OnValueChanged));
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

This time isAlive returns true because the property descriptor is maintaining a reference to the ListBoxItem. Now, let’s try an alternative approach that involves creating a helper class to listen for the property change.

ListBoxItem i = new ListBoxItem();
WeakReference wr = new WeakReference(i);
PropertyChangeNotifier notifier = new PropertyChangeNotifier(i, “IsSelected”);
notifier.ValueChanged += new EventHandler(OnValueChanged);
i = null;
GC.Collect();
bool isAlive = wr.IsAlive;

In this case isAlive is false indicating that the object can be collected even though we’re still maintaining an explicit reference to the notifier. The implementation for the class – PropertyChangeNotifier – is listed below. The class is basically a simple DependencyObject that exposes 2 properties – Value returns the value of the property of the object that it is watching and PropertySource returns the object whose property it is watching. The constructor for the object takes the object whose property is to be watched for changes and the property that should be watched. This class takes advantage of the fact that bindings use weak references to manage associations so the class will not root the object who property changes it is watching. It also uses a WeakReference to maintain a reference to the object whose property it is watching without rooting that object. In this way, you can maintain a collection of these objects so that you can unhook the property change later without worrying about that collection rooting the object whose values you are watching.

public sealed class PropertyChangeNotifier :
DependencyObject,
IDisposable
{
#region Member Variables
private WeakReference _propertySource;
#endregion // Member Variables
 
#region Constructor
public PropertyChangeNotifier(DependencyObject propertySource, string path)
: this(propertySource, new PropertyPath(path))
{
}
public PropertyChangeNotifier(DependencyObject propertySource, DependencyProperty property)
: this(propertySource, new PropertyPath(property))
{
}
public PropertyChangeNotifier(DependencyObject propertySource, PropertyPath property)
{
if (null == propertySource)
throw new ArgumentNullException(“propertySource”);
if (null == property)
throw new ArgumentNullException(“property”);
this._propertySource = new WeakReference(propertySource);
Binding binding = new Binding();
binding.Path = property;
binding.Mode = BindingMode.OneWay;
binding.Source = propertySource;
BindingOperations.SetBinding(this, ValueProperty, binding);
}
#endregion // Constructor
 
#region PropertySource
public DependencyObject PropertySource
{
get 
{
try
{
// note, it is possible that accessing the target property
// will result in an exception so i’ve wrapped this check
// in a try catch
return this._propertySource.IsAlive
? this._propertySource.Target as DependencyObject
: null;
}
catch
{
return null;
}
}
}
#endregion // PropertySource
 
#region Value
/// <summary>
/// Identifies the <see cref=”Value”/> dependency property
/// </summary>
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(“Value”,
typeof(object), typeof(PropertyChangeNotifier), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnPropertyChanged)));
 
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PropertyChangeNotifier notifier = (PropertyChangeNotifier)d;
if (null != notifier.ValueChanged)
notifier.ValueChanged(notifier, EventArgs.Empty);
}
 
/// <summary>
/// Returns/sets the value of the property
/// </summary>
/// <seealso cref=”ValueProperty”/>
[Description("Returns/sets the value of the property")]
[Category("Behavior")]
[Bindable(true)]
public object Value
{
get
{
return (object)this.GetValue(PropertyChangeNotifier.ValueProperty);
}
set
{
this.SetValue(PropertyChangeNotifier.ValueProperty, value);
}
}
#endregion //Value
 
#region Events
public event EventHandler ValueChanged;
#endregion // Events
 
#region IDisposable Members
public void Dispose()
{
BindingOperations.ClearBinding(this, ValueProperty);
}
#endregion
}

Another possible approach would be to implement your own derived WeakEventManager but I’ll leave that as an exercise for the reader. For those that choose to go this route, there is such a class – except its internal – in the PresentationFramework assembly.

SyncHashtable is not enumerable…

January 19, 2008

One of the things I really like about working on Mole is that I get to debug some obscure issues that I haven’t come across before. Today, Karl mentioned that there was an issue when dealing with collections – specifically with a synchronized hashtable. Mole was dealing with collections using one of the base collection interfaces – ICollection. He fixed the issue correctly by iterating the IDictionaryEnumerator you get from the IDictionary implementations of a hashtable but I wanted to see what was go on so I decided to look into this further.

The problem can be reproduced with the following snippet:

Hashtable ht = new Hashtable();

Hashtable syncedTable = Hashtable.Synchronized(ht);

IEnumerator enumerator = ((ICollection)syncedTable).GetEnumerator();

Or more likely it would be something like this:

Hashtable ht = new Hashtable();

Hashtable syncedTable = Hashtable.Synchronized(ht);

syncedTable.Add(“Foo”, “Bar”);

EnumerateCollection(syncedTable);

Where EnumerateCollection was something like the following:

private void EnumerateCollection(IEnumerable enumerable)

{

    foreach (object value in enumerable)

    {

        // do something

    }

}

I took at a look at MS’ code for the Hashtable class using Reflector and there is an obvious bug in their implementation. I did a quick internet search and it seems like people have been bitten by this same issue for a while so its hard to believe that it still exists within the framework today. In case anyone encounters the issue, I’ll explain what’s going on.

Hashtable implements the IDictionary interface which derives from ICollection and therefore IEnumerable. Both IDictionary and IEnumerable define a GetEnumerator method. For IDictionary this returns an IDictionaryEnumerator and for IEnumerable this returns an IEnumerator. Hashtable’s implementation of the IDictionary method is a public virtual GetEnumerator method. Its implementation of the IEnumerable method is an explicit implementation of the interface method.

e.g. IEnumerator IEnumerable.GetEnumerator();

The Hashtable class exposes a public static method named Synchronize that is supposed to take a hashtable and return a thread safe hashtable. There are actually flaws in the thread safety aspect of the implementation but that is another matter outside the issue we were dealing with. The Synchronize methods returns an instance of a private nested class named SyncHashtable which derives from Hashtable and is basically a thin wrapper around the Hashtable you pass to the Synchronize method. SyncHashtable overrides the virtual methods on the base Hashtable class and attempts to make dealing with the hashtable thread safe by using locks around edits.

SyncHashtable correctly overrides the public virtual GetEnumerator method and returns the IDictionaryEnumerator of the hashtable its wrapping. However, and herein lies the problem, it does not reimplement the IEnumerable.GetEnumerator method. Therefore, you get the base Hashtable’s implementation which returns an enumerator (HashtableEnumerator) for the SyncHashtable itself. This enumerator class assumes that the buckets member variable of the Hashtable it is to enumerate is non-null but the SyncHashtable specifically uses an overload of the Hashtable constructor that does not initialize this member (and others normally initialized for a Hashtable). It makes sense that they would not want to initialize these values since the SyncHashtable doesn’t store its own values – remember its just a thin wrapper around the Hashtable you provided to the Synchronize method – but then they should have reimplemented the IEnumerable.GetEnumerator method.

So if you’re writing any code that enumerates collections using the IEnumerable interface (directly or indirectly) with an object where you’re not in control of the source, you may want to consider dealing with the IDictionary’s enumerator first.

So you could fix the EnumeratorCollection method above as follows:

private void EnumerateCollection(IEnumerable enumerable)

{

    IEnumerator enumerator;

 

    // SyncHashtable has a bug where its IEnumerable

    // returns an enumerator whose ctor causes a crash.

    // instead, we can get around the problem using its 

    // IDictionary.GetEnumerator impl

    Hashtable table = enumerable as Hashtable;

 

    if (null != table)

        enumerator = table.GetEnumerator();

    else

        enumerator = enumerable.GetEnumerator();

 

    while (enumerator.MoveNext())

    {

        object value = enumerator.Current;

 

        // do something

    }

}

Compare Property & Field Values with Mole

January 15, 2008

As seems to happen with Mole, a suggestion quickly snowballed into a feature implementation. Mole now has the ability to save the members (properties/fields) of the selected element to an xml file and allow you to load that xml file back in to allow property comparison. This will be extremely helpful when you’re trying to debug a problem where something works for one element but doesn’t for another instance. There’s even an option to filter out members with the same value so you can see just the properties that differ.

 You can download the latest version here.

In addition, Karl has been posting some videos on YouTube that show how to use Mole. You can view those videos here.


Follow

Get every new post delivered to your Inbox.