The Missing .NET #3: An AutoComplete TextBox in WPF, Part 1 – A rough first draft

The .NET framework is huge, but not so huge that it does everything for everyone; there are things that they in Redmond miss or don’t do for whatever reason but is still generally applicable to many developers. So, dear reader, I present to you a new series of posts on stuff I find missing in .NET, typically where even the Google fails to find the answer. It could be a useful class, a technique, a good practice or documentation that should be in the framework but isn’t.


The more I use WPF, the more I’m impressed and confounded by it. Impressed because it is really well-designed, thoughtful, and quite rich right out of the gate; I’m confounded by the things it’s lacking. I realize they had to ship something sooner than later, but some of the things Microsoft left out seem pretty trivial to implement given what I know about WPF. One of these is an auto-completing TextBox (It was even late to the Windows forms party, but still…). The most famous example is the address ComboBox in the browser. Start typing to see that the computer remembers what you typed previously. Auto-complete is everywhere in the OS, and you can see it on the web in spots too, now: Compose a message in Facebook and you’ll see your contact list drop down and filter out as you type.

I’ve seen suspiciously little from The Google on auto-completing text boxes using WPF. This can lead me to possible two explanations:

  1. Auto-complete is obviously trivial and so everyone just implements it in two lines in their own projects, and I’m a complete idiot for searching The Google in the first place; or
  2. No one is using WPF for anything  usable with normal-looking controls — they just want the 3-D light show with lasers.

In either case, I figure I’ll just keep writing this post. There are definitely more complete idiots out there, if 1 is the case. If 2 is the case, I just have to wait a few months or years for this post to be relevant.

When I set out, I had a goal to make a TextBox with auto-complete, I was going to use WPF’s idioms to the fullest, meaning no custom controls or inheriting from TextBox to add what I want. Also, I detest making custom controls because they are so hard to maintain and they aren’t just there in the IDE to use, like the default controls; the case would have to be pretty compelling to replace something as fundamental as the text box, and autocomplete ain’t it.

Besides, I think it’ll be a rare thing to create a custom control in WPF, at least a custom control the way a WinForms developer would think about a custom control: there’s just too much you can do with element composition and templates in WPF.

After some digging, I noticed that the bits and pieces of AutoComplete are already there in WPF; all I had to do was stitch them up together in a nice little package. So what I’d like to do is talk about those parts before I explain how I made the control. In the first part, I’ll talk about filtering the list as the user types; you know, the part that gives a textbox its autocomplete-y-ness.

List-Filtering: CollectionViewSource

People like lists in their blog posts I’ve found; so here’s a list: the Best Thing about WPF

  • Data-binding

The end.

You can write an RSS reader in like 100 lines of XAML and zero lines of code, all with data-binding. Representing custom classes is a matter of a moment, creating a DataTemplate for them. Hierarchical data? No problem. XML? No problem. Database? Um, not sure, don’t use ’em, but probably.

WPF was designed with data-driven apps as one of the key scenarios, and it shows. What’s even nicer is that you can get started right away without knowing too much about how databinding works. But dig a little deeper and you can see how well-designed it is.

For instance, the ListBox can represent a list of items and, with DataTemplates, you can customize the look of each item. You can also track the currently selected item and bind other controls to that item. What if you had two ListBoxes, though, both pointing to the same collection, and you wanted one to show a subset of the collection? Could you do that?

Absolutely.

When you bind to a list source WPF wraps the source in an ICollectionView. The ICollectionView manages the currency (the currently selected item) of the list for the ListBox. Each ListBox gets a different ICollectionView instance. If you look at the API for ICollectionView, you’ll see some methods and properties for grouping, sorting, and filtering.

We’re interested in filtering lists! If you want to filter a list, you can create your own ICollectionView through it’s XAML representation, CollectionViewSource; bind it to your source; bind your list box to your CollectionViewSource and then register for the Filter event on the view.

The XAML below provides an example of this.

