Friday, January 22, 2010

Video series: 3-Tier Pattern Architecture with Unity

E00: Intro
http://www.youtube.com/watch?v=qaL-q4q6OIA

E01: set up the sample application
part1 http://www.youtube.com/watch?v=mUwWU9IUpR0
part2 http://www.youtube.com/watch?v=75iSSZ7o0gs
part3 http://www.youtube.com/watch?v=qg2U6-kG9l0

E02 : Dependency Injection "object management" with Unity
part1: http://www.youtube.com/watch?v=s5rd7mUu89A
part2: http://www.youtube.com/watch?v=XmUQvqjsTYU

E03 : component management "modularity" with Unity
E04 : configurability
E05 : testing/mocking



Sunday, December 6, 2009

ArchitectureSamples-FunqUnity in C#4.0


I have posted a very nice sample application on my googlecode:
ArchitectureSamples-FunqUnity
You can checkout the code with tortoise. You need VS2010 Express or higher. Soon I will post a sibling to this sample also in VB.NET. All necessary binaries: Unity, NUnit and RhinoMocks are committed with the sample for your convenience.

The sample application demonstrates the following architectural aspects:
. Domain Driven Design / Repository Pattern
. Modularity: Type safe registration of services
. Modularity: Xml registration of components
. Modularity: Inject xml configuration
. Dependency Injection
. Unit Tests / Mocks: isolate the repository the layer when testing the application layer
. Functional programming: use lambdas to isolate components in child containers
. Functional programming: use lambdas to isolate ADO.NET infrastructure calls (connections, commands)
. Functional programming: use lambdas to create a database technology factory (sqlce, oledb, ...)

Please sent me comments... If I get enough input I will include more aspects such as:
. Presentation patterns: MVC (console apps)
. Presentation patterns: MVP (win apps and web forms apps)
. Presentation patterns: Presentation Model (wpf and silverlight)
. Data Access Guidance
. Web Services Layer, DTO pattern
. Plug-in patterns
. Domain Driven Design / aggregates, validation, rules

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:

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:


  • 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();