Sunday, 27 December 2009

Prism Sample: Resources

An area of Prism development that often gets overlooked is the management of resources.  I mentioned in a previous blog that View reuse is unlikely, but that doesn't mean you should create unnecessary dependencies to a resource assembly.

Similar to modules, resource assemblies can have an accompanying interface assembly.  This is done by defining ComponentResourceKeys in your interface assembly and using them as resource keys in your resource dictionary and in your Views.

public static class Styles
    public static ComponentResourceKey LargeTextStyleKey
        get { return new ComponentResourceKey(typeof (Styles), "LargeTextStyle"); }

and in your Xaml...

<textblock text="My Sample TextBlock Style"
           Style="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type Interfaces:Styles}, ResourceId=LargeTextStyleKey}}" />

Taking this approach decouples your modules from the resource assembly.  The advantage to do this is not so much in the area of reuse, but more in the implementation of themes.  Any Views that require the use of a resource can simply refer to it by its ComponentResourceKey.

Additionally, I would only have the Shell load the external resources, since the View modules are now unaware of the external resource.  The only draw back in doing this is you will lose your Visual Designer when editing your Xaml, because the designer cannot resolve the resource to render it.

It is also worth setting up default styles based on control types, by using the control type as the resource key (e.g. {x:Type TextBlock}).  This does not require the use of ComponentResourceKeys.

The area of theming WPF applications is a common one and there are a number of resources on CodePlex which address this area.  One example is the Razre WPF Framework, or you can build your own ThemeManager.

I think this pretty much concludes the PrismSample articles.  This was meant as an introduction for developers starting out with Prism and to provide some guidelines in setting up a Prism solution.  I hope this was of some use.  I'm certain others will have differing opinions, and that's okay too.  I'm always on the hunt for new approaches and new ideas.

I think Prism has a real future in WPF development.  Once you get into it and see the benefits, it changes how you think about and view WPF development; afterwards it is difficult not to think and develop that way, which is a good thing.

As always, comments/feedback welcome...

Saturday, 26 December 2009

Prism Sample: Services

In addition to Views and ViewModels, your Prism application will likely have one or more Services.  Per the CAL documentation, a service is defined as:

A service is an object that provides functionality to other components in a loosely coupled way through an interface and is often a singleton.

This is a fitting definition, but doesn't indicate belongs in a service or when something should be service.  Services reside outside the View-ViewModel pattern and provide functionality to anything that needs it.  In practice a service should address an area of business logic and have an appropriate name which describes the functionality it contains, like CustomerService or DataService, etc.
Avoid making a service a dumping ground for functionality you don't know where to put.  I tend to view services as static libraries of functionality, generally consisting of methods (think WCF Service Contracts).  My personal preference is to avoid storing state or exposing properties in services.  I don't use services to control workflow.  Instead I would implement a Controller to govern the workflow, and have the Controller consume the service.
On one Prism project, we would have regular design meetings where we would discuss where a given piece of functionality should reside.  The governing rule that came about, was that the ViewModel is directly concerned with the View and servicing the View; code that belongs in the ViewModel is there because of some requirement dictated by the View.  If that wasn't the case, we were probably looking at a general piece of business logic which likely belonged in a service (or Controller, if one existed).
Following this line of thinking, we found more and more of our code moving to services, until we had a robust services layer, and a lean ViewModel which simply became a consumer of the services.  This approach prevented business logic getting lost or hidden in ViewModels.  It also supported our decision to separate out our services into their own assemblies, which I would highly recommend.

Sunday, 20 December 2009

Prism Sample: Modules

Central to Prism is the concept of modules and modular design, therefore it's worth spending some time defining exactly what a module is, what it contains and what it shouldn't contain.  Per the Prism documentation:

