I’m always on the quest for better coding tools, and a new one I’ve been playing with for the last couple weeks is a code search tool called Entrian Source Search. It is a Visual Studio plugin that maintains an index of your code base for rapid search results. Not free – $29/dev after a 30-day trial.

How does it work?

When you open a solution for the first time, you are prompted if you want to create an index and if so which path(s) you want to monitor.

Entrian New Solution image

New Solution prompt

Entrian Setup Index image

Setup index dialog

I especially liked the option to “Share another solution’s index”.  It is those little details that show a project’s maturity.

Why not just use the built-in Find in Files?

  • Indexed searches are exceptionally faster
  • Highlighted results are easier to skim
  • A results grid that shows the matches in the same place instead of just dumping them at the end of a path
  • When folders/files/lines are repeated, the entries after the first are grayed out a little which is a nice visual cue of repetition
  • Right-click context menu with several convenient refinements/actions
  • More keyboard shortcuts (the way to my heart)
  • Searching your code base (instead of your solution) will pick-up all those hard to find usages in configuration files, reflection usages, etc. that may get missed otherwise.  Yes, you can configure Find in Files to search folders – but have you?

See for yourself:

Visual Studio Find Results image

Visual Studio Find Results

Entrian Search Results image

Entrian Search Results

Entrian Search Results Context Menu image

Entrian Search Results Context Menu

What about other tools on the horizon?

I’ve been using TextCrawler for a long time, and it is still my tool of choice to run a search without bringing up Visual Studio.  It is free and runs quick, but the UI could use some love (e.g. keyboard shortcuts, respond to window size changes).  This tool is unfortunately not very active (sad trombone).

What I’m really interested in watching is Sando.  I’ve been trading e-mails with its lead David C. Shepherd and they come to the search game with an intent to go far beyond a simple grep.  Out of ABB Research and with the help from some developers in the community they are building an engine that prioritizes search results, offers auto-completion and is focused on research-driven functionality.  Sure it will support an exact match search like the others (*yawn*), but what it does that makes it stand apart is fuzzy searching like a true search engine.  The concept is amazing for discovery in a new code base, or all of those times you can’t exactly remember what you called that method.  It currently only searches code files within the solution which is a deal breaker for me, but I’m excited to see how the product evolves as it is very active and growing.  If you’re looking for an open source project to join (besides CodeMaid of course 😉 ) – then I would definitely encourage you to take a look at Sando (source on CodePlex) and be a part of its future.  It is available on Visual Studio Gallery if you want to give it a whirl or check out their new website for more details.

Sando

Sando

Summary

Entrian Source Search is my recommendation for today, but my hopes for the future are with Sando.  If you have any other code search tool recommendations then speak up in the comments. 🙂

Welcome back for part 3 in this INotifyPropertyChanged series. This time we’ll be taking a look at reversed notifications which are another code smell with this pattern.

Reversed notifications

What do I mean by reversed notifications? When you have a dependent property (FullName) which is calculated based on an independent property (FirstName) then you have to make sure you raise notifications for FullName whenever FirstName changes. Since there isn’t a direct way to do this, a common approach is to have the source directly do the work for the destination:

        public string FirstName
        {
            get { return GetPropertyValue<string>(); }
            set
            {
                if (SetPropertyValue(value))
                {
                    RaisePropertyChanged("FullName");
                }
            }
        }

        public string FullName
        {
            get { return string.Format("{0} {1} {2}", FirstName, MiddleName, LastName); }
        }

It works, but it is putting the knowledge of the dependency between the properties in the wrong place. With this approach, the independent property (FirstName) has to be aware of all of its dependencies (FullName). It would be much better if the dependent property could take care of itself. So how do we flip this around in the right direction?

NotifiesOnAttribute

