Compressing Files and Folders with SharpZipLib

I have found a lot of examples on how to compress files using C# but only a few that would compress all files and folders (including subfolders). I found an example in this forum that show how to do it using SharpZipLib.

Here is what I did with it:

static void Main(string[] args)
{
    ZipOutputStream zip = new ZipOutputStream(File.Create(@"d:\my.zip"));
    zip.SetLevel(9);
    string folder = @"D:\Work\AnyDirectory\";
    ZipFolder(folder, folder, zip);
    zip.Finish();
    zip.Close();
}

public static void ZipFolder(string RootFolder, string CurrentFolder, 
    ZipOutputStream zStream)
{
    string[] SubFolders = Directory.GetDirectories(CurrentFolder);

    //calls the method recursively for each subfolder
    foreach (string Folder in SubFolders)
    {
        ZipFolder(RootFolder, Folder, zStream);
    }

    string relativePath = CurrentFolder.Substring(RootFolder.Length) + "/";

    //the path "/" is not added or a folder will be created
    //at the root of the file
    if (relativePath.Length > 1)
    {
        ZipEntry dirEntry;
        dirEntry = new ZipEntry(relativePath);
        dirEntry.DateTime = DateTime.Now;
    }

    //adds all the files in the folder to the zip
    foreach (string file in Directory.GetFiles(CurrentFolder))
    {
        AddFileToZip(zStream, relativePath, file);
    }
}

private static void AddFileToZip(ZipOutputStream zStream, string relativePath, string file)
{
    byte[] buffer = new byte[4096];

    //the relative path is added to the file in order to place the file within
    //this directory in the zip
    string fileRelativePath = (relativePath.Length > 1 ? relativePath : string.Empty) 
                              + Path.GetFileName(file);

    ZipEntry entry = new ZipEntry(fileRelativePath);
    entry.DateTime = DateTime.Now;
    zStream.PutNextEntry(entry);

    using (FileStream fs = File.OpenRead(file))
    {
        int sourceBytes;
        do
        {
            sourceBytes = fs.Read(buffer, 0, buffer.Length);
            zStream.Write(buffer, 0, sourceBytes);
        } while (sourceBytes > 0);
    }
}

This is not hard but I had to figure out that the file names needed to have the relative path before it in order to correctly place them in the same folders within the compressed zip file.

I hope this helps!

Converting Base10 to Base26

There is a post I answered on the asp.net forums I thought was really interesting because it reminded me of my college times. Actually I'm pretty sure that the guy who posted the question was trying to get an answer to his homework, but it doesn't matter, I had fun doing it :-). The problem was to do an ascending sequence using the alphabet (which is a Base26). Something like: A,B,C...Z,AA,AB,AC...AZ,BA,BB,BC...BZ and so on. Well the easiest way to do this is to convert our regular Base10 numbers to Base26 because using Base10 we can do a plain for loop and cout up to the number we want and while doing the loop we can convert the Base10 to Base26. Here is the algorithm: 

        public static string NumberToString(int value)
        {
            StringBuilder sb = new StringBuilder();
            
            do
            {
                value--;
                int remainder = 0;
                value = Math.DivRem(value, 26, out remainder);
                sb.Insert(0, Convert.ToChar('A' + remainder));
                
            } while (value > 0);

            return sb.ToString();
        }

I know this isn't very useful for everyday programming but it was fun to remember the time I was still in college solving this kind of problem. It was a really fun exercise.

Typed Convert using Generics

Last night I answerd a interesting question on the Asp.Net Forums that I thought is worth a post. The objective was to create a method using Generics that could get a value from the Session only instead of returning a Object it would return the value in the type defined in the generic method. Just to make the demonstration easier I'll use a Dictionary instead of the Session but it works just the same:

class TypeTest
{
    private static Dictionary<string, object> PretendSession = new Dictionary<string, object>();

