Using Flagged Enums

Have you ever written or come across code where you have a series of boolean values that determine whether or not certain actions are allowed?

Example:


public class WorkDays
{
  public bool Sunday { get; set; }
  public bool Monday { get; set; }
  public bool Tuesday { get; set; }
  public bool Wednesday { get; set; }
  public bool Thursday { get; set; }
  public bool Friday { get; set; }
  public bool Saturday { get; set; }

  public bool Weekdays { get { return Monday && Tuesday && Wednesday && Thursday && Friday; } }
  public bool Weekends { get { return Sunday && Saturday; } }

  public int NumberOfDaysWorked
        {
            get
            {
                int numberOfDaysWorked = 0;

                if (CanWorkMonday) numberOfDaysWorked++;
                if (CanWorkTuesday) numberOfDaysWorked++;
                if (CanWorkWednesday) numberOfDaysWorked++;
                if (CanWorkThursday) numberOfDaysWorked++;
                if (CanWorkFriday) numberOfDaysWorked++;
                if (CanWorkSaturday) numberOfDaysWorked++;
                if (CanWorkSunday) numberOfDaysWorked++;

                return numberOfDaysWorked;
            }
        }
}

There’s a more elegant approach that is utilized through the standard .net framework that we too can mimic.

This scenario is a perfect candidate for using a flagged enum and the power of bit operations.



    [Flags]
    public enum Days
    {
        None = 0,
        Sunday = 1,
        Monday = 2,
        Tuesday = 4,
        Wednesday = 8,
        Thursday = 16,
        Friday = 32,
        Saturday = 64,
        MondayToFriday = Monday | Tuesday | Wednesday | Thursday | Friday,
        Weekend = Saturday | Sunday,
        All = MondayToFriday | Weekend,
    }

    public class WorkDays
    {
        public Days DaysWorked { get; set; }

        /// <summary>
        /// Get the Number of Days worked.
        /// NOTE: Uses bitwise and operation.
        /// </summary>
        public int NumberOfDaysWorked
        {
            get
            {
                Days days = DaysWorked;
                int numberOfDaysWorked = 0;
                for (; days != 0; numberOfDaysWorked++)
                {
                    days &= days - 1; // clear the least significant bit set
                }
                return numberOfDaysWorked;
            }
        }
    }

By defining an enum with each successive value a power of 2 greater (i.e. binary) you can then use the bitwise or (|) and bitwise (&) operations to group and determine which values are selected.


    [TestClass]
    public class ExampleTestClass
    {
        [TestMethod]
        public void Test()
        {
            var mondayToFriday = new WorkDays { DaysWorked = Days.MondayToFriday };
            Assert.IsFalse(Days.Sunday.In(mondayToFriday.DaysWorked));
            Assert.IsFalse(Days.Saturday.In(mondayToFriday.DaysWorked));
            Assert.IsTrue(Days.Wednesday.In(mondayToFriday.DaysWorked));
            Assert.AreEqual(5, mondayToFriday.NumberOfDaysWorked);

            var monday = new WorkDays { DaysWorked = Days.Monday };
            Assert.IsFalse(Days.Sunday.In(monday.DaysWorked));
            Assert.IsTrue(Days.Monday.In(monday.DaysWorked));
            Assert.AreEqual(1, monday.NumberOfDaysWorked);

            var mondayAndWednesday = new WorkDays { DaysWorked = Days.Monday | Days.Wednesday };
            Assert.IsFalse(Days.Tuesday.In(mondayAndWednesday.DaysWorked));
            Assert.IsTrue(Days.Monday.In(mondayAndWednesday.DaysWorked));
            Assert.IsTrue(Days.Wednesday.In(mondayAndWednesday.DaysWorked));
            Assert.AreEqual(2, mondayToFriday.NumberOfDaysWorked);

            var weekend = new WorkDays { DaysWorked = Days.Weekend};
            Assert.IsTrue(Days.Saturday.In(weekend.DaysWorked));
            Assert.IsTrue(Days.Sunday.In(weekend.DaysWorked));
            Assert.IsFalse(Days.MondayToFriday.In(weekend.DaysWorked));
            Assert.AreEqual(2, weekend.NumberOfDaysWorked);
        }
    }

    public static class Extensions
    {
        /// <summary>
        /// Is the specified enumeration value within the range of Enum values?
        /// </summary>
        /// <param name="value">the enum value to look for in the range</param>
        /// <param name="range">the range of enum values (eg. bitwise OR'd values)</param>
        /// <returns></returns>
        public static bool In(this Enum value, Enum range)
        {
            var valueNumber = (int) Enum.Parse(value.GetType(), value.ToString());
            var rangeNumber = (int) Enum.Parse(range.GetType(), range.ToString());
            return (valueNumber & rangeNumber) == valueNumber;
        }
    }

