Thoughts on DDD and IoC

I have found that, if you drive out the dependencies of an object and express those dependencies in terms of interfaces, your domain tends to be a lot more clearly defined but that you need to rely far more heavily on your IoC container to address these dependencies. Fortunately, it also allows you to find dependency patterns far more easily and consolidate those dependencies into concrete implementations that have a focus in purpose (a.k.a. the single responsibility principle). Driving out these dependencies from the requirements of the class through interfaces leads to many small, client-specific, interfaces so that anyone that comes across the class later on and wants to try and figure out what the intent is of the code is not going to be distracted by a dependency that has been passed in that has many more methods on it than is needed by the client class itself (a.k.a. the interface segregation principle). Making these dependencies required through either constructor dependency (my personal choix de vie) or property dependency injection (not my favourite because it is more open to runtime errors) is called an inversion of control (a.k.a. the dependency inversion principle)  leads to strong reliance on an Inversion of Control container.  This method of designing classes and driving out features are two of the three principles of SOLID design.

SOLID is not new (thank you Uncle Bob!) and I think that many of the concepts are generally agreed upon by most developers concerned with good design. What I want to do in this article is try and illustrate how this changes the way you develop your code.

In the first scenario, I am responsible for building a class that shows the name of the application in the title bar of the application window. We’re trying to develop a really strong architecture with as few points of failure as possible so that we can make a change in one spot and it corrects the bug in other spots as well.

  • Whether I am using MVP, MVC, MVVM, or straight code-behind classes I’ll have a class that is connected to the User Interface screen (webpage, windows form, mobile device screen, whatever).

class MainPageBackingClass {
        // Public property the UI uses to provide the Application Name in the title bar
        public string TItleBarText { get { } }
}

  • There’s a desire to provide localization for our application and that’s going to be provided somewhere else in our application. My class needs to get the string that puts the application name up on the screen.

class MainPageBackingClass {
        public MainPageBackingClass(IMainPageBackingClassStringsProvider stringsProvider) { .. }
        // Public property the UI uses to provide the Application Name in the title bar
        public string TItleBarText { get { return  stringsProvider.ApplicationName; } }
}

interface IMainPageBackingClassStringsProvider { string ApplicationName { get; } }

At this point I don’t care, from the design of my class’ perspective, what is implementing IMainPageBackingClassStringsProvider, I just care that I need something to provide that string for me. The subtle point to notice here is that the class is defining what it needs and driving out it’s dependencies. There is an interface (IMainPageBackingClassStringsProvider) that is providing only the single string. That’s okay.

Okay, I’m done and I feel good about myself. My next assignment is to create a class that assembles an email message. It puts the user’s name in the formatted message.

  • I need a class that takes a format-able string and puts the user’s name in it.
class MessageBuilder { }

  • It’s going to need something to provide the formatted message to it.
class MessageBuilder {
        MessageBuilder(IFormattedMessageProvider messageProvider) { … }
}

interface IFormattedMessageProvider { string FormattedMessage { get; } }

  • And now a method that takes in something that provides the user’s name
class MessageBuilder {
        public string Format(IUserNameProvider userNameProvider) {
               return string.Format(messageProvider.FormattedMessage, userNameProvider.UserName);
        }
}

interface IUserNameProvider { string UserName { get; } }

In my application I now have three dependencies (IMainPageBackingClassStringsProvider, IFormattedMessageProvider, and IUserNameProvider). There’s an emerging pattern here that there are at least two dependencies requiring strings. Since a class can implement multiple interfaces without any problem, I am going to build a class that has a singular purpose (to provide localized strings) and implement both interfaces.

class StringsProvider : IMainPageBackingClassStringsProvider, IFormattedMessageProvider {
         public string ApplicationName { get { return “Hello World”; } }
         public string FormattedMessage { get { return “Welcome {0}!”; } }
}

