Archive

Archive for 2008

A WPF File Selection control

March 14th, 2008

 fileselector

This is a pretty simple user control, which allows you to display a file dialog to open or save files. Its look can be easily adjusted, and it provides built-in truncation of the file string to a predefined length if necessary. Here’s the XAML for the above sample control:

<files:FileSelector x:Name="openFileSelector"
                    Mode="Open"
                    MaxDisplayLength="50"
                    Height="24"
                    Width="400" />

 

The TextBlock in the screenshot which displays the full file path was simply bound to the control’s FileName dependency property:

<TextBlock Text="{Binding ElementName=openFileSelector, Path=FileName}" />

 

The control does not provide too many extension or styling points – the idea is that you just copy it into your solution, adjust the styling of the control’s contents (Border, Button etc.) and be on your way. The source comes with a small sample project – enjoy 🙂

Download Control

Author: Categories: WPF Controls Tags: ,

New Blendables

March 6th, 2008

Just saw that Blendables have extended their portfolio of WPF controls. The stuff looks good, but unfortunately, their licensing scheme doesn’t:

A license is required for each machine utilizing the blendables controls. […] As we do not offer a deactivation method, if you must reactivate on a new developer machine you are allowed up to 3 activations. This is for the case of re-imaging or setting up a new developer machine. Once this limit is reached you must contact blendables support at […] to proceed with activation.

I must say, not purchasing their product is a no-brainer…

Author: Categories: WPF Controls Tags:

Preventing WPF TreeView items from being selected

March 6th, 2008

If you have a WPF TreeView control that shows nested data, and you don’t want the user to select nodes that contain child nodes, you can solve this declaratively as TreeViewItem provides all we need:

  • HasItems dependency property (bool)
  • Focusable dependency property (bool)

As both properties have the same type, you can use a binding expression (needs inversion of the boolean), or just use a trigger. Here’s the trigger:

 

<!-- root items can only be expanded, not selected -->
<Trigger Property="HasItems"
         Value="true">
  <Setter Property="Focusable"
          Value="false" />
</Trigger>

 

tree_dialogikWith this trigger in place, simply clicking on a node that contains child items does not change the tree’s current selection, while expanding/collapsing still works.

A common scenario for such a behavior is a tree that contains nodes which are used for grouping purposes only as in the example screenshot.

Author: Categories: WPF, WPF Controls, WPF TreeView Tags: ,

A KeyedCollection for int keys

March 5th, 2008

I’m using this class so much that I thought I’d share it with you. This generic class is an implementation of the KeyedCollection<TKey, TItem> class for items that have a numeric key:

public abstract class NumericallyKeyedCollection<T> : KeyedCollection<int, T>
{ }