A module in the Composite Application Library is a logical unit in your application. Modules assist in implementing a modular design. These modules are defined in such a way that they can be discovered and loaded by the application at run time. Because modules are self-contained, they promote separation of concerns in your application. Modules can communicate with other modules and access services in a loosely coupled fashion. They reduce the friction of maintaining, adding, and removing system functionality. Modules also aid in testing and deployment.

Having worked on a number of Prism projects with a wide range of developers, each interpreting this from their own perspective and experience.

Two of the guiding principles behind this are:
Single Responsibility Principle
Separation of Concerns

While most can agree on these principles, views differ on the depth and extent to which they are applied.  On one end of the spectrum we have the theorist, whose motivation may be to strictly adhere to these (some times with religious fervor).  And on the other end we have the realist, who simply wants to build a working piece of software that meets the business requirements.

The theorist looks beyond the business requirement, while the realist may argue that strict allegiance to these principles is outside the scope of the requirements.  Somewhere, somehow these views are resolved, usually by an architect or team lead; and the result usually falls somewhere in the middle.

Personally, I fall in the middle, and maybe lean towards the realist.  I don't feel software development should be an academic exercise.  If someone entertains the idea of using a certain design pattern, I'm always interested in "what problem does this solve?" and "what does it buy me?"  Unacceptable answers are "because Fowler said so" or "because that's what the Prism team does".

Enough of this, let's talk about modules...

In an earlier post, I talked about creating an Advertising module for Blogger and said I would create the following modules:


Some developers would be tempted to bundle these up into two assemblies:

storing their Views, ViewModels and Services in a single assembly.

And I could be convinced of this.  It's certainly easier to maintain.  But I would argue that Views/ViewModels and Services are logically separate and warrant their own assemblies.  It's not inconceivable that another module or system could be a consumer of these services, without the need for Views or ViewModels.

So, why separate out Views from ViewModels?

I think it is somewhat idealistic to expect Views designed for Product A to be simply dropped into Product B (two different implementations).  In theory this is possible, but in practice I've never seen it happen.  Here we get into areas of look and feel and layouts.  While we can do a lot to make a view generic and use themes and skins to alter its appearance, at the end of the day there is always going to be something different or required which makes the view unusable.  So why bother?

I always assume my views are not going to be reusable; that they're part and parcel to a specific implementation.  My ViewModels, however, are completely reusable.  I would also argue that mocking up Views is far less time consuming than the creation of ViewModels.

Regardless of what I think, your design decisions are going to be driven by a number of factors.  I think its important to consider all views and options, and decide which is suitable.

Thursday, 17 December 2009

Prism Sample: Basic Concepts

As stated in my earlier post, this model solution attempts to illustrate how Prism and Unity are used, what is a module, what belongs in one and what doesn’t, the use of interfaces and design patterns.
One of the most basic aspects of code organisation is knowing “what goes where”.  This is especially true with Prism projects.  Given you will likely have a dozen or more projects in your solution, it’s pretty important to sort out early on where things belong.
I always try to minimise dependencies between my assemblies; and from time-to-time work-out what would be required to take a module and drop it into another application.  I’m always looking for ways to remove a dependency or decouple.  Even if I don’t have an immediate requirement to do that, as a general rule it’s a good idea.

Picking the right naming convention for your projects and namespaces is pretty important.  I would spend ample time on this before embarking on any serious coding.  Maybe start with a prototype solution and put in some basic modules, a shell, some services, and their accompanying interfaces.  Play around with it and massage it into something you're comfortable with.  I think there is a natural order and organisation for these various projects and components.

Microsoft's recommended namespace convention is:

for example, if I were creating an advertising module for Blogger, I would see something like...


Microsoft has an excellent guideline for create .Net components at:

Implementation vs Interface
It's important to understand the difference between implementation and interface as it applies to modular development.  An interface is simply a public contract that defines an exposed surface.  Whereas, implementation deals with the deploy or realisation of the interface.  Interfaces do not contain business logic,  simply a definition of what something will look like once it is implemented.
Prism and Unity makes heavy use of interfaces.  Interfaces are mapped to your implementation classes, either in code or in a configuration file.

