Friday, September 25, 2009

Design Patterns – Singleton Pattern

The Singleton pattern gives us a way to restrict the instantiation of objects of given class to certain number, in the common usage to one only.

The Singleton class instantiates itself and works as a global repository for an instance of itself. For example we share a database connection or log writer across all threads in one process.

Implementation of Singleton pattern



Here i'm going to implement Singleton class in C#. The class should hide its constructor. It has also GetInstance() method that gives back the only concrete instance. We embed the concrete instance of the class into the static variable "obj".

For the purpose of the demonstration we have one public method Add() used to add some number to the class and Total() which gives back the total of the added numbers.



public class Singleton
{
private static Singleton obj = new Singleton(); // holds a reference to the only concrete instance

private static int total = 0; // we add numbers up to this via Add()

private Singleton() { } // hiden constructor

public static Singleton GetInstance() { return obj; } // returns the only concrete instance

public void Add(int number)
{ // add up to the total
lock (obj) // synchronize in concurrency
{
Thread.Sleep(new Random().Next(1000)); // randomly wait up to a second
total += number;
Console.WriteLine(String.Format("Add {0} to total", number));
}
}

public int Total()
{ // gets the total
lock (obj)
return total;
}
}




In Add() method we have a timeout up to a second to randomize the time to run the method.

We also locked the access to the class variables for concurrency. We are going to test the Singletion class in multithreaded environment.


Usage of Singleton pattern




First we create three static helper methods which will make calls to Add() with different number from one to three.