Now, here’s the kicker of this entire scenario. There’s a temptation for us to consolidate all of those strings that are being provided by the StringsProvider class into a single interface (maybe call it IStringsProvider) and have both the MessageBuilder class and MainPageBackingClass have a dependency on a single interface. On first inspection, that would appear to a good idea. The issue comes that a later developer might get confused as to the intent of the code in one of the classes if there are more methods/properties available to them than is needed by the class. If, for example, it ended up that you had two interfaces, one provided ApplicationName as a string and another providing ApplicationTitle as a string.

From within the context of separate interfaces, each class relying on an interface providing only the single string, it would be easy for the developer to know which string they were to be using within the class. It wouldn’t be confusing because there’s only one property to choose from. If, though, we had consolidated those string providing dependencies into a single interface, we now have two properties (ApplicationName and ApplicationTitle) being provided by this interface. Which one should I, as a developer of MainPageBackingClass choose? What if there are hundreds of other properties to choose from in my consolidated interface that I now have to scan through and guess which one I really need to use? It’s much easier to express the intent of the code through individualized interfaces.

Interfaces are the cheapest thing to produce in code.

Luckily classes can implement multiple interfaces (even hundreds if need be) and there’s always your IoC container that can produce all the magic to get your class the one it needs at run-time.

Local Installation of Windows Server AppFabric

I went through the process of installing and getting AppFabric working on my local machine based on information I gathered in my Windows Workflow 4.0 and Windows Server AppFabric – My Resources for Getting Started post. I then had to create a document that instructed other developers on my team how to install and get our workflow app up and running. Here’s the script (as I think it would be useful to anyone else just getting started). I know that not all the steps are necessary (e.g. installation of the persistence store can be done within the AppFabric Configuration Wizard) but I felt these were the more intuitive steps to letting developers know what was going on under the hood. Here goes nothing:

Installing AppFabric

  1. Download and install the version of Windows Server AppFabric appropriate for your machine (see Additional Information section at bottom of the page to determine which to install)

Note: At the end of installation you will see the “See recommended updates” link at the top. Click it and install the updates. Also, uncheck the “Launch configuration tool.” checkbox. We will configure this in a separate step to add clarity.

Make sure you do this!

Installing Persistence Store (Database)

  1. Create a new database (“SQLPersistenceStore”, but name is really unimportant), run the scripts (provided by Microsoft) to create the schema and logic for this database. Manually run the following scripts, located in %SystemRoot%\WINDOWS\Microsoft.Net\Framework\v4.0.30319\SQL\en\ or %SystemRoot%\WINDOWS\Microsoft.Net\Framework64\v4.0.30319\ if you are running a 64 bit operating system: SqlWorkflowInstanceStoreSchema.sql and SqlWorkflowInstanceStoreLogic.sql
  2. Create a SQL User account to connect to the newly created database. The user account needs to have db_reader and db_writer permissions as well as be given ownership of the System.Activities.DurableInstancing schema (created in the above step).

Configuring AppFabric

  1. Run the Configure AppFabric application (now installed in your start menu).
    Do this too!
  2. (Optional? I am not sure that the monitoring service is necessary but I think that it is what creates the add-in in IIS Manager to view the persisted instances) On the ‘Hosting Services Tab’ of the Windows Server AppFabric Configuration Wizard’ screen, check the ‘Set monitoring configuration’ checkbox, select the System.Data.SqlClient item from the ‘Monitoring provider’ drop-down and click ‘Configure’
    Configuring the Hosting Service
  3. On the ‘Windows Server AppFabric Monitoring Store Configuration’ screen, click the ‘Register AppFabric monitoring store in root web.config checkbox, select the database (created in step 1 above) in the Connection String section, and select the ‘SQL Server authentication’ option in the ‘Security Configuration’ section, providing the username and password created above.
    Configuring the Monitoring Store
  4. Back on the Hosting Services Tab, check the ‘Set persistence configuration’ checkbox, select the sqlStoreProvider item from the ‘Persistence provider’ drop-down and click ‘Configure’
    Configuring the Persistence Store
  5. On the ‘Windows Server AppFabric Persistence Store Configuration’ screen, click the ‘Register AppFabric persistence store in root web.config checkbox, select the database (created in step 1 above) in the Connection String section, and select the ‘SQL Server authentication’ option in the ‘Security Configuration’ section, providing the username and password created above.
  6. Back on the ‘Windows Server AppFabric Configuration Wizard’, click the ‘Next >’ button to complete the wizard.

Creating the Virtual Directory

  1. Open IIS Manager (inetmgr from the ‘Run’ prompt) and create a new Application under the Default Website node and pointing the virtual directory to the workflow project folder in your development environment (e.g. c:\dev\MyWorkflowApp\source\application\WorkflowProject).

Windows Workflow 4.0 and Windows Server AppFabric – My Resources for Getting Started

I’m starting on a new feature of the application I work on in my day-to-day. We’re building out a feature to replicate some human workflows that are long running. Here’s some of the resources I have accumulated so far:

Introduction


Windows Workflow Foundation (WF) is a method of creating discrete activities that can be used to model the workflow of an application or human workflows. It “provides a programming model, in-process workflow engine and rehostable designer to implement long-running processes as workflows within .NET applications”.

With .NET 4.0, a new programming model as well as further integration between Windows Communication Foundation (WCF) and WF was created.

The tasks I am looking to automate are human activities that are often long-running such as follow-up processes as well as approval processes where an activity is performed, a duration expires or the workflow is preempted by further user input and then continues to completion. The Creating a Long-running Workflow Service article defines a durable workflow as a “long running workflow services may run for long periods of time. At some point the workflow may go idle waiting for some additional information. When this occurs the workflow is persisted to a SQL Server database and is removed from memory. When the additional information becomes available the workflow instance is loaded back into memory and continues executing.” These long running, durable workflows can be hosted in WCF Services (Hosting Options: self-hosted in a managed application, hosted in a managed windows service, in Internet Information Services [IIS], or Windows Process Activation Services [WAS]), Windows Servies (self-created or Windows Server AppFabric), or in the cloud (Windows Azure AppFabric).

WF 4.0


Activity-specific Links


Windows Server AppFabric


Installation


Deployment


Windows Workflow (WF) Samples


Download Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4

Documentation

See Also


A small change

This is a small tid-bit of an extension method I created when I realized that the ability to combine a collection of strings into a character-separated string was only available as a static method of the String class:

public static string Join(this IEnumerable<string> strings, string separator) {
    return String.Join(separator, strings);
}

This allows me to achieve the following, which I would argue is slightly more intuitive:

var myListOfStrings = new List<string> {"January", "February", "March"};
var myCombinedListOfString = myListOfStrings.Join(",");

LinqFu: Dynamic Linq in NHibernate 3.0 (Alpha 3) Linq Provider (part 2 of n)

By following the Dynamic Linq sample from ScottGu’s post, I was able
to use the new Linq provider in NHibernate 3.0 Alpha 3 to create
dynamic Linq statements for NHibernate. The idea is to incorporate
the Visual Expression Builder for Dynamic Linq to allow users to
create their own data filters. Simply copy the Dynamic.cs file from
the DynamicQuery sample and replace the second method
with the following:
public static NhQueryable<T> Where<T>(this IQueryable<T> source,
    string predicate, params object[] values) {
    if (source == null) throw new ArgumentNullException("source");
    if (predicate == null) throw new ArgumentNullException("predicate");
        LambdaExpression lambda = DynamicExpression.ParseLambda(
            source.ElementType, typeof(bool), predicate, values);
        return new NhQueryable<T>(source.Provider,
            Expression.Call(
                typeof(Queryable), "Where",
                new Type[] { source.ElementType },
                source.Expression, Expression.Quote(lambda)));
    }

NOTE: I wasn’t able to get it to work with NHibernate 2.1’s Linq Provider as NHibernateQueryable didn’t inherit from IQueryable. I tried for most of the day to weave my way through it but thought it might just be easier to try the new version of NHibernate and upgrade the references in my app than to create maintenance work for myself in the future.

LinqFu: Linq in Linq (part 1 of n)