<Grid Name="grid1">
     <Grid.Resources>
        <ObjectDataProvider x:Key="people" 
                            ObjectType="{x:Type local:People}" 
                            MethodName="GetPeople" />
        <CollectionViewSource x:Key="viewSource" 
                              Source="{StaticResource people}" 
                              Filter="CollectionViewSource_Filter"/>
    </Grid.Resources>
    <ListBox ItemsSource="{Binding Source={StaticResource viewSource}}" />
</Grid>

The CollectionViewSource_Filter event handler is where your filtering code goes. If you hook it up in XAML, you get a nice event with specific event args, but you could also do it in code, in which case, the Filter property is a Predicate<T> delegate. The event deals with each item in the data source at a time.

So where am I going with this ICollectionView thing? Well, if you look at what constitutes an autocomplete textbox in Win32, it’s a just a textbox with a listbox below that shows up when typing happens and filters the items in the list based on what’s typed.

So why not start there in WPF?

Autocomplete TextBox First Draft

My first iteration wasn’t a control or anything more complicated than the XAML below

<StackPanel >
    <TextBox Name="textBox1" 
         VerticalAlignment="Top" 
         HorizontalAlignment="Stretch" 
         TextChanged="textBox1_TextChanged" />
    <ListBox Name="listBox1" 
         Visibility="Hidden"
         ItemsSource="{Binding Source={StaticResource viewSource}}"
         HorizontalAlignment="Stretch" 
         Focusable="False"/>
</StackPanel>

The viewSource in the ListBox.ItemsSource Binding is the same as the previous XAML snippet. In the code behind file, I have the following event handlers:

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    CollectionViewSource viewSource = (CollectionViewSource) grid1.FindResource("viewSource");
    this.listBox1.Visibility = this.textBox1.Text != "" 
                                    ? Visibility.Visible : Visibility.Hidden;

    viewSource.View.Refresh();
}

private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
{
    e.Accepted = e.Item.ToString().StartsWith(textBox1.Text, 
                        StringComparison.CurrentCultureIgnoreCase);
}

When the text changes, I ask the viewSource’s ICollectionView to Refresh. This in turn raises the Filter event that determines if each item in the list should still be there based on the text in the TextBox. Cool, eh? That’s all that’s needed

Run it with your favourite IDE with some suitable data, start typing and you have the basic concept of an autocompleting TextBox. That was easy.

Next time: we package this up in a reusable way.

Subtext to WordPress: Converting blog engines

I think my mom is my only constant reader, but if you used to read jasonkemp.ca when I was writing it more frequently than the last year and a half, you’ll notice a few changes in appearance that only scratch the surface of the changes that I’ve made.

I moved hosts; I moved OSes; and I moved blog engines. I decided to move to WordPress on LAMP from Subtext on IIS. And I’m really happy with the move, too, which is rare, if Google is any indication; everyone else is moving the other way. There was only one, Aaron Lerch, who went in my direction and he wrote an import plug in, which I didn’t use because it required all these extra downloads. [Um, re-reading Aaron’s post, I see now that his BlogML Import plugin is probably the way to go if you’re in this situation. There’s only one extra download.]

To make matters worse, I had a version of Subtext that must’ve been a development version because the BlogML export didn’t work at all. So I had to use all my hacking skills to read directly from the database with the current Subtext source (Thank goodness it was open source!). I’ll spare you the details of that export; it wasn’t perfect or pretty but I got my posts, comments, and categories, which was close enough for what I wanted. So I had a BlogML XML file and I needed to convert to a WordPress export file, which is just some gussied up RSS. In the intervening years since I stopped blogging and now, .NET 3.5 was released, so I thought this was the perfect time to play with LINQ and the new XML APIs.

LINQ is seriously cool. Working with XML is seriously not, no matter what API you have. Those were the two conclusions I came up with. The new XML APIs are pretty sweet, though. They’re the closest I can come to writing code that handles XML the way I think about XML. But that’s not what I’m writing this post about.