class Program
{
// add
static void HelperOne() { Singleton.GetInstance().Add(1); }
static void HelperTwo() { Singleton.GetInstance().Add(2); }
static void HelperThree() { Singleton.GetInstance().Add(3); }
...



Then in Main() we run three threads and run concurrently the three static helper methods.

We wait for the threads to finish and show the total of all additions to the singleton class.




static void Main(string[] args)
{
Thread[] threads = new Thread[]
{
new Thread(new ThreadStart(HelperOne)),
new Thread(new ThreadStart(HelperTwo)),
new Thread(new ThreadStart(HelperThree))
};

foreach (Thread thread in threads) { thread.Start(); }
foreach (Thread thread in threads) { thread.Join(); }

Console.WriteLine(String.Format("The total is {0}",
Singleton.GetInstance().Total()));

Console.Read();

}



Run the example



Running that I've got the following output:




Happy codding!

Atanas Hristov


Shout it

Friday, September 11, 2009

Design Patterns – Chain of Responsibility Pattern

Imagine you have complicated decision logic and you’ve got a big if-then-else like structure in your code which you want to simplify.
The Chain of Responsibility Pattern is a good way for code refactoring in such situation. It will make the code more flexible and easy to support and modify in the future.

You prepare a set of interdependent chain handler classes linked in a chain. Every chain handler class implements part of the decision logic and has a link to next chain handler object. A request data object is passed thru the chain. Eventually one of the handlers on the chain matches some decision criteria, does data processing and ends up the run flow. This would be the handler objects in the chain that takes the responsibility and does data processing having received the request data object.

In this example we will try to programmatically come up with a conclusion based on passed in to the chain two boolean parameters. For every possible combination of those parameters we are going give a conclusion back, so we have four different possible results. Otherwise we could do things using conditional structures like:



If Param1 is true
If Param2 is true
Conclusion1
Else
Conclusion2
Else
If Param2 is true
Conclusion3
Else
Conclusion4


Based on that conditional structure we will create chain of responsibility with four different chain handler classes covering all decision making combinations.

We will use C# as a programming language for the examples.

Chain Handler Interface and Base Class



We start with the definition of the chain handler interface. The chain handler object stores internally a request data object. We have a way to set if there is a handler next on the chain. The handler has Run() void where the decision making and eventually data processing will be done.



// All handler objects implement common interface.
// T: request object- holds data to process
// and the result of the processing
public interface IChainHandler<TRequest>
{
IChainHandler<TRequest> SetNextLink(IChainHandler<TRequest> next); // set link to next handler
void Run(); // does processing
}



As we will have four chain handler classes and they all have a lot in common, we create parent abstract base class for chain handler.



// base class for all concrete chain handler objects
public abstract class ChainHandlerBase : IChainHandler<RequestData>
{
// the request data object
protected RequestData _requestData;

// a reference to next chain handler object
private IChainHandler<RequestData> _nextHandler;

// hide parameterless constructor
private ChainHandlerBase() { }

// expose constructor with parameters
public ChainHandlerBase(RequestData requestData)
{
_requestData = requestData;
}
// set the reference to the next chain handler object
public IChainHandler<RequestData> SetNextLink(IChainHandler<RequestData> nextHandler)
{
_nextHandler = nextHandler;
return _nextHandler;
}

// let the concrete implementation make processing decision
public abstract void Run();

// run next handler in the chain if defined or end up the processing
protected void RunNext()
{
if (_nextHandler != null)
_nextHandler.Run();
}

}



Request Data Object



A step back – we need to define the request data object which we’ll pass thru the chain. This object holds two input boolean parameters and a holder where we write the conclusion message back.



// Data to pass thru the chain.
// Based on this data the chain
public class RequestData
{
// pass in parameters
public bool HaveLotOfMoney { get; set; }
public bool HaveBrilliantIdea { get; set; }

// a message to send back
public string MessageBack { get; set; }
}




Concrete Chain Handler Implementations



Now we are ready to define concrete chain handler classes and cover all possible combinations of the input parameters.



// concrete chain handler object
public class ChainHandlerOne : ChainHandlerBase
{
public ChainHandlerOne(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((_requestData.HaveLotOfMoney) && (_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "I am with you.";
return;
}
RunNext();
}
}

// concrete chain handler object
public class ChainHandlerTwo : ChainHandlerBase
{
public ChainHandlerTwo(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((_requestData.HaveLotOfMoney) && (!_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "Well done. Go on pension.";
return;
}
RunNext();
}
}

// concrete chain handler object
public class ChainHandlerThree : ChainHandlerBase
{
public ChainHandlerThree(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((!_requestData.HaveLotOfMoney) && (_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "What a nice idea.";
return;
}
RunNext();
}
}

// concrete chain handler object
public class ChainHandlerFour : ChainHandlerBase
{
public ChainHandlerFour(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((!_requestData.HaveLotOfMoney) && (!_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "Don't give up.";
return;
}
RunNext();
}
}




Set Up the Chain



We are ready at this point to put in order the chain. We create chain handler objects and link them in a appropriate order. We send to the first handler in the chain a request data object and hit the Run() method to get the result calculated.



// wraps the chain initialization and processing code
static RequestData WhatAboutMe(RequestData requestData)
{
// construct the first chain handler.
ChainHandlerBase firstHandler = new ChainHandlerOne(requestData);

// arrange chain of responsibility as list of chain handker objects
firstHandler
.SetNextLink(new ChainHandlerTwo(requestData))
.SetNextLink(new ChainHandlerThree(requestData))
.SetNextLink(new ChainHandlerFour(requestData));

// start processing of the request data
firstHandler.Run();

// return back the request data with the message created
return requestData;
}



Run the Chain



The win of utilizing chain responsibility pattern is the extensibility of our code in future. If we need additional logic we have to implement new chain handler class. We also may construct the chains in one or another way, we can order the chain handler object based on concrete needs. We absolutely take care of single responsibility principle and we divide a long and complicated to maintain code into well testable small classes.

Finally let’s run our chain of responsibility implementation. We’ll send every possible combination of input to the chain and see what’ll happen.




static void Main(string[] args)
{
Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = true, HaveBrilliantIdea = true }).MessageBack);

Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = true, HaveBrilliantIdea = false }).MessageBack);

Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = false, HaveBrilliantIdea = true }).MessageBack);

Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = false, HaveBrilliantIdea = false }).MessageBack);

Console.Write("Hit Enter to finish.");
Console.ReadLine();
}



Running that we get on the console like:



Atanas Hristov

kick it on DotNetKicks.com
Shout it

Monday, September 7, 2009

Upload file to database with ASP.NET MVC and Castle Active Record

A file upload function to web application raises the question where to store the uploaded data. One possibility is to just store into the file system. This is inexpensive and easy to implement, but you have to think for file backups. If you don’t have huge amount of data you can also upload files directly into a database using binary format for table column to store the content of the file.

In this post I’m going to give a try of the second option and create simple application to store uploaded files directly into the database.

I will use Postgres database to store the file uploads and as ORM I will use Active Record from the Castle project. Then I need a driver for .NET to connect to the database, we will use the Npgsql driver.

With Castle Active Record you can easy switch to another database server; it’s just matter of switching the referenced driver and replace appropriately the configuration into Web.config file.

Assume we have PostgreSQL Server on localhost up and running and we will connect to the database "postgres" as user "postgres".




Create the project and set the configuration



We start with creating new ASP.MVC Application in Visual Studio and give it the name of "UploadToDb".

We then add references to the following assemblies from our project:

NHibernate.dll
Castle.ActiveRecord.dll
Castle.Components.Validator.dll
Castle.Core.dll
Castle.DynamicProxy.dll
Iesi.Collections.dll
Npgsql.dll

