Sunday, November 22, 2009

List of most common Design Patterns


In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Design pattern (computer science)

Below I have a list of most common design patterns.

Creational Patterns

Abstract Factory

Creates an instance of several families of classes

Builder

Separates object construction from its representation

Factory Method

Creates an instance of several derived classes

Prototype

A fully initialized instance to be copied or cloned

Singleton

A class of which only a single instance can exist

Structural Patterns

Adapter

Match interfaces of different classes

Bridge

Separates an object's interface from its implementation

Composite

A tree structure of simple and composite objects

Decorator

Add responsibilities to objects dynamically

Façade

A single class that represents an entire subsystem

Flyweight

A fine-grained instance used for efficient sharing

Proxy

An object representing another object

Behavioral Patterns

Chain of Responsibility

A way of passing a request between chains of objects

Command

Encapsulate a command request as an object

Interpreter

A way to include language elements in a program

Iterator

Sequentially access the elements of a collection

Mediator

Defines simplified communication between classes

Memento

Capture and restore an object's internal state

Observer

A way of notifying change to a number of classes

State

Alter an object's behavior when its state changes

Strategy

Encapsulates an algorithm inside a class

Template Method

Defer the exact steps of an algorithm to a subclass

Visitor

Defines a new operation to a class without change

Tuesday, November 17, 2009

Type safe named instances with Unity

The following example demonstrates registering a named instance in Unity. The only problem here is that both the registration and resolving of the dependency is done using a string. Even using a static class to hardcode all strings in a kind-of type safe way gives us no guaranty that the developer will respect the convention.






An alternate way of doing this would be using a delegate to resolve the instance giving a type safe argument such as an enumeration. So the registration in unity is a bit different...



Instead of a static class with constants we now have a type safe enumeration:



...and finally the client class that resolves the delegate:



In addition the actual resolving of the configuration string (typically read from a config) is done lazy... at the moment we really need it.
Finally we don't have ambiguity in registering in the container a type such as string, since we now mark the instance with an additional type (marker type).

Thursday, November 12, 2009

Implementing a .NET Framework Data Provider

Five years ago I needed to implement a web app for a chemicals company, that was using data from SqlServer, Oracle, Documentum and Hummingbird. The problem was that at that time both Documentum and Hummingbird (document management systems) had no oledb nor .net providers available. So my data layer became a big mess due to the fact that some of my code was through ADO.NET and the rest was using proprietary API's from Documentum and Hummingbird. In addition having such code was very error prone and not testable at all, since those API's at that time were very low level.
The solution that I had found was to implement my own .NET Data Provider. I used as basis an example posted on msdn: Implementing a .NET Framework Data Provider.
The article provides a template implementation of a "Fake/Sample" data provider for an in-memory database "Fake/Sample". If you are investigating in this direction then following the above link will be very helpful.
For your convenience I have created a sample wpf app using this code. The code is an identical copy of the original; I have only made some improvements to make it up-to-date with .NET 4.0 since the initial article was written for .NET 1.0
You can checkout the sources using tortoise: http://bakopanos.googlecode.com/svn/trunk/blog/DotNetDataProviderTemplate/
I used Visual Studio 2010 for this :-)


An overview of the code

The "fake/sample" database in the sample mimics a real world database that returns a cursor of the following structure:

internal class SampleDbResultSet
{
    public struct MetaData
    {
        public string name;
        public Type type;
        public int maxSize;
    }
    public int recordsAffected;
    public MetaData[] metaData;
    public object[,] data;
}
The commands supported by the sample database are startwith "select " and startwith "update ". This is it: 2 hardcoded commands, no args or anything...
The select command returns always the following resultset hardcoded in code:

id  name  orderid  
1  Biggs  2001  
2  Brown  2121  
3  Jones  2543  
4  Smith  2772  
5  Tyler  3521  

The update command simply alters the (2,2) cell of the above table.

Once you understand this sample you can implement your own wrapper for the database of your choice. I am about to implement a dataprovider for reading a large number of xml files...

Preventing Dialogs or Trace.Fail

The System.Diagnostics provide a very nice infrastructure for logging. When you start an app, by default a DefaultTraceListener is added to the Debug.Listeners collection. The problem is that the DefaultTraceListener instance has the property AssertUiEnabled set to true. This will popup a nice message box, in case for example of this statement






In winforms or console apps this is quite nice. Especially the possibility to attempt a retry ...



In case you need to disable this dialog: for a wpf app, for asp.net, for a wcf service... then you simply need to set the AssertUiEnabled property to false. In addition you can wire your own outputs...


Wednesday, November 11, 2009

How much does it cost to resolve with Unity?

The following sample shows how expensive it is to resolve types using a DI container. On my notebook it showed the following:

