Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Omer van Kloeten's Facebook profile

Get Firefox

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

November 2007 - Posts

Linked List Insertion Capable of Surviving Abnormal Termination

I just finished a short conversation with Aaron Randall from London who used the little Windows Live Messenger Flash application in my sidebar (oh, how I love thee, Internets) to ask me a question he had about linked lists after reading one of my posts:

"I am trying to understand the data structure for a doubly-linked list. I wanted to see if there was any way of having a data structure that could survive things like hardware failure (the computer can go down during updating a doubly-linked list without having its node broken/separated)"

His question was specifically for insertion and it got me thinking. The problem here is that given three nodes (inserting B between A and C), there are four steps to insertion into a doubly linked list, none of which has to be made in any specific order: Update A's forward link to B, update B's forward link to C, update B's backward link to A and also update C's backward link to B.

Given an abnormal termination, one has to be able to resume operation with the assumption that the data's integrity remains. This means that no matter during which phase of the insertion the computer fails, you will be able to resume normal work when it returns to its normal state.

RuggedLinkedListNodeI came up with a solution in which you would have a two-phase commit using six steps:

  1. A's FutureNext pointer is set to point to B. Commit to disk.
  2. B's Next pointer is set to point to C.
  3. A's Next pointer is copied from its FutureNext pointer.
  4. C's Previous pointer is set to point to B.
  5. B's Previous pointer is set to point to A.
  6. A's FutureNext pointer is nullified. Commit to disk.

The first step is the first phase in the two-phase commit, in which the link to the new node is established. Should a failure occur at any time after the first stage's completion, a simple batch application scanning nodes for a non-null FutureNext pointer and completing the remaining five steps would be sufficient to keep data integrity.

Hope this helps, Aaron. :)

WPF's Use of Partial Classes' Access Modifiers

While writing a reusable component for a client, I placed it in a different assembly and began to change all of the non-public classes' access modifiers to internal. Building the project, I received the following error:

error CS0262: Partial declarations of 'ClassName' have conflicting accessibility modifiers.

The two conflicting source files were my original ClassName.xaml.cs file and the automatically generated ClassName.g.cs file. It appeared that the ClassName.g.cs stated that my class was still public. Here are my types:

MyWindow.cs:

internal partial class MyWindow : Window

MyWindow.g.cs:

public partial class MyWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector

After a bit of digging, I found the culprit. Apparently, when you have a non-public modifier, you have to qualify your element with the x:ClassModifier attribute. In my case, the code looked like this:

<Window x:Class="MyNamepsace.MyWindow" x:ClassModifier="internal"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

All works and all is well in the world... Well, not everything. You see, this is both ugly and easily avoidable.

Why is this ugly? The x:ClassModifier attribute clearly states that the string passed to it:

[...] varies, depending on the code-behind programming language being used.

This makes your XAML file's correctness bound to the language the code-behind is written in, rather than be language-neutral and CLR-centric.

Another assumption made by WPF's design team was that the default value is public, which means every type is added to the list of publicly visible types in your assembly by default. If you write a client application, this may not be of any concern to you, but if you write reusable components, this is a highly important design decision. On the other hand, this might just be me nitpicking.

How could this be avoided? As you may well know, when defining a partial class, the definition is collected from every part, glued together, and only then are default behaviors appended and the code is compiled. This means that if you fail to write an access modifier in one file and only write it in another, there will be an access modifier, but on the other hand, writing two conflicting modifiers will cause a compiler error.

This means that the only thing needed to be done to avoid the entire need for the x:ClassModifier attribute was to emit generated code with no access modifier and have the code-behind implicitly take control of it.

Final words: This can also be found in base class references, where all partial classes are marked as deriving from the same base type, as you can see in the examples above. Then again, this may just be a safeguard against people messing with their base classes... who knows.
I hope this would go away in the next version of the designer. Is anyone listening?

Three Ways To Create Dynamic Menus

