Sammy Ageil

Disambiguation of Technologies

Using Factory method pattern in .Net

The sole purpose of design patterns is to provide an object oriented based solution to known problems. Another reason to use design pattern is to solve a common programming challenges regarding re-usability and maintainability. The motivation behind the factory method pattern is clear, it simply builds objects when the object hierarchy is clearly defined.

The factory building process is often aided by using parameters, the parameters are used to determine the type of object the client is requesting. Of course having parameters is not a requirement.

Reasons to use a factory pattern:
  1. When your object hierarchy is clearly defined
  2. When the client (any client) doesn’t know the concrete type to initialize at runtime
  3. When the object's creating logic is complicated
Use case:

To further examine the benefits of using the factory method pattern, we will create a use case and work through the requirements using a windows form application. Our client is an HR organization with the following easy requirements for an HR application:

  1. Needs to be able to create employee records (Manager, SalesPerson and HelpDeskAnalyst)
  2. All employees have a Title and vacation days (for the purpose of this demo, all human rights and labor laws will be violated as we are not paying these employees)
  3. HR personnel need to be able to enter an employee title to create the employee
  4. Managers have 4 week vacation days, SalesPersons have a 2 week vacation days and HelpDeskAnalyst employee gets 3 week vacation days
  5. Client will need to be able to add additional employee types as the business grows
The no thought process solution to solving our domain problem:

As mentioned above, the requirements are rudimentary at best, the easiest way to comply with the clients requirements is by writing the following solution.

For this demo, we will create a windows form project and add the following classes

  1. The base abstract Employee class (you can choose to create an interface if you like)

    public abstract class Employee
    {
       public  virtual string Title { get{ return "Employee";}}
       public  abstract int VacationDays { get; }
     
    }
  2. The HelpDeskAnalyst class (note that it inherits from Employee)

    public class HelpDeskAnalyst : Employee
     {
         public override  string Title
         {
             get
             {
                 return "Help Desk Analsty";
             }
         }
         public override int VacationDays
         {
             get
             {
                 return 15;
             }
         }
        
     }
  3. The Manager class

    public class Manager : Employee
     {
         public  override string Title
         {
             get
             {
                 return "Manager";
             }
         }
         public override int VacationDays
         {
             get
             {
                 return 20;
             }
         }
     }
  4. The SalesPerson class

    public class SalesPerson : Employee
     {
         public override string Title
         {
             get
             {
                 return "Sales Person";
             }
         }
         public override  int VacationDays
         {
             get
             {
                 return 10;
             }
         }
     }
  5. Finally, the client code (used inside a click event)

    private void CreateButton_Click(object sender, EventArgs e)
           {
               var userInput = UserInputTextBox.Text.ToLowerInvariant();
               Employee employee;
               switch (userInput)
               {
                   case "manager":
                       employee = new Manager();
                       break;
                   case "helpdeskanalyst":
                       employee = new HelpDeskAnalyst();
                       break;
                   case "salesperson":
                       employee = new SalesPerson();
                       break;
                   default:
                       employee = null;
                       break;
               }
               Display(employee, userInput);
           }
           void Display(Employee employee, string userInput)
           {
               DisplayLabel.Text = employee == null ? "failed to create employee using provided title" + userInput : string.Format("Employee Title is {0} and Employee Vacation Days are {1}", employee.Title, employee.VacationDays);
           }

So what’s wrong with this implementation?

Some may argue nothing, the code builds and fulfill the client requirements and they would be right, if we were living in procedural programming age. But we are aiming to apply OOP principles and create reusable components without any of this tight coupling.

Factories to the rescue :

We will refactor our existing solution to use a factory to create the employee and apply OOP SOLID principles. First, we will create a factory interface (IEmloyeeFactory), this interface will contain a single method returning an employee object.

Here s what a factory method UML should look like

The factory Interface and implementation:

public interface IEmployeeFactory
 {
     Employee CreateEmployee(string title);
 }
 public class EmployeeFactory : IEmployeeFactory
 {
     private static readonly ConcurrentDictionary<string, Type> dictionary = new ConcurrentDictionary<string, Type>();
     static EmployeeFactory()
     {
         var employeeSubTypes = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsSubclassOf(typeof(Employee)));
         foreach (var type in employeeSubTypes)
         {
             dictionary.TryAdd(type.Name.ToLowerInvariant(), type);
         }
     }
     public  Employee CreateEmployee(string title)
     {
         var result =  (dictionary.Where(e => String.Compare(e.Key, title, false) == 0).Select(e => e.Value)).FirstOrDefault();
         return result != null ? (Employee) Activator.CreateInstance(result) : null;
     }
 }

