Rich Newman

March 2, 2008

Model-View-Presenter using the Smart Client Software Factory (Introduction To CAB/SCSF Part 25)


Part 23 and part 24 of this series of articles described the Model-View-Presenter pattern.

This article explains how the Smart Client Software Factory supports this pattern by generating appropriate classes.

Guidance Automation Packages in the Smart Client Software Factory

We saw how we could use the Smart Client Application Guidance Automation Package to set up a Smart Client Application in part 18. We can also set up a Model-View-Presenter pattern in a Smart Client application using another of the Guidance Automation Packages.

This will only work in an existing Smart Client Application.

Running the Model-View-Presenter Package

To use the Guidance Automation Package we right-click in Solution Explorer on a project or folder where we want to run the package. It is intended that we do this in the Views folder in a business module. On the right-click menu we select ‘Smart Client Factory/Add View (with presenter)’. We get a configuration screen that lets us name our view, and also lets us put the classes that get created into a folder. For the purposes of this example we name our view ‘Test’, and check the checkbox that says we do want to create a folder for the view.

When we click ‘Finish’ we get three classes and a TestView folder as below:


Classes Created

  1. TestView
    This is (obviously) our View class. It is intended that this contain the auto-generated code to display the View. As discussed in the previous articles any complex view logic will not go into this class, but will go into the Presenter.
  2. TestViewPresenter
    This is our Presenter class. As discussed in previous articles this should contain logic to deal with user events. It should also contain any complex view logic, and should directly update the View with the results of an view logic calculations. It has access to the View class via an interface.
  3. ITestView
    This is the interface that the View implements. The Presenter can only update the View through this interface.


In terms of the diagrams shown in parts 23 and 24 this looks as below. Remember that we may or may not have arrows between the Model and the View depending on whether we are using the active View or passive View version of Model-View-Presenter:


Where’s the Model?

The Guidance Automation package does not set up a Model class for us. As we have seen, the Model has no direct references to a View/Presenter pair (it raises events), and there may be multiple View/Presenter pairs for one Model. Further the Model would not usually be in the same folder, or even in the same component, as our View and Presenter.

For these reasons we are expected to set up our Model classes separately by hand.

Note that the Presenter (and the View as well if we are using the active View pattern) will have a direct reference to the Model. We will have to add these references manually.

Active and Passive View: a Quick Recap

Remember that in Model-View-Presenter the Presenter updates the View via an interface. We can set this up so only the Presenter is allowed to update the View. This is the ‘passive View’ pattern. We can also set this up so that the Presenter can update the View in complex cases, but the View can also update itself (in response to an event or user request) in simple cases. This is the ‘active View’ pattern.

Active and Passive View: Which Should We Use?

The pattern described in the SCSF documentation is the passive View: the documentation implies that all updates to the View should be done by the Presenter.

However there is nothing to stop us using the active View pattern with the classes generated by the Guidance Automation Package. We can add code to update the View wherever we like. In fact I would recommend using active View in simple cases: passive View should only be used where we are putting too much logic into the View class.

Should We Use Model-View-Presenter for Every Screen? A Personal View

Let me also reiterate a point made in part 24. It’s easy to get obsessive about the use of patterns and use them everywhere without thinking. My personal opinion is that we should only use the full Model-View-Presenter pattern where we have a complex screen that will benefit from the separation of the View and Presenter classes. For very basic screens the pattern is really too complex to give us benefit. In simple cases I think it is fine to put event handling and screen update logic directly behind the screen.

Note that I don’t think this applies to the use of the Model. We should always separate out the business logic from our screens into separate classes (this is what Martin Fowler calls ‘Separated Presentation’). However, we frequently have screens that don’t show any business logic or business data, so we may not need a Model class either.

For example an About screen that just shows the system name and version won’t need separate View and Presenter classes, and probably won’t need anything in a Model class either.

Equally a screen that shows a read-only grid of currencies used in a trading system probably doesn’t need separate View and Presenter classes. In this case the currencies themselves should be in a Model class so that other screens can access them.

Implementation Details: What We’d Expect

If we examine the diagram above, we expect the Presenter to have a data member with type of our ITestView interface that it will use to access the View. We expect the View to implement the ITestView interface to allow this. We further expect the View to have a direct reference to the Presenter class (a data member), which it will use to invoke code relating to user events. We’d probably expect both the View and the Presenter classes to be created the first time the View is needed.

Implementation Details: the Base Presenter Class

The actual details of the implementation of the Presenter are a little unusual.

If we look at the code generated by the Guidance Automation Package we see that the TestViewPresenter above has been given its core functionality by inheriting from an abstract Presenter<TView> class. Remember that the generic ‘TView’ simply lets us provide a type whenever we use the Presenter class. Here we inherit from Presenter, and provide the type when we inherit:

    public partial class TestViewPresenter : Presenter<ITestView>

This allows the base Presenter class to have a data member of type ITestView (which is what we expect), rather than it being directly in the TestViewPresenter class. Note that the base Presenter is in the Infrastructure.Interface project (which is one of the reasons why we have to use this pattern in a Smart Client application).

The base Presenter class exposes our ITestView data member publicly, contains a reference to our WorkItem, and has disposal code and a CloseView method. It also has virtual OnViewReady and OnViewSet methods. These get called when you’d expect from the name and let us respond at the appropriate times by overriding the methods in our TestViewPresenter class.

All the above functionality in the base Presenter class means that the derived TestViewPresenter class is basically empty when it is created. It is up to us to put logic in there to handle user events and complex view logic.

The TestView class is a normal user control. It implements ITestView and contains a reference to the TestViewPresenter as we’d expect. It also calls OnViewReady as appropriate (in the OnLoad event of the user control). Again other than this TestView is also basically empty.


This article has shown us how to set up Model-View-Presenter classes using the Smart Client Software Factory, and discussed some issues surrounding it.

December 16, 2007

Foundational Modules and Names as Constants (Intro to CAB/SCSF Part 21)


Part 19 and part 20 of this series of articles looked at business modules in the Smart Client Software Factory.

This article looks at foundational modules briefly, and also discusses the pattern for handling names in the SCSF.

Foundational Modules