We change the Web.config file and add the appropriate settings for Active Record.

In "configSections" we add new section sub element for the Active Record. Next to "configSections" we add "activerecord" element where we specify the connection parameters and the database driver we are going to use.




<configuration>
<configSections>
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
….
</configSections>
<activerecord isWeb="false" isDebug="true">
<config>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.PostgreSQL81Dialect"/>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.NpgsqlDriver"/>
<add key="hibernate.connection.connection_string" value="Server=localhost;Port=5432;Database=postgres;User ID=postgres;Password=;"/>
</config>
</activerecord>







Database table and domain model



First we'll create Active Record class for the domain object "Upload" into Models directory. This is an entity object and has property Id which is a primary key into the database. We’ve got also data property which holds the binary data from the file we upload. There is also mimetype property which holds the MIME type of the uploaded file.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Scopes;
using NHibernate.Expression;
using System.Data;
using System.Collections;

namespace UploadToDb.Models
{
[ActiveRecord("uploads")]
public class Upload : ActiveRecordBase<Upload>
{
private int id = 0;
[PrimaryKey(PrimaryKeyType.Sequence, SequenceName = "uploads_seq")]
public int Id
{
get { return id; }
set { id = value; }
}

private byte[] data = new byte[] { };
[Property]
public byte[] Data
{
get { return data; }
set { data = value; }
}

private string mimetype = "";
[Property]
public string Mimetype
{
get { return mimetype; }
set { mimetype = value; }
}

public static Upload FindById(int id)
{
return FindOne(Expression.Eq("Id", id));
}
}
}




To search uploaded files into the database we use the above implemented method FindById(int) which is just used to enclose and wrap that extra Actie Record syntax with the expressions. Otherwise we have a lot of search capabilities coming with Active Record, for example to get list of all file uploads we use Models.Upload.FindAll() as the class Models.Upload inherits from ActiveRecordBase class.


We create table to store the uploaded files



CREATE TABLE "uploads" (
"id" int DEFAULT 0 NOT NULL,
"mimetype" Varchar NOT NULL,
"data" Bytea
);

ALTER TABLE "uploads" ADD CONSTRAINT "uploads_pk" PRIMARY KEY ("id");

CREATE SEQUENCE uploads_seq START 1;
ALTER TABLE uploads ALTER COLUMN id SET DEFAULT nextval('uploads_seq'::text);








Set up the application



At application start we will initialize Active Record. Open Global.asax.cs file and edit method Application_Start(). After RegisterRoutes we add the initialization piece of code:



protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);

// load configuration from Web.config
Castle.ActiveRecord.Framework.IConfigurationSource source =
System.Configuration.ConfigurationManager.GetSection("activerecord")
as Castle.ActiveRecord.Framework.IConfigurationSource;

// Initialize and mention which types define our model
Castle.ActiveRecord.ActiveRecordStarter.Initialize(source,
typeof(Models.Upload));
}







The UploadController class



Basically we’d need three different URLs: Add – to upload new file; Get- to get uploaded file and finally Index which gives us list of all uploads.

We’ll create UploadController class in Controllers directory. Then we implement the three methods.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace UploadToDb.Controllers
{
public class UploadController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(HttpPostedFileBase file)
{
if (file != null)
{
Models.Upload upload = new UploadToDb.Models.Upload();
upload.Mimetype = file.ContentType;
upload.Data = new byte[file.ContentLength];
file.InputStream.Read(upload.Data, 0, file.ContentLength);
upload.Save();
}
return Index();
}

public FileContentResult Get(int id)
{
Models.Upload upload = Models.Upload.FindById(id);
return File(upload.Data, upload.Mimetype);
}

public ActionResult Index()
{
this.ViewData["uploads"] = Models.Upload.FindAll();
return this.View("Index");
}

}
}



Method Add() calls Index() after the file upload finished, those way we get the list of the uploads after we upload new file.


The HTML view



Created directory Views\Upload and add there view Index. I won’t select a master page for the purpose of the presentation. I also won’t use strongly-typed view, but just will thread the ViewData as a dictionary.




<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>File uploads</title>
</head>
<body>

<h3>1.List of uploads</h3>
<%
UploadToDb.Models.Upload[] uploads = (UploadToDb.Models.Upload[])this.ViewData["uploads"];
foreach (UploadToDb.Models.Upload upload in uploads.OrderBy(x=> x.Id))
{
%>
<div><%= Html.ActionLink(upload.Id.ToString(), "Get", new { upload.Id })%></div>
<%
}
%>


