We’re Hiring

Wednesday April 16th, 2008 @ 11:23 PM by Chris

For a while now, my employer has maintained an opening for a talented software developer. They have not advertised the position very heavily because (a) we live in an area that is not rich with developers and (b) our small, Agile team has chugged along fairly well without this extra person.

That all changed today when a colleague - and friend - opted for greener pastures. He’s returning to the company where he started his career as an intern, a place he is particularly fond of, and I cannot blame him for taking a job that more closely fulfills his professional and personal desires. I wish him all the best.

Still, our small team of developers just shrunk by one, and we need to fill the gap.

In a larger city this would not be a problem. We’d just advertise the position and the resumes would pour in. But our location is our biggest hurdle when it comes to attracting talented developers. We simply can’t pull from as large a pool as a city like Austin, Texas can.

So where do I work? Nez Perce County, a small county government in north-central Idaho. As one might imagine, it is not exactly a mecca for software development talent. But that hasn’t stopped us from trying. People we talk to are always surprised to learn that our tiny little IT shop in Idaho is practicing Agile techniques. Yet that is exactly what we’re doing.

We subscribe to Agile practices, Extreme Programming in particular, and we drink from the TDD fountain. We use Continuous Integration, unit tests, acceptance tests, and frequent customer feedback along with short iterations to write quality, maintainable code and deliver business value to our customers (which, incidentally, includes us, since we are also taxpayers; we’re our own bosses in manner of speaking).

We work in an open environment and every developer has two monitors at their workstation. We work closely together as a team and have an on-site customer to help provide rapid feedback.

What We’re Looking For

We realize that we’re a bit handicapped by our geography. We’re not going to see a lot of great resumes. So it’s important for us to identify candidates that have the capacity to learn and possess a passion for software development. Ideally, candidates for our shop would have the following qualifications:

  • Knowledge of Object Oriented design and principles
  • Knowledge/Experience with C# .Net, or a similar object-oriented language (Java, C++)
  • Database experience
  • Willingness to learn

Bonus points for knowledge/experience with any of the following: Gang of Four design patterns, Unit Testing, IoC, CAB and/or SQL Server.

More information about the position, including benefits and pay, can be gathered by contacting my boss, Randy Buttenhoff, via the Nez Perce County IT web page.

Posted in .NET, General, Agile Development, Software Development, CAB | No Comments »

Unsaved Changes When CAB Application Closes: The Notification Pattern

Thursday April 10th, 2008 @ 8:21 PM by Chris

Occasionally this question pops up on the CAB message boards: How do I prevent my application from closing if the user has unsaved changes?

Turns out that there’s a very simple pattern you can utilize to handle this situation. It’s called the Notification Pattern. Jeremy Miller, .Net guru, has a very good blog post on this pattern. He uses it to illustrate a standard way to handle validation on domain objects, but it’s a valuable pattern in other cases too, as I’ll show.

As Martin Fowler writes in his article, the Notification Pattern can be as simple as “a collection of strings which are error messages that the domain generates while it’s doing its work.” This is, in fact, how simple our implementation is where I work. A collection of strings, nothing more. You can use something else besides strings - a rich object with many properties and a public interface - if you like. But for this demonstration I’ll stick to strings.

The easiest way to implement this in CAB is with a Service class. All that is required is an event and a method to call to get notifications. The interface to the service basically looks like this:

public delegate void ApplicationClosingEventHandler(List<string> notifications);

public interface INotificationService
{
   event ApplicationClosingEventHandler ApplicationClosing;
   List<string> GetNotifications();
}

And the Service itself:


public class NotificationService : INotificationService
{
   public virtual event ApplicationClosingEventHandler ApplicationClosing;

   public virtual List<string> GetNotifications()
   {
      List<string> notifications = new List<string>();

      if (ApplicationClosing != null)
      {
         foreach (ApplicationClosingEventHandler handler in ApplicationClosing.GetInvocationList())
         {
            handler.Invoke(_unsavedChangesNotifications);
         }
      }
      return notifications ;
   }
}