For further information check out the following resources:

If you’re gotten a bit rusty on your bitwise operations:
http://en.wikipedia.org/wiki/Bitwise_operation

Flagged Enum:
http://weblogs.asp.net/wim/archive/2004/04/07/109095.aspx

Posted in .Net, C# at November 2nd, 2008. No Comments.

Visual Studio 2008 – Shortcut Keys for running Unit Tests

Short Cut Keys to Run Tests:

• Ctl R, T: Run Tests in Current context (namespace, class, and method – ie. Based on where your cursor is within a file it determines the tests to run)
• Ctl R, C: Run Tests in Current Test Class
• Ctl R, N: Run Tests in Current Namespace
• Ctl R, S: Run All Tests in Solution
• Ctl R, D: Run the Tests in the Last Test Run
• Ctl R, F: Run the Failed Tests of the Last Test Run

Posted in .Net, C#, Development, Unit Testing at October 30th, 2008. 2 Comments.

I’m back

After having 9 months off from doing .net (travelling, bumming and then a 3 month contract role as an architect in a coldfusion shop) I finally got myself a role doing what I love doing best – playing with .net and c#.

In the last 4 weeks I’ve been researching and prototyping apps that use

It’s been awesome to have the time and resources to touch across all of these technologies to enjoy their benefits and to loath the limitations.

All in all I reckon all of the technologies are a great addition to the .net stack and look forward to seeing them mature with each new release.

I look forward to documenting my findings as I find time to re-work them into don’t-give-away-IP examples.

Posted in .Net, Asp.Net, C#, Unit Testing at October 30th, 2008. No Comments.

Running VS Unit Tests stops IIS

We recently ran into this problem where we discovered that running our VS unit tests was killing IIS.

As with all problems, I like to break things down to the simplest scenario I can find and as such created a brand new unit test that did nothing to see if that still caused the problem – it did.

So knowing that it had nothing to do with any code that was web dependent I knew to start looking elsewhere.

Turns out the problem is caused by enabling code coverage on projects that are dependent on IIS – e.g. a web project.

Visual Studio Code Coverage

The simple solution is to disable code coverage on the problem-causing project OR alternately remove the dependency on IIS by modifying it to use the in-built Cassini web server.

Posted in .Net, Development, Unit Testing at October 24th, 2008. No Comments.

Using Enums for constant values

Have you ever found yourself using c# const values to remove the risks associated with using copies of string literals throughout your code base?

Example:

public static class VehicleTypesConsts {
 public const string Car = 'Car';
 public const string Motorbike = 'Motorbike';
 public const string Truck = 'Truck';
}

In a situation like this it’s quite easy to replace these const values with a C# enum and use the System.Enum.GetName static method to return Enum properties name.

public enum VehicleTypesEnum {
  Car,
  Motorbike,
  Truck,
}

Calling

Enum.GetName(typeof(VehicleTypesEnum), VehicleTypesEnum.Car)

will return the string value “Car”.

Looking at this syntax you could be forgiven for thinking why bother? It’s too much hassle and looks puss.

Well using C# 3.0 extension methods you can provide a convenience method to all Enums to return the enum string representation.

public static class EnumExtensions {
  static public string GetName(this Enum enumeration) {
    return Enum.GetName(enumeration.GetType(), enumeration);
  }
}

Now you can just write:

VehicleTypesEnum.Car.GetName()

