Archive

Archive for February, 2008

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: ,

WPF application patterns and Unit Testing

February 1st, 2008

Josh Smith, prolific Code Project writer and blogger, has written a great article about MVC (or M-V-poo, as the doctor would say!) and unit testing of WPF apps. The article can be found on Code Project:

http://www.codeproject.com/KB/WPF/MVCtoUnitTestinWPF.aspx

Author: Categories: WPF Tags: ,

Finding an ancestor of a WPF dependency object

February 1st, 2008

This is a simple snippet which helps you to find a specified parent of a given WPF dependency object somewhere in its visual tree:

(Snippet updated 2009.09.14)

 

/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the
/// queried item.</param>
/// <returns>The first parent item that matches the submitted
/// type parameter. If not matching item can be found, a null
/// reference is being returned.</returns>
public static T TryFindParent<T>(this DependencyObject child)
    where T : DependencyObject
{
  //get parent item
  DependencyObject parentObject = GetParentObject(child);

  //we've reached the end of the tree
  if (parentObject == null) return null;

  //check if the parent matches the type we're looking for
  T parent = parentObject as T;
  if (parent != null)
  {
    return parent;
  }
  else
  {
    //use recursion to proceed with next level
    return TryFindParent<T>(parentObject);
  }
}

/// <summary>
/// This method is an alternative to WPF's
/// <see cref="VisualTreeHelper.GetParent"/> method, which also
/// supports content elements. Keep in mind that for content element,
/// this method falls back to the logical tree of the element!
/// </summary>
/// <param name="child">The item to be processed.</param>
/// <returns>The submitted item's parent, if available. Otherwise
/// null.</returns>
public static DependencyObject GetParentObject(this DependencyObject child)
{
  if (child == null) return null;
  
  //handle content elements separately
  ContentElement contentElement = child as ContentElement;
  if (contentElement != null)
  {
    DependencyObject parent = ContentOperations.GetParent(contentElement);
    if (parent != null) return parent;

    FrameworkContentElement fce = contentElement as FrameworkContentElement;
    return fce != null ? fce.Parent : null;
  }

  //also try searching for parent in framework elements (such as DockPanel, etc)
  FrameworkElement frameworkElement = child as FrameworkElement;
  if (frameworkElement != null)
  {
    DependencyObject parent = frameworkElement.Parent;
    if (parent != null) return parent;
  }

  //if it's not a ContentElement/FrameworkElement, rely on VisualTreeHelper
  return VisualTreeHelper.GetParent(child);
}

 

 

This snippet works with arbitrary dependency objects that are of Type Visual or Visual3D. So let’s say you need a reference to the Window that hosts a given Button control somewhere, all you need is this:

Button myButton = ...
Window parentWindow = UIHelper.TryFindParent<Window>(myButton);

 

The above TryFindParent method also makes it easy to get an item at a given position. The method below performs a hit test based on a given position. If hit testing does not return the requested item (e.g. a clicked CheckBox on a tree, while you are keen on the TreeViewItem that hosts the CheckBox), the procedure delegates the lookup to TryFindParent.

This comes in very handy for mouse-related events if you just need to now what’s under your mouse pointer:

/// <summary>
/// Tries to locate a given item within the visual tree,
/// starting with the dependency object at a given position. 
/// </summary>
/// <typeparam name="T">The type of the element to be found
/// on the visual tree of the element at the given location.</typeparam>
/// <param name="reference">The main element which is used to perform
/// hit testing.</param>
/// <param name="point">The position to be evaluated on the origin.</param>
public static T TryFindFromPoint<T>(UIElement reference, Point point)
  where T:DependencyObject
{
  DependencyObject element = reference.InputHitTest(point)
                               as DependencyObject;
  if (element == null) return null;
  else if (element is T) return (T)element;
  else return TryFindParent<T>(element);
}
Author: Categories: WPF Tags: