donderdag 21 februari 2013

Fluent builder pattern

In this article we'll see how we can construct an object in a fluent way. This pattern is called Fluent Builder or Fluent interface.

In the previous article I've refactored a class that does too much, into a class that does one thing (Single Responsibility Principle). Now we take a look at how we can improve a specific part of the code with the Fluent Builder pattern.

This is the class we start with:


public class SourceXDocumentCreator
{
   public XDocument AddMetadata(XDocument xdoc, string metadata)
   {
      // Add metadata to XDocument
      // return XDocument
   }

   public XDocument AddHeader(XDocument xdoc, string title)
   {
      // Add header with title  to XDocument
      // return XDocument
   }

   public XDocument AddLogo(XDocument xdoc, string name,
                            double width, double height)
   {
      // Add logo to XDocument
      // return XDocument
   }

   // etc.
}

If we call this class to create a SourceXDocument, it could look like this:

var xdoc = GetXDocumentById(1);
var creator = new SourceXDocumentCreator();
xdoc = creator.AddMetadata(xdoc, metadata);
xdoc = creator.AddHeader(xdoc, "This is the title");
xdoc = creator.AddLogo(xdoc, "name", 7.2, 4.3);

As you can see every first variable of each method call is xdoc. If we need that variable in each method, we can just as well add it to the constructor of SourceXDocumentCreator:

public class SourceXDocumentCreator
{
   private XDocument _xdoc;

   public SourceXDocumentCreator(XDocument xdoc)
   {
      _xdoc = xdoc;
   }

   public XDocument AddMetadata(string metadata)
   {
      // Add metadata to _xdoc
      // return _xdoc
   }

   public XDocument AddHeader(string title)
   {
      // Add header with title to _xdoc
      // return _xdoc
   }

   public XDocument AddLogo(string name, double width,
                            double height)
   {
      // Add logo to _xdoc
      // return _xdoc
   }

   // etc.
}

Now we have the private variable _xdoc, it's not neccesary anymore to pass xdoc to each and every method. And we can use SourceXDocumentCreator like this:

var xdoc = GetXDocumentById(1);
var creator = new SourceXDocumentCreator(xdoc);
xdoc = creator.AddMetadata(metadata);
xdoc = creator.AddHeader("This is the title");
xdoc = creator.AddLogo("name", 7.2, 4.3);

This looks a lot cleaner, but still we can reduce the amount of code we need. We actually only need the final xdoc, and not semi-finished product:

var xdoc GetXDocumentById(1);
var creator = new SourceXDocumentCreator(xdoc);
creator.AddMetadata(metadata);
creator.AddHeader("This is the title");
xdoc = creator.AddLogo("name", 7.2, 4.3);

And now only the creator variable is redundant. But we can reduce that too, like this:

var xdoc GetXDocumentById(1);
var creator = new SourceXDocumentCreator(xdoc)
   .AddMetadata(metadata)
   .AddHeader("This is the title")
   .AddLogo("name", 7.2, 4.3)
   .Build();

For the code above to work, we have to change our SourceXDocumentCreator class, so each of the 'add'-methods returns the current instance of SourceXDocumentCreator:


public class SourceXDocumentCreator
{
   private XDocument _xdoc;


   public SourceXDocumentCreator(XDocument xdoc)
   {
      _xdoc = xdoc;
   }

   public SourceXDocumentCreator AddMetadata(string metadata)
   {
      // Add metadata to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddHeader(string title)
   {
      // Add header with title to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddLogo(string name,
                                         double width,
                                         double height)
   {
      // Add logo to _xdoc
      return this;
   }

   public XDocument Build()
   {
      return _xdoc;
   }

}

Because each Add-method returns and instance of SourceXDocumentCreator, we can call another Add-method on it again:


var creator = new SourceXDocumentCreator(xdoc)
   .AddMetadata(metadata)
   .AddHeader("This is the title");

And we can continue to call some other methoda:

creator = creator
   .AddLogo("name", 7.2, 4.3)
   .WithSomethingElse()
   .AndAnotherThing()
   .ThisToo();

But how do we get the final XDocument of each method returns an instance of SourceXDocumentCreator? for this, we add a public Build method, which returns the _xdoc variable. And to complete that class, we rename it to SourceXDocumentBuilder, to express better that the fluent builder  pattern is used.

This is the final SourceXDocumentBuilder:


public class SourceXDocumentBuilder
{
   private XDocument _xdoc;

   public SourceXDocumentCreator(XDocument xdoc)
   {
      _xdoc = xdoc;
   }

   public SourceXDocumentCreator AddMetadata(string metadata)
   {
      // Add metadata to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddHeader(string title)
   {
      // Add header with title to _xdoc
      return this;
   }

   public SourceXDocumentCreator AddLogo(string name,
                                         double width,
                                         double height)
   {
      // Add logo to _xdoc
      return this;
   }

   public XDocument Build()
   {
      return _xdoc;
   }
}


dinsdag 19 februari 2013

Single responsibility principle


At the current project I'm working on we've made a class with one of the most meaningless names I've ever encountered: Preprocessor. It's used to combine different parts of xml into a final xml document, but you probably can not tell that by the name of it. This class has two problems that I'll write about: it has a bad name, and it does too much so we couldn't find a good name for it.

public class Preprocessor
{
   public PreprocesResult Proces(PreprocesInput preprocesInput)
   {
   }
}


Preprocessor is a bad name for our class, because it doesn't mean anything in our domain. If we were building a system that had something to do with audio or video, then preprocessor maybe wouldn't be a terrible name. But we are building a system that manages documents and publications and the workflow involved. And the name preprocessor doesn't say anything about what is being processed, or how, or what the output will be. Is it preprocessing documents, or publications or something else?

XmlPreprocessor would be a better name. Still not good, but at least it would say what is being processed.

If multiple parts of xml would be put together, then XmlJoiner would be a better name, or XmlCombiner.

Why couldn't we choose a good name for our class? Because this class does too much. This is a list of things the class does when you call the Process() merhod:


  • Add Metadata to the given XML document;
  • Add header element to the given XML document;
  • Get all referenced to images from content, get image data from database and disk;
  • Calculate width/height ratio from image;
  • Change image-values in the given XML document;
  • Get organisation that created the given XML document;
  • Get logo image of organisation, save to temp folder and save reference to database;
  • Calculate width/height ratio from image;
  • Add Logo-element to the given XML document;
  • Get XSL file from disk;
  • Execute XSL transformation on the given XML document;
  • Save final version of the created XML document to temp folder and save reference to database.

As you can see the class does quite a few different things. Some are related to xml, some are related to getting data from disk or a database and some are related to calculating things like width/height ratio. And all are necessary to create the final XML document. But not all things should be put in one class. Let's look at every function of the class that is really related to modifying XML:


  • Add Metadata to XML;
  • Add header element to XML;
  • Get organisation that created the document;
  • Get logo image of organisation, save to temp folder and save reference to database;
  • Calculate width/height ratio from image;
  • Add Logo-element to XML;
  • Get all referenced to images from content, get image data from database and disk;
  • Calculate width/height ratio from image;
  • Change image-values in XML;
  • Get XSL file from disk;
  • Execute XSL transformation;
  • Save final version of XML to temp folder and save reference to database;


Now that we've identified the functions that are related to XML we can put them into another class:

public class SourceXDocumentCreator
{
   public XDocument AddMetadata(XDocument xdoc, string metadata)
   {
      // Add metadata to XDocument
      // return XDocument
   }

   public XDocument AddHeader(XDocument xdoc, string title)
   {
      // Add header with title  to XDocument
      // return XDocument
   }

   public XDocument AddLogo(XDocument xdoc, string name,
                            double width, double height)
   {
      // Add logo to XDocument
      // return XDocument
   }

