Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, January 24, 2009

Implementing and testing mapping code with AutoMapper

I was thinking some months ago that it would be great to have a property mapper that eliminates tedious mapping code . I'm very happy that Jimmy Bogard and his team just have published a framework called AutoMapper that resolves that issue. I haven't tested it yet but the idea looks promising.

Why would I use AutoMapper?
  • In order to implement better encapsulation and layering with less amount of coding
  • In order to unit-test mapping code using a simple 'Mapper.AssertConfigurationIsValid()'

Sunday, January 11, 2009

TypeMockAutoMocker on CodePlex

I' ve just uploaded the TypeMockAutoMocker to http://www.codeplex.com/typemockautomocker

How to use it:
1.) Download TypeMockAutoMocker.dll
2.) Copy it to your project and set an assembly reference to it
2.) Set 'Copy local = true' on your TypeMock.dll
3.) Have fun (see Link)

StructureMap 2.5.1 and TypeMock 5.1.2 ist the only tested configuration at the moment.

Friday, January 2, 2009

AutoMocking Container with TypeMock Isolator

I have implemented an AutoMocking container for the Isolator inspired by an Introduction to the AutoMocking container in StructureMap, the fact that our test setups usually are pretty messy and Jeremy's claim that TypeMock users probably don't care about dependency injection. But why do I want to use DI (Dependency Injection) in conjunctions with TypeMock? I don't want to fight a 'religious war' based on that question, but here is what I think:

  • TypeMock without DI lacks an explicit boundary that defines what the class under tests is and which classes are mocks or stubs. This is about solid design and to isolate parts of the software in a structured manner. It’s true that you can mock everything with TypeMock but this is just about mocking and not about software design.

  • DI with another mocking framework than TypeMock is like .NET without System.Reflection. I don't like to use System.Reflection but sometimes it's just the right thing. It’s the same with TypeMock. If everything (own code, legacy-code, external libraries etc.) had a solid design you wouldn't need it but sometime it makes the life so much easier.
Example without Dependency Injection
There is the class under test called ValidationViewPresenter and it has following dependencies:



A a test without DI could look like:
[Test]
public void CanValidateCreditCardNumber()
{
// Arrange
var viewMock = Isolate.Fake.Instance<ValidationView>();
var customerServiceMock = Isolate.Fake.Instance<CustomerService>();
var creditCardServiceMock = Isolate.Fake.Instance<CreditcardService>();
var customer56 = new Customer {CreditCardNr = "5500 0001 0001 0001"};

// Mock the (hidden) dependencies
Isolate.Swap.NextInstance<ValidationView>().With(viewMock);
Isolate.Swap.NextInstance<CustomerService>().With(customerServiceMock);
Isolate.Swap.NextInstance<CreditcardService>().With(creditCardServiceMock);
// Mock the calls to the dependencies
Isolate.WhenCalled(()=>viewMock.CustomerNr).WillReturn(56);
Isolate.WhenCalled(() => customerServiceMock.GetCustomer(56)).WillReturn(customer56);
Isolate.WhenCalled(()=> creditCardServiceMock.ValidateCreditCard("5500 0001 0001 0001")).WillReturn(true);

// Act
  var presenter = new ValidationViewPresenter();

presenter.ValidateCreditCardOfCustomer();
// Assert
Isolate.Verify.WasCalledWithExactArguments(() => viewMock.IsValid = true);
}

Example with Dependency Injection
After introducing constructor injection it looks like:
[Test]
public void CanValidateCreditCardNumber()
{
// Arrange
var viewMock = Isolate.Fake.Instance<ValidationView>();
var customerServiceMock = Isolate.Fake.Instance<CustomerService>();
var creditCardServiceMock = Isolate.Fake.Instance<CreditcardService>();
var customer56 = new Customer {CreditCardNr = "5500 0001 0001 0001"};
// Inject dependencies manually
  var presenter = new ValidationViewPresenter(viewMock, customerServiceMock, creditCardServiceMock);

Isolate.WhenCalled(()=> viewMock.CustomerNr).WillReturn(56);
Isolate.WhenCalled(() => customerServiceMock.GetCustomer(56)).WillReturn(customer56);
Isolate.WhenCalled(() => creditCardServiceMock.ValidateCreditCard("5500 0001 0001 0001")).WillReturn(true);

// Act
presenter.ValidateCreditCardOfCustomer();

// Assert
Isolate.Verify.WasCalledWithExactArguments(() => viewMock.IsValid = true);
}

Example with Automocking Container
Let's eliminate the explicit constructor injection by introducing the TypeMockAutoMocker now:

[Test]
public void CanValidateCreditCardNumber()
{
// Arrange
var customer56 = new Customer {CreditCardNr = "5500 0001 0001 0001"};
  var presenterMocker = new TypeMockAutoMocker<ValidationViewPresenter>(MockMode.AAA);

var viewMock = presenterMocker.Get<IValidationView>();
var customerServiceMock = presenterMocker.Get<ICustomerService>();
var creditCardServcieMock = presenterMocker.Get<ICreditCardService>();

Isolate.WhenCalled(() => viewMock.CustomerNr).WillReturn(56);
Isolate.WhenCalled(() => customerServiceMock.GetCustomer(56)).WillReturn(customer56);
Isolate.WhenCalled(() => creditCardServcieMock.ValidateCreditCard("5500 0001 0001 0001")).WillReturn(true);

// Act
presenterMocker.ClassUnderTest.ValidateCreditCardOfCustomer();

// Assert
Isolate.Verify.WasCalledWithExactArguments(() => viewMock.IsValid = true);
}
As you can see the AutoMocking container couldn’t eliminate a lot of complexity. This is due to the fact that the test itself is complex and there are a number of non-default preconditions.

A better example with AutoMocking Container
Following code tests the same method but with different preconditions again. But this time we can rely on the default behavior that was setup by the AutoMocking container. This means that all involved and not explicitly mocked interfaces or classes do have a default behavior.

[Test]
public void CanHandleNotExistingCustomer()
{
// Arrange
  var presenterMocker = new TypeMockAutoMocker<ValidationViewPresenter>(MockMode.AAA);

var viewMock = presenterMocker.Get<IValidationView>();
Isolate.WhenCalled(() => viewMock.CustomerNr).WillReturn(56);

// Act
presenterMocker.ClassUnderTest.ValidateCreditCardOfCustomer();

// Assert
Isolate.Verify.WasCalledWithExactArguments(() => viewMock.IsValid = false);
}
Conclusion
There is a big chance that you can get lost using TypeMock and StructureMap in conjunction. The problem is that there are too many ways how they can be combined. However I hope that the TypeMockAutoMocker could help in a way that it's defining a common pattern for how to setup the tests and how to inject the mocks. Remember always:
  • Depended classes are instantiated by the AutoMocker automatically.
  • Depended interfaces and abstract classes are instantiated as mocks. These mocks do have a default behaviour where every method can be called.
  • Depended concrete classes are instantiated by calling its greediest constructor. They are not mocked.
  • To change the default behaviour you can use Inject() to register your own mock to the AutoMocker. It's how you can setup a mock manually.

Sound’s like ‘convention over configuration’. And that makes life definitely easier.


Thursday, October 16, 2008

Reflecting about how we implement aggregates

How we implement aggregates

Since the beginning of my current project we tried to apply the ideas of structuring our business-logic into aggregates. We started to implement the aggregates using the following guidelines:

  • define an aggregate root and implement it as a public class
  • define the internal classes of an aggregate and implement it as a public class
  • implement a repository that can query and return aggregate roots of this class
  • try to avoid accessing the internals (like traversing from aggregate root to an internal class) from outside the aggregate
  • put as much as possible of the business-logic into the aggregate root

Following this rules we had some sort of guidelines about where to locate the business-logic and when to implement a repository. I think it was worth to have the aggregates. It was a valuable concept when we had to change our application from a 2-tier to a 3-tier architecture.

Nevertheless we always had following problems with aggregates:

  • Most of the time we had code in the presentation-layer that accessed the internals of an aggregate. It appeared often in case where there was an one-to-one data binding. For instance, in a master-detail view, where the master was the aggregate root an the detail an internal entity of the aggregate. (e.g. editing invoice and invoice position)
  • There were relations on the data model that do not comply the aggregate rules. In such a case we often had a nice definition of an aggregate, however there was sometimes a nasty dependency. It happend that an internal entity was depending on another entity in another aggregate. We agreed that this is not bad and that it can be abstracted to a dependency between the two involved aggregates.
And what happened:

  • Since the internals could be accessed, the business-logic begun to spread out into the presentation layer. It's impossible always to have the discipline to comply the aggregate rules and all of us violated it from time to time.
  • We didn't centralize the creational-logic. The test code is often a mess and it deals with setting-up the aggregates as well the internals of an aggregate.
  • A NDepend-analyse revealed that our business-logic assembly will be a serious maintenance problem ('Zone of pain')

Why is our business-logic in the zone of pain?

We generally get closer to the 'zone of pain' (see link for details), when a high number of types in an assembly:

  1. are more concrete than abstract (see Abstractness in the formula)
  2. are used a lot by other assemblies (see Ca in the formula)
  3. do not depend on other types (see Ce in the formula)

Since I can't see any value in implementing business-logic abstract (1.) and our business-logic already depends on a small number of types in other assemblies (2.) the only variable would be to reduce the number of types that are used by other assemblies (3.).

How could we do it different?

We could try to better encapsulate the internals of an aggregate avoiding the problems described above. That means, not allowing to access any internals by another type than the aggregate root. This increases the afferent coupling of the aggregate root, on the other hand eliminates the afferent coupling of the internals. The afferent coupling of the business logic assembly itself would then decrease.

Therefore I transformed one of our aggregates from something like that

// File Invoice.cs
public class Invoice
{
public EntitySet<InvoicePosition> Positions { get; set; }
}
public class InvoicePosition
{
}

to

// File Invoice.cs
public partial class Invoice
{
private EntitySet<Invoice.InvoicePosition> Positions { get; set; }
}
// File InvoicePosition.cs
public partial class Invoice
{
private class InvoicePosition
{
}
}
After completing the refactoring and changing some logic in the presentation layer I got the following code metrics:

  1. The assembly containing the business logic moved a little bit away from the zone of pain (from D=0.577 to 0.575). This is still bad, however the refactoring had a positive effect.
  2. The type-rank for the refactored aggregate root increased from 10.7 to 12. Ca (Afferent coupling) increased from 62 to 66. That means, it got a more important part of the business logic.
  3. The CC (cyclomatic complexity) for the aggregate root increased from 38 to 77, while CC decreased generally for the presentation layer (e.g. in one case from 26 to 16). That means that we put complexity into the business logic. It's a good thing since the complexity generally is easier to test and therefore to maintain in the business logic. It was also possible to eliminate duplicated business logic found in the presentation layer.

Testability and Unittests

As the internals are completely hidden from outside now I test the refactored aggregate with state-based black-box tests. I think that's a reasonable way to do it since the test setup do not depend anymore on the implementation details of an aggregate. I'm not sure if this should be a general testing strategy for aggregates. I think there are more complex cases, where white-box tests would still be needed. The following pictures shows on the left, the test-code before the refactoring and on the right, the test-code after:

Friday, March 21, 2008

Some thoughts about C# 3.0

We have been using the new C#3.0-features for two months and its quite interesting that our code looks in some parts like Jeremy describes in C#3.0 is like a moped. I wouldn't like to miss the new features and I won't stop using them but I'm thinking it's getting too much.

It makes me feel that C# already had it's best time and there should be something new. Where is the new microsoft-ruby-language? C# was a better Java (I mean the language not the community) but where is now the better ruby?

Sunday, January 13, 2008

Behind the scences of LINQ

I always knew that LINQ was founded on the idea of monads but even trying hard I couldn't understand how LINQ and monads are related to each other.

But fortunately there is Wes Deyer and he describes in The Marvels of Monads what I always wanted to know. It's a pity that LINQ was always described and documented as query language rather than as a monad extensions. When I look to the msdn-documentation there is no hint that I could implement query operators on other types than IEnumerable and IQueryable.

But that's exactly what Wes is doing. He sees a more general concept and he shows a way to implement the query operators on any type. In fact this is for me a huge step and leads us to a new level of abstraction where LINQ (as a list-monad) seems to be a specific case of a monad.

My preferred way to use LINQ was the method syntax as I thought this is the more general case. But now, after knowing that the query syntax is something like a monad extension I start to like it.

Saturday, December 29, 2007

Playing around with NBehave

As I said recently I'm still exploring tdd and its capabilities. The next evolutionary step could be bdd. Therefore I downloaded NBehave and I tried to write one story with it. Passive View is my preferred playground and thats how it goes with NBehave and TypeMock.NET:

First the declaration of the View, the Presenter and a Service-Gateway that is used by the Presenter to retrieve some information.
protected IView _view;
protected Presenter _presenter;
protected EventHandler _updateRequestedEvent;
protected IServiceGateway _serviceGatway;

The setup of the this objects is not showed here. It simples instantiates mocks for the View and the ServiceGateway and injects it into the Presenter using Constructor-Injection. The _updateRequestedEvent is a mocked event on the view and is also used later in the example.

First I have to specify a story. This is done like that:

[TestFixtureSetUp]
public void FixtureSetup()
{
_getCurrentTimeStory = new Story("Getting the current service time");
_getCurrentTimeStory.AsA("User").IWant("to update the displayed current time")
.SoThat("I can see what time is on the serivce side");
}

And that's one scenario that came in my mind:

[Test]
public void HelloNTServiceIsNotAvailable()
{
using (RecordExpectations recorder = RecorderManager.StartRecording())
{
_view.ShowMessageBox("The Service is currently not available");
recorder.CheckArguments();
}
_getCurrentTimeStory.WithScenario("Service is not available")
.Given("the Service returns an exception", new Exception("Error"), e =>
{
using (RecordExpectations recorder = RecorderManager.StartRecording))
{
recorder.ExpectAndThrow(_serviceGatway.GetTime(), e);
}
})
.When("I update the current time", () => _updateRequestedEvent(this, EventArgs.Empty))
.Then("a message box should display", "The Service is currently not available", m =>
{
MockManager.Verify();
})
;
}

Looks quite chaotic and a developer not used to NUnit,TypeMock and NBehave might not understand it at first glance. I also think the combination of NUnit,TypeMock and NBehave is a little bit strange as they do not integrate very well. Maybe there is another way how to combine those frameworks?

But what I like is the overall structure that it gives to the tests and the readable test output that can be interpreted by a product owner. Here are now the scenario above and another scenario that I could present to him:

Story: Getting the current service time

Narrative:
As a User
I want to update the displayed current time
So that I can see what time is on the serivce side

Scenario 1: Service is not available
Given the Service returns an exception: System.Exception: Error
When I update the current time
Then a message box should display: The Service is currently not available

Scenario 2: Service is available
Given the Service returns the time: 01.01.2000 12:24:23
When I update the current time
Then the label on the view should display: 12:24

Sunday, December 16, 2007

Evaluating a dependency injection framework

I heard the first time about tdd in the year 2002 when a colleague of mine introduced me to a tool called 'NUnit'. I found tdd very helpful from the beginning and I was always one of them that pushed that paradigm and mindset. I learned like a lot of the other tdd enthusiasts, that 'test first' is good, that 'test isolation' is really necessary, that a 'mocking framework' helps a lot, and that it's all about a good design. On this journey I'm now at a point where I question: could a 'dependency injection framework' help?

That is what I tried to find out today and what this post is about. I wrote a simple application including:
  • a wpf client with one window called Window1
  • a wcf service called Service with one Methode GetDate() that returns the current date and time
  • one assembly testing the wpf-presentation and wcf-service (just unit-tests)

Introducing a DI-Framework

One trying to write tests in such an environment knows that integrating the real wpf- and wcf-environment into the tests is a bad idea. Instead it's better to stub and mock those environments to get easier, more stable, and faster tests. This means we usually want a test-configuration where the most external dependencies (like wpf or wcf) are mocks or stubs. On the other hand we want to have a configuration on a deployed system that utilizes the real dependencies. So it's something about configuration and that's where the DI-frameworks come into play.

I decided to give Jeremy's StructureMap a try because it doesn't look so overloaded like Sprint.NET or Windsor.

Following code shows my wcf-service IService that I include in the presentation-layer as a Service-Gateway (see also ServiceStub-Pattern):


