Archive for November, 2008

Isolater for SharePoint

Typemock are offering their new product for unit testing SharePoint called Isolator For SharePoint, for a special introduction price. it is the only tool that allows you to unit test SharePoint without a SharePoint server. To learn more click here.

The first 50 bloggers who blog this text in their blog and tell us about it, will get a Full Isolator license, Free. for rules and info click here.

ItemsSourceChanged Event using Attached Dependency Properties

If you stumble across this blog, you might have been searching for the non-existant ItemsSourceChanged event on a ListBox or ListView in Wpf.

Yeah… it isn’t there and it sucks.

But, there is a workable that I wouldn’t define as a hack. More of a Wpf extension. :D

I am a huge fan of Attached Dependency Properties. They are a perfect tool to extend the functionality of closed controls. Attached Dependency Properties also circumvent the pain of created your own custom control.

I am going to use an attached dependency property to mimic an ItemsSource Changed event.

The full code :

   1: /// <summary>
   2: /// ItemsSourceChanged Behavior uses an Attached Dependency Property
   3: /// to add and raise a rotued event whenever an ItemsControl's ItemsSource property
   4: /// changes. Also looks for INotifyCollectionChanged on the ItemsSource and raises the
   5: /// event on every collection changed event
   6: /// </summary>
   7: public static  class ItemsSourceChangedBehavior
   8: {
   9:     #region ItemsSourceChanged Property
  10:  
  11:     /// <summary>
  12:     /// ItemsSourceChanged Attached Dependency Property with Callback method
  13:     /// </summary>
  14:     public static readonly DependencyProperty ItemsSourceChangedProperty =
  15:                                               DependencyProperty.RegisterAttached("ItemsSourceChanged",
  16:                                               typeof(bool), typeof(ItemsSourceChangedBehavior),
  17:                                               new FrameworkPropertyMetadata(false, OnItemsSourceChanged));
  18:  
  19:     /// <summary>
  20:     /// Static Get method allowing easy Xaml usage and to simplify the
  21:     /// GetValue process
  22:     /// </summary>
  23:     /// <param name="obj">The dependency obj.</param>
  24:     /// <returns>True or False</returns>
  25:     public static bool GetItemsSourceChanged(DependencyObject obj)
  26:     {
  27:         return (bool)obj.GetValue(ItemsSourceChangedProperty);
  28:     }
  29:  
  30:     /// <summary>
  31:     /// Static Set method allowing easy Xaml usage and to simplify the
  32:     /// Setvalue process
  33:     /// </summary>
  34:     /// <param name="obj">The obj.</param>
  35:     /// <param name="value">if set to <c>true</c> [value].</param>
  36:     public static void SetItemsSourceChanged(DependencyObject obj, bool value)
  37:     {
  38:         obj.SetValue(ItemsSourceChangedProperty, value);
  39:     }
  40:  
  41:     /// <summary>
  42:     /// Dependency Property Changed Call Back method. This will be called anytime
  43:     /// the ItemsSourceChangedProperty value changes on a Dependency Object
  44:     /// </summary>
  45:     /// <param name="obj">The obj.</param>
  46:     /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
  47:     private static void OnItemsSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  48:     {
  49:         ItemsControl itemsControl = obj as ItemsControl;
  50:  
  51:         if (itemsControl == null)
  52:             return;
  53:  
  54:         bool oldValue = (bool)e.OldValue;
  55:         bool newValue = (bool)e.NewValue;
  56:  
  57:         if (!oldValue && newValue) // If changed from false to true
  58:         {           
  59:             // Create a binding to the ItemsSourceProperty on the ItemsControl
  60:             Binding b = new Binding
  61:                             {
  62:                                 Source = itemsControl,
  63:                                 Path = new PropertyPath(ItemsControl.ItemsSourceProperty)
  64:                             };
  65:  
  66:             // Since the ItemsSourceListenerProperty is now bound to the
  67:             // ItemsSourceProperty on the ItemsControl, whenever the 
  68:             // ItemsSourceProperty changes the ItemsSourceListenerProperty
  69:             // callback method will execute
  70:             itemsControl.SetBinding(ItemsSourceListenerProperty, b);
  71:         }
  72:         else if (oldValue && !newValue) // If changed from true to false
  73:         {
  74:             // Clear Binding on the ItemsSourceListenerProperty
  75:             BindingOperations.ClearBinding(itemsControl, ItemsSourceListenerProperty);
  76:         }
  77:     }
  78:  
  79:     #endregion
  80:  
  81:     #region Items Source Listener Property
  82:  
  83:     /// <summary>
  84:     /// The ItemsSourceListener Attached Dependency Property is a private property
  85:     /// the ItemsSourceChangedBehavior will use silently to bind to the ItemsControl
  86:     /// ItemsSourceProperty.
  87:     /// Once bound, the callback method will execute anytime the ItemsSource property changes
  88:     /// </summary>
  89:     private static readonly DependencyProperty ItemsSourceListenerProperty =
  90:         DependencyProperty.RegisterAttached("ItemsSourceListener",
  91:                                             typeof(object), typeof(ItemsSourceChangedBehavior),
  92:                                             new FrameworkPropertyMetadata(null, OnItemsSourceListenerChanged));
  93:  
  94:  
  95:     /// <summary>
  96:     /// Dependency Property Changed Call Back method. This will be called anytime
  97:     /// the ItemsSourceListenerProperty value changes on a Dependency Object
  98:     /// </summary>
  99:     /// <param name="obj">The obj.</param>
 100:     /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
 101:     private static void OnItemsSourceListenerChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
 102:     {
 103:         ItemsControl itemsControl = obj as ItemsControl;
 104:         
 105:         if (itemsControl == null)
 106:             return;
 107:  
 108:         INotifyCollectionChanged collection = e.NewValue as INotifyCollectionChanged;
 109:  
 110:         if (collection != null)
 111:         {
 112:             collection.CollectionChanged += delegate
 113:                                                 {
 114:                                                     itemsControl.RaiseEvent(new RoutedEventArgs(ItemsSourceChangedEvent));
 115:                                                 };
 116:  
 117:         }
 118:  
 119:         if (GetItemsSourceChanged(itemsControl))
 120:             itemsControl.RaiseEvent(new RoutedEventArgs(ItemsSourceChangedEvent));
 121:     }
 122:  
 123:     #endregion
 124:  
 125:     #region Items Source Changed Event
 126:  
 127:     /// <summary>
 128:     /// Routed Event to raise whenever the ItemsSource changes on an ItemsControl
 129:     /// </summary>
 130:     public static readonly RoutedEvent ItemsSourceChangedEvent =
 131:         EventManager.RegisterRoutedEvent("ItemsSourceChanged", 
 132:                                          RoutingStrategy.Bubble, 
 133:                                          typeof(RoutedEventHandler),
 134:                                          typeof(ItemsControl));
 135:  
 136:     #endregion
 137: }

 

