| William's profileSo long, and thanks for ...BlogLists | Help |
|
August 24 Specificity Beta ReleasedI’ve released a Beta for Specificity, so it’s no longer just a source repository. Specificity still isn’t ready for full release. There’s additions to the release I plan to make, including project and item templates. However, I expect the APIs to be stable at this point. Creating a release, including an installer, was important to me. See, it’s going to help with one of the largest complaints I’ve received for Onyx: figuring out which source revision of Specificity to use. In the next day or two, I’ll update Onyx to use an installed version of Specificity, and those issues should be gone. I’ve had to learn a lot of new tech to make this release. I’m using Wix to create the installer, and that’s not the most intuitive thing to work with. Then there’s the project and item templates that I’m working on. These require a custom wizard to control code generation, since Specificity is compatible with numerous different unit testing frameworks. If I find the time, I’ll try and blog about what I’ve discovered here, but if nothing else, hopefully the source will be useful for anyone else trying to figure this stuff out. August 03 Conventionally Speaking about ViewModelsDisclaimer: This blog post is theoretical notes about an interesting subject, and does not contain a working solution. I will probably provide a solution in the future, but if you’re looking for one here, you’ll be disappointed. Glenn Block had an interesting post about the “spirit” of the ViewModel design pattern. If you haven’t read it yet, do yourself a favor and go do so. I’m not going to talk about his subject matter here, really, but there was a very interesting reply in this posting from Ward Bell who’s also got a blog that’s well worth reading. In the reply, Ward talks about simplifying XAML/WPF coding by using convention based programming. In particular, this paragraph in his response stuck out to me:
See, the thing is, we do have a way to easily walk the XAML tree. I’ve been playing around with a couple of different convention based solutions to WPF programming, some of which will see the light of day in Onyx in the near future, hopefully. What I’d like to do with this blog post is explore the idea, describing a concept that could be implemented to do exactly what Ward wants. I’m going to discuss implementation details, but I’m not going to provide code. This is all theoretical and is being presented for discussion purposes. Ward gives a use case where he has a TextBox that’s been provided an x:Name value. He then says “A one-line wizbang in the code-behind constructs the binding for us ... and not just for this TextBox but for every control bound to a property of Person.” First, I don’t like the idea of needing a “one-line whizbang in the code-behind.” I’d propose that instead we rely on an attached property/behavior to do this. Onyx already has the perfect attached property for this: View.ViewModel. The change handler for this attached property can walk the tree to provide our convention based bindings. In WPF we can actually use a trick that would enable us to not even have to walk the tree manually. View.ViewModel in the WPF version of Onyx is marked as an inherited property, so we’ll get change notifications for every child element which means WPF has done the work of walking the tree for us. In Silverlight you’ll have a bit more work to do, and it may be a bit tricky to handle some timing issues, but it’s all very doable. I’d like to discuss using x:Name as the hook to use for our conventions. I don’t like this, for a few reasons. First, the fact that x:Name creates backing fields for you is something that I don’t care for, unless your intention really is to have a backing field. Second, x:Name is meant to be unique, while there will be several scenarios where we don’t want to be restricted in this manner. So, I’d propose using a special attached property for our hook. I’m struggling with a good name for this one, but for now let’s just call it View.Moniker. So, now we have everything that’s necessary to do data binding by convention instead of configuration. But we can carry this idea much further. Let’s say we have a Button that we’ve given a View.Moniker of “Save”. If we have a SaveIsEnabled property on our ViewModel, that should be bound to the IsEnabled property of the Button. If we have an OnSaveClicked method on the ViewModel, that should be added as an event handler for the Click event of the Button. If we have a SaveCommand property on the ViewModel, that should be added as a command binding on the Button. You can imagine several other conventions to adhere to, so this should be an extensible concept. Instead of hard coding the conventions, include an ApplyConventions (needs a better name) event that can be hooked into to apply the conventions required by the individual application. So, what are your thoughts on this? July 22 Why EventAggregator?This is a serious question, though maybe you’re thinking about the wrong answers. See, I understand why one would want to decouple communication between a subject and observer. What I don’t understand is why we need a “fancy schmancy aggregator object” to do this. I’ve seen several designs, and several criticisms of every one of those designs and in every case I wonder if there’s a design that could make everyone happy. However, more importantly, I come back to wondering why we need an aggregator at all. Seems to me a static event and Publish method would eliminate the need for an aggregator at all. public static class Events { public static event EventHandler CustomerAdded; public static void PublishCustomerAdded(object sender) { EventHandler handler = CustomerAdded; if (handler != null) { handler(sender, EventArgs.Empty); } } } To subscribe to the “aggregated event” you just follow normal conventions. private void Subscribe() { Events.CustomerAdded += OnCustomerAdded; } To publish the “aggregated event” you simply call the method provided for this purpose. private void Publish() { Events.PublishCustomerAdded(this); } There’s lots of benefits to this design.
The only downside I see is that there doesn’t have to be a single “registry” for aggregated events (though there can be), but whether or not that’s a downside is certainly debatable. I’m really curious what other people see as reasons to prefer an EventAggregator over this simple pattern? July 21 Services – Your ViewModel Death Star
Services? So, what is a service? This very question got asked on Stack Overflow in response to an answer I gave to another question. Like I answered on Stack Overflow, put simply, a service is an object that provides functionality to be used by other objects. These services are generally provided to the other objects through either the Service Locator or Inversion of Control patterns. Onyx provides a generalized mechanism for this using the Service Locator pattern, hopefully with the hooks necessary to override this to use Inversion of Control instead. In any event, services are powerful, because they are reusable pieces of code that can be easily replaced with alternative implementations. This means that at runtime they can do all the logic necessary to accomplish your task in a tightly coupled fashion, just as you would have in the old days before the ViewModel pattern using event handlers in your codebehind. Then in your tests you can replace this behavior with test doubles that provide the behavior you need for the test in a way that’s not coupled to any UI. Message Boxes Let’s try and make this concrete with an example. One problem that everyone new to the ViewModel design pattern asks about is how you display a MessageBox to the user in response to something that occurs in a Command handler in the ViewModel. You can’t simply call MessageBox.Show, because that’s makes the code impossible to test. This is one problem for which, although there might be alternative solutions, the best solution is to use a service. The first thing to do when here is to define our service. Since a service needs to be replaceable, we need to use either an abstract class or an interface to define the service. We’ll stick with using an interface. public interface IDisplayMessage { void ShowMessage(string message); } I’ve kept this very simple for this blog post. Onyx actually defines an IDisplayMessage service that’s more complete, allowing you to fully specify all of the optional parameters that you can supply when calling MessageBox.Show, but that would be a distraction to this conversation. OK, the service is defined. Now we need to provide an implementation. internal class DisplayMessageService : IDisplayMessage { public void ShowMessage(string message) { MessageBox.Show(message); } } Again, this is a simplified implementation for the purposes of discussion here. All that our service does is delegate to MessageBox.Show, which is a tightly coupled implementation. That’s fine, because when we use the service, we won’t be tightly coupled, since we can provide a different implementation of the service. For instance, not only can we provide a test double in our unit tests, but we could also decide that instead of display a modal dialog, all such messages should be displayed in a list in a docked message window in our UI, and this change doesn’t require any modification to the ViewModels that use the service. Next up, we have to supply the service to our ViewModel somehow. We’ll do this by adding a parameter to the constructor, which is the Inversion of Control pattern. public Window1ViewModel(IDisplayMessage displayMessage) { this.displayMessage = displayMessage; Then in the ViewModel we can use this service to display a message. this.displayMessage.ShowMessage(string.Join(Environment.NewLine, this.SelectedDisciples.ToArray())); Keeping things simple, we’ll just manually supply the service when we create the ViewModel (this is often referred to as “poor man’s dependency injection” since we’re not using a container). this.DataContext = new Window1ViewModel(new DisplayMessageService()); Keep in mind that everything we did here was the simplest possible implementation that can illustrate how to use services, and not necessarily the best or most maintainable way of doing this. I don’t want to confuse you with the extra code necessary to use a container for either service location or dependency injection, as those are architectural artifacts not necessary to the concept of using services. So, we declared a service for displaying messages to the user, implemented a version that will display a MessageBox, provided the service to the ViewModel, and used it to display a message. We now have a ViewModel that displays a message in a way that’s decoupled from how the message is displayed and thus decoupled from the View and testable. All of this easily allowed us to solve a problem that at first look appears to be extremely difficult to implement when following the ViewModel design pattern. You’ll find nearly everything you run into that appears to be complicated to do when following the ViewModel pattern is actually easy to solve by using a service. In fact, you can find yourself going overboard here, and use services for problems that are better solved using other mechanisms. For instance, you could use a service to replace data bindings, but that wouldn’t be the correct solution to the problem. Don’t be too enticed by the power of services. Look first for alternative solutions, and if none present themselves, then look to the service as your solution. Remember the analogy from the last post, which is even more poignant this time around. You wouldn’t go duck hunting with a death star, nor should you solve most day to day problems with services. However, it’s nice to know there’s no problem you can’t solve as long as you’ve got services to back you up. July 14 Behavior – Your Trusty ViewModel Bazooka
The “Little Guns” First, I’d better step back. I call the attached behavior and services “big guns” for a reason. They should not be your tool of choice on a daily basis. You wouldn’t go duck hunting with a bazooka, nor should you solve most day to day problems with behaviors or services. Most of the day to day problems are solved with the “little guns”, data bindings and commands. We’re only going to pull out the “big guns” when the problem is so large that the “little guns” wouldn’t put a dent in it. Attached Properties OK, today we’re just going to discuss attached behaviors. But in order to do so, we need to back up a little bit and discuss attached properties. I suppose, if I were really going to be thorough, I should back all the way up and discuss dependencies properties, but if you’re new enough to WPF to need me to go back that far, you’re not ready for this discussion ;). An attached property is a dependency property that’s defined on one type, but that can be applied to a dependency object of another type. The typical example given when talking about attached properties are the Grid.Row and Grid.Column properties. These are defined by, and used by, the Grid type, but you set their values on children of the Grid that probably are different types that are entirely unaware of the Grid type and these properties. <Grid Margin="4"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ListBox Grid.Row="0"/> <Button Grid.Row="1" Content="Test"/> </Grid> The Remora Pattern Early in the WPF lifetime, one BenCon blogged about a pattern that he called the Ramora (sic) pattern. I’m not sure if he’s the first to discover this pattern or not, but I’m going to give him credit, as folks are want to do on the intarweb thingy. Over time, this pattern came to be more commonly known as an “attached behavior”, and more recently with the Blend SDK we now just call it a Behavior (though a Behavior is a class that encapsulates this stuff, so don’t let that confuse you). Basically, and attached behavior is just an attached property that when set it applies some behavior to the item it’s attached to, usually by subscribing to some event on the item. If that’s clear as mud to you, hopefully things will become more clear as we actually implement a behavior. This idea is important to the ViewModel design pattern because often what you’re wanting to do is enable the ViewModel to change the behavior of the View in some way. Selection We’re going to look at one of the more common problems you may face when following the ViewModel pattern that’s easily solved by using an attached behavior: tracking and changing the selection in a multi-select ListBox. For single-selection you have a couple of options. The CollectionView has a CurrentItem property that will be the selected item. However, it doesn’t expose a property that represents the selected items. On the ListBox itself the SelectedItem is a dependency property that you can bind to a property on your ViewModel. However, the SelectedItems is a read-only dependency property and can’t be used to track selection directly. The ListBox does have a SelectionChanged event that could be bound to the ViewModel, but that will only provide you with half a solution. You’re ViewModel could use this to track the selection made by the user, but could not use it to programmatically change the selection. An attached behavior is a perfect solution to this problem. An attached property can be used to bind to a collection exposed by the ViewModel, and the remora pattern can then be used to monitor changes to either the ViewModel’s collection or the ListBox.SelectedItems collection, and apply those changes to the other collection. public static class Selection { private static readonly DependencyProperty SynchronizerProperty = DependencyProperty.RegisterAttached( "Synchronizer", typeof(ListSynchronizer), typeof(Selection)); public static readonly DependencyProperty ItemsProperty = DependencyProperty.RegisterAttached( "Items", typeof(IList), typeof(Selection), new PropertyMetadata(null, OnItemsChanged)); public static IList GetItems(DependencyObject source) { return (IList)source.GetValue(ItemsProperty); } public static void SetItems(DependencyObject source, IList value) { source.SetValue(ItemsProperty, value); } private static void OnItemsChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { IList targetList = null; MultiSelector selector = source as MultiSelector; if (selector != null) { targetList = selector.SelectedItems; } else { ListBox listBox = source as ListBox; if (listBox != null) { targetList = listBox.SelectedItems; } } if (targetList == null) { return; } ListSynchronizer synchronizer = (ListSynchronizer)source.GetValue(SynchronizerProperty); if (synchronizer != null) { synchronizer.Dispose(); } IList sourceList = (IList)e.NewValue; if (sourceList == null) { return; } synchronizer = new ListSynchronizer(sourceList, targetList); } } Internally here we’re using a ListSynchronizer type to encapsulate all of the event handling logic, and we’re storing an instance of this type in a private attached dependency property. Here’s the ListSynchronizer in all of its glory. internal sealed class ListSynchronizer : IDisposable { private bool disposed; private IList source; private IList target; public ListSynchronizer(IList source, IList target) { this.source = source; this.target = target; StartListening(this.source); StartListening(this.target); Synchronize(); } ~ListSynchronizer() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void StartListening(IList list) { INotifyCollectionChanged incc = list as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged += OnCollectionChanged; } } private void StopListening(IList list) { INotifyCollectionChanged incc = list as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged -= OnCollectionChanged; } } private void Synchronize() { Synchronize(this.target, this.source); if (!this.target.Cast<object>().SequenceEqual(this.source.Cast<object>())) { Synchronize(this.source, this.target); } } private void Synchronize(IList source, IList target) { StopListening(target); try { foreach (object item in source) { target.Add(item); } } finally { StartListening(target); } } private void OnCollectionChanged( object sender, NotifyCollectionChangedEventArgs e) { IList targetList = object.ReferenceEquals(sender, this.source) ? this.target : this.source; switch (e.Action) { case NotifyCollectionChangedAction.Add: PerformActionOnList(targetList, e, Add); break; case NotifyCollectionChangedAction.Move: PerformActionOnList(targetList, e, MoveOrReplace); break; case NotifyCollectionChangedAction.Remove: PerformActionOnList(targetList, e, Remove); break; case NotifyCollectionChangedAction.Replace: PerformActionOnList(targetList, e, MoveOrReplace); break; case NotifyCollectionChangedAction.Reset: Synchronize(); break; } } private void PerformActionOnList( IList list, NotifyCollectionChangedEventArgs e, Action<IList, NotifyCollectionChangedEventArgs> action) { StopListening(list); try { action(list, e); } finally { StartListening(list); } } private void Add(IList list, NotifyCollectionChangedEventArgs e) { int itemCount = e.NewItems.Count; for (int i = 0; i < itemCount; i++) { int insertionPoint = e.NewStartingIndex + i; if (insertionPoint > list.Count) { list.Add(e.NewItems[i]); } else { list.Insert(insertionPoint, e.NewItems[i]); } } } private void MoveOrReplace(IList list, NotifyCollectionChangedEventArgs e) { Remove(list, e); Add(list, e); } private void Remove(IList list, NotifyCollectionChangedEventArgs e) { int itemCount = e.OldItems.Count; for (int i = 0; i < itemCount; i++) { list.RemoveAt(e.OldStartingIndex); } } private void Dispose(bool disposing) { if (this.disposed) { return; } if (disposing) { StopListening(this.source); StopListening(this.target); } this.disposed = true; } } OK, that code is admittedly a tad complicated, but using it is not. <ListBox Grid.Row="0" SelectionMode="Extended" ItemsSource="{Binding Disciples}" ui:Selection.Items="{Binding SelectedDisciples}"/> I should note, similar behaviors have been posted before, including one by fellow Disciple Marlon Gretch. I chose to use this one anyway, because it does the best job of illustrating how a behavior can solve a common ViewModel problem. Besides, I think I was the first person to post such a solution to this problem, though finding it is difficult. I won’t point you there now, because this is a much better implementation and description. I hope this helps someone new to WPF and the ViewModel pattern. Next up, services! Edit: Ran across a blog post today by Edward Tanguay with another example, binding to a PasswordBox, where behaviors allow you to work around what would otherwise be a tricky area in the ViewModel pattern (I'll note that another Disciple Peter O'Hanlon also blogged about a behavior for this, and I've had this one in my bag of tricks for quite a while). July 13 SketchFlow BookUnless you’ve been living under a rock, or you’re not a WPF/Silverlight developer I suppose, then you’ve heard about SketchFlow. We recently were given access to this exciting new tech in a recent Blend 3 release candidate (you’ll probably want the Silverlight 3 tools and developer runtime as well). SketchFlow allows a designer to create prototypes that use actual WPF code that will be your starting point for the real application, but using a style that makes the PHB not assume the code is close to being ready to ship. This prototype also allows the PHB and other interested parties to annotate the live running application with feedback notes and “penciled” markings. This feedback can be exported and sent back to the designer, who can quickly make suggested changes. This is probably one of the most obvious, yet never implemented (to my knowledge) ideas to ever come down the pike. It’s sheer genius! So, we get our first access to SketchFlow last week, and now there’s already public information about a book on the subject, including a free chapter download! Haven’t read this yet, but you know I’m going to. July 09 Value ConvertersI need to get into blogging more. So, today, I’m going to start by blogging about a topic that came up in my development efforts recently. I’m going to discuss ValueConverters and an interesting way to implement them in WPF. In case you don’t know what a ValueConverter is, it’s a class that implements the IValueConverter interface and is used to convert to and from one value to another. Often these values are of different types, but that’s not a requirement of a ValueConverter. WPF ships with a few ValueConverters out of the box, such as the BooleanToVisibilityConverter, but there’s plenty of room for your own ValueConverters. Josh Smith recently started a discussion on the WPF Disciples list about whether or not ValueConverters were still needed when using the ViewModel pattern. Like most such philosophical questions, I’m not sure we came to a definitive answer, but I’m going to state my opinion here. While it’s true that you could put all of your value conversions into the ViewModel, with expose properties for exactly what you want to use in the View, there are reasons to not always want to do this. First, it’s not very DRY (Don’t Repeat Yourself) to hand code the conversions over and over again in your ViewModels. ValueConverters are little pieces of code that can be reused over and over again. Second, doing all of your conversions in the ViewModel can result in more complex interfaces. For example, imagine we have some boolean value in our Model layer that will be used to determine whether or not some controls are enabled in the UI. If it’s true, some controls will be enabled while others will be disabled. If we were to handle this entirely within the ViewModel, we’d require at least two properties, one for enabling some of the controls and another for disabling the rest. You can see how your complicating the ViewModel here when you expose two properties for the same logical state just to allow for different UI state. In a little bit I’ll show you a NotConverter that would allow you to continue to expose a single property here, which makes for a more logical interface design on the ViewModel. Finally, it usually doesn’t make sense to expose purely visual information from your ViewModel. For example, imagine that same boolean value from the Model is going to be used to change the color of some text in the UI. At first the designer decides it should be Red when the value is True, but later decides it would make the text look too much like an error indication so he wants to make it Orange instead. If you’d done the conversion in the ViewModel, you’d have to change code every time such decisions were made, while if a configurable ValueConverter had been used, the designer could just change the XAML. So, now that I’ve explained what ValueConverters are for, and why you should still be inclined to use them despite the fact that you’re using the ViewModel pattern (you are, aren’t you?), lets dig into a little trick you can use when writing a ValueConverter. I talked earlier about a NotConverter, so let’s start with that. Imagine we’ve already coded the NotConverter in the typical fashion. Here’s how you would use the converter in your XAML. <Window x:Class="WPFConverters.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="clr-namespace:WPFConverters" Title="Window1" Height="300" Width="300"> <Window.Resources> <ResourceDictionary> <ui:NotConverter x:Key="NotConverter"/> </ResourceDictionary> </Window.Resources> <StackPanel> <CheckBox IsChecked="{Binding IsDisabled}" Content="Disable"/> <Button Content="Test" IsEnabled="{Binding IsDisabled, Converter={StaticResource NotConverter}}"/> </StackPanel> </Window>
You have to declare the NotConverter in a ResourceDictionary and specify the binding should use it by using the StaticResource MarkupExtension. Well, recently I stumbled upon a trick that can simplify this. The idea is to make the NotConverter not only an IValueConverter, but also a MarkupExtension itself. Doing so simplifies the XAML into this. <Window x:Class="WPFConverters.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="clr-namespace:WPFConverters" Title="Window1" Height="300" Width="300"> <StackPanel> <CheckBox IsChecked="{Binding IsDisabled}" Content="Disable"/> <Button Content="Test" IsEnabled="{Binding IsDisabled, Converter={ui:NotConverter}}"/> </StackPanel> </Window>
I knew this couldn’t be a new idea, so I Googled it and came across this CodeProject article. There were several criticisms in the comments for the article about how the sample converter wasn’t really a singleton. There was also a link to a posting on this same topic by Dr. WPF. Having just read the CodeProject article, I left a comment about how this wasn’t a singleton and some perceived problems about it not being one. Shame on me. I made a classic mistake. People assume, because of the name, that a Singleton should enforce the creation of only a single instance. This isn’t true. If you read the classic GoF book on this pattern, although a single instance is typical scenario the pattern is really just about controlling how many instances are created. So, it might actually be argued that this is a Singleton. More importantly, it’s possible to implement this idea in a way that there’s no memory or performance reason to prefer the classic implementation to the MarkupExtension version, and that’s what I want to illustrate here. So, here’s the implementation of that NotConverter. [MarkupExtensionReturnType(typeof(NotConverter))] [ValueConversion(typeof(bool), typeof(bool))] public class NotConverter : MarkupExtension, IValueConverter { private static WeakReference Cache = new WeakReference(null); public override object ProvideValue(IServiceProvider serviceProvider) { NotConverter converter = (NotConverter)Cache.Target; if (converter == null) { converter = this; Cache.Target = converter; } return converter; } public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return !(bool)value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return !(bool)value; } }
The trick is to use a WeakReference to cache the converter, so we won’t keep any instances of the converter alive any longer than we would with the classic implementation. Next, the ProvideValue method will either return the cached converter, or will cache and return itself if there is no cached version. This eliminates the extra allocation pointed out in the implementations used in both the CodeProject article and the posting by Dr. WPF. Finally, the concern about the overhead of using this as a MarkupExtension is a red herring, since the classic implementation is already using a MarkupExtension (the StaticResource extension) itself. The end result, this new NotConverter should have all of the same runtime characteristics as the classic implementation, only it will be easier to use. There’s a variation on this I want to talk about. Some ValueConverters are configurable. For instance, I want to talk about the BooleanToVisibilityConverter. The one provided by WPF isn’t configurable, and that’s a shame. I never remember if the “not visible” value is Visibility.Hidden or Visibility.Collapsed, but it doesn’t matter, you want both in different circumstances. So, I’d like to provide a BooleanToVisibilityConverter that can be configured for either behavior. But since it’s configurable, how do I use this MarkupExtension trick? By caching values for any different configuration requested! [MarkupExtensionReturnType(typeof(BooleanToVisibilityConverter))] [ValueConversion(typeof(bool), typeof(Visibility))] public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter { private static WeakReference[] Cache = new WeakReference[] { new WeakReference(null), new WeakReference(null) }; private Visibility negativeVisibility = Visibility.Collapsed; public Visibility NegativeVisibility { get { return this.negativeVisibility; } set { if (value == Visibility.Visible) throw new ArgumentOutOfRangeException("Visible is not a valid negative visibility value."); this.negativeVisibility = value; } } public override object ProvideValue(IServiceProvider serviceProvider) { int index = NegativeVisibility == Visibility.Collapsed ? 0 : 1; BooleanToVisibilityConverter converter = (BooleanToVisibilityConverter)Cache[index].Target; if (converter == null) { converter = this; Cache[index].Target = converter; } return converter; } public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (bool)value ? Visibility.Visible : NegativeVisibility; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (Visibility)value == Visibility.Visible ? true : false; } }
Our cache is now an array, and we store each of the differently configured converters requested by the MarkupExtension using the same technique as we did with our NotConverter. Hope these ideas are useful for somebody. May 08 Hey, Twitter! I’m over here!OK, I need to stop being negative on my blog, but this rant has to be posted publicly. Twitter is a very useful service, and there’s a lot of new services popping up around it. Most of these new services actually rely on Twitter Search, though, and that’s where I’m in trouble. See, I’m invisible to Twitter Search. I’ve been using Twitter for nearly a year, but none of my Tweets appear. Makes it impossible to use hashtags, participate in Twibes and other things. I first noticed the issue a few months back when I tried to start using a #wpfonyx hashtag when tweeting about my Onyx project. The hashtag wasn’t working properly, and it took me a while doing some research to figure out the problem was that I simply was invisible to Twitter Search. On March 30, I opened a support request (Request 118748) explaining the issue. On April 1, @crystal closed the ticket with the following remarks.
Please note, this was a full closure of the ticket, which meant it was dead. Nothing I could do with this ticket after that. Also note that it was closed without a resolution. The link given doesn’t lead you to a posting which can be used to resolve the issue myself, but rather just takes you to a posting saying “yeah, we’re broke, nothing you can do, but hey, maybe you’d like to put a comment on this page to let us know you’re broken?” I thought this was horrid tech support. No company I’ve worked with would ever treat a tech support ticket in this fashion. What it comes down to is, they have a widespread problem, and don’t want to be burdened with having to track hundreds (thousands?) of tickets for the same issue. Their solution is this public forum posting. That’s a non-solution. From the customer’s end, there’s no longer any accountability. There’s no way for me to track the progress of the issue. So I put my comment on the page like they asked (which I did, more than once), and then what? They aren’t going to tell me when my problem is resolved. Theoretically I can get e-mailed with updates to this page, which I am doing, but that’s more than suboptimal. I now get spammed with nearly 30 updates a day, as more and more people add comments about how it’s broken, or still broken, for them. Worse, though, not only am I not able to track things, but Twitter Support isn’t either. They made some correction that evidently helped some folks out last month, but it didn’t correct the problem for everyone. There was no way for them to know that, however, unless people added new comments to this page. Now Twitter Support has the same problems with tracking that I do, but compounded because of the likely failure to track by the users. On April 21, I got fed up with this and opened a new request, Request 196806.
This request was promptly marked as resolved (don’t know the exact terminology that Twitter Support uses here, but this is the state that should have been used with the first ticket, as it allows me to reopen the issue if I don’t believe it is resolved). The history on the ticket doesn’t show me the full history (yet one more thing they should fix), it only shows me the comments that I added. So I can’t reveal exactly what they said, but there’s enough in my response when I reopened it to give you an idea.
Yeah, I know, I was a jerk here, and I’m showing my dirty laundry to the world. However, I think I was justified in being a jerk, since I was being jerked around by them. I understand Twitter is a free service for me, but that’s no excuse for acting so unprofessionally here. Heck, they couldn’t even be bothered to read the ticket, as the majority of their response had already been explicitly addressed. So, in my humble opinion, Twitter Support needs a major overhaul. However, the problem isn’t just Twitter Support. Obviously Twitter Development has some major problems as well. They have a known issue that’s impacting a very large number of users. It’s a fairly serious issue, and not just a minor inconvenience. This should be high priority. In addition, as a developer myself, it seems to be a problem that shouldn’t be that hard to diagnose and correct, and if it is, that would just speak volumes about the codebase. Yet, here I, and many others, are… invisible. This seems to be nearly as big of an issue as the stability problems Twitter suffered a while back. Update: On 5/13, Twitter shut down the forum page, claiming the problem was fixed. They also closed my support ticket. I was skeptical that the "fix" would apply to my own issue, and tweeted about it yesterday (along with several other tweets). Today, I'm still invisible to search. So, my skepticism was well founded. They closed the ticket assuming the problems were the same, without testing, despite the fact I explicitly stated it was unlikely the issues were related. I've reopened the ticket, but I'm not holding my breath on this one. May 05 WPF Model-View-ViewModel Toolkit 0.1In case you’ve missed the announcement, Microsoft has released a new toolkit as part of the WPF Futures which is meant to aid in the development of WPF applications that follow the M-V-VM (hence forth, I’ll call this View Model) pattern. Here’s my impressions of what was released. First, I’ll look at the Word documents included. There’s two parts to this. Part 1 provides a general introduction to the pattern. The first section of this document discusses the “Model-View-X Paradigm”. Eek. That rankles with me. Sorry, I’m nit-picking here, but this is meant as constructive criticism. Why Paradigm, instead of Pattern, which is the accepted word to use? In any case, this section seems to struggle a bit with describing what differentiates View Model from the other patterns, including a reference to Presentation Model with little explanation to why there’s a mention (such as, they’re the same pattern, perhaps?). I think this just lends further proof that we either should be able to communicate the differences, or we should stick with a single name for the pattern. The rest of this document tries to justify the pattern with a sample application, but I think the justification is poorly presented. The problem is that they work backwards, starting with a spaghetti implementation, refining it a bit and trying to explain why it’s better. I think it would work better to state why one would use the pattern up front, and then demonstrate the differences in an implementation. As it is, trying to figure out why requires reading the entire document. I’ll also note that the current structuring required putting the unit testing last, which many TDD and BDD practitioners will take issue with. When unit testing is such an important reason for why you’d use this pattern, I really think this is a mistake. I’ll also note that the section on commanding could use some work. There’s little explanation as to why RoutedCommands are problematic, and the one reason given isn’t even valid (the target of a RoutedCommand must be part of the UI element tree… which is disproved by the Onyx command binding services that easily create command bindings for RoutedCommands with the ViewModel as the target). Part 2 provides a walkthrough of writing a contact book application following View Model pattern. The overview describes the roles of the three components: Model, View and ViewModel. I’ll take exception to the description of the ViewModel, which explicitly states the ViewModel should not be aware of the View. That’s not really a requirement of the pattern, and in fact, while you should avoid tight coupling as always, some knowledge of the View is often beneficial if not necessary. I don’t mind code/frameworks that are opinionated on this topic, but this isn’t a framework, and I’m not sure that Microsoft should be in the business of being opinionated on topics like this. When you run the project template, it creates a project with four folders: Commands, Models, ViewModels and Views. I’m not sure how I feel about that. I will say that I’ve never used a folder structure like this. My Models are nearly always in a separate project. I prefer my ViewModels to live right along side the Views, as it makes it easier to find and open these related components. Finally, my Commands are usually defined in the ViewModels and not in separate classes, much less folders. This structure is typical in a web MVC architecture, but this isn’t MVC and I just don’t think I like this layout. The template imperatively creates the View and the ViewModel and associates them in code. I don’t care for this at all, much preferring a declarative approach using the XAML markup. The association is also solely through the DataContext, which is fine, but I prefer to use a different DP (which usually sets the DataContext as well). Within a View, the DataContext will change frequently (for instance, in ItemsControls), but I still want to be able to talk about the ViewModel associated with the child elements. The template creates a DelegateCommand class with a good implementation. One sincerely hopes this is a stop gap solution, as DelegateCommand really should reside in a library (preferably the BCL) and not be generated by the template. In any event, the DelegateCommand is certainly a best practice, and appears to be the only such concept actually included here, which is strange. Where’s the ViewModel base? Where’s the helpers for validation, INotifyPropertyChanged, etc. I realize this isn’t a framework, but there should still be more support from the templates. How about a ViewModel item template that creates a class that implements INPC? One hopes that version 0.2 starts to address the low hanging fruit here. The section on unit testing is going to be controversial. Not only did we not follow TDD/BDD as I pointed out earlier, but the walkthrough utilizes the “Create Unit Tests…” feature, which is a questionable practice even if you’re not going to follow “test first”. The “ClearContactBookCommandTest()” is long and complicated with a total of 6 asserts spread out through the entire test. Definitely not unit testing best practice here. What’s really heart breaking is that there’s even three sections of asserts with comments that read “// Validate something”. Isn’t that a clear indication that they should be separate tests? I hope future releases do a better job of promoting best practices here. The Toolkit is probably useful to some, though I won’t be using it, and I can’t point someone new to View Model at this as a learning point. May 04 A Rose by any other nameOK, it’s official. The WPF community loves the Model-View-ViewModel pattern. That’s wonderful! However, I have always had problems with the name. So much so, that I’ve frequently jokingly used the good Dr.’s MVPoo name instead. So, what’s wrong with the name? As the good Doc explains, there’s a lot of variations on what’s basically the same pattern (forgive me for taking liberties here, as I do know that the variations have very important qualities that distinguish them as unique patterns in and of themselves, but once distilled down for the layman, they’re just different shades of red). Adding a new variation on the pattern can be confusing enough that one should endeavor to ensure there’s no duplication, and let’s be honest, Presentation Model already exists. To be fair, as far as I can tell form searching the Internet on this topic, the first public exposure to Presentation Model was in May of 2004, while the first time Microsoft publicly used the M-V-VM name was in October of 2005. It seems reasonable to me that this variation on M-V-C may have been independently “discovered” at the same time, so it’s more than easy to forgive the existence of two names historically. However, I still find it to be very unfortunate that we have two names for the same pattern. In an ideal world, I would suggest we stick with a single name, and since Presentation Model was publicly first, we should go with Presentation Model. However, this isn’t an ideal world. The WPF community is too strongly entrenched with the M-V-VM name. The community is just not likely to give the name up, no matter what we do or say now. If it helps (and it helps me), you can think of M-V-VM as a variation of Presentation Model that’s specific to WPF and its data binding and commanding infrastructure. Unfortunately, for outsiders already familiar with Presentation Model, even this explanation is likely to cause confusion, but it’s better than no explanation at all. OK, so I’m admitting the name isn’t ideal because of the existence of two names for the same pattern, but I’m also relenting to the pressures of the community who have already adopted the name. However, even then, I have some other problems with the name. Model-View-ViewModel is a mouth full. It’s just too much to say and/or type. The acronym M-V-VM is less to type, but it still stinks. It’s a pain to type with the hyphens, and impossible to read without them. When spoken, it’s a tongue twister worthy of inclusion in the Fox in Socks book. I’ve heard from a few insiders that there’s a growing movement to correct this issue by renaming the pattern to just ViewModel (I assume they mean without the space, though I’d prefer View Model which is more in agreement with Presentation Model). This caused me to go over my angst about the name all over again. If we’re going to change the name, you’ll have to get the community to agree with the change. M-V-VM is so entrenched now, that I’m not sure it’s possible. However, if all of the more influential folks within the community were to adopt the change, it is possible that the community could be swayed. If we were to make that attempt, though, wouldn’t it be better to take the opportunity to reduce the name down to a single name? In other words, wouldn’t it be better to try and sway the community to switch to Presentation Model, which was publicly first and more widely known in the broader community? It seems so to me. However, one could argue that it’s more likely that we’d persuade the WPF community to change the name to View Model than to Presentation Model, because View Model is just a shorter way of saying the already entrenched Model-View-ViewModel name. So, what do others think? Should we try and change the name within the WPF community? If so, what name should we try and change it to: Presentation Model, View Model, ViewModel, MVPoo? Edit: Some discussion about this blog entry has also gone on in the WPF Disciples list here. May 01 yUML – Quite the interesting web serviceIsn't that diagram spiffy? OK, I’ll be the first to admit, there’s nothing that exciting about the image here. What I do find quite interesting is that it was dynamically created by a web service through the simple use of an <img> tag.
The text representation of the diagram can certainly be cryptic and complex, and you’d hardly want to use this for a very large UML diagram, but for blog posts where you want to highlight some design aspects, it can sure be a useful little tool. Check out some other samples using the tool. April 16 Behavior Driven Design and Specificity – Part III previously wrote about some ideas I was toying with for Specificity to add a base class to aid in writing BDD style test fixtures in a portable (works with any unit testing framework) fashion. I’ve been using a solution like I posted then ever since, and have concluded the design is a bit fragile. Relying on the actual test methods to properly use the Result property in order to ensure Arrange and Act are called, just isn’t a production quality design. That got me to thinking, however. What I was trying to do here was a poor man’s attempt at AOP (Aspect Oriented Programming). The .NET world already has a better (though not perfect) solution for AOP in the form of ContextBoundObject. I should be able to leverage that and get a much better implementation of the concepts I wanted. In fact, there’s a CodePlex project that uses this idea already, called MSTestExtensions. I didn’t care for the way you had to write extensions using MSTestExtensions, and it wasn’t going to work out of the box for my BDD base class in any event, so I had to just borrow the idea without using it. So, I spent a couple of days hacking, and the result is now in the Specificity project. I’m still not entirely convinced I’ve got the correct extension mechanism baked in, so if you start to use this code, beware that I’m very likely to make breaking changes in this area of the API. So, what did I come up with? First, there’s an ExtendableTestFixture base class that you inherit from if you want to be able to “extend” your test methods. This provides all of the ContextBoundObject magic, as well as provides the necessary hooks for you to be able to create TestExtensionAttribute attributes that actually modify the process flow of the test methods, allowing you to add code before or after the test method. The way you code a TestExtensionAttribute is where I’m most likely to make breaking changes. The BDD base class, called Observation in the previous post, is now called SpecificationContext. It inherits from TestExtensionBase and uses an internal SpecificationContextAttribute to cause all test methods to run the Arrange, Act and Teardown virtual methods. The use is the same as in the previous post (minus the Result property magic), but the implementation is now much more robust. There is a down side. ContextBoundObject adds some overhead to object creation and method calls that will slow your tests down. It’s my experience that the overhead isn’t all that great, and I’m more than willing to except it for the benefits provided here, but you’ll have to judge for yourself. There’s a couple of other test extension attributes included as well, just to illustrate that this is useful even if you’re not interested in using the SpecificationContext concept. There’s an ExpectedDurationAttribute which allows you to declaratively specify that a test shouldn’t take longer than some amount of time, and a TestTransactionAttribute that declaratively wraps your test method in a TransactionScope. I’ll admit, I’m not convinced attributes like these are appropriate… I’d prefer the non-declarative approaches, for many of the same reasons that I prefer Specify.That(action).ShouldThrow<Exception>() over ExpectedExceptionAttribute. However, I don’t want to force my opinions here on users, and I did need some attributes to illustrate what’s possible here. I’d love to hear feed back on this. March 20 Reflecting on CodeStatic reflection. It’s all the rage. What is static reflection? It’s obtaining type information at compile time instead of runtime, typically by using LINQ expression trees. Here’s my take on providing a static helper to do this. public static class Reflect { public static MemberInfo GetMember(Expression<Action> expression) { if (expression == null) { throw new ArgumentNullException( GetMember(() => expression).Name); } return GetMemberInfo(expression as LambdaExpression); } public static MemberInfo GetMember<T>(Expression<Func<T>> expression) { if (expression == null) { throw new ArgumentNullException( GetMember(() => expression).Name); } return GetMemberInfo(expression as LambdaExpression); } public static MethodInfo GetMethod(Expression<Action> expression) { MethodInfo method = GetMember(expression) as MethodInfo; if (method == null) { throw new ArgumentException( "Not a method call expression", GetMember(() => expression).Name); } return method; } public static PropertyInfo GetProperty<T>(Expression<Func<T>> expression) { PropertyInfo property = GetMember(expression) as PropertyInfo; if (property == null) { throw new ArgumentException( "Not a property expression", GetMember(() => expression).Name); } return property; } public static FieldInfo GetField<T>(Expression<Func<T>> expression) { FieldInfo field = GetMember(expression) as FieldInfo; if (field == null) { throw new ArgumentException( "Not a field expression", GetMember(() => expression).Name); } return field; } internal static MemberInfo GetMemberInfo(LambdaExpression lambda) { if (lambda == null) { throw new ArgumentNullException( GetMember(() => lambda).Name); } MemberExpression memberExpression = null; if (lambda.Body.NodeType == ExpressionType.Convert) { memberExpression = ((UnaryExpression)lambda.Body).Operand as MemberExpression; } else if (lambda.Body.NodeType == ExpressionType.MemberAccess) { memberExpression = lambda.Body as MemberExpression; } else if (lambda.Body.NodeType == ExpressionType.Call) { return ((MethodCallExpression)lambda.Body).Method; } if (memberExpression == null) { throw new ArgumentException( "Not a member access", GetMember(() => lambda).Name); } return memberExpression.Member; } } If you look closely, the code itself shows you a use for the idea. Yep, it’s definitely dogfood. Pay attention to how we raise ArgumentNullExceptions in this code. No “magic strings” for us. This is compiled code. If I use the wonderful IDE refactoring capabilities to rename the argument, the string passed to the ArgumentNullConstructor is also refactored, because it’s static code and not a string literal. There’s also situations where you don’t have an instance of data to use for reflecting, and the above code isn’t so useful in this case. That’s where it’s big brother comes in. public static class ReflectOn<T> { public static MemberInfo GetMember(Expression<Action<T>> expression) { if (expression == null) { throw new ArgumentNullException(Reflect.GetMember(() => expression).Name); } return Reflect.GetMemberInfo(expression as LambdaExpression); } public static MemberInfo GetMember<TResult>(Expression<Func<T, TResult>> expression) { if (expression == null) { throw new ArgumentNullException(Reflect.GetMember(() => expression).Name); } return Reflect.GetMemberInfo(expression as LambdaExpression); } public static MethodInfo GetMethod(Expression<Action<T>> expression) { MethodInfo method = GetMember(expression) as MethodInfo; if (method == null) { throw new ArgumentException( "Not a method call expression", Reflect.GetMember(() => expression).Name); } return method; } public static PropertyInfo GetProperty<TResult>(Expression<Func<T, TResult>> expression) { PropertyInfo property = GetMember(expression) as PropertyInfo; if (property == null) { throw new ArgumentException( "Not a property expression", Reflect.GetMember(() => expression).Name); } return property; } public static FieldInfo GetField<TResult>(Expression<Func<T, TResult>> expression) { FieldInfo field = GetMember(expression) as FieldInfo; if (field == null) { throw new ArgumentException( "Not a field expression", Reflect.GetMember(() => expression).Name); } return field; } } Now I can do something like this. class Program { public void Foo() { } static void Main(string[] args) { Console.WriteLine(ReflectOn<Program>.GetMethod(p => p.Foo()).Name); } } Want another, more practical use? public abstract class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate { }; protected void OnPropertyChanged() // All properties changed { OnPropertyChanged(null); } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } protected void OnPropertyChanged<T>(Expression<Func<T>> expression) { OnPropertyChanged(Reflect.GetProperty(expression).Name); } } public class Foo : ObservableObject { private string message; public string Message { get { return this.message; } set { this.message = value; OnPropertyChanged(() => Message); } } } No more magic strings when raising PropertyChanged from INotifyPropertyChanged implementations. The performance here is obviously worse than using the magic string, but it’s a lot better than using actual runtime reflection. March 17 Behavior Driven Design and SpecificityI’ve been using an assertion framework at least similar to the one I’ve put up on CodePlex called Specificity for quite some time now. The main goal of that library is solely to provide an assertion framework that’s extendable and discoverable, and it does so in a fashion that doesn’t tie it to any specific test framework. The naming conventions used within Specificity follow a more of the BDD form rather than the TDD form, with Should instead of Assert. However, I’ve not actually used any of the BDD frameworks available for .NET, mostly because I have to use MsTest at work and I am accustomed to using it and so continue to use it outside of work. Recently, I’ve been experimenting with following BDD at least to the extent that my unit testing framework of choice will allow (the Test terminology leaks through in the attribute names used, which BDD purists would not care for). This has eventually lead to me experimenting with a base class that I think may be useful for inclusion in Specificity. This base class isn’t tied to any testing framework, and thus could be a drop-in base class for tests you write using any existing testing framework, much like the assertions in Specificity. The base class is really quite simple, though I’m sure it could be expanded. Part of the inspiration came from Jean-Paul S. Boodhoo, though I’ve simplified it quite a bit in ways that most developers would be more comfortable with, I think. Here it is in all its glory (such as it is): public abstract class Observations<TResult> { private bool acted; private TResult result; protected TResult Result { get { if (!this.acted) { ArrangeAndAct(); } return this.result; } } protected virtual void Arrange() { } protected abstract TResult Act(); private void ArrangeAndAct() { Arrange(); this.result = Act(); this.acted = true; } } That’s it. I told you there wasn’t much to it. I’ve chosen to follow the AAA (Arrange, Act and Assert) terminology rather than the “context” and “because” terminology used by Jean-Paul, but the examples from the blog post of his that I linked are easily translated. Here’s his first example, just to give you the flavor of how this is used. [TestClass] public class When_adding_2_numbers : Observations<int> { protected override int Act() { return 2 + 2; } [TestMethod] public void should_result_in_the_sum_of_the_2_numbers() { Specify.That(this.Result).ShouldBeEqualTo(4); } } Of course, this was in MsTest, but you should be able to easily translate it to whatever test framework you use. I’ve not leveraged the Setup concepts available from most testing frameworks because it would tie the code to a specific testing framework, and because some frameworks (looking at you, xUnit.net) don’t have the concept, relying on the constructor instead. I’ve not addressed cleanup here, though it should be possible to work that one out. If your test methods are side effect free (they should be), there’s little purpose in enabling cleanup, so I’ve not bothered to think to deeply on that one. This seems extremely simplistic, but the point behind the base class is to force a BDD approach to testing, where you have a test per feature, rather than a test per class. It’s a poor man’s addition to a TDD framework to enable a BDD style. I’d love to hear input on this one. What do people think of the idea? What about the implementation? Should something like this go into Specificity? Nit-pick me to death, please. March 11 Onyx and SpecificityIn case you've not seen it other places, I've started a couple of CodePlex projects myself. The first is an assertion library for unit testing, with a focus on extensibility and intellisence discover ability, called . The second is a WPF framework to aid in the development of applications that use the M-V-VM design, called Onyx. Both are still under development and haven't yet had a release, but the code is usable and worth checking out. A Thriple PlayJosh Smith, a fellow Disciple who probably needs no introduction, has released a new project on CodePlex called Thriple. This project aids in the use of 3D concepts within WPF by providing simple concepts that do the heavy lifting for you: ContentControl3D which contains a BackContent as well, and can rotate to show both sides; and Panel3D which shows it's content along a single path in 3D space. This is definitely a project worth checking out if you want to add the final polish to your WPF applications, without having to learn the complicated 3D APIs. March 06 Dueling BanjosIn this case, the “banjos” are FXCop and StyleCop. Can’t we all just get along? Here’s the deal. I’m a big proponent of using static checkers such as FXCop and StyleCop. I think they go a long way towards improving the quality of code. However, lately there have been a few things about these tools that have been driving me crazy. Let’s start with FXCop. There’s a couple of warnings you run into frequently when developing in WPF (at least, I do). CA1810 is a warning about performance when you use a static constructor instead of a static initializer. My first though is, how bloody important is this sort of optimization? The hit can’t be that big, especially when you consider it’s a one time hit and not something that can be amplified by usage in a loop. This sounds like premature optimization to me, and we all know the famous quote about that! Normally, however, this would be a minor thing to comply with, and wouldn’t occur all that often. In fact, my natural instinct is to use an initializer. However, in WPF the static constructor is often required for things like registering class event handlers with the EventManager. You can’t really use an initializer for this, and suppressing this every time it happens is a PITA. At least with FXCop I can turn the rule off, even if I do have to manually do that for each and every project (hint Microsoft: we could use some sort of solution based configuration here). The next FXCop warning that’s annoying me a lot is CA1004, which complains when you use a generic type parameter only in the return type and not as a parameter type. Seems this is supposed to be “confusing” for developers. Well, I call BS. If you don’t understand how generics work, you probably shouldn’t be coding in .NET languages that support the concept. If you look around it’s really not uncommon at all to have code that uses a generic parameter as the return type, as syntactic sugar to simplify scenarios where you’d otherwise have to employ a cast. Again, though, I can turn this one off. StyleCop has a lot of rules I don’t agree with as well. The bloody file header stuff serves no real purpose, other than keeping specific legal counsel happy. Legally, you don’t have to provide a copyright statement at all: your code will still be protected by copyright laws. You certainly don’t have to repeat it for every file in a project. Not only does it clutter the source, it’s a PITA when the copyright notice must change (such as a change on the date). I also hate the warning that wants you to place the imports inside the namespace. VisualStudio doesn’t like this, either. The default templates put the imports outside, and intellisense helpers have a hard time with indentation for imports they add when inside the namespace. All for something that, despite the attempts to make it sound like a sound technical thing to do, it’s really just a “tabs vs. spaces” kind of debate. However, what I’m here to talk about today is how these two tools sometimes don’t like each other. The specific issue I want to talk about is with naming member variables. See, StyleCop doesn’t like you to use “warts” or “hungarian notation” at the beginning of member variable names. This means the typical usages of “m_” and “_” at the beginning of member variable names is verboten, according to StyleCop. OK, let’s not get into any “religious arguments” over this. I prefer the warts, honestly, but I can live without them. So, the warts are gone. I no longer use them, in order to keep StyleCop happy. Unfortunately, this means I often make FXCop unhappy. See, FXCop has this warning, CA1500, which complains when you use a local variable name that’s the same as a member variable name (thankfully, it doesn’t complain when you do this with parameters to constructors. However, it’s still fairly common to need a local representation of data for the same thing as the member. Argh!!! I’ve actually resorted to use names like “theWidget” instead of “widget” for local names, just to shut the tools up. This is a wart, but because it’s a word, StyleCop won’t complain. Sad. Very sad. I’d rather go back to using “m_” or “_” on member variable names (though “this._widget”, which another StyleCop rule requires, is a bit silly). Well, enough ranting. I’ve got work to do. February 10 EventWaitHandle considered harmfulRan across this MSDN page while searching for something else today. A “Community Content” response by “mike_msdn” asked the following question:
The short answer to this is “yes”. Like many other code samples in MSDN, this one is utter crap. Just riddled with bugs. Be careful you understand the code when using any examples you find on the Internet, even if the source is one that should be authoritative. (An interesting aside: there are folks at Microsoft who understand this topic, yet we still get broken samples in the MSDN.) Like the title of this blog says, I’m going to go out on a limb and say that EventWaitHandle should be considered harmful. Actually, this isn’t the first time I went out on that limb, as when I worked on Boost.Threads I constantly had to explain how Win32 synchronization event objects were dangerous little buggers that should be avoided like the plague. I wish the things didn’t exist, as 9 times out of 10 (or worse) when someone uses an EventWaitHandle, they shouldn’t have. It’s a rare scenario in which an EventWaitHandle can be safely used, and an even rarer scenario in which it’s the solution you should choose. So, what’s wrong with EventWaitHandle? It doesn’t address the issue of synchronizing access to shared state. This means that if shared state is involved you have to use some other synchronization mechanism in conjunction with the EventWaitHandle. However, this introduces race conditions between the wait and the lock. This is a subtle race condition as well… one that will go undetected for years, and then fail miserably at the worst possible time. Don’t believe me? Do a Google search on how to implement a “condition variable” on Win32. A condition variable is a special synchronization concept that combines the “unlock-wait-lock” set of operations into a single atomic operation, avoiding the race conditions I’m talking about here. When you do the Google search, the first thing you should notice is how complicated many of the solutions are. That should be enough to convince you that EventWaitHandle is the wrong solution in these scenarios. If not, really start to dig into the search results and see how most of those implementations have been proven to be broken. Then look at the implementation in Boost.Threads. If you can understand that implementation, then you have enough knowledge to safely use an EventWaitHandle… but you’ll also know better than to do so ;). Back to the question by “mike_msdn". If the sample code is broken, how would you implement a producer consumer? Wikipedia has an entry on this. You could decide to use a Semaphore solution, as the article shows. This requires two Semaphore objects and a lock. Unlike EventWaitHandle solutions, when coded correctly, there’s no race condition between the Wait on the Semaphore and the lock, because we take advantage of the semantics of the Semaphore count. The other solution, and the simplest solution, is to use a “monitor”. Remember that “condition variable” I talked about before? Well, a “monitor” basically marries a “condition variable” and a “mutex” into a single concept. The .NET runtime has supported this concept since the beginning, with the Monitor static class. Here’s partial code to “fix” the buggy MSDN code, using a monitor (you should be able to figure out the missing pieces of code… I don’t have the time right now to create a fully working sample). public class SyncObject { public bool exit; } public class Producer { private readonly Queue<int> _queue; private readonly SyncObject _sync; public Producer(Queue<int> q, SyncObject sync) { _queue = q; _sync = sync; } public void ThreadRun() { int count = 0; Random r = new Random(); lock (_sync) { while (true) { while (_queue.Count >= 20) { // This loop waits for the consumer Monitor.Wait(_sync); } Monitor.Wait(_sync, 0); // Release the lock to allow exit flag to be set if (_sync.exit) { break; } _queue.Enqueue(r.Next(0, 100)); Monitor.Pulse(_sync); count++; } } Console.WriteLine("Producer thread: produced {0} items", count); } } public class Consumer { private readonly Queue<int> _queue; private readonly SyncObject _sync; public Consumer(Queue<int> q, SyncObject sync) { _queue = q; _sync = sync; } public void ThreadRun() { int count = 0; lock (_sync) { while (true) { while (_queue.Count == 0 && !_sync.exit) { Monitor.Wait(_sync); } if (_sync.exit) { break; } _queue.Dequeue(); Monitor.Pulse(_sync); count++; } } Console.WriteLine("Consumer thread: consumed {0} items", count); } } Like I said, the Monitor stuff has been in .NET from the very beginning. It’s sad that very little code makes use of it. It’s scary that a lot of code that doesn’t is instead relying on buggy constructs, often using EventWaitHandle objects. January 12 StubsSeems that Pex is shipping with a new framework for creating “stubs” for use when creating unit tests. When I first read about this, the source generation aspect made me skeptical. However, the general design of these stubs I find quite intriguing. Traditional Mock frameworks (you need to understand the differences between various “test fakes”, but I’m not differentiating in this post) use code generation (Reflection.Emit) to create dynamic proxies. Unfortunately, this means that when you have to stub out what you expect a method to return, for instance, you have to write a significant amount of code that, while usually “fluent”, isn’t very natural. In fact, this sort of code in unit tests has been one of my least liked aspects of doing TDD. The tests just aren’t easy to write, or to read. However, the delegate based approach I find to be much easier to understand. Maybe that’s just me, but I find it so much easier to code and later read and understand, that I’m switching immediately. However, the Stubs framework itself isn’t something I’m going to make the switch to, at least today. The issue isn’t the source generation. I’ve decided that’s not such an issue. The issue I have is simply one of licenses. Nothing wrong with the Pex license, other than it’s not compatible with my needs. Short term, I’m just going to start hand coding these stubs/fakes. It’s not that difficult, though making the code pass StyleCop makes them a little more verbose than I’d like for such boilerplate stuff. Long term, it might be worth looking into creating my own code generator for this. At some point, we can hope that the Pex Stubs library will move out of “research” and thus have a more widely usable license, but until then… December 19 Calculating Hash CodesI don’t know about you, but I find overriding Equals to be a pita. Why? Because if you override Equals, you also must override GetHashCode, and that’s just no fun. ;) ReSharper evidently will generate GetHashCode for you, according to this stackoverflow entry. That’s all find and dandy (if you use R#), but the code is a tad bit ugly if you’ve got to modify it. Not that it’s not very understandable, it’s just a lot to have to type out for each field that should participate in the calculation of the hash code. So, I got to thinking about whether a helper might not make this easier. Here’s what I came up with. Let me know what you think about this idea. public struct HashCode { private readonly int value; internal HashCode(int value) { this.value = value; } public static HashCode From<T>(T value) { return new HashCode(value.GetHashCode()); } public HashCode And<T>(T other) { int hash = this.value; unchecked { hash = (hash * 397) ^ other.GetHashCode(); } return new HashCode(hash); } public override bool Equals(object obj) { if (!(obj is HashCode)) { return false; } return this == (HashCode)obj; } public override int GetHashCode() { return this.value; } public static bool operator ==(HashCode left, HashCode right) { return left.value == right.value; } public static bool operator !=(HashCode left, HashCode right) { return left.value != right.value; } } public override int GetHashCode() { return HashCode.From(firstField).And(secondField).GetHashCode(); } I think that should be much easier to maintain. |
|
|