[ServiceContract]
public interface IService
{
[OperationContract]
DateTime GetTime();
}
/// <summary>
/// Gateway to intercept for testing
/// </summary>
public interface IServiceGateway : IService
{
void Close();
}
/// <summary>
/// Real gateway using the wcf generated ServiceClient class
/// </summary>
public class ServiceGateway : IServiceGateway
{
private readonly ServiceClient _service;

public ServiceGateway()
{
_service = new ServiceClient();
}

public void Close()
{
_service.Close();
}

public DateTime GetTime()
{
return _service.GetTime();
}
}
/// <summary>
/// Stub for testing
/// </summary>
public class ServiceGatewayStub : IServiceGateway
{
public void Close()
{
}

public DateTime GetTime()
{
return new DateTime(2000, 1, 1, 12, 34, 55, 12);
}
}
Step 1:
Using the following code to resolve the reference to the external wcf-service

IServiceGateway gateway = ObjectFactory.GetInstance<IServiceGateway>()
and using the following configuration for the tests

<StructureMap>
<DefaultInstance PluginType="HelloNTPresentation.IServiceGateway,HelloNTPresentation" PluggedType="HelloNTService.ServiceGatewayStub,HelloNTTests" Scope="Singleton"/>
</StructureMap>
I could wire the code during the tests to the ServiceGatewayStub instead of the real ServiceGateway.

Step 2:
I didn't like that because it meant that we have to setup a configuration for the real (not test) environment like:

<StructureMap>
<DefaultInstance PluginType="HelloNTPresentation.IServiceGateway,HelloNTPresentation" PluggedType="HelloNTPresentation.ServiceGateway,HelloNTPresentation" Scope="Singleton"/>
</StructureMap>
After I have had read how to build an IoC container in 15 lines of code I thought that DI can't be so difficult and I tried to build my own DI-framework. I liked very much that I could configure the DI in the code now and eliminate the file-based configuration:
      ObjectFactory.Register<IServiceGateway>(() => new ServiceGatewayStub());
IServiceGateway gateway = ObjectFactory.Create<IServiceGateway>();
All tests were green and I was happy to start the refactored sample application first time after. But there was big surprise when it crashed. I had forgotten to configure DI for the wcf-service and wpf-service. But where should I put that configuration? Both of them run in some kind of hosted environment and I wasn't able to find a nice place to put that configuration-code. So I realized that it's a little bit harder than I thought to write an own DI-Framework.

Step 3:
Back to StructureMap I found a way to minimize the file-based configuration. The solution was to use the attributes PluginFamily and Pluggable that define default behaviour. In this case the class ServiceGateway is the default implementation of IServiceGateway and there is no need to configure it for the wcf-service and the wpf-client anymore.

    [ServiceContract]
public interface IService
{
[OperationContract]
DateTime GetTime();
}
[PluginFamily("ServiceGateway")]
public interface IServiceGateway : IService
{
}
[Pluggable("ServiceGateway")]
public class ServiceGateway : IServiceGateway
{
}
Step 4:
Now let's have a look to following the presenter (presenter is what is responsible for the presentation-logic):

    public class Presenter: IDisposable
{
readonly IView _view;
readonly IServiceGateway _service;

public Presenter(IView view, IServiceGateway service)
{
_view = view;
_service = service;
}
}
That presenter shows all internal dependencies on its constructor. This enables us to use constructor injection when writing tests with a Mock-Framework (e.g. TypeMock)
     _serviceGatway = RecorderManager.CreateMockedObject<IServiceGateway>();
_view = RecorderManager.CreateMockedObject<IView>();
_presenter = new Presenter(_view, _serviceGatway);
But what's about the others that don't want to bother about providing those dependencies to the constructor? And that's where the DI-framework gets really valueable because it enables us to instantiate concrete classes without providing the needed arguments to the constructor. Following code is from the wpf-client and shows how this is done:

    Presenter presenter = ObjectFactory.FillDependencies<Presenter>();
Just for completeness, I have to mention how I configured IView:

    [PluginFamily("Window1")]
public interface IView
{
}
[Pluggable("Window1")]
public partial class Window1 : Window, IView
{
}
Summary

  • I always used constructor injection but with a DI-framework it gets easier because the client code doesn't need to manage the dependencies anymore.
  • I like StructureMap because it looks simple and it works.

Tuesday, December 11, 2007

Offline data synchronization

I wrote a few days before that it looked like I would get involved in a SOA-project. Today it looks like I will get involved in another project! This new project could have following technical characteristics:
  • said to be a rich-client-project
  • support for offline disconnected scenarios (offline agents)
  • distributed application (Internet, intranet or some kind of private network)
  • integration with a backend system (no idea what kind of interface that would be)

Sounds interesting .... So I bought yesterday something about WPF to update myself with 'state of the art rich client development'.

Maybe the new Microsoft Synch Framework could be interesting in that context too. I watched this and it looks promising. I have to admit that I hate that kind of presentations but it looks that it's flexible and can be extended. I'm not yet sure about that but at least the synch-runtime can be instantiated in a object-oriented manner and that's always a good sign. Would be great if it could be connected to a service instead of a database.

Saturday, December 1, 2007

excpetion handling could be easy

We have been doing a major refactoring in our project trying to get rid of the legacy exception handling. As we went through our code we had some good laughs (we shouldn't have laughed as we still have to maintain that for a long time) and it was obvious that some developers had no clue about how to deal with exceptions or were too lazy to implement a more sophisticated handling. It seemed that some developers didn't miss any opportunity to get rid of that nasty exceptions. It seemed that we were fighting a .NET-bug called 'Exception'.

We also had a lot of discussons about exceptions, especially because we wanted to eliminate exception swallowing but not to change the user experience! Our product manager stated that it's better to have an obscure behaviour that the users knows than a new fancy error dialog that indicates problems at the root. (Users don't like fail fast!)

I didn't want to talk about that stuff but I have just come across some similar thoughts:

http://grabbagoft.blogspot.com/2007/11/stop-madness.html (see Try Catch Publish Swallow)
http://grabbagoft.blogspot.com/2007/06/swallowing-exceptions-is-hazardous-to.html
http://grabbagoft.blogspot.com/2007/06/re-throwing-exceptions.html

Tuesday, November 20, 2007

Expresso - Regextool and others

I used Expresso first time today and I liked it much more than the Regulator that I've used up to now . The 'Regex Analyzer'-View and the 'Search Result'-View display the Regex and the matches as a tree and this helps me a lot in understanding Regex's.

I've always wanted to mention that I'm using a visual studion plugin named Cool Commands. I'm using just one command of it: 'Collapse All Projects' . It collapses my 20 projects in a solution with one click! Will the brand-new visual studio 2008 support that out of the box?

Monday, May 28, 2007

p geht zu f

Mit der nächsten Version von .NET (Codename 'Orcas') werden wir tagtäglich mit Lambda-Ausdrücken arbeiten. Doch wie spricht man ein Lambda-Ausdruck überhaupt aus?

Was ist zum Beispiel mit p => f => f(p) ?

Wes Dyer vom C# Compiler Team spricht es in einem Interview als 'goes to' aus. In Englisch ist das also p goes to f goes to f(p). Ich finde dies in Ordnung aber beim Einsetzen der Variable f im Ausdruck f => f(p) finde ich das 'goes to' ungenau, da neben dem Binden der Variable f auch gleich die Funktionsapplikation f(p) stattfindet.

Eric White spricht in seinem Blogeintrag, abhängig von jeweiligen Kontext, von einem 'becomes' oder 'such that'.

Für das oben genannte Beispiel finde ich p goes to f becomes f(p) das Beste, weil der Lambda-Ausdruck in folgenden Schritten evaluiert wird:
  1. 'p => f' oder 'p goes to f', da nach dem Einsetzen der Variable p eine anonyme Methode resultiert welche p bindet und f als Parameter hat. In dem Sinne geht also p zu f, oder eben 'p goes to f'.
  2. 'f => f(p)' oder 'f becomes f(p)', da nach dem Einsetzen von f die Funktion f(p) ausgeführt wird. In dem Sinne wird als f in f(p) umgewandelt, was auf Englisch dann auch als 'f becomes f(p)' ausgesprochen werden kann.

Ich werde also in Zukunft das letzte '=>' als 'becomes' und alle vorangehenden '=>' als 'goes to' aussprechen.

Beispiele:

  • 'a => b => a+b' ist 'a goes to b and becomes a+b'
  • 'a => 1 + a' ist 'a becomes 1+a'