NHibernate cache system. Part 1

31 December 2011 | View comments (1)

In this series of articles I will try to explain you how NHibernate cache system works and how it should be used in order to get the best performance/configuration from this product.

NHibernate Cache architecture

NHibernate has an internal cache architecture that I will define absolutely well done. On an architectural point of view, it is designed for the enterprise and it is 100% configurable. Consider that it allows you to create also your custom cache provider!

The following picture show the cache architecture overview of NHibernate (actually the version I am talking about is the 3.2 GA).

image

The cache system is composed by two levels, the cache of level 1 that usually it is configured by default if you are working with the ISession object, and the cache of level 2 that by default is disabled.

The cache of level 1 is provided by the ISession data context and it is maintained by the lifecycle of the ISession object, this means that as soon as you destroy (dispose) an ISession object, also the cache of level 1 will be destroyed and all the corresponding objects will be detached from the ISession. This cache system works on a per transaction basis and it is designed to reduce the number of database calls during the lifecycle of an ISession. As an example, you should use this cache if you have the need to access and modify an object in a transaction, multiple times.

The cache of level 2 is provided by the ISessionFactory component and it is shared across all the session created using the same factory. Its lifecycle correspond to the lifecycle of the session factory and it provides a more powerful but also dangerous set of features. It allows you to keep objects in cache across multiple transactions and sessions; the objects are available everywhere and not only on the client that is using a specific ISession

Cache Level 1 mechanism

As soon as you start to create a new ISession (not an IStatelessSession!!) NHibernate starts to holds in memory, using a specific mechanism, all the objects that are involved with the current session. The methods used by NHibernate to load the data into the cache are two: Get<T>(id) and Load<T>(id). This means that if you try to load one or more entities using: LinQ, HQL, ICriteria … NHibernate will not put them into the cache of level 1.

Another way to put an object into the lvl1 cache is to use persistence methods like Save, Delete, Update and SaveOrUpdate.

image

As you can see from the previous picture, the ISession object is able to contains two different categories of entities, the one that we define “loaded” using Get or Load and the one that we define “dirty”, which means that they were somehow modified and associated with a session.

Load and Get, what’s the difference?

A major confusion I personally noticed while working with NHibernate is the not correct usage of the two methods Get and Load so let’s see for a moment how they work and when they should or should not be used.

Get

Load

 

Fetch method

Retrieve the entire entity in one SELECT statement and puts the entity in the cache.

Retrieve only the ID of the entity and returns a non fetched proxy instance of the entity. As soon as you “hit” a property, the entity is loaded.

How it loads

It verifies if the entity is in the cache, otherwise it tries to execute a SELECT

It verifies if the entity is in the cache, otherwise it tries to execute a SELECT

Not Available

If the entity does not exist, it returns NULL

If the entity does not exist, it THROW an exception

 

I personally prefer Get because it returns NULL instead of throwing a nasty exception, but this is a personal choice; while some of you may prefer to use Load because you want to avoid a database call until is really needed.

Below I wrote a couple of very simple tests to show you how the Get and Load methods work across the same ISession.

Get<T>()

   1:  [Test]
   2:  [Category("Database")]
   3:  public void UsingGetThePersonIsFullyCached()
   4:  {
   5:      using (var session = factory.OpenSession())
   6:      {
   7:          using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
   8:          {
   9:              var persons = MockFactory.MakePersons();
  10:              persons.ForEach(p => session.Save(p));
  11:              tx.Commit();
  12:              session.Clear();
  13:              Console.WriteLine("*** FIRST SELECT ***");
  14:              var expectedPerson1 = session.Get<Person>(persons[0].PersonId);
  15:              Assert.That(expectedPerson1, Is.Not.Null);
  16:              Console.WriteLine("*** SECOND SELECT ***");
  17:              var expectedPerson2 = session.Get<Person>(persons[0].PersonId);
  18:              Assert.That(expectedPerson2, Is.Not.Null);
  19:              Assert.That(expectedPerson2.FirstName, Is.Not.EqualTo(string.Empty));
  20:          }
  21:      }
  22:  }

In this test I have created a list of Persons in one transaction and then I cleared the session in order to be sure that nothing was left in the cache. Then I loaded one of the Person entities using the Get<T> method and then I load it again using the same method call in order to verify that the SELECT statement was issued only once.

image

As you can see, NHibernate is loading the entire entity from the database in the first call, and in the second one is simply loading it again from the level 1 cache. You should notice here that NHibernate is loading the entire entity in the first Get<T> call.

Load<T>()

[Test]
[Category("Database")]
public void UsingLoadThePersonIsPartiallyCached()
{
    using (var session = factory.OpenSession())
    {
        using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
        {
            var persons = MockFactory.MakePersons();
            persons.ForEach(p => session.Save(p));
            tx.Commit();
            session.Clear();
            Console.WriteLine("*** FIRST SELECT ***");
            var expectedPerson1 = session.Load<Person>(persons[0].PersonId);
            Assert.That(expectedPerson1, Is.Not.Null);
            Console.WriteLine("*** SECOND SELECT ***");
            var expectedPerson2 = session.Load<Person>(persons[0].PersonId);
            Assert.That(expectedPerson2, Is.Not.Null);
            Assert.That(expectedPerson2.FirstName, Is.Not.EqualTo(string.Empty));
        }
    }
}

In this second test I am executing the same exact steps of the previous one, but this time I am using the Load<T> method and the result is completely different! Look at the SQL log below:

image

Now NHibernate is not loading the entity from the database at all, it is loading it only in the second call, when I try to hit one of the Person properties. If you debug this code you will notice that NHibernate issues the database call at the line Assert.That(expectedPerson2.FirstName, Is.Not.EqualTo(string.Empty)); and not before!

Session maintenance

If you are working with the ISession object in a Client application or if you are keeping it alive in a web application using some strange behaviors like keeping it saved inside the HttpContext you will realize, soon or later, that sometimes the cache of level 1 needs to be cleared.

Now, despite the fact that these methods (based on my personal experience) should never be used, because it means that you are wrongly implementing your data layer, and despite the fact that the behavior of these methods may result in something unexpected, NHibernate provides three different methods to clear the cache of level 1 content.

 

Session.Clear

 

Session.Evict

 

Session.Flush

 
             
 

Removed all the existing objects from the ISession without syncing them with the database

Remove a specific object from the ISession without syncing it with the database

Remove all the existing objects from the session by syncing them with the database

I will probably write more about these three methods in some future post but if you need to investigate more about them, I would suggest you to read carefully the NHibernate docs available here: http://www.nhforge.org/doc/nh/en/index.html

In the next article we talk about the level 2 cache.

NHibernate cache system. Part 2

31 December 2011 | View comments (0)

In the previous post we saw how the cache system is structured in NHibernate and how it works. We saw that we have different methods to play with the cache (Evict, Clear, Flush …) and they are all associated with the ISession object because the cache of level 1 is associated with the lifecycle of an ISession object.

In this second article we will see how the second level cache works and how it is associated with the ISessionFactory object that is in charge of controlling this cache mechanism.

Second Level cache architecture

How does the second level cache work?

image

First of all, when an entity is cached in the second level cache, the entity is disassembled into a collection of keys/values pair, like a dictionary and persisted in the cache repository. This mechanism is accomplished because most of the second level cache providers are able to persist serialized dictionary collections and because in the same time NHibernate does not force you to make serializable your entities (something that IMHO, should never be done!!).

A second mechanism happens when we cache the result of a query (Linq, HQL, ICriteria) because these results can’t be cached using the first level cache (see previous blog post). After we cache a query result, NHibernate will cache only the unique identifiers of the entities involved in the result of the query.

Third, NHibernate has an internal mechanism that allows him to know and keep track of a timestamp value used to write tables or to work with sessions. How does it work? Well the mechanism is pretty clear, it keeps track of when the last table was written too. A series of mechanism will update this timestamp information and you can find a better explanation of Ayende’s blog: http://ayende.com/blog/3112/nhibernate-and-the-second-level-cache-tips.

Configuration of the second level cache

By default the second level cache is disabled. If you need to use the second level cache you have to let NHibernate know about that. The hibernate.cfg file has a dedicated section of parameters that should be used to enable the second level cache:

<property name="cache.provider_class">
   NHibernate.Cache.HashtableCacheProvider
</property>
<!-- You have to explicitly enable the second level cache ->
<property name="cache.use_second_level_cache">
   true
</property> 

First of all we specify the cache provider we are using, in this case I am using the standard hashtable provider, but I will show you in the next article what are the real providers you should use. Second we say that the cache should be enabled; this part is really important because if you do not specify that the cache is enable, it simply won’t work … Confused smile