    public static void Test()
    {
        PretendSession.Add("int", 10M);
        Console.Out.WriteLine(Get<int>("int"));
    }

    public static T Get<T>(string theKey)
    {
        object aSessionObject = PretendSession[theKey];

        if (aSessionObject == null)
        {
            return default(T);
        }

        return (T) aSessionObject;
    }
}

This code works well for most cases but you can get in trouble when you work with Value Types. Look at code that follows and to undestand the problems with boxing and unboxing value types:

 //doesn't work, need explicit cast 
int i = 10M; 

//now it's fine 
int i = (int)10M; 

//boxing and unboxing work fine 
object o = 10; 
int i = (int)o; 

//doesn't work 
object o = 10M; 
int i = (int)o;

When you know exactaly what is the type of you are putting inside the Session it all goes fine. When you don't know what type you are working with you need the help of the Convert class to convert the type before casting it. To do this we test if the object is of type ValueType and if it is, before casting it we use the ChangeType method of the Convert class to make sure that the object really contains the type we will try to cast it to.

 

class TypeTest
{
    static Dictionary<string, object> PretendSession = new Dictionary<string, object>();

    public static void Test()
    {
        PretendSession.Add("int", 10M);
        Console.Out.WriteLine(Get<int>("int"));
    }

    public static T Get<T>(string theKey)
    {
        object aSessionObject = PretendSession[theKey];

        if (aSessionObject == null)
        {
            return default(T);
        }

        if (aSessionObject is ValueType)
        {
            return (T)Convert.ChangeType(aSessionObject, typeof(T));
        }

        return (T)aSessionObject;
    }
}

Now you should be safe to use your Get<T> method. Hope this can help other people that face this same issue.

Linq: Using Group By with Multiple Columns

I have a group of classes that I build to get metadata from the database to use with my code generators. The class has the following structure:

public class ConstraintMetadata
{
    public string ConstraintName { get; set; }

    public string ColumnName { get; set; }

    public string ConstraintType { get; set; }

    public string TableName { get; set; }
}

I wanted to write a group by clause using Linq to group the objects I retrieved from the db by TableName, ConstraintName and ConstraintType. This would allow me to have one object for each constraint with a list of all the columns. Since Linq only allows one object in the group by clause the way out is to create an anonymous object with all the properties I want.

var constraints = from c in constraintsMetadata
                  group c by new
                             {
                                 c.TableName, 
                                 c.ConstraintType, 
                                 c.ConstraintName
                             } into g
                      select new
                      {
                          g.Key.ConstraintName,
                          g.Key.ConstraintType,
                          g.Key.TableName,
                          Columns = g.Select(x=>x.ColumnName).ToList()
                      };

Now, if I want to get all the constraints for a table and print it to the console window I can do this:

var tableConstraints = constraints.Where(x => x.TableName == table.Name);

foreach (var tableConstraint in tableConstraints)
{
    Console.Out.WriteLine("Constraint Name:{0}, Table:{1}, Type:{2} Columns:", 
        tableConstraint.ConstraintName , 
        tableConstraint.TableName, 
        tableConstraint.ConstraintType);
    foreach (var column in tableConstraint.Columns)
    {
        Console.Out.WriteLine(column);
    }
}

 

Find out the calling method

This is one that I found really interesting. I needed to log which methods were calling a certain method, I knew that reflection was the answer but I never thought it would be so easy.

Have you used the CallStack window on your VisualStudio when you are debugging? Well, all that information is available through the System.Diagnostics.StatckTrace class. This means that you have access to method calling stack to do whatever you like.

The StackTrace is composed of an array of StackFrames which represent each method on the stack.

To demonstrate this I’ll create a class with four methods (Method1, Method2, Method3, Method4) which will be called in the following order:

Main -> Method1 -> Method2 -> Method3 -> Method4

class Program
{
    static void Main(string[] args)
    {
        StackTraceTest stt = new StackTraceTest();
        stt.Method1();
    }
}