WorkItems, Presenters and other classes that know about the dirty state of their models can take a dependency on this Service and subscribe to the ApplicationClosing event. When the event is fired, their handler adds a notification to the list, if it needs to.


public MyPresenter : Presenter<IMyView>
{
   private INotificationService _notificationService; 

   public MyPresenter([ServiceDependency] INotificationService notificationService)
   {
      _notificationService = notificationService;
      _notificationService.ApplicationClosing += new ApplicationClosingEventHandler(AppClosingHandler);
   }

   private void AppClosingHandler(List<string> notifications)
   {
      if(myModelIsDirty)
         notifications.Add("My object is dirty");
   }
}

The next step is to hook the whole thing into the Shell.Closing event. Back in the ShellApplication class, typically in the AfterShellCreated override, you can wire up to the Shell.Closing event:

public override AfterShellCreated()
{
   base.AfterShellCreated();

   Shell.Closing += new CancelEventHandler(Shell_Closing);
}

In your handler, you can query the INotificationService and get any notifications. If the notification list is empty, you can safely exit the application. Otherwise, pop a MessageBox and alert them.

private void Shell_Closing(object sender, CancelEventArgs ee)
{
   INotificationService notificationService = RootWorkItem.Services.Get<INotificationService>();

   List<string> notifications = notificationService.GetNotifications();

   if(notifications.Count > 0)
   {
      e.Cancel = true;
      // Alert the user
   }
}

That’s it. Simple, right? The nice thing about this pattern is that even with simple notifications, like strings, you can still give the user some very useful information on where unsaved changes exist. In our application, for instance, we let the user know which module and “use case” (very broad term here) contains the unsaved changes, so they can find those unsaved changes faster and make the save.

The Notification Pattern is one of the simplest, yet most useful, patterns that you’ll run into in any application, not just CAB. Now go forth and prevent your users from losing data when they close your app!

Posted in .NET, Software Development, CAB | 2 Comments »

Dependency Injection In CAB/SCSF, And When Not To Use It

Monday March 31st, 2008 @ 7:18 PM by Chris

Lately it seems like I’ve been asked this question a lot when I’m doling out advice on using CAB: How come I don’t use [ComponentDependency] or [State] to pass model state to the Presenters/Controllers via Dependency Injection?

In answering this question I learned something about the way I think about architecture, classes, dependencies and data. And since the question gets asked frequently enough, I figured it deserved a blog post.

There Is A Difference Between A Dependency And The Model

I’ll start by saying that I think there is a big difference between a dependency on another class and model state (data). In my opinion, the calling class should not be able to exist without its dependencies - it’s like a car without wheels or a an iPod without memory - it’s fairly useless. (This is, incidentally, why I prefer constructor injection over property injection; I don’t like the idea of being able to create an object without all the necessary parts.) But a calling class could (and should) be able to exist without the model - the data. The calling class should be able to accept input at any time, not just at construction.

Dependencies, to me, are classes that the calling class must have in order to do its job. Dependencies perform a critical task in the overall use case, and as such they have to be there when the object is created. And hopefully these dependent objects exist as such because we’ve separated out individual responsibilities of the larger use case into small classes that do just one job and do it well. Our calling class should be relying on only interfaces to these dependencies - a contract and nothing more. They key point is that the calling class can’t do its job without its dependencies. It’s like a crock pot without a chord to plug it in; it’s useless if you want to cook anything. If a user tries to operate the calling class without its dependencies it should fail miserably.

Model state, on the other hand, is something the calling class should be able to live without and accept at any time. It’s data that should be passed in whenever. It’s like the food for a crock pot. The crock pot (calling class) can exist just fine without any food in it. You can plug it in, turn it on, and turned the knobs. When you use a crock pot, you put one type of food into it (uncooked data) and you expect to get another type of food out of it (cooked data). The crock pot processes the input and gives an output, and this is the way most classes operate. And like a good class, a crock pot can accept input at any time, be it 9AM or 5PM (you, as the user, just have to be prepared to wait for the expected result, but I’m not going to get into background threads here :) )

