Archive for December, 2008

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)

<ListBox Style="{StaticResource ListBoxStyle}"
 SelectedItem="{Binding SelectedItem}"

Behaviors:DoubleClickCommandBehavior.DoubleClickCommand="{Binding EditCommand}"

ItemsSource="{Binding Items}"
 ItemTemplate="{StaticResource Template}">
</ListBox>

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

Domain Model, Data Mapper, Repository, Unit of Work Patterns and Lazy Load, oh my!

Our efforts to create a library for building enterprise-level LOB has led us to the Domain Model, Data Mapper, Repository, Unit of Work and Lazy Load patterns, just like everybody else. I just got my copy of Nilsson’s Applying Domain-Driven Design and Patterns and enjoy it very much. I believe Rob Conery commented on the pattern of patterns approach that defines Domain-Driven Design. That statement, while a bit incomplete, appears to hold true.

Aside from well-documented pitfalls, domain-driven design appears quite fresh and appealing, at least to me. Nevertheless, I ran into several hurdles while trying to implement the Unit of Work and Repository patterns. In particular, where do I add the Data Mapper? I’ve puzzled over this the last few days without any good answers.

This evening as we were walking out the door, JB and I decided we’d finally look into Expressions and building our own IQueryable implementation so that we could lazy load our mapped domain models. Lo and behold, I think this answers my other questions, as well, as building the query expression also allows us to map to the data provider, no matter what that may be, including Entity Framework or LINQ to SQL Expression trees.

Implementing IQueryable also allows us to catch each object as it is pulled through the iterator and tag it for change tracking. Now many reading this post will probably be thinking that this sounds like a lot of work—and I’m sure it is—and that these benefits were supposed to be delivered through Entity Framework, LINQ to SQL, etc. Well, you are right, but due to the lack of interfaces and current limitations, these may not always be the best options.

I’ve just started learning this myself, so I can only point you to the how, not the how hard. Check out the LINQ: Building an IQueryable Provider Series. As I progress, you can be I’ll be commenting on the ease or difficulty of building a custom IQueryable provider. Several others appear to have gone this route, so it can’t be a completely worthless pursuit (see SubSonic and IQToolkit).

Anyone else taken the plunge? What were your experiences?

GreekFire Updates – Hello, M and Entity Framework

This update contains some big changes. You can get this source code here.

The first deployment of the source was very basic.

It didn’t really show anything new or flashy. I did dabble a bit into writing tests in a BDD fashion (or at least attempt to).

I am going to detail out some of the new changes in this source. Naturally there are tests for all the new classes and functionality.

 

IChangeSet

IChangeSet now only has the GetInserts, GetDeletes, and GetUpdates methods. My thoughts are that the ChangeSet is supposed to only be a readonly entity allowing for investigation into the Unity Of Work. Having the Add methods and Reset exposed too much functionality. A DataContext will just be coupled to its ChangeSet for now. I don’t see any harm in that coupling.

 

M Model

I created an M file to start building up my domain. I think M is fantastic! I am not a database guru by any stretch so being able to write out a domain in a very readable and manageable syntax is awesome.

module GreekFireExpense
{
    type Expense
    {
        Id : Integer64 = AutoNumber();
        Description : Text;
        Title : Text;
        Amount : Decimal28;
    } where identity Id;
    ExpenseTable : Expense*;
}

I haven’t found a sufficient manner to run the SQL scripts or the M compiler with specific arguments from VS right now. So I am still using IntelliPad to generate the SQL (I am also not a command line guru).

 

Entity Framework

After creating the database, I created an Entity Framework project. I am created a new DataContext to work with the EntityFramework.

Also the Entities from the Entity Framework do not ‘live’ past the DataContext. The DataContext manages the mapping between my Data Entities and my Domain Entities.

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.

The Greek Fire Experiment

Tutorial D in F#

Does anyone know of a project to implement Tutorial D in F#, similar to the Dee project for Python? I’m currently trying to get Dee working on IronPython, which would get me closer to my goal of using a true relational model for data access. I would like to stick with a .NET implementation, so that leaves out Rel. I have tried Dataphor, but I find it trying to be too much a complete platform and not easy to use as just a utility. I think either a good C# or F# implementation would be both excellent to have and a fun project on which to work. Anyone interested?

Excel Financial Functions for .NET

Luca Bolognese recently posted a new library that makes Excel’s financial functions available through .NET managed code without going through Excel! This is excellent news for anyone working on a financial or LOB app. Luca created the library to mimic the Excel functions, including errors or bugs, in F#. The release comes in two versions: a smaller .dll that will run on an installed F# installation and a larger, stand alone .dll for those who do not wish to deploy F#.

Check it out at the MSDN Code Gallery.