Thursday 22 December 2011

Inversion of Control - Simple Logging Engine Example

Define an interface ILogger. The idea being that different implementations of the ILogger class will log to different mediums (e.g. console or a file).

public interface ILogger
{
     void OpenLog();
     void CloseLog();
     void Log(string message);
}
Here's an example implementation of ILogger that outputs to console (or default out):

public class ConsoleLogger : ILogger
{
     public void OpenLog()
     {
          //Don't need to do anything
     }
     public void CloseLog()
     {
          //Don't need to do anything
     }
     public void Log(string message)
     {
         Console.WriteLine(message);
     }
}
And this example implementation of ILogger logs to a file:

public class FileLogger : ILogger
{
     private StreamWriter sw; 
     public void OpenLog()
     {
          sw = new StreamWriter(@"C:\FileLogger.log", true);
          sw.AutoFlush = true;
     }
     public void CloseLog()
     {
         if (sw != null)
         {
              sw.Close();
              sw.Dispose();
              sw = null;
         }
     }
     public void Log(string message)
     {
         if (sw != null)            
              sw.WriteLine(message);
     }
}
And now for the logging engine itself:
public class LoggingEngine
{
     private ILogger logger;
     public LoggingEngine()
     {
          this.logger = new ConsoleLogger(); //Default console 
     }
     public LoggingEngine(ILogger logger)
     {
          this.logger = logger; //Inject a different logger
     }
     public void Log(string message)
     {
          this.logger.OpenLog();
          this.logger.Log(message);
          this.logger.CloseLog();
     }
}
Finally, the two lines below make a log entry by specifying an ILogger implementation (a FileLogger in this case):

var loggingEngine = new LoggingEngine(new FileLogger());
loggingEngine.Log("Hello, world!");
As the above two lines show, you can now swap in/out a new ILogger implementation with ease, therefore reducing the coupling between your logging functionality and the rest of your application. We can also easily instantiate loggingEngine with the default constructor and log to standard output by default.

Inversion of Control with Dependency Injection

I recently heard of the Inversion of Control (IoC) software architecture in a video by Scott Allen. After some googling, I came across the blog post below by Joel Abrahamsson - highly recommended for someone new to the topics of IoC and Dependency Injection. I think the whole idea of IoC shows the advantages of programming to an interface rather than an implementation.

Click here for Joel's blog post.

Wednesday 21 December 2011

C# How To: Bit Flags

I use an Enumeration type whenever I need to define a set of named constants that can be assigned to a variable. Enums are easier on the brain than magic numbers and they ensure that valid values are being used throughout your code (you also have the added compile-time checking advantage).

The following enum models the months in the year:

enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
To use the above enum, you define a variable of the enum type that can be assigned a value from the enumeration:

Months christmasMonth = Months.Dec;
The variable christmasMonth now represents the month December. It's worth knowing that by default, each enum value is assigned an integer value based on its order of definition (the underlying type of an enumeration value is actually an integer). In this example, the value Months.Jan is assigned the integer 0 and Months.Dec is assigned the int 11. These integer values can be overridden as we will see further below.

Sometimes, it makes sense to be able to assign multiple enum values to a single variable. For example, it would be nice to be able to assign multiple Month enum values to a Months variable called summerHolidayMonths. This is possible using the bit flag technique.

To create a bit flags enum, you assign the attribute [System.FlagsAttribute] to the enum definition and sequentially assign values of the power two (starting from zero) to each enumeration value:

[System.FlagsAttribute]
enum Months
{
     Jan = 0x0,   //000000000001 (base 2) 0 (base 10)
     Feb = 0x1,   //000000000010 (base 2) 1 (base 10)
     Mar = 0x2,   //000000000100 (base 2) 2 (base 10)
     Apr = 0x4,   //000000001000 (base 2) 4 (base 10)
     May = 0x8,   //000000010000 (base 2) 8 (base 10)
     Jun = 0x10,  //000000100000 (base 2) 16 (base 10)
     Jul = 0x20,  //000001000000 (base 2) 32 (base 10)
     Aug = 0x40,  //000010000000 (base 2) 64 (base 10)
     Sep = 0x80,  //000100000000 (base 2) 128 (base 10)
     Oct = 0x100, //001000000000 (base 2) 256 (base 10)
     Nov = 0x200, //010000000000 (base 2) 512 (base 10)
     Dec = 0x400  //100000000000 (base 2) 1024 (base 10)
}
Thus, the enum value Months.May, can now also be represented by the bit pattern "000000010000".

By thinking in terms of bits, we can now use the bitwise logical OR operator in C# to assign multiple enumeration values to a single enum variable, for example:

Months summerHolidayMonths = Months.May | Months.Jun | Months.Jul | Months.Aug;
summerHolidayMonths now represents the months May, June, July and August.

By logical OR'ing each value, we're storing the bit pattern "000011110000" in the summerHolidayMonths variable. As stated, this pattern was arrived at by bitwise OR'ing the bit patterns of each of the summer month enum values:

 Months.May = 000000010000
 Months.Jun = 000000100000
 Months.Jul = 000001000000
 Months.Aug = 000010000000
              ------------
Logical OR  = 000011110000


Clever... but how do we know if a particular month is stored in the summerHolidayMonths variable? We can use the bitwise logical AND operator like so:

bool isJuneInSummerMonths = (summerHolidayMonths & Months.June) == Months.June;
We can also remove a month from the summerHolidayMonths by computing the bitwise logical XOR of the variable with the enum value to remove. In the example below, we're removing the month May from summerHolidayMonths:

summerHolidayMonths = summerHolidayMonths ^ Months.May;
I'll leave it to you to apply the XOR on the months to see that it does really work!