In part 18 of this series of articles we saw how we can use one of the Guidance Automation Packages to add a business module to our solution. There’s also a Guidance Automation package that lets us add a ‘foundational module’ to our solution. This is on the same submenu as the ‘Add Business Module (C#)’ option we saw above. So to add a foundational module to our solution right-click the solution folder in Solution Explorer, select Smart Client Factory/Add Foundational Module (C#) and then click through the two setup screens.

A foundational module is identical to a business module except that it does not have a root WorkItem. This is because it is intended to contain supporting functionality rather than core business functionality for our solution. It is not expected that we will create business objects and add them to the various WorkItem collections.

So we are expected to create fairly generic services and supporting code in foundational modules, rather than business code. Of course we could do this in the Infrastructure projects mentioned in part 18, but a foundational module allows us to separate out supporting code into its own CAB module.

Note that we can create an interface component, ‘Module.Interface’, for our foundational module in exactly the same way as for a business module. This allows other components in the solution to use the module’s functionality without referencing it directly, as described above.

Constants Folders

In our examples above we have seen several Constants folders being set up. The main Smart Client solution has a Constants folder in both the Infrastructure.Interface component and the Shell component. Both the foundational modules and the business modules have Constants folders in both their main Module components and their Module.Interface components.

The Constants folders all contain four classes: CommandNames, EventTopicNames, UIExtensionSiteNames, and WorkspaceNames. In the Constants folders mentioned above most of these are empty by default, although Infrastructure.Interface has some constants set up in its classes.

The important thing to notice here is that the individual classes with the same name are arranged in an inheritance hierarchy. So if we have a business module in our Smart Client solution (as in the code example we have already seen) then CommandNames in the Module itself inherits from CommandNames in Module.Interface, which in turn inherits from CommandNames in Infrastructure.Interface. CommandNames in Shell also inherits from Infrastructure.Interface.

The reason these classes exist is to allow us to use standard constants throughout our solution for names, rather than having to use strings. The inheritance hierarchy lets us define these constants at the correct level in the hierarchy, but then to use any of them very simply by just accessing the class at the level the code is at.

The reason we don’t want to use strings in our code as names is they are prone to error in entry (since we can’t use intellisense) and can’t be checked by the compiler at compile-time: if we enter a string name wrongly we will get a run-time error. If we use constants to represent these strings we avoid both of these problems.

This will be clearer in an example:

We might call a Workspace on our Shell form “LeftWorkspace” when we add it to the Workspaces collection of the root WorkItem. Elsewhere in the code we may want to retrieve that workspace and interact with it, for example to call the Workspace’s Show method to display a SmartPart. Normally to do this the syntax would be, for example:


The obvious difficulty with this is that we are just entering the name “LeftWorkspace” as a string, which is prone to error and the compiler can’t check.

So we add the code below to the WorkspaceNames class in Infrastructure.Interface. We add it to the Infrastructure.Interface component because the Workspace is being defined in the Infrastructure part of the solution, but we want it to be available outside of that:

public const string LeftWorkspace = "LeftWorkspace";

Now suppose we want to use this Workspace name in code in a business module. The WorkspaceNames class in the business module inherits from the WorkspaceNames class in Infrastructure.Interface, and hence the constant is available in that class. All we need do is reference that class to access any Workspace name. So we just import the appropriate namespace:

using SmartClientDevelopmentSolution.Module1.Constants;

And then we can do:


Now intellisense is available when we enter the ‘LeftWorkspace’ name, and the compiler can check that what we have entered is correct.

Note that if we have a Workspace name defined just for the module (say ‘LocalWorkspace’) we can still just do WorkspaceNames.LocalWorkspace to access it.

So these Constants folders provide us with an easy way of using named constants for items in the WorkItem hierarchy throughout our code.

December 12, 2007

SCSF Business Modules: Start Up and the ControlledWorkItem (Introduction to CAB/SCSF Part 20)


Part 19 of this series of articles discussed business modules in a Smart Client solution generated using the Smart Client Software Factory. This article continues that discussion.

The Load Method of a Business Module

As discussed in the previous article, a business module has a class called ‘Module’ which inherits from class ModuleInit. We saw in part 1 of this series of articles that this means the Load method in that class will get called at start up, provided the module has been added to the ProfileCatalog file.

The Load method of Module generated by the Smart Client Software Factory is as below:

        public override void Load()
            ControlledWorkItem<ModuleController> workItem = _rootWorkItem.WorkItems.AddNew<ControlledWorkItem<ModuleController>>();

As we can see, it’s creating a ControlledWorkItem class instance and adding it to the WorkItems collection of the root WorkItem. It’s then calling the Run method on the Controller property of this WorkItem.


ControlledWorkItem is a class that inherits directly from WorkItem. So a ControlledWorkItem is a WorkItem. The ControlledWorkItem also adds additional functionality to the WorkItem, and, crucially, it is a sealed class (which means we can’t inherit from it).

The idea here is that each business module should have a ControlledWorkItem as a root for its functionality. This is what we are creating in the Load method. In the overall WorkItem hierarchy each business module ControlledWorkItem is immediately below the root WorkItem for the entire solution.

Inheriting WorkItem to add Functionality

The ControlledWorkItem has been created to clarify the situation with regard to adding code to WorkItems. When we start using the CAB we quickly find that we need our WorkItems to be extended in various ways. They are intended to control business use cases, after all. For example we may want specific services instantiated at start up and added to the Services collection. Doing this in the WorkItem itself may seem like a sensible thing to do. Clearly the main WorkItem class is a CAB framework class, but we can inherit from it to give it this additional behaviour.

The reference implementations of both the CAB and the SCSF do this: each WorkItem inherits from the base WorkItem class and extend it to give the use case functionality. If you look at the CustomerWorkItem in the Bank Teller Reference Implementation you’ll see this.

Why Inheriting from WorkItem has been Deprecated

The difficulty with this is that our WorkItem class is acting as both a container for all the various WorkItem collections, as we have discussed before, AND as a place where all the code for a business use case goes.

This breaks the Single Responsibility principle, which is that every class should have just one responsibility in a system to avoid confusion.

As a result the Patterns and Practices team have decided it’s not ideal to have developers inherit from WorkItem and add functionality to the derived class. Instead a second class is created to contain the new code, and that class is associated with the WorkItem class by composition.

How ControlledWorkItem Addresses the Problem

This is what the ControlledWorkItem is doing. The ControlledWorkItem class itself inherits from WorkItem, but also has a member variable that references another class. The type of this class is generic (so the developer provides it), and the class is instantiated when the ControlledWorkItem is created.

So in the line of code below we are creating the ControlledWorkItem and adding it to the root WorkItem’s WorkItems collection. However we are also telling the ControlledWorkItem that its member class should be of type ModuleController, and that class will get instantiated and set up as the member variable.

ControlledWorkItem<ModuleController> workItem = _rootWorkItem.WorkItems.AddNew<ControlledWorkItem<ModuleController>>();

We are not expected to inherit from ControlledWorkItem itself. In fact we can’t because it is sealed: the Patterns and Practices team have done this deliberately to indicate that the pattern has changed. Instead we add our additional functionality for the WorkItem to the ModuleController class.


We can access the ModuleController instance from the ControlledWorkItem using the Controller property. We can then call a Run method on that class. This is the standard pattern that is generated by the Guidance Automation Package: note that the final line in the Load method above is:


So we can add start up code for the WorkItem into the ModuleController class in the Run routine.

The SCSF gives us a default ModuleController whenever we set up a Module, as we have seen. This has a default Run method. There isn’t any code that actually does anything in this method, but four empty methods are set up in ModuleController to indicate to us the sort of things we should be doing:

    public class ModuleController : WorkItemController
        public override void Run()

There are also comments in these routines to describe what we should be doing inthem. To see this in more detail look in any of the ModuleController classes in the sample code.

WorkItemController Class

Note also above that our default ModuleController inherits from a class called WorkItemController, which is an abstract base class intended to be used just of these controllers. Inheriting from this ensures that we have a Run method in our derived class as there is an abstract function of this name in the base class.

The base WorkItemController also gets a reference to the associated WorkItem using our usual dependency injection pattern. This can be accessed via the WorkItem property on the WorkItemController class.

Finally the WorkItemController class has two overloaded ShowViewInWorkspace methods, which can create and show a SmartPart in a named Workspace in the WorkItem.

Obviously we don’t have to make our ModuleController inherit from WorkItemController. However, if we don’t this base class functionality will not be available.


This article has discussed the standard patterns generated by the Smart Client Software Factory for starting up business (and other) modules.

Part 21 of this series of articles will look briefly at foundational modules, and will also discuss the way names are handling in Smart Client Software Factory projects.

December 9, 2007

Business Modules and Interfaces in the SCSF Smart Client Solution (Introduction to CAB/SCSF Part 19)


Part 18 gave a brief introduction to the Smart Client Software Factory. This article continues that discussion by looking at business modules, and also examining how the various modules in a Smart Client solution are expected to interact.

Recap on the Smart Client Application

In part 18 we saw that a ‘Guidance Automation’ package in the Smart Client Software Factory lets you create a base solution for a smart client program. It sets up four projects, three of which are infrastructure projects.

One of the projects is an empty ‘Infrastructure.Module’ project. Infrastructure.Module is a CAB module as described earlier in this series of articles: it isn’t directly referenced by the other projects in the solution but can be used to write infrastructural code for the solution without any tight-coupling with the rest of the solution. We’ll examine this in a little more detail below.

Business Modules

It isn’t intended that we put business logic into the Infrastructure projects discussed above. Instead we are meant to create ‘business modules’.

To create a business module we use another of the Guidance Automation packages: we right-click the solution in Solution Explorer, select Smart Client Factory/Add Business Module (C#), click ‘OK’ in the ‘Add New Project’ window and then click ‘Finish’ in the ‘Add Business Module’ window.

This gives us two new projects in the solution with default names Module1 and Interface.Module1 as below:


Once again here Module1 is a Composite Application Block module, and is not referenced by any other project in the solution. However, Module1.dll IS added to the ProfileCatalog (which is in Shell). This means that the Load method of a class inheriting ModuleInit in Module1 will get called by the CAB at start up, as described in part 1 of this series of articles. The class with the Load method in Module1 is called ‘Module’. We’ll look at what the Load method is doing in the next article in this series.

Note here that the Module and ModuleController classes are identical to those in Infrastructure.Module. Note also that there’s really no code at all in Module1.Interface: there are just some empty classes in a folder called Constants.

Business Module Interaction with the Rest of the Smart Client Project

As discussed in part 1 of this series, a ‘module’ is a standalone project to be used in a composite user interface. So our business module here is intended to be a slice of business functionality that can potentially be developed independently of the other modules in the application. Because the business module isn’t directly referenced by other modules a separate development team could potentially work on it and change it. It can then in theory be plugged in to the containing framework without the need for code changes in the framework. The other project’s libraries might not even need to be recompiled since they don’t actually reference the business module directly.

Clearly in practice it’s likely that the business module will have to interact with the rest of the Smart Client solution on some level. There will be a need for:

  1. The business module to use the infrastructure components: for example it might need to put a toolstrip into the Shell form.
  2. Other components in the Smart Client solution to use some of the business module functionality. As a simple example we might have a business module that deals with customers and a back-end customer database. It might have screens to show customer data and allow updates. Another business module might want to display these screens in response to a request: an Orders module might allow a double-click on a customer name to show the customer.

We want to achieve the interaction described above in a way that’s as loosely-coupled as possible, so that we can change the system easily. To do this we make sure that all interaction is through the Interface projects.

We now examine each of these possible scenarios in more detail:

1. The Business Module Using Infrastructure Components

For this scenario in our example solution Module1 references Infrastructure.Interface directly. It is set up to do this by default when you add the business module to the solution. Note that Infrastructure.Interface is intended to (mainly) contain .NET interfaces: it is not meant to contain large amounts of code.

Note that Module1 does not reference Infrastructure.Module or Infrastructure.Library directly, nor should it under any circumstances. These projects may well be under the control of a separate development team from our business module team, and they may need to be updated independently of the business modules. So we reference the interface project, and that handles our interaction with the Infrastructure libraries.

This seems to be a concept that developers working on these projects have difficulty with: almost every member of my development team at work has added one of these libraries to a business module at some stage.

I think the confusion arises because it’s not necessarily obvious how we do this. If my module just references an interface how can I actually call any functionality using just the interface? The answer is that we are once again using the dependency inversion and dependency injection concepts described in part 3 and part 4 of this series of articles.

An example here may help.


We’ll use the WorkspaceLocator service that the SCSF adds into the Infrastructure.Library component when we create a Smart Client solution. The WorkspaceLocator service lets you find the Workspace a SmartPart is being displayed in, although this isn’t relevant for this discussion: all we’re interested in is how to invoke the service from a business module.

There’s a class called WorkspaceLocator that actually does the work in SmartClientDevelopmentSolution.Infrastructure.Library.Services. There’s also an interface in Infrastructure.Interface as below:

namespace SmartClientDevelopmentSolution.Infrastructure.Interface.Services
    public interface IWorkspaceLocatorService
        IWorkspace FindContainingWorkspace(WorkItem workItem, object smartPart);

Note that Infrastructure.Library references Infrastructure.Interface and so WorkspaceLocator can implement this interface. Note also that our business module, Module1, also references Infrastructure.Interface but NOT Infrastructure.Library. So it can’t see the WorkspaceLocator class directly and thus can’t call FindContainingWorkspace on it directly. So how do we use the service?

The answer is that this is the standard CAB dependency inversion pattern using WorkItem containers to access objects.

At start up the solution creates an instance of the WorkspaceLocator service and adds it into the Services collection of the root WorkItem, referencing it by the type of the interface:

RootWorkItem.Services.AddNew<WorkspaceLocatorService, IWorkspaceLocatorService>();

This actually happens in the new SmartClientApplication class mentioned in part 18, but all we really need to know is that the service will be available on the root WorkItem.

Now, in our module we know we can get a reference to the root WorkItem in our new module by dependency injection in a class:

        private WorkItem _rootWorkItem;
        public Module([ServiceDependency] WorkItem rootWorkItem)
            _rootWorkItem = rootWorkItem;

Our module also knows about the IWorkspaceLocator interface since it references Infrastructure.Interface. So it can retrieve the WorkspaceLocator service object from the root WorkItem using the interface, and can then call the FindContainingWorkspace method on that object:

            IWorkspaceLocatorService locator = _rootWorkItem.Services.Get<IWorkspaceLocatorService>();
            IWorkspace wks = locator.FindContainingWorkspace(_rootWorkItem, control);
            MessageBox.Show("Workspace located: " + wks.ToString());

In summary, as long as our module knows the interface to the functionality it needs, and knows how to retrieve an object that implements that interface from a WorkItem collection of some kind, it doesn’t need to have direct access to the underlying class to use the object. This was explained in more detail in earlier articles in this series.

2. Other Components Using the Business Module Functionality

For other components to use our business module functionality we are expected to work out what functionality our business module should expose to the rest of the solution. We should then define interfaces that allow access to that functionality and put them into our Module1.Interface component.

Other components in the solution can then reference Module1.Interface and call the functionality. Note that to allow them to do this we need to ensure that the correct objects are available in a WorkItem, as described above. Once again other components should NOT reference Module1. We can then change Module1 without impacting the other components.

We may of course need to change the interfaces. In this case it may be sensible to retain the old version of the interface component itself so not all other components have to upgrade, and to add a new version with the changed interfaces in as well. The old interface can then be disabled when everyone has upgraded.


This article has examined modules in a Smart Client solution, and discussed how they should interact.

Part 20 of this series of articles will look in a little more detail at some of the new code structures in modules in a Smart Client solution.

December 8, 2007

Introduction to the Smart Client Software Factory (CAB/SCSF Part 18)

Filed under: .net, CAB, Composite Application Block, SCSF, Smart Client Software Factory — richnewman @ 5:45 pm


So far in this series of articles the focus has been on the core functionality of the Composite Application Block (CAB). No mention has been made of the Smart Client Software Factory (SCSF), in spite of the fact that the series is entitled ‘An Introduction to the Composite Application Block and the Smart Client Software Factory’.

This article and the ones that follow will remedy that. They will discuss what the Smart Client Software Factory is, how it relates to the Composite Application Block, and how to use it.

Versions of the Composite Application Block and Smart Client Software Factory

The first version of the Composite Application Block was released in December 2005. This had all of the features that have been described in this series of articles so far. As was mentioned in part 1 of this series, the Composite Application Block on its own is quite difficult to understand and learn how to use. Furthermore, documentation and support in the initial version were somewhat lacking: many developers complained that they couldn’t understand how to use the new framework.

The Patterns and Practices team released a follow-up version in June 2006, and another in May 2007. However, they did not attempt to change the core Composite Application Block code. Instead they provided additional documentation and examples, as well as a way of automatically generating code for various useful patterns using the Composite Application Block. We’ll examine this in a little more detail below.

The idea behind these SCSF releases was to make it easier for developers both to learn and to use the Composite Application Block software (and other application blocks). However, as we shall see, the SCSF introduces new code and patterns on top of the CAB’s already complex structures, and the documentation could still be clearer. In many ways the Patterns and Practices team have added to the confusion with these releases rather than clarifying the situation.

Software Factories

The last two releases were branded as the ‘Smart Client Software Factory’. A ‘software factory’ is one of the latest computer industry buzzwords.

The idea behind software factories is that current software development practices depend on highly-skilled developers, who are similar to craftsmen in a pre-industrial age. The argument is that the need for highly-skilled craftsmen is the reason that many software projects fail: there are too few really good craftsmen, and they are usually hand-crafting from scratch in every new project. We need to ‘industrialize’ the software development process. Software should be created using ‘software factories’.

Like many computer industry buzzwords, what a ‘software factory’ is in practice is a little unclear. It tends to vary depending on the author, but in general a software factory should provide a means of producing code in a standard way. This may mean reusing and customizing existing code, simply following a set of guidance practices, or generating code automatically based on a model, which may be visual. It may mean a combination of all of these techniques. The phrase is also often used to describe model-driven development, possibly using domain-specific languages.

Smart Client Software Factory

Microsoft’s ‘software factory’ is slightly simpler than some of the usual definitions described above. The ‘Smart Client Software Factory’ comprises a small set of code generators plus some documentation and examples. The code generators are quite straightforward, producing code to set patterns (there’s no model to be maintained here).

The paragraph below is from the SCSF documentation:

‘The software factory provides a set of proven and integrated practices that are exposed through patterns, How-to topics, QuickStarts, a reference implementation, a Visual Studio Guidance Automation Toolkit package, and architecture documentation. The software factory guides projects through the development of smart client applications based on the architecture of the Composite User Interface Application Block.’

The Visual Studio Guidance Automation Toolkit Package

The Smart Client Software Factory includes a ‘Visual Studio Guidance Automation Toolkit Package’. This is an add-in to Visual Studio that automates certain software development tasks relating to the CAB. Some of these are added to the right-click context menu in Solution Explorer.

Probably the most useful Guidance Package, however, is the one that generates a new Smart Client Application project. This is also a good place to start when investigating what the Smart Client Software Factory can do.

This Guidance Package is available if you request a new project in the usual way inside Visual Studio after the SCSF has been installed. The New Project window has a project type of ‘Guidance Package’ available. Underneath that you can choose a new ‘Smart Client Application (C#)’:


If you select this option the Guidance Package will show a screen that allows you to set some properties of your solution. In particular you need to tell the Package where the Composite Application Block libaries are, and to set some options. These include whether you want a separate module for layout of the Shell (in general you won’t want this). The Guidance Package will then set up a Smart Client solution as below:


The SmartClientDevelopmentSolution

This is a base solution for a smart client project using the Composite Application Block. It gives your code some basic structure. It also gives you a lot of code on top of the Composite Application Block code itself: the various projects contain about 3,000 lines of code in total.

So we have even more code to try to understand if we are to use the resulting project effectively.

As you can see we are given four basic projects:

1. Shell

This is the start-up project for the solution. It is very similar to the start-up projects in the sample applications we’ve already seen in this series of articles: it has a start-up class (ShellApplication) which (indirectly) inherits from FormShellApplication. It has a form, ShellForm, which is the containing window for the application. It has a ProfileCatalog which will contain the composite application modules to be loaded.

If you compare this the Naïve Application sample code from part 1 of this series of articles you will see the similarities.

However, there are subtle differences as well, mainly in the form of extra code constructs. For example, ShellApplication actually inherits from a class called ‘SmartClientApplication’ which in turn inherits from FormShellApplication. The SmartClientApplication class simply sets up some SCSF services.

Additionally the ProfileCatalog now allows us to specify dependencies. We also have a Constants folder with a series of class files in it. We’ll examine these extra code constructs in later articles.

2. Infrastructure.Interface

The remaining Infrastructure projects are intended to provide common functionality for all of the composite applications we add into our solution. However, we don’t want to directly reference the projects that contain the code. Instead we want to hide the code behind interfaces in a separate library and reference the interface library. Infrastructure.Interface is this interface library. It mainly contains interfaces, with some simple classes.

3. Infrastructure.Library

The Infrastructure.Library project contains the bulk of the new code that this SCSF solution gives us. In fact it contains about 2000 lines of code, including such things as the Action Catalog, and support for loading modules using sources other than ProfileCatalog.xml.

4. Infrastructure.Module

Infrastructure.Module is an empty module project. It is intended that any code that we as developers want to add to the infrastructure section of our solution will go in here. It is a CAB module, which we have seen before, and it contains a ModuleInit class as we’d expect (see part 1 of this series of articles). However, it also contains a ModuleController class, which inherits WorkItemController. This will be discussed further in the next article.


This article has given us an overview of the Smart Client Software Factory, and shown how one of it’s key components is the ability to create a standard solution that can be used as the basis for a Composite Application Block application.

Part 19 of this series will discuss this solution a little more, and will look at SCSF Business Modules.


Discussion of software factories:

November 4, 2007

Composite Application Block or WPF Composite Client?

I’ve had a question from a Greg Bayer this week about what my thoughts were on the Composite Application Block and Smart Client Software Factory (CAB/SCSF) ‘now that it appears that both are being put out to pasture by Microsoft’. My response became a little long to be posted as a comment.

I suspect Greg was referring to the announcements from Microsoft about the ‘Windows Presentation Foundation(WPF) Composite Client’ and the death of Acropolis this week:

Acropolis, of course, was Microsoft’s ‘CAB/SCSF for WPF’ (we’re in acronym hell here). Put more simply, it was intended to be the next version of the Composite Application Block. The Acropolis team have released a few previews (CTPs), but now it appears that a new direction is being taken and something called the ‘WPF Composite Client’ will effectively replace it.

My thoughts on this are that it actually clarifies the situation for those of trying to write user interface software right now. No CAB replacement is arriving soon (a year away), so if we want a composite application framework from Microsoft the CAB has to be the one to go for. And there isn’t anything else on the market that is directly comparable, although obviously there are other dependency injection frameworks we could use.

Even when this CAB replacement arrives it is going to focus on Windows Presentation Foundation (WPF). WPF is the future for user interface developers, and we should all be looking at it. However, I wouldn’t use it for enterprise development right now. It’s still early days for a new technology, it has some serious failings currently (the user interface editor isn’t great), and it has a huge learning curve. It’s not at all clear that taking the risk of using such a new technology is going to give you sufficient business benefit to warrant the extra cost. Some of the major benefits of WPF just aren’t relevant for the sort of application I develop (e.g. better multimedia integration).

And what’s more, you can’t run it on Windows 2000, which can still be an issue if you work in a major organization.

As Glenn Block says ‘Win Forms is not dead.’ ‘Win Forms is the recommended breadth solution for LOB application development for the foreseeable future’.

So, in answer to Greg’s question, the CAB is still relevant, and I would still use it on an application I was starting to build today. That answer may well change in a year’s time however.

Having said all that, my opinions on how we should use the current version of the CAB may not be what you expect. The CAB is a superb piece of software. Even where the Patterns and Practices group have got things wrong they’ve done so in an interesting way, and you can learn from their mistakes.

However using an all-pervasive dependency injection framework can get you into a scoping mess. By ‘all-pervasive’ I mean putting every object you create into a dependency injection container, and only mapping dependencies through those containers (never using ‘new’). Controlling scope doing this is difficult, and you can end up destroying all the encapsulation advantages of object-orientation. I’ll be blogging about this in the future, but I think a more restricted use of the CAB may be appropriate.

October 27, 2007

Introduction to SmartParts and Workspaces (Introduction to CAB/SCSF Part 15)


Part 14 of this series of articles discussed UIExtensionSites. This article continues our discussion of user interface elements in the Composite Application Block by giving an introduction to SmartParts, and a very brief introduction to Workspaces. Part 16 will expand on this discussion. Workspaces and SmartParts are interlinked and to understand one you need some understanding of the other.

Why do we need Workspaces and SmartParts?

We don’t have to use any of the new user interface elements described in this article. We can create a composite application as described in previous articles using just the existing Form class, UserControl class and the various visual components found in the standard toolbox in Visual Studio. Part 1 and part 5 of this series of articles showed how we can construct a very basic multiple document interface (MDI) application comprising three independent modules. Those articles didn’t use any of the CAB user interface components.

Many introductory texts on the Composite Application block start with Workspaces and SmartParts. This series of articles has left them until close to the end. This is because I personally found SmartParts very confusing (and still do to a certain extent), and because we don’t need to use them to get the benefits of the Composite Application Block. Workspaces are more useful, as we shall see.


‘SmartParts’ were first introduced in the original CAB code back in 2005. As mentioned above the concept can be confusing. SmartParts are most easily thought of as user controls in a CAB application. In fact they can be any visual element low-level element in your CAB user interface. They can, for example, be child forms in an MDI application.

However, in almost every case you will come across SmartParts will be user controls (including the normal children in CAB MDI applications).

Microsoft’s CAB documentation defines a SmartPart as ‘a view of data (in the MVC pattern) such as a control, a Windows Form, or a wizard page’. This is slightly misleading as SmartParts don’t necessarily have to display any data, and don’t have to be in an MVC pattern.

SmartParts Collections

In part 2 of this series of articles we saw that a WorkItem can be thought of as a ‘run-time container of components’ and that the WorkItem class has various collection classes associated with it (e.g. Items, Services, WorkItems). One of these collection classes is the SmartParts collection. As we shall see later in this article, another collection class on a WorkItem is the Workspaces collection.

So perhaps a better definition of a SmartPart is as any object that is put into the SmartParts collection in a WorkItem in the CAB.

However, even this definition is confused by the fact that the Workspaces collection itself has a SmartParts collection. This means there are two SmartParts collections at different places in any WorkItem. This article will call these ‘WorkItem SmartParts’ and ‘Workspace SmartParts’. The two collections behave in different ways, which are discussed below. Before that we’ll take a quick look at what a Workspace actually is. This brief exposition will be expanded on in part 16.


Microsoft’s CAB documentation defines Workspaces as:

“The components that encapsulate a particular visual layout of controls and SmartParts, such as within tabbed pages.”

Workspaces are themselves controls that allow other controls to be laid out within them. In particular they are designed to allow SmartParts to be laid out within them.

Several Workspace types are available in the Visual Studio toolbox and can just be dragged onto our screens. In this sense they are like the existing layout controls in the .NET Framework (e.g. the TabControl).

Where Workspaces differ from existing layout controls is in the fact that they are part of and utilize the CAB dependency injection containers (Workitems). As with SmartParts, WorkItems have a ‘Workspaces’ collection which, obviously, contains all the Workspaces associated with the WorkItem.

We can create a Workspace in our Workspaces collection in the usual way with the AddNew keyword. However, we don’t need to do this if we’ve just dragged our Workspace onto a screen: the ObjectBuilder will recognize it as a Workspace when it is created, and add it to the appropriate collections.

Workspaces also interact with SmartParts in a standard way: they have a Show method that will display a SmartPart, an ActiveSmartPart property that gets a reference to the active SmartPart in the Workspace, and so on. These methods will be examined in more detail in part 16 of this series of articles.

SmartParts Collections: WorkItem SmartParts

We look now at the SmartParts collections in more detail. To show the concepts involved there is a code example available.

The SmartParts collection in a WorkItem is just a filter on the Items collection, filtering for any Items where the underlying class is decorated with the attribute ‘SmartPart’. If we have an object whose class is decorated with the SmartPart attribute and add it directly to either the Items collection or the SmartParts collection it will appear in both. However, if we try adding an object NOT decorated with the attribute to the SmartParts collection it will get added to the Items collection only.

The underlying type of our SmartPart doesn’t matter for this . It can be any class at all. As long as that class is decorated with ‘SmartPart’ it will behave as described above. The intention is that objects added to this collection be visual ones (user controls, forms etc.) but they don’t have to be.

Example of WorkItem SmartParts

This is illustrated in the code example. Here we have a user control, UserControl1, that is decorated with the SmartPart attribute:

    public partial class UserControl1 : UserControl
        public UserControl1()

In the AfterShellCreated method we add this to the SmartParts collection of the RootWorkItem:


We then examine what effect that has on the various collection classes on the RootWorkItem. We can see that the UserControl1 object is in both the SmartParts collection and the Items collection as we would expect (see below for the results output).

Similarly we define a plain old .NET class and also decorate that with the SmartPart attribute:

    internal class TestClass {}

We then just add that to the Items collection of the RootWorkItem in AfterShellCreated:


If we now look at the RootWorkItem collection classes we see that the TestClass object is in both the SmartParts collection and the Items collection in exactly the same way as the UserControl instance above. It is a ‘SmartPart’ even though it has no visual element.

The full output of the relevant collections from this example is shown below under ‘Output from SmartParts Example’.

SmartParts Collections: Workspace SmartParts

As discussed above, the second SmartParts collection is on a Workspace. An object gets added to this collection if we call the Show method on the Workspace with the object as the parameter.

For the Workspace SmartParts collection it doesn’t matter whether the object’s class is decorated with the ‘SmartPart’ attribute or not: it gets added to the Workspace SmartParts collection when the Show method of the Workspace is called regardless.

Note that the Show method doesn’t add the object into the Items collection of the WorkItem, nor does it add the object into the WorkItem SmartParts collection.

We’ll examine how Workspaces work, and how they interact with SmartParts, in more detail in part 16 of this series of articles. In particular we’ll look at why the Show method is a useful one, and we’ll examine how SmartPartInfo classes work and why we need them. For now you can just accept that this second collection exists and can be useful.

Issues with Workspace SmartParts

One issue here is that objects can only be added to the SmartParts collection of a Workspace if they inherit System.Windows.Forms.Control at some level. That is, in this case our SmartParts are forced to be visual controls.

Also you can’t add SmartParts directly to the SmartParts collection of a Workspace. The only way to add an object to this collection is to use the Show method of the Workspace (I think). Note that they don’t get removed from this collection just because you call Show with a different SmartPart.

You were warned that this is confusing.

Example of Workspace SmartParts

The code example discussed above has been extended to show how Workspace SmartParts work. We have added a DeckWorkspace (one of the more common Workspace classes) to our Shell form simply by dragging it from the Toolbox. We’ve also added another user control class to the project, UserControl2.

We then display the user control in the Workspace by calling the Show method:

this.Shell.deckWorkspace1.Show(new UserControl2());

This has the effect of adding UserControl2 to the SmartParts collection of the Workspace. However, UserControl2 is NOT added to the Items collection of the WorkItem, nor to the SmartParts collection of the WorkItem.

In the example above we defined a plain old .NET class and added it to the WorkItem’s SmartParts collection. We can’t do this with the Workspace’s SmartParts collection because this collection will only accept objects that inherit from Control at some level.

One thing to note here is that UserControl2 is decorated with the SmartPart attribute, but this makes no difference at all to the example. We can remove it and the example will work in the same way. This is because this attribute is not relevant for the SmartParts collection on a Workspace.

Output from SmartParts Example

The SmartParts example uses some simple looping code to output the collections created to the Output window. The results of this are shown below. As we can see, UserControl1 and TestClass (discussed in the section ‘Example of WorkItem SmartParts’ above) appear in the Items collection, and in the SmartParts collection at RootWorkItem level. However, UserControl2 (from the section ‘Example of Workspace SmartParts’) appears ONLY in the SmartParts collection on the Workspace. This is what we’d expect as discussed above.

[d506f65b-e818-4379-b15a-5e53bfe7777f, Microsoft.Practices.CompositeUI.State]
[f4d17dcd-13cc-4d61-b24b-0b3cd03c88a8, Shell.Form1, Text: Form1]
[deckWorkspace1, Microsoft.Practices.CompositeUI.WinForms.DeckWorkspace]
[1d141251-3436-4a8a-8bd3-1e63ceca3d9e, Shell.UserControl1]
[632482f5-aaa3-490b-b800-3575bea33a06, Shell.TestClass]
[1d141251-3436-4a8a-8bd3-1e63ceca3d9e, Shell.UserControl1]
[632482f5-aaa3-490b-b800-3575bea33a06, Shell.TestClass]
[deckWorkspace1, Microsoft.Practices.CompositeUI.WinForms.DeckWorkspace]

The SmartPart Attribute

Another source of confusion with SmartParts is what exactly the SmartPart attribute does. Several texts mention that it doesn’t seem to make much difference whether it’s there or not, and this is true to an extent with the Workspace SmartParts collection.

In fact there are (at least) two places where the SmartPart attribute makes a difference:

  1. As we’ve already seen any object decorated with the SmartPart attribute that is added to either the Items or the SmartParts collection of a WorkItem will effectively be added to both collections. Any object without the SmartPart attribute added to either collection will end up in the Items collection only. Remember that the SmartParts collection of a WorkItem is really just a filter on the Items collection for any objects that have the SmartPart attribute.
  2. The SmartPart attribute also makes a difference if we add a Control to the Controls collection of the Shell, or to the Controls collection of a Control on the Shell, when the Shell is being initialized (in its constructor). In this case the ObjectBuilder recognizes that we have a WorkItem SmartPart. It adds the SmartPart to the Items collection of the WorkItem and hence to the SmartParts collection (since it has the SmartPart attribute).

This is still confusing, but the behaviour in 2 is there so that if you drag a User Control with the SmartPart attribute onto the Shell from the Toolbox then it will get added to the SmartParts collection of the root WorkItem at start up.

Example of Effects of SmartPart Attribute on User Controls Dragged on to the Shell Form

Some example code showing this is available. This has a user control with the SmartPart attribute applied (SmartPartUserControl) and a user control with no SmartPart attribute (NormalUserControl). Both of these have been dragged onto the Shell form (Form1).

Additionally in the constructor of the Shell form we manually instantiate a SmartPartUserControl and add it to the Form’s Controls collection:

    public partial class Form1 : Form
        public Form1()
            SmartPartUserControl smartPartUserControl = new SmartPartUserControl();
            smartPartUserControl.Name = "Manually instantiated user control";

That’s all the code that’s been added. Once again the code dumps the various relevant WorkItem collections in AfterShellCreated by using simple loops outputting to the Output window:

[fa70dbe9-0c30-443e-9fe6-a13e353994e0, Microsoft.Practices.CompositeUI.State]
[d67d7177-cf63-4b4f-9447-ef2fd1e8271b, Shell.Form1, Text: Form1]
[userControl11, Shell.SmartPartUserControl]
[deckWorkspace1, Microsoft.Practices.CompositeUI.WinForms.DeckWorkspace]
[Manually instantiated user control, Shell.SmartPartUserControl]
[userControl11, Shell.SmartPartUserControl]
[Manually instantiated user control, Shell.SmartPartUserControl]
[deckWorkspace1, Microsoft.Practices.CompositeUI.WinForms.DeckWorkspace]

As we can see, both SmartPartUserControls have been added to both the Items and WorkItem SmartParts collections, whilst the NormalUserControl does not appear (although we can see it on the Shell fine: it just hasn’t been added to these collections). This is what we’d expect from the discussions above.

Summary of the SmartParts Collections and their Intention

The intention of the Workspace SmartParts is to give us (and the CAB Framework) a collection of SmartParts that have been shown in a Workspace but not closed. These can be re-activated (effectively brought to the front). We can show Controls that are not marked with the SmartPart attribute in a Workspace (and hence arguably aren’t really SmartParts). However this collection needs to track everything that has been shown, and so it all ends up in this collection.

The intention of the WorkItem SmartParts is to give us a collection of SmartParts that we as developers can control and use. Here we do want everything in the collection to have the SmartPart attribute: this is what distinguishes SmartParts from ordinary Items as far as this collection is concerned.

Workspace SmartParts have to be Controls (i.e. inherit from System.Windows.Forms.Control at some level). WorkItem SmartParts can be any object.

My personal opinion is that it would have been less confusing if the CAB developers had given the SmartParts collection on the Workspace a different name: ‘ViewsShown’ or something similar might have been better.


This article gave a brief introduction to SmartParts and showed why they can be confusing. It also gave an even briefer introduction to Workspaces. Part 16 of this series of articles will examine Workspaces in more detail, and expand on how we can use SmartParts in our code. It will also look at the SmartPartInfo class.

October 20, 2007

More on UIExtensionSites (Introduction to CAB/SCSF Part 14)


Part 13 of this series of articles discussed UIExtensionSites, and gave a basic example of how they work.

This article discusses UIExtensionSites in more detail, including a discussion of their use of the Adapter design pattern.

Whilst most of this article is fairly straightforward, I should say now that I am very sceptical of the value of UIExtensionSites and we have decided not to use them in our current project. I’ll discuss this below.

Additional Functionality of the UIExtensionSites

The basic example in part 13 showed how we can register a ToolStrip as a UIExtensionSite in a WorkItem using the RegisterSite method. We can then access it from other modules via the UIExtensionSites collection of the WorkItem.

In particular we can then add ToolStripButtons to it using the Add method of the UIExtensionSite.

In addition to the Add method, a UIExtensionSite has a Remove method which, clearly, removes an item that has been added to the UIExtensionSite.

A UIExtensionSite is really just a simple collection class behind the scenes (in fact it’s a wrapper around List<object>). Obviously in the case of a ToolStrip it’s a collection of ToolStripButtons.

In addition to the Add and Remove methods, the UIExtensionSite class has some of the usual public methods you’d expect on a collection class: Count, Clear, Contains, and GetEnumerator (which allows ‘foreach’ to be used on the collection, of course).

Types that can be added to a UIExtensionSite

The only types that can be registered as UIExtensionSites without additional work are types that contain ToolStripItems: that is, ToolStrips, MenuStrips and StatusStrips.

It is possible to set up other user interface items so that they can be used as UIExtensionSites. To do this you need to write an adapter class for your user interface items. We’ll examine this in more detail below.

Restrictions of UIExtensionSites

So we have a means of adding a ToolStrip, MenuStrip or StatusStrip to a collection that can be accessed from any module in a Composite Application Block project. We can then add or remove ToolStripItems from the ToolStrip, MenuStrip or StatusStrip. We can clear them as well.

However, that’s it. If we want to do anything more sophisticated we can’t easily. For example, if we have a menu item that can be checked we can’t use these interfaces to find out if it’s checked or not. Equally, if we just want to hide a ToolStrip from code it can’t be done easily.

You might think you could cast the UIExtensionSite back to its original type to get this functionality. So to hide the ToolStrip you might cast the UIExtensionSite to ToolStrip and call the Hide method. Unfortunately this isn’t possible: there isn’t a direct cast to the underlying type. We’ll examine the relationship between ToolStrip and UIExtensionSite in a little more detail below.


So what is the UIExtensionSite giving us? I’m sure the original idea was to decouple our underlying user interface items (ToolStrips etc.) from the way individual modules would access them. By having a generic UIExtensionSite with a generic interface we could plug in any user interface element we wanted, and maybe even swap them around. So if we wanted to use a different ToolStrip to Microsoft’s we could do so: all we’d really need to do would be to ensure the methods in the interface (Add, Remove etc.) worked correctly.

However even this isn’t possible with the current implementation of UIExtensionSite. If you look back at the code in the basic example in part 13 we are explicitly creating a ToolStripButton object in our client code:

            ToolStripButton toolStripButton = new ToolStripButton("Show Red Screen");
            toolStripButton.Click += new System.EventHandler(toolStripButton_Click);
            UIExtensionSite uiExtensionSite = parentWorkItem.UIExtensionSites["ShellToolStrip"];

In this code we have decoupling in the sense that we are handling a generic UIExtensionSite object rather than a specific ToolStrip object. However we are still tightly coupled to Microsoft’s ToolStrip since we’re creating the ToolStripButton. If we wanted to swap out the ToolStrip and replace it with a different one we’d have to change all this code.

As I mentioned in the introduction, I am struggling to understand what UIExtensionSites are giving us: they make it difficult to access core functionality of our ToolStrips etc. without giving us proper decoupling.

How is the Basic Example Working?

In the example in part 13 we added a ToolStrip to the UIExtensionSites collection of the RootWorkItem. We then retrieved the same object from the same collection. However, when we retrieved the object it had type UIExtensionSite. This meant that we then called the Add method of UIExtensionSite to add buttons to the ToolStrip.

You may be wondering how we managed to do this. UIExtensionSite is a class, and clearly ToolStrip doesn’t inherit it. How are we calling Add on UIExtensionSite and getting ToolStripButtons added to a ToolStrip class? The answer to this is that we are using an adapter pattern, as we shall see in more detail below.

Using Other User Interface Elements as UIExtensionSites

As mentioned above we can use other user interface elements than just ToolStrips, MenuStrips and StatusStrips as UIExtensionSites. However, we have to do a little more work to get this going. In fact, we have to write an adapter class for our user interface element. This tells the CAB what to do when the Add or Remove methods are called on the associated UIExtensionSite.

Before we discuss how to do this we’ll quickly recap the Adapter pattern.

The Adapter Design Pattern

The adapter is a pattern that we use when we want a class to implement a standard interface but don’t want to (or can’t) change the actual code of the class. In the case of our UIExtensionSites our user interface elements (e.g. ToolStrips) will have methods for adding and removing individual items (e.g. ToolStripButtons). However we want to be able to use a generic ‘Add’ method on a UIExtensionSite object to add ToolStripButtons. We clearly can’t change the ToolStrip class to implement this, so we use an adapter.

The book ‘Design Patterns: Elements of Reusable Object-Oriented Software’ (the ‘Gang of Four’ book) says the intent of the Adapter pattern is to:

“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.”

The Adapter class diagram is below:


The idea here is that we have some class Adaptee that has a ‘SpecificRequest’ method that the client wants to call. However, the client code uses an Adapter class to invoke the functionality, calling the ‘Request’ method. Adapter is an abstract base class: it’s just defining an interface that the client code will use.

Furthermore we can’t, or don’t want to, change the Adaptee class to actually inherit from Adapter. So instead we write a ConcreteAdapter class. This inherits Adapter, and so has a Request method. It also takes a reference to the Adaptee class (usually in its constructor) and caches it in a data member. This means we can write a very simple implementation of the Request method in our Adapter class that simply forwards the call to the SpecificRequest method on the Adaptee object in the data member.

Now the client code can work with Adapter objects, calling the Request method, but still get the functionality of the SpecificRequest method of the Adaptee.

Of course the Adapter class can do much more work than just forwarding method calls to methods with different names. The Adaptee might need several calls to do the work we want done in the call to Request on the interface, and the Adapter class can clearly deal with that as well.

One consequence of the use of this pattern is that we can’t cast our Adaptee class to Adapter since it doesn’t implement it directly. This explains why in our examples we can’t cast our UIExtensionSite (or the IUIElementAdapter data member it contains) back to our original ToolStrip. As mentioned above this restricts quite severely what we can do with a UIExtensionSite.

How this is Implemented in the CAB for UIExtensionSites

For UIExtensionSites in the Composite Application Block this pattern is made slightly more complex. The Patterns and Practices group have separated out the interface implemented by our Adapter base class into an actual C# interface called IUIElementAdapter which is then implemented by our abstract base class
UIElementAdapter<TUIElement>. You don’t need to worry about the details of this. All you need to know is that to implement your own adapter you need to inherit from UIElementAdapter<TUIElement> where TUIElement is the type of the objects that will be added to or removed from the UIExtensionSite. Inheriting this class compels you to override the abstract Add and Remove methods that it contains.

As you’ve probably realized, the Composite Application Block already contains an adapter class for ToolStrips, MenuStrips and StatusStrips. This is snappily called ‘ToolStripItemCollectionUIAdapter’and is in the CompositeUI.WinForms library.

Custom UIExtensionSite Example

This example will again be based on the Red and Blue form example used in part 13. This time we will add a panel to the left side of the screen that display link labels. Our link labels will bring the appropriate red or blue screen to the front:


The panel will be set up as a UIExtensionSite. It will therefore have an Add method that allows you to add a LinkLabel into the panel, and similarly have a Remove method that allows you to take one out.

The code for this example is available.

LinkLabelPanel User Control

To implement this the first thing we need is a user control to act as the panel for the LinkLabels. This needs to have methods to add and remove labels. To set this up all we have to do is add a UserControl to the Shell project, make its background white, and add methods to handle the LinkLabels as below:

    public partial class LinkLabelPanel : UserControl
        public LinkLabelPanel()
        private const int labelSpacing = 22;
        private int nextLabelTop = 10;
        private const int left = 3;
        public void AddLabel(LinkLabel label)
            label.Location = new Point(left, nextLabelTop);
            nextLabelTop += labelSpacing;
        public void RemoveLabel(LinkLabel label)

As you can see this keeps track of where the next LinkLabel should be positioned vertically in data member nextLabelTop. We can add a LinkLabel to the panel by calling AddLabel, and this adds it to the Controls collection and positions it appropriately.

Note that the Remove method isn’t particularly sophisticated since it does no repositioning of existing controls: it will just take the LinkLabel it is passed off the screen and leave a gap where it previously was.

The Adapter

To be able to use this as a UIExtensionSite we need an adapter class that inherits UIElementAdapter<LinkLabel> (since LinkLabel is the type that we are adding and removing from the UIExtensionSite). This is a very simple adapter that just forwards the calls to the underlying LinkLabelPanel. It gets a reference to this LinkLabelPanel passed in in its constructor:

    public class LinkLabelPanelUIAdapter : UIElementAdapter<LinkLabel>
        LinkLabelPanel panel;
        public LinkLabelPanelUIAdapter(LinkLabelPanel panel)
            this.panel = panel;
        protected override LinkLabel Add(LinkLabel uiElement)
            return uiElement;
        protected override void Remove(LinkLabel uiElement)

Using the LinkLabelPanel

We can now use the LinkLabelPanel in the same way as we did the ToolStrip in the example in part 13.

Firstly we add the user control to our Shell form, dock it to the left, and make its Modifiers property have value ‘Internal’.

We then register the UIExtensionSite in method AfterShellCreated. One slight difference here is that we need to tell the CAB which adapter it needs to use, and we do this by using a different overload of RegisterSite:

        protected override void AfterShellCreated()
            this.Shell.IsMdiContainer = true;
            RootWorkItem.Items.Add(this.Shell, "Shell");
            RootWorkItem.UIExtensionSites.RegisterSite("LinkLabelPanel", new LinkLabelPanelUIAdapter(this.Shell.linkLabelPanel1));

As mentioned above our adapter needs to have a reference to the LinkLabelPanel passed to it in its constructor.

Now we can add LinkLabels to our UIExtensionSite from our individual Red and Blue module projects. Again this is done in the same way as for the ToolStrip example in part 13. We create a new LinkLabel, retrieve the UIExtensionSite that represents the LinkLabelPanel from the UIExtensionSites collection, and use the Add method to add the LinkLabel to it. We set up the Click event of the LinkLabel using .NET events, again analogously to what we did with the Click event for our ToolStripButtons in part 13:

        private Form1 form;
        public override void Load()
            // Code as before
            Form shell = (Form)parentWorkItem.Items["Shell"];
            form = new Form1();
            form.MdiParent = shell;
            LinkLabel label = new LinkLabel();
            label.Text = "Show Red Screen";
            label.Click += new System.EventHandler(label_Click);
            UIExtensionSite uiExtensionSite = parentWorkItem.UIExtensionSites["LinkLabelPanel"];
        void label_Click(object sender, System.EventArgs e)

That’s it: if we repeat the code immediately above in both the Red and the Blue projects our example we will work as we desire.


UIExtensionSites allow us to access user interface elements in the shell of a Composite Application Block project in a generic way. The CAB provides us with code (an adapter) to let us use ToolStrips, MenuStrips and StatusStrips as UIExtensionSites. If we wish to use other user interface elements as UIExtensionSites we can quite simply write our own adapter class.

However, UIExtensionSites are quite limited in the functionality they provide, restricting us to just Add and Remove methods for elements of the UIExtensionSite. As a result we may need some more powerful mechanism to provide the rich user interface support we require.

Part 15 of this series of articles will discuss Workspaces and SmartParts.

October 13, 2007

Introduction to UIExtensionSites (Introduction to the CAB/SCSF Part 13)


Part 12 of this series of articles went into some detail on events in the Composite Application Block, and concluded our discussions of commands and events.

As we’ve already discussed in this series of articles, the Composite Application Block (CAB) is intended as a means of creating smart client applications that are composed of several independent ‘modules’. We’ve also seen that the CAB has a number of other features to make development easier in general, in particular a dependency injection framework.

However, when we think of a ‘smart client’ we usually think of a well-designed and powerful user interface. The CAB introduces a number of new classes to aid in the design and implementation of such user interfaces.

So far this series of articles has not really discussed user interfaces at all, and certainly hasn’t covered any of the user interface elements of the CAB. The next few articles will remedy this.


This article and the next will discuss one of the CAB user interface classes, the UIExtensionSite. A UIExtensionSite is a user interface element of the shell (the containing window) for a composite application. It might be a ToolStrip, a MenuStrip or a StatusBar, but could be any shared user interface element. The idea of the UIExtensionSite class is to allow each individual module to talk to these elements of the shell in a decoupled way.

In this article we’ll start with a basic example. In fact, we’re going to base the example on an earlier one, which will be recapped first.

Basic Example Starting Point – Recap of the BasicMDIApplication from Part 5

For this example we start with the code for the first example from part 5 of this series of articles, ‘BasicMDIApplication’. This contains three projects, none of which reference each other. However, each project contains one form, and when we run the application two of the forms appear as MDI children of the third. The two MDI children are coloured red and blue respectively.

This was done in a slightly contrived way (it’s not the way you’d do it in production code). In our Shell project in method AfterShellCreated we added the Shell form itself to our RootWorkItem’s Items collection:

        protected override void AfterShellCreated()
            this.Shell.IsMdiContainer = true;
            RootWorkItem.Items.Add(this.Shell, "Shell");

Then we accessed it from the same collection in each of the other projects. We did this in the Load method of theModuleInit class in each project. There we set the MdiParent property of the project’s form to be the Shell form:

        public override void Load()
            Form shell = (Form)parentWorkItem.Items["Shell"];
            Form1 form = new Form1();
            form.MdiParent = shell;

Note that here we had access to the parentWorkItem of the project (which is the same as the RootWorkItem). We got access to this through dependency injection.

The original code is available here.

Basic Example Extended

We’ll extend this so that the Shell form has a ToolStrip with two buttons. One of these will bring the red MDI child to the front, and one will bring the blue MDI child to the front. Remember that there are no direct references between any of the projects, so it isn’t immediately obvious how we do this.

Furthermore, each individual project will set up its own ToolStrip button. So the ToolStrip itself will be in the Shell project. The Red project will contain code to create the ‘Show Red Form’ button and add it to the ToolStrip. Similarly the Blue project will contain code to create the ‘ShowBlueForm’ button and add it to the ToolStrip.

Basic Example – Code in the Shell Project

To do this we first add the ToolStrip to the Shell form using the visual designer. We’ll call it ‘shellToolStrip’. To make life easy in this simple example we’ll give it a scope of ‘Internal’ (by changing the ‘Modifiers’ property).

Then we extend AfterShellCreated to register this ToolStrip as a UIExtensionSite:

        protected override void AfterShellCreated()
            this.Shell.IsMdiContainer = true;
            RootWorkItem.Items.Add(this.Shell, "Shell");
            RootWorkItem.UIExtensionSites.RegisterSite("ShellToolStrip", this.Shell.shellToolStrip);

The RegisterSite method has the effect of adding the object passed in its second parameter (the shellToolStrip) to the UIExtensionSites collection of the RootWorkItem. The UIExtensionSites collection is indexed by name, and RegisterSite gives the object the name passed in the first parameter (“ShellToolStrip”).

Basic Example – Code in the MDI Child Projects

As in the original example, we have access to the RootWorkItem in the individual projects containing the MDI child forms. So we can retrieve a UIExtensionSite object from the UIExtensionSites collection of that RootWorkItem. The UIExtensionSite object represents the ToolStrip. UIExtensionSite has an Add method we can use to add a ToolStripButton to the UIExtensionSite.

So in the ModuleInit classes (RedModuleInit and BlueModuleInit) of the appropriate MDI child projects we create such a button. We give it an appropriate event handler for its Click event. We’re using standard .NET events here:

        private Form1 form;
        public override void Load()
            // Code as before
            Form shell = (Form)parentWorkItem.Items["Shell"];
            form = new Form1();
            form.MdiParent = shell;

            // Create a new button, hook it up to an event handler, 
            // and add it to our ToolStrip by using the UIExtensionSite.
            ToolStripButton toolStripButton = new ToolStripButton("Show Red Screen");
            toolStripButton.Click += new System.EventHandler(toolStripButton_Click);
            UIExtensionSite uiExtensionSite = parentWorkItem.UIExtensionSites["ShellToolStrip"];

        void toolStripButton_Click(object sender, System.EventArgs e)

That’s all there is to this example. The only change to the above code for the Blue project is that the ToolStripButton is initialized to have Text “Show Blue Button” rather than “Show Red Button”.

Basic Example – Results

The code for this is available. If we run it we get a screen as below. Clicking “Show Blue Screen” brings the blue child form to the front, clicking “Show Red Screen” brings the red child form to the front.


As previously with this example, please note that this is not the way you would normally set up an MDI application in the CAB (although it might well be the way you would set up a ToolStrip). The example simplifies many aspects of the code in order to demonstrate the core concepts.


In this article we’ve created an application with three separate projects that don’t reference each other, but having a common ToolStrip in the Shell project with buttons contributed by the other projects.

In part 14 we will examine how this is working in more detail, show how we can use UIExtensionSites for other user interface elements, and discuss what value this is adding to the development process.

October 7, 2007

Table of Contents for ‘Introduction to CAB/SCSF’ Articles (2)

I’ve revised the table of contents to give some detail on what each of the articles is about:

Part 1 Modules and Shells

A guide to these two core concepts without the need to understand dependency injection or WorkItems. Explains what a composite application is and why we might want one, and shows a naive application that uses the CAB to run three separate projects simultaneously without them referencing each other. Also explains some of the mysteries of how CAB applications behave at start-up.

Part 2 WorkItems

A quick initial look at WorkItems, explaining their importance both as containers of code and as a hierarchy that allows us to control the scope of the code.

Part 3 Introduction to Dependency Injection

A discussion of dependency injection and why it’s useful in general, without reference to the Composite Application Block. A code example is given. The relationship to the strategy pattern is examined, as well as the various different types of dependency injection.

Part 4 An Aside on Inversion of Control, Dependency Inversion and Dependency Injection

A discussion of the concepts of inversion of control and dependency inversion, and how they relate to dependency injection. Again these concepts are discussed without direct reference to the Composite Application Block.

Part 5 Dependency Injection and the Composite Application Block

This article finally revisits the Composite Application Block, showing how we can use dependency injection to get hold of WorkItems in projects that are not conventionally referenced, and hence access the objects in their containers. It discusses the various ways of doing dependency injection in the CAB using the attributes ComponentDependency, ServiceDependency and CreateNew, and gives an example illustrating this. It further discusses the ObjectBuilder briefly, and explains how dependency injection works in the WorkItems hierarchy.

Part 6 Constructor Injection in the Composite Application Block

A brief article on how to use constructor injection with the CAB, and why we might not want to.

Part 7 Introduction to Services in the Composite Application Block

Discusses what services are in general, what they are in the Composite Application Block, and how the Services collection differs from the Items collection. Gives a basic example, and an example of splitting interface from implementation in a service.

Part 8 Creating and Using Services in the Composite Application Block

Dives into services in much more detail, including an in-depth examination of the various ways of creating and retrieving services.

Part 9 The Command Design Pattern

Another article looking at some theory without direct reference to the Composite Application Block: explains the command pattern, how it relates to .NET, and why its a good thing if you’re writing menus.

Part 10 Commands in the Composite Application Block

Shows how to use Commands in the Composite Application Block to hook up clicks on menus to their handlers. Explains why we might want to do it this way rather than with the more usual .NET approach using events. Looks at how to handle Status with Commands, the parameters passed to a CommandHandler, and discusses writing your own CommandAdapters to handle other invokers than menus. Gives a CommandAdapter example.

Part 11 Introduction to Events in the Composite Application Block

Recaps the usual events in .NET and explains why we might want something simpler. Gives a basic example of the Composite Application Block’s alternative approach.

Part 12 Events in the Composite Application Block

Goes into detail of what we can do with the Composite Application Block’s events: examines the handling of scope, how the EventTopics collection works, use of the ThreadOption enumeration to ensure that our event executes on the GUI thread, more flexible event handling with AddSubscription and RemoveSubscription, hooking up .NET events to CAB events with AddPublication, and how to disable CAB events.

Older Posts »

Blog at