The following tips may be obvious to some, but I felt it was worth mentioning:

Tip #1 - Do not create strong references to implementation assemblies.
The exception to this are assemblies which comprise your Model.

Tip #2 - Do not place anything in your implementation assemblies which forces other assemblies to create a strong reference.
An example of this are Event classes.  You may have a module which publishes events, presumably to be subscribed to by other modules.  Do not include the Event class in your module assembly, instead place it in your module's interface assembly.  This makes it available to other assemblies though the interface reference.  Another common example are enumerations.

Tip #3 - Do not register your implementation classes in the Module Initialize method.
Registering classes in the Initialize method implies a specific implementation, but not all implementations.  Instead map your classes in a Unity configuration file.

Tip #4 - Do not inject views into regions in the Module Initialize method.
I never understood why anyone would want to do this, as it pretty much ruins any chance of reusing the module.  Instead, delegate view orchestration to another module, layer or layout manager.

In fact, I can't think of good reason to put any code in the Module Initialize method.

These tips address some hidden or covert implementation that commonly occurs in Prism development.

Wednesday, 16 December 2009

Prism Sample: Introduction

I had a request to post some sample code illustrating the use of Model-View-ViewModel pattern, Controllers and DelegateCommands.  This lead to the creation of a sample Prism solution.  An interesting exercise, since it gave me a chance to incorporate many of what I consider to be Prism best practices.
I consider proper solution setup and organisation to be critical in working with Prism.  Mistakes made in this area often come back to haunt you.  There are many ways to organise your projects and code.  What is probably more important is pick a solution structure that everyone can agree with and stick with it.  A lack of agreement or ignorance of architecture can make team development a nightmare.

I intend to write a series of postings detailing out what I consider to be areas of interest, and why I've organised things as I did.
You can download the solution here (408kb).  You will require Visual Studio 2008 SP1.  I've stripped out all XML documentation and PDBs to keep the file size down.

Please let me know if you run into any problems loading and running this solution.

Thursday, 3 December 2009

Some Agile thoughts...

Is it me, or have others found Agile development projects to be chaotic?  I will not profess to be an expert in this area.  I've been a developer on about four Agile-based projects, ranging from a handful of developers to a team of 20.  And, on the larger projects, the more Agile is pushed the more chaos seems to result.

At worst it feels like a mad coding free-for-all, in an effort to meet development targets, while abandoning or ignoring coding conventions and best practices.  The idea being, "if we just get the cards done...the project will get done".

I don't know how many times I've coded up a piece of functionality, written tests, etc., only to find weeks later, that someone else on the team "refactored" it, rendering it unusable.  One step forward, two steps back.  I've only really experienced this on Agile projects.

Don't get me wrong, when I first encountered Agile I felt it had merit; and I still do.  But somewhere  between theory and execution the plot can get lost.

I've always consider myself to be self-managing.  You give me a spec and I will methodically design, develop, test and document it to a finished product.  Maybe that's a bit old-school, but it got the job done.

I would be interested in what others think about this.

Tuesday, 20 October 2009

Win 7 Anti-Virus

For those of you running Win 7, you may have found it frustrating finding a suitable anti-virus product.  From experience, major players promoting Win 7 compatibility have proven anything but.
A friend told me about Microsoft's new Security Essentials, which handles anti-virus, spyware and malware detection.  Best of all, it's free!  You can download it here:

Unlike other products, Security Essentials has a remarkably small footprint and has negligible impact on performance.  Highly recommended.

Friday, 16 October 2009

The Golden Age of UI Design

If you’ve been using computers as long as I have, you will be familiar with the evolution of Windows, from the humble 3.x on up to Win 7. A lot has changed over the years. As developers we have had to shift gears with each new incarnation. I’m probably dating myself if I mention Windows 3.1 and VB 3.0, but given the time, VB 3 practically ushered in RAD and allowed developers to create respectable UIs for the platform.

