subtext, open source comments edit

In my previous post, I outlined some minor changes to the skinning model for Subtext. In this post, I will give a high level overview of how skinning works in Subtext.

Subtext renders a Skin by combining a set of CSS stylesheets with a set of .ascx controls located in a specific skin folder.  If you look in the Skins directory for example, you might see a set of folders like this.

Subtext Skin

Skin Template

A common misperception is that each folder represents a Skin.  In fact, each folder represents something we call a Skin Template, and can be used to render multiple skins.  One way to think of it is that each folder contains a family of skins.

Each folder contains a series of .ascx controls used to render each skin in that skin family as well as some CSS stylesheets and images used for individual skins or for the entire family.

For example, the Redbook template folder contains three skins, Redbook, BlueBook, and GreenBook.  In the screenshot below, we can see that there are three CSS stylesheets that specifically correspond to these three skins.  How does Subtext know that these three stylsheets define three different skins while the other stylesheets in this folder do not?


The answer is that this is defined within the Skins.config file.


The Skins.config file is located in the Admin directory and contains an XML definition for every skin.  Here is a snippet of the file containing the definition for the Redbook family of skins. This snippet shows the definition of the BlueBook skin.

<?xml version="1.0"?>
<SkinTemplates  xmlns:xsd="" 
    <SkinTemplate Name="BlueBook" 
        <Script Src="~/Admin/Resources/Scripts/niceForms.js" />
        <Style href="~/skins/_System/csharp.css" />
        <Style href="~/skins/_System/commonstyle.css" />
        <Style href="~/skins/_System/commonlayout.css" />
        <Style href="niceforms-default.css" />
        <Style href="print.css" media="print" />

There is a SkinTemplate node for each Skin within the system (I know, not quite consistent now that I think of it. Should probably be named Skin). 

The Name attribute defines the name of this particular skin. 

The TemplateFolder attribute specifies the physical skin template folder in which the all the ascx controls and images are located in. 

The StyleSheet attribute specifies which stylesheet defines the primary CSS stylesheet for this skin. 

For example, the GreenBook skin definition looks just like the BlueBook skin definition except that the StyleSheet attribute references Green.css instead of Blue.css.

Within the SkinTemplate node is a collection of Script nodes and a collection of Style nodes.  These specify any client scripts (such as Javascript) and other CSS files that should be included when rendering this skin.  As you can see, the tilde (~) syntax works for specifying a path to a file and a developer can specify a media and a conditional for each CSS stylesheet.


I keep mentioning that Subtext depends on a collection of .ascx user controls when it renders a family of skins. Let’s talk about them for a moment. 

In the second screenshot above, you may have noticed a directory named Controls.  This contains the bulk of the .ascx controls used to render a specific skin.  There was also a control named PageTemplate.ascx in the parent directory.


Each skin in a family of skins is rendered by the same set of UserControl instances.  The only difference between two skins within the same family is the CSS stylesheet used (which can account for quite a difference as we learn from CSS Zen Garden).

The PageTemplate.ascx control defines the overall template for a skin, and then each of these user controls in the Controls directory is responsible for archiving a specific portion of the blog.

Select a different skin from another skin family, and Subtext will load in a completely different set of UserControl files, that all follow the same naming convention.

Drawbacks and Future Direction

This is one of the drawbacks to the current implementation.  For example, rather than using data binding syntax, each .ascx file is required to define certain WebControl instances with specific IDs.  The underlying Subtext code then performs a FindControl searching for these specific controls and sets their values in order to populate them.  This naming convention is often the most confusing part of implementing a new skin for developers.

It used to be that if a WebControl was removed from an .ascx file (perhaps you didn’t want to display a particular piece of information), this would cause an exception as Subtext could not find that control. We’ve tried to remedy that as much as possible.

In the future, we hope to implement a more flexible MasterPage based approach in which the underlying code provides a rich data source and each skin can bind to whichever data it wishes to display via data binding syntax.

From a software perspective, this changes the dependency arrow in the opposite direction.  Rather than the underlying code having to know exactly which controls a skin must provide, it will simply provide data and it is up to the individual skin to pick and choose which data it wishes to bind to.


We provided the Naked skin so that developers creating custom skins could play around with an absolutely bare-bone skin and see just how each of the controls participates in rendering a blog.

tags: Subtext, Skins, Skinning, Blogs

comments edit

This is my third post about Skinning in Subtext. Previously I talked about some breaking changes.  Then I gave a high level overview of skinning in Subtext.  In this post I want to mention one new feature for those who use custom skins.