Then you may provide to the cache a default expiration in seconds:

<!-- cache will expire in 2 minutes -->
<property name="cache.default_expiration">120</property>

If you want to add additional configuration properties, they will be cache provider specific!

Cache by mapping

One of the possible configuration is to enable the cache at the entity level. This means that we are marking our entity as “cachable”.

<class
   name="CachableProduct“
   table="[CachableProduct]“
   dynamic-insert="true“
   dynamic-update="true">
   <cache usage="read-write"/>

In order to do that we have to introduce a new tag, the <cache> tag. In this tag we can specify different type of "”usage”:

  • Read-write
    It should be used if you plan also to update the data (no with serializable transaction)
  • Read-only
    Simplest and best performing, for read only access
  • Nonstrict-read-write
    If you need to occasionally update the data. You must commit the transaction
  • Transactional
    not documented/implemented yet because no one cache provider allows transactional cache. It is implemented in the Java version because J2EE allow transactional second level cache

Now, if we write a simple test that will create some entities and will try to retrieve them using two different ISession generated by the same ISessionFactory we will get the following behavior:

using (var session = factory.OpenSession())
{
   // create the products
    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        Console.WriteLine("*** FIRST SESSION ***");
        var expectedProduct1 = session.Get<CachableProduct>(productId);
        Assert.That(expectedProduct1, Is.Not.Null);
        tx.Commit();
        // retrieve the number of hits we did to the 2nd level cache
        Console.WriteLine("Second level hits {0}", 
           factory.Statistics.SecondLevelCacheHitCount);
    }
}
using (var session = factory.OpenSession())
{
    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        Console.WriteLine("*** SECOND SESSION ***");
        var expectedProduct1 = session.Get<CachableProduct>(productId);
        Assert.That(expectedProduct1, Is.Not.Null);
        tx.Commit();
        // retrieve the number of hits we did to the 2nd level cache
        Console.WriteLine("Second level hits {0}", 
           factory.Statistics.SecondLevelCacheHitCount);
    }
}

The result will be the following:

image

As you can see the second session will access the 2nd level cache using a transaction and will not use the database at all. This has been accomplished just by mapping the entity with the <cache> tag and by using the GET<T> method.

Let’s make everything a little bit more complex. Let’s assume for a second that our object is an aggregate root and it is more complex than the previous one. If we want to cache also a collection of child or a parent reference we will need to change our mapping in the following way:

<!-- inside the product mapping file -->
<bag name="Attributes" cascade="all" inverse ="true">
  <cache usage="read-write"/>
  <key column="ProductId" />
  <one-to-many class="CacheAttribute"/>
</bag> 
<!-- inside theCacheAttribute file -->
<class
    name="CacheAttribute"
    table="[CacheAttribute]"
    dynamic-insert="true"
    dynamic-update="true">
  <cache usage="read-write"/>
  <!-- omit -->
  <many-to-one 
     class="CachableProduct" 
     name="Product" cascade="all">   
    <column name="ProductId" />
  </many-to-one>
</class>

Now we can execute the following test (I am omitting some parts for saving space, I hope you don’t mind …)

using (var session = factory.OpenSession())
{
    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        Console.WriteLine("*** FIRST SESSION ***");
        var expectedProduct1 = session.Get<CachableProduct>(productId);
        Assert.That(expectedProduct1, Is.Not.Null);
        Assert.That(expectedProduct1.Attributes, Has.Count.GreaterThan(0));
        tx.Commit();
        Console.WriteLine("Second level hits {0}", 
           factory.Statistics.SecondLevelCacheHitCount);
    }
 
}
using (var session = factory.OpenSession())
{
    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        Console.WriteLine("*** SECOND SESSION ***");
        var expectedProduct1 = session.Get<CachableProduct>(productId);
        Assert.That(expectedProduct1, Is.Not.Null);
        Assert.That(expectedProduct1.Attributes, Has.Count.GreaterThan(0));
        tx.Commit();
        Console.WriteLine("Second level hits {0}", 
           factory.Statistics.SecondLevelCacheHitCount);
    }
}

And this is the result from the profiled SQL:

image

In this case the second ISession is calling the cache 4 times in order to resolve all the objects (2 products x 2 categories).

Cache a query result

Another way to cache our result is by creating a cachable query that is slightly different than creating a cachable object.

Important note:

In order to cache a query we need to set the query as “cachable” and then set the corresponding entity as “cachable” too. Otherwise NHB will cache the ID of the entity but then it will always fetch the entity and cache only the query result.

To write a cachable query we need to implement an IQuery object in the following way:

using (var session = factory.OpenSession()) {
     using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
     {
        var result = session
             .CreateQuery("from CachableProduct p where p.Name = :name")
             .SetString("name", "PC")
             .SetCacheable(true)
             .List<CachableProduct>();
        tx.Commit();
     }
 }

Now, let’s try to write a unit test for this:

using (var session = factory.OpenSession())
{
    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        Console.WriteLine("*** FIRST SESSION ***");
        var result = session
            .CreateQuery("from CachableProduct p where p.Name = :name")
            .SetString("name", "PC")
            .SetCacheable(true)
            .List<CachableProduct>();
        Console.WriteLine("Cached queries {0}", 
             factory.Statistics.QueryCacheHitCount);
        Console.WriteLine("Second level hits {0}", 
             factory.Statistics.SecondLevelCacheHitCount);
        tx.Commit();
    }
}
using (var session = factory.OpenSession())
{
    using (var tx = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        Console.WriteLine("*** SECOND SESSION ***");
        var result = session
            .CreateQuery("from CachableProduct p where p.Name = :name")
            .SetString("name", "PC")
            .SetCacheable(true)
            .List<CachableProduct>();
        Console.WriteLine("Cached queries {0}", 
             factory.Statistics.QueryCacheHitCount);
        Console.WriteLine("Second level hits {0}", 
             factory.Statistics.SecondLevelCacheHitCount);
        tx.Commit();
    }
}

And this is the expected result:

image

In this case the cache is telling us that the second session has 1 query result cached and that we called it once.

Final advice

As you saw using the 1st and 2nd level cache is a pretty straightforward process but it requires time and understanding of NHibernate cache mechanism. Below are some final advice that you should keep in consideration when working with the 2nd level cache:

  • 2nd Level Cache is never aware of external database changes!
  • Default cache system is hashtable, you must use a different one
  • Wrong implementation of the 2nd level cache may result in a non expected performance degrade (i.e. hashtable doc)
  • First level cache is shared across same ISession, second level is shared across same ISessionFactory

In the next article we will see what are the available cache providers.

NHibernate cache system. Part 3

31 December 2011 | View comments (0)

In this series of articles we saw how the cache system is implemented in NHibernate and what can we do in order to use it. We also saw that we can choose a cache provider but we didn’t have a look yet at what providers we can use.

I personally have my own opinion about the 2nd level cache providers available for NHibernate 3.2 and I am more than happy if you would like to share with me your experience about it.

Below is a list of the major and the most famous 2nd level cache providers I know:

image

I would personally suggest you to answer the following questions in order to understand what is the cache provider you need for your project:

  • Size of you project (small, standard, enterprise)
  • Cache technology you have already in place
  • Quality attributes required by your solution (scalability, security, …)

SysCache

SysCache and the most recent SysCache2 is a cache provider built on top of the old ASP.NET cache system. It is available from ASP.NET cache provider (NHibernate.Cache.SysCache.dll)

It is an abstraction over ASP.NET cache so it can’t be used in a non-web application. It works but Microsoft suggest to do not use it for non-web applications.