Next time you define an enumeration, give some thought as to whether it makes sense to allow users of your enum to store multiple enumeration values in the enumeration variable - if it does make sense, then use bit flags!

Tuesday 20 December 2011

LINQPad

I've never really enjoyed using SQL to query a relational database in my apps (primarily because of the object-relational impedance mismatch), I have enjoyed being able to throw all of that relational logic over to an Object to Relational Mapping (ORM) framework. At present, I'm using Microsoft's Entity Framework but I've also heard that NHibernate isn't a bad open source alternative. One thing I love about ORM framework's like Entity Framework is that they give me the ability to query my data source's using LINQ. LINQ is similar to SQL in the sense that it's a declarative way of forming a query (the syntax is also not that different from SQL). However, a LINQ query is embedded and compiled within a C# assembly.

About a year ago I came across LINQPad which is a graphical tool that lets you execute C# in a nice little sandbox-like environment. I've used LINQPad extensively to practice C#/LINQ and can't recommend it enough. There is a free and paid version. The last time I checked, the main difference between the two versions is that the paid version supports intellisense.

A  highly recommended tool for someone new to C# who just wants a quick alternative to Visual Studio for trying out a code snippet, whether LINQ-based or not.

Monday 19 December 2011

C# How To: Log to File

Over the past few weeks, I've needed to write a number of small "throw-away" console applications. These applications processed a large amount of data and there was a need to log progress. I wrote the following fairly reusable file logging class which someone may find useful. Alternatively, I'm also interested to get some feedback on whether it could be improved in any way, so feel free to comment on this one.

public class FileLogger
{
    private static FileLogger singleton;
    private StreamWriter logWriter;

    public static FileLogger Instance
    {
        get { return singleton ?? (singleton = new FileLogger()); }
    }

    public void Open(string filePath, bool append)
    {
        if (logWriter != null)
            throw new InvalidOperationException(
                "Logger is already open");

        logWriter = new StreamWriter(filePath, append);
        logWriter.AutoFlush = true;
    }

    public void Close()
    {
        if (logWriter != null)
        {
            logWriter.Close();
            logWriter = null;
        }
    }

    public void CreateEntry(string entry)
    {
        if (this.logWriter == null)
            throw new InvalidOperationException(
                "Logger is not open");
        logWriter.WriteLine("{0} - {1}",
             DateTime.Now.ToString("ddMMyyyy hh:mm:ss"),
             entry);
    }
}
Simple example of usage (I'd wrap this in a try/catch/finally where the finally calls the close method):

FileLogger.Instance.Open(@"C:\MyLog.log", false);
FileLogger.Instance.CreateEntry("Hello, world!");
FileLogger.Instance.Close();

Sunday 18 December 2011

String.IsNullOrEmptyWhiteSpace Extension Method

This is hopefully the first of a series of related posts on some useful Extension methods that I've written. If you're not familiar with Extension methods then think of them as additional methods that you can add to any class you want additional functionality or behaviour for. For example, you can add a new method to the .NET BCL String class (as in this post). Prior to this feature, you could achieve this by deriving from a class and adding a new method in the deriving class, but Extension methods now give you a more reusable alternative. I'd recommend reading up on this topic by clicking here.

One thing I often find myself having to do is validate a string for not being empty. One fairly primitive way to accomplish this is to test for the following condition in an if statement:

input.Equals(string.Empty)
This will return true if input is an empty string. Sometimes, however, you need to also test if the input contains empty white space. Imagine if the user accidently hit the space key and the value for input was the string "  ". The test above would return false in such a case. To cater for such scenarios, I wrote the following extension method in a class library project.

public static bool IsNullOrEmptyWhiteSpace(this string str)
{
     return (str == null || str.Trim().Equals(string.Empty));
}
The test would now look like:

if (input.IsNullOrEmptyWhiteSpace())
     //Tell user to enter something
** Update (13/03/2013) **

As of .NET 4 the static method IsNullOrWhiteSpace was added to the String datatype, therefore making the extension method above redundant (unless you're still using earlier versions of the framework :).

Inheriting from a Generic Collection

You're probably familiar with generics in C#. For example, if you wanted to create a strongly-typed list of Car objects, where Car is defined as:

internal class Car
{
     public string Manufacturer { get; set; }
     public string Model { get; set; }
}
Then you can create a list with the statement:

var cars = new List<Car>();
However, you can also create a custom Car collection class or Abstract Data Type (ADT) with very little effort. By little effort, I mean that you do not need to concern yourself with managing the state of the collection class and implementing your own Add(...), Remove(...) etc. methods. To accomplish this, you can simply inherit from a generic List of the type you want a collection class for. So if we wanted our own "Cars" collection class, we can define the class as:

internal class Cars : List<Car>
{
     //... we inherit all of the List class' functionality
}
Pretty simple. Now we have a strongly-typed collection class to store our Car objects in. Furthermore, we do not need to write unit tests as we didn't write any custom logic to manage the internal state of our new collection class. To use our new class, it's as simple as newing up an object of the Cars class, and making use of all those useful List methods you're already familiar with...!

var cars = new Cars();
cars.Add(new Car() { Manufacturer="Porsche", Model="Cayman" });
cars.Add(new Car() { Manufacturer="Mercedes", Model="C Class" });

cars.ForEach(
    c => Console.WriteLine("{0} - {1}", c.Manufacturer, c.Model));

Welcome

I'm a Computer Science/Software Engineering postgraduate who is now working as a Software Developer in industry. I have chosen to specialise in the Microsoft .NET Framework (C#). This blog is a place for me to write about the things I've learnt. Hopefully, someone else may also find it useful.