I had to perform some LinqFu today where I used a Linq expression within a Linq expression and thought I would post a reminder to myself about what I did and how I did it. Looking at it afterward, I’m surprised it was as simple as it was. *shrug* I guess that’s how these things go.
 
Basically, it’s the equivalent of selecting an order based on its order items (to use the classic relationship scenario).
 
var value = 10;
 
if ((from order in orders where order.Items.Any(item => item.Value >= value) select order).Any()) { //Any orders w/item whose value is >= value
   MessageBox.Show(string.Format("There are orders with items greater than or equal to ‘{0}’, value));
}

WPF ISO Date Format Converter

This is a little piece of code I put together for an application. The code is no longer being used but I didn’t want to lose it.
 
 

public sealed class IsoDateValueConverter : IValueConverter {

     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {

          if (value != null && value is DateTime) {

               var date = (DateTime)value;

               return date.ToString(SystemInformation.DateTime.IsoShortDateFormat);

          }

          return string.Empty;

     }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {

          if (culture == null) {

               throw new ArgumentNullException("culture");

          }

          if (value != null && value is string) {

               return DateTime.ParseExact((string)value, SystemInformation.DateTime.IsoShortDateFormat, CultureInfo.InvariantCulture);

          }

          return null;

     }
}

 

Simple Object State Awareness

Through the implementation of two custom interfaces (IClonable<T> and IStateAware) and one from the .NET framework (IEquatable<T>) it becomes pretty simple to create a class that’s state-aware. The IClonable<T> interface is simply a representation of the Prototype Pattern that I have made a sample of on my website previously.
 
Here are the two custom interfaces:
 
     public interface IClonable<T> {
          T Clone();
     }
 
     public interface IStateAware {
          void StoreCurrentState();
          bool HasChanged { get;  }
     } 
 
Here’s a sample implementation:
 

     public class MyClass : IClonable<MyClass>, IEquatable<MyClass>, IStateAware {

          MyClass currentState;

 

          public string FirstName { get; set; }

          public string LastName { get; set; }

 

          public MyClass Clone() {

               return (MyClass) MemberwiseClone();

          }

 

          public bool Equals(MyClass other) {

               return other.FirstName == FirstName &&

                         other.LastName == LastName;
          }
    

         public void StoreCurrentState() {

               currentState = Clone();
          }

 

          public bool HasChanged {

               get {

                    if(currentState == null) return false;

                    return !Equals(currentState);

               }
          }

     }

 
Now I can take a snapshot of the object at any time and determine if it has changed later on.
 

MVVM, Infragistics XamDataGrid, and Exporting to Excel

I was watching Craig Shoemaker’s video blog post on Introduction to XamDataGrid Excel Exporting and was excited that he started things out with a ViewModel but the export code was all performed in a code-behind. This left me wanting more. The problem is that InfragisticsDataPresenterExcelExporter requires you to pass a DataPresenterBase object (implemented by the XamDataGrid) as a parameter. This makes sense as the power of the DataPresenterExcelExporter feature is that whatever formatting you have put in place on your grid is what gets exported, saving me being asked to try and replicate a user’s grouping, sorting, or what-not in Excel.
 
So, I used a UserControl, and PRISM‘s generic DelegateCommand (one of my favorites) to pass the XamDataGrid instance through to my ViewModel and was able to move toward a more pure MVVM implementation of the export to excel feature.
 
 You can find the complete sample here:

 

Object Validation in an Extension Method

I was trying to find a way to define the state of an object based on a set of rules and assign a name to that set of rules that, then defines the state of the object. Here’s what I came up with:
 

     public static class Extensions {

          public static bool Is<T>(this T item, Predicate<T> conditions) {

               return conditions(item);

          }
     }
 
This allows me to define the conditions of any object such that I can give a name to its state based on how the business speaks about the object:
 

     Predicate<MyObject> InACancelledState = (x => x.Cancelled.HasValue);

 

This leads me to be able to code fluently about the state of the object at runtime:

     if (obj.Is(InACancelledState)) {

          // Do some stuff

     }