class StackTraceTest
{
    public void Method1()
    {
        Console.Out.WriteLine("Inside Method1");
        Method2();    
    }

    private void Method2()
    {
        Console.Out.WriteLine("Inside Method2");
        Method3();
    }

    private void Method3()
    {
        Console.Out.WriteLine("Inside Method3");
        Method4();
    }

    private void Method4()
    {
        Console.Out.WriteLine("Inside Method4");
        StackTrace st = new StackTrace();
        StackFrame[] frames = st.GetFrames();
        for (int i = 0; i < frames.Count(); i++)
        {
            Console.Out.WriteLine("StackTrace info: Index: {0}/Method: {1}", 
                i, frames[i].GetMethod().Name);
        }
    }
}

Each method displays a message on the console letting you know that it has been invoked. When the program gets to Method4 it will print the name of the methods on the stack.

Here is the output:

Put a break point on the end of the Method4 and you can take a look at VisualStudios CallStack window to compare with the console output.

As a test you might want to move the StackTrace code to the other methods to see that it will show all the method that led to method currently executing.

For more information look at the StackFrame and MethodBase classes at MSDN.

Sharing Static Field Only Within a Thread

When you use a static field it’s data is shared among any classes using it. That’s something that everyone should know. When programming web applications, every request from the browser will span a new Thread. If you have a static field in a class that is used in a page’s code behind all it’s value will be shared by all requests.

This is great but sometimes you want to share the static field between a bunch of classes that do some business logic when the browser sends a request and you want the static field to share data among all these business logic classes. But when you think that there will be several requests to your site simultaneously (hopefully) you notice that the static field is not only being shared between all business classes in the request but between all business classes in all the requests. You might or might not want this behavior.

In order for a field to have a different value for each thread running, the simplest way is to decorate the static field with a ThreadStaticAttribute attribute.

[ThreadStaticAttribute]
public static int ThreadInfo;

If you never used this attribute here is piece of code that will prove that this really works:

class Program
    {
        static void Main(string[] args)
        {
            ParentClass.MySharedInfo = 5;

            for (int i = 1; i < 3; i++)
            {
                ParameterizedThreadStart pts = new ParameterizedThreadStart(RunTest);
                Thread t = new Thread(pts);

                t.Start(i * 10); 
        }

        }

        public static void RunTest(object val)
        {
            ParentClass.MySharedInfo = (int)val;

            ParentClass cp = new ParentClass();
            cp.Write();
            cp.ChildClass.Write();

            Thread.Sleep(1000);
            cp = new ParentClass();
            cp.Write();
            cp.ChildClass.Write();
        }
    }

    class ParentClass
    {
        [ThreadStaticAttribute]
        public static int MySharedInfo;

        public ChildClass ChildClass { get; set; }

        public ParentClass()
        {
            ChildClass = new ChildClass();    
        }

        public void Write()
        {
            Console.WriteLine("ParentClass ThreadId:{0} / MySharedInfo:{1}",
                Thread.CurrentThread.ManagedThreadId, MySharedInfo);
        }
    }

    class ChildClass
    {
        public void Write()
        {
            Console.WriteLine("ChildClass ThreadId:{0} / MySharedInfo:{1}", 
                Thread.CurrentThread.ManagedThreadId, ParentClass.MySharedInfo);
        }
    }

The code above defines two classes: ParentClass and ChildClass. ParentClass has a static field decorated with the ThreadStaticAttribute attribute and an instance of a ChildClass. The Main method set’s the static filed to 5. Then a loop will start two Threads and create a new ParentClass in each of them. The static field value is set to different values. The class will print the static field value from the ParentClass and from the ChildClass two times. Between the first and the second time the value is printed there is a Thread.Sleep of 1 second. This pause shows that each thread maintains it’s own value.

ToDataTable Method for Linq Queries Results

