Archive for the ‘Uncategorized’ Category

How do I hide columns with a Wpf GridView?

In my current project we ran across a problem where we wanted to hide certain columns in a grid view based on domain criteria.

We looked into custom grid headers, attached properties, custom controls, etc. Every path lead to a very complex and more importantly custom solution.

I spent an afternoon playing around and came up with this solution which we are using today.

It’s simple, easy to follow, and doesn’t require any custom code. All it uses is the power of style and triggers. The biggest knock is OH NOES! you have a bit of duplication in your xaml.

What is it?

Well, you set the ‘View’ property in your style. Then you utilize style triggers to swap out the View.

Yup.. easy.. simple… no mess.

Example :

<style x:Key="listViewStyle" TargetType="ListView">
    <setter Property="View">
        </setter><setter .Value>

            <gridview>
                <gridviewcolumn Header="Name"
                                DisplayMemberBinding="{Binding Name}" />
                <gridviewcolumn Header="Salary"
                                DisplayMemberBinding="{Binding Salary}" />
            </gridview>

        </setter>

    </style><style .Triggers>
        <datatrigger Binding="{Binding HideCols}" Value="True">

            <setter Property="View">
                </setter><setter .Value>

                    <gridview>
                        <gridviewcolumn Header="Name"
                                        DisplayMemberBinding="{Binding Name}" />
                    </gridview>

                </setter>

        </datatrigger>
    </style>

Repositories and Presentation

I recently came upon a question in the Domain Driven Design Yahoo! Groups asking whether or not the presentation layer should interact directly with repositories or through a method on the entity (domain model). Having just finished Nilsson’s Applying Domain Driven Design Patterns and (finally) getting my head around LINQ to SQL on my current project, I decided to weigh in on the matter.

As always, it depends. You can indeed allow the presentation layer to use the repository directly, just as you can allow the presentation layer to use a factory to create your entities. Your current implementation is something I started off with when I started trying to do DDD, and follows more of the Active Record pattern, as mentioned by another responder, thought Active Record, by definition, matches the database table field for field.

You have several options:

  1. Use your current approach. You’ll probably need to merge your repository and entity by using static methods and properties, though, which can make it messy, and I wouldn’t recommend it. That’s why I stopped using this approach, anyway.
  2. Add a validation mechanism to your repository to validate your entities or, if your entities validate themselves, report the entities’ validation before you save.
  3. If you really like the Save method on your entity and you use .NET or a dynamic language (not sure about other platforms), you can use extension methods to “add” a Save method that wraps a call to your repository. This is really option 2 with some syntactic sugar.
  4. BEST PRACTICE (?): Use a Unit of Work, such as LINQ to SQL’s DataContext, Entity Framework’s ObjectContext, or NHibernate’s / SubSonic 3′s ISession to manage transactions and repsoitories, then call SubmitChanges() through the unit of work.

The Unit of Work pattern can be a little hard to understand at first, but it is quite powerful and great for managing rollbacks (which are extremely difficult if you always wrap your unit of work/repositories in the entity methods).

For reference, try these links:
http://iridescence.no/post/ASPNET-MVC-DataContext-and-The-Unit-of-Work-Pattern.aspx
http://www.west-wind.com/weblog/posts/246222.aspx

For keeping LINQ to SQL and Entity Framework persistence ignorant (PI), see:
http://iancooper.spaces.live.com/blog/cns!844BD2811F9ABE9C!397.entry
http://code.msdn.microsoft.com/EFPocoAdapter

Double Click Command Behavior

I recently posted how to bind an ICommand on a ViewModel to an Input binding.

I thought I would also add a post sharing an attached dependency property I use to binding ‘double click’ to an ICommand.

The xaml to use the behavior looks like : (naturally where Behaviors is my xml namespace, etc)

&lt;ListBox Style=&quot;{StaticResource ListBoxStyle}&quot;
 SelectedItem=&quot;{Binding SelectedItem}&quot;

Behaviors:DoubleClickCommandBehavior.DoubleClickCommand=&quot;{Binding EditCommand}&quot;

ItemsSource=&quot;{Binding Items}&quot;
 ItemTemplate=&quot;{StaticResource Template}&quot;&gt;
&lt;/ListBox&gt;