The cache space is not configurable so it is the same for different session factories … really dangerous on a web application that requires isolation between the various users (http://ayende.com/blog/1708/nhibernate-caching-the-secong-level-cache-space-is-shared)

Useful for: small in house projects, better for web projects hosted in IIS

NCache

NCache is a distributed in-memory Object cache and a distributed ASP.NET Session State manager product.

It is able to synchronizes cache across multiple servers so it is designed also for the enterprise.

It provides dynamic clustering & cache configuration for 100% uptime for a real scalable architecture.

Cache reliability through data replication across servers

InProc/OutProc cache for multiple processes on same machine

API identical to ASP.NET Cache

It is available for download and trial here http://www.alachisoft.com/ncache/edition-comparison.html, it is a third party provider and it is not free.

Useful for: medium to big applications that are designed to be scalable

MemCache

MemCache is a famous Linux cache system designed exclusively for the enterprise. It is a complex enterprise cache system based on Linux platform that provide a cache mechanism also for NHibernate.
It is pretty easy to be scaled on a big server farm because it is designed to do so
It does not require licensing cost because it’s an OSS and it is a well known system with a big community.

The following picture represents the core logic of MemCache:

image

The only downside is that it requires a medium knowledge of Linux OS in order to be able to install and configured it.

Useful for: enterprise applications that are designed to be scalable

Velocity, a.k.a. AppFabric

Velocity has been now integrated in AppFabric and it is the cache system implemented by Microsoft for the enterprise. It requires AppFabric and IIS and it can be used locally or with Azure (does it make sense to cache in the cloud?? Flirt male).

  • AppFabric Caching, provides local caching, bulk updates, callbacks for updates, etc... so this is why it's exciting over something like MemCache which doesn't provide these features Out of the Box.
  • For enterprise architectures, really scalable, Microsoft product (there may be a license requirement)

Useful for: enterprise applications that are designed to be scalable

Sharing assembly version in Visual Studio 2010.

11 December 2011 | View comments (2)

Last week I came up with a fancy requirement that forced me to struggle a little bit in order to find an appropriate solution. Let’s say that we have a massive solution file, containing something like 100ish projects and we would like to keep the same assembly version number for all these projects.

In this article I will show you how the assembly version number works in .NET and what are the possible solutions, using Visual Studio.

Assembly version in .NET

As soon as you add a new project (of any type) in Visual Studio 2010, you will come up with a default template that contains also a file “AssemblyInfo.cs” if you are working with C# or “AssemblyInfo.vb” if you are working with VB.NET.

image

If we look at the content of this file we will discover that it contains a set of attributes used by MSBuild to prepare the assembly file (.dll or .EXE) with the information provided in this file. In order to change this information we have two options:

  1. Edit the AssemblyInfo.cs using the Visual Studio editor.
    In this case we are interested in the following attributes, that we will need to change every time we want to increase the assembly version number:
       1:  using System.Reflection;
       2:  using System.Runtime.CompilerServices;
       3:  using System.Runtime.InteropServices;
       4:   
       5:  [assembly: AssemblyVersion("1.0.0.0")]
       6:  [assembly: AssemblyFileVersion("1.0.0.0")]
  2. Or, we can open the Project properties window from Visual Studio using the shortcut ALT+ENTER or by choosing “properties” of a VS project file from the Solution Explorer
    image

How does the versioning work?

The first thing that I tried was to understand exactly how this magic number works in .NET.

If you go to the online MSDN article, you will find out that the version number of an assembly is composed by 4 numbers, and each one has a specific mean

1. Major = manually incremented for major releases, such as adding many new features to the solution.
0. Minor = manually incremented for minor releases, such as introducing small changes to existing features.
0. Build = typically incremented automatically as part of every build performed on the Build Server. This allows each build to be tracked and tested.
0 Revision = incremented for QFEs (a.k.a. “hotfixes” or patches) to builds released into the Production environment (PROD). This is set to zero for the initial release of any major/minor version of the solution.

Two different assembly version attributes, why?

I noticed that the [assembly] attribute class exposes two different properties, Assembly Version and Assembly File Version.

AssemblyFileVersion

This attribute should be incremented every time our build server (TFS) runs a build. Based on the previous description you should increase the third number, the build version number. This attribute should be placed in a different .cs file for each project to allow full control of it.

AssemblyVersion

This attributes represents the version of the NET assembly you are referencing in your projects. If you increase this number in every TFS build, you will incur in the problem of changing your reference redirect every time the assembly version is increased.

This number should be increased only when you release a new version of your assembly and it should be increase following the assembly versioning terminology (major, minor, …)

Control the Versioning in Visual Studio

As I said before VS allows us to control the version number in different ways and in my opinion using the properties window is the easiest one. As soon as you change one of the version numbers from the properties window, also the AssembliInfo.cs file will be automatically changed.

But what happens if we delete the version attributes from the assembly info file? As expected VS will create an assembly with version 0.0.0.0 like the picture below:

image

Note: if we open the Visual Studio properties window for the project and we write down the version 1.0.0.1 for both, Assembly and AssemblyFile attribute, VS will re-create these two attributes in the AssemblyInfo.cs file.

Sharing a common Assembly version on multiple projects

Going back to the request I got, how can we setup a configuration in Visual Studio that allows us to share on multiple projects the same assembly version? A partial solution can be accomplished using shared linked files on Visual Studio.

Ok, what’s a shared linked file, first of all? A linked file is a file shortcut that points in multiple projects to the same single file instance. A detailed explanation of this mechanism is available on Jeremy Jameson’s blog at this page.

Now, this is the solution I have created as an example where I share an AssemblyVersion.cs file and an AssemblyFileVersion.cs file to the entire Visual Studio solution.

image

Using this approach we have one single place where we can edit the AssemblyFileVersion and the AssemblyVersion attributes. In order to accomplish this solution you need to perform the following steps:

  1. Delete the assembly version and the assembly file version attributes for all the existing AssemblyInfo.cs files
  2. Create in one project (the root project) a file called AssemblyFileVersion.cs containing only the attribute AssemblyFileVersion
  3. Create in one project (the root project) a file called AssemblyVersion.cs containing only the attribute AssenblyVersion
  4. Add as linked files these two files to all the existing projects
  5. Re-Build everything

Final note on Visual Studio properties window

Even if my root project has now two files with the attributes AssemblyFileVersion and AssemblyVersion, when I open the Visual Studio properties window, it tries to search for these attributes in the AssemblyInfo.cs file, and clearly, it can’t find them anymore, so it does not display anything:

image

If you add a value to these textboxes Visual Studio will re-create the two attributes in the AssemblyInfo.cs file without taking care of the two new files we have created and as soon as you try to compile the project you will receive this nice error:

image

So, in order to use this solution you need to keep in mind that you can’t edit the AssemblyFileVersion and the AssemblyVersion attributes from the VS properties window if they are not saved in the AssemblyInfo.cs file!

I believe that MS should change this in the next versions of Visual Studio.

Winking smile

NET Event–Migrating WinForm application

14 August 2011 | View comments (2)

Last month (21st of July 2011) I spoke at the Bermuda NET Event “Migrating WinForm applications to WPF/Silverlight”. This has been for me the first NET Event in Bermuda but for sure it will not be the last one. We are planning to have a new event this autumn where we will touch other topics like: ALM, Parallels and more.

Thanks to Alessio Bellisomi, the web developer that works in my company, I am able to share with you some nice pictures of the event and three short movie of the event. Unfortunately, for this event, we were not super organized so I do not have with me the full video of the entire event. I promise that for the next event we will provide the entire video and maybe we will be also able to stream the content.

The audience, considering that we were in Bermuda and considering that it was end of July, was more than expected. I believe we were around a 30/40 ish attendees. The feedback has been really positive and we expect a very fast grow of this UserGroup by having more events and more speakers.

Pictures

The pictures are available through Google photos

Slides

Videos

The videos have been hosted on my Vimeo account and they can be viewed through their web site

Bermuda WinForm event, part 01 from Raffaele Garofalo on Vimeo.

Bermuda WinForm event, part 02 from Raffaele Garofalo on Vimeo.

Bermuda WinForm, part 03 from Raffaele Garofalo on Vimeo.

Thanks

Special thanks need to go to Sandra de Silva (president of the UG and owner of Nova Ltd) and to the other members of the committee. I want also to thank all the participants and I hope this autumn there will be more!

Speaking about WPF in Bermuda.

11 July 2011 | View comments (7)

Last year in Bermuda we had a new born, a NET community. The community has been created by some locals companies to attract developers, architects and analyst; but also anybody passionate of development.

You can check-out the web site here: http://www.dnug.bm/.

This month I will have the opportunity to present my two books:

and to talk about WPF/Silverlight.

During this event I will explain what are the common problems you may encounter when moving from legacy applications to WPF/Silverlight. When you should and when you should not migrate an application to a new UI technology. When you should use WPF and when you should use Silverlight. Oh and I will also give some free copies of my books plus some additional discounts.

This is the page of the event: http://www.dnug.bm/index.php?option=com_jevents&task=icalrepeat.detail&evid=5&Itemid=58&year=2011&month=07&day=21&title=july-2011-dot-net-user-group-event&uid=a620ff387a7449aaad68443c9780f7c2

If you are planning a vacation around the 21st of July, please come here and join us in this first event about WPF/Silverlight.

Hope to see you there!

PS: I forgot to mention that one of the amazing price for the attendees is to win a 1 year subscription to MSDN.

TypeMock tutorial #03. Control behaviors.

01 July 2011 | View comments (2)

Note for purists: In this tutorial I am showing you a simplified example of a Unit of Work and a Repository, please do not care about the complexity or simplicity of these objects but look at the TypeMock implementations.

We are now at the third post of this series and I found out that there are a lot of readers interested in learning TypeMock, which means that series will have to continue!

Last time, we have created some object’s mocks using TypeMock but they were simple Value Objects with nothing or very few business logic in it. This time I want to show you how you can control the behaviors of a mock so that you do not have to control or fake the entire object if you are testing a single method.

Testing a IUnitOfWork

I do not know if you have already created a data layer in your career of software developer; if you did not, you can have a look at one of my tutorials or books about layering an application.

First of all we have a Unit of Work, which allows us to “Save”, “Update” or “Delete” the object we are passing it using a generic signature. The contract for a Unit of Work is represented by the following image:

image

As you can see we have a simple interface with three methods and we still do not have an implementation for it but we have some expectations that we would like to pre-test using a mock in order to be sure that the next step will be properly handled by TypeMock.

The pre-requisite is that every entity in our domain has some properties inherited by a base class DomainObject; these properties can tell us the ID of the entity, if the entity is new, modified or deleted.

The following object represents the base class for a domain entity.

image

The 3 properties are of type boolean while the UniqueId is of type Guid, so by default we will have a Guid.Empty value and after we mark dirty or updated the object we should have them populated.

 

 

 

 

 

Test the interface

If we test the interface we can start by writing three different expectations like the three following snippets:

Mark a new entity
  1. [Test]
  2. [Category("DataLayer")]
  3. public void CanMarkANewEntityToNewAndChangeItsId()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>();
  6.     IUnitOfWork uow = Isolate.Fake.Instance<IUnitOfWork>();
  7.     uow.MarkNew(person);
  8.     Assert.That(person, Has.Property("UniqueId").Not.EqualTo(Guid.Empty));
  9.     Assert.That(person, Has.Property("IsNew").True);
  10. }