   // etc.
}

The name is much better now, as it clearly states that the class can be used to create some Source XML Document. (There probably are alternatives that are even better.)

If we ever need to extend or modify the SourceXDocumentCreator class, it's much easier to decide how to do it. As it's evident that saving or loading files from disk or database shouldn't be in there, opposed to the first class Preprocessor, which did exactly that and much more.
Also calculating ratio's doesn't belong in SourceXDocumentCreator.
But adding an element to the underlying XDocument does belong in the SourceXDocumentCreator class. And so does the function of changing a specific value in the underlying XDocument. 

Conclusion
This article showed that gving a class a good name, and making sure that a class doesn't do too much (does only one thing), helps in making it easier to decide if and how to modify it.

For more information about the Single Responsibility principle see:
http://en.wikipedia.org/wiki/Single_responsibility_principle

dinsdag 5 februari 2013

XML Serialization with C# (update)

This is now my preferred way to serialize an object. You can choose the XML Serializer and the DataContract Serializer;


public class XmlSerializer
{
   public static MemoryStream SerializeToMemoryStream<T>(T t)
   {
      var memorystream = new MemoryStream();
      var s = new System.Xml.Serialization.XmlSerializer(typeof (T));

      xmlserializer.Serialize(XmlWriter.Create(memorystream), t);

      memorystream.Flush();
      memorystream.Seek(0, SeekOrigin.Begin);

      return memorystream;
   }

   public static string SerializeToString<T>(T t)
   {
      return SerializeToString(t, Encoding.UTF8);
   }

   public static string SerializeToString<T>(T t, Encoding encoding)
   {
      var settingsString = encoding.GetString(SerializeToMemoryStream(t).ToArray());
      return settingsString;
   }
}

        public class DatacontractSerializer
        {
            public static MemoryStream SerializeToMemoryStream<T>(T t)
            {
                var stream = new MemoryStream();
                var s = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
                s.WriteObject(XmlWriter.Create(stream), t);
                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                return stream;
            }

            public static string SerializeToString<T>(T t)
            {
                return SerializeToString(t, Encoding.UTF8);
            }

            public static string SerializeToString<T>(T t, Encoding encoding)
            {
                var settingsString = encoding.GetString(SerializeToMemoryStream(t).ToArray());
                return settingsString;
            }
        }
    }

zaterdag 26 januari 2013

Autofac and multiple implementations of an interface


How can we use Autofac to inject multiple implementations of an interface into a class, and how can we choose a specific implementation?

Let's say we have this interface for an object with which you can view files:

public interface IViewer
{
   void View(string filename);
}


And we have multiple implementations:

public class PdfViewerLarge : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}

public class PdfViewerSmall : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}


public class XlsViewerLarge : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}


public class XlsViewerSmall : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}

As you can see we have four Viewers. How can we use Autofac to inject these Viewers into a class?
First let's register the Viewers with Autofac, in an MVC3 website:

var builder = new ContainerBuilder();
builder.RegisterControllers(typeof (MvcApplication).Assembly);
builder.RegisterType<PdfViewerBig>().As<IViewer>();
builder.RegisterType<PdfViewerSmall>().As<IViewer>();
builder.RegisterType<XlsViewerSmall>().As<IViewer>();
var container = builder.Build();

Autofac will automatically put all viewers into an IEnumerable<IViewer>, which you can resolve like this:

var viewers = container.Resolve<IEnumerable<IViewer>>();

And we can easily use this in an MVC3 website like this:

public class HomeController : Controller
{
   private readonly IEnumerable<IViewer> _viewers;

   public HomeController(IEnumerable<IViewer> viewers)
   {
   _viewers = viewers;
   }

   public ActionResult Index()
   {
      foreach(var viewer in _viewers)
      {
         viewer.View("filename.pdf");
      }

      return View();
   }
}


How to choose a specific implementation from a collection?

The example above of the HomeController is pretty stupid, as we're using each viewer to view a document, even if the viewer is not suited for the filetype. What we realy want is something like:

var viewer = _viewers.Single(it => it.Filetype == ".pdf");
viewer.View("file.pdf");

There are multiple ways to do this. These are the three I like:
1. Use an enum value with autofac
2. Use Metadata with Autofac
3. Use Metadata within each Viewer


Enum value with Autofac