With regards to the Windows User Interface, I can still remember the release of Windows 95 and all the fervour it created. There were developers and IT pros complaining bitterly about the change, citing their preference for 3.1 and their dislike for the new battleship grey 95. Those of us who embraced 95 in all its greyness, found new UI controls in our toolbox, most notably the Windows Common Controls. Enthusiasts, like myself, poured over Microsoft’s Windows 95 User Interface Guidelines book, a tome containing pixel by pixel specifications for creating standard Windows applications.

If you were like me, this wasn’t enough. The next rung on the ladder was exploiting (some times questionable) Win API and GDI hacks, all in the attempt to enhance our application interfaces.

The advent of .Net put an end to much of this. Designing WinForm applications certainly got easier and custom UIs no longer required slimy hacks. But, we were still limited to XP styled desktop applications.

Concurrent with the advancements in Windows programming, the internet exploded and took centre stage. Graphic designers and illustrators sat side-by-side with application developers to create a new breed of user interface. User expectations were raised; not only did a UI have to be functional, but it had to be sexy as well. Flash and Shockwave designers and developers expanded this further, raising the bar even higher.

All of these advancements made WinForms look rather antiquated.

All this was about to change with the release of .Net 3.0 and the introduction of Windows Presentation Foundation (WPF). For those unfamiliar with WPF, WPF is a XAML-based framework for creating Vista-styled desktop applications. Think XHTML meets WinForms and you’re almost there.

Not only was WPF structurally different from its WinForms cousin, but included new resources and functionality WinForm developers only dreamed of. At last, desktop developers could create dynamic, sexy user interfaces that rivalled their contemporaries. The capabilities of WPF are so vast, that if you can dream it, you probably can build it.

Gone are the stringent interface guidelines dictated by Microsoft; in its place are new collaborations between graphic designers and artists and software developers to produce user-centric software. All-in-all, this change is rather liberating. Where its headed I don’t know; will it be different from the past? Guaranteed.

However, this is no Holy Grail. Designers and developers will still manage to produce repulsive, poorly designed software. But this is a chance we’re going to have to take.

Wednesday, 7 October 2009

Using OnValidate method in LINQ to SQL

If you are using LINQ to SQL you may have noticed the OnValidate partial method.

public partial class Person : INotifyPropertyChanging,
     partial void OnValidate(ChangeAction action);

This method gets automatically called when the class participates in the DataContext SubmitChanges.

When working with LINQ to SQL classes I prefer to keep my code generated classes separated from any modifications or customisations.  Normally, I will create a folder in my project called ExtendedClasses, there I can extend my business objects, giving them a <classname>.extended.cs file name.  This allows me to regenerate my business objects without fear of losing these customisations.

So, in my extended class file I will include...