<h3>2.Upload new file</h3>
<% using (Html.BeginForm("Add", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
Choose file: <input type="file" name="file" />
<input type="submit" />
<% } %>


</body>
</html>






Basically we have two parts here.

Part one is a list of all the uploaded files. It creates list of links to open the uploaded files via the "Get" method.

Part two is an html multipart form used to upload new file. After the file upload finished, we invoke again the Index controller method to list all the files uploaded to the database.


To upload file to database run the application and navigate the browser to ~/Upload/ directory.


I've got that screen after two files uploaded:







Enjoy!

Atanas Hristov

Friday, September 4, 2009

Logging with log4net

Log4net is a very powerful tool to get information from running application. After deployment your code has to deal with environment that is more or less different than on your development machine. Log4net not only provides your application with powerful logging where you can specify a lot of options and levels, but you can even dynamically turn on and off logging for different classes while the application is running at the same time.


The homepage of the project is:
http://logging.apache.org/log4net/index.html

I’m about to show you the way I’m usually using log4net in my projects.



Step one



The very first step is to add reference to log4net.dll to the project.



Initialization of log4net



It has to be done once in your application. You can prepare and run static initializer in the manner of:

 
public class Initializer
{
private static object _locked = new object();
protected static bool initialized = false;

public static Initializer() { Init(); }

public static void Init()
{
lock (_locked)
{
if (initialized)
return;

log4net.Config.XmlConfigurator.Configure(); // run once at app startup
...
}
}
}



Then call Initializer.Init() at application start-up from your Global.aspx or Main() for example.




Add logger for one class



One possibility to use log4net is to create separate logger for one class only. Thereof you can:

a/ write to separate and dedicated for that class only log file,
b/ or you can have different formating for logging messages from that class,
c/ or you can set different log level for the log messages from that class,
d/ or just because the class name could be written along with the logging messages so it will be easy to localize the part of the code from where the message comes.

Here is part of declaration of class named "McChannel" for which class we will define class logger.

 

// (1) add using directives:
...
using log4net;
using log4net.Config;

[ActiveRecord("mc_channels")]
public class McChannel : ActiveRecordBase
{
// (2) declare and initialize static per class logger
private static readonly ILog log = LogManager.GetLogger(typeof(McChannel));
...
}




From inside the body of that class you can use the logger "log" like:

 

log.Debug("Selecting channel names at.");
log.DebugFormat("Addiding channel {0}", one.Channel_name_official);








You have log.Debug(), log.Info(), log.Warn(), log.Error(), log.Fatal() methods you use for logging and they all have the corresponding extended with string formatting methods: log.DebugFormat(), log.InfoFormat(), log.WarnFormat(), log.ErrorFormat(), log.FatalFormat(). In the exact priority order as listed here the Debug() has the lowermost priority.

In your configuration (see below) you have to set which level of logging you want to log. The logging levels as they are defined in order of decreasing priority are:

OFF: no logging at all.
FATAL: only log.Fatal() messages will be logged
ERROR: log.Error()and higher will be logged
WARN: log.Warn() and higher will be logged
INFO: log.Info()and higher will be logged
DEBUG: log.Fatal()and higher will be logged
ALL: all logging methods will be logged.



Configuration of log4net in App.config or Web.config



Let's prepare simple configuration for log4net.

First in configSections we add element section with attribute name="log4net".
Then we add sub element "log4net" to element "configuration".

We create appender "RollingFileAppender" which defines where we write logging messages and what the pattern for formatting the log messages is. Furthermore the files will be rotated.

We can have more than one appender in your configuration.

Then we default set priority levels for the whole application to "ERROR" - see element "root" - but we define for class "McChannel" priority level of "DEBUG".

Here is the complete example:


 

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="D:\Logfile.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="100" />
<maximumFileSize value="1024KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<!-- ALL DEBUG INFO WARN ERROR FATAL OFF -->
<!-- Setup the root category, add the appenders and set the default level to ERROR -->
<priority value="ERROR" />
<!-- Set the default logger -->
<appender-ref ref="RollingFileAppender" />
</root>
<logger name="McChannel">
<!-- Only for the logger for class McChannel we set level to DEBUG -->
<level value="DEBUG" />
</logger>
</log4net>
</configuration>




The output of logging messages from class McChannel goes to D:\Logfile.txt after we run the application.


this.Dispose()



Log4net is very flexible. You can add the logging messages into a database table, you can use the TraceContext of ASP.NET, the console appender can produce colorized output, you can append to the Application event log in Windows, address Windows Messenger Service, send emails with logging messages and many more.

Have a nice weekend!

Atanas Hristov