When you query a DataTable using Linq the normal result will be an IEnumerable, which is not a DataTable (obviously). If you need a DataTable as a result you already have an extension method called CopyToDataTable which will turn your IEnumerable into a new DataTable. Although if you want to join two DataTables and the merge the DataRows into a new Anonymous Type the CopyToDataTable will not help you. Let’s see how to create a helper method that will transform an IEnumerable of anonymous types into a new DataTable.

First let’s create two DataTables: Person and Job. Here’s the code:

DataTable dtPerson;
DataTable dtJob;

dtPerson= new DataTable("Person");
DataColumn dc;

dc = new DataColumn("Id", typeof(int));
dtPerson.Columns.Add(dc);

dc = new DataColumn("Name", typeof(string));
dtPerson.Columns.Add(dc);

dc = new DataColumn("Age", typeof(int));
dtPerson.Columns.Add(dc);

//JOB DataTable
dtJob = new DataTable("Job");

dc = new DataColumn("PersonId", typeof(int));
dtJob.Columns.Add(dc);

dc = new DataColumn("Position", typeof(string));
dtJob.Columns.Add(dc);

Here is the code to populate the DataTables:

DataRow dr = dtPerson.NewRow();
dr[0] = 1;
dr[1] = "Gabriel";
dr[2] = 31;
dtPerson.Rows.Add(dr);

dr = dtPerson.NewRow();
dr[0] = 2;
dr[1] = "Elisa";
dr[2] = 27;
dtPerson.Rows.Add(dr);

dr = dtJob.NewRow();
dr[0] = 1;
dr[1] = "Programmer";
dtJob.Rows.Add(dr);

dr = dtJob.NewRow();
dr[0] = 2;
dr[1] = "Manager";
dtJob.Rows.Add(dr);

Now let’s write a Linq query to join these two DataTables:

var query = from p in dtPerson.AsEnumerable()
             join j in dtJob.AsEnumerable() on p.Field<int>("Id") equals j.Field<int>("PersonId")
             select new
             {
                 Id = p.Field<int>("Id"),
                 Name = p.Field<string>("Name"),
                 Job = j.Field<string>("Position")
             };

Notice that the result of the query is an IEnumerable of an anonymous type with three properties (Id, Name and Position) which is a merge of our two DataTables data. Now for the helper method that will convert this result to a new DataTable. The base of this idea is in my previous article on using reflection on anonymous types. I’ll use this principle to inspect the properties of the anonymous type and create new DataColumns for the new DataTable. After that all it’s needed is iterating over the results creating new DataRows. Here’s the method:

public static DataTable ToDataTable(this IEnumerable objectList)
{
    //if the result is null or if the number of
    //objects is less then 1, return null
    if (objectList == null || 
        objectList.OfType<object>().Count() < 1)
    {
        return null;
    }
    //create a new list based on the IEnumerable
    List<object> list = new List<object>(objectList.OfType<object>());

    //take the first object in the list
    object o = list[0];
    //get the type of the object
    Type t = o.GetType();
    //read all the info of the properties
    PropertyInfo[] properties = t.GetProperties();

    DataTable dt = new DataTable();
    //for each property create a new column
    //in the DataTable
    foreach (var pi in properties)
    {
        //the new column has the name of the property
        //and it's type
        DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
        //add the column to the DataTable
        dt.Columns.Add(dc);
    }

    //add the rows to the DataTable
    foreach (var item in list)
    {
        DataRow dr = dt.NewRow();
        //each property represents a column 
        //that has to be set
        foreach (var pi in properties)
        {
            dr[pi.Name] = pi.GetValue(item, null);
        }
        dt.Rows.Add(dr);
    }
    return dt;
}

That’s it. The returning DataTable will have three columns (int Id, string Name, string Position). If you want you can download the code for the class here. In this code for download I transformed the ToDataTable method into an extension method.

Reflection on Anonymous Types

Using reflection on anonymous types is just like reflection on any other type.