Using int-Keys takes a bit more work than other types, because KeyedCollection provides indexers for both key and index. However, if the key’s type is int as well, you don’t have that option anymore. This class fills that gap by providing a few things for you:

  • GetByKey, TryGetByKey, and GetByIndex methods
  • Simplified exception handling and much better exception messages that include the invalid parameters. You can even customize exception messages by overriding the virtual GetKeyNotFoundMessage method.
  • An AddRange method which takes an IEnumerable<T>
  • For security reasons, the indexer has been overwritten and throws an InvalidOperationException if it is invoked. I just caught myself too much using it with the wrong parameters (index rather than key or vice versa). You might want to reverse that if you need to automatically serialize the collection to XML.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Hardcodet.Util
{
  /// <summary>
  /// An implementation of a <see cref="KeyedCollection{TKey,TItem}"/> for items that
  /// have a numeric key, an therefore do not provide individual
  /// indexers for both key and index. As an alternative, this class provides
  /// <see cref="GetByIndex"/> and <see cref="GetByKey"/> methods plus more
  /// sophisticated exception handling for invalid keys.<br/>
  /// For security measures, the numeric indexer has been disabled, as using it
  /// is just misleading because one cannot tell whether it returns an item by
  /// index or by key...
  /// </summary>
  public abstract class NumericallyKeyedCollection<T> : KeyedCollection<int, T>
  {
    #region constructors

    /// <summary>
    /// Creates an empty collection.
    /// </summary>
    public NumericallyKeyedCollection()
    {
    }


    /// <summary>
    /// Inits the collection by copying all items of another
    /// collection.
    /// </summary>
    /// <param name="items">A collection of items to be added
    /// to this collection.</param>
    public NumericallyKeyedCollection(IEnumerable<T> items)
    {
      AddRange(items);
    }

    #endregion


    #region get by id

    /// <summary>
    /// Tries to retrieve a given item by its key.
    /// </summary>
    /// <param name="key">The key that was used to store the
    /// item.</param>
    /// <returns>The matching item, if any. Otherwise
    /// <c>default(T)</c> (null in case of standard objects).</returns>
    public T TryGetByKey(int key)
    {
      return Contains(key) ? GetByKey(key) : default(T);
    }


    /// <summary>
    /// Overrides the default implementation in order to provide a more sophisticated
    /// exception handling. In case of an invalid ID, an exception with a message is
    /// being thrown that is built the <see cref="GetKeyNotFoundMessage"/> method.
    /// </summary>
    /// <returns>The item with the matching key.</returns>
    /// <exception cref="KeyNotFoundException">Thrown if no descriptor
    /// with a matching ID was found.</exception>
    public T GetByKey(int key)
    {
      try
      {
        return base[key];
      }
      catch (KeyNotFoundException)
      {
        //throw custom exception that contains the key
        string msg = GetKeyNotFoundMessage(key);
        throw new KeyNotFoundException(msg);
      }
    }


    /// <summary>
    /// Overrides the default implementation in order disable usage of the indexer,
    /// as its usage is no longer clear because index and item keys are both of
    /// the same type.<br/>
    /// Invoking this indexer always results in a <see cref="InvalidOperationException"/>.
    /// </summary>
    /// <returns>Nothing - invoking the indexer results in a <see cref="InvalidOperationException"/>.</returns>
    /// <exception cref="InvalidOperationException">Thrown if the indexer is being invoked.</exception>
    public new virtual T this[int key]
    {
      get
      {
        string msg = "Using the indexer is disabled because both access through index and item key take the same type.";
        msg += " Use the GetByKey or GetByIndex methods instead.";
        throw new InvalidOperationException(msg);
      }
    }


    /// <summary>
    /// Gets an exception message that is being submitted with
    /// the <see cref="KeyNotFoundException"/> which is thrown
    /// if the indexer was called with an unknown key.
    /// This template method might be overridden in order to provide
    /// a more specific message.
    /// </summary>
    /// <param name="key">The submitted (and unknown) key.</param>
    /// <returns>This default implementation returns an error
    /// message that contains the requested key.</returns>
    protected virtual string GetKeyNotFoundMessage(int key)
    {
      string msg = "No matching item found for key '{0}'.";
      return String.Format(msg, key);
    }

    #endregion


    #region get by index

    /// <summary>
    /// Gets the item at the specified <paramref name="index"/>.
    /// </summary>
    /// <param name="index">Index within the collection.</param>
    /// <returns>The item at the specified index.</returns>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/>
    /// if not a valid index of the internal list.</exception>
    public virtual T GetByIndex(int index)
    {
      return Items[index];
    }

    #endregion


    #region add items

    /// <summary>
    /// Adds a number of items to the list.
    /// </summary>
    /// <param name="items">The items to be appended.</param>
    public void AddRange(IEnumerable<T> items)
    {
      foreach (T item in items)
      {
        Add(item);
      }
    }


    /// <summary>
    /// Adds an item to the end of the collection.
    /// </summary>
    /// <param name="item">Item to be added to the collection.</param>
    /// <remarks>This override just provides a more sophisticated exception
    /// message.</remarks>
    public new void Add(T item)
    {
      try
      {
        base.Add(item);
      }
      catch (ArgumentException e)
      {
        int key = GetKeyForItem(item);
        if (Contains(key))
        {
          string msg = "An item with key '{0}' has already been added.";
          msg = String.Format(msg, key);
          throw new ArgumentException(msg, "item", e);
        }
        else
        {
          //in case of any other argument exception, just throw the
          //original exception
          throw;
        }
      }
    }

    #endregion
  }
}

Using it is fairly easy. Imagine you have a user collection that stores User objects by their numeric UserId. All you need to get going is this:

/// <summary>
/// Stores <see cref="User"/> instances by their numer
/// <see cref="User.UserId"/>.
/// </summary>
public class UserCollection : NumericallyKeyedCollection<User>
{
  protected override int GetKeyForItem(User item)
  {
    return item.UserId;
  }
}

 

…accordingly, here’s how you manipulate the collection:

public void Test()
{
  UserCollection col = new UserCollection();
  col.Add(new User(123));

  User userByIndex = col.GetByIndex(0);
  User userByKey = col.GetByKey(123);
}
Author: Categories: C# Tags:

Firebird requires MS-DOS compatible file paths

February 28th, 2008

I was contacted by a customer today, who received exceptions when trying to open a Firebird database (using the current version 2.03) on his machine:

 

Error message: FirebirdSql.Data.FirebirdClient.FbException:
I/O error for file CreateFile (open) “M:[…]Aufträgesome database.fdb”