There are quite a few sources about how to create dynamic menus (menus that are not embedded in XAML or code, but rather loaded from an external file):

  1. Loose XAML - Using the XamlReader, one can load an external, non-pre-compiled fragment of XAML, much like the one presented here:
    <MenuItem
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    Header="_Simple">
    <MenuItem Header="1" />
    <MenuItem Header="2" />
    <MenuItem Header="3" />
    </
    MenuItem>
    The above fragment will then be loaded into the menu like so:
    using (FileStream looseXamlFile = File.OpenRead("Loose.xaml"))
    {
    this.mainMenu.Items.Insert(0,
    (MenuItem)XamlReader.Load(looseXamlFile));
    }
    And on the window, it will look like this:

    simple

    This is a very useful thing and you can read more about this method on Tamir's weblog.
    However, this way, you are bound to the elements of the WPF schema and all errors that would have occurred in the past during compile-time, will now occur during run-time. These presents a hardship for the developer. The bigger problem is what happens when receiving the items for the menu from a different source, such as a list you wish to bind to, in which case, you simply can't use Loose XAML.
  2. Data Templates - This way is the most intuitive way to bind a list of items or, better yet, an unary tree of items to a GUI representation of them. For instance, we have a list of Item objects (a simple class with one property - Value) and wish to bind them to menu items.
    <MenuItem x:Name="dataTemplateMenu" Header="_Data Template" >
    <MenuItem.Resources>
    <DataTemplate DataType="{x:Type local:Item}">
    <MenuItem Header="{Binding Path=Value}" />
    </DataTemplate>
    </MenuItem.Resources>
    </
    MenuItem>
    The XAML described here takes each Item and represents it using a MenuItem. To load a list into the menu, we simply call:
    dataTemplateMenu.ItemsSource = itemArray;
    After this call, all of the items will have MenuItems created for them and will look like this:

    data.templates 

    Very nice, but something is wrong here. Yes, the items are extremely large. Hovering over one reveals that we have something inside that menu:

    data.templates.hover

    Hum. That looks familiar. It's the same size as a normal MenuItem... Oh, wait, that's because it really is one. This is because when you create a Data Template, the items that enter the tree are actually your user-defined objects (in this case, the Item class). Before applying the template, the menu item asks the object about to be inserted into it whether it can be visually displayed. Because Item has no visual representation, the process creates a MenuItem to hold it, thus creating two menu items (the one automatically created and the one created using the Data Template).
  3. Item Container Style - So after two ways that didn't work well for us, the one that will is the MenuItem's ItemContainerStyle. This way, all you do is simply define a style for all of the menu items that will be placed under a certain menu item and use binding to bind those items to the values of your objects' properties:
    <MenuItem x:Name="itemContainerStyleMenu" Header="_Item Container Style">
    <MenuItem.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}">
    <Setter Property="Header" Value="{Binding Path=Value}" />
    </Style>
    </MenuItem.ItemContainerStyle>
    </
    MenuItem>

    Then you set the source:
    itemContainerStyleMenu.ItemsSource = itemArray;
    and presto:

    item.container.style

    We now have what we needed.

    Extra: Recursive hierarchy could also be achieved using:
    1. Placing the style in the resources of a window, the application, etc. with a key.
    2. A setter of ItemsSource that binds to the collection of child items.
    3. A setter of ItemContainerStyle that will point to the style's key.

The source for this article is available here.

Pet peeve: Why would you change the "&Name" mnemonic notation from Win32 to something that is not better ("_Name" in WPF), only different? I'd have gone with a MenuItem.Mnemonic property that receives a character and doesn't pass validation if the Text property doesn't contain that character. If you're going to change, you might as well change for a reason.

Posted: Nov 14 2007, 08:47 AM by Omer van Kloeten | with 12 comment(s)
Filed under:
Simplifying the WeakEvent Pattern

Building on the work started by William Kempf, I set out to make using the WeakEvent Pattern simpler and more readable. My intention was to make sure the user would have to write the minimum amount of code to use it, in order to draw it closer to the more intuitive model of strongly referenced events. To use, download the project, reference it and go over the following steps:

Using the Model

  1. Create an EventManager. This class will be used by the mechanism internally to register to the object's strongly referenced event itself. Note that IMyEvent is simply an interface containing the event's description and can therefore be replaced with the type exposing the event itself, rather than a special interface. Also note that the EventManager inherits from WeakEventManagerBase with itself and the type it uses as generic parameters.
    public sealed class MyEventManager
    : WeakEventManagerBase<MyEventManager, IMyEvent>
    {
    protected override void StartListeningTo(IMyEvent source)
    {
    source.MyEvent += DeliverEvent;
    }

    protected override void StopListeningTo(IMyEvent source)
    {
    source.MyEvent -= DeliverEvent;
    }
    }
  2. Add a WeakHandler field to the type containing the method and reference that same method, much like a simple delegate instance. This is done to keep the WeakHandler's reference alive for the duration the containing type lives.
    private readonly WeakHandler<MyEventManager, MyEventArgs> handler;

    ...

    this
    .handler = new WeakHandler<MyEventManager, MyEventArgs>(this.listener_MyEvent);
  3. Register to the object's event. Note that all types are inferred, except for the type specified as the provider of the event.
    handler.ListenTo(sender as IMyEvent);
  4. Raising the event will now call the referenced method for as long as the type containing the handler lives.

Points of Interest Behind the Scenes

  1. The WeakHandler's ListenTo and StopListeningTo methods are extension methods so that you wouldn't have to specify TSource too when creating the WeakHandler (in the example above - IMyEvent).
  2. The WeakHandler's constructor receives EventHandler<TArgs> so that you could simply specify a method and it would implicitly be converted to the delegate type, instead of having to use the whole delegate syntax.
  3. A WeakHandler can be assigned 0..n methods, using its Append and Remove methods. The intuitive comparison to null (or other WeakHandlers) is also available to determine if there are methods referenced by the instance, but calls to methods on the instance will not raise a NullReferenceException.
  4. All methods placed in the WeakHandler's list must be instance methods (there is no reason to use a WeakHandler with static methods) that were declared in the type the WeakHandler was declared on. This is to prevent a situation where object A declares a WeakHandler, but references a method on object B, causing object B to live at least until object A is dereferenced, dereferencing the WeakHandler field.