If you don't understand the reason behind initializing the dictionary in a static constructor, Read the post titled "Understanding Constructors in .Net"

After adding the IEmployeeFactory interface and implementing it, our client (the button's click event) looks like this:

private void CreateButton_Click(object sender, EventArgs e)
    {
        var userInput = UserInputTextBox.Text.ToLowerInvariant();
        IEmployeeFactory factory = new EmployeeFactory();
        var emp = factory.CreateEmployee(userInput);
      Display(emp, userInput);
    }
What did we achieve?

By redesigning our solution to use a factory pattern approach we achieved the following:

  1. Loose coupling, our client doesn't know what kind of employee is used
  2. Open Closed Principle doesn't need to be violated as we can extend our factory with modifying the current ones
  3. Extensibility, we can add additional employee types without having to modify any of the existing code and our application will work
download and experiment with the demo used (56.1KB)

All about the Lazy<T> Data Structure in C# .Net

.Net Lazy<T> is a type which describes one of many ways the framework deals and stores data structures. Confused? Let’s define and differentiate these two.

A data structure is an abstract description of a way of organizing / structuring data to allow specific operations on it to be performed efficiently, data structures are always made up of types and or other structures.

A type on the other hand is just concrete representation of an object, its’ properties and operations/methods. In order to understand the Lazy data structure we have to familiarize ourselves with its benefits and limitations.

The benefits:

So, what does using Lazy provide us with? Why should we use it?

Lazy<T> provides us with a clean out of the box way to differ loading an object until a time which it’s needed. This could be extremely beneficial if the object’s operations involves creating or utilizing expensive resources (high CPU usage, I.O operations or Ram allocation etc.)

Consider this Student class example:

public  class Student
 {
     public int Id { get; set; }
     public Student()
     {
         //Thread.Sleep(5000);
     }
     public Student(int id)
     {
         Id = id;
     }
 }

This is just a simple student class we will use to demonstrate some Laziness (Good laziness of course).

Talk is cheap, let create some unit tests. I will use Xunit to create a few unit tests to test the following:

  1. Test the Laziness of a Lazy<T>
  2. Test Lazy<T> thread safety

First, we test the laziness of this type, the following test will pass because the IsValueCreated returns false before we assign Value property of the Lazy<T>.

[Fact]
public void Should_CreateLazyStudent_Using_Default_Constructor_And_Return_False()
{
   var lazyStudent = new Lazy<Student>();
   var  loaded = lazyStudent.IsValueCreated;
   Assert.False(loaded);
}

In the next test, we will prove that the Lazy<T> doesn't get created before it Value is used or assigned to a variable.

 [Fact]
public void Should_CreateLazyStudent_Using_Default_Constructor_And_Return_True()
{
    var lazyStudent = new Lazy<Student>();
    var value = lazyStudent.Value;
   var loaded = lazyStudent.IsValueCreated;
    Assert.True(loaded);
}

Both tests clearly demonstrate the true Laziness of the Lazy<T> type. You can further prove that by placing a debug breakpoint in the Student class constructor during the tests and run the test in debug mode (constructor will only be called using the second test when we attempt to use the Value property).

Lazy<T> Thread safety:

It's critical to understand that Lazy<T> is default thread safe, this doesn't mean your T properties and methods also thread safe.Ensuring thread safety of all properties and methods are the developer's responsibility.

Another way to specify thread safety and how a Lazy instance synchronizes access among multiple threads is by using LazyThreadSafetyMode enumeration.

In our next three unit tests, we will use all of these enumerations.

Since we are testing thread safety, you need to uncomment the Thread.Sleep(5000); line in the Student class constructor before running the thread safety tests.

The first one to use is LazyThreadSafetyMode.None.Using None basically means we don't want any thread safety, this should be OK to use if are sure that only one thread can access the value of T.

    [Fact]
    public void Should_Create_ThreadSafe_LazyStudent_Using_LazyThreadSafetyMode_None()
    {
        var lazyStudent = new Lazy<Student>(LazyThreadSafetyMode.None);
        //alternatively, you can use false instead of LazyThreadSafetyMode.None
        //var lazyStudent = new Lazy<Student>(false);
        var students = new ConcurrentBag<Task<Student>>();
      Task.Run(  () =>
        {
            Parallel.For(0, 2, i =>
            {
                students.Add(Task.Run(() => lazyStudent.Value));
            });
        }).Wait();
            var areEqual =  object.ReferenceEquals(students.First().Result, students.Last().Result);
            Assert.True(areEqual);
    }

Because we set ThreadSatetyMode to None, the above test fails as the code will try to create two students in a multi-threaded manner without any thread safety.

Next unit test will test LazyThreadSafetyMode.ExecutionAndPublication.

LazyThreadSafetyMode.ExecutionAndPublication guarantees only one instance of T is created, the same instance will always be returned to the caller.

[Fact]
public void Should_Create_ThreadSafe_LazyStudent_Using_LazyThreadSafetyMode_ExecutionAndPublication()
    {
        var lazyStudent = new Lazy<Student>(LazyThreadSafetyMode.ExecutionAndPublication);
        var students = new ConcurrentBag<Task<Student>>();
        Task.Run(() =>
        {
            Parallel.For(0, 2, i =>
            {
                students.Add(Task.Run(() => lazyStudent.Value));
            });
        }).Wait();
        var areEqual = object.ReferenceEquals(students.First().Result, students.Last().Result);
        Assert.True(areEqual);
    }

If you place a debug breakpoint in the Student constructor you will see that it will only be called once.

The last enumeration to test is LazyThreadSafetyMode.PublicationOnly. Unlike ExecutionAndPublication when multiple threads try to initialize a Lazy<T> instance simultaneously using PublicationOnly, all threads are allowed to run the initialization method or constructor, However, the first thread to complete the initialization wins and it's instance is returned to all callers.If you place a debug breakpoint on the Student constructor, you will see that its called multiple times, However, we can prove that the same instance is returned to caller (our test method) by comparing both instance using object.ReferenceEquals and the comparison always return true.

[Fact]
public void Should_Create_ThreadSafe_LazyStudent_Using_LazyThreadSafetyMode_PublicationOnly()
{
    var student = new Lazy<Student>( LazyThreadSafetyMode.PublicationOnly);
    var concurrentBad = new ConcurrentBag<Task<Student>>();
    Task.Run(() =>
    {
        Parallel.For(0, 2, loop => concurrentBad.Add(Task.Run(() => student.Value)));
    }).Wait();
    var areEqual = object.ReferenceEquals(concurrentBad.First().Result, concurrentBad.Last().Result);
    Assert.True(areEqual);
}

Finally, there is an alternative way to create a Lazy<T>, you can use a Func<out TResult>. like so:

Func<Student> initStudent = () =>
{
    return new Student();
};
[Fact]
public void Should_Create_ThreadSafe_LazyStudent_Using_Using_Initialization_Method()
{
    var lazyStudent = new Lazy<Student>(() => initStudent(), LazyThreadSafetyMode.None);
    var students = new ConcurrentBag<Task<Student>>();
    Task.Run(() =>
    {
        Parallel.For(0, 2, i =>
        {
            students.Add(Task.Run(() => lazyStudent.Value));
        });
    }).Wait();
    var areEqual = object.ReferenceEquals(students.First().Result, students.Last().Result);
    Assert.True(areEqual);
}

If you run this unit test in debug mode, you will see that it throws an exception with the following message "ValueFactory attempted to access the Value property of this instance". The reason for the exception is obvious, we are using LazyThreadSafetyMode.None and we have a race condition resulting from the two threads created in Parallel loop. Using as initialization method causes the Lazy<T> to cache exceptions (see final thoughts).

Final thoughts

Microsoft Lazy<T> documentation states that In addition to specifying the thread safety of a Lazy<T> instance, the LazyThreadSafetyMode enumeration affects exception caching. When exceptions are cached for a Lazy instance, you get only one chance to initialize the instance.If an exception is thrown the first time you call the Lazy<T>.Value property, that exception is cached and rethrown on all subsequent calls to the Lazy<T>.Value property. The advantage of caching exceptions is that any two threads always get the same result, even when errors occur.When you specify the PublicationOnly mode, exceptions are never cached. When you specify None or ExecutionAndPublication, caching depends on whether you specify an initialization method or allow the default constructor for T to be used. Specifying an initialization method enables exception caching for these two modes. If you use a constructor that does not specify an initialization method, exceptions that are thrown by the default constructor for T are not cached.

All duplicate code was removed from the sample application Download, unzip the file and start your own experiments.

Any thoughts? hit the comment box.

Using Visitor Pattern with reflection in .Net

In my previous visitor pattern post constraints section, I wrote about the ability to mitigate the limitation of the visitor pattern using reflection.

Since then, I have gotten a few emails requesting refactoring the sample application to show how and what should be refactored.

These are the steps I took to refactor the application:

  1. Refactor IVisitor interface to the following:

    public interface IVisitor
    {
        void Visit(object @object);
    }
  2. Move the visit method from USDVisitor to VisitorBase class and add some reflection logic to read and write the IVisitor's properties (addition is highlighted in yellow)

    public abstract class VisitorBase : IVisitor
      {
          public Dictionary<string, decimal> Converted { get; set; }
          public virtual string FromCurrency { get; set; }
          public virtual string ToCurrency { get; set; }
          public string ConversionServiceURL
          {
              get
              {
                  return string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X",
                      FromCurrency.ToUpper(), ToCurrency.ToUpper());
              }
              set
              {
                  ConversionServiceURL = value;
              }
          }
          protected VisitorBase()
          {
              if (Converted == null)
              {
                  Converted = new Dictionary<string, decimal>();
              }
          }
          public virtual async Task GetCurrencyExchangeAsync(decimal exchange, Action<decimal> action)
          {
              try
              {
                  decimal converted = 0.0m;
                  var client = new WebClient();
                  string result = await client.DownloadStringTaskAsync(ConversionServiceURL);
                  var split = result.Split(',');
                  if ( split.Length >= 0)
                  {
                      decimal rate;
                      if (Decimal.TryParse(split[1], out rate))
                      {
                          converted = rate * exchange;
                      }
                  }
                  action(converted);
              }
              catch (WebException ex)
              {
                  Console.Write(ex.Message);
              }
          }
          private PropertyInfo GetProperty(object @object, string propertyName)
          {
              var props = @object.GetType().GetProperties();
              return   props.FirstOrDefault(x => x.Name == propertyName);
          }
          public async void Visit(object @object)
          {
              FromCurrency = (string) GetProperty(@object, "PurchaseCurrency").GetValue(@object);
              var totalPurchaseValue = (decimal)GetProperty(@object, "TotalPurchaseValue").
    GetValue(@object); await GetCurrencyExchangeAsync((decimal)totalPurchaseValue, ConvertedValue => { var totalpurchaseConvertedProp = GetProperty(@object, "TotalPurchaseConverted"); totalpurchaseConvertedProp. SetValue(@object, Convert.ChangeType(totalPurchaseValue,
    totalpurchaseConvertedProp.PropertyType)); Converted.Add(@object.GetType().Name, ConvertedValue); }).ConfigureAwait(false); } }
  3. This is the USDVisitor after refactoring:

    public class USDVisitor : VisitorBase
    {
        public override string ToCurrency
        {
            get
            {
                return "USD";
            }
            set
            {
                base.ToCurrency = value;
            }
        }
    }