and it will return the string “Car”.

The following test method shows illustrates the varying ways to achieve the same result:

        [TestMethod]
        public void Test()
        {
            string expected = 'Car';
            Assert.AreEqual(expected, VehicleTypesConsts.Car);
            Assert.AreEqual(expected, Enum.GetName(typeof(VehicleTypesEnum), VehicleTypesEnum.Car));
            Assert.AreEqual(expected, VehicleTypesEnum.Car.GetName());
        }
Posted in C# at October 13th, 2008. 1 Comment.

SqlDependency and DateTime values

I ran into a problem today where I was trying to set up a SqlDependency against a table, with what I thought was a plain vanilla select statement:


private const string SqlCommandText =
    "Select ImportDate From dbo.Imports Where ImportDate = '{0:yyyyMMdd}'";

I was formatting this string with a date/time value at runtime, then passing that into my SqlCommand object, then attempting to register the dependency. Well guess what – it didn’t work! The SqlNotificationEventArgs class kept telling me that my statement was invalid. Checking the special considerations using query notifications, I couldn’t see anything wrong with my query, so I was a bit lost.

Anyway, I decided to axe the “Where” condition from my query, and sure enough, it worked! So, by process of elimination, I figured it was something to do with converting a date from a character string that was throwing it. Not sure why; this works fine when run as T-Sql, or within a normal query…

To get around this problem, I used the “best practice” approach of using a parameter in the SqlCommand object:


private const string SqlCommandText =
    "Select ImportDate From dbo.Imports Where ImportDate = @ImportDate";

protected SqlCommand CreateSqlCommand() {
    var command = new SqlCommand(SqlCommandText);
    command.Parameters.Add(new SqlParameter("ImportDate", SqlDbType.DateTime) {
        Value = PositionDate
    });

    return command;
}

To my surprise, this worked a treat! I guess in the end, it wasn’t all that surprising, however I for some reason thought that using a parameter would surely not work; hence the reason I was pre-formatting the date/time in the first place!

Posted in C#, Sql Server at September 22nd, 2008. 3 Comments.

Internet Explorer: Fighting back!

One of my all time favourite features about FireFox is the Web Developer Toolbar, which makes life much simpler when you’re trying to figure out problems with your web pages. Up until now, internet explorer hasn’t offered anything that’s quite so concise and easy to use, which makes FireFox the easy choice for web developers everywhere.

Developer Tools

Well, now that Internet Explorer 8 Beta 2 has been released, the choice is no longer so clear. IE8 now includes “Developer Tools” which, so far, look like an absolute gem.

So far, I’ve only played with the script debugger, which works pretty much as you would expect, and handily uses the same keyboard shortcuts as Visual Studio. The CSS debugger looks great too – you can selectively turn on/off different parts of your stylesheet using the checkbox next to each style declaration.

Though I’m still a long way off giving up FireFox, I’m happy to see that Internet Explorer is finally offering something that will at least tempt me to use it sometimes.

Posted in .Net at August 28th, 2008. 1 Comment.

Alternating items without using an AlternatingItemTemplate

Many of the controls in ASP.Net (e.g. a Repeater) support the concept of an AlternatingItemTemplate, which, as the name suggests, allows you to define an additional item template to change the look and feel for each alternating item in the data source. This is all well and good, but I’ve never seen a good use for it; more often than not, all you really want to do in your alternating item is, for example, slightly change the background colour for ease of visual differentiation.

Though you can use the alternating item template for this, it typically involves you duplicating a lot of code, since the AlternatingItemTemplate is mostly the same as your ItemTemplate (save perhaps for a CSS class declaration somewhere).


  <asp:Repeater ID="rpt" runat="server">
      <HeaderTemplate>
          <table cellpadding="0" cellspacing="0">
              <tr>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Age</th>
              </tr>
       </HeaderTemplate>
       <ItemTemplate>
              <tr>
                  <td><%# Eval("FirstName") %></td>
                  <td><%# Eval("LastName") %></td>
                  <td><%# Eval("Age") %></td>
              </tr>
       </ItemTemplate>
       <AlternatingItemTemplate>
              <tr class="Alternating">
                  <td><%# Eval("FirstName") %></td>
                  <td><%# Eval("LastName") %></td>
                  <td><%# Eval("Age") %></td>
              </tr>
       </AlternatingItemTemplate>
       <FooterTemplate>
          </table>
       </FooterTemplate>
  </asp:Repeater>