And as soon as we run this test it simply fails because of course TypeMock is not able to properly mock the method MarkNew as we did not instruct it on how to do it …

The solution in this case is pretty straightforward, before invoking the MarkNew<T> method we need to teach to TypeMock what is our expectation for this method when we add a Person object to it.

DoInstead()
  1. Isolate.WhenCalled(() =>
  2.     uow.MarkNew(person))
  3.     .DoInstead(callContext =>
  4.                    {
  5.                        var p = callContext.Parameters[0] as Person;
  6.                        p.UniqueId = Guid.NewGuid();
  7.                        p.IsNew = true;
  8.                        return p;
  9.                    });
  10. var expectedPerson = uow.MarkNew(person);

In this case we have informed TypeMock that when we will call the method MarkNew<T> passing as a generic paramenter the Person object, it will have to modify the person object and return it with a new ID and the IsNew property populated.

Another way to do that is to use the WillReturn method of TypeMock that can be used, like in this case when we have functions and not void methods.

WillReturn
  1. person.UniqueId = Guid.NewGuid();
  2. person.IsNew = true;
  3. Isolate.WhenCalled(() => uow.MarkNew<Person>(person)).WillReturn(person);
  4. var expectedPerson = uow.MarkNew(person);

In the same way we can test that the method may also return an unexpected exception, so we can inform TypeMock to force the mock interface to throw an exception.

This section of type mock is called Controlling method behaviors and you can find a detailed documentation about it at this address:

controlling methods

In the next tutorial we will see how to customize a chain of mockup object and faking the methods so that the IUnitOfWork will be used as a dependency for a Repository class.

If you want you can also download the code of every tutorial at this address on Codeplex:

http://typemock.codeplex.com/

Winking smile

Encrypted string of the week: IHcKGzESRVs=
using Blowfish CBC 64bit

TypeMock tutorial #02. Object creation.

25 June 2011 | View comments (0)

In this new  part of the TypeMock series I am going to show you how to deal with objects and classes in general, how you can create them and what are (honestly aren’t) the limit of TypeMock on dealing with objects.

First of all I have just drawn down a little domain that I have added to the demo application. I am planning to upload this demo the next week on Codeplex.com so that every geek reading this blog can just go there and download the source code.

The Demo domain

The domain is a very simple one, we have an abstract base class called Person, then we have two concrete classes, an Employee and a Customer that right now do not have any differences (we will see in the next tutorials why we have two different concrete classes) and then we have a value object Address that is composed only if we provide to it a parent Person object in the constructor. The Person entity exposes a read-only IEnumerable collection of Addresses, so in order to add or remove an address we must use the provided methods AddAddress and RemoveAddress.

The following picture shows the corresponding class diagram of this small domain.

ClassDiagram

These are the most important piece of code that you may be interested in:

Read-only collection Addresses
  1. private IList<Address> addresses = new List<Address>();
  2.  
  3. public IEnumerable<Address> Addresses
  4. {
  5.     get { return this.addresses; }
  6. }
  7.  
  8. public void AddAddress(Address address)
  9. {
  10.     if (this.addresses.Contains(address))
  11.     {
  12.         throw new InvalidOperationException("The address is already in the collection.");
  13.     }
  14.     this.addresses.Add(address);
  15. }
  16.  
  17. public void RemoveAddress(Address address)
  18. {
  19.     if (!this.addresses.Contains(address))
  20.     {
  21.         throw new InvalidOperationException("The address is not in the collection.");
  22.     }
  23.     this.addresses.Add(address);
  24. }

and

Constructor of an Address obj
  1. public Address(Person person)
  2. {
  3.     Person = person;
  4. }
  5.  
  6. public Person Person { get; private set; }

As you can see we have few things that need to be tested but in order to do that we have to create new instances of these objects in order to run our tests, which is pretty verbose and boring

Create the test project

The first step is to create a new Visual Studio 2010 Visual C# class library project and call it TypeMockDemo.Fixture and add the following references to it:

image

The references are pointing to:

  • my TDD framework nUnit (you can work with any TDD framework but I personally found nUnit to be the best out there …)
  • TypeMock assemblies, installed in the GAC of your machine
  • The TypeMockDemo project (the one we have the domain entities in)

Now we can start to create the first class fixture and verify that we can create a new Person, a new Employee and a new Customer. But hold on a second! How can we mock an abstract and two sealed class with a mocking framework? We simply can’t if we are not using TypeMock … Winking smile

Create new abstract and Sealed
  1. [Test]
  2. [Category("Domain.Isolated")]
  3. public void AssertThatCanCreateANewPerson()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>();
  6.     Assert.That(person, Is.Not.Null);
  7. }
  8.  
  9. [Test]
  10. [Category("Domain.Isolated")]
  11. public void AssertThatCanCreateANewEmployee()
  12. {
  13.     Person person = Isolate.Fake.Instance<Employee>();
  14.     Assert.That(person, Is.Not.Null);
  15. }
  16.  
  17. [Test]
  18. [Category("Domain.Isolated")]
  19. public void AssertThatCanCreateANewCustomer()
  20. {
  21.     Person person = Isolate.Fake.Instance<Customer>();
  22.     Assert.That(person, Is.Not.Null);
  23. }

Looking at the code we have introduced the new method Isolate.Fake.Instance<T> that is coming from TypeMock. With this method we can simply inform TypeMock that we want it will create for us a Proxy of the object we want to mock and it will return a derived class of the tested one, even if we are mocking a sealed class.

If the class is sealed TypeMock will create a new instance of the original object while if the object is abstract, TypeMock will create a proxy version of that object. Same thing will be done for all the child properties, complex or not …

image

That’s simply wow, we just used two lines of code to create a mockup and test it.

Now let’s move forward and let’s verify that we will not be able to add the same address twice and to remove the same address twice from a Person object.

Working with Instances or Proxy?

First of all we start to create this simple test but the result is not the one we expect …

Test a collection
  1. [Test]
  2. [Category("Domain.Isolated")]
  3. public void AssertThatCanAddTheSameAddressTwice()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>();
  6.     Address address = Isolate.Fake.Instance<Address>();
  7.     person.AddAddress(address);
  8.     Assert.That(person.Addresses.Count(), Is.EqualTo(1));
  9.     Assert.Throws<InvalidOperationException>(() => person.AddAddress(address));
  10. }

nUnit bombs saying that at line 8 the expected result is supposed to be 1 but in reality is 0. Why? This happens because TypeMock has created a full mockup proxy of the person object so also the methods AddAddress and RemoveAddress are mocks and they do not point to the real code we have implemented …