The conversion got me about 90% there, but there were a couple things that I needed to fix: mapping old urls to the new ones because your urls are probably the most important thing about people reaching your website and handling image paths; both of which are handled with mod_rewrite and the htaccess file. Until IIS 7, I don’t think Windows had anything as cool as that and even with IIS 7, it may not, certainly not as simple as a text file.

Using this helpful article, I generated all the rewrite rules from the BlogML export file, since it had all the old post urls. I only had roughly one hundred articles so I just hard-coded everyone of them. They all take the form of

RewriteRule ^rss.aspx http://www.jasonkemp.ca/blog/feed [r=301,nc]

I didn’t want to mess with mod_rewrite too much, because regular expressions require a quiet room and lots of testing, so I kept it pretty simple. What the above says is if my web server receives a request for rss.aspx, then permanently redirect to http://www.jasonkemp.ca/blog/feed, that’s what the r=301 means. The ‘nc’ means case doesn’t matter. Spaces matter here! Notice there are no spaces in the the square brackets. It won’t work otherwise.

The last thing I had to do to convert was images. My images were in two spots: the root folder and in an ‘images’ folder. So my posts have those paths in them. Rather than go through all my posts and changing the paths, I added another rewrite rule:

RewriteRule ^(images/)?(.+)\.(gif|jpg)$ blog/img/$2.$3 [nc]

That’s about as fancy as I get in mod_rewrite. What this says is any jpg or gif file either in the root or in the path images/, then redirect to blog/img/ with the same name and extension. So if I had an image in a post with the path images/1.jpg, then mod_rewrite will convert that to blog/img/1.jpg.

Converting this took a few weeks of off and on development. Changing blog engines is anything but trivial right now. If anyone is curious about the code, just ask.

Technorati Tags: ,,,

A Fast Equals() – Remember to Always Measure

For years, I thought I had the one, true answer to Equals() from seeing something in some MSDN article a long, long time ago – like 2002 or 2003. Or maybe it was on Brad’s or Krystof’s blog and freaked out because I wasn’t doing it. Whatever the case, I’d make sure to point out the “proper” way to do Equals() to my colleagues. And I always made sure that I’d do it the same way for all my types that needed Equals overridden. Then I decided to measure it.

So, what did I think the best way to do Equals was? Consider this type:

    class MyClass
    {
        public int NumberValue;
        public string StringValue;
    }

If I were to write Equals the way I used to, I would write it the following way:

        public override bool Equals(object obj)
        {
            if (obj == null || obj.GetType() != GetType())
                return false;
            if (ReferenceEquals(obj, this))
                return true;
            MyClass other = (MyClass) obj;
            return other.NumberValue == this.NumberValue &&
                   other.StringValue == this.StringValue;
        }

Note that the above implementation suffices the conditions for a robust Equals. The important part of Equals() is that it covers all the following cases:

  • it returns false if obj is null;
  • it returns false if obj is not the same type as this;
  • it returns true if the references are the same;
  • it doesn’t throw Exceptions; and
  • it doesn’t allocate memory.

The actual evaluation of equality is per class and changes for every class. In the example above, the equality evaluation is the return statement comparing the string and the int of both MyClass instances. The above list of conditions is boilerplate and should be met for every Equals method you write.

So what’s the problem? My Equals method does everything in that list just fine. Right?

Two of the conditions are trivial to meet: the check for null and check for reference equality. The hard one to meet, perhaps because are there so many ways of doing it, is checking for the right type. In my method above, I check the type by comparing GetType() of both obj and this. If they aren’t equal, I return false. That turns out to be 5 times slower than the other two ways of doing it: the is and as operator.

The .NET Design Guidelines recommend you use the as operator to check the type rather than the is operator because it does the type check and assignment all at once. So let’s re-write the Equals method to use the as operator:

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(obj, this))
                return true;
            MyClass other = obj as MyClass;
            if (other != null)
              return other.NumberValue == this.NumberValue &&
                     other.StringValue == this.StringValue;
            return false;
        }