By setting the ItemsSourceChanged property on any ItemsControl to true, the ItemsSourceListener property will be bound to the ItemsSource property. The ItemsSourceListener callback will be executed anytime the ItemsSource changes and therefore can raise the ItemsSourceChanged routed event.

Also if the ItemsSource implements INotifyCollectionChanged, I added a delegate so that on the CollectionChanged event, the ItemsSourceChanged event will also be raised.

Feel free to use the code and adapt it to your needs.

Peace out!

JB

Framework Design

I’ve been spending some time lately reading and listening to talks on Framework Design and Language Design. In particular, I’ve found Krzysztof Cwalina’s blog and PDC talk very enlightening. I also rather enjoyed the PDC panel discussion on the Future of Programming Languages. I find this all very fascinating, but in a recent desire to apply pragmatism, I wondered how any of this could really help me in my day-to-day development tasks. Except to program to the framework’s design for efficiency and consistency, I had a hard time with that question.

However, with regard to my new hobby of extracting reusable patterns from apps I’m building, I really appreciate the idea of extracting these patterns into small, reusable and interoperable parts. In the Future of Programming panel, Jeremy Siek noted the importance of libraries working with other libraries (e.g., ASP.NET with ASP.NET MVC or ASP.NET AJAX with many Javascript libraries). Some libraries, however, implement their patterns too tightly around certain patterns to the exclusion of others. This can increase speed—Ruby on Rails comes to mind—but removes the ability to use other patterns or pluggable libraries–such as with Merb or Ramaze–to keep to the Ruby frameworks.