Control the creation
  1. [Test]
  2. [Category("Domain.Isolated")]
  3. public void AssertThatCanAddTheSameAddressTwice()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>(Members.CallOriginal, ConstructorWillBe.Called);
  6.     Address address = Isolate.Fake.Instance<Address>();
  7.     person.AddAddress(address);
  8.     Assert.That(person.Addresses.Count(), Is.EqualTo(1));
  9.     Assert.Throws<InvalidOperationException>(() => person.AddAddress(address));
  10. }

If we change the way TypeMock is creating the object Person, we can now say to it:

Dear TypeMock, I want that you create an instance of my object and that you call its constructor so that I can test the code I have implemented in this abstract class …

Et voila’, the test will pass! Same thing for the remove address and so on …

Now, the last test we may require is that we want to be sure that when we create a new address, the constructor is properly injecting the parent Person object so that we can keep a back-forward reference from the parent object and the collection of children.

Test injection in constructor
  1. [Test]
  2. [Category("Domain.Isolated")]
  3. public void AssertThatWhenCreateAnAddressTheParentPersonIsInjected()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>(Members.CallOriginal, ConstructorWillBe.Called);
  6.     Address address = Isolate.Fake.Instance<Address>();
  7.     Assert.That(person, Is.Not.Null);
  8.     Assert.That(address, Is.Not.Null);
  9.     Assert.That(address, Has.Property("Person").EqualTo(person));
  10. }

We run the test and kabum! It fails again. This time it fails on the address side because the Person instance TypeMock is injecting is not the same it returned to use in the previous line of code. So what can we do now?

We can manually create an Address and inject the parent Person but it sucks … or we can do this:

Customize constructor
  1. [Test]
  2. [Category("Domain.Isolated")]
  3. public void AssertThatWhenCreateAnAddressTheParentPersonIsInjected()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>(Members.CallOriginal, ConstructorWillBe.Called);
  6.     Address address = Isolate.Fake.Instance<Address>(Members.CallOriginal, ConstructorWillBe.Called, person);
  7.     
  8.     Assert.That(person, Is.Not.Null);
  9.     Assert.That(address, Is.Not.Null);
  10.     Assert.That(address, Has.Property("Person").EqualTo(person));
  11. }

 

We simply inject the person value we want to use (the one created by TypeMock) because this is what it is going to happen with live code. What we care here is to be sure that inside the Address class constructor, the Person parameter is passed to the read-only property Person of the Address class, nothing more, nothing less!

Conclusion

As you can see, TypeMock is pretty cool and it allows you to control the way we can create and fake objects. Even if we use proxies we can still ask to TypeMock to create a real mock that reflect our code so that we can still test the business logic included in our objects without the need of creating complex objects manually.

If you want to read more about this topic I kindly suggest you this:

In the next tutorial we will see how to customize the methods and other behaviors of an object and I will also publish the first part of the quiz that will allow you to win almost 1,000 USD value of TypeMock license!

Stay tuned

A Devil in the house …

22 June 2011 | View comments (0)

Just a little OT to keep you up to date also about my private life (if anyone of you cares … Winking smile).

Last Friday we got a new member in our family, after we lost our precious Doberman after 10 years, we decided to move forward and forget the drama by getting a new dog. This time we bought a Jack Russell Terrier … what a Devil!

Her name is Sophie, she is now 3 months old and she is the alpha of her litter … so a little bit a “devil dog”. Really energetic and with a strong character! A nice challenge for me and my wife.

The first thing we want to teach her is to jump on a surf board and surf! I will publish a video of her soon.

For now, enjoy this:

TypeMock tutorial #01. Startup.

17 June 2011 | View comments (0)

The best way to learn a tool is to try it, test it and then finally use it over your code. Of course if the tool provides also a great community support and a great documentation the task will be easier.

Some weeks ago we started to adopt a wonderful tool to create mockups and other TDD fancy stuff, the tool is TypeMock.

The idea I got is to create a series of tutorials about TypeMock and provide to you a piece of a code to download a full license of this tool. At the end of the series (probably 1 month) you will be able to enable your 10 days trial into a full working license. I will create a sort of bid and from all my readers that will contact me to get the license I will come up with one or two free licenses.

Guys, consider that one license of TypeMock is 800 $ !!

Setup and Installation

In order to start right away with TypeMock you need to download the latest version of the tool (at this time they have the version 6.0.10) but be careful because they upload new versions often. The product you need to download for .NET is Isolator.NET. They also provide additional tools that we will analyze during this series, like:

  • TestDriven.NET, an integrated test runner for Visual Studio
  • Isolator for Sharepoint
  • Isolator for ASP.NET and ASP.NET MVC
  • TeamMate, a useful tool to monitor your TDD approach
  • Isolator ++, the same version but for C++
  • TestLint, a nice tool that will help you to develop your TDD skill

and more.

After you have downloaded the setup (7 Mb) you will have to follow a very straightforward setup wizard with only two options available; use the advanced option and install everything including the samples for .NET.

That’s it, you are now ready to go!

File Location

TypeMock is installed on your C:\ drive and depending on where you choose to install it, you should have a folder called TypeMock/Isolator/6.0 on your Program Files directory. Inside this folder you can find all the assemblies available from TypeMock.

You do not need to use them directly as TypeMock is also installed on your GAC folder but if you plan to work with C.I. (Continuous Integration) you may probably need to add a reference to these files instead of pointing directly to the GAC, depending on what type of build server you are working with … Winking smile

Inside the folder Examples you will find a set of useful examples to start to learn TypeMock quickly but do not worry as I will go through all these examples in this series.

If you want to make your experience with TypeMock easier and smoother, I kindly suggest you to download and install also TestDriven.NET or Resharper with Gallio. I personally use and love Resharper so you will find in this series all the reference examples pointing to the Resharper UI inside Visual Studio. The choice is up to you but I personally believe R# is the best tool so far for Visual Studio (IMHO)

Visual Studio integration

After the installation you can open Visual Studio and this is the surprise you will find in the IDE:

Screen shot 2011-06-13 at 11.56.00 PM You will find a new menu on Visual Studio called TypeMock; in this menu you can setup the license, the profiler to use with TypeMock and few other options for a better Visual Studio experience.

There aren’t a lot of other ways to easily configure TypeMock but we will see together how you can tackle each of the common tasks you may encounter while working with TypeMock.

From this menu you have also the easy option of enabling/disabling TypeMock at anytime so that you can or cannot work with it without the need to restarting Visual Studio every time (like you have to do with other plugins of Visual Studio).

The Demo Project

I have created a very small project for this series of tutorials to show you how you can test every single layer of a .NET application using TypeMock to separate the dependencies. The structure of the demo project is in the following way:

Screen shot 2011-06-19 at 4.26.58 PM

The project is composed by 4 different layers:

  1. TypeMockDemo: the project that contains the Domain Model of the tutorial
  2. TypeMockDemo.DataLayer: a data layer built around NHibernate 3.2
  3. TypeMockDemo.ServiceLayer: the service layer used to write the business logic around the domain and the data layer
  4. TypeMockDemo.UserInterface: an application developed using WPF 4.

 

 

For each project there is a corresponding “fixtures” project that includes all the fixtures related to the project. With fixture I mean “test” … Winking smile

Tutorials and resources

Before starting to follow this series I kindly suggest you to have a look at the TypeMock web site learning content, so that you will follow better my tutorials. As you know, I do not usually go too deep into a specific topic, so if you need to learn also what TDD is, I kindly suggest you to read also the following tutorials about TDD and testing in general.

TypeMock learning content:

TDD learning content:

 

So stay tuned and I’ll see you next Friday for the next part of this series.

New content for my Microsoft book

15 June 2011 | View comments (9)

The Microsoft’s book I have published few months ago: “Building Enterprise Applications with WPF and MVVM” has been a success but I still got some negative feedbacks that me and my editor we want to get rid off.

This book is my first real book and of course it was my first experience on writing a book (for this reason we kept the price of the book very low). Anyway .. I got some bad feedbacks about missing parts, parts not explained as expected and a misunderstanding of the book audience and target.

I personally believe that the biggest problem is in the title of book, it drives you a little bit out of the topic of the book, if you buy this book you will believe to get the “bible to LOB applications with MVVM”, which is not.

For this reasons and also to keep high the audience of the book, we have decided to deliver for free new additional content for the book! Open-mouthed smile

The list of the new content is still under discussion with my editor but this is a rough list of the topics I will touch or expand in this new context that should be composed by 3 additional chapters!

  • Design patterns
    I am planning to add 20/30 additional pages on the second chapter in order to exhaustively cover everything related to the most known design patterns
  • Advanced MVVM
    I will add a new chapter where I will explain some “well known” problems you may find when the adoption of the MVVM pattern starts to get tricky!
  • Composite Frameworks for MVVM in practice
    In this chapter we will build the same Master-Detail UI logic using the three most famous frameworks for WPF/Silverlight: PRISM, Caliburn and Light Toolkit

