Inside Look at a Real World Web Project – Planning, Strategy, Design, and Implementation

My team and I just deployed a high-profile, albeit small website for one of our brands. This article will give you an inside look at each step of this real world project, which you may not necessarily be able to find in a WROX publishing book. I will cover the project framework, overall design strategy, and working with Sitecore. In a cross-post, one of my teammates, @kaidez [http://www.kaidez.com], go into the detail of front-end code and some of the invaluable tools that simplified the general development of this project.

Project Framework

For our framework, we chose SCRUM. In a 4-person web team, all sitting within reach of each other, we have found that over the years, this works best for us. The designers know what the developers are doing and vice versa. Like SCRUM, we are fast and efficient. In fact, I am very proud of my team. As a 4-person standalone web design shop, I think we’d do rather well, assuming we wouldn’t have to pay for our own healthcare.

In the role of ScrumMaster, the first thing I did was set up a storyboard in scrumy.com (pronounced scruh-mee, not screw-me, which is a completely different NSFW site). If you haven’t used this tool before, give it a try. Its drag-and-drop interface lets you create stories, associate tasks with a user, and drag-and-drop them from column to column (to-do, in progress, verify, complete). Maintaining a storyboard like this, not only puts your project manager at ease, who may be in a remote location, but also keeps the team sane when you need to get out of the coding zone and get a perspective on the project progress.

Design Strategy

If you only get one takeaway from this, it’s that no matter how small the project, proper design and planning will always serve a benefit.

Since we adopted Sitecore as the official CMS tool, our design was already partially established. With this being a small product informational site, our Sitecore template design was not unlike the Sitecore demo project. The difference between our solution and the demo project is the level of OOP design.

What I have seen with novice Sitecore developers is as soon as they start developing a site, they completely abandon n-tier architecture and OOP best practices. Sitecore does not and should not replace a good OOP design.

Take the Product entity as an example. A Product may have a name, image, link, and a description. In a 3-tier (DAL/BLL/UI) architecture, you would create a class for it in the Business Logic Layer. In our case, we display products in a category page and in a product page. If you care about your code, there should be an alarm that goes off that detects duplicate functionality and tells you to extract it to one common place; hence, the need for our BLL assembly.

If you are still not seeing the benefit, consider the readability and general elegance of binding an asp:repeater to a List of products with dot notation and intellisense, as opposed the ugly DataBinder.Eval() function.

<asp:Repeater ID="rptProducts" runat="server">
	<ItemTemplate>
		<a href="<%#((Product)Container.DataItem).Link)" %>
			<%#((Product)Container.DataItem).Image) %><br/>
			<%#((Product)Container.DataItem).Name) %>
		</a>
	</ItemTemplate>
</asp:Repeater>

As another best practice, you will want a Core assembly to keep track of static constants and variables. In our case, it holds the URL to our CDN which is different from environment to environment.

Team Development Environment

After the design is knocked out, I have to make sure everyone’s development environment is properly set up and wired up to TFS. I’ve seen developers skip this step until the project is complete, but I cannot stress this enough – these shortcuts will only make your life more difficult. Set up TFS before you start development and don’t forget to check in changes to avoid having other developers overwrite your changes or hearing the never-old “well… it works on my machine” phrase.

The Sitecore templates were done during the design phase in a true Agile environment – in a locked conference room with the entire team, so at this point, it was safe for everyone’s environment to be pointed at the same Sitecore database environment since the templates weren’t really changing.  I created the solution with by including the Sitecore files and assemblies, created BLL/Core projects, and checked everything into TFS, after which everyone did a GLV (get latest version).

Sitecore Deployment

We build this site using Sitecore v6.4. With this version, there is no staging module that you have install like with v6.1, so I thought that after I take care of the checklist in Sitecore’s Configuring Production Environments handbook, I’d be home free, but not so. If you want the cache to automagically clear after publish, you will have to set the EnableEventQueues property to “true” in your web.config

Takeaways

A little planning and preparation before will save you a lot of fan cleaning later. No matter how small the project, if you are in a real world environment, chances are it will at some point grow or will probably need maintenance. Following best practices in the beginning, you will avoid cursing yourself and/or your team when it’s time to do that maintenance or expansion.

  • Remember to use a project framework that will fit your team and organization, whether it’s SCRUM or something else. If it’s something else, you will still find scrumy.com to be useful for simple task management.
  • Use TFS, or something else if you don’t have TFS, for source control early on before development kicks off.
  • Do not disregard a good n-tier design just because you are working in a CMS.

Check out @kaidez’s cross-blog on this topic here: www.kaidez.com.

Design Patterns Series: The Decorator Pattern (with a real-world soccer example!)

Good News: You just landed a gig at as a developer for the Soccer department of ESPN! Bad News: Deadlines are tight and documented requirements are scarce.

In fact, the entire project is behind, but shortcuts and bad code are not tolerated and they need you to implement a robust system, due yesterday.

The Project: Implement a system that displays statistics for a given team.

The Challenge: In the requirements that are present, it specifies that you are to provide the basic win-loss-draw stats for each team, but you heard that more statistics will need to be developed. You don’t know when they will come and you don’t know which stats they will be. What you do know is that the generic functionality will have functionality to display the statistics in a tabular fashion.

They run a tight shop here, so a good OOP design is expected. Perhaps, one that adheres to the Open-Closed Principle, which in the Head First: Design Patterns text states that

Classes should be open for extension, but closed for modification.

This means that when they come to you with additional statistics, instead of creating additional lines in the existing class, creating the need to recode, recompile, and retest, you close the existing class, but code the structure in such a way that you can add extension classes using the principles you have learned so far.

This is where the Decorator Pattern comes in.

The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

With this pattern, you start out with an abstract class that will house the common functionality skeleton. Let’s call it the Component. In our case, there is the Display() method, and the team name. Our initial requirements state that we are going to display the W-L-D records for a team. At this point, we know we are definitely extending this abstract class, a.k.a. component, as a ConcreteComponent.

public abstract class TeamData
//Component
{
    public abstract string Display();
    public string TeamName;
    private string _teamName;
}

public class Matches : TeamData
//ConcreteComponent
{
    public int Wins {get; set;}
    public int Losses {get;set;}
    public int Draws {get;set;}

    public Matches(string teamName,int wins,int losses,int draws)
    {
        TeamName = teamName;
        Wins = wins;
        Losses = losses;
        Draws = draws;
    }

    public override string Display()
    {
        var sbStats = new StringBuilder();
        sbStats.Append("Team Name: " + TeamName);
        sbStats.Append("Record (W|L|D): ");
        sbStats.Append(Wins + "|");
        sbStats.Append(Losses + "|");
        sbStats.Append(Draws);

        return sbStats.ToString();

    }
}

We know more requirements are coming, so how do we plan for the future? We create another abstract class, a.k.a Decorator, inheriting the Component object, which is also an abstract class. Any extension classes, a.k.a. ConcreteDecorators, will have the benefit of following the functionality skeleton with the flexibility of creating custom functionality.

public abstract class TeamStatDecorator : TeamData
//Decorator
{
    protected TeamData teamData;
    public void AttachComponent(TeamData _teamData)
    {
        teamData = _teamData;
    }
    public override string Display()
    {
        if (teamData != null)
            teamData.Display();
    }
}

public class HomeAwayAdvantage : TeamStatDecorator
//ConcreteDecorator
{
    public int GoalsScoredHome { get; set; }
    public int GoalsScoredAway { get; set; }
    public int GoalsConcededHome { get; set; }
    public int GoalsConcededAway { get; set; }

    public HomeAwayAdvantage(int goalsScoredHome, int goalsScoredAway,
    int goalsConcededHome, int goalsConcededAway, string teamName)
    {
        TeamName = teamName; //inherited
        GoalsScoredHome = goalsScoredHome;
        GoalsScoredAway = goalsScoredAway;
        GoalsConcededHome = goalsConcededHome;
        GoalsConcededAway = goalsConcededAway;

    }
    public override string Display()
    {
        //first we call the class we inherit from - TeamStatDecorator
        base.Display();

        var sbStats = new StringBuilder();
        sbStats.Append("Team Name: " + TeamName);
        sbStats.Append("Goals Scored (Home|Away): ");
        sbStats.Append(GoalsScoredHome + "|" + GoalsScoredAway);
        sbStats.Append("Goals Conceded (Home|Away): ");
        sbStats.Append(GoalsConcededHome + "|" + GoalsConcededAway);

        return sbStats.ToString();
    }
}

If at any point we would need to add another statistic functionality, we inherit from the TeamStatDecorator. If you recall back, we mentioned that “has-a” relationships were preferred to inheritance and “is-a” relationships, but in our case, the classes are chained together at run-time. Take a look at the code below.

public class DecoratorExample
{

    static void Main()
    {
        // Create ConcreteComponent and decorator
        var matches = new Matches("Machester United", 9,2,1);
        var homeAwayAdvantage = new HomeAwayAdvantage("Machester United", 14, 3, 5, 4);
        //var otherDisplayType1 = new OtherDisplayType1();
        //var otherDisplayType2 = new OtherDisplayType2();

        // Link them
        homeAwayAdvantage.AttachComponent(matches);
        //otherDisplayType1.AttachComponent(homeAwayAdvantage);
        //otherDisplayType2.AttachComponent(otherDisplayType1);

        //call the last overridden method in the chain
        Console.WriteLine(homeAwayAdvantage.Display());
        //Console.WriteLine(otherDisplayType2.Display());

    }
}

Output:
Team Name: Manchester United
Record (W|L|D): 9 | 2 | 1

Team Name: Manchester United
Goals Scored (Home | Away): 14 | 3
Goals Conceded (Home | Away): 5 | 4

As you can see, we can keep adding decorators (otherDisplayType1,otherDisplayType2) without touching our main TeamData abstract class. If we want custom functionality with the decorators, we simply put it into the decorator abstract class and stick to the open-closed principle.

Hope this made sense. Would love to hear your feedback!

Design Patterns Series: The Observer Pattern

During last night’s Superbowl game – did you pay attention to the score box at the top-left corner? Think about the code you would write to do the keep the score up to date.  Would you get it to poll every couple of seconds for updates?  Let’s also say that hypothetically the same system fed the updates to NFL.com.  Are you going to have multiple systems now checking for updates? Or, is there perhaps a better way to do this?


If you recall the my post about design patterns, this problem has also been solved for you.  The design pattern that solves it is called The Observer Pattern and it too is described beautifully in the book on which this series is based: Head First Design Patterns.

Here is the definition from the text:

“The Observer Pattern defines a one-to-many relationship between a set of objects.  When the state of one object changes, all of its dependents are notified.

Lightbulb, yes? Hopefully? How about building a “push” type of notification mechanism that will notify the scoreboard, website, and any other subscriber that cares to be informed of the score?

Before we get into the code details, it’s important to visualize it from an architecture design perspective.

Subject (abstract)
registerObserver()
removeObserver()
notifyObservers()

The Subject abstract class gets implemented by a real, a.k.a. concrete subject like the main score keeping system.  So now, this system can register many observers, like scoreboards, websites, phones, etc., as well as remove them, and mass notify them.  This ISubject has an IObserver interface that has a single method called update().  This interface gets implemented by an actual observer that has implements this method which may update the scoreboard, phone app, or a website RSS feed.  For this to happen though, it must instantiate the concrete observer and register with it, which says “Hey, I’d like to subscribe to your events.  Please push an update to me anytime there is one and I’ll do my own thing to update my interface – and don’t worry, because you don’t have to know the details.  You and I are loosely coupled that way.”

Another great example of loose coupling here.  If the score keeping system had to know the details of how to update a website, a phone app, a TV scoreboard, and a bunch of other devices, not only would you have a humungous amount of lines in your code, but you would also have to recompile and retest anytime you wanted to add a new device implementation.  With loose coupling, that’s hidden in the actual observer object so that all the Subject has to know is that that device is registered and to send it an update when one exists.

Now that we see the benefit, let’s take a look at how you would implement the C# code for this.
Quick disclaimer: The .NET Framework has given us events and delegates, and while there are many ways to skin a cat and do this several ways, I am just using C# to show you the underlying object-oriented code to get this to work.

We create an interface for Observer and an abstract class for Subject
IObserver.cs

using System;

public interface IObserver
{
     void Update(object subject);
}

Subject.cs

using System;
using System.Collections;

public abstract class Subject
{
    private ArrayList observers = new ArrayList();

    public void AddObserver(Observer observer)
    {
         observers.Add(observer);
    }

    public void RemoveObserver(Observer observer)
    {
        observers.Remove(observer);
    }

    public void Notify()
    {
          foreach(Observer observer in observers)
          {
               observer.Update(this);
          }
     }
}

ScoreKeeper.cs

public class ScoreKeeper : Subject
{
      public int TeamOneScore {get;set;}
      public int TeamTwoScore {get;set;}

    //could be called by the master score keeper
    public void ChangeScore(int scoreOne,int scoreTwo)
    {
         TeamOneScore = scoreOne;
         TeamTwoScore = scoreTwo;

          Notify();
     }
}

ScoreWebForm.cs

public class ScoreWebForm : IObserver
{
       public void Update(object subject)
       {
            //let's make sure the right subject
            //called this method.
            if(!(subject is ScoreKeeper)
               return;

            //update asp:label web controls
           labelScore1.Text = ((ScoreKeeper)subject).TeamOneScore;
           labelScore2.Text = ((ScoreKeeper)subject).TeamTwoScore;
     }
}

There you have it.  Another problem solved by design patterns.  Hopefully, if you have not heard about design patterns before, you are slowly beginning to see the value.  Make sure to catch the entire series on my blog and get yourself a copy of the above mentioned book if you haven’t already done so.

Behavior-Driven Development (BDD) – Setting up Visual Studio/Team Foundation Server (TFS)

In my earlier post, I defined what Behavior-Driven Development (BDD) was and threw in a code example using RhinoMocks.   Hopefully, I was able to inspire some of you out there.  In the event that I did and you will actually attempt to adopt this methodology in your enterprise, I will walk you through the steps required to smoothly integrate this into your existing development environment.

What You Will Need

  • Microsoft Visual Studio 2008 or 2010 Test Edition or above
  • Team Foundation Server
    • This is optional if you want to into take advantage of MSBuild running your tests on check-in.
  • RhinoMocks – (Download Link)
  • TestDriven.NET – (Download Link)
    • This is also optional.  TestDriven.NET is an add-in testing component for Visual Studio that makes running your tests a breeze.
    • The personal edition is free for open source users, trial users, and students.

Step 1 – RhinoMocks
Download RhinoMocks.  The zip file does not contain an executable.  It’s just a library that you will reference in your project.  You can put it in a new directory someone on C:\ for now.

Step 2 – TestDriven.NET
Download and install.  Again, this is an optional component but you should definitely give it a “test drive” and decide, if you are in a company setting, whether you want to purchase a license.  It my example, I will be using MSTest, but it supports multiple test frameworks like NUnit.

Step 3 – Create an empty C# class library project

This will be the project you will be testing against.  You can add it to source control if you have a connection to Team Foundation Server.

When you create it, it should also create a solution.

Step 4 – Create another empty C# class library project
This will be the test project.  Make sure to stick to a consistent naming convention.  I end my test projects with “.UnitTests” in the name (e.g. BLL.ShoppingCart.UnitTests).  This allows you to specify a wildcard pattern in MSBuild when running tests.  I’ll go into this in more detail below.

Step 5 – Add Rhino.Mocks.DLL reference to test project
Right click on References and click Add Reference.  Locate the RhinoMocks DLL file you extracted in the first step and add it to the project.

Step 6 – Write your test and build solution

When copying my code, please replace the less than/greater than signs with brackets.  The code css styler had a problem with them.

using Rhino.Mocks;

namespace BLL.Cart.UnitTests
{

<TestClass>
public class CartTest
{
private MockRepository _mock;

<TestInitialize>
public void TestSetup()
{

_mock = new MockRepository();
}

<TestMethod>
public void WhenItemAdded_CartQuantityShouldIncrease()
{
//test code
} } }

Step 7 – Create Build Definition and Incorporate Test Assemblies

In Team Explorer, you will go through the regular motions of creating a build definition.  The option that will trigger the tests is on the last option screen where you will indicate your test assembly pattern, as shown in the screenshot inset.

The last thing you will want to make sure is that the Rhino.Mocks DLL you included in the project is added to source control. Otherwise, when MSBuild attempts to build your solution, you will get a reference error and it will not build.

And that’s it.

As always, I’d love to hear your feedback to see if this was helpful or if there is anything I might have missed.

Design Patterns Series: The Strategy Pattern

To use the example from Head First: Design Patterns, suppose you have a class called Duck and two classes that inherit it: MallardDuck and RedheadDuck.

Duck
quack()
swim()
display()
fly()

What happens when you are asked to implement a RubberDuck class? A RubberDuck does not fly() or quack() so the design is a bit off.  This is actually a great example that illustrates that a “has a” relationship is better than an “is a” relationship.  Instead of inheriting from a Duck superclass, we will be inheriting some interfaces, that represent behaviors – FlyBehavior and QuackBehavior.

The Strategy Pattern, as the book describes it is, “defines a family of algorithms, encapsulates each one, and makes them interchangeable.  Strategy lets the algorithm vary independently from clients that use it.”   Here is what the Duck class looks like after we apply the Strategy pattern.
Client

Duck
FlyBehavior flybehavior
QuackBehavior quackBehavior
swim()
display()
setFlyBehavior()
setQuackBehavior()

encapsulates

FlyBehavior (interface)
fly()

inherited by

FlyWithWings
fly()

and

FlyNoWay (used by RubberDuck)
fly()

Similarly, you can have apply the same principle to QuackBehavior.

Here is what the code looks like in C#.

public abstract class Duck
{
  QuackBehavior quackBehavior;
  FlyBehavior flyBehavior;
}
public class MallardDuck : Duck
{
   public MallardDuck()
   {
        flyBehavior = new FlyWithWings();
        quackBehavior = new Quack();
   }
}
public class RubberDuck : Duck
{
     flyBehavior = new FlyNoWay();
     quackBehavior = new QuackNoWay();
}

The takeaway here is to use behaviors, or has-a relationships on entities that might change later on so that you don’t have to rewrite the parts of the code or class that do not change.