partial void OnValidate(ChangeAction action)
    if (action == ChangeAction.Insert)
        //Do validation for inserts
    if (action==ChangeAction.Insert ||
        //Do basic validation for inserts and updates

I avoid including any business rules in this class level validation, and stick to data related validation, such as field lengths, data ranges and required fields all based on my data model.  Any validation errors get raised by throwing an exception.
Because the OnValidate method is private, you may want to include a public Validate method.

public void Validate()
    if (PersonId==Guid.Empty)

With the public Validate method I can validate my business object from the UI layer before passing it down to my services layer.

catch (Exception e)
    MessageBox.Show(e.Message + "\n\n" + e.StackTrace);

Tuesday, 15 September 2009

UK Post Code Search using LINQ to XML

I recently delved into working with UK Post Codes, including validation and searching.  This is not my first contact with this area, and in the past it has always involved large SQL tables or by using third-party products.

This time, I was looking for something a bit more portable, like XML.

I was able to find freeware downloads of UK Post Codes including their longitude and latitude, which was easily imported into a SQL Server database.

I've created a class library called PostCodes.UK, which contains useful methods for validating post codes and determining which post codes fall within a given radial distance from a target post code.  All of the search and validation routines utilise LINQ to XML to query the XDocument.

The class library relies on a PostCodes.xml file (supplied in the Test Harness project), which gets loaded as an XDocument.  I've included a small WPF Test Harness application which illustrates how this library is used.

To run this solution you will need Visual Studio 2008 SP1.  The source code is available here.

For those interested in this area, there is an informative government page on Postal Geography, which explains the structure of the UK post codes.  You should be aware that UK post codes are always changing; however, if all you need is outward code resolution (e.g. PO6 ), chances are you can make do with public domain data.

Another site with useful information is:

Thursday, 10 September 2009

Juan Enriquez Video

A friend recently sent me this link to a presentation made by Juan Enriquez on TED.

Enriquez has a unique viewpoint on recent global events, namely with the economy and technological advancements. And he has a sense of humour which appears to be a rare commodity nowadays.

Worth having a look.

Tuesday, 8 September 2009

IsIn Extension Method

Another useful extension method I've found is the IsIn() method. This is comes in handy when you have to test for enumeration values, for example:
public enum StatusValues


if(myObject.Status == StatusValues.Closed ||
   myObject.Status == StatusValues.Pending ||
   myObject.Status == StatusValues.Expired)

This can become cumbersome when testing for a number of values.

The IsIn Extension Method simplifies this by taking a param list of values.
public static bool IsIn<T>(this T thisObject, params T[] values)
    if (thisObject != null && values != null && values.Length > 0)
        foreach (var value in values)
            if (thisObject.Equals(value))
                return true;

    return false;
Using this method, the above code can be rewritten as follows:

//using the IsIn Extension Method

Monday, 31 August 2009

Retro Flip Clock WPF Control

I know, I know...I last thing we need is another WPF Clock.  However, I recently went looking for a Flip Clock control and found surprisingly few - in fact, no usable ones.  So, it was back to the drawing board.

Most of the attention has been on appearance, rather than functionality.  Feel free to modify and enhance.
You can download the source code with sample project here.

Sorry for the broken link, the server that hosted this file has been rebuilt and no longer contains my downloads.  Here is a link on my SkyDrive.  This zip file contains the core files, you will need to add them to a project.

Wednesday, 26 August 2009

Ethics and IT

I was recently offered employment at an investment bank in London, to which I respectfully declined.  The agent I was dealing with was somewhat surprised and wanted to know why.  I told him that I couldn't bring myself to work for the banksters.  He was amused and replied "should my moral compass change..." the offer still stood.  Interesting.

I never considered my moral compass to be so fluid, to actually consider assisting corporate criminals rape the general public. What? Bigger? Better? Faster? More Efficiently?  I suppose I could find a way to justify it, but I couldn't see myself telling someone that is what I did for a living.

I, like the next guy, seeks to be well rewarded for their work.  That doesn't automatically mean I do anything just because the rate is high.  I consider my services to be valuable and the products I produce hopefully forward the goals and aims of my client.  I mean, why do it at all if some good doesn't come out of it?

I was discussing this point with some friends; where do you draw the line?  I knew where my line was.  But it occurred to me that I shouldn't assume everyone has or is even aware of "The Line".  That there may be some people in the IT industry who will simply work on any project provided the price was right.

Would you design software which assisted a pharmaceutical company to develop new mind-altering drugs which may result in suicide or mayhem?

Or how about software which controls a guided missile that has an impressive kill-ratio?  (no, it's not the X-Box)

No? Well somebody does.

Now, these are not new questions.  While at engineering school we had a Technology and Ethics course, but it never delved into these types of issues (which may have had something to do with the Department of Defence contracts).  Maybe no course can answer these questions, maybe only you can come up with an answer you can live with.

So, in addition to the legalised drug pushers and the war-mongers we add a new villain (well, not new, just newly exposed) - the Banker, purveyors of economic chaos and destruction.  The respected banker, pillar of the community.  Lovely.

If your love of banking is so strong, why not work for the Financial Services Authority?  I hear they're quite busy and need all the help they can get.

Tuesday, 25 August 2009

Layout Manager for Prism v2

One of the issues you may encounter when working on a Prism project is the management of regions and views within your application. While the RegionManager does an adequate job of managing regions, the orchestration of views and regions is pretty much left up to the developer.

A common approach is to define string constants in a common infrastructure assembly and injecting views into regions using these constants. This gets the job done, but adds rigidity to your application. For applications which require multiple layouts, coordinating regions and views can be a bit tedious.

One common approach I would not recommend is injecting your views in your module's Initialize method.
public void Initialize()
    var view = new MyView();
This violates the encapsulation of the module, restricting the reuse of the module.

On one project, we opted to create a "layout module". The sole purpose of this module was to load a layout UserControl into the Shell region of the main application window, and injecting the views into its own defined regions. Definitely a step in the right direction by decoupling the module views from the regions. The layout module was defined and loaded like any other module, but had to be the last module loaded due to its dependencies. One drawback to this approach was the increasing number of dependencies. The layout module had to reference all the infrastructure assemblies of the views it was required to manage.

Still this solution felt a bit too purpose-built. And other issues quickly arose, such as multiple layout support.  Ideally we were looking for a complete decoupling of regions and views with the ability to dynamically load layouts as required.

We quite liked the idea of using layout views, views whose sole purpose was to define regions, and providing no business or UI logic. But, the source and introduction of these views needed to be dynamic and flexible. The LayoutManager is my first attempt at tackling this issue. Its purpose is to dynamically manage one or more layout configurations for a Prism application.

To compile and run the LayoutManager you will need Visual Studio 2008 SP1 and the latest version of the Composite Application Guidance for WPF and Silverlight - February 2009.

The solution is fairly standard Prism solution, consisting of an Infrastructure, Shell and Modules projects. For the sake of simplicity, I've only included a single Modules project, where normally there would be more.

The LayoutManager maintains a collection of Layout objects, which define layout controls, along with the views that will reside in the layout.

The LayoutManager is configured by a LayoutProvider specified in your app.config file.

<section name="layoutProvider" type="Composite.Layout.Configuration.LayoutProviderSection, Composite.Layout"/>

Currently, two providers are available: ConfigLayoutProvider and XamlLayoutProvider. Custom providers can be used by inheriting from LayoutProviderBase.

Defines the LayoutManager in the app.config file as shown below:
<layoutProvider name="ConfigLayoutProvider" type="Composite.Layout.Configuration.ConfigLayoutProvider, Composite.Layout">
    <layoutManager shellName="Shell" >
        <layout name="FirstLayout" 
              fullname="First Layout" 
              description="This is the default layout" 
            <view typeName="LayoutManager.Infrastructure.IViewA, LayoutManager.Infrastructure" regionName="Left"  />
            <view typeName="LayoutManager.Infrastructure.IViewB, LayoutManager.Infrastructure" regionName="Right" />
            <viewModel typeName="LayoutManager.Infrastructure.IMenuViewModel, LayoutManager.Infrastructure" regionName="Menu"  viewProperty="View"/>

Defines the LayoutManager in Xaml

<layoutProvider name="XamlLayoutProvider"
type="Composite.Layout.Configuration.XamlLayoutProvider, Composite.Layout"

The source of the Xaml can be specified by type or by filename.
<Layout:LayoutManager xmlns=""
        <Layout:Layout x:Name="FirstLayout"
                       Fullname="First Layout"
                       Description="This is the default layout"
                <Layout:ViewModel RegionName="Menu"
                                  Type="{x:Type Infrastructure:IMenuViewModel}"
                                  ViewProperty="View" />
                <Layout:View RegionName="Left"
                             Type="{x:Type Infrastructure:IViewA}" />
                <Layout:View RegionName="Right"
                             Type="{x:Type Infrastructure:IViewB}" />

Each Layout contains a Views collection. The views collection accommodates both Views and ViewModels. The View specifies what view control is to be loaded and what region it is to be placed in. You can also set the visibility for the view. Use the ViewProperty of the ViewModel to specify the name of the property on your ViewModel which holds the View.

The LayoutManager is loaded after all of the modules have initialized. In the Bootstrapper.cs:

protected override void InitializeModules()

private void InitializeLayoutManager()
     var layoutManager = LayoutConfigurationManager.LayoutManager;
     Container.RegisterInstance(layoutManager, new ContainerControlledLifetimeManager());
     //parameterless LoadLayout loads the default Layout into the Shell
The LayoutManager requires use of the Container. Once your layouts have been loaded, call the Initialize method passing in the container.

Once that is done, you can register the LayoutManager in the container making it accessible to other modules.

Loading a Layout
Layouts are loaded by calling the LoadLayout method of the LayoutManager.

LoadLayout() loads the default layout in the Shell

LoadLayout(string layoutName) loads the named layout in the Shell

The MenuViewModel.cs illustrates the use of LoadLayout:
private void LayoutCommandExecute(ILayout layout)
var layoutManager = _Container.Resolve<ILayoutManager>(); 

The basic sequence of loading a layout is:
  1. If there is a current layout, remove it from the RegionManager.
  2. Clear out any controls that were bound to any regions. This step is necessary otherwise you will get an InvalidOperationException ("This control is being associated with a region, but the control is already bound to something else") when you try to reload it in the future. Currently, the LayoutManager only supports ItemsControls, ContentControls and Panels using the RegionManager.RegionName attached property.
  3. Add the new Layout Control to the RegionManager.
  4. Register any Regions contained within the Layout Control.
  5. Load any views associated with the new layout.
There are several events raised by the LayoutManager:

  • LayoutManagerInitializedEvent raised at the end of Initialize (see MenuViewModel.cs for an example of subscribing to this event)
  • LayoutLoadingEvent raised at the beginning of LoadLayout
  • LayoutLoadedEvent raised at the end of LoadLayout
  • LayoutUnloadingEvent raised before the current layout is about to be unloaded
  • LayoutUnloadedEvent raised after the current layout has been unloaded
All of these events are published through the EventAggregator.

Currently there are several limitations with the LayoutManager, these are:
LayoutManager currently only supports UserControls as layout controls. There is also the basic assumption that your application main window has a single region defined, where layout controls are injected. Regions must be defined in XAML using the RegionManager.RegionName attached property.

Other Considerations
While the LayoutManager does decouple the regions from the views, it does not entirely do away with string-based region names. Dynamic manipulation of regions and views in code will still rely on region names (see the AddCommandExecute method in MenuViewModel.cs on how to programmatically add layouts). And region name attributes must match actual region names in the Layout control.

A possible approach to addressing this dependency may be to introduce a RegionType enumeration such as Top, Bottom, Left, Right, Center, StatusBar, Menu, Toolbar, etc. In which case, the LayoutManager could resolve these regions regardless of string names.

I have not tested the LayoutManager in all possible scenarios, such as nested layouts and custom RegionAdapters, or with Silverlight.

You can download the LayoutManager source code here.

Monday, 24 August 2009

StringBuilder Extensions

I recently had a requirement to modify some Html-based reports.  These reports were built up in code using a StringBuilder, along with report content data.  The plus-point is that it worked and delivered the desired reports.  On the downside, the code was tedious and verbose.  For example:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("<TABLE id=\"Table2\" width=\"100%\">");
stringBuilder.Append("<TR style=\"page-break-inside : avoid\"><TD class=\"reportHeaderTitle\" >" + ResourceManager.GetString("ReportTitle", culture) + "</TD></TR>");
stringBuilder.Append("<TR><TD style=\"PADDING-LEFT: 5px; PADDING-BOTTOM:10px\" width=\"100%\">");
stringBuilder.Append("<TABLE id=\"Table2\" width=\"100%\">");
stringBuilder.Append("<TR style=\"page-break-inside : avoid\"><TD class='reportHeader' align=\"center\" width=\"50%\">" + ResourceManager.GetString("ReportSubTitle", culture) + "</TD>");
stringBuilder.Append("<TD class='reportHeader' align=\"center\" width=\"50%\">" + ResourceManager.GetString("ReportResults", culture) + "</TD></TR>");

I was staring at 1000s of lines of code like this.  After a while it was all a blur.

My first impulse was to subclass the StringBuilder and build up some Html-specific methods.  Unfortunately, the StringBuilder class is sealed.   I also looked at the HtmlTextWriter class, a class primarily used when working with custom server controls.  But, this seemed overkill for the purpose.  I just needed a clean way to build-up an Html string in code.

I then turned to writing a set of Extensions Methods to provide this functionality.
#region Using Directives

using System.Text;


namespace Common.Extensions
    public static class StringBuilderExtensions
        public static void BeginTable(this StringBuilder stringBuilder)

        public static void EndTable(this StringBuilder stringBuilder)

        public static void BeginRow(this StringBuilder stringBuilder)

In refactoring the code I first pulled all of the inline styles out and into style classes.  Then I began migrating the existing code over to use the new extension methods.  The refactored code looks something like this:

var stringBuilder = new StringBuilder();
stringBuilder.Append(ResourceManager.GetString("ReportTitle", _Culture));

stringBuilder.Append(ResourceManager.GetString("ReportSubTitle", _Culture));
stringBuilder.Append(ResourceManager.GetString("ReportResults", _Culture));
In it's current state, the extensions only supply the Html tags that were required, but could easily be expanded to support all of the commonly used tags.  I personally find this refactored code much easier to read and maintain.

You can download the here.
I hope this may be of some use.

Extension Method Usage

If you are like me, once you have the Big Extension Method Realisation you tend to go overboard on their use.  This is eventually followed by the more practical Extension Method Usage Realisation.  This second realisation puts Extension Methods into perspective.

For example, you could quite easily create an extension method like this:
public static bool IsNull(this object thisObject)
return thisObject == null;
This method can replace



But is it worth it?  Is there anything wrong with myObject==null?  Of course not.  So why change it or replace it with an extension method.  It adds no new functionality, just a change of syntax.
Additionally, you will often collect your extension methods and place them in a common assembly.  Use of the above extension method creates an dependency on this assembly.  But what does it buy you?  I would argue, nothing.  So, lose it.
From my experience in working with extension methods, I've found the most valuable to be methods that supply missing functionality or ones that encapsulate often repeated code. 
An example of this is checking if a collection contains any items, kind of like a cousin of String.IsNullOrEmpty.  For me, this is a prime candidate for an extension method, and should have been included in the IList interface (IMHO).

public static bool HasItems(this IList collection)
return collection != null && collection.Count > 0;
So we reduce
if(myCollection!=null && myCollection.Count>0)

to a clean and simple


I know there is not a shortage of resources on the web regarding extension methods.  However, after working with them for a few years, I have managed to collect a few "must have" extension methods, which I will be posting over time.

CodeProject Articles

I have authored two CodeProject articles on WPF and Prism.

WPF Gadget Container Control

Layout Manager for Prism v2

If you are interested in this area of .Net, check them out and let me know what you think.


This is my second blogging attempt, the first failed due to blogger's guilt. Now I have a renewed sense of purpose and dedication and have allocated time to make this a respectable blog. Round Two...