The Power of LINQ – Sorting Lists with a single line of code

This post, just like the code example, is short and to the point, because that’s how LINQ is – short, to the point, and powerful.

Let’s say you have an object called Country.  There will be a List<> populated with it that is going to be used in a drop-down box.  It has the following properties:

  • CountryName (string)
  • DropDownValue (string)
  • SortOrder (int)

The business logic for the list is to order it by SortOrder, and then by CountryName.  You ready for the code?

var destinationList = sourceList.OrderBy(c => c.SortOrder).ThenBy(c=> c.CountryName).ToList();

That’s it. You should note that the difference between OrderBy() and Sort() is that Sort() will actually resort the list you are running it on. OrderBy() on the other hand just returns the result set, but doesn’t actually commit the order to the list; hence, the ToList() assignment to destinationList.

Using Generic Http Handlers to Speed Up ASP.Net – Writing XML

ASP.Net Page vs. Generic HTTP Handler

Web forms (aspx files) and web controls (ascx files) that populate the forms are the two most common elements we create in an ASP.Net web applications.  Web forms are great. You put in some <asp:tags /> and ASP.Net does the rest to render the HTML, and it’s done in a lot less lines than you would have to write with classic ASP 3.0.

With all this magic, however, there is a lot that happens behind the curtains.  There are 11 events that take place during the loading of an ASP.Net page.

    A Generic .ashx handler just has the ProcessRequest method.

    XML Output

    For something like writing raw XML to the browser which may not have any page controls like buttons or images, this is a perfect example of where you can benefit from the performance gain by using a generic http handler instead of wiring up events you won’t use with an .aspx page.  The code to output the XML is fairly simple.

    public class Handler : IHttpHandler
    {
          public void ProcessRequest (HttpContext context)
           {
               context.Response.ContentType = "text/xml";
               context.Response.Write(
                     MyBLL.XmlHelper.GetFor(someobject));
          }
    
          public bool IsReusable
          {
               get { return false; }
          }
    }
    

    You should notice at least a 5 – 10% improvement in performance versus an asp.net page.

    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.