This is the main reason why I don’t find it acceptable to use Dependency Injection to get the model into a Presenter. A model isn’t a dependency - it’s data. It is input that should be acceptable to pass to the class at any time. Dependency Injection is for creating types that the calling class needs to operate, not for passing data.

So How Do We Pass The Model Around In A Multi-View, Shared-State Scenario?

In CAB, I find the EventBroker to be the best way to pass model state to child views in a large, multi-view scenario where each view needs to rely on a shared model state. I leave it up to the Controlling class (typically a WorkItem) to handle the fetching of the model (from a service, repository or factory). When it is ready to load the child views, it fires a Load event and passes the model state as an event argument. Since objects are pass by reference in .NET, every listening class gets the same instance of the model. An update to some portion of the model on one view can be immediately reflected in the other views (if they’re looking at the relevant portion of the model).

I like the EventBroker in this case because it keeps a clear separation between dependencies and data.

With the EventBroker, the Controller has the flexibility to determine when to give the child views the model. This ends up being useful later on, because now a View can receive updated data at times other than object instantiation, and we get to use the same input mechanism (namely, an event argument). With the EventBroker I don’t have to worry about when a Presenter receives its data, just that when it does, it knows what to do with it.

The other thing I really like about using the EventBroker is that it becomes super-easy to test the Presenter. The EventBroker uses attributes to decorate methods, and that makes testing a Presenter nothing more than simple method calls to invoke the logic. This frees me from having to utilize a TestableRootWorkItem, for instance, to test a Presenter. I don’t like having to rely on big, bloated test stubs just to test simple method calls.

Posted in .NET, CAB | No Comments »

Saving Settings in a CAB Application

Wednesday January 16th, 2008 @ 5:31 PM by Chris

Recently, I started looking at ways to implement a feature in our application that we’ve had on the back burner for a while: saving settings.

As an example, one portion of our application utilizes dock window panels. The reason for these dock panels is to give the user more flexibility to layout the screens as they choose. However, customizable screens are pretty pointless if the user has to re-organize their application every time they open it. In order for customization to work, the settings need to be saved between uses of the application.

We use Infragistics controls for our docking panels. I wasn’t exactly sure how easy or difficult it would be to save those settings, so I fired up Google and found this article on the Infragistics website.

I’m going to quote the relevant part here, and let you see what the folks at Infragistics have to say about this:

In a standard Windows Forms application where all of the user interface components and events are accessible from within the application, we would normally handle the main form’s FormClosing event and in this event, we can simply call the DockManager.SaveAsXML( ) method to save it easily. Due to the nature of working with CAB and the nested SmartParts and Workitems, it is not so simple to handle this situation in the same way.

Actually, it is. I’ll get to that in a minute after you read their recommended approach, which I find unacceptable:

To handle this scenario, we can listen to the events fired by the UltraDockWorkspace whenever we make a change to its controls and then we can save the Layout. This means that whenever we pin, dock, float or resize any of the controls, we will be saving the Layout. This should not raise any concerns because it does not happen so often. If you are saving the layout as a stream and writing it to a remote database somewhere, then this may introduce some performance related issues, so as an alternative, you can always save to a file on disk and when the application closes, you can stream the file to the database just once.

This is over-complicating the solution and trying to dismiss performance as a non-issue. That’s just wasteful, in my opinion, when there are better, simpler solutions to be had.

The truth is that it is actually very simple to handle this in CAB with an EventBroker event.

First, in the ShellApplication class, subscribe to the Shell’s ApplicationClosing event. Just the old fashioned way - wire that puppy up with += and get an event handler established. Inside that event handler you fire an EventBroker event, like so:

RootWorkItem.EventTopics[EventTopicNames.ApplicationClosing]
   .Fire(this, new EventArgs(), RootWorkItem, PublicationScope.Global);

You don’t need to declare an EventPublication - just fire the event through the RootWorkItem.