Consider this simple anonymous object being instantiated:

var anonyObject = new
{
    Name = "Gabriel",
    Age = 31
};

If you want to know all the properties, it’s values and types you can query the object with the reflection classes like this:

//get the type of the anonymous object
Type anonyType = anonyObject.GetType();
//get all the properties info
PropertyInfo[] props = anonyType.GetProperties();
//display each of the properties info
foreach (var prop in props)
{
    Console.WriteLine("Name:{0}, Value:{1}, Type:{2}",prop.Name, 
        prop.GetValue(anonyObject, null), prop.PropertyType);
}

I just wanted to share this code because I’m going to use it in my next article in which I will talk about creating a helper method to transform the result from a Linq query that returns anonymous types to a DataTable.

Extension Methods

Extension methods are one of my favorite features of C# 3.0, they allow you to create new methods and plug them in classes already defined without having to derive them or even change it’s source code.

Everyone uses the DateTime class and a lot of those people have a class with handy methods to handle DateTime. Many of the handy methods would look better in the DateTime class but you can’t change it’s source code and you don’t want to derive from it and create a new DateTime class (of course). With extension methods you can plug these new methods in the DateTime class.

Let’s create a simple method named ’’‘DaysSince” that operates on two dates returning the number of days from one date to the other. The logic of the method is really simple:

    public static class DateUtil
    {
        public static int DaysSince(DateTime d1, DateTime d2)
        {
            TimeSpan ts = d1.Subtract(d2);
            return ts.Days;
        }
    }

You would use this class like this:

DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(DateUtil.DaysSince(today, pastDate);

My goal now is to be able to do this:

DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(today.DaysSince(pastDate));

To make this change just put a ’’‘this’’’ keyword in front of the first parameter of the static method. Now it should be like this:

public static class DateUtil
{
    public static int DaysSince(this DateTime d1, DateTime d2)
    {
        TimeSpan ts = d1.Subtract(d2);
        return ts.Days;
    }
}

That is it, you can now make a call to the DaysSince method from any DateTime instance variable.

Here a the rules for creating a ExtensionMethod:

  1. Create a public static class (you call call it anything you want)
  2. Create the method you want as a public static method
  3. The first parameter of the method must always the a ’’‘this’’’ keyword followed by the class you want to plug the method to and the name of the parameter
  4. Whenever you want to use the extension method the ’’‘namespace’’’ in which the class is into must be referenced

If you want to create a method ’’‘WeeksAgo’’’ that let you get a new DateTime x weeks before the a certain date all you need to do is this:

public static class DateUtil
{
    public static int DaysSince(this DateTime d1, DateTime d2)
    {
        TimeSpan ts = d1.Subtract(d2);
        return ts.Days;
    }
    public static DateTime WeeksAgo(this DateTime d1, int numberOfWeeks)
    {
        DateTime newDate = d1.AddDays(-numberOfWeeks * 7);
        return newDate;
    }
}

And then you can use it like this:

Console.WriteLine(today.WeeksAgo(2).ToString());

Really cool addition to your utility belt, isn’t it?

C# Custom Type Conversions

C# allows for implicit and explicit type conversion between classes when there is an inheritance situation. Something like this:

class BaseClass { }

    class DerivedFromBaseClass : BaseClass { }

    class Program
    {
        static void Main(string[] args)
        {
            BaseClass bc = new DerivedFromBaseClass(); //implicit conversion

            DerivedFromBaseClass dbc = (DerivedFromBaseClass)bc; //explicit conversion
        }
    }

Ok, this shouldn’t be anything new to know since this is a feature present in all object oriented languages I know. But now I want to talk about a stranger kind of conversion and for this I’ll have to mix apples and oranges.

Let’s define to classes: Apple and Orange.

class Apple
    {
        public string Farm { get; set; }

        public Apple(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an apple from the {0} farm", this.Farm);
        }

    }

    class Orange
    {
        public string Farm { get; set; }

        public Orange(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an orange from the {0} farm", this.Farm);
        }
    }

As you can see these two classes are totally unrelated, they don’t have any inheritance relation with each other.

Let’s convert Apples to Oranges using the cast-like sintax. This is possible using the keywords ’’‘operator’’’, ’’‘explicit’’’ in a static method that will do the conversion. Here are the changes to the Apple class so that it can be converted explicitly to an Orange.

class Apple
    {
        public string Farm { get; set; }

        public Apple(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an apple from the {0} farm", this.Farm);
        }

        public static explicit operator Apple(Orange o)
        {
            Apple a = new Apple(o.Farm);
            return a;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Orange o = new Orange("GreatSouth");
            Console.WriteLine(o.ToString());

            Apple a = (Apple)o; //explicit conversion
            Console.WriteLine(a.ToString());
        }
    }

Ok, it works. You can also do an implicit conversion but in this case you must be aware that it will also create (automatically) the explicit conversion. This is why you can’t define both these conversions in the same class. Following is the changes necessary to the Orange class so that you can make implicit and explicit conversions from Apples to Oranges:

class Orange
    {
        public string Farm { get; set; }

        public Orange(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an orange from the {0} farm", this.Farm);
        }

        //this will allow implicit and explicit conversion
        public static implicit operator Orange(Apple a)
        {
            Orange o = new Orange(a.Farm);
            return o;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Apple a = new Apple("GreatSouth");
            Console.WriteLine(a.ToString());

            Orange o = a; //implicit
            Console.WriteLine(o.ToString());

            //or you could do it like this
            o = (Orange)a; //explicit
            Console.WriteLine(o.ToString());
        }
    }

I hope you found this interesting. Once again a know that my examples are not always the most thought out but I’m certain that you got the idea and will be able to put it work in a real life situation.

Understanding how yield keyword works

If you work with C# you must know that in order to traverse a collection using the ‘foreach’ construct the collection must implement the IEnumerable interface. There’s a lot of documentation about that on the web so I won’t go into it. What I’d like to show you is an alternative to the IEnumerable interface using the ‘yield’ keyword. Take a look at this code:

public class Player
    {
        public string Name { get; set; }

        public Player(string name)
        {
            this.Name = name;
        }
    }

    public class Team
    {
        Player[] players = new Player[3];

        public Team()
        {
            players[0] = new Player("Gabriel");
            players[1] = new Player("Elisa");
            players[2] = new Player("Rafaela");
        }

        public IEnumerator GetEnumerator()
        {
            foreach (Player player in players)
            {
                yield return player;
            }
        }
    }

You can now test the code in a foreach like this:

 public static void TestYield()
        {
            Team team = new Team();
            foreach (Player player in team)
            {
                Console.WriteLine(player.Name);
            }
        }

This is really interesting, right? But how does it work? Shouldn’t the iteration through the players array start from scratch every time you call the method? Nope! This is where the magic of the yield comes in. Every time the yield is executed it will “pause the state” of the iteration and the next time the method is called it will resume the iteration from the next item. I could even rewrite my code in the following way and it would have the same effect:

public IEnumerator GetEnumerator()
        {
            yield return players[0];
            yield return players[1];
            yield return players[2];
        }

This code is only for demonstration purposes, I know that iterating the array like this wouldn’t be very smart :-) I just wanted to show you that the execution will pause.

This woks because in compile time the method using the yield will be transformed into a class which implements the IEnumerator interace and it’s stated will be maintained like any other object, that is why you get the impression the method is paused. It’s cool to understand how these things work under the hood, isn’t it?

Get the number of business days between two dates

Here’s a simple way of getting the number of business days between two dates using C#.

DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) && (dtBegin.DayOfWeek != DayOfWeek.Sunday))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }

You can enhance this method consulting a list of holidays to check if the current date is indeed a business day. For this you have to have the list of holidays somewhere. In our example I’ll create a fake method that will provide the holidays list.