Subtext 1.9 actually reduces the the number of pre-packaged skins that come with it out of the box.  That’s right, we got rid of the skins that screamed, “Hey! I was designed by a developer who wears plaid pants with flannel shirts!”.  Over time, we hope to add more polished designs.

Of course we don’t want to leave developers with custom developer designed skins out in a lurch.  Taking an informal poll I found that a majority of Subtext users deploy a custom skin typically based on one of the out-of-the-box skins. 

As I described in the overview, skins are configured via a file named Skins.config.  One problem with having all the skin definitions in this file is that any customizations a user might make are overwritten when upgrading to a new version of Subtext.

It is incumbent upon the user to merge new changes in.  We thought we could make this better so we have introduced the new Skins.User.config file.

The format for this file is exactly the same as the format for Skins.config.  The only difference is that we do not include such a file in the Subtext distribution.  Thus you can place your custom skin definitions in this file and it will not get overwritten when upgrading.

From now on, it is recommended that if you customize an existing skin, you should rename the folder and place your skin definition in Skins.User.config.

tags: Subtext, Skins, Skinning, Blogs

comments edit

Gratuitious nature pic for no good reason other than I love Windows
WriterJust sticking my head above water long enough to take a breath and to link to some rubbish called the Programmer’s Bill of Rights that Jeff Atwood declares on his blog.

I don’t understand this guy.  You let this sort of dangerous propaganda spread and software departments will become much more efficient and be able to build better systems with less money. 

You realize what that means, don’t you?  Companies will be able to get more done with less people

For those who lose their jobs because of this, blame Atwood.  Then again, if you’re reading his blog, you’re probably not the target audience that would get laid off due to increased efficiency.  Readers of my blog on the other hand …

comments edit

This post is an ode to one of my favorite, albeit extremely minor, additions to .NET 2.0.  This is the method that I am sure we have all written in some sort of StringHelper library of some sort, but are now glad it is included in the framework as it makes our code a tad bit cleaner and shuts up that pesky FxCop warning about using the length of the string to test for empty strings.

And under the hood, it does the right thing.

public static bool IsNullOrEmpty(string value)
      if (value != null)
            return (value.Length == 0);
      return true;

If you haven’t met this method, do get well acquainted.

comments edit

Tonight we had our first game of the new season against Hollywood United who now feature Alexi Lalas and Frank Le Boeuf, among several other former pro and national team players.  Let’s just say the result wasn’t pretty.  At least not pretty for us as they dismantled us 12 to 0.

As bad a beating as it was, it was exciting to be playing against such a high caliber team.  And we managed to put together some good plays, but pretty much looked erratic and rushed with the ball.

I asked one of my teammate’s wife to take some photos, but being a night game, none of them turned out too well.  Here is the best I got showing both these players.

Frank and Alexi on the

I had one good play in which I dummied the ball, faking Alexi and taking him out of the play as he was hot on my back (I know, I’m reaching here).  Of course later in the game, he embarrassed me with a nutmeg.

After the game we were chatting with a player from their team who is going to be in a new TV show called Heros.  He told us his superpower in the show was that if he touches you he paralyzes you.  Now we know what happened on the field.

Next game we hope to hold them to single digits.  We’re in need of a keeper if you know any former standout keepers.

comments edit

Stephen Colbert of Comedy Central’s The Colbert Report is in my opinion the funniest comedian on television right now. As Mugatu (played by Will Ferrell, the funniest comedian in movies) would say, “It’s that damn Stephen Colbert! He’s so hot right now! Stephen Colbert.”

This clip had me rolling on the floor laughing for its spot on parody of Dungeons and Dragons. It is probably funnier to those of us who geeked out with D&D back in the day than for the unitiated.

After watching it, one gets the sense that he really was a player. It turns out he is a true fan, based on this Gamespy report.

comments edit

Interesting post on the 37Signals blog regarding competing against Google.  Harb references a post by Paul Graham about Kiko’s founders putting their site up on eBay. 

Long story short, it sounds like Kiko came out with a web-based calendar, but when Google came out with theirs, Kiko’s growth stopped, users defected, and they threw in the towel.

Paul’s solution is to stay out of Google’s way.

Kind of sounds like what could happen to Blogjet with the advent of Windows Live Writer.  However Harb offers a more optimistic take on the events.

No. Don’t run, don’t hide. Be different. You can’t outdo Google by trying to match them point-by-point, but you don’t have to. There are other, better ways to fight. Compete differently.