If you believe that the book is still missing other information, feel free to send me an e-mail and I will be glad to discuss this with my editor.

Note: Remember also that we are planning to distribute the source code of the book as an Open Source project on Codeplex.com before the end of the year.

Hope this will help!

Unity and injection with factories.

14 June 2011 | View comments (0)

Last week in the office I just found a bug on how I was implementing a series of Inversion of Control chain using Microsoft Unity. To be precise, the bug has been found by one of the new guy in the team, Gary McLean Hall, the author of the book “APRESS - Pro WPF and Silverlight MVVM”.

Before starting with the explanation of the problem, let’s see what I am talking about. I believe that anyone of you know already concepts like “Inversion of Control” and ‘Dependency Injection”; if you don’t, just follow the links. Winking smile

A classic injection mechanism.

A classic mechanism of IoC is the one used by the Unit of Work and Repository patterns, where a repository can’t exist without an injected unit of work able to control the transaction. So, in order to have such a kind of example, I have implemented a simple data layer that shows you these dependencies:

image

Now, for these two contracts we will need to concrete implementations like the following classes:

image

And the final touch will be the implementation. Now, I am not going to implement a full data layer in this post as it is not the target of this writing, instead I want to show you how to “inject” a unit of work …

Repository constructor
  1. using System;
  2. using System.Linq;
  3.  
  4. namespace InversionOfControl_dynamic
  5. {
  6.     public sealed class Repository : IRepository
  7.     {
  8.         #region IRepository Members
  9.  
  10.         public void Create<T>(T entity)
  11.         {
  12.             this.unitOfWork.MarkNew(entity);
  13.         }
  14.  
  15.         /// IRepository implementation removed to save space ...
  16.  
  17.         #endregion
  18.  
  19.         #region Injection of the Unit of Work
  20.  
  21.         private IUnitOfWork unitOfWork;
  22.  
  23.         public Repository(IUnitOfWork unitOfWork)
  24.         {
  25.             this.unitOfWork = unitOfWork;
  26.         }
  27.  
  28.         #endregion
  29.  
  30.     }
  31. }

Now we can easily register the components with Unity and verify that when we call a Repository class, we are injecting a new Unit of Work using Unity.

The following test is accomplishing this task:

TDD the injection process
  1. [TestFixture]
  2. public sealed class StandardFixture
  3. {
  4.     private IUnityContainer container;
  5.  
  6.     [TestFixtureSetUp]
  7.     public void InitializeTests()
  8.     {
  9.         container = new UnityContainer();
  10.         container.RegisterType<IUnitOfWork, UnitOfWork>();
  11.         container.RegisterType<IRepository, Repository>();
  12.     }
  13.  
  14.     [Test]
  15.     public void Assert_That_Unity_Can_Resolve_Dependency()
  16.     {
  17.         IRepository repository = container.Resolve<IRepository>();
  18.         Assert.That(repository, Is.Not.Null);
  19.         Assert.That(repository, Is.InstanceOf<Repository>());
  20.         // Here I have created a public read-only property
  21.         // for testing purposes
  22.         Assert.That(repository, Has.Property("UnitOfWork").Not.Null);
  23.     }
  24. }

So far so good. The only missing part here is the last statement (line 22) of the code. Here I have created a read-only IUnitOfWork property, only in the concrete Repository class, in order to test that the IUnitOfWork is injected properly.

Injecting using factory

Now, let’s assume for a second that the previous approach is not valid; it is not valid because we are not in charge of creating an IUnitOfWork by our self. We need a factory that will create the contract for use.

So, first of all, I am going to create a simple factory that will return, with a static method, an instance of an IUnitOfWork object.

Unit of Work Factory
  1. public sealed class Factory
  2. {
  3.     public static IUnitOfWork GetUnitOfWork()
  4.     {
  5.         return new UnitOfWork();
  6.     }
  7. }

Now we are screwed because the previous approach does not work anymore… Green with envy If I want to create a new instance of a repository I need to inform Unity, somehow, that it needs to call this method of the factory to create a new instance of an IUnitOfWork. But how?

We found the class InjectionFactory ables to specify a delegate for the creation of a new object, like this code:

InjectionFactory declaration
  1. container = new UnityContainer();
  2. container.RegisterType<IUnitOfWork>(new InjectionFactory(c =>
  3.     Factory.GetUnitOfWork()));
  4. container.RegisterType<IRepository, Repository>();

Now we can simply assert that when we create two instance of an IRepository interface using Unity, it will return two different instances of the IUnitOfWork object:

Code Snippet
  1. [Test]
  2. public void Assert_That_Unity_Can_Resolve_Dependency()
  3. {
  4.     var currentRepository = container.Resolve<IRepository>();
  5.     var currentUoW = currentRepository.GetType().GetProperty("UnitOfWork").GetValue(currentRepository, null);
  6.  
  7.     var expectedRepository = container.Resolve<IRepository>();
  8.     var expectedUoW = currentRepository.GetType().GetProperty("UnitOfWork").GetValue(expectedRepository, null);
  9.  
  10.     Assert.That(currentUoW, Is.Not.Null);
  11.     Assert.That(expectedUoW, Is.Not.Null);
  12.  
  13.     Assert.That(currentUoW, Is.Not.EqualTo(expectedUoW));
  14. }

If you want to read more about this object and other way of customizing the way Unity allows you to register objects, you can have a look at this section of MSDN:

Happy IoC to everybody!

Open-mouthed smile

Applied WPF in context is out.

05 June 2011 | View comments (4)

During the last two months I have been away from Bermuda and I didn’t have a lot of time to write or post any news on this blog.

In the meantime, I didn’t realize that my new book from APRESS: “Applied WPF 4 in context” has been published so it is time to post some info about it.

The cover of the book is following the APRESS new style and it is the following one:

APRESS_cover

The new series “applied in context” of APRESS deliver content by example and practical code, so in this book you will realize a full working WPF 4 application using all the available tools of Microsoft like: Visual Studio 2010, Expression Blend 4 and SQL Server 2008 R2.

Who this book is for?

This book is for Windows application developers who want to understand the context in which WPF sits and the standards and best practices that can be employed to improve the efficiency and maintainability of their projects. This book can be used by a junior developer to learn WPF and understand how to architect a layered application, and it can be used also by a senior developer as a reference for developing scalable WPF applications.

Table of content.

Following is the table of content of the book:

  1. Introducing WPF and XAML
  2. Sample Application: Overview and Getting Started
  3. Microsoft Expression Blend
  4. Creating the Views
  5. Adding Controls to the Views
  6. The Entity Framework
  7. Data Binding
  8. Command Handling and Event Routing
  9. Testing with TDD   
  10. Reports with Microsoft Reporting Services
  11. Deploying the Application Using ClickOnce
  12. Design Patterns in WPF
  13. WPF and Multi-Threading
  14. Interacting with WCF

Distributors.

The book is released and published by APRESS so in this case the book can be bought from the APRESS web site or from one of their distributors. Right now, Amazon has already run out of copies so you should expect the next distribution starting the 7th of June for the Paperback copy. You can still download the e-book from Amazon.com or APRESS. I am not sure I will distribute this book also with Kindle as I had some issues with the previous one so for now it won’t be available directly in the Kindle web site or in the iBook application for iPad.

Right now you can buy the book here:

The are also other distributors that I do not personally follow but I believe that buying the book directly from APRESS will give you the best price/availability options.

Prices.

This is the list of the official prices, if you find the book with a different price from a different distributor than the one listed in the previous section I am not aware about it, so please let me know if you believe someone is distributing the book with a non fair price.

Print version with shipment from APRESS including TAX: 49.99 USD

E-book version from APRESS including TAX: 34.99 USD

Enjoy and as usual, let me know what you think about it! Hot smile

Updates for April/May 2011

12 April 2011 | View comments (2)

Note: Starting from the 15th of April 2011 until the 6th of May 2011 I will be off-island. During this period I will not have access to the internet so I will not able to approve you comments or either to read and answer them. You can try to send me an e-mail using the contact form but I can't guarantee you that I will be able to read it.