The below UML diagram models our sample application after refactoring.


By using reflection we can now add as many visitors to the application without having to add additional visit methods for to handle them.

Download the refactored app (2.1MB)

If you have any comments or need further clarification, hit the comment box and I will respond as soon as I can.

Add syntax highlighting to Blogengine.net 2.9 using CSS3 and jQuery

Accidents happen!!. That is what I was told by my previous host after they failed to recover my blog’s data from their SQL Server after it suffered a catastrophic failure. Considering this was the second time and I am not being interested in having the pleasure of experiencing another accident, I moved the blog to a different hosting provider.

With that comes the task of having to recreate all posts (I had performed some backup after the first “accident”). Since I was happy with Blogengine.Net prior to the data loss, I didn't see a reason to switch to a different blogging engine (that may not true as I considered writing my own engine in Mono and hosting it at home on a Linux server, I then changed my mind due to ISP’s EULA) .

I downloaded BE 2.9 then realized that the engine has gone through a major overhaul. There are some great and not so great changes:

Great things:

  1. Use of Angularjs
  2. HTML5 is heavily used
  3. CSS3 is used
  4. Mobile ready (using twitter bootstrap)

Not so great:

  1. TinyMCE editor not used (uses bootstrap-wysiwyg)
  2. syntaxhighlighter.js was removed from the engine