Perhaps the same can be said for the creator of BlogJet vs Microsoft.  I was chatting with Jon Galloway about this and I suggested this would really hurt BlogJet, perhaps even spell its demise in the long run.  How does a tiny company challenge Microsoft and compete against a free product?  Jon was more optimistic and pointed to SourceGear as a counterexample.

I was not convinced.  Writing software to post to a blog has a much lower bar of entry compared to a source control system.  But so does writing a Calendar app, no?

It will be interesting to see if Dmitry can competes differently and come out with some creative means to keep Blogjet viable.  Good luck.

comments edit

Work on Subtext 1.9 is progressing well with more and more contributors chipping in. No firm release date yet, but hopefully soon.  The latest builds are pretty stable, but there a few more minor bug fixes to get in there. Also we plan to implement the MetaWeblog API newMediaObject method in order to better support Windows Live Writer.

If you like to live dangerously, you can download one of the latest builds and give it a twirl.  Please note that link is running off of a VMWare Server within a Shuttle box in my office/guest room. So if we have guests, that link is going down for the night.

Of course, should you find a bug, you know the drill.

In the meanwhile, you can track our status by checking out our CruiseControl.NET statistics page.  As you can see, our code coverage from unit tests is steadily climbing, currently at 34%.  There are 23584 lines of code with 1367 FxCop warnings.

comments edit

That is a fine question in need of a good answer.  The answer for implementors is easily found in the spec.  For the rest of us there is the exceedingly sparse entry (at the time of this writing) in Wikipedia.

That entry is somewhat pathetic at the moment. I mean who wrote that crap?! Hmmm.. Well taking a look at the history… I see that the perpetrator was…oh! me.

Well I am sure one of you can do a much better job than I did of elaborating on the topic.

comments edit