I have received many queries about my first book on LOB applications so in this post I will try to answer to most of them. Please forgive me in advance if I can't answer to all your queries.
  • Source code
    Many of you are wondering why the source code of the demo application for the MVVM book is "skinny" and why I didn't provide a full working application.
    The book has been released and the work behind it is huge. This book is supposed to be a guideline for a senior developer on how to architect a LOB application so in my opinion it was not necessary to provide all the code required to make a fully working application. I mean the application works but I left the "finishing touch" to the reader. Anyway, due to the high demand, I will work on this and during the summer I will post new versions of the app probably on CodePlex so that I can be an Open Source project where each dev interested can put some effort on it.
  • APRESS WPF Book vs MS MVVM book
    Why Raf wrote two books and not one? First let me say that Microsoft and APRESS are two separated companies; my "MVVM" book has been published by Oreilly for Microsoft Press while my APRESS book will be published by APRESS ... The first one talks about "Architecting a LOB application and the MVVM pattern" while the second one "teach you from scratch a layered WPF application". If you want a reference to layer an application you have to buy the first book, especially if you are new to the topic (layering), if you want to learn: WPF, MVVM, Entity Framework, threading on WPF and more you have to buy the second one, event if you are a middle expert WPF developer.

I do not like to blown my own trumpet and who has worked with me can confirm that, but, if you are interested in learning WPF and learning how to architect a LOB application you have to buy both books as just one will not cover all the topics you need to master this technology. I would personally buy the MS PRESS book, read it once, then buy the APRESS WPF book, read it and build the sample application, then read again the MS PRESS one.

 The final note is about the comments. The book is on Amazon.com and OReilly.com and as an author I would kindly appreciate if you can post a comment that explains what you liked and what you didn't like about the books. Posting a comment with 2 stars saying "the source code is not available" while it is on OReilly.com, it is just silly and doesn't help anybody ... If you have a problem with the source code, feel to contact me, even if you disagree with some of my ideas exposed in my books. I have a wide open mentality and I love to have "constructive discussions" with my readers.

Updates for my Microsoft Book

03 April 2011 | View comments (15)

After one week that my book about LOB applications has been published I started to receive some additional questions that I am trying to address in this post.

First of all I want to thank all the guys and girls that are buying the book and all the people that are providing feedbacks for the book. I really appreciate. I want also to specify that the Microsoft book has not been released as a “Book about MVVM” but more as a “book to discover LOB and layered applications”. I believe that part of the misunderstanding as been caused by the book’s title but we wanted to specify the MVVM keyword in the title because the book spent two chapters on it.

The source code has been published and you can find in the book the correct address that will point you to the download. I want to thanks Ted Anderson that on Amazon.com has notified me about the error done by OReilly in the publishing address. The source code is available here:

http://examples.oreilly.com/9780735650923-files/­9780735650923_files.zip. Please do not download the code and pretend to get explanations from my if you didn’t buy the book yet … Winking smile

The T-SQL to generate the database is not necessary. When you will open the Visual Studio 2010 solution, you need to run the Test show here:

TDD for generate the SQL Datab
  1. [TestFixtureSetUp]
  2. public void CanCreateDatabaseSchema()
  3. {
  4.     try
  5.     {
  6.         var cfg = new Configuration();
  7.         cfg.Configure();
  8.         cfg.AddAssembly(Assembly.Load("CRM.Dal.Nhibernate"));
  9.         new SchemaExport(cfg).Execute(true, true, false);
  10.     }
  11.     catch (Exception exception)
  12.     {
  13.         Assert.Fail(exception.ToString());
  14.     }
  15. }
  16.  
  17. [Test]
  18. public void CanGetAUnitOfWork()
  19. {
  20.     try
  21.     {
  22.         ISessionFactory factory = new SessionFactory();
  23.         IUnitOfWork unitOfWork = factory.CurrentUoW;
  24.         Assert.That(unitOfWork, Is.Not.Null);
  25.         Assert.That(unitOfWork.Orm, Is.Not.Null);
  26.     }
  27.     catch (Exception exception)
  28.     {
  29.         Assert.Fail(exception.ToString());
  30.     }
  31. }

 

REMEMBER THAT BEFORE RUNNING THE TEST YOU SHOULD CREATE THE DATABASE IN SQL SERVER AND CHANGE THE CONNECTION STRING IN THE APP.CONFIG.

Also remember that the source code has been created only to show you some practical examples of how to layer a LOB application, how to use NHibernate or Entity Framework with the same data layer and how to architect the MVVM pattern. If you want to use the application in a production environment, you have to spent additional time on it in order to get a final product.

For any other additional information I am here.

Please if you find errors or mistakes in the book, I would really appreciate if you can post an errata corrigge in the corresponding section of the OReilly web site: http://oreilly.com/catalog/0790145309686/

Next month I will publish my second book “Applied WPF in Context” with APRESS; in that book you will find whatever you need to learn WPF and the MVVM pattern.

Stay tuned!

Source code for my MVVM book.

26 March 2011 | View comments (4)

This post is an update for all the enquires I got about the source code for my MVVM book published few days ago. (Please follow this thread: MVVM book).

The book was planned to be published for the first week of April 2011 but it was already published this week due to the high demand we received from the customers.

Unfortunately the source code of the demo application is under polishing process in these days and it will be available next week.

Please forgive me for this and stay tuned, I will update this post as soon as the source code will be released.

Thank you

My book for Model View ViewModel (MVVM) and n-tier applications is out

22 March 2011 | View comments (10)
(a.k.a. Buy one copy!)

Finally I am excited and glad to let you know that my first book: “Building Enterprise Applications with Windows® Presentation Foundation and the Model View ViewModel Pattern” is out and available through the major IT books distributors like: www.amazon.com, kindle, www.oReilly.com and more.

cat

Distributors

Please forgive me if I am missing some of my distributors but I do not have yet the full list. The book is available through the oReilly website at this address: http://oreilly.com/catalog/0790145309686/ in the following formats: PDF, EBOOK, KINDLE and PAPERBACK (hard copy); of course the hard copy costs a little bit more.

You can also order the book using www.amazon.com at this address; unfortunately, Amazon will not start to deliver the book until the 1st week of April 2011 while if you order the book from the oReilly web site, you can get it right away.

Prices

On amazon, the hard copy costs $19.99 and the Kindle version costs $14.99.

On oReilly the hard copy is $19.99, the Ebook is $14.99 and both together cost $21.99

Free Copies

I have assigned some free copies to the participants of the last UGIALT conference, I will send them a free copy of the book as soon as I will get the green light from oReilly. I am planning to distribute other free copies at the next .NET community event and I will let you know when this will be. For now, buy a copy and make me happy! Open-mouthed smile

Thanks

First of all I want to thanks oReilly and Microsoft to let me write this book. I also want to thank Russell Jones, my editor and primary publishing contact for this book. He is the only person who believed in me from the beginning, and he put himself on the line to get this project approved by Microsoft Press. I will be always thankful to him for that. He did also a wonderful job in helping me to complete the job on time, and to organize the whole project. Thanks to Kristen Borg, my production editor that spent a lot of time and effort to finalize and get this project done.

Of course I have to thank my wonderful wife that for the last 6 months she helped me in getting this job done by pushing me every time I was letting go the project for one or another one reason.

Comments

Please, please, please. If you plan to buy a copy of the book ( I hope so) I would really appreciate if you can leave a comment, on Amazon or on OReilly or on both of them and let me know what you really think about it. I love to get constructive criticisms on my work as they always help me to do the next thing better. Please, don’t be shy and don’t be nice if I do not deserve it!

Updates

I have received already a lot of requests about the book and the distribution. So, if you want an hard copy or an ebook you can get one, right away on the OReilly web site. If you go on Amazon.com, the book, the Kindle version or the EBook will not be distributed until the end of March 2011. If you need details about the book content, I am planning to write a new blog post ASAP.

Bye bye Morgana!

23 February 2011 | View comments (8)

This is an off-topic post and I want to spend a space on my wall to my dog, the best “friend” I ever had in my life and probably the best I will ever have.150245_1694100553588_1270026602_31873922_1816636_n

Morgana has been my dog since the end of 2001, as soon as I ended the school and I got the first job I left my parents house and I started to live with my actual wife. I always had the dream of having a Doberman and I decided with Debbie to go to a Doberman breeding farm and get one.

Morgana was there, in a corner, very shy. She didn’t want to leave the farm and at that time she probably didn’t like us at all; she was only 2 months old and we were taking her away from her mother …

After few weeks she got quickly used to us and I would say that we both felt in love. A love that never ended and that will never end.

I cannot tell you how many adventures and misadventures I had with my dog, you wouldn’t even imagine. I can just tell you that she was there when I got married, she was there when I lost my job and she was there when I left Italy to move to Bermuda! She was here in Bermuda and she was ready to come back with me in Italy when I lost my job in Bermuda 2 years ago. She has always been with me, she was part of the family!