Using attributes, we can specify our dependencies directly on the dependent property – leaving the independent property untouched!

        public string FirstName
        {
            get { return GetPropertyValue<string>(); }
            set { SetPropertyValue(value); }
        }

        [NotifiesOn("FirstName")]
        public string FullName
        {
            get { return string.Format("{0} {1} {2}", FirstName, MiddleName, LastName); }
        }

Magic! 😉

Ok, lets peek behind the scenes to see how that is being accomplished. We have defined a NotifiesOnAttribute class which simply takes a string parameter pointing to the independent property. We’ve also set the AttributeUsage to allow for the property to be defined multiple times. So in our example above we can also be notified when MiddleName and LastName change by repeating the attribute definition. In our view model, we do a lazy-initialized pull of all the attribute definitions on our class and store them in an ILookup structure which is basically a dictionary without unique keys. Finally when we are raising property changed, we check our cache of dependent properties and if any are found then we raise PropertyChanged on them as well.

        private ILookup<string, string> _dependentLookup;

        private ILookup<string, string> DependentLookup
        {
            get
            {
                return _dependentLookup ?? (_dependentLookup = (from p in GetType().GetProperties()
                                                                let attrs = p.GetCustomAttributes(typeof(NotifiesOnAttribute), false)
                                                                from NotifiesOnAttribute a in attrs
                                                                select new { Independent = a.Name, Dependent = p.Name }).ToLookup(i => i.Independent, d => d.Dependent));
            }
        }

        protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));

                foreach (var dependentPropertyName in DependentLookup[propertyName])
                {
                    RaisePropertyChanged(dependentPropertyName);
                }
            }
        }

Tada!

Performance

We’re almost done, but we still have to check out our performance. I’ve modified the sample application (below) that raises a million notifications using both mechansims. Here’s the results:

Performance image

Performance comparison between direct and attribute based mechanisms.

Our baseline took 9.565s, and our attribute approach took 10.099s – just about a 5% increase which works for me. 🙂

Summary

With attributes on our dependent property, we can not only cut down our code but we can also put our logic back in the right place. Thanks for reading these article(s). I hope you enjoyed them and if you have other ideas on how to improve the INotifyPropertyChanged pattern please chime in on the comments. 🙂

Code: SteveCadwallader.NotifyPropertyChanged.3of3.zip

Part 1: INotifyPropertyChanged (1 of 3) – without the strings
Part 2: INotifyPropertyChanged (2 of 3) – without the backing fields

Welcome back for part 2 in this INotifyPropertyChanged series. This time we’ll be taking a look at the backing fields that are a common smell to this pattern.

Backing fields

To prevent raising notifications when a property is not really changing, it is very common to check the new value against the old. This means we have to save the old value somewhere and the easiest way to do that is with a matching backing field.

        private int _iterations;

        public int Iterations
        {
            get { return _iterations; }
            set
            {
                if (_iterations != value)
                {
                    _iterations = value;
                    OnPropertyChanged();
                }
            }
        }

It works, but it smells of redundancy especially since we usually don’t use that backing field anywhere else. If only we could store the property’s value somewhere else…

Backing dictionary

Instead of a backing field behind every individual property, we can create a single backing dictionary to cover all of our properties. We’ll also create a couple helper methods for getting and setting property values.

        private readonly Dictionary<string, object> _propertyBackingDictionary = new Dictionary<string, object>();

        protected T GetPropertyValue<T>([CallerMemberName] string propertyName = null)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            object value;
            if (_propertyBackingDictionary.TryGetValue(propertyName, out value))
            {
                return (T)value;
            }

            return default(T);
        }

        protected bool SetPropertyValue<T>(T newValue, [CallerMemberName] string propertyName = null)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            if (EqualityComparer<T>.Default.Equals(newValue, GetPropertyValue<T>(propertyName))) return false;

            _propertyBackingDictionary[propertyName] = newValue;
            OnPropertyChanged(propertyName);
            return true;
        }

This code encapsulates both the equality comparisons and storing/retrieving the values in a tidy fashion that we can promote up to a base class and only have defined once.