Since my blog has been getting a bit geek heavy for my wife’s taste (see comment


The above pic was taken by my brother-in-law when the in-laws visited this past spring.

Lazy Sea

On that same trip, we took a boat ride in Oceanside and took a pic of these orgyastic sea lions. In public no less! Shameful.

comments edit

ChoirIn Jeff Atwood’s latest post entitled Source Control: Anything But SourceSafe he is preaching the gospel message to choose something other than Visual Source Safe and I am screaming amen in the choir section.

There are three common reasons I hear for sticking with Visual Source Crap (I sometimes swap that last word with one that doesn’t break the acronym).

1. It is free!

UPDATE: As a lot of people pointed out, VSS isn’t free. What I meant was that it comes with the MSDN Universal Subscription, so many companies already have a copy of VSS.

So is Subversion.  I was on a project recently in which VSS corrupted the code twice!  The time spent administering to it and time lost was a lot more costly than a license to SourceGear Vault.

2. We know how to use it and don’t want to learn a new system.

When I hear this, what I am really hearing is we like our bad habits and don’t want to spend the time to learn good habits.  Besides, Eric Sink already wrote a wonderful tutorial.

3. We have so much invested in VSS.

Well you had a lot invested in classic ASP (or other such technology) and that didn’t stop you from switching over to ASP.NET (Ruby on Rails, Java, etc…), did it?

The reason I spend time and energy trying to convince clients to switch is that it saves them money and saves me headaches.  It really is worth the effort.

For Open Source projects (or any project that receives user code contributions), Subversion and CVS have the nice benefit of a patching feature making it easy to contribute without having write access.

tags: Source Control

comments edit

Book Oh boy are you in for a roller coaster ride now!

Let me start with a question, How do you iterate through a large collection of data without loading the entire collection into memory?

The following scenario probably sounds quite familiar to you. You have a lot of data to present to the user. Rather than slapping all of the data onto a page, you display one page of data at a time.

One technique for this approach is to define an interface for paged collections like so…

/// <summary>
/// Base interface for paged collections.
/// </summary>
public interface IPagedCollection
    /// <summary>
    /// The Total number of items being paged through.
    /// </summary>
    int MaxItems

/// <summary>
/// Base interface for generic paged collections.
/// </summary>
public interface IPagedCollection<T> 
    : IList<T>, IPagedCollection

The concrete implementation of a generic paged collection is really really simple.

/// <summary>
/// Concrete generic base class for paged collections.
/// </summary>
/// <typeparam name="T"></typeparam>
public class PagedCollection<T> : List<T>, IPagedCollection<T>
    private int maxItems;

    /// <summary>
    /// Returns the max number of items to display on a page.
    /// </summary>
    public int MaxItems
        get { return this.maxItems; }
        set { this.maxItems = value; }

A method that returns such a collection will typically have a signature like so:

public IPagedCollection<DateTime> GetDates(int pageIndex
    , int pageSize)
    //Some code to pull the data from database 
    //for this page index and size.
    return new PagedCollection<DateTime>();

A PagedCollection represents one page of data from the data source (typically a database). As you can see from the above method, the consumer of the PagedCollection handles tracking the current page to display. This logic is not encapsulated by the PagedCollection at all. This makes a lot of sense in a web application since you will only show one page at a time.

But there are times when you might wish to iterate over every page as in a streaming situation.

For example, suppose you need to perform some batch transformation of a large number of objects stored in the database, such as serializing every object into a file.

Rather than pulling every object into memory and then iterating over the huge collection ending up with a really big call to Flush() at the end (or calling flush after each iteration, ending up in too much flushing), a better approach might be to page through the objects calling the Flush() method after each page of objects.

The CollectionBook class is useful just for that purpose. It is a class that makes use of iterators to iterate over every page in a set of data without having to load every record into memory.

You instantiate the CollectionBook with a PagedCollectionSource delegate. This delegate is used to populate the individual pages of the data we are iterating over.

public delegate IPagedCollection<T> 
    PagedCollectionSource<T>(int pageIndex, int pageSize);

When iterating over the pages of a CollectionBook instance, each iteration will call the delegate to retrieve the next page (an instance of IPagedCollection<T>) of data. This uses the new **iterators feature of C# 2.0.

Here is the code for the enumerator.

///Iterates through each page one at a time, calling the 
/// PagedCollectionSource delegate to retrieve the next page.
public IEnumerator<IPagedCollection<T>> GetEnumerator()
  if (this.pageSize <= 0)
    throw new InvalidOperationException
      ("Cannot iterate a page of size zero or less");

  int pageIndex = 0;
  int pageCount = 0;

  if (pageCount == 0)
    IPagedCollection<T> page 
      = pageSource(pageIndex, this.pageSize);
    pageCount = (int)Math.Ceiling((double)page.MaxItems / 
    yield return page;

  //We've already yielded page 0, so start at 1
  while (++pageIndex < pageCount)
    yield return pageSource(pageIndex, this.pageSize);

The following is an example of instantiating a CollectionBook using an anonymous delegate.

CollectionBook<string> book = new CollectionBook<string>(
    delegate(int pageIndex, int pageSize)
        return pages[pageIndex];
    }, 3);

I wrote some source code and a unit test you can download that demonstrates this technique. I am including a C# project library that contains these classes and one unit test. To get the unit test to work, simply reference your unit testing assembly of choice and uncomment a few lines.

Technorati Tags: Tips, TDD, C#, Generics, Iterators

comments edit

There is a lot of buzz around Windows Live Writer.  I Might as well throw my two cents into the fray.  Keep in mind that I do understand this is a beta.

The Good

  • It uses the paragraph tag <p> around your paragraphs rather than <br /> tags.
  • Keyboard shortcuts for switching views.
  • Integrates your blog’s style when previewing.  This is an impressive feature.  When I preview the post I am working on, it displays the post as if it was posted on my site.  I have seen a temporary blog post with the message This is a temporary post that was not deleted. Please delete this manually. (c3eaf4ab-0941-4881-9d17-d4f62bde069e)  in a few blogs related to obtaining a blog’s style. My guess is that Windows Live Writer posts to the blog, then deletes the post.  It takes a diff to figure out what changed.  That’s just my guess.
  • When adding a link, it has a field for the rel tag.  Nice!
  • It handles my unusual FTP setup using an FTP virtual directory. Not every tool deals with that correctly.
  • Inserting images allows you to apply a few simple effects. Very neat!
  • Support for Really Simple Discovery (RSD).  I just added RSD to Subtext.
  • Plugins!

The Needs Improvement

Since this is a beta, I didn’t feel right calling it “The Bad”.

  • Doesn’t let you specify the title attribute of a tag.
  • Inserts   all over the place as you edit text.
  • What key do I hit to Find Next?
  • No Find and Replace? Really?
  • Be nice to have HTML highlighting in the HTML View.
  • If I markup a word with the <code> tag, then cut and paste that word elsewhere in the Normal view, it marks up the pasted word with the font tag rather than using the underlying tag.

The Wish

  • Using typographic characters for singe quotes and double quotes ala MS Word.
  • Integration with CSS styles from the blog. Be nice to have a pulldown for various CSS classes.
  • Configurable shortcuts. I use the <acronym /> and <code /> tag all the time and have shortcuts for these configured in w.bloggar.

All in all, I really like it so far.  It has a nice look and feel to it and if they iron out a lot of these kinks, this may be the one to beat.

Unfortunately, this may cause some delays in Subtext 1.9 unless I can fight off the vicious urge to write some Microformat plugins. Why must these people introduce such interesting toys into my life! Where will I find the time? ;)