I can live with the new editor, its light weight and easy on the eyes. However, having no syntax highlighting in development driven blog made me realize how much I missed Sytaxhighter.js so I decided to crap my won using CSS3, jQuery and Visual Studio Productivity Power Tools.

These are steps taken to allow syntax highlighting as its shown on this blog:

  1. Downloaded VS.NET Power tools from Here
  2. Configured the tool to set a CSS class on the copied code (in VS.NET go to tools, Options, Productivity Power Tools)
  3. Add the following CSS3 into main.css in BE’s standard template (or whatever template you use). Note the use of !important here? we want to override whatever the default templates provide
    pre {
           border: 1px solid #367136;
           border-radius: 4px !important;
           counter-reset: line-numbering !important;
           height: auto;
           max-height: 500px;
           overflow: auto;
           padding: 10px 5px 5px;
           white-space: pre !important;
           word-break: normal !important;
           word-wrap: normal !important;
       }
     
           pre .line:before {
               /*CSS3 line numbering*/
               content: counter(line-numbering, decimal) !important;
               counter-increment: line-numbering !important;
               padding-right: 2em !important;
               text-align: right !important;
               width: 1.5em !important;
           }
     
       .linenum {
           background-color: #F1F1F1;
           border-right: 5px solid #6CE26C;
           color: #000000;
           display: inline-block;
           width: 2em !important;
       }
  4. In the master.master file of your template add the following jQuery snippet
    <script>
            $(function () {
                $("pre.code").html(function (index, html) {
                    return html.replace(/^(.*)$/mg, "<span class=\"linenum\"><span class=\"line\">$1</span></span>");
                });
            });
        </script>