[Update: Within minutes of posting this, the post has been linked to from the Microsoft Israel homepage. I am truly honored.]

Posted: Nov 12 2007, 09:42 AM by Omer van Kloeten | with 1 comment(s)
Filed under:
Multi-binding inside Multi-binding

You can't.

Well, that was the short version of things. Now comes the long one.

Take the following piece of XAML:

<Label x:Name="color">
    <MultiBinding Converter="{StaticResource luminanceConverter}">
        <Binding Path="AddedLuminance" />
        <MultiBinding Converter="{StaticResource rgbToCmyk}">
            <Binding Path="R" />
            <Binding Path="G" />
            <Binding Path="B" />
        </MultiBinding>
    </MultiBinding>
</Label>

The above fictional piece of code takes a color's RGB (Red/Green/Blue) values, converts it to a CMYK (Cyan/Magenta/Yellow/Black) representation and then adds luminance. This is all done to display a value for the user which the application doesn't need to compute on its own for the sake of logic. It's also useful, because whenever AddedLuminance, R, G or B change, the value is recalculated.

The only problem with the above code is that it doesn't work, since apparently, you can't place a MultiBinding inside a MultiBinding.

I guess I'll have to wait for the next version for that one...

Posted: Nov 12 2007, 08:19 AM by Omer van Kloeten | with 5 comment(s)
Filed under:
Automatically Filtering a ComboBox in WPF

Haven't you always wanted to use a combo box like the one in Start menu's Run dialog?

afcb

A client asked me for the exact same thing, and now you can download it from here too. The Automatically Filtered ComboBox inherits from the original ComboBox and adds the auto-filtering, along with an ability to filter while ignoring case. The IsTextSearchEnabled property already allows you to do all this (and the use of which is therefore supported), but it doesn't allow for case sensitivity and filtration of the results.

Interesting bits about the code:

/// <summary>
///
Gets the text box in charge of the editable portion of the combo box.
/// </summary>
protected TextBox EditableTextBox
{
get
{
return ((TextBox)base.GetTemplateChild("PART_EditableTextBox"));
}
}

The above section of code lets you access the text box that sits at the top of the combo box. We use this text box to get the selection (just like what we could get from a ComboBox in Windows Forms using the SelectedText property).

ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
view.Filter += this.FilterPredicate;
ICollectionView view = CollectionViewSource.GetDefaultView(this.ItemsSource);
view.Refresh();

The above two piece of code use the CollectionViewSource class to create a filter on the default view of the ItemsSource. This mechanism is used internally by the original ComboBox to filter and/or sort the source of the items. I'm a bit baffled by why the WPF team would decide on only using a single, global view for the items' source, rather than a model like the one presented in ADO.NET using the DataView on DataTables. Thanks to Tomer for  the heads up on that one.

private bool FilterPredicate(object value)
{
// We don't like nulls.
if (value == null)
return false;

// If there is no text, there's no reason to filter.
if (this.Text.Length == 0)
return true;

string prefix = this.Text;

// If the end of the text is selected, do not mind it.
if (this.length > 0 && this.start + this.length == this.Text.Length)
{
prefix = prefix.Substring(0, this.start);
}

return value.ToString()
.StartsWith(prefix, !this.IsCaseSensitive, CultureInfo.CurrentCulture);
}

The above is the predicate for filtering. As you can see, only items that start with the text already in the box are kept in the list (Yes, value.ToString() is not a correct implementation; I will change it in the future). Notice that if the selection is on the end of the text, we do not use that part for the search, since the very next character pressed will replace the selected text and we would like to show the possible results for such a keystroke.

As I am still in the process of getting used to WPF, there is still much to learn. I would gladly accept any comment you may have about the means to the end and also on my style and conventions. You always have something new to learn :)

Quickly Find a Type's Assembly and Namespace

Sometimes you want to know a type's exact namespace and assembly (for instance, in order to find it in Reflector). Instead of waiting forever for Visual Studio's Help to load (that is, if you haven't already disabled F1) or searching Google for the answer, simply click on Go To Definition (or F12 in the default C# scheme), and hover over the meta data file's tab page header.

Referencing Nested Types With x:Type

If you have a nested type, VS2008 beta 2's designer will tell you that you can't reference it using x:Type, stating that "Type X was not found."

However, this apparently does work, but only when using the CLI syntax for nested types, like this:

{x:Type xmlnamespace:TypeName+NestedTypeName}

Cider will continue to warn that the type was not found, but it will work.

More Posts