public static void CalculateNumberOfWeekdays()
        {
            DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);
            List<DateTime> holidays = GetHolidays();

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) 
                    && (dtBegin.DayOfWeek != DayOfWeek.Sunday)
                    && (!holidays.Contains(dtBegin)))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }
            Console.WriteLine(dayCount);
        }

        public static List<DateTime> GetHolidays()
        {
            List<DateTime> holidays = new List<DateTime>();
            holidays.Add(new DateTime(2008, 8, 7));
            return holidays;
        }            

See you next time.

Design Pattern: Singleton

This is the first post on a series about Design Patterns using C#. I will not publish all the articles in a sequence but you can expect from time to time to have a new post about some pattern.

The first pattern I want to talk about is the Singleton.

Objective

You need a singleton when your application require one and only one instance of a single class and also that this instance can be accessed whenever necessary.

Case Scenario

Imagine that you want a Logger class that will store all messages in a internal list. You need the hold the all the messages in a single place. If you had more than one instance of a Logger class you would have the messages scattered over the various instances. To avoid this will use a singleton.

The Solution

We are going to create a Logger class in our example.

The first issue the singleton should handle is how to prevent users from creating multiple instances of a class. To achieve this you have to block (hide) the constructor. This can be done making it private.

private Logger() { }

Now the that the constructor is private how can you instantiate the class? You are right, you can’t do it from outside the class so we are going to do it from the inside. Since we need to keep the one instance we create we need a variable to hold it. We are going to declare this variable as static so that we don’t need the class to be instantiated in order to keep the value.

//this will hold our unique instance
private static Logger instance = null;

The next step is to come up with a way to create the only instance and at the same time gain Access to that instance. This can be done using a static method that will check the instance variable and if it is null it will create a new instance and return it, if it’s not null it will return the previously create instance.

public static Logger Instance()
        {
            //if the instance is null you have to instantiate it
            if (instance == null)
            {
                instance = new Logger();
            }
            return instance;
        }

This is all we need for our singleton but we still need to add the functionality for the Logger class. We need a list to store the messages, a method to add new messages and a method to print all the messages already stored. Here is the code for it:

//holds all the messages
        private List<string> messages = new List<string>();

        //add a new message to the Logger
        public void Log(string message)
        {
            messages.Add(message);
        }

        public void PrintAllMessages()
        {
            foreach (string message in messages)
            {
                Console.WriteLine(message);
            }
        }

Here is the code for the whole class:

public class Logger
    {
        private static Logger instance = null;

        private Logger() { }

        public static Logger Instance()
        {
            //if the instance is null you have to instantiate it
            if (instance == null)
            {
                instance = new Logger();
            }
            return instance;
        }

        //holds all the messages
        private List<string> messages = new List<string>();

        //add a new message to the Logger
        public void Log(string message)
        {
            messages.Add(message);
        }

        public void PrintAllMessages()
        {
            foreach (string message in messages)
            {
                Console.WriteLine(message);
            }
        }
    }

How to use it

Using the singleton is easy, the only difference from normal class use is that when you need an instance of the object you will not be able to call the constructor (it’s private now) so you need to request an instance through the Instance() method that we created.

In our usage examples I’ll declare two logger variables and pass different messages to each one. Since there’s only one instance both these variables will have references to the same object. This can be verified when you call the PrintAllMessages method of any of the loggers. You’ll notice that they will print all the messages that were passed to any of the variables.

Here is the code so you can test it at home:

 class Program
    {
        static void Main(string[] args)
        {
            Logger logger1 = Logger.Instance();
            Logger logger2 = Logger.Instance();

            logger1.Log("loading one");
            logger2.Log("loading two");

            logger1.Log("Success");
            logger2.Log("Failure");

            logger1.PrintAllMessages();
        }
    }

That’s it for the Singleton, I hope this is useful to someone somewhere :-)