75825_1694100353583_1270026602_31873920_6957437_n

Every person that met us (friends, parents, relatives or simply neighbors) knows how nice, sweet and smart Morgana was. She never gave us any problem, she was the perfect dog, the one that every person would like to have. The family dog, smart, sweet and dutiful but in the same time spiteful if I was not giving her the time she deserved!

Now she is not with us anymore, unfortunately. The pain is still big for me and I feel I am missing something now, like a piece of my life is now empty, gone. When I got her my father was not happy because he had a dog and he told me: “Raf, you can’t even imagine the pain you will have when your dog will die”  and he was absolutely right! The pain is a lot and I still do not know how to fill the gap she left.

I just want to write this post to remember her, to let her know that she will be always in my heart and that I will never, ever forget her!

Bye bye Morgana!

Winking smile

State pattern using C#. Part 02.

20 February 2011 | View comments (0)

In the previous post we saw how we can implement the state pattern (I know, I didn’t show you the purist way of using the State pattern …) and include in the state execution the flow logic.

This technique is fine but … it requires a lot of effort in the implementation and requires a lot of maintenance, plus it has the GAP of forcing us to re-run the CanExecute delegate every time we want to execute a specific action.

On the web I have found some solutions that personally didn’t satisfy me at all. I personally believe that the best way of designing a state machine workflow is to use a workflow engine and NET Framework provides with NET 4 an amazing state engine. Anyway let’s see what the web offers instead of using WF 4.

Stateless Open source project

Stateless is an Open source project hosted on Google code and available here: http://code.google.com/p/stateless/; it is a C# implementation of a stateless workflow using the BOO language.

We have the same domain exposed in the previous post but in this case we modified a little bit the Order object and we do not use anymore the Command pattern.

OrderObjectStateless

The class Order has 5 different methods that can modify its state in the following way:

Create an Order
  1. public void Create()
  2. {
  3.     this.State = OrderState.Created;
  4. }

They do not verify anymore if the action can or cannot be execute, we just know that the Create method, for example, modifies the state of the Order to “Created”.

Now it is time to wrap this code in a separated class that we will call OrderService and that is identified in DDD as a Domain Service object, a service used in the domain space to wrap business logic and keep it outside the Entity object. The final result should like this one:

statelessdiagram

The trick with http://code.google.com/p/stateless/ is to split the service in two parts, the first one is used to Bootstrap the stateless framework in the following way:

Stateless boostrapping
  1. public sealed class OrderService
  2. {
  3.     private StateMachine<OrderState, OrderActions> workflow;
  4.  
  5.     public OrderService()
  6.     {
  7.         workflow = new StateMachine<OrderState, OrderActions>(OrderState.Undefined);
  8.         workflow
  9.             .Configure(OrderState.Undefined)
  10.             .Permit(OrderActions.Create, OrderState.Created);
  11.         workflow
  12.             .Configure(OrderState.Created)
  13.             .Permit(OrderActions.Cancel, OrderState.Cancelled)
  14.             .Permit(OrderActions.Modify, OrderState.Modified)
  15.             .Permit(OrderActions.Approve, OrderState.Approved);
  16.  
  17.     }

And then we add a method in the service that will be used to Fire a specific state change, like this one:

Command pattern
  1. public void Fire(Order order, OrderActions action)
  2. {
  3.     workflow.Fire(action);
  4.     order.State = workflow.State;
  5. }
  6.  
  7. public bool CanFire(Order order, OrderActions action)
  8. {
  9.     return workflow.CanFire(action);
  10. }

Now, by default, Stateless raises an error (Exception) if the operation can’t be executed. The following test demonstrates the exception raised by stateless:

TDD
  1. [Test]
  2. public void CannotApproveAnOrderBeforeCreatingIt()
  3. {
  4.     var order = new Order();
  5.     var service = new OrderService();
  6.     Assert.Throws<InvalidOperationException>(() =>
  7.         service.Fire(order, OrderActions.Approve));
  8.     Assert.That(order.State, Is.EqualTo(OrderState.Undefined));
  9. }

The exception is of type InvalidOperationException.

Conclusion

Stateless is a good state machine framework, open source, easy to learn and it has a good and clear DSL language. Unfortunately the project is very young, the active developer is only one and it still has a huge list of ToDo and Bugs to be fixed.

It can be used to replace custom If and Switch in the Domain language but if you need to do some custom and more complicated evaluations, Stateless can result very verbose because it doesn’t have a UI so you have to prepare all the If and Switch using the Configure syntax.

State pattern using C#. Part 01

13 February 2011 | View comments (0)

I have been busy for a while writing my two books about MVVM and WPF but I am almost done so be ready to get more posts in the next months. This one is the first of a series that I will write to solve the state pattern issue.

Today I want to start to talk about the state pattern, a design pattern used to represent the state of an object and how we can apply this pattern in a normal WPF application.

The problem we have is that based on the state of an Order we can or we can’t execute a specific action.

Before starting to talk about the pattern we need a sample application, right? So, what is better than having a nice WPF application that we will use to represents the problem? Smile

Process an order using States

The example I want to use is the classic Order entity that during the order process can be moved to different states. The following diagram create with Visual Studio shows you what I am talking about:

StateDiagram

The previous image shows the state diagram applied to an Order:

  • You can create  an order and after it is created the state is of type Created
  • Then you can modified the order or you can cancel the order; if you cancel the order, its state is cancelled and you can’t do anything anymore
  • An order that has been created can be approved and its state will change to approved

So in the previous Use Case we have identified 4 actions (blue) and 3 states (white), for each action there is a specific state, in a specific state you can execute only a specific or a set of specific actions and from one state you can move only to one or more specific states. For instance, from the Approved state we can’t rollback to the Created state and so on …

Now, how would you express the previous diagram using a Domain Model composed by an Order entity and a State property? First thing first is to implement a Domain Entity.

OrderObject

Now we can implement the classic state pattern described by Martin Fowler.

Classic implementation of the State Pattern

If you are an MVVM developer you may believe that the first and almost the easiest way of implementing this pattern is to use the Command pattern, right? So, if we plan to extend that in the Order entity we should have a model like the following one:

CommandPattern

Where the command implementation may be something like this:

Command Pattern
  1. CreateOrder = new Command(
  2.     () => true,
  3.     () =>
  4.         {
  5.             Code = "ABC123";
  6.             State = OrderState.Created;
  7.         }
  8.     );
  9. ModifyOrder = new Command(
  10.     () => State == OrderState.Created,
  11.     () =>
  12.         {
  13.             State = OrderState.Modified;
  14.         });
  15. CancelOrder = new Command(
  16.     () => this.State == OrderState.Created || this.State == OrderState.Modified,
  17.     () => { this.State = OrderState.Cancelled; });

 

When an order is created, by default, we do not allow any state so the default state is undefined and these are the tests:

TDD - change state
  1. [Test]
  2. public void AssertThatANewOrderIsUndefined()
  3. {
  4.     var order = new Order();
  5.     Assert.That(order.State, Is.EqualTo(OrderState.Undefined));
  6. }
  7.  
  8. [Test]
  9. public void AssertThatANewOrderCanBeCreated()
  10. {
  11.     var order = new Order();
  12.     order.CreateOrder.Run();
  13.     Assert.That(order.State, Is.EqualTo(OrderState.Created));
  14. }

 

The last step needs to verify that if we try to move from one state to a not allowed state, the action that we try to execute will throw an exception:

TDD - Not allowed method
  1. [Test]
  2. public void AssertThatCannotApproveANewOrderNotCreated()
  3. {
  4.     var order = new Order();
  5.     Assert.That(order.State, Is.EqualTo(OrderState.Undefined));
  6.     Assert.Throws<NotSupportedException>(() => order.ApproveOrder.Run());
  7. }

 

Conclusion using the Classic method

This technique is not clean and it is very verbose but it is absolutely testable, but not maintainable. For instance, if the number of state enum will increase we have to touch all over the code that execute the flow logic and probably we need also to refactor all the commands so we can say that this solution is fine but not maintainable at all.

Another gap of this solution is that every time we want to execute a command we need to fire the CanExecute method that may process some “long running” business logic behind:

Command Run() method
  1. public void Run()
  2. {
  3.     if (canExecute == null || canExecute.Invoke())
  4.     {
  5.         this.execute.Invoke();
  6.     }
  7.     else
  8.     {
  9.         throw new NotSupportedException("The action can't be executed.");
  10.     }
  11. }

In the next blog post we will see a different approach. At the end of the series (04 posts) I will provide a WPF application on www.codeplex.com with the source code posted in this series; please be patient for now as I can’t upload the final source code yet.