Now for the candy, here’s what our property looks like after:

        public int Iterations
        {
            get { return GetPropertyValue<int>(); }
            set { SetPropertyValue(value); }
        }

No more backing fields, and we’ve more than halved the amount of code we have to write! If you’re bouncing in your chair in excitement now – don’t worry you’re not alone. 😉

Credit for the idea goes to Bas Hamer who mentioned the idea in a comment on Jesse Liberty’s C# 5 – Making INotifyPropertyChanged Easier post.

Note that calling SetPropertyValue will return a boolean indicating if the value has changed or not. You can use this to perform additional work when the property has changed. A typical use is notifying other dependent properties, but we’re going to take care of that too in the next part of this series.

Performance

Same as last time, how do these approaches compare in performance? I’ve modified the sample application (attached) that raises a million notifications using both mechanisms. Here’s the results:

Performance image

Performance comparison between backing field based and backing dictionary based mechanisms.


Our backing field baseline took 4.805s to raise a million notifications. Using a backing dictionary took 5.327s to do the same, meaning only about a 10% hit for the extra work which is very modest and well worth the code cleanup in my opinion.

Summary

With a backing dictionary in a base class, we can cut out a lot of redundant code without a noticeable performance penalty. Stay tuned for the next part in the series, where we’ll get rid of reversed notifications.

Code: SteveCadwallader.NotifyPropertyChanged.2of3.zip

Part 1: INotifyPropertyChanged (1 of 3) – without the strings
Part 3: INotifyPropertyChanged (3 of 3) – without the reversed notifications

If you’ve worked with WPF, you’ve probably encountered INotifyPropertyChanged.  It is a great notification mechanism, but it has a few common code smells we’ll iron out over this three part series.

String based

The default way of raising a notification is to specify the property name with a string.

        private int _iterations;

        public int Iterations
        {
            get { return _iterations; }
            set
            {
                if (_iterations != value)
                {
                    _iterations = value;
                    OnPropertyChanged("Iterations");
                }
            }
        }

        protected void OnPropertyChanged(string propertyName)
        {

It works, but it smells of both fragility (a typo or property rename will silently break it) and redundancy.

Lambda based

A different way of raising a notification is to specify the property name with a lambda expression.

        private int _iterations;

        public int Iterations
        {
            get { return _iterations; }
            set
            {
                if (_iterations != value)
                {
                    _iterations = value;
                    OnPropertyChanged(() => Iterations);
                }
            }
        }

        protected void OnPropertyChanged<T>(Expression<Func<T>> exp)
        {

It works, and no longer smells of fragility.  It is still redundant though, and makes you wonder about performance which we’ll cover shortly.

CallerMemberName based

Now with C# 5 there is another way of raising a notification which is to utilize the CallerMemberName attribute. This new attribute defined in our OnPropertyChanged method will pull the property name for us automatically.

        private int _iterations;

        public int Iterations
        {
            get { return _iterations; }
            set
            {
                if (_iterations != value)
                {
                    _iterations = value;
                    OnPropertyChanged();
                }
            }
        }

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {

It works, no fragility and no redundancy. 🙂

Performance

Back to performance, how do these alternatives stack up?  I created a sample application (attached) that raises a million notifications using each of these three mechanisms. Here’s the results:

Performance image

Performance comparison between string based, lambda based and CallerMemberName based mechanisms.

Our string baseline took 4.857s to raise a million notifications. Using lambda expressions took 8.154s, an increase of nearly 70%. Using CallerMemberName however was nearly identical to the baseline at 4.768s, which is great news since it means we can take advantage of more robust code without any performance concerns!

Hope it helps – stay tuned for the next two parts in the series, where we’ll get rid of backing fields and reversed notifications. 🙂

Code: SteveCadwallader.NotifyPropertyChanged.1of3.zip

Part 2: INotifyPropertyChanged (2 of 3) – without the backing fields
Part 3: INotifyPropertyChanged (3 of 3) – without the reversed notifications