00:00:00.0040000
00:00:01.7080000
00:00:00.1640000

As you can easily see resolving a type with Unity is something like at least 40 times slower. Is it worth it? I believe yes because you'll catch up with the performance on good design.

Hints: migration from VS2008SP1 -> VS2010Ultimate

1. The 2nd line of the project file has being changed
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">



<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">


When you try to open the migrated project with VS2008 you simply get the following warning:

Project file contains ToolsVersion="4.0", which is not supported by this version of MSBuild. Treating the project as if it had ToolsVersion="3.5".

...all the rest work fine!

2. A whole set of new elements has being added to the default PropertyGroup of the project; all these are not breaking when you try to open the migrated project with VS2008.

<FileUpgradeFlags> 
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
<PublishUrl>http://localhost/Utilities/</PublishUrl>
<Install>true</Install>
<InstallFrom>Web</InstallFrom>
<UpdateEnabled>true</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>true</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>


3. A new element has being added on the PropertyGroup of each configuration; also nothing breaking... VS2008SP1 ignores them.

<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> 


4. A new ItemGroup have being added; also nothing breaking... VS2008SP1 ignores them.

<ItemGroup> 
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.VisualBasic.PowerPacks.10.0">
<Visible>False</Visible>
<ProductName>Microsoft Visual Basic PowerPacks 10.0</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>


5. If your projects have being set to "Treat warnings as errors" then VS2010 is much more sensitive, especially to xmldocumentation mistakes.

Fail: VS2010 Setup


Monday, November 9, 2009

Functional programming using Unity

C# 3.0 comes with functional programming capabilities that can become very handy if combined with a dependency injection framework as Unity.
Take a look at the following example. The function ‘doThis’ can be register in the unity container just like any other instance of a type. At the time of registration the function ‘doThis’ isn’t called yet. It’s not even called at the time of resolving the function ‘doThis’ from the container. This idea is very useful when doing lazy things with Unity.
//create a unity container
IUnityContainer container = new UnityContainer();   
//define a function
Func<bool> doThis = delegate 
{ 
Debugger.Break(); 
return true; 
}; 
//register the function as instance
//function will not execute during registration 
container.RegisterInstance(doThis);
//resolve the function from the container
//function will not execute during the resolving
var f = container.Resolve<Func<bool>>();
//will execute here:-) 
f();

Tuesday, November 3, 2009

UnityContainer Lifetime Management extension methods

The following code snippet  registers the type MySingletonObject to the IMyObject interface as a singleton. The problem is that in order to get the UnityContainer type you need a references to the Microsoft.Practices.Unity.dll and in order to get the ContainerControlledLifetimeManager type you will need a reference to the Microsoft.Practices.ObjectBuilder2.dll

Now if the case is that you need more that ContainerControlledLifetimeManager type from Microsoft.Practices.ObjectBuilder2.dll then it’s worth the reference… if not then the following extension method could help you do the same as before without the need for a reference to Microsoft.Practices.ObjectBuilder2.dll (in a large project you will most likely have some base class library dll with common and shared types; create the extension method there…)


Using the extension method the code now looks like this:



Same idea can be applied for  ExternallyControlledLifetimeManager.

Note that Chris Tavares (from the p&p team) has mentioned in the p&p summit 2009 last month that the next release of Unity will have the Microsoft.Practices.ObjectBuilder2.dll most likely merged into the Unity assembly.

NUnit 2.4.* to NUnit 2.5.* migration / Rhino.Mocks

NUnit 2.5 has changed quite substantially compared with the previous 2.4.8 release, as outlined in the NUnit 2.5 release notes
The problems that I had when migrating tests to NUnit 2.5 were:

  • Assert.IsInstanceOfType has been replaced by Assert.IsInstanceOf
  • NUnit.Framework.SyntaxHelpers namespace no longer exists. All classes that were in this namespace have been moved to the NUnit.Framework namespace
  • Many alias conflicts if using Rhino.Mocks
    using RIs = Rhino.Mocks.Constraints.Is;
    using NIs = NUnit.Framework.Is;
    using RProperty = Rhino.Mocks.Constraints.Property;
    using NProperty = NUnit.Framework.Property;
    using RAssert = NUnit.Framework.Assert;
    using NAssert = NUnit.Framework.Assert;
    using NList = NUnit.Framework.List;
    using RList = Rhino.Mocks.Constraints.List;
  • Has.Length(2); has been replaced by Has.Length.EqualTo(2));
  • Has.Count(1); has been replaced by Has.Count.EqualTo(1);
  • Has.Property("Length", 20) has been replaced by Has.Property("Length")
  • Error 243 Warning as Error: 'NUnit.Framework.Text' is obsolete: 'Use Is class for string constraints'
Good luck migrating