This method meets all the conditions of a good Equals, but has the advantage of being pretty fast, faster than the first way I did it anyway. Since the gurus in Redmond recommend the as operator, you’d think that it’s the fastest: wrong! Check it:

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(obj, this))
                return true;
            if (obj is MyClass)
            {
                MyClass other = (MyClass) obj;
                return other.NumberValue == this.NumberValue &&
                       other.StringValue == this.StringValue;
            }
            return false;
        }

Equals with the is operator and then casting is actually the fastest of them all (by about 10% when compared to the as operator). All three methods meet the conditions of a good Equals method, but the least intuitive one – to me at least – has the advantage of being the fastest. And it’s cheap speed, too: you get it just by implementing Equals the same way everytime for every type. You generally want Equals to be pretty fast because it will show up a lot in loops and operations on collections.

My point? Always measure – don’t assume you’re doing things right. It’s good to go back and think about the fundamentals once in a while.

Using the Command Pattern in Windows Forms clients

I’ve been doing a lot of research with the Command pattern lately at work. Here’s what I found: You’re doing yourself a disservice – and your team – if you don’t play the hell outta this thing!

It’s a very powerful design for non-trivial Windows Forms clients. What’s non-trivial? Anything that uses a menu, toolbar or context menu to show perform the same action. In fact it’s so useful and so powerful that I’m a little disappointed that Microsoft didn’t provide something like it in the framework itself. They’ve provided something in Avalon WPF, but I haven’t had the chance to play with it. I know they use it: Visual Studio and Office take advantage of it. (For example, think of how many ways you can copy and paste text.)

What are some of the advantages?

  • Automation – how easy is it to automate tasks in Visual Studio with a macro? Or reassign a keyboard shortcut? Enough said.
  • Completely decouples the UI from the business objects. It’s easy to say this but really hard to do it, especially if deadlines are tight. With commands, you can keep the UI and throw away the business objects or vice versa.
  • Easily allows plugins or addins. Suppose you have a client with a unique look that you want to control, but you want to offer the ability to extend or introduce functionality to third parties. Commands allow that. It’s how Visual Studio Add-ins do it.

There are disadvantages, of course – every design has drawbacks:

  • It complicates the application design. Every pattern complicates application design; they’re used because the benefits outweigh the cost. In fact, they should only be used when the benefits outweigh the costs.
  • Using commands complicate your controls and forms. Suppose you have a button that will be used to execute a command. Do you subclass Button so that it contains a Command and override OnClick? Do you use a normal Button and handle the Click event in the form? Change Button with MenuItem. Repeat questions.
  • Debugging is a little harder. There are features in .NET 2.0 to mitigate this one.

So what does a Command look like? Well, that’s largely up to you. The bare minimum would be one method that would allow you to perform the action associated with a Command:

public interface ICommand

{

void Execute();

}

All of your concrete commands would implement this interface and when the button or menu is clicked, call command.Execute(). Easy, eh? There is a whole lot more you can do with the shared interface, however. In fact, there is a lot of common code that you can take advantage of, which is why I prefer an abstract class, like so:

public abstract class Command

{

public string Key { get; protected set; }

public string DisplayName { get; protected set; }

 

public bool Enabled { get; }

 

public abstract void Execute();

}

All the properties would have an implementation, I leave it out because I’m only concerned with API right now. We still have that abstract Execute() method, but now we have a few properties that deserve some explanation. To further separate the UI from the business logic, if the text that the user sees is associated with the command rather than the UI, then you can easily replace the commands without modifying the UI at all. This is extremely powerful when you start dealing with collections of commands that can all be handled in the same way. So that explains DisplayName.

The Enabled property is fairly obvious: there are times when it would either be impossible or just plain wrong to perform an action; in those cases, you want to disable the UI so that the action cannot be performed. I’ll come back to the Enabled property in a second.

The Key property is for when Commands are grouped together in a collection. It makes sense to store most of your commands globally with the main form in a list or map. We’ll need a way to uniquely identify them so that we can retrieve them later. That’s what the Key property is for. Go to Tools -> Options in Visual Studio, select Keyboard. There you’ll see the keys for the commands in Visual Studio, no pun intended.