Speaking of which, Tim Heuer already has written a couple of plugins

[Download Windows Live Writer]

comments edit

Subtext Logo No, this is not a case of breaking and entering. With preparations for the next release of Subtext, apparently our SourceForge ranking has climbed up into the top 15. Now keep in mind this is a ranking of the most active projects, and is not a ranking of the success or value of a project. It is an amalgamation of source control checkins, discussion forum activity, and other statistical factors.

Even so, it is satisfying to see our project listed as #13 in the most active projects last week. It is an indication that more and more people are getting involved and having fun building this puppy.

I hadn’t even noticed until several people pointed it out.

I imagine that number will dip after we release when we all take a collective sigh of relief.

comments edit

Or did I?

JackAce, a former coworker of mine and total poker addict, happened upon this fine piece of artwork and astutely snapped this picture for posterity with his T-Mobile (click through to go to the original flickr pic).

Picture of my last name graffiti'd on a park

Soon the entire city of Angels will know the name of Haack!!! BWAHAHA!

Unfortunately the idiot taggers didn’t follow my instructions. I told them to tag my URL, not my name.


Good taggers are hard to find. You might promote your blog by writing good content, posting comments in other blogs, and other such nonsense, and hey that’s cool for you. But this is how we roll in L.A.


comments edit

Here are a couple of useful methods for getting information about the caller of a method. The first returns the calling method of the current method. The second returns the type of the caller. Both of these methods require declaring the System.Diagnostics namespace.

private static MethodBase GetCallingMethod()
  return new StackFrame(2, false).GetMethod();

private static Type GetCallingType()
  return new StackFrame(2, false).GetMethod().DeclaringType;

Pop Quiz! Why didn’t I apply the principle of code re-use and implement the second method like so?

public static Type GetCallingType()
    return GetCallingMethod().DeclaringType;

A virtual cigar and the admiration of your peers to the first person to answer correctly.

comments edit

A while ago Ian Griffiths wrote about an improvement to his TimedLock class in which he changed it from a class to a struct. This change resulted in a value type that implements IDisposable. I had a nagging question in the back of my mind at the time that I quickly forgot about. The question is wouldn’t instances of that type get boxed when calling Dispose?

So why would I wonder that? Well let’s take a look at some code and go spelunking in IL. The following humble struct is the star of this investigation.

struct MyStruct : IDisposable
    public void Dispose()

Let’s write an application that will instantiate this struct and call its Dispose method via the interface.

public class App
    public void DemoDisposable()
        IDisposable disposable = new MyStruct();
    public void DisoseIt(IDisposable disposable)

Finally we will take our trusty Reflector out and examine the IL (I will leave out the method header).

.maxstack 2
.locals init (
    [0] [mscorlib]System.IDisposable disposable1,
    [1] NeverLockThis.MyStruct struct1)
L_0000: ldloca.s struct1
L_0002: initobj NeverLockThis.MyStruct
L_0008: ldloc.1 
L_0009: box NeverLockThis.MyStruct
L_000e: stloc.0 
L_000f: ldarg.0 
L_0010: ldloc.0 
L_0011: call instance void 
L_0016: ret 

Notice the bolded line has a boxing instruction. As we can see, our struct gets boxed before the Dispose method is called.

The using statement requires that the object provided to it implements IDisposable. Here is a snippet from the MSDN2 docs on the subject.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources.

I wondered if the using statement enforced the IDisposable constraint in the same way a method would. Let’s find out. We will add the following new method to the App class.

public void UseMyStruct()
    MyStruct structure = new MyStruct();
    using (structure)

This code now implicitely calls the Dispose method via the using block. Cracking it open with Reflector reveals…

.maxstack 1
.locals init (
    [0] NeverLockThis.MyStruct struct1,
    [1] NeverLockThis.MyStruct struct2)
L_0000: ldloca.s struct1
L_0002: initobj NeverLockThis.MyStruct
L_0008: ldloc.0 
L_0009: stloc.1 
L_000a: ldloca.s struct1
L_000c: constrained NeverLockThis.MyStruct
L_0012: callvirt instance string object::ToString()
L_0017: call void [mscorlib]System.Console::WriteLine(string)
L_001c: leave.s L_002c
L_001e: ldloca.s struct2
L_0020: constrained NeverLockThis.MyStruct
L_0026: callvirt instance void 
L_002b: endfinally 
L_002c: ret 
.try L_000a to L_001e finally handler L_001e to L_002c