Error while trying to open file —> FirebirdSql.Data.Common.IscException:
  An exception of type FirebirdSql.Data.Common.IscException was thrown.
    at FirebirdSql.Data.Client.Gds.GdsConnection.ReadStatusVector()
    at FirebirdSql.Data.Client.Gds.GdsConnection.ReadResponse()
    at FirebirdSql.Data.Client.Gds.GdsDatabase.ReadResponse()
    at FirebirdSql.Data.Client.Gds.GdsDatabase.Attach(DatabaseParameterBuffer dpb,
        String dataSource, Int32 port, String database)
    at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()

 

The solution was as simple as embarassing: It appears that Firebird doesn’t play nice with national characters (e.g. umlauts) anywhere in a database’s file path. Changing the folder name Aufträge to something ASCII compatible like Orders resolved the issue. Apparently, you should use MS-DOS compatible file paths only when working with Firebird.

Well, after all the next-gen stuff I packed into the app, this should give my customers (at least the ones who really miss their Windows 3.1) that warm, fuzzy vintage feeling the software has been lacking so far. Lucky me 😉

Author: Categories: Database Tags: ,

Programmatically filtering the WPF TreeView

February 12th, 2008

There will be filtering and multi selection support in the next iteration of my WPF TreeView, but based on a request on the Code Project forum, I decided to implement a simple filtering mechanism on the current version.

First of all, you can provide filtering without even touching the control base class by just applying the filter in your implementation of the abstract GetChildItems method. This method would effectively filter all items of the sample tree:

//returns subcategories that should be available through the tree
public override ICollection<ShopCategory>
                           GetChildItems(ShopCategory parent)
{
  //create a filtered list
  List<ShopCategory> list = new List<ShopCategory>();
  foreach(ShopCategory category in parent.SubCategories)
  {
    if ( ... ) list.Add(category);
  }
  
  return list;
}

In order to have the tree react to changed filter conditions, calling the tree’s Refresh() method takes care of everything.

This approach is dead simple, and it has the advantage that only items that are supposed to be accessible on the tree are being processed by the control. On the other hand, it also means that you would have to recreate the tree every time the tree’s filter changes.

 

In order to provide an alternative, I also looked at filtering the tree on the UI level (filtering == just hide the filtered nodes). The following sample sample operates on the tree implementation of the sample application, and provides a property of type Predicate<ShopCategory>. In order to get it working, I needed to do 3 things:

  • Apply the filter for new nodes that are being created
  • Run the filter if a node is being expanded
  • Refresh the tree if the filter is being set

 

I must say I’m quite satisfied – as the control provides me with virtual methods to intercept everything, the whole thing took about 2 minutes to set up 🙂

 

private Predicate<ShopCategory> filter = null;


/// <summary>
/// Defines a filter for items that are bound to the tree. Set to
/// null in order to disable filtering.
/// </summary>
public Predicate<ShopCategory> Filter
{
  get { return filter; }
  set
  {
    filter = value;

    //recreate the tree in order to apply the filter on
    //all currently visible nodes
    //-> of course, this could be optimized, but it does the job
    Refresh(GetTreeLayout());
  }
}


/// <summary>
/// Applies the filter on all child nodes.
/// </summary>
/// <param name="treeNode"></param>
protected override void OnNodeExpanded(TreeViewItem treeNode)
{
  //make sure child nodes are being created
  base.OnNodeExpanded(treeNode);

  //apply filter
  foreach (TreeViewItem childNode in treeNode.Items)
  {
    ApplyFilter(childNode, (ShopCategory)childNode.Header);
  }
}


/// <summary>
/// Immediately applies the filter on newly created items. This
/// is somewhat redundant (as we're also handling <see cref="OnNodeExpanded"/>),
/// but ensures we also consider root nodes.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
protected override TreeViewItem CreateTreeViewItem(ShopCategory item)
{
  //delegate node creation to base class
  TreeViewItem node = base.CreateTreeViewItem(item);

  //apply the filter and return the node
  ApplyFilter(node, item);
  return node;
}



/// <summary>
/// Filters categories if the <see cref="Filter"/> property
/// is set by simply setting the <see cref="TreeViewItem.Visibility"/>
/// property to <see cref="Visibility.Collapsed"/> if the item does
/// not match the filter.
/// </summary>
private void ApplyFilter(TreeViewItem node, ShopCategory item)
{
  bool visible = filter == null || filter(item);
  node.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;
}

 

You can try it out by adding the above code to the sample tree (CategoryTree.cs), and setting the Filter property in an event handler of the sample app. Note that OnNodeExpanded is already overridden, so you’ll end up with two duplicate methods if you paste in the snippet.

Author: Categories: WPF TreeView Tags: ,