I tried this font and it look really nice.
Monday, February 16, 2009
Thursday, February 12, 2009
How many layer does it take to abstract everything, and should we?
Architecture is about building a structure just strong enough to fulfill the requirement but not to much to keep the cost as low as possible. But in every project there is two kind of requirement: functional and non-functional. We think about functional requirement when they are explicitly express by the client.
I want a car that can take me from home to work and back.
The architect’s job is to make sure the car will be powerful enough to do the job, that it will be big enough to hold at least one person and to be able to carry enough fuel for the whole trip. If we stick just to those requirement we will end up with a single passenger car mostly made of plastic and with a gas tank of 1 L. Is this enough? That meets the initial requirements, but of course we have to take care of more than that. That’s were we have to think about non-functional requirements like security, standard, extensibility, maintainability, durability, usability and so on. Moreover, when a client ask for a car to go from home to work and back, he actually means he want to be able to go on vacation trip with it too, but you won’t know that at first.
To find a solution to all these requirements we have to do like we do when we face a complex problem; add abstraction layers. For a car that mean we have to respect some industry standard rules. For example we have make sure we can buy wheels, wipers, oil filters or cd player knowing it will fit on our car even if the combination of two specific model has never been tried before. As long as it respect standard like dimension it will work.
Is software development we have to set those standards for databases, components, UI interfaces, Logging, Error handling, and so on. We doo that usually with interfaces and abstract classes. Those abstraction will act as specifications anybody can use to build compatible pieces that will work on our system. If a car doesn’t expect to have more than 6 speakers it doesn’t make sense to build a cd player that can use 7 speakers. Likewise, is software, once we publish an interface, it doesn’t make sense to add other methods than the ones supported, they won’t be called anyway.
Now get back the initial question. How many layer does it take to abstract everything, and should we? If your are a purist you will try to add a layer of abstract between your code and all other code base you don’t have control over. But how far will you go? Is it a good thing to build your own control by deriving from the framework ones? Will you push the abstraction to the level of any part layer of your code can live independent of all others?
Remember what I said at the beginning? Just enough but not too much. So my answer is it depends but I like to leave me open doors so if later I want to split two layer it wont be too much difficult to do. Today with refactoring tools and test frameworks you can do big changes to your code without being too worry about breaking something.
Wednesday, February 11, 2009
Refactoring single threaded code to multithreaded and to Tasks (with Parallel Extension Framework)
Introduction
Someone asked me to post a simple sample on how to build a multi threaded application. So I put together this blog post. Of course to maintain everything readable and easy to follow there’s no error handling and no validation.
Starting point
A-SingleThreadSimpleModel in the source code
For this sample I used a person as my model object. Someone could say that I should not use stupid objects but its more understandable this way.
So we have a person that could talk and walk. Obviously most of us can do these to things at the same time, but we must tell the computer how to do it. First we will start by a single threaded model to show you all the objects involve. Then we will refactor it a little to make it more manageable and then we will make it multi treaded using first thread an later tasks. Task is a new concept that will be introduced in Visual Studio 2010.
Let’s look at the Person class:
public class Person
{
private int _position;
private readonly List<string> _log = new List<string>();
public void Say(string message)
{
var words = message.Split(' ');
foreach (var word in words)
{
Thread.Sleep(400);
SomethingSaid(this, new TalkEventArgs(word));
}
Log.Add(message); // not thread safe
}
public void Walk(int steps)
{
for (int i = 0; i < steps; i++)
{
Thread.Sleep(100);
_position++; // not thread safe
MovedForward(this, new WalkEventArgs(1));
}
}
public int Position { get { return _position; } }
public List<string> Log { get { return _log; } }
public event EventHandler<TalkEventArgs> SomethingSaid = delegate { };
public event EventHandler<WalkEventArgs> MovedForward = delegate { };
}We have a very simple class here with two properties, two methods and two events. After initialising this class we can call Say(…) or Walk(…) like demonstrated in this console application:
public class Program
{
static void Main(string[] args)
{
var p = new Person();
p.SomethingSaid += (sender, e) => Console.WriteLine("I'm saying: {0}", e.Message);
p.MovedForward += (sender, e) => Console.WriteLine("I walked: {0} steps", e.Steps);
Stopwatch stopwatch = Stopwatch.StartNew();
p.Walk(20);
p.Say("Let me tell you something");
stopwatch.Stop();
Console.WriteLine("It took me {0} ms\nto walk {1} steps\nand say \"{2}\"",
stopwatch.ElapsedMilliseconds,
p.Position,
String.Join("; ", p.Log.ToArray()));
}
}If you run this sample you should get something like this:
I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I'm saying: Let I'm saying: me I'm saying: tell I'm saying: you I'm saying: something It took me 5511 ms to walk 20 steps and say "Let me tell you something" Press any key to continue . . .
We can clealry see that only one task ca be done at any time. We either walk or talk but not both.
Refactoring
B-SingleThreadRefactored in the source code
Now let’s take this sample to the next level. In this refactoring phase we will:
- Extract an interface
- Build a base class
- Add a little thread safety
First the interface:
public interface IPerson
{
void Say(string message);
void Walk(int steps);
int Position { get; }
IEnumerable<string> Log { get; }
event EventHandler<TalkEventArgs> SomethingSaid;
event EventHandler<WalkEventArgs> MovedForward;
}This interface will then be implemented by a base class:
public abstract class PersonBase : IPerson
{
private int _position;
private readonly List<string> _log = new List<string>();
#region Implementation of IPerson
public abstract void Say(string message);
public abstract void Walk(int steps);
public int Position { get { return _position; } }
public IEnumerable<string> Log { get { return _log; } }
public event EventHandler<TalkEventArgs> SomethingSaid = delegate { };
public event EventHandler<WalkEventArgs> MovedForward = delegate { };
#endregion
protected void Moving(int steps)
{
for (int i = 0; i < steps; i++)
{
Thread.Sleep(100);
Interlocked.Increment(ref _position); // thread safe
MovedForward(this, new WalkEventArgs(1));
}
}
protected void Speaking(string message)
{
var words = message.Split(' ');
foreach (var word in words)
{
Thread.Sleep(400);
SomethingSaid(this, new TalkEventArgs(word));
}
_log.Add(message); // not thread safe yet!
}
}Executing the code after this refactoring should gives you the exact same output as before.
Using Thread
C-MultiThreadUsingThread in the source code
Now let’s try to multi thread this sample a little. We will define a new interface for that. This interface will declare 4 new members: BeginSay, EndSay, BeginWalk and EndWalk. All the “begin” method will initiate background thread to do the task. All the “end” method will act as synchronization mechanism. This is where we can catch exception. Here is the IThreadPerson interface:
public interface IThreadPerson : IPerson
{
Thread BeginSay(string message);
void EndSay(Thread callBack);
Thread BeginWalk(int steps);
void EndWalk(Thread callBack);
}And an implementation of it:
public class Person : PersonBase, IThreadPerson
{
#region IThreadPerson Members
public Thread BeginSay(string message)
{
var starter = new ThreadStart(() =>
{
Say(message);
});
var thread = new Thread(starter);
thread.Start();
return thread;
}
public void EndSay(Thread talk)
{
talk.Join();
}
public Thread BeginWalk(int steps)
{
var starter = new ThreadStart(() =>
{
Walk(steps);
});
var thread = new Thread(starter);
thread.Start();
return thread;
}
public void EndWalk(Thread walk)
{
walk.Join();
}
#endregion
}Each “begin” method will return a new thread which we can use to synchronize the process. By calling “end” method we explicitly wait for the result. These method can be placed into a try catch block to handle any possible exeption that may occur.
If you run this you will get something like this:
I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I'm saying: Let I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I'm saying: me I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I'm saying: tell I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I'm saying: you I walked: 1 steps I walked: 1 steps I walked: 1 steps I walked: 1 steps I'm saying: something It took me 2017 ms to walk 20 steps and say "Let me tell you something" Press any key to continue . . .
As you can see it took about half the tome to complete and we are doing two things at the same time.
Using Task
D-MultiThreadUsingTask in the source code
Using Task from Parallel Extensions Framework is almost the same as Thread except some types and the way to create a thread are different.
Here is the ITaskPerson interface:
public interface ITaskPerson : IPerson
{
Task BeginSay(string message);
void EndSay(Task callBack);
Task BeginWalk(int steps);
void EndWalk(Task callBack);
}And the task implementation of Person:
public class Person : PersonBase, ITaskPerson
{
#region ITaskPerson Members
public Task BeginSay(string message)
{
var task = Task.Create(x => { Say(message); });
return task;
}
public void EndSay(Task talk)
{
talk.Wait();
}
public Task BeginWalk(int steps)
{
var task = Task.Create(x => { Walk(steps); });
return task;
}
public void EndWalk(Task walk)
{
walk.Wait();
}
#endregion
}As you can see it’s a little simpler to create a Task than a Thread. The usage is also simpler. Here how to call it:
Task walk = p.BeginWalk(20);
Task talk = p.BeginSay("Let me tell you something");
p.EndWalk(walk);
p.EndSay(talk);But this way of doing is somehow deprecated. Here is a more “Parallel Extensions” way:
Task[] tasks = new Task[]
{
p.BeginWalk(20),
p.BeginSay("Let me tell you something")
};
Task.WaitAll(tasks);The execution of both method should give you almost the same result as with the Thread version.
Conclusion
I hope it will help you building multi thread and thread safe application.
Why ++ operator is not thread safe
Here is a quick hint on how to make your software thread safe. If you want to increment a member of your class you would probably do something like this:
public void NotSafe()
{
val++;
}
Where val is a member of your class.But this is not thread safe. Doing this involve 4 operations:
- Loading the field and put it on the stack
- Putting 1 on the stack to increment by 1
- Calling add on the stack
- Storing the result in the field
Here is the corresponding IL:
.method public hidebysig instance void NotSafe() cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: dup
L_0003: ldfld int32 ClassLibrary1.Class1::val
L_0008: ldc.i4.1
L_0009: add
L_000a: stfld int32 ClassLibrary1.Class1::val
L_000f: ret
}
The problem is that anywhere between any of the 4 steps another thread can try to do the same thing. For example if a second thread pup in just after the first one is between step 1 and 2 they will both try to increment the same value and store it on the stack. To resolve this problem you can use a lock like this:
public void SafeLock()
{
lock (valLock)
{
val++;
}
}
But this will generate the following IL:
.method public hidebysig instance void SafeLock() cil managed
{
.maxstack 3
.locals init (
[0] object CS$2$0000)
L_0000: nop
L_0001: ldarg.0
L_0002: ldfld object ClassLibrary1.Class1::valLock
L_0007: dup
L_0008: stloc.0
L_0009: call void [mscorlib]System.Threading.Monitor::Enter(object)
L_000e: nop
L_000f: nop
L_0010: ldarg.0
L_0011: dup
L_0012: ldfld int32 ClassLibrary1.Class1::val
L_0017: ldc.i4.1
L_0018: add
L_0019: stfld int32 ClassLibrary1.Class1::val
L_001e: nop
L_001f: leave.s L_0029
L_0021: ldloc.0
L_0022: call void [mscorlib]System.Threading.Monitor::Exit(object)
L_0027: nop
L_0028: endfinally
L_0029: nop
L_002a: ret
.try L_000f to L_0021 finally handler L_0021 to L_0029
}
As you can see there is a lot more code involve to ensure thread safety, A quicker, faster an easier way to do this s to use Interlocked class. This class will use low level OS call to modify the member. Here’s how to use it:
public void Safe()
{
Interlocked.Increment(ref val);
}
This will be render as two major IL steps:
- Load value from the field and put it on the stack
- Call Increment
Here is the IL representation of this:
.method public hidebysig instance void Safe() cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: ldflda int32 ClassLibrary1.Class1::val
L_0007: call int32 [mscorlib]System.Threading.Interlocked::Increment(int32&)
L_000c: pop
L_000d: ret
}
Now every time you will see something++ you will know that this is not thread safe and how to fix it.
@ 2/11/2009 07:03:00 AM 1 commentaires
Label: C#, OOP, Parallel Extensions, Tip
Tuesday, February 10, 2009
The complete history of the Internet in 8 minutes
The complete, comprehensive history of the Internet from 1957 to 2009, in just 8 minutes.
[from Gizmodo]
Saturday, February 7, 2009
XML Serialization Tip: Hiding default constructor
Here is a quick tip. You all know that to serialize and deserialize an object in XML you need a default (parameter less) constructor. But sometimes you don’t want anybody to use it other than the serializer itself.
By making the default constructor obsolete you can make sure no code will directly call it.
public class MyClass
{
[Obsolete("For XML Serialization Only", true)]
public MyClass()
{
// Needed for XML serailisation
}
public MyClass(string initialValue)
{
// ...
}
// ...
}Don’t forget to specify true as the second argument to the Obsolete attribute. This will raise a compilation error if this constructor is called directly. I insist on “directly” because nothing will prevent someone to use reflection to call it. XML Serialisation can occur because it uses reflection to do it.
@ 2/07/2009 05:16:00 PM 9 commentaires
Label: Attributes, C#, Tip
Friday, January 30, 2009
How to quickly wrap a single item into a collection
The situation
I just started to play with WPF and I like that very much. Its a lot easier to do many things that were very hard to do in Win Forms.
I’m working on a software that need a tree view. In win form you have to build the entire tree a node at a time, adding them recursively until done. In WPF though, there is a faster way to do that.
First let say we have a tree structure like this:
public class TreeNode
{
private BindingList<TreeNode> _children;
public BindingList<TreeNode> Children
{
get { return children; }
set { /* setter code */ }
}
}
Later in your code you define a property of that type to bind to:
public TreeNode Root
{
get { return _root; }
}
With this code you can build a structured tree of nodes. Then you can use a TreeView object in your xaml file:
<TreeView Name="treeView1"
ItemsSource="{Binding ElementName=Win,Path=Root}"
ItemTemplate="{StaticResource NodeTemplate}" />
The Problem
The problem with this is that the TreeView needs a collection or at least an enumerable source as its ItemSource. What if we don’t want to bind to the Children property of the root? What if we have some interesting property to show on the root node?
The Solution
We can build a temporary collection to pleased the TreeView:
public List<TreeNode> Root
{
get
{
var list = new List<TreeNode>;
list.Add(_root);
return list;
}
}
Of course this will work. But isn’t a little too much having to create an instance of a list object to do that? Here is a simpler an more efficient way to achieve the same result.
public IEnumerable<TreeNode> Root
{
get { yield return _root; }
}
Wow! That’s short! If you don’t know what “yield return” keyword is, you may find this code sample a little odd. “yield return” is what LINQ uses internally to iterate thru any IEnumerable data source without having to build an internal list. In our case we only need a list of one item, so using this technique can optimise your code.
Wednesday, January 28, 2009
My first computer (part2)
For those of you who still trying to find what was my first computer, here it is:
http://oldcomputers.net/adam.html
http://en.wikipedia.org/wiki/Coleco_Adam
Tuesday, January 27, 2009
Debugging Windows Service Without Deploying It
Code available on Code Project: http://www.codeproject.com/KB/tips/EasyDebugWindowsServices.aspx
Introduction
At the beginning, there was no easy way to build a Windows service using Visual Studio and .NET Framework. Now that Microsoft has integrated this functionality as a template and a class library, it's much more easy to do that. This is good, but to test your newly created service you have to deploy it. That means you must add an installer and build a whole MSI file and run it in your environment. Once deployed, you can start it with Windows Service controller and attach a debugger to it.
I don't know how this sounds to you, but to me it is too much unneeded work to do a quick test. This article describes a much more easy way to do that.
Using the Code
You will find a sample application using this concept. Here is how it works.
First you need a working Windows service. (For more information, refer to this.)
In Visual Studio, building a Web service is easy. Create a new project and select Windows Service template.
Then add ServiceDebuggerHelper project to your solution and a reference to it. You can find it in the sample code.
By default, when you create a Windows service project, Visual Studio will create two classes: a Program class and a Service1 class. Here is what the program class looks like:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
}
}The first thing we have to do is to surround that code with a conditional statement to let us control if we want to run as a real service or just in debugging mode.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
if (args.Length > 0 && args[0].ToLower().Equals("/debug"))
{
Application.Run(new ServiceRunner(new Service1()));
}
else
{
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
}
}
}In this new Program class, ServiceRunner will be acting as a service host. To make it work, you have to add the "/debug" command line option in your project properties.
Go to Project -> ... Properties -> Debug and type /debug in the command line arguments field.
From there, you have two options to make your service debuggable. Either you implement IDebuggableService or inherit from DebuggableService base class.
Implementing IDebuggableService Interface
If you already subclass ServiceBase and use that subclass for all your services or if you just want to have full control over the implementation, you should implement theIDebuggableService interface. Here is its definition:
public interface IDebuggableService
{
void Start(string[] args);
void StopService();
void Pause();
void Continue();
}Notice that the stop method is called StopService to avoid conflict with the existing Stop method of the ServiceBase class.
Here is a sample implementation of this interface:
public partial class Service1 : ServiceBase, IDebuggableService
{
//
// Your existing service code
//
// ...
//
#region IDebuggableService Members
public void Start(string[] args)
{
OnStart(args);
}
public void StopService()
{
OnStop();
}
public void Pause()
{
OnPause();
}
public void Continue()
{
OnContinue();
}
#endregion
}Subclassing DebuggableService
Subclassing your service from DebuggableService is even more simple. All you have to do is change the base class from ServiceBase to DebuggableService.
public partial class Service1 : DebuggableService
{
//
// Your existing service code
//
// ...
//
}All the control methods are already implemented by DebuggableService.
Points of Interest
In my sample code, I added a Windows Form class to let you start, stop and pause your service. You can use it as is, build your own controller interface or just call the methods in your program class. It is up to you.
Of course you should still deploy your service to give it the final test run. One good reason to do this is to test the actual security context in which your service will run. It will not have the same permission as when you run it in Visual Studio, but this technique can speed up the development process.
Code available on Code Project: http://www.codeproject.com/KB/tips/EasyDebugWindowsServices.aspx