As you can see, there is no sign of a box statement anywhere to be seen. Forgive me for ever doubting you .NET team. As expected, it does the right thing. I just had to be sure. But do realize that if you pass in a value type that implements IDisposable to a method that takes in IDisposable, a box instruction will occur.

comments edit

Today I was thinking about how much I enjoy doing business with a particular company and realized my natural inclination was not to blog about it. Yet when a company really drops the ball, I have no problem airing my criticisms. I don’t know about you, but I don’t like to be around people who are only critical and never offer praise. It gets to be tiresome.

So today I would like to give a shout out to Paychex (I am not in any way affiliated with them other than being a customer). We signed up with them to handle our payroll and everything has been extremely smooth. We had a few problems (not related to them) when we initially started and they went way above and beyond to help us straighten our books related to payroll.

Not only that, the payroll specialist who handles our account is extremely courteous and helpful on the phone. Just an all around cool guy. It is very telling when you are looking forward to calling in payroll because you like talking to the rep. Paychex just seems to understand customer service and gets it right.

So tell me, who deserves your shout out today?, code, mvc comments edit

UPDATE: For a more full featured implementation of this pattern for ASP.NET Web Forms, check out the WebForms MVP project! It’s available as a NuGet package! Install-Package WebFormsMVP

Martin Fowler recently split the Model-View-Presenter pattern into two new patterns, Supervising Controller and Passive View. They are pretty much two different flavors of the MVP pattern differentiated by how much application logic is placed within the view.

The goal of this post is to demonstrate an end-to-end walk-through of the process of implementing the Supervising Controller pattern starting with a rough schematic. My goal is not explain the Supervising Controller pattern in detail but to help others take it out of the sounds nice in theory bucket and move it into I can and will use this in a real project, I promise bucket. There are many ways to implement the pattern for any given scenario, so keep in mind that this is not the one true way, just one way.

The Schematic

For this fictional scenario, I might as well pick an interface that I am familiar with, a blogging engine. In particular I will create a very very simple page to edit the body of a blog post and add and remove tags associated with the post. In trying to keep the example simple, I leave out all minor and extraneous details such as a title for the blog post. How important is a title, really?

Tag UI Schematic

The chicken scrawl above is a hand-drawn quick and dirty schematic for the user interface. No surprises here. There is a text area for entering the body of the blog post. There is a list of existing tags for the current post on the right. At the bottom of the list of tags is a text box. In order to add a new tag, the user can simply type in the name of the tag and click the add button. This will add a new tag to the list and associate it to the blog post. Note that when adding tags, any changes to the blog post should not be lost. The user can also remove tags by clicking the [x] next to the tag name.

When the user is finally ready to save the blog entry, the user clicks the Save button.

Defining the View

The next step is to analyze the schematic and define a view interface that can appropriately represent this interface. For the sake of this discussion, I will implement a single view that will represent this entire page. An alternative approach would be to break the page into two user controls and implement each user control independently with its own view and presenter.

Examining the schematic reveals what properties we need to populate the view interface. Obviously the view should have a getter and setter for the body text. Probably good to have a property that returns a collection of tags as well. We will want a getter and setter for the tag textbox, and a an event each for the buttons.

The entire process of defining a view interface may take multiple iterations. I am going to skip that long process (mainly because I cannot bear to type that much) and show you what I ended up with. Before I created the specific view interface, I defined a more generic base interface, IView. This is the base interface I will use for all my ASP.NET views.

public interface IView
    event EventHandler Init;

    event EventHandler Load;

    bool IsPostBack { get; }

    void DataBind();

    bool IsValid { get;}

One thing to notice is this interface defines two events, Init and Load. Most implementations of MVP that I’ve seen place an Initialize method on the Presenter/Controller class that every concrete view implementation must remember to call at the right time.

But when you have an ASP.NET Control or Page implement this interface, you don’t have to remember to have every concrete view call anything and you don’t have to implement these interfaces. It is already done for you by the ASP.NET runtime. You get the initialization call for free. Less code is better code I always say.

One common complaint with such an approach is that events on an interface are hard to test. I thought the same until I discovered Rhino Mocks. Now testing events is quite easy.

Here is the final view interface for the blog post edit page.

