Archive for the ‘CAB’ Category

On a recent project I worked on I had a need to create a client-server application. What I was after was real-time updating of the clients when data on the server changed. These sorts of applications crop up from time to time in one’s career, and they present a unique set of challenges. I figured I’d store the results of my work on my blog, and if it helps someone else then great.

I am not posting the actual application here because it relies on some machine-specific hardware devices, but what I did instead was to extract the core functionality out into a sample application that shows how the duplex service is constructed and how it is used. I created a simple service that contains a list of Movies. The clients have the ability to add a new Movie to the server, or delete an existing one. There’s no fancy business rules or elaborate domain objects because I’m mostly interested in documenting the duplex service usage.

You can download the application here. It was written in C#, .Net 3.5. It utilizes StructureMap for dependency injection (which I highly recommend) and I’ve included that library with the package. The executable files are included in the corresponding /bin directories so you don’t have to compile the application if you want to see it work.

Notes:

  • The server is a console application. It will write to the console when a client subscribes or unsubscribes from the service, and it will print the count of the remaining subscribers.
  • To see the real-time updating in action, open two clients. Add a new movie title to the list in one client and you’ll see the immediate update in both clients.

WCF Duplex Service Contract

A note about this service: You will notice I am passing .Net objects across the wire with this service. There are no data transfer objects and no requirements for interoperability. I have complete control over both sides of the wire; the client and server applications. And in general, when you are writing a client-server app that’s going to be the case. This is not a “web services” solution; there are plenty of those already.

There is a caveat to creating and using a WCF Duplex service: You have to keep the connection open if you want your client to respond to callbacks. With WCF, once a connection falls into a Faulted state it becomes useless, and there’s no going re-connecting. You have to re-create the connection from scratch.

Normally, when using a one-way service, you only create the connection for as long as it takes you to call the service. But here we want our client to actively listen to callbacks from the service (as opposed to polling the service, which puts the burden for updates on the client and can leave the client with stale data). To make that happen we have to utilize a keepalive call with a timer, so that we ping the service frequently enough to maintain the connection. WCF will timeout a connection after 10 minutes of inactivity due to the way the underlying timeout scheme is written, and I have yet to find a single configuration knob that will allow a connection to live longer than that in a reliable fashion. The keepalive, however, works and is rock solid.

My service implements two interfaces. One is for the plumbing associated with subscribing and unsubscribing to the service, and using a keepalive to maintain the connection to the service. The second interface is the one the client is really interested in, and has all the calls to deal with the data. You don’t have to separate these interfaces; I did because it shields the client from having to see those plumbing methods (they can still get to them if they cast want to it).

The plumbing interface looks like this:

[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof (IMovieServiceCallback))]
public interface IDuplexService
{
    [OperationContract]
    bool KeepAlive();

    [OperationContract]
    void Subscribe();

    [OperationContract]
    void Unsubscribe();
}

The second service interface looks like this:

[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IMovieServiceCallback))]
public interface IMovieService : IDuplexService
{
    [OperationContract]
    IList<Movie> FindAll();

    [OperationContract]
    bool Exists(string title);

    [OperationContract]
    void Add(string title);

    [OperationContract]
    void Delete(Movie movie);
}

In both cases I’ve decorated the service interface with the [ServiceContract] attribute and specified the [CallbackContract], which looks like this:

public delegate void MoviesChangedEventHandler();

public interface IMovieServiceCallback
{
    event MoviesChangedEventHandler OnMoviesChanged;

    [OperationContract]
    void MoviesChanged();
}

The only thing that’s left to do on the client side is setup the configuration file where we specify the WCF settings and then implement the interface. I’m not going to post the XML here (you can download the sample app to see it, basic WCF stuff). What I will do is post the relevant code inside the service that deals with subscribers.

Service Implementation

The service maintains a list of subscribers which take the form of the IMovieServiceCallback. The three key methods for dealing with the subscribers are thus:

bool IDuplexService.KeepAlive()
{
    return true;
}

void IDuplexService.Subscribe()
{
    var callback = OperationContext.Current.GetCallbackChannel<IMovieServiceCallback>();
    if (!_subscribers.Contains(callback))
        _subscribers.Add(callback);

    RemoveDeadConnections();
}

void IDuplexService.Unsubscribe()
{
    var callback = OperationContext.Current.GetCallbackChannel<IMovieServiceCallback>();
    if (_subscribers.Contains(callback))
        _subscribers.Remove(callback);

    RemoveDeadConnections();
}

The KeepAlive is the simplest thing; just return a boolean. All we really care about is hitting the service to keep it open, and we do that with the aid of a timer in the client’s proxy (which we’ll get to later on).

Where things get interesting is how we handle the manipulation of data. In a one-way service the client would ask the service to create a new Movie and persist it. Once that operation was complete, the client would then proactively ask the service for an updated list of Movies. The client does all the work in this situation, making the requests. That’s fine for one client, but if other clients want to know when the data changes, they have to poll the service.

With a duplex service we tend to make a request of the service and then forget about it; the service will update us (and every other client) when its ready. So deleting a Movie looks like this:

public void Delete(Movie movie)
{
    _repository.Delete(movie);
    _movieCache = _repository.FindAll();
    UpdateSubscribers();
}