What follows is the code. Enjoy! – JB

   1: /// <summary>
   2: /// Double Click Command Behavior.
   3: /// Is a attached dependency property where you attach a command to execute upon the dependency object
   4: /// (control) being 'double clicked'
   5: /// </summary>
   6: /// <remarks>created by Jonathan Birkholz 7/21/08</remarks>
   7: public static class DoubleClickCommandBehavior
   8: {
   9:     #region Double Click Command Property
  10:
  11:     public static readonly DependencyProperty DoubleClickCommandProperty =
  12:         DependencyProperty.RegisterAttached("DoubleClickCommand",
  13:                                             typeof(ICommand), typeof(DoubleClickCommandBehavior),
  14:                                             new PropertyMetadata(null, DoubleClickCommandChanged));
  15:
  16:     public static ICommand GetDoubleClickCommand(DependencyObject obj)
  17:     {
  18:         return (ICommand)obj.GetValue(DoubleClickCommandProperty);
  19:     }
  20:
  21:     public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
  22:     {
  23:         obj.SetValue(DoubleClickCommandProperty, value);
  24:     }
  25:
  26:     #endregion
  27:
  28:     #region Double Click Command Parameter Property
  29:
  30:     public static readonly DependencyProperty DoubleClickCommandParameterProperty =
  31:         DependencyProperty.RegisterAttached("DoubleClickCommandParameter",
  32:                                             typeof(object), typeof(DoubleClickCommandBehavior),
  33:                                             new PropertyMetadata(null));
  34:
  35:     public static object GetDoubleClickCommandParameter(DependencyObject obj)
  36:     {
  37:         return (object)obj.GetValue(DoubleClickCommandParameterProperty);
  38:     }
  39:
  40:     public static void SetDoubleClickCommandParameter(DependencyObject obj, object value)
  41:     {
  42:         obj.SetValue(DoubleClickCommandParameterProperty, value);
  43:     }
  44:
  45:     #endregion
  46:
  47:     #region Double Click Command Changed
  48:
  49:     private static void DoubleClickCommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  50:     {
  51:         Selector selector = obj as Selector;
  52:
  53:         if (selector != null)
  54:             selector.PreviewMouseLeftButtonDown += HandlePreviewMouseLeftButtonDown;
  55:     }
  56:
  57:     private static void HandlePreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseEventArgs)
  58:     {
  59:         if (mouseEventArgs.ClickCount == 2)
  60:         {
  61:             DependencyObject depObj = sender as DependencyObject;
  62:
  63:             if (depObj != null)
  64:             {
  65:                 Selector selector = depObj as Selector;
  66:
  67:                 if (selector != null)
  68:                 {
  69:                     if (selector.SelectedItem != null)
  70:                     {
  71:                         ICommand command = GetDoubleClickCommand(depObj);
  72:                         object commandParameter = GetDoubleClickCommandParameter(depObj);
  73:
  74:                         command.Execute(commandParameter);
  75:                     }
  76:                 }
  77:
  78:             }
  79:         }
  80:     }
  81:
  82:     #endregion
  83: }

How to bind custom ICommands to Input Bindings

If you are developing using any sort of V-VM-M pattern, you are already loving the awesome binding powers of Wpf.

And you should also be loving ICommand and binding buttons to ICommand properties on your VM.

What you might have discovered is that binding ICommands to Keys and other input gestures is not as easy as it was with vanilla Routed Commands.

But have no fear! There is a solution.

By utilizing Josh Smith’s Element Spy trick and creating a custom InputBinding, we can gain the functionality of binding an ICommand to a Key, etc.

Here is my custom input binding :

 

   1: public class MyInputBinding : KeyBinding
   2: {
   3:     #region Fields
   4:  
   5:     private static readonly DependencyProperty BoundCommandProperty = 
   6:                     DependencyProperty.Register("BoundCommand",
   7:                                                 typeof (ICommand),
   8:                                                 typeof (MyInputBinding),
   9:                                                 new PropertyMetadata(OnBoundCommandChanged));
  10:  
  11:     #endregion
  12:  
  13:     #region Properties
  14:  
  15:     public ICommand BoundCommand
  16:     {
  17:         get { return GetValue(BoundCommandProperty) as ICommand; }
  18:         set { SetValue(BoundCommandProperty, value);}
  19:     }
  20:  
  21:     #endregion
  22:  
  23:     #region Methods
  24:  
  25:     private static void OnBoundCommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  26:     {
  27:         MyInputBinding binding = obj as MyInputBinding;
  28:  
  29:         if (binding == null) return;
  30:  
  31:         binding.Command = e.NewValue as ICommand;
  32:     }
  33:  
  34:     #endregion
  35: }

Then when you combine the use of the ElementSpy, your xaml looks like:

<Window.Resources>

    <InputBindingSandbox:ElementSpy x:Key="spy" />

</Window.Resources>


<Window.InputBindings>

    <InputBindingSandbox:MyInputBinding BoundCommand="{Binding Source={StaticResource spy},

                                                               Path=Element.DataContext.MyCommand}"

                                        Key="Enter" />

</Window.InputBindings>

Naturally the custom input binding is very simple and does not expose the Command Parameter nor the Command Target, etc. But the basic pattern is there so feel free to utilize and extend.

Happy coding!

JB

Greek Fire at CodePlex

The Greek Fire experiment is also being shared for all to see at CodePlex.

You can get the source code here.

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

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