Now, by itself, the above Command is very powerful. However, we’re not done. Combine the above with Data Binding in Window Forms and you have to write almost no code at all. Data Binding is a very powerful technology, which you’ll know about if you’re one of the millions of ASP.NET developers out there. In .NET 2.0, Windows Forms apps got the same treatment. I can’t cover data binding in detail in this post, so I’ll just assume you know about it. To really take advantage of Data Binding I have to modify my Command class slightly:

public abstract class Command : INotifyPropertyChanged

{

bool enabled;

string key, displayName;

 

public event PropertyChangedEventHandler PropertyChanged;

 

public string Key

{

get { return key; }

protected set { key = value; }

}

 

public string DisplayName

{

get { return displayName; }

protected set

{

if (displayName != value)

{

displayName = value;

OnPropertyChanged(new PropertyChangedEventArgs(“DisplayName”));

}

}

}

 

public bool Enabled

{

get { return enabled; }

set

{

if (enabled != value)

{

enabled = value;

OnPropertyChanged(new PropertyChangedEventArgs(“Enabled”));

}

}

}

 

public abstract void Execute();

 

protected void OnPropertyChanged(PropertyChangedEventArgs e)

{

PropertyChangedEventHandler handler = PropertyChanged;

if (handler != null)

handler(this, e);

}

}

OK, I gave you the whole implementation. You’ll see that my Command class now implements the INotifyPropertyChanged interface. This allows the data binding code to update the control that has bound to the data when the data changes. You’ll note that DisplayName and Enabled will raise the PropertyChanged event. Therefore you can create a Button, hook it up to a Command with a minimum of code and let the power of data binding deal with turning the command on and off:

Button button = new Button();

Command command = new ArbitraryCommand(“My Data”);

button.DataBindings.Add(“Text”, command, “DisplayName”);

button.DataBindings.Add(“Enabled”, command, “Enabled”);

button.Click += delegate { command.Execute(); };

This technique is very powerful when your business objects change on their own without user interaction.

There are few things you have to note. The DisplayName property will have to be internationalized if your app is interested in the rest of the world, which will make the class more complex. Also, the Command pattern kind of falls down when you need to pass data to the command. You lose the polymorphism of the Command class when you have to either know the specific concrete type or what data must be passed to a particular command.

Still, if you are doing serious Windows Forms apps, you should consider the Command pattern.

Technorati tags: , patterns

Now playing: Santana – Just Feel Better (Feat. Steven Tyler Of Aerosmith)

PowerShell profile folder is different than Monad

This week, Microsoft announced Monad’s product name, PowerShell, as well as releasing an RC1 release (The very good user guide can be found here). There are quite a few changes that you can read about on their new blog: http://blogs.msdn.com/powershell. While I think Monad is just fine for a name, I like PowerShell, too. It’s much better than the other names these dummy marketers came up with. I actually have this image in my head when I think the name PowerShell that I might just blog about, but not in this post. While we’re still on naming, though, msh is a way better name for a file extension that ps1. Oh well.

Because of the name change, the profile folder in My Documents has changed but not to something intuitive, so I figured I’d post about it and hopefully let Google pick it up. The folder name for the betas was My Documents\msh. In this folder, you could put your profile script to customize the shell as well as other scripts. I posted earlier about setting the Visual Studio environment variables via script (btw, I plan on making that script better, stay tuned). That’s where you’d put those scripts.

Since the name change to PowerShell, it’d be natural to think that the folder would have to be renamed from msh to ps1, or ps. You’ll find that that is totally wrong. I think for the same reason that the .msh extension got changed to .ps1, instead of just .ps, the new folder name is My Documents\PSConfiguration.

You’ll also have to rename all of your scripts to .ps1. I tried to come up a quick little command, but I failed and just did it by hand (I only had three). I’m still stuck in the learning curve. Luckily, Peter Provost, who is far more proficient in the new shell, gives us just what we need.

Technorati tags: , , MSH

Now playing: Matthew Sweet – Sick Of Myself