If this sounds like you, then never fear – there IS a better way!

When you’re binding, you have access to the RepeaterItem via the Container property, which contains an ItemIndex property. As such, the simplest way of alternating your items is simply to check if the number divides evenly by two:


  <asp:Repeater ID="rpt" runat="server">
      <HeaderTemplate>
          <table cellpadding="0" cellspacing="0">
              <tr>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Age</th>
              </tr>
       </HeaderTemplate>
       <ItemTemplate>
              <tr class="<%# Container.ItemIndex % 2 == 0 ? "Alternating" : String.Empty %>">
                  <td><%# Eval("FirstName") %></td>
                  <td><%# Eval("LastName") %></td>
                  <td><%# Eval("Age") %></td>
              </tr>
       </ItemTemplate>
       <FooterTemplate>
          </table>
       </FooterTemplate>
  </asp:Repeater>

There is a minor downside using this approach – the non-alternating rows will all declare an empty CSS class within them. But, this is a sacrifice I think is acceptable to decrease repetition of code.

Posted in Asp.Net at August 27th, 2008. No Comments.

Extension methods on interfaces

This is actually quite straightforward, but something that perhaps you may not have thought about.

On my current project, I have the concept of a “PerishableObject” – an object whose value is only valid between two particular dates. The interface for an IPerishable looks something like this:


public interface IPerishable {
    /// <summary>
    /// Get/Set the date that this component is valid from
    /// </summary>
    DateTime? ValidFrom { get; set; }

    /// <summary>
    /// Get/Set the date that this component is valid until
    /// </summary>
    DateTime? ValidTo { get; set; }
}

Now, logically, I wanted to create a helper method called “IsValidOn”, which could be passed a date, and would return true/false indicating if the component is valid on the supplied date. Obviously, I could define this in the interface, but that would leave me to either implement the method on every object which implements the interface, or to create a common base class which implemented that method, and then force all perishable objects to inherit from this base class. Both of these are not desirable!

Thankfully, extension methods in C# 3.0 provide a perfect solution for this:


/// <summary>
/// Determines if the perishable component is valid on the given reference date
/// </summary>
/// <param name="component">The component to be tested</param>
/// <param name="referenceDate">Reference date to test</param>
/// <returns><c>true</c> if the perishable component is valid on the given reference date</returns>
static internal bool IsValidOn(this IPerishable component, DateTime? referenceDate) {
    if (!referenceDate.HasValue) {
        return true;
    }

    return (!component.ValidFrom.HasValue || component.ValidFrom.Value <= referenceDate)
        && (!component.ValidTo.HasValue || component.ValidTo.Value >= referenceDate);
}

Defining extension methods against an interface is a great way of extending the interface without bulking it up.

Posted in .Net, C# at July 14th, 2008. 2 Comments.

Daily question: Fun with constructors

It’s been a while since anyone has posted a daily question, but here’s one to get y’all in the mood…

Given the following code:


public class BaseClass {
    public BaseClass() : this("Base value") {
        Console.WriteLine("Base: Empty");
    }

    public BaseClass(object value) {
        Console.WriteLine("Base with value: {0}", value);
    }
}

public class DerivedClass : BaseClass {
    public DerivedClass() : this("Derived value") {
        Console.WriteLine("Derived: Empty");
    }

    public DerivedClass(object value) : base(value) {
        Console.WriteLine("Derived with value: {0}", value);
    }
}

What will be printed to the console when a new DerivedClass object is created using the default DerivedClass constructor:


    new DerivedClass();

First person to post the correct answer wins a prize consiting solely of that warm fuzzy feeling you get by being the first person to answer a question correctly.

Posted in C#, Daily Question at July 10th, 2008. 3 Comments.