JB and I are attempting to extract patterns from our current project to enable faster development in future WPF/Silverlight projects. The current plan is to build our library around Composite WPF, an excellent library from Microsoft’s Patterns and Practices group for building rich client applications in WPF, and soon in Silverlight. We’re planning to build a business layer framework with service interfaces to the Composite WPF library and use the Repository pattern to allow for various data access methodologies.

That’s a loose description of our plan. What do you think? Do you see any flaws? For instance, we are currently not thinking about interchangeable UI libraries, even though a few, such as Silverlight.FX, have started to appear. Are we missing any existing business layer libraries? (I am not familiar with any myself, but I imagine someone has created one somewhere.) We are interested in your thoughts!

Interfaces and Mock Objects (part 1 Coupling)

Lots of people having numerous bog entries, books, and essays, etc. on mock objects and testing.

Here is my attempt to express a simple but critical concept with development. I plan on breaking it down to simple examples.

I will provide smaller more focused blog entries just like I focus on coding smaller more focused classes, methods, and tests. :D

The purpose of creating interfaces and utilizing mock objects is to eliminate dependencies.

The goal is to have loose coupling between objects that interact.

What does coupling mean?

To summarize wikipedia, coupling is the degree to which an object relies on another object.

If an object relies heavily on another object, then it is said to be tightly coupled.

Example :

image

ClassA is said to be tightly coupled to ClassB because the Calculate method accepts the concrete class ClassB.

Meanwhile :

image

ClassC is said to be loosely coupled because instead of using a concrete class as a parameter, the Calculate method accepts an IDoStuff interface. Now ClassC isn’t coupled to any specific implementation of IDoStuff.

Here is an example of the flexibility this provides :

image

The quick summation is that since ClassA’s Calculate method required ClassB, ClassA was tightly coupled to ClassB.

With ClassC we leveraged the IDoStuff interface to de-couple ClassC from any implementers of IDoStuff. So ClassB and ClassD can implement IDoStuff and ClassC is not coupled to either of those implementations or any implementation. ClassC is only coupled to the interface.

Designing your code to be loosely coupled pays huge dividends for testing.

So that’s the brief focused blog entry for part 1!

Peace out!

JB

On the subject of blogging and originality

Timothy Zahn, a great science fiction author, in an afterward for a short story addressed the issue of originality.

He stated that with science fiction (as with other subjects) it is very difficult to be “original.” His argument was that it isn’t the originality of the idea that matters but what you do with it.

Of course South Park also captured this with the “Simpson’s Did It” episode where Butters as Professor Chaos kept trying to develop an original diabolical plan but kept just repeating Simpson plots.

This rambling is just to address the issue that not all blog entries can be original and often repeat the same info found elsewhere. If I do use a blog as a resource then trust me, I will give credit. If someone else has already done a similar subject or blog and I did not give credit, then I did not know about it.

I will site resources I use and feel free to “trust, but verify” anything I write about.

So that is a brief post… more to follow.

Peace out!

JB

Back!

I doubt I had many followers on my blog from Software Architects, but I did enjoy blogging.

When I moved to Catapult Systems (my current employer) I was immediately involved with a Wpf and Silverlight project for a client. It was a nightmare in terms of scope creep, project management, and requirements gathering. In short, a major trial by fire.

I learned an enormous amount and am the better for it. But, since the project was always behind and there was always more work to do, I could not find the time to blog. And I did miss it.

Luckily I have a new project and new client where things are going fantastic. I am working now on the same team as my co-blogger, Ryan.

Ryan definitely has that crazy passion that makes a great developer.

So together we decided to focus our energy on a blog and on a special project that will endeavor to capture the winning formula to developing that next generation .Net application.

Right now we are using Composite Wpf (aka Prism) and Linq To Sql to develop a great application.

To say things are going great is an understatement. The application looks amazing and the coding is a pleasure.

But like all projects, we can do it better the next time. So our project is to start prototyping that next time.

As for my blog entries, they will probably be random from simple concepts to complex code implementations. I have no desire to focus my blog entries on the PhDs or on the unwashed coding masses.

So enjoy or  ! enjoy (haha.. nerd humor)

Peace out!

JB