That’s it, now you have syntax highlighting with line numbering without having to download an external JavaScript library.

Measure code performance using an Action in .Net

One of my favorite duties at work is performing code reviews, I find the process instrumental in identifying opportunities for improvements regardless of the team / organization size or its available skill sets.

There is an abundance of reasons to start performing code reviews and none to prevent.

Reasons to perform code reviews are:

  1. Code Quality, reviewers ensure quality of code committed.
  2. Mentoring, code reviews are the best to tool to help team identify developers' areas of improvements.
  3. Team familiarity, teams will know each others strengths and know where to go and who to ask for help.
  4. Defect rate reduction, chances of having defects in reviewed code are much smaller than in unreviewed code (we all make mistakes).

Smart bear Software have written an excellent & free book on code reviews, you can see it Here

Today, I wanted to measure the performance of some Parallel function submitted by one of our developers and found myself writing this Action. The action takes another action as a parameter, runs it while writing the performance measures to Visual Studio.Net output window

public static Action<Action> PerformanceCalculator = ((action) =>
{
    var watch = new Stopwatch();
    watch.Start();
    Debug.Write(string.Format("Started Stopwach at {0} ", DateTime.Now), action.Method.Name);
    action();
    watch.Stop();
    Debug.Write(string.Format("Stopped Stopwach at {0} ", DateTime.Now), action.Method.Name);
    Debug.Write(string.Format("Total execution time in TotalMilliseconds is {0} ", watch.Elapsed.TotalMilliseconds), action.Method.Name);
});

The last Debug.Write call will contain the method's total time consumption in milliseconds. That's it, short and sweet. You utilize this to measure performance of any C# call.

PerformanceCalculator(WriteThreadSafeBuffer);

Create a lazy task in .Net

Lazy initialization is a practice whereby you only load or initialize an object when you first need it. This means the object initialization is deferred until the first time it’s used.

In our development world this can be extremely beneficial when we have expensive resources and or components to initialize like a database connection or accessing the file system to read, write or edit a file.

Framework 4.0 introduced the Lazy<T> Type, This type allows us to create an object and defer its initialization until we need it (Singleton Pattern type construct). One of the main advantage of the Lazy<T> is the ability to specify a Func<T> to server as factory design pattern method as well as specifying if the Lazy<T> should be treated as a thread safe object or not.

Here is an example to demonstrate lazy tasks in C#:

Func<string, string> TextFileReader = (fileName ) =>
            {
                var stringBuilder = new StringBuilder();
                using (var streamreader = new StreamReader(fileName))
                {
                    string line;
                    while ((line = streamreader.ReadLine()) != null)
                    {
                        stringBuilder.AppendLine(line);
                    }
                }
                return  stringBuilder.ToString();
            };

There is nothing fancy or over complicated here; We have a func that accept a string (filename) and return a string (the content of the file).

The next snippet will create a Lazy<task<string>> to read the file and use it's content:

var lazyreaderTask = new Lazy<Task<string>>(() =>
           Task<string>.Factory.StartNew(() =>
           TextFileReader(@"E:\Demo.txt")), true);
           Console.WriteLine("Is value created? {0}", lazyreaderTask.IsValueCreated);
           Console.WriteLine("Result from task {0}", lazyreaderTask.Value.Result);
           Console.WriteLine("After exectuting the task {0}", lazyreaderTask.IsValueCreated);

If you comment line 5 in the above snippet, you will notice that the lazy task hasn't executed (IsValueCreated=false).Lazy<T> will executes only when is Value is called.

The final thing to note here is the true parameter on line 3, this parameter is used to set the lazy object as thread safe