The service delegates to a Repository to handle the delete, updates its internal cache, and then makes a call out to all the subscribers, in essence telling them, “Hey, the data has changed. Update yourself”.

Updating the subscribers then becomes a matter of looping through them and calling the method on the callback interface:

private void UpdateSubscribers()
{
    for (int i = _subscribers.Count - 1; i >= 0; i--)
    {
        if (((ICommunicationObject) _subscribers[i]).State == CommunicationState.Opened)
        {
            _subscribers[i].MoviesChanged();
        }
        else
        {
            ((ICommunicationObject) _subscribers[i]).Abort();
            _subscribers.Remove(_subscribers[i]);
        }
    }
}

We are doing one extra step here: getting rid of delinquent subscribers. You see, there’s no easy, event-driven way to determine when a client has faulted or disconnected in a non-nice way. So the best plan is to periodically prune off bad subscribers. In my service, I do this whenever the data changes, and whenever a client subscribes or unsubscribes. It helps keep the subscriber list clean.

Client Proxy

With the service side of things mostly out of the way it’s time to move on to the client. Here I’ve manually created a client proxy (not using svcutil.exe). The proxy class implements the methods from IMovieService. Beyond the methods on the IMovieService interface, the proxy has a few responsibilities:

  1. Create the DuplexChannel and establish the connection to the service.
  2. Subscribe to the service.
  3. Create a Timer and fire the KeepAlive periodically.
  4. Unsubscribe from the service when shutting down.
  5. Respond to callback events from the server and re-fire them in a chain-of-command style pattern to the client.

Connect handles the first three responsibilities:

public void Connect()
{
            _movieServiceCallback = new MovieServiceCallback();
            _movieServiceChannelFactory = new DuplexChannelFactory<IMovieService>(_movieServiceCallback, _movieServiceEndpointConfigurationName);

            _movieService = _movieServiceChannelFactory.CreateChannel();
            ((IContextChannel) _movieService).OperationTimeout = new TimeSpan(0, 0, 0, 30);
            _movieService.Subscribe();
            _movieServiceCallback.OnMoviesChanged += MoviesChanged;

            _timer = new Timer(60000);
            _timer.Elapsed += TimerElapsed;
            _timer.AutoReset = true;
            _timer.Start();
}

A Disconnect method handles the fourth responsibility. Responding to the service is handled by the MovieChanged event, which simply re-fires it:

 private void MoviesChanged()
{
    if (OnMoviesChanged != null)
        OnMoviesChanged();
}

The other thing that I have the proxy do is make asynchronous calls to the service for methods that I know should be asynchronous. An example is Delete():

private delegate void DeleteDelegate(Movie movie);

public void Delete(Movie movie)
{
    DeleteDelegate deleteDelegate = _movieService.Delete;
    AsyncCallback callback = AsyncCompleteMethod;
    deleteDelegate.BeginInvoke(movie, callback, null);
}

private void AsyncCompleteMethod(IAsyncResult ar)
{
}

When the client makes a call to delete, it’s made asynchronously, and the client can immediately return. The UI doesn’t lock up and life goes on for the client. When the service is done processing the delete it will update the subscribers. That’s when they’ll have to respond in a way that doesn’t lock the UI or crash the program.

Client

In my view’s presenter class I take a dependency on the IMovieService interface. By way of StructureMap, the presenter gets the MovieServiceProxy, and we wire up to it’s OnMoviesChanged event:

private IMovieService _movieService;

public ShellPresenter(IMovieService movieService)
{
    _movieService = movieService;
}

public override void OnViewReady()
{
    base.OnViewReady();
    ((IMovieServiceProxy) _movieService).OnMoviesChanged += MoviesChanged;
    MoviesChanged();
}

The MoviesChanged method just queries the service for the list of Movies (which are conveniently cached in the service, so the service isn’t hitting the database every time a client requests the list).

private void MoviesChanged()
{
    View.Movies = _movieService.FindAll();
}

And this is where the trouble occurs if you don’t handle it correctly. We’ve just had what amounts to a background thread inform us to update our view. If we try and do this directly we’re going to get some unpleasant behavior in our UI. So we let the View handle this properly:

public delegate void UpdateMovieListDelegate(IList<Movie> movies);

public IList<Movie> Movies
{
    set
    {

        if (InvokeRequired)
        {
            var args = new object[1];
            args[0] = value;
            BeginInvoke(new UpdateMovieListDelegate(UpdateDataGridView), args);
         }
         else
         {
             UpdateDataGridView(value);
         }
     }
}

 private void UpdateDataGridView(IList<Movie> movies)
{
    _dataGridView.DataSource = null;
    _dataGridView.DataSource = movies;
}

InvokeRequired is a property on Controls, and it’s a convenient way to determine if the update is coming from another thread. If so, we can launch the operation asynchronously on the proper thread, in this case, the UI thread, since controls in .NET can only be updated by the thread they were created on.

Real-time, client-server type applications aren’t terribly difficult to deal with, they just require a different mindset in regards to when things get updated. And then one just has to utilize the asynchronous tools that the .NET framework has provided to make sure things get done in a way that doesn’t cause your application to hang or crash.

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.

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 notifications);

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

And the Service itself:



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

   public virtual List GetNotifications()
   {
      List notifications = new List();

      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
{
   private INotificationService _notificationService; 

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

   private void AppClosingHandler(List 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();

   List 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!

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.

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.