Now you can subscribe to this event anywhere you like: Presenter, WorkItem, View, doesn’t matter. Using a plain old EventSubscription, you can know when the application is closing and do something with your settings. All we’ve done here is Chain of Responsibility - we’ve taken an event and propagated it further down the line, until the classes that really care about it can answer it and do their work.

Now your WorkItems/Presenters/Views know when the application is closing, so they can write their settings to anything you like: a file, a service, whatever. I think a good idea is to provide a SettingsService here, and simply make calls like this:

[EventSubscription(EventTopicNames.ApplicationClosing, ThreadOption.UserInterface)]
public void OnApplicationClosing(object sender, EventArgs e)
{
   settingsService.SaveSomeWorkspacesSettings(SomeWorkspace.SaveAsXml());
}

The SettingsService can deal with the implementation details of saving to a file, or a DB, or wherever.

This solution seems much better to me than the guidance on Infragistics website. There’s no need to hook into any control events or write settings to disk/database more than one time. Just write them out when the application closes, as you would for a non-CAB application.

Posted in .NET, CAB | 4 Comments »

StateService In A CAB Application

Wednesday December 5th, 2007 @ 9:30 PM by Chris

CAB comes with a default implementation for handling state called the State bag. However, it’s not a particularly good implementation. Part of the problem with the CAB state bag is that it’s not strongly typed; it’s basically a glorified Dictionary. When you retrieve an object from the State bag you do this:

Employee employee = (Employee)State["SomeKey"];

Since I started using CAB, I’ve avoided using the CAB State bag. I remember a hallway chat with Brad Wilson during last year’s Patterns & Practices Summit, where Brad basically said, “Yeah, we wish we would have had time to remove the State bag from CAB before it shipped, but the schedule didn’t allow it.” Brad’s advice was to roll our own State service if we wanted to handle state.

For a while, our shop functioned without a State service and without relying on the State bag. One solution we initially tried was to dump objects into the WorkItem’s Item collection. This is not much better than the State bag, but it does have the advantage of being typed. However, it makes unit testing a pain because now your Presenter class is dependent on having a WorkItem injected into it for unit testing purposes. I don’t like those sorts of dependencies when I unit test - I like to test classes in bare isolation with mocks.

A second solution we used was to simply hold on to objects via private member variables in Presenter classes:

public class SomeViewPresenter : Presenter<ISomeView>
{
   private Employee _employee;
   private IPayrollService _payrollService; 

   [InjectionConstructor]
   public SomeViewPresenter([ServiceDependency] IPayrollService payrollService)
   {
      _payrollService = payrollService;
   }

   [EventSubscription(EventTopicNames.LoadEmployee, ThreadOption.UserInterface)]
   public void LoadEmployee(object sender, EventArgs<int> e)
   {
      _employee = _payrollService.GetEmployee(e.Data);
   }
}

This is simple, but creates its own pain during testing. When you use private member variables to hold on to references to objects, you have to ensure that whatever method in your Presenter is responsible for fetching the business object from its source (like LoadEmployee) must be called prior to calling the method you’re really interested during testing, because you have to be able to load the private variable with an actual object. This is awkward, to say the least. Not to mention that it precludes us from doing any sort of sophisticated state management, like undo/reset.

For testing purposes, wouldn’t it be better if we could just call the method we’re really interested in testing, and not have to initialize or load the Presenter? And isn’t maintaining model state outside the scope of the Presenter anyway? It’s job is coordination, not state management.

To solve these problems I gravitated toward the creation of an IStateService and an ApplicationClosingEventHandler delegate. The interface and delegate are listed below:

public delegate bool ApplicationClosingEventHandler(IList<string> unsavedChangesNotification);

public interface IStateService
{
   void SetState(string key, object obj);
   T GetState<T>(string key);
   T Undo<T>(string key);
   bool Remove(string key);
   bool ContainsKey(string key);
   bool HasUnsavedChanges();
   IList<string> UnsavedChangesNotifications { get;}

   event ApplicationClosingEventHandler ApplicationClosing;
}

The implementation is as follows:

public class StateService : IStateService
{
   protected IDictionary<string, Memento> _state = new Dictionary<string, Memento>();
   protected IList<string> _unsavedChangesNotifications;

   public virtual void SetState(string key, object obj)
   {
      if (_state.ContainsKey(key))
      {
         throw new ArgumentException("An item with the same key has already been added to the StateService.");
      }
      else
      {
         using (MemoryStream buffer = new MemoryStream())
         {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(buffer, obj);
            Memento memento = new Memento(obj, buffer.ToArray());
             _state.Add(key, memento);
         }
      }
   }

   public virtual T GetState<T>(string key)
   {
      return (T)_state[key].Item;
   }

   public virtual bool ContainsKey(string key)
   {
      return _state.ContainsKey(key);
   }

   public virtual bool Remove(string key)
   {
      return _state.Remove(key);
   }

   public virtual T Undo<T>(string key)
   {
      T obj;

      using (MemoryStream buffer = new MemoryStream(_state[key].ByteArray))
      {
         buffer.Position = 0;
         BinaryFormatter formatter = new BinaryFormatter();
         obj = (T)formatter.Deserialize(buffer);
      }

       _state[key].Item = obj;
      return obj;
   }

   public virtual event ApplicationClosingEventHandler ApplicationClosing;

   public virtual bool HasUnsavedChanges()
   {
      _unsavedChangesNotifications = new List<string>();
      bool hasUnsavedChanges = false;

      if (ApplicationClosing != null)
      {
         foreach (ApplicationClosingEventHandler handler in ApplicationClosing.GetInvocationList())
         {
            bool result = handler.Invoke(_unsavedChangesNotifications);

            if (result)
               hasUnsavedChanges = true;
          }
      }

      return hasUnsavedChanges;
   }

   public virtual IList<string> UnsavedChangesNotifications
   {
      get { return _unsavedChangesNotifications; }
   }
}

The StateService has two main parts: state management and gathering unsaved changes notification. The first part, the state management, works similar to the Memento pattern you’d find in GoF. There’s a SetState, GetState and Undo (Reset), which will place your object back into the state it was in when you last called SetState. This is not n-level undo: it’s just 1-level undo because that’s all we need right now. But you could tweak it to support n-level undo pretty easy I think.

The StateService achieves the 1-level undo by taking a “snapshot” of the object when SetState is called. It then serializes the object to a binary stream and stores it, along with a reference to the actual object, in a “memento” class (not a true Memento pattern as you would see in GoF because we don’t ask objects to provide their own mementos, but the idea is similar). Of course, since it uses serialization it expects your objects to be Serializable. If you didn’t want that, you’d have to provide a different implementation. But since most objects that require state management are probably serializable already, this seems a logical fit.

The second part of the StateService is gathering unsaved change notification. Now, you may wonder: why do we need the delegate when we could just iterate through the list of objects we’re already holding in the StateService, and if they inherit from some base class (which ours do) then we could just cast them to the base class and check a “dirty” flag and know if there were objects in an unsaved state. But we added the delegate because we wanted interested classes (Presenters/Controllers) in our application to be able to return a message telling the user where those unsaved changes are located within the UI, so the user can quickly find them and make the necessary saves. You might think this is overkill or unnecessary, but you haven’t had to write code for our users :)

Thus, the StateService publishes an ApplicationClosing event which interested controllers/presenters in the UI layer can subscribe to. When the user goes to shut down the application we listen for that event (at the Shell level) and ask the StateService if it has any unsaved changes. The StateService queries all it’s listeners and if there are any unsaved changes then we can halt the application from closing and throw up a MessageBox with the list of messages from the event handler.

So why all the fuss with the service? The advantage here is that the StateService can easily be mocked via a tool like RhinoMocks. State management now becomes the responsibility of the StateService, and not the Presenter. We’re able to separate those concerns, which helps us focus on testing the real responsibilities of the Presenter, which is typically coordination between the model and the view.

It’s not the most awesome solution, I’m sure, but it serves our needs. And since this is a topic that continues to crop up in CAB circles, I thought I’d post our way of doing things.

Posted in .NET, Software Development, CAB | 2 Comments »

« Previous Entries