If you can think of a way to describe every viewer with an enum then this is a good option. It works like this;

Declare an enum:

public enum ViewerType { PdfLarge, PdfSmall, XlsLarge, XlsSmall }

Next register the type using the enum with Autofac:


builder.RegisterType<PdfViewerLarge>()
   .Keyed<IViewer>(ViewerType.PdfLarge);


builder.RegisterType<PdfViewerSmall>()
   .Keyed<IViewer>(ViewerType.PdfSmall);


builder.RegisterType<XlsViewerLarge>()
   .Keyed<IViewer>(ViewerType.XlsLarge);


builder.RegisterType<XlsViewerSmall>()
   .Keyed<IViewer>(ViewerType.XlsSmall);

In an MVC Controller the Viewers will be injected like this:

public class HomeController : Controller
{
   private readonly IIndex<ViewerType, IViewer> _viewers;

   public HomeController(IIndex<ViewerType, IViewer> viewers)

   {
      _viewers = viewers;
   }
}


Now we can use this way to select the desired implementation in an ActionMethod :

public ActionResult Index()
{
   var viewer = _viewers[ViewerType.PdfLarge];

   // do something with viewer

   return View();
}


Metadata with Autofac

Autofac provides a way to add metadata to registered services:

builder.Register(c => new PdfViewerLarge())
   .As<IViewer>()
   .WithMetadata("FileType", ".pdf");

We can also use strong typed metadata. First we have to define which metadatakeys we have:

public interface IViewerMetadata
{
    string FileType { get; }
    long MaxFileSize { get; }
}

Now we can use this metadata to register a type:

builder.RegisterType<XlsViewerSmall>()
   .As<IViewer>()
   .WithMetadata<IViewerMetadata>(m =>
      {
         m.For(p => p.MaxFileSize, 10000);
         m.For(p => p.FileType, ".xls");
       });

In an MVC Controller the Viewers will be injected like this:

public class HomeController : Controller
{
   private IEnumerable<Meta<IViewer, IViewerMetadata>> _viewers;

   public HomeController(
             IEnumerable<Meta<IViewer, IViewerMetadata>> viewers)
   {
      _viewers = viewers;
   }
}

Now we can use this way to select the desired implementation in an ActionMethod :

public ActionResult Index()
{
   var viewer = _viewers.Single(
                   it => it.Metadata.FileType == ".xls" &&
                   it.Metadata.MaxFileSize > 1000
                               ).Value;


   // do something with viewer

   return View();
}



Metadata inside an implementation

Another option to store metadata is inside the implementation itself. This is the way it works:

First we take an implementation, for example the PdfViewerLarge.


public class PdfViewerLarge : IViewer
{
   public void View(string filename)
   {
      // Do something smart
   }
}


We have to add the metadata to it, as public properties. But first add the metadata to the interface:

public interface IViewer
{
   string FileType {get;}
   long MaxFileSize {get;}
   void View(string filename);
}

Next we can implement it:



public class PdfViewerLarge : IViewer
{

   public string FileType
   {
      get { return ".pdf"; }
   }
   
   public long MaxFileSize

   {
      get { return 1000000; }
   }



   public void View(string filename)
   {
      // Do something smart
   }
}

When we register the type in Autofac we don't have to include any metadata:


builder.RegisterType<XlsViewerSmall>()
   .As<IViewer>();

But we can still use metadata in our Actionmethod:


public ActionResult Index()
{

   var viewer = _viewers.Single(
                   it => it.Value.FileType == ".xls" &&
                   it.Value.MaxFileSize > 1000
                                ).Value;


   // do something with viewer

   return View();
}


One drawback of this method is that every type has to be instanciated first. If creating a new instance of a specific implementation is an expensive operation, the other two options are preferable.

donderdag 3 januari 2013

Building Windows Services in C# with Topshelf

If you're building Windows Services I highly recommend to use Topshelf. As they say themselves it's an easy service hosting framework for building Windows services using .NET. It makes it easier to debug and install/uninstall the windows service, without having to write a lot of plumbing code.

You can find it here:

Topshelf on GitHub