public interface IPostEditView : IView
    string BlogPostBody { get;set;}

    ICollection<Tag> Tags { get; set; }

    string NewTag { get; set;}

    int BlogPostId {get;}

    event EventHandler PostSaved;

    event EventHandler TagCreated;

    event EventHandler<TagRemovedEventArgs> TagRemoved;

Again, no surprises. One thing to note is the BlogPostId property. In this scenario, it is the view that is responsible for figuring out which blog post to edit. This makes sense in a lot of scenarios as the id may be coming in from a query string or via some other means. However, in other scenarios, you might want the controller to be responsible for figuring out which post to edit.

Writing a Unit Test

Now our next major task is to implement the presenter. But before we do that, we should start off with a basic unit test. The first thing I want to test is that the presenter properly attaches to the events on the view. The following is the test I wrote. Notice that there is some code in the SetUp method that I am not presenting here. You can see that code later.

public void VerifyAttachesToViewEvents()
    viewMock.Load += null;
    viewMock.PostSaved += null;
    new PostEditController(viewMock, 

Defining the presenter {.clear}

With the test in place, I can move forward and start implementing the controller. In practice, I only implement enough to get my test to pass, at which point I write another test and the cycle continues. In order not to bore you, I will skip ahead and show you the entire Controller implementation.

public class PostEditController
    BlogPost blogPost;
    IPostEditView view;
    IBlogDataService dataService;
    //Attaches this presenter to the view’s events.
    public PostEditController(IPostEditView view, 
      IBlogDataService dataService)
        this.view = view;
        this.dataService = dataService;
    void SubscribeViewToEvents()
        view.Load += OnViewLoad;
        view.PostSaved += OnPostSaved;
        view.TagCreated += OnTagCreated;
        view.TagRemoved += OnTagRemoved;

    void OnTagRemoved(object sender, TagRemovedEventArgs e)
        this.blogPost = this.dataService.GetById(view.BlogPostId);
        view.Tags = blogPost.Tags;

    void OnPostSaved(object sender, EventArgs e)

    void OnTagCreated(object sender, EventArgs e)

    void OnViewLoad(object sender, EventArgs e)
        if (!view.IsPostBack)
    public Tag GetTagById(int id)
        //Normally we’d probably just have a method 
        //of the service just return this.
        foreach (Tag tag in this.blogPost.Tags)
            if(tag.Id == id)
                return tag;
        return null;

    void LoadViewFromModel()
        this.blogPost = this.dataService.GetById(view.BlogPostId);
        view.Tags = blogPost.Tags;
        view.BlogPostBody = blogPost.Description;
    void Save()
        this.dataService.Save(view.BlogPostId, view.BlogPostBody);
    void CreateAndAddTag()
        //Need to rebind the tags. retrieve tags from db.
        this.blogPost = this.dataService.GetById(view.BlogPostId);
        view.Tags = blogPost.Tags;
        view.NewTag = string.Empty;

Implementing the View {.clear}

I have yet to implement the ASP.NET page that will implement the view, yet I am able to write a bunch of unit tests (which I will provide) against the presenter to make sure it behaves appropriately. This is the benefit of this pattern in that much more of the UI logic is now testable.

Implementing the ASP.NET page is pretty straight forward. I drop a few controls on a page, wire up the controls declaratively to their data sources, and then implement the IPostEditView interface. As much as possible, I want to leverage ASP.NET declarative data binding. The point isn’t to force developers to write more code. Here is the code behind for the page. I apologize for the code heaviness of this article.

public partial class _Default : System.Web.UI.Page, IPostEditView
    PostEditController controller;
    ICollection<Tag> tags;
    public _Default()
         this.controller = 
             new PostEditController(this, new BlogDataService());
    protected void Page_Load(object sender, EventArgs e)
    public void Update()

    public int BlogPostId
        get { return GetBlogId(); }
    private int GetBlogId()
        string idText = Request.QueryString["id"];
        int result;
        if(int.TryParse(idText, out result))
            return result;
        return 1;

    public string BlogPostBody
        get { return this.txtDescription.Text; }
        set { this.txtDescription.Text = value; }

    public ICollection<Tag> Tags
        get { return this.tags; }
        set { this.tags = value; }

    public string NewTag
        get { return this.txtNewTag.Text; }
        set { this.txtNewTag.Text = value; }
    protected void OnSaveClick(object sender, EventArgs e)
        EventHandler postSaved = this.PostSaved;
        if (postSaved != null)
            postSaved(this, EventArgs.Empty);
    protected void OnAddTagClick(object sender, EventArgs e)
        EventHandler tagCreated = this.TagCreated;
        if (tagCreated != null)
            tagCreated(this, EventArgs.Empty);

    void OnTagDeleteClick(object source, 
                          RepeaterCommandEventArgs e)
        EventHandler<TagRemovedEventArgs> tagRemoved 
        = this.TagRemoved;
        if(tagRemoved != null)
            string tagTitle 
          = ((Literal)e.Item.FindControl("ltlTag")).Text;
            tagRemoved(this, new TagRemovedEventArgs(tagTitle));

    public event EventHandler TagCreated;

    public event EventHandler PostSaved;

    public event EventHandler<TagRemovedEventArgs> TagRemoved;
    protected override void OnInit(EventArgs args)
        this.btnSave.Click += OnSaveClick;
        this.btnNewTag.Click += OnAddTagClick;
        this.rptTags.ItemCommand += OnTagDeleteClick;

When I finally compile all this and run it, here is the view I see in the browser.

Blog Post Editor Page

The benefits of this exercise become clear when you find bugs in the UI logic. Even while going through this exercise, I would find minor little bugs that I could expose by writing a failing unit test. I would then fix the bug which would cause the test to pass. That is a great way to work!

As an exercise for the reader, I left in a bug. When you leave the tag textbox blank, but click the Add button, it adds a blank tag. We should just ignore a blank tag. Try writing a unit test that fails because it assumes that a tag will not be added when the NewTag field is left blank. Then make the test pass by fixing the code in the Controller class. Finally, verify that by fixing the unit test, that the actual UI works by trying it out in the browser.

I apologize for glossing over so many details, but I did not want to turn this post into a book. If you want to read more on MVP, check out Bill McCafferty’s detailed treatment at the CodeProject. Also worth checking out is Jeremy D. Miller’s post on Model View Presenter.

Finally, to really understand what I am trying to present here, I encourage you to download the source code and try it out. I have included extensive comments and unit tests. This requires the free Web Application Project Model from Microsoft to compile and run.

The code doesn’t require a database connection, instead simulating a database via some static members. Please understand, that code is just a simulation and is not meant to be emulated in production code.

comments edit

I knew this question would come up, so I figure I would address it in its own blog post. Mike asks a great question about my MVP implementation (actually he asks two).

One observation…don’t you seem to be tying the presenter to the ASP.NET event model? If not, can you use the same presenter for a WinForms app?

The answer is that I am absolutely tying my presenter to ASP.NET.


Well when I first working on the article, I planned on creating an abstracted IView and presenter that would work for both ASP.NET and Windows Forms, but ran into a few problems. The biggest problem is that I rarely have to write a Windows Forms applications. In fact, I almost never do. So why spend all this time on something I won’t need? I had to call YAGNI on my efforts.

Premature Generalization

Besides, I didn’t want to run afoul of Eric Gunnerson’s #1 deadly sin of programming, premature generalization. There is no point in writing an IView and Presenter to work with both winforms and ASP.NET unless I am also implementing concrete instances of both at the same time. Otherwise I will write it for one platform and hope it will work for the other. If I ever do implement it for the other, I will probably have to rewrite it anyways.

Parity is a rarity

Secondly, even if I did need it, there are some other issues to deal with. First, trying to write a single presenter for both ASP.NET and a WinForms app assumes the user interaction with the application and the view is going to be roughly the same. That is rarely the case. If I have to go to the trouble to write a Winforms app, I will certainly take advantage of its UI benefits.

Leaky Abstractions Rear Their Head

Thirdly, despite all the hoops that ASP.NET jumps through to abstract the fact that it is a web application and present an API that feels like a desktop platform, it is still a web application platform. The abstraction is leaky and trying to abstract it even more causes problems.

For example, in a Winforms view, you only need to call the Initialize method once because the data is persistent in memory. With an ASP.NET view by default, you have to essentially repopulate every data field every time a user clicks a button. Can you imagine a Winforms app written like that?

Of course you could more closely simulate the Winforms view in ASP.NET view by storing these fields in ViewState or, shudder, Session, but this then becomes a constraint on your ASP.NET view in order to support this pattern, forcing you to take a Winforms approach to a web based app. Ideally a presenter for an ASP.NET application should not have to assume that the ASP.NET view is going to store fields in a persistent manner.


So that is a long-winded answer to a short question. I believe if I had to, I could get the same Presenter to work for both a Winforms App and an ASP.NET app. These problems I mention are not insurmountable. However, I would need to be properly motivated to do so, i.e., have a real hard requirement to do so.