<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>planetgeek.ch</title>
	
	<link>http://www.planetgeek.ch</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Wed, 09 May 2012 09:32:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/planetgeekch" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="planetgeekch" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>The repository anti pattern clarified</title>
		<link>http://www.planetgeek.ch/2012/05/08/the-repository-anti-pattern-clarified/</link>
		<comments>http://www.planetgeek.ch/2012/05/08/the-repository-anti-pattern-clarified/#comments</comments>
		<pubDate>Tue, 08 May 2012 21:07:41 +0000</pubDate>
		<dc:creator>Daniel Marbach</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[domain driven design]]></category>
		<category><![CDATA[repository]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3417</guid>
		<description><![CDATA[In my last post I showed the transformation from the generic repository to the unit of work pattern only. I received an interesting question in the comment section. Looks nice so far. But didn’t you mix up and simplify things a little bit too much here? For me the Repository is the separation of Domain [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/05/08/the-repository-anti-pattern-clarified/";
		var dzone_title = "The repository anti pattern clarified";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>In my <a title="What is that all about the repository anti pattern?" href="http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/" target="_blank">last post</a> I showed the transformation from the generic repository to the unit of work pattern only. I received an interesting question in the comment section.</p>
<blockquote><p>Looks nice so far. But didn’t you mix up and simplify things a little bit too much here? For me the Repository is the separation of Domain Objects and Persistent Entities. It’s also a separation of the client from the used persistency technology (either NHibernate, EF, SharePoint, ADO.NET, WebService or whatever). As client side calling code, I really don’t care, where and how my data is stored.</p>
<p>Of course the interface of the repository should be expressive enough and not generic as this was mentioned many times by you and the different contributors.</p>
<p>But why do you mix together the Repository with the UnitOfWork and the transaction handling? Is it something NHibernate specific? Did I miss your point?</p></blockquote>
<p>I want to clarify my point in this blog post.<br />
<span id="more-3417"></span><br />
I don&#8217;t think I mixed up a little too much. The implementation I show in the blog post is moving from the repository pattern to the unit of work pattern. The article shows that a repository is an unneccesary abstraction which can be removed. Let us look into the formal definition of repositories and unit of work:</p>
<blockquote><p>&#8220;A REPOSITORY represents all objects of a certain type as a conceptual set (usually emulated). It acts like a collection, except with more elaborate querying capability. Objects of the appropriate type are added and removed, and the machinery behind the REPOSITORY inserts them or deletes them from the database. This definition gathers a cohesive set of responsibilities for providing access to the roots of AGGREGATES from early life cycle through the end.&#8221;<br />
[...]<br />
&#8220;Although the REPOSITORY will insert into and delete from the database, it will ordinarily not commit anything. It is tempting to commit after saving, for example, but the client presumably has the context to correctly initiate and commit units of work. Transaction management will be simpler if the REPOSITORY keeps its hands off.&#8221;<br />
- Domain Driven Design: Tackling complexity in the heart of the software -</p></blockquote>
<p>and the unit of work</p>
<blockquote><p>&#8220;When you&#8217;re pulling data in and out of a database, it&#8217;s important to keep track of what you&#8217;ve changed; otherwise, that data won&#8217;t be written back into the database. Similarly you have to insert new objects you create and remove any objects you delete.&#8221;<br />
[...]<br />
&#8220;A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you&#8217;re done, it figures out everything that needs to be done to alter the database as a result of your work.&#8221;<br />
- Patterns of Enterprise Application Architecture -</p></blockquote>
<p>As we see the two definitions closely relate to each other. The repository does not only offer querying capabilities but also allows to add and remove entities. But Repositories itself should not commit operations on the database. That is the responsibility of the unit of work. But the unit of work itself has to keep track of changes (add, removes and updates). Even querying requires the usage of an explicit business transaction (aka unit of work scope), not having an explicit transaction can result in implicit (and autocommiting transactions, see (1)). Therefore for querying we should also wrap these in a unit of work scope. I always prefer being explicit about my unit of work boundaries.</p>
<p>So what I did in the end is: I moved the add, remove and update responsibility solely to the unit of work (as it has to keep track of changes anyway). When you do that all what is left on the repository is the querying capability. Querying also needs explicit unit of work boundaries (business scope) and this can also be moved to the unit of work. Hope that helps.</p>
<p>(1)<br />
<strong>NHibernate</strong>: &#8220;When we don&#8217;t define our own transactions, it falls back into implicit transaction mode, where every statement to the database runs in its own transaction, resulting in a large performance cost (database time to build and tear down transactions), and reduced consistency.&#8221;<br />
<a href="http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions" target="_blank">http://nhprof.com/Learn/Alerts/DoNotUseImplicitTransactions</a><br />
<strong>EF</strong>: &#8220;When performing a SaveChanges operation, the Entity Framework implicitly wraps all of the commands in a database transaction; however, you can take control of transactions as well.&#8221;<br />
<a href="http://msdn.microsoft.com/en-us/library/orm-9780596520281-01-16.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/orm-9780596520281-01-16.aspx</a></p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/05/08/the-repository-anti-pattern-clarified/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What is that all about the repository anti pattern?</title>
		<link>http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/</link>
		<comments>http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/#comments</comments>
		<pubDate>Sat, 05 May 2012 14:18:37 +0000</pubDate>
		<dc:creator>Daniel Marbach</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[repository]]></category>
		<category><![CDATA[unit of work]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3404</guid>
		<description><![CDATA[There are a lot of discussions going on about the repository pattern. I also started one at the last usergroup meeting together with Julie Lerman. Generally the generic repository is considered an anti pattern as stated by Greg Young, he offers a solution by applying a composition pattern to maximize code reuse. Mike from SapiensWork [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/";
		var dzone_title = "What is that all about the repository anti pattern?";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>There are a lot of discussions going on about the repository pattern. I also started one at the last usergroup meeting together with Julie Lerman. Generally the generic repository is considered an anti pattern as stated by <a href="http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/" target="_blank">Greg Young</a>, he offers a solution by applying a composition pattern to maximize code reuse. Mike from SapiensWork even calls it a <a href="http://www.sapiensworks.com/blog/post/2012/03/05/The-Generic-Repository-Is-An-Anti-Pattern.aspx" target="_blank">complete anti pattern</a>. Ayende calls it since a long time <a href="http://ayende.com/blog/3955/repository-is-the-new-singleton" target="_blank">the new singleton</a>. Ayende also suggests in his older articles to either use directly NHibernate&#8217;s ISession or RavenDB&#8217;s IDocumentSession. Complex queries should be placed into query objects according to his article. So do we really need a repository? This article tries to answer this question.</p>
<p><span id="more-3404"></span><br />
Let us look into how a generic repository would look like.</p>
<pre class="brush: csharp; title: ; notranslate">
interface IRepository&lt;T&gt; {
IEnumerable&lt;T&gt; FindAllBy(IQuery&lt;T&gt; query);
void Add(T item);
void Delete(T item);
...
}
</pre>
<p>This approach has the following drawbacks:</p>
<ul>
<li>We need to instantiate for each entity a new repository of T</li>
<li>Like Greg states we are loosing expressivness when we are using FindAllBy(new CustomerByNameQuery(&#8220;Daniel&#8221;))</li>
</ul>
<p>What about when we apply Gregs composition approach?</p>
<pre class="brush: csharp; title: ; notranslate">
Public class CustomerRepository {
    private Repository&lt;Customer&gt; internalGenericRepository;
    Public IEnumerable&lt;Customer&gt; GetCustomersWithFirstNameOf(string name) {
         internalGenericRepository.FindAllBy(new CustomerFirstNameOfQuery(name));
    }
}
</pre>
<p>This would be a bit more expressiv because we have meaningful methods which describe what actually is done instead of FindAllBy(new QueryObject(&#8230;)). But still there is one major drawback:</p>
<ul>
<li>We need to instantiate a concrete class for each entity type we want to fetch data from.</li>
</ul>
<p>Let us try even another approach. What about that repository:</p>
<pre class="brush: csharp; title: ; notranslate">
interface IRepository {
IEnumerable&lt;T&gt; FindAllBy&lt;T&gt;(IQuery&lt;T&gt; query)
 where T : Entity;
…
}
</pre>
<p>We suddenly don&#8217;t need to instantiate a repository for each entity. We can fetch data from multiple entities with the same repository instance. But still it has a drawback:</p>
<ul>
<li>It is missing expressivness</li>
</ul>
<p>How could we overcome this issue? There is actually a solution with extension methods. We can use extension methods to cover the query objects behind the scenes and give this approach more expressivness.</p>
<pre class="brush: csharp; title: ; notranslate">
public static class CustomerRepositoryExtensions {
   public static IEnumerable&lt;Customer&gt; GetCustomersWithFirstNameOf(this IRepository repository, string name) {
      return repository.FindAllBy(new CustomerFirstNameOfQuery(name))
   }
}
</pre>
<p>Now we can have the following:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Foo {
   public Foo(IRepository repository) {
      this.repository = repository;
   }
   public void Bar() {
      var customers = this.repository.GetCustomersWithFirstNameOf(&quot;daniel&quot;);
   }
}
</pre>
<p>That looks kinda nice. It is easy to test. We don&#8217;t need a real database for the Foo class. But stop! What about transaction management and where is the session in case of NHibernate or something similar? In case of NHibernate we can directly use ISessionFactory.GetCurrentSession() to get the current session and then start a transaction.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Foo {
   public Foo(ISessionFactory sessionFactory, IRepository repository) {
      this.sessionFactory = sessionFactory;
      this.repository = repository;
   }
   private ISession Session {
      get { return this.sessionFactory.GetCurrentSession(); }
   }
   public void Bar() {
      using(var tx = this.Session.BeginTransaction()) {
         var customers = this.repository.GetCustomersWithFirstNameOf(&quot;daniel&quot;);
         // modify customers
         tx.Commit();
      }
   }
}
</pre>
<p>Suddenly we have NHibernate not only in the query objects and the repository implementation (someone needs to pass the current session of the call scope into the query) but also on the business logic. And also we have two dependencies which need to be injected in every class which needs database access. We can solve the first problem with an easy adapter for the session and the transaction which even allows nested scopes:</p>
<pre class="brush: csharp; title: ; notranslate">
    public class UnitOfWork : IUnitOfWork
    {
        private readonly Func&lt;IUnitOfWorkScope&gt; rootScopeFactory;
        private readonly Func&lt;IUnitOfWorkScope&gt; dependentScopeFactory;
        public UnitOfWork(ISessionFactory sessionFactory, Func&lt;IUnitOfWorkScope&gt; rootScopeFactory, Func&lt;IUnitOfWorkScope&gt; dependentScopeFactory)
        {
			this.sessionFactory = sessionFactory;
            this.rootScopeFactory = rootScopeFactory;
            this.dependentScopeFactory = dependentScopeFactory;
        }
        public IUnitOfWorkScope Start()
        {
            IUnitOfWorkScope scope = !CurrentSessionContext.HasBind(this.sessionFactory)
                                         ? this.rootScopeFactory()
                                         : this.dependentScopeFactory();
            scope.Begin();
            return scope;
        }
    }
	public class UnitOfWorkScope : IUnitOfWorkScope
    {
        public UnitOfWorkRootScope(ISessionFactory sessionFactory)
        {
			this.SessionFactory = sessionFactory;
        }
        protected ISessionFactory SessionFactory { get; private set; }
        protected ISession Session
        {
            get { return this.SessionFactory.GetCurrentSession(); }
        }
        protected ITransaction Transaction
        {
            get { return this.Session.Transaction; }
        }
        public virtual void Begin()
        {
            if (!this.Session.Transaction.IsActive)
            {
                this.isTransactionCreated = true;
                this.Session.BeginTransaction();
            }
        }
        public virtual void Commit()
        {
            this.isScopeCompleted = true;
            if (this.isTransactionCreated)
            {
                this.Transaction.Commit();
            }
        }
        public virtual void Rollback()
        {
            this.isScopeCompleted = true;
            this.Transaction.Rollback();
        }
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!this.isScopeCompleted &amp;&amp; this.Transaction.IsActive)
                {
                    this.Rollback();
                }
                if (this.isTransactionCreated)
                {
                    this.Transaction.Dispose();
                }
            }
        }
    }
	public class UnitOfWorkRootScope : UnitOfWorkScope
    {
        public UnitOfWorkRootScope(ISessionFactory sessionFactory)
            : base(sessionFactory)
        {
        }
        public override void Begin()
        {
            ISession session = this.SessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
            base.Begin();
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                ISession session = CurrentSessionContext.Unbind(this.SessionFactory);
                session.Close();
                session.Dispose();
            }
        }
    }
</pre>
<p>Let&#8217;s revisit our Foo class, shall we?</p>
<pre class="brush: csharp; title: ; notranslate">
public class Foo {
   public Foo(IUnitOfWork uow, IRepository repository) {
      this.uow = uow;
      this.repository = repository;
   }
   public void Bar() {
      using(IUnitOfWorkScope scope = this.uow.Start()) {
         var customers = this.repository.GetCustomersWithFirstNameOf(&quot;daniel&quot;);
         // modify customers, other class could att
         scope.Commit();
      }
   }
}
</pre>
<p>Nice we gained a little bit of abstraction in our business code regarding the persistency layer but we still have two dependencies in our Foo class. But do we really need the repository abstraction? NHibernate&#8217;s ISession is itself an unit of work. So why don&#8217;t we just move these few members onto the scope?</p>
<pre class="brush: csharp; title: ; notranslate">
    public interface IUnitOfWorkScope : IDisposable
    {
        void Begin();
        void Commit();
        void Rollback();
	IEnumerable&lt;T&gt; FindAllBy&lt;T&gt;(IQuery&lt;T&gt; query)
          where T : Entity;
        ...
    }
</pre>
<p>We can even move away the generic restriction which would then allow to use projections in the query too. This simplifies Foo to the following implemention (still using the extension method approach but this time on IUnitOfWorkScope).</p>
<pre class="brush: csharp; title: ; notranslate">
public class Foo {
   public Foo(IUnitOfWork uow) {
      this.uow = uow;
   }
   public void Bar() {
      using(IUnitOfWorkScope scope = this.uow.Start()) {
         var customers = scope.GetCustomersWithFirstNameOf(&quot;daniel&quot;);
         // modify customers, other class could att
         scope.Commit();
      }
   }
}
</pre>
<p>Isn&#8217;t that nice? No need for repositories. Unit testable. Simple and small abstraction. All persistency related stuff in either in the query or in the unit of work implementation and only there we need tests which either go to the database or use InMemory databases. But there is still one caveat regarding testability. Can you spot it?</p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Future of Activation blocks</title>
		<link>http://www.planetgeek.ch/2012/04/23/future-of-activation-blocks/</link>
		<comments>http://www.planetgeek.ch/2012/04/23/future-of-activation-blocks/#comments</comments>
		<pubDate>Mon, 23 Apr 2012 22:30:09 +0000</pubDate>
		<dc:creator>Remo Gloor</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[Scopes]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3392</guid>
		<description><![CDATA[Since I started using and working on Ninject I have never seen a good use case for Activations Blocks like they are implemented at the moment. That&#8217;s why I&#8217;m currently planning on changing their behavior to give them more sense. This blog post will explain what I have in mind at the moment. Current usage [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/04/23/future-of-activation-blocks/";
		var dzone_title = "Future of Activation blocks";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>Since I started using and working on Ninject I have never seen a good use case for Activations Blocks like they are implemented at the moment. That&#8217;s why I&#8217;m currently planning on changing their behavior to give them more sense. This blog post will explain what I have in mind at the moment.<br />
<span id="more-3392"></span><br />
<strong>Current usage and behavior (Ninject 3.0.0)</strong></p>
<p>Ninject V3.0.0 provides kernel.CreateBlock() which returns a IResolutionRoot. Within this resolution root every type exists exactly once as a local singleton object no matter which scope is defined for the binding.</p>
<p>In my opinion this behavior makes no sense. There are situations where you want to have exactly one instance of a service in the application. Activations Blocks do not allow to use these services because exactly one instance of each dependency is created within the activation block. Instead of sharing the instance between multiple activation blocks a new one is created for each activation block.</p>
<p><strong>Purpose of activation blocks</strong></p>
<p>The second problem of activation blocks is the way they are used. In order to create one you have call the CreateBlock method on the kernel. This has two disadvantages<strong>:</strong></p>
<ol>
<li>To create an activation block you need to know the kernel which gives you a dependency on Ninject.</li>
<li>You will get an IResolutionRoot on which you can resolve any type of dependency which means you are using Ninject like a kind of service locator.</li>
</ol>
<p>Because of these problems the activation block shouldn&#8217;t be used within applications. We can achieve the same behavior without having these problems with named scopes. How this is done is explained in the next chapter.</p>
<p>But there is situations where activation blocks are helpful. There are frameworks e.g. ASP.NET WebAPI and NServiceBus that have the concept to create a scope around a request. While integration into these types of frameworks using named scopes is possible it is much simpler to do so with an activation block. But the current implementation of the activation block where everything is a singleton object within the block is not correct an needs to be changed as described in the last part of this article.</p>
<p><strong>Creating an activation block using a Named Scope</strong></p>
<p>As already explained using activation blocks within an application has two disadvantages. You can get the same behavior using named scopes and factories.</p>
<p>Instead of creating a new block you pass a factory to the component that is responsible to start the activation block and use it whenever a new activation block is required. E.g. pass a IMyTcpRequestHandlerFactory to the IMyTcpServer class and whenever a new connection is established this factory is used to create a new IMyTcpRequestHandler.</p>
<p>The second step is to configure that this newly created component is the scope for other components it is depending on using a named scope and assign this scope to the dependencies:</p>
<pre class="brush: csharp; title: ; notranslate">
public class MyTcpRequestHandler : IMyTcpRequestHandler
{
    public MyTcpRequestHandler(ISomeDependency someDependency) {}

    ....
}

const string TcpRequestScope = &quot;TcpRequestScope&quot;;
Bind&lt;IMyTcpRequestHandlerFactory&gt;().ToFactory();
Bind&lt;IMyTcpRequestHandler&gt;().To&lt;MyTcpRequestHandler&gt;().DefinesNamedScope(TcpRequestScope);
Bind&lt;ISomeDependency&gt;().To&lt;SomeDependency&gt;().InNamedScope(TcpRequestScope);
</pre>
<p>In case you need to create multiple dependencies depending on some runtime conditions you can pass other factories to this component and use them to create them. But in this case you will have to load the Ninject.Extensions.ContextPreservation extension together with the named scope extension.</p>
<p><strong>How activation blocks will behave in future</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public class MyTcpRequestHandler : IMyTcpRequestHandler
{
    public MyTcpRequestHandler(IProcessingStrategyFactory processingStrategyFactory, ...) {}

    public void HandleRequest()
    {
        var contentType = this.GetTcpContentType();
        var processingStrategy = contentType.IsXml
            ? this.processingStrategyFactory.CreateXmlProcessingStrategy();
            : this.processingStrategyFactory.CreateBinaryProcessingStrategy();

        ....
    }
}

const string TcpRequestScope = &quot;TcpRequestScope&quot;;
Bind&lt;IMyTcpRequestHandlerFactory&gt;().ToFactory();
Bind&lt;IProcessingStrategyFactory&gt;().ToFactory();
Bind&lt;IMyTcpRequestHandler&gt;().To&lt;MyTcpRequestHandler&gt;().DefinesNamedScope(TcpRequestScope);
Bind&lt;IProcessingStrategy&gt;().To&lt;XmlProcessingStrategy&gt;().InNamedScope(TcpRequestScope);
Bind&lt;IProcessingStrategy&gt;().To&lt;BinaryProcessingStrategy&gt;().InNamedScope(TcpRequestScope);
</pre>
<p><strong>Changes to the current activation block</strong></p>
<p>I&#8217;m currently planning to add a new scope InActivationBlockScope to Ninject. Only bindings with this scope type will be affected by the activation block. Within an activation block they will be local singleton objects. Exactly one instance will be created within the activation block and they will be disposed together with the activation block. Outside of an activation block they will behave like transient objets. All other scopes will behave exactly the same way within and outside of activation blocks.</p>
<p>With this change it will be possible to use the existing scopes within an activation block while having the possibility to scope some objects by an activation block. This will make it easy to use Ninject together with Frameworks like ASP.NET WebAPI and NServiceBus.</p>
<p>Currently, this change is still a proposal. Feedback is very welcome.</p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/04/23/future-of-activation-blocks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SunRay Terminal unexpected reboot</title>
		<link>http://www.planetgeek.ch/2012/04/02/sunray-terminal-unexpected-reboot/</link>
		<comments>http://www.planetgeek.ch/2012/04/02/sunray-terminal-unexpected-reboot/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 19:24:20 +0000</pubDate>
		<dc:creator>konrad.dambeck</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[vdi]]></category>
		<category><![CDATA[Broken pipe]]></category>
		<category><![CDATA[ID 197738]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[SocketException]]></category>
		<category><![CDATA[Sun]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3384</guid>
		<description><![CDATA[For a project we use some SunRay 3 Plus terminal with the Sun Oracle VDI server. After all I only can say this thin client solution rock!!! But in the project time we hade to debug a problem. The problem was some Sun Ray Clients did unexpected reboots every 2 till 5 minutes. And it [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/04/02/sunray-terminal-unexpected-reboot/";
		var dzone_title = "SunRay Terminal unexpected reboot";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>For a project we use some SunRay 3 Plus terminal with the Sun Oracle VDI server. After all I only can say this thin client solution rock!!! But in the project time we hade to debug a problem. The problem was some Sun Ray Clients did unexpected reboots every 2 till 5 minutes. And it comes even stranger, next day the Terminal works without any problem and another terminal reboots. After some vi action we found the following error in the Log of the vdi server.<br />
<span id="more-3384"></span><br />
<em>TIME SERVERNAME utauthd: [ID 197738 user.info] Worker5 UNEXPECTED: during send to: java.net.SocketOutputStream@94c924 error=java.net.SocketException: Broken pipe</em></p>
<p>After searching the error in the net, we don’t get any step forward. next thing we did analyze the thin client traffic with wire shark. 30 seconds before the Terminal reboots there are many tcp retransmits on the network.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/04/image.png"  rel="lightbox" rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.planetgeek.ch/wp-content/uploads/2012/04/image_thumb.png" alt="image" width="600" height="98" border="0" /></a></p>
<p>It was “to milk mousses”* after some searching (x&gt;2 Day’s) we find out that the arp Table on the switch with the SunRay attached flips a mac address.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/04/image1.png"  rel="lightbox" rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.planetgeek.ch/wp-content/uploads/2012/04/image_thumb1.png" alt="image" width="396" height="118" border="0" /></a></p>
<p>With this additional input it takes 20 seconds and we get the brake trough idea. The problem was a simple IP conflict with a old Printer. So if you ever get this problem don’t waste 3 Day’s of your live.</p>
<p>Regards Konrad</p>
<p>*milk mouse is some German saying for we are working very hard but don’t get any step near the Target.</p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/04/02/sunray-terminal-unexpected-reboot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Open Source Software and Medical Technical Projects</title>
		<link>http://www.planetgeek.ch/2012/03/27/open-source-software-and-medical-technical-projects/</link>
		<comments>http://www.planetgeek.ch/2012/03/27/open-source-software-and-medical-technical-projects/#comments</comments>
		<pubDate>Tue, 27 Mar 2012 15:50:53 +0000</pubDate>
		<dc:creator>Urs Enzler</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[MedTech]]></category>
		<category><![CDATA[Open source]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3369</guid>
		<description><![CDATA[These are the slides with comments of my conference talk at MedConf 2012 in Lucerne: Software development without using open source software (OSS) is unthinkable in today’s world. This holds also for medical technical projects. This presentation is split into three parts. First we take a look at some myths and facts about open source [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/03/27/open-source-software-and-medical-technical-projects/";
		var dzone_title = "Open Source Software and Medical Technical Projects";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>These are the slides with comments of my conference talk at <a href="http://www.medconf.ch/">MedConf 2012</a> in Lucerne:</p>
<p>Software development without using open source software (OSS) is unthinkable in today’s world. This holds also for medical technical projects.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Agenda.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Agenda" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Agenda_thumb.png" alt="Agenda" width="244" height="184" border="0" /></a></p>
<p>This presentation is split into three parts. First we take a look at some myths and facts about open source software. Then at how to integrate an OSS into your project so it can be validated against regulatory requirements. And finally, we’ll see what is important when selecting open source software.</p>
<p><span id="more-3369"></span></p>
<p>During my career as a software engineer, I got used to use open source software a lot.</p>
<p>But when I started in my very first medical technical project, I was confronted with strong opinions about open source software.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/NoChance.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="NoChance" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/NoChance_thumb.png" alt="NoChance" width="244" height="184" border="0" /></a></p>
<p>I was told that they don’t meet the quality needs. It was unthinkable to use some sloppy written code of someone who has nothing better to do in his spare time than coding.</p>
<p>And that it would be insane to rely on a piece of software for which there was no commercial support. Overall, using open source software would just be far too risky.</p>
<p>&nbsp;</p>
<p>Okay, I said, but let’s take a look at some facts.</p>
<p>First, we need to take a look at what kinds of software we actually have in our project.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/KindsOfCode.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="KindsOfCode" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/KindsOfCode_thumb.png" alt="KindsOfCode" width="244" height="184" border="0" /></a></p>
<p>There is the code we wrote ourselves. Then there is the code we bought – typically as closed source. And there is open source code.</p>
<p>There are even some mixtures of these kinds. For example there are commercial libraries, which offer you the source code, too. Or there are open source projects that offer commercial support. But for simplicity, let’s use these three types of source code.</p>
<p>&nbsp;</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Quality.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Quality" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Quality_thumb.png" alt="Quality" width="244" height="184" border="0" /></a></p>
<p>Now, let’s take a look at the myth that the quality of open source software is not as good as the quality of our own code or of commercial libraries.</p>
<p>The question here is: What does actually influence quality?</p>
<p>&nbsp;</p>
<p>The main driver for quality is …</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Feedback.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Feedback" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Feedback_thumb.png" alt="Feedback" width="244" height="184" border="0" /></a></p>
<p>… feedback.</p>
<p>The more feedback a projects gets about defects and its usability the better its quality gets.</p>
<p>But this is a big problem for the code we wrote ourselves. There is much less feedback than commercial or open source projects get. Simply due to the fact, that they are used in more projects, by more developers and users.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/DomainKnowHow.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="DomainKnowHow" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/DomainKnowHow_thumb.png" alt="DomainKnowHow" width="244" height="184" border="0" /></a></p>
<p>Domain know-how of the developers is another big influence on the quality. Only when the developers know what they are building, quality can get really high.</p>
<p>Obviously, our own team cannot know everything. So there are aspects in our software where we lack domain know-how. Or does your team know how to write a scheduling component for example?</p>
<p>That means, that the quality of commercial or open source software in special areas is much higher than when built by ourselves. Commercial and open source projects focus on a single topic and therefore gain domain know-how on this single topic.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Transparency.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Transparency" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Transparency_thumb.png" alt="Transparency" width="244" height="184" border="0" /></a></p>
<p>Transparency helps to assess quality. When you can look at the code, or see how many defects are in the defect tracking system, you can decide for yourself whether a library or product is good enough for you.</p>
<p>Most commercial products don’t give you access to the source code or the defect tracking system. Therefore, they are a black box and hard to assess.</p>
<p>In open source software, as in your own code, you have full access. You can run some quality metrics against the code and check how many open defects lie around in the defect tracking system and how long it normally takes the team to fix a defect.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/MotivationInnovation.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="MotivationInnovation" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/MotivationInnovation_thumb.png" alt="MotivationInnovation" width="244" height="184" border="0" /></a></p>
<p>Finally, quality is a result of motivated teams and innovative solutions.</p>
<p>People working in open source projects are likely highly motivated. They spend their spare time!</p>
<p>The people involved in your team or from the company you buy software from may be a bit less motivated.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/CoverityScan.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="CoverityScan" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/CoverityScan_thumb.png" alt="CoverityScan" width="244" height="184" border="0" /></a></p>
<p>The coverity scan (<a href="http://scan.coverity.com/">http://scan.coverity.com/</a>) of the year 2011 states that &#8220;Open source quality for active projects in Coverity Scan is better than the software industry average.“</p>
<p>To sum up, if you are looking for quality in your software, try not to implement it yourself.</p>
<p>&nbsp;</p>
<p>Another myth is that you don’t get any guarantees with open source software.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Maintenance.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Maintenance" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Maintenance_thumb.png" alt="Maintenance" width="244" height="184" border="0" /></a></p>
<p>So what happens if you need help with a defect? You probably don’t get a support contract.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/MaintenanceTypes.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="MaintenanceTypes" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/MaintenanceTypes_thumb.png" alt="MaintenanceTypes" width="244" height="184" border="0" /></a></p>
<p>It’s like with your own code. There, you have to support yourself.</p>
<p>With commercial products, you can rely on the support. But far too often, support is slow, and you’ll have to wait for the next release for your problem to be fixed.</p>
<p>With open source software you get the best of both worlds. Either you can take measures on your own and fix the defect yourself, or rely on the project team and the community to fix the problem for you.</p>
<p>Although you don’t have a contract in hand, open source software gives you flexibility to act on your own, or wait for the project to take care of defects. The latter is in most cases the cheaper variant.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/MaintenanceFDA.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="MaintenanceFDA" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/MaintenanceFDA_thumb.png" alt="MaintenanceFDA" width="244" height="184" border="0" /></a></p>
<p>An analysis of the Food and Drug Administration shows that from the recalled medical devices between 1992 and 1998, 7.7% were caused by software failures.</p>
<p>79% of these software related recalls were caused by software defects that were introduced when changes were made to the software after its initial production and distribution.</p>
<p>Therefore, if you are looking for quality, externalize maintenance and profit from the feedback of everyone else using the software.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Corporate-Governance.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Corporate Governance" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Corporate-Governance_thumb.png" alt="Corporate Governance" width="244" height="184" border="0" /></a></p>
<p>When using open source software in your projects, there are other things you need to consider, too.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Distribution.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Distribution" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Distribution_thumb.png" alt="Distribution" width="244" height="184" border="0" /></a></p>
<p>The license of the open source software you want to use can have a big influence on how you have to distribute your software.</p>
<p>If you for example use a GPL license, all derived work has to be published under GPL, too. Therefore, avoid GPL open source software if you want to build commercial software.</p>
<p>On the other side, projects licensed under Apache 2.0 require you only to include the license and information from where you have the code, somewhere in the installation.</p>
<p>Unfortunately, there are a lot of different licenses. You may need a lawyer to make sure that you don’t run into any problems with some of these.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/CopyRightPatents.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="CopyRightPatents" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/CopyRightPatents_thumb.png" alt="CopyRightPatents" width="244" height="184" border="0" /></a></p>
<p>Another aspect you have to be aware of is copy right and patent violation.</p>
<p>In your own code, it’s up to you to make sure that the developers don’t violate any patents or copy rights.</p>
<p>This also applies to most open source projects. But there are foundations that take care of these questions, like the Eclipse and Apache Foundation.</p>
<p>And if you use open source software that is used by a wide variety of other companies, it’s unlikely that someone will succeed with a patent lawsuit.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Risks.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Risks" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Risks_thumb.png" alt="Risks" width="244" height="184" border="0" /></a></p>
<p>Regarding risk management, writing your own code, buying a commercial product and using open source software have all their advantages and disadvantages.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/RiskList.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="RiskList" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/RiskList_thumb.png" alt="RiskList" width="244" height="184" border="0" /></a></p>
<p>Regarding legal aspects, commercial products are best for you (they would have a problem and not you). Open source software has a bit less risk than writing your own code because of the foundations we have seen before helping to mitigate these risks. And you are probably not alone.</p>
<p>The risk of bad quality is highest for your own code. Mainly because of the lack of feedback compared to commercial and open source software. Commercial products and open source software with bad quality likely won’t survive very long.</p>
<p>There is always the risk that the product you use is no longer maintained. This is more likely in open source projects. But at least, you have the source code and could continue using it. If a commercial product is dead, your only option is to leave it. There is also an end of life in your own code. If know-how about your code is sparsely distributed in your team, a team member leaving could have the same effect.</p>
<p>Open source software could get commercial. However this happens quite rarely and you could still continue to use the latest open version of the product. Or of course, buy the new version. Obviously, the risk of getting commercial has already occurred for commercial products.</p>
<p>Implementing your own code is for sure the most expensive variant if there are commercial or open source products available that solve the same problem. Therefore, the financial risk is highest for your own code. The financial risk is lowest for open source software because you get the software for free. However, it still costs to integrate and learn an open source software.</p>
<p>The risk that the solution you built or bought is only a short-living solution is highest for your own code. That’s because of less feedback compared to commercial or open source software. A short-lived solution forces you to invest effort soon because it does not support future development.</p>
<p>Finally, there is the risk that the roadmap or release cycle of the product you chose does not match your needs in the future. Open source software gives you however the possibility to act on your own and adapt the source code yourself. This can be very important regarding your own deployment cycles.</p>
<p>Overall, open source software is a strong choice regarding risks. Especially, if financial aspects have a heavy weight for you.</p>
<p>&nbsp;</p>
<p>Looking back at my first medical technical project, once we convinced the developers and project leaders that open source software can save us a lot of money and trouble, the guys from the regulatory department stepped in.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/IntegrationValidation.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="IntegrationValidation" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/IntegrationValidation_thumb.png" alt="IntegrationValidation" width="244" height="184" border="0" /></a></p>
<p>They said that they don’t want any open source software, how should this software be validated?</p>
<p>&nbsp;</p>
<p>The most important point is that you take the source code of the open source project and add it to the source control system where your own code lives.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/LikeYourOwn.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="LikeYourOwn" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/LikeYourOwn_thumb.png" alt="LikeYourOwn" width="244" height="184" border="0" /></a></p>
<p>This is the only way you will know in the future, which version of the open source software was used in which of your releases. And maybe the open source project dies and you cannot download the sources anymore.</p>
<p>Furthermore, you will have to maintain your software probably for a long time. This can be a problem with commercial products. Maybe the product does not support the latest operating system anymore. With open source software, you can adapt the code yourself as a last resort.</p>
<p>Regarding validation, it can be a great advantage that you can fix defects yourself. You could do this in a way so that only a minimum of code is changed and therefore minimizing validation effort needed.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Validation.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Validation" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Validation_thumb.png" alt="Validation" width="244" height="184" border="0" /></a></p>
<p>It’s very unlikely that you get support for validation from the open source project.</p>
<p>To validate the open source software, you should treat it just like your own code. Do whatever you do with your own code to get it validated.</p>
<p>The advantage of open source software is that it is not a black box to you.</p>
<p>You can review the code and if the open source software contains unit or acceptance tests, you can use them, too.</p>
<p>Additionally, you could even include the source code when submitting your project for validation.</p>
<p>&nbsp;</p>
<p>When using open source software, make sure that you use an …</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Up-to-date.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Up-to-date" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Up-to-date_thumb.png" alt="Up-to-date" width="244" height="184" border="0" /></a></p>
<p>… up-to-date version.</p>
<p>Documentation and help from the community is normally only available for up-to-date versions.</p>
<p>And you can only profit from externalized maintenance if you update regularly.</p>
<p>Good open source projects provide you with tutorials how to upgrade from one version to the next. Therefore you shouldn’t be behind more than one version.</p>
<p>&nbsp;</p>
<p>Looking back at my first medical technical project, it took some time to get support from all involved parties. But finally, open source software could be used in great variety.</p>
<p>But there is still one problem to solve:</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Choose.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Choose" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Choose_thumb.png" alt="Choose" width="244" height="184" border="0" /></a></p>
<p>How to find the right open source software.</p>
<p>First of all, the open source software should solve a problem of yours. But that is not enough.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/ProjectCharacteristics.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="ProjectCharacteristics" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/ProjectCharacteristics_thumb.png" alt="ProjectCharacteristics" width="244" height="184" border="0" /></a></p>
<p>You should check whether the project has a road map so that you can decide whether the project runs in the right direction. Take a look at news, releases, commit and the number of committers to see whether the project is alive. Check whether there is an issue tracker and how many defects are in there. And whether these defects get fixed in a reasonable amount of time.</p>
<p>Technically, you should check whether you can build the sources so you could fix defects yourself. Check whether there are unit and acceptance tests and whether the code style suits you.</p>
<p>And very important, check if there are any external dependencies and if they meet your requirements.</p>
<p>&nbsp;</p>
<p>In order to get you up to speed quickly, take a look at the…</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Documentation.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Documentation" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Documentation_thumb.png" alt="Documentation" width="244" height="184" border="0" /></a></p>
<p>… documentation. Are there a wiki, web page and samples. Are they up-to-date? Do you find success stories of other people using this software?</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Community.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Community" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Community_thumb.png" alt="Community" width="244" height="184" border="0" /></a></p>
<p>Is there a community that supports the OSS. Is there a forum? Are questions answered? In a reasonable time frame?</p>
<p>It takes quite a lot of time to get a picture of an open source software. But it will save you lots of problems when done thoroughly.</p>
<p>&nbsp;</p>
<p>To sum everything up, I’d like you to think about …</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/CallToAct.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="CallToAct" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/CallToAct_thumb.png" alt="CallToAct" width="244" height="184" border="0" /></a></p>
<p>… whether open source software could help you in your projects to get better quality, less maintenance or to finish your project earlier before beginning to write your own code.</p>
<p>And if you use open source software …</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/GiveFeedback.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="GiveFeedback" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/GiveFeedback_thumb.png" alt="GiveFeedback" width="244" height="184" border="0" /></a></p>
<p>… please provide feedback.</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/03/Outro.png"  rel="lightbox[roadtrip]"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Outro" src="http://www.planetgeek.ch/wp-content/uploads/2012/03/Outro_thumb.png" alt="Outro" width="244" height="184" border="0" /></a></p>
<p>&nbsp;</p>
<h3></h3>
<h3>Links</h3>
<p><a href="http://www.fda.gov/medicaldevices/deviceregulationandguidance/guidancedocuments/ucm085281.htm#_Toc517237946">FDA guideance (validation of 3rd party software)</a></p>
<p><a href="http://scan.coverity.com/">Coverty scan (OSS quality)</a></p>
<p><a href="http://www.planetgeek.ch/2010/06/20/how-to-select-open-source-libraries/">How to select open source libraries (Daniel Marbach)</a></p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/03/27/open-source-software-and-medical-technical-projects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Client / Server Localization – Resources</title>
		<link>http://www.planetgeek.ch/2012/03/23/client-server-localization-resources/</link>
		<comments>http://www.planetgeek.ch/2012/03/23/client-server-localization-resources/#comments</comments>
		<pubDate>Fri, 23 Mar 2012 12:58:28 +0000</pubDate>
		<dc:creator>Daniel Marbach</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Localization]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3286</guid>
		<description><![CDATA[In my last post I described the problem domain behind client / server localization. In this post I&#8217;m going to tackle how dynamic translation can be achieved in a client / server environment. The basic idea is to use compiled resources from the server side and transport it over the wire to the client. When [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/03/23/client-server-localization-resources/";
		var dzone_title = "Client / Server Localization &#8211; Resources";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>In my <a title="Client / Server Localization – Introduction" href="http://www.planetgeek.ch/2012/01/25/client-server-localization-introduction/">last post </a>I described the problem domain behind client / server localization. In this post I&#8217;m going to tackle how dynamic translation can be achieved in a client / server environment. The basic idea is to use compiled resources from the server side and transport it over the wire to the client. When talking about &#8220;resources&#8221; we want to use a mechanism which is really close to the way localization generally works under .NET. To understand this we need to have a look into the resource manager.<br />
<span id="more-3286"></span><br />
The .NET Resource manager under System.Resources has the following responsibilities:</p>
<ul>
<li>It looks up culture-specific resources</li>
<li>Provides resource fallbacks when a localized resource does not exists</li>
<li>Supports resource serialization</li>
</ul>
<p>The ResourceManager can either retrieve resources from binary resource (.resources) files laying on the disk or from resource files which are embedded in an so called satellite assembly. Satellite assemblies are special assemblies (they only contain resources) which are compiled and deployed together with the corresponding main assembly but can be individually versioned. Usually you have one satellite assembly per language you support in your application. Using satellite assemblies for dynamic client / server localization doesn&#8217;t make sense because the client doesn&#8217;t use the same deployment units (aka assemblies) as the server application. Luckily the ResourceManager allows use to declare file based resource managers from binary resource files by using the static method <em>CreateFileBasedResourceManager</em>. This declares a ResourceManager which doesn&#8217;t depend on any particular assembly.</p>
<p>Binary resource files must follow a certain convention. Each binary resource file must have a <strong>basename</strong>. For example we could define a basename &#8220;MyResources&#8221;. In this case the default resource file on the disk must be called &#8220;MyResources.resources&#8221;. The language dependent resource files must be called &#8220;MyResources.[de/fr-Be..].resources&#8221;. So imagine we have the following resource structure on the server side:</p>
<pre>someserverpath/MyResources.resources
someserverpath/MyResources.de.resources
someserverpath/MyResources.de-ch.resources
...</pre>
<p>The only thing we have to do to start with dynamic localization is we need to somehow transfer all the *.resources files from the server to the client. The client needs to place all the downloaded files into a similar structure as found on the server, for example:</p>
<pre>someclientpath/MyResources.resources
someclientpath/MyResources.de.resources
someclientpath/MyResources.de-ch.resources
...</pre>
<p>After we have downloaded and placed all *.resources files on the client side we need to instantiate a resource manager <strong>for each basename</strong>. In the example above this can be achieved with the following line of code:</p>
<pre class="brush: csharp; title: ; notranslate">
var myResourcesRM = ResourceManager.CreateFileBasedResourceManager(&quot;MyResources&quot;, &quot;someclientpath/&quot;);
</pre>
<p>As soon as we want to translate something on the client we only need to call</p>
<pre class="brush: csharp; title: ; notranslate">
myResourcesRM.GetString(&quot;resourcekey&quot;)
</pre>
<p>So far so good. In the next post I&#8217;m going to show how we can get resources from the server to the client and how to handle multiple resource managers and basenames. Stay tuned.</p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/03/23/client-server-localization-resources/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to suppress exceptions with fluent assertions</title>
		<link>http://www.planetgeek.ch/2012/03/22/how-to-suppress-exceptions-with-fluent-assertions/</link>
		<comments>http://www.planetgeek.ch/2012/03/22/how-to-suppress-exceptions-with-fluent-assertions/#comments</comments>
		<pubDate>Thu, 22 Mar 2012 20:32:18 +0000</pubDate>
		<dc:creator>Daniel Marbach</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[fluentassertions]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3296</guid>
		<description><![CDATA[Imagine you need to code the following requirements: When an exception is thrown the transaction must be rolled back The thrown exception must be rethrown The productive code could look like: Now how would you write the requirements above in two separate unit tests? Here comes FluentAssertions into the play. We just write a little [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/03/22/how-to-suppress-exceptions-with-fluent-assertions/";
		var dzone_title = "How to suppress exceptions with fluent assertions";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>Imagine you need to code the following requirements:</p>
<ul>
<li>When an exception is thrown the transaction must be rolled back</li>
<li>The thrown exception must be rethrown</li>
</ul>
<p>The productive code could look like:</p>
<pre class="brush: csharp; title: ; notranslate">
public class SomeComponent
{
   public void Do() {
      ITransaction tx = this.session.BeginTransaction();
      try {
      this.session.Save(foo);
      } catch(DataException e) {
         tx.Rollback();
         throw;
      }
   }
}
</pre>
<p>Now how would you write the requirements above in two separate unit tests? Here comes <a href="http://fluentassertions.codeplex.com/" target="_blank">FluentAssertions </a>into the play.</p>
<p><span id="more-3296"></span></p>
<p>We just write a little extension method which ignores a specific kind of exception type and hook it up just after the fluent assertions extension method &#8220;Invoking&#8221;.</p>
<pre class="brush: csharp; title: ; notranslate">
    public static class CustomAssertionExtensions
    {
        public static void IgnoreAnyExceptions&lt;TException&gt;(this Action action)
            where TException : Exception
        {
            try
            {
                action();
            }
            catch(TException)
            {
            }
        }
    }
</pre>
<p>And here the test code which uses it.</p>
<pre class="brush: csharp; title: ; notranslate">
    [TestFixture]
    public class SomeComponentTest
    {
        private ITransaction transaction;
        private ISession session;
        private SomeComponent testee;

        [SetUp]
        public void SetUp()
        {
            this.transaction = A.Fake&lt;ITransaction&gt;();
            this.session = A.Fake&lt;ISession&gt;();
            this.SetupSessionReturnsTransaction();

            this.testee = new SomeComponent(this.session);
        }

        [Test]
        public void WhenExceptionOccurs_ShouldRollbackTransaction()
        {
            A.CallTo(() =&gt; this.session.Save(A&lt;object&gt;.Ignored)).Throws(new DataException());

            this.testee.Invoking(t =&gt; t.Execute()).IgnoreAnyExceptions&lt;DataException&gt;();

            A.CallTo(() =&gt; this.transaction.Rollback()).MustHaveHappened();
        }

        [Test]
        public void WhenExceptionOccurs_ShouldRethrow()
        {
            A.CallTo(() =&gt; this.session.Save(A&lt;object&gt;.Ignored)).Throws(new DataException());

            this.testee.Invoking(t =&gt; t.Execute()).ShouldThrow&lt;DataException&gt;();
        }

        private void SetupSessionReturnsTransaction()
        {
            A.CallTo(() =&gt; this.session.BeginTransaction()).Returns(this.transaction);
        }
    }
</pre>
<p>Hope this helps. I suggest you check out <a href="http://fluentassertions.codeplex.com/" target="_blank">fluent assertions</a>! Have fun. By the way the example was written using <a href="https://github.com/patrik-hagne/FakeItEasy" target="_blank">FakeItEasy</a>. Be sure to check it out too!</p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/03/22/how-to-suppress-exceptions-with-fluent-assertions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create your own hamcrest matcher</title>
		<link>http://www.planetgeek.ch/2012/03/07/create-your-own-matcher/</link>
		<comments>http://www.planetgeek.ch/2012/03/07/create-your-own-matcher/#comments</comments>
		<pubDate>Wed, 07 Mar 2012 12:17:07 +0000</pubDate>
		<dc:creator>Adrian Elsener</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[hamcrest]]></category>
		<category><![CDATA[matcher]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3187</guid>
		<description><![CDATA[If you are familiar with hamcrest and JUnit the time will come when you have the need to create your own matchers. Creating your own matcher can be as simple as useful. One reason for creating your own matcher could be that your object is not a default object like a String or a Collection. [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/03/07/create-your-own-matcher/";
		var dzone_title = "Create your own hamcrest matcher";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>If you are familiar with hamcrest and JUnit the time will come when you have<br />
the need to create your own matchers.<br />
Creating your own matcher can be as simple as useful. One reason for<br />
creating your own matcher could be that your object is not a default object<br />
like a String or a Collection. And if you would like to get a more readable<br />
version of the assert for the next developer who has to read your<br />
test. Let&#8217;s make an example. If you have an object with two methods;<br />
&#8220;<em><strong>getName</strong></em>&#8221; and &#8220;<em><strong>getNumber</strong></em>&#8221; and you would like to check whether the resulting object<br />
has the correct values.<br />
In my opinion the best way to verify this is to create two matchers and<br />
combine them. Before we can combine these two matchers let&#8217;s see how to<br />
create them.<span id="more-3187"></span><br />
For our examples we will test an instance of the following class:</p>
<pre class="brush: java; title: ; notranslate">
public class Foo {
   public String getName() {
      return &quot;Foo&quot;;
   }

   public int getNumber() {
      return 41;
   }
}
</pre>
<p>If you have a look at the Matcher interface you will see some hints<br />
which tell you not to implement the Matcher itself. So have a look at<br />
BaseMatcher which is referred to in the Matcher interface.</p>
<p>Let&#8217;s check if the number is 42 and the name is “Bar”. The samples show<br />
possible solutions without every time creating its own class files. I just<br />
write a small factory method instead of creating a matcher class. This<br />
will be the first step while coding your test/matcher. If you see the<br />
matcher can be used somewhere else, it should be very easy to create an<br />
own class. It would also be helpful to create a factory class which<br />
will centralize your matchers.</p>
<h3>Using BaseMatcher</h3>
<p>If we use BaseMatcher we will recognize that we have to implement the<br />
following two methods:</p>
<ul>
<li><strong><em>public boolean matches(Object item)</em></strong> : here we will do the check.<br />
The item will be our object under test (Should be an instance of<br />
Foo).</li>
<li><strong><em>public void describeTo(Description description)</em></strong> : here we will<br />
have to return a description of our matcher. This will simplify our<br />
life if there are failures.</li>
</ul>
<p>Now let&#8217;s see how the implementation of a BaseMatcher could look like for<br />
checking the value of getNumber().</p>
<pre class="brush: java; title: ; notranslate">
private Matcher&lt;Foo&gt; hasNumber(final int i) {
   return new BaseMatcher&lt;Foo&gt;() {
      @Override
      public boolean matches(final Object item) {
         final Foo foo = (Foo) item;
         return i == foo.getNumber();
      }
      @Override
      public void describeTo(final Description description) {
         description.appendText(&quot;getNumber should return &quot;).appendValue(i);
      }
   };
}
</pre>
<p>And the usage would look like this:</p>
<pre class="brush: java; title: ; notranslate">
@Test
public void numberIs42() {
   final Foo testee = new Foo();
   assertThat(testee, hasNumber(42));
}
</pre>
<p>This results in a failing test. All right we want a failing test<br />
otherwise we could not have a look at the features of our new matcher<br />
since this will only be apparent while the test is failing <img src='http://www.planetgeek.ch/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
So the test will give us this output:</p>
<pre><strong>java.lang.AssertionError: Expected: (getNumber should return &lt;42&gt;) got: &lt;ch.adrianelsener.MatcherSampleTest$Foo@136070f0&gt; </strong></pre>
<p>You will agree with me that this is not very useful. But it is a good<br />
demonstration why to do a failing test first, to demonstrate what can happen when<br />
the test fails, otherwise you might never have noticed that there is room for<br />
improvement.<br />
There are two possible solutions to get a more powerful message:</p>
<ul>
<li>Implementing toString on Foo would be one of them but not what we want.</li>
<li>Implement the method <strong>&#8220;<em>public void describeMismatch(final</em><br />
<em>Object item, final Description description)</em>&#8220;</strong> in our<br />
matcher</li>
</ul>
<p>If we add &#8220;describeMismatch&#8221;, our matcher would now look like this:</p>
<pre class="brush: java; title: ; notranslate">
private Matcher&lt;Foo&gt; hasNumber(final int i) {
   return new BaseMatcher&lt;Foo&gt;() {
      @Override
      public boolean matches(final Object item) {
         final Foo foo = (Foo) item;
         return i == foo.getNumber();
      }
      @Override
      public void describeTo(final Description description) {
         description.appendText(&quot;getNumber should return &quot;).appendValue(i);
      }
      @Override
      public void describeMismatch(final Object item, final
Description description) {
         description.appendText(&quot;was&quot;).appendValue(((Foo) item).getNumber());
     }
   };
}
</pre>
<p>Now the result of the failing test tells us:</p>
<pre><strong>Expected: getNumber should return &lt;42&gt; but: was&lt;41&gt; </strong></pre>
<p>This will work great, but you will have to do casts all the time even hough you<br />
define the type of the object to test in the signature. To<br />
solve this you can use the TypsafeMatcher.</p>
<h3>TypesafeMatcher</h3>
<p>This matcher is almost identical to BaseMatcher. Almost <img src='http://www.planetgeek.ch/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  The<br />
differences are:</p>
<ul>
<li><strong><em>protected boolean matchesSafely(final T item)</em></strong></li>
<li><strong><em>protected void describeMismatchSafely(final T item, final</em></strong><br />
<strong><em>Description mismatchDescription)</em></strong></li>
</ul>
<p>Now the item already is of the known type and it is verified by<br />
TypesafeMatcher to be what it should be. If you use the assertThat<br />
method it would change nothing, since there are generics to define<br />
what you can match and what not but the casts are no longer necessary.<br />
Our sample matcher will change into something like this:</p>
<pre class="brush: java; title: ; notranslate">
private Matcher&lt;Foo&gt; hasNumber(final int i) {
   return new TypeSafeMatcher&lt;Foo&gt;() {
      @Override
      public void describeTo(final Description description) {
         description.appendText(&quot;getNumber should return &quot;).appendValue(i);
      }

      @Override
      protected void describeMismatchSafely(final Foo item, final
Description mismatchDescription) {
         mismatchDescription.appendText(&quot; was &quot;).appendValue(item.getNumber());
      }

      @Override
      protected boolean matchesSafely(final Foo item) {
         return i == item.getNumber();
      }
   };
}
</pre>
<p>If you let the test run you will see the same result as with the<br />
matcher extended from BaseMatcher. But we don’t have to cast the<br />
object all the time. Now you’ll ask what will the<br />
TypesafeDiagnosingMatcher bring more. Let’s have a look.</p>
<h3>TypesafeDiagnosingMatcher</h3>
<p>With the TypesafeDiagnosingMatcher you only have to implement two<br />
methods. These are:</p>
<ul>
<li><strong><em>public void describeTo(final Description description)</em></strong> : This<br />
has still the same function: Describe what the matcher is doing</li>
<li><strong><em>protected boolean matchesSafely(final T item, final Description</em></strong><br />
<strong><em>mismatchDescription)</em></strong> : Here we do the check <strong>AND</strong> the<br />
error description.</li>
</ul>
<p>So we change the creation of our matcher to the following:</p>
<pre class="brush: java; title: ; notranslate">
private Matcher&lt;Foo&gt; hasNumber(final int i) {
   return new TypeSafeDiagnosingMatcher&lt;Foo&gt;() {
      @Override
      public void describeTo(final Description description) {
         description.appendText(&quot;getNumber should return &quot;).appendValue(i);
      }

      @Override
      protected boolean matchesSafely(final Foo item, final
Description mismatchDescription) {
         mismatchDescription.appendText(&quot; was &quot;).appendValue(item.getNumber());
         return i == item.getNumber();
      }
   };
}
</pre>
<p>There is one point you have to keep in mind. If the match fails, the method<br />
matchesSafely will be called at least twice. This is because the<br />
method will be called to do the match <strong>AND</strong> to write<br />
the failure message.</p>
<h3>FeatureMatcher</h3>
<p>There is one abstract matcher which will be very easy to use for our<br />
problem. When implementing FeatureMatcher we just have to implement<br />
“<strong><em>protected abstract U featureValueOf(T actual);</em></strong>” (T will be our item<br />
and U the type that has to be checked) and all the rest will be done<br />
by FeatureMatcher. No more failuretext no more description. Nice,<br />
isn’t it?<br />
Here how our matcher looks like after implementing it with FeatureMatcher:</p>
<pre class="brush: java; title: ; notranslate">
private Matcher&lt;Foo&gt; hasNumberFeatureMatcher(final Integer i) {
   return new FeatureMatcher&lt;Foo, Integer&gt;(equalTo(i), &quot;number&quot;, &quot;number&quot;) {
      @Override
      protected Integer featureValueOf(final Foo actual) {
         return actual.getNumber();
      }
   };
}
</pre>
<p>After executing we will have this StackTrace:</p>
<pre><strong>java.lang.AssertionError: Expected: number &lt;42&gt; but: number was &lt;41&gt; </strong></pre>
<p>As you see, we have to change something. The FeatureMatcher is<br />
designed to return a value (feature) of an object. Because of this we<br />
have something special in the constructor. Have you seen it? Yes,<br />
the equalTo matcher. This is because the feature matcher is<br />
designed to take an other matcher. So it would also be possible to<br />
compare with lessThan/greaterThan etc. Nice isn’t it?</p>
<h2>Combining two matchers</h2>
<p>Now let&#8217;s do the rest. Our goal was to compare two getters. To do this<br />
the CombinableMatcher will be helpful. Just have a look at Matchers<br />
and you will find the following way to combine two matchers:<br />
“<em><strong>Matchers.both(MatcherA).and(MatcherB)</strong></em>”. In my opinion this is a very<br />
readable way to combine two matchers. But there is one problem with<br />
it: The message will not be as good as it should. If we let this run</p>
<pre class="brush: java; title: ; notranslate">
assertThat(testee, both(hasName(&quot;Foo&quot;)).and(hasNumber(42)));
</pre>
<p>we will se something like this:</p>
<pre><strong>java.lang.AssertionError: Expected: (getName should return "Foo" and getNumber should return &lt;42&gt;) but: was &lt;ch.adrianelsener.Foo@2484e723&gt; </strong></pre>
<p>if we do not implement toString on our result we can’t really get<br />
enough information to get a conclusion what happend. Here I would do a<br />
little manual work.</p>
<pre class="brush: java; title: ; notranslate">
class MyCombinableMatcher&lt;T&gt; extends BaseMatcher&lt;T&gt; {
   private final List&lt;Matcher&lt;? super T&gt; matchers = new ArrayList&lt;&gt;();
   private final List&lt;Matcher&lt;? super T&gt; failed = new ArrayList&lt;&gt;();

   private MyCombinableMatcher(final Matcher matcher) {
      matchers.add(matcher);
   }

   public MyCombinableMatcher and(final Matcher matcher) {
      matchers.add(matcher);
      return this;
   }

   @Override
   public boolean matches(final Object item) {
      for (final Matcher&lt;? super T&gt; matcher : matchers) {
         if (!matcher.matches(item)) {
            failed.add(matcher);
            return false;
         }
      }
      return true;
   }

   @Override
   public void describeTo(final Description description) {
      description.appendList(&quot;(&quot;, &quot; &quot; + &quot;and&quot; + &quot; &quot;, &quot;)&quot;, matchers);
   }

   @Override
   public void describeMismatch(final Object item, final Description
description) {
      for (final Matcher&lt;? super T&gt; matcher : failed) {
         description.appendDescriptionOf(matcher).appendText(&quot; but &quot;);
         matcher.describeMismatch(item, description);
      }
   }

   public static &lt;LHS&gt; MyCombinableMatcher&lt;LHS&gt; all(final Matcher&lt;? super LHS&gt; matcher) {
      return new MyCombinableMatcher&lt;LHS&gt;(matcher);
   }
}
</pre>
<p>If we now execute this line:</p>
<pre class="brush: java; title: ; notranslate">
assertThat(testee, all(hasNameTypesafeMatcher(&quot;Bar&quot;)).and(hasNumber(42)));
</pre>
<pre><strong>java.lang.AssertionError: Expected: (getName should return "Foo" and getNumber should return &lt;42&gt;) but: getName should return "Foo" but was "Bar" getNumber should return &lt;42&gt; but was &lt;41&gt; </strong>
</pre>
<h2>assertThat or assertThat ?</h2>
<p>If you see just something like this</p>
<pre><strong>java.lang.AssertionError: Expected: (getName should return "Foo" and getNumber should return &lt;42&gt;) got: &lt;ch.adrianelsener.Foo@21a79b48&gt; </strong></pre>
<p>Then it might be because you have used the assertThat from JUnit and not the one<br />
from hamcrest. This is because JUnit delivers an assertThat to get<br />
small support for hamcrest. But it does not use all of the &#8220;new&#8221; features<br />
of hamcrest. They deliver an old implementation. All you have to<br />
do is use MatcherAssert.assertThat within the hamcrest library. It<br />
would be better to get the JUnit jar without hamcrest and replace it<br />
completely by the hamcrest jar itself.</p>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/03/07/create-your-own-matcher/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unleash your code with PostSharp</title>
		<link>http://www.planetgeek.ch/2012/02/24/unleash-your-code-with-postsharp/</link>
		<comments>http://www.planetgeek.ch/2012/02/24/unleash-your-code-with-postsharp/#comments</comments>
		<pubDate>Fri, 24 Feb 2012 11:49:39 +0000</pubDate>
		<dc:creator>Daniel Marbach</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[PostSharp]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3157</guid>
		<description><![CDATA[Currently, I have some spare time and wanted to play around with geeky stuff. The guys from sharpcrafters.com provided me a evaluation version of their tool PostSharp. PostSharp is a framework for aspect oriented programming in .NET. In short, aspect oriented programming helps you to remove unnecessary boiler plate code such as logging, transaction handling, [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/02/24/unleash-your-code-with-postsharp/";
		var dzone_title = "Unleash your code with PostSharp";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>Currently, I have some spare time and wanted to play around with geeky stuff. The guys from <a href="http://www.sharpcrafters.com/" target="_blank">sharpcrafters.com</a> provided me a evaluation version of their tool PostSharp. PostSharp is a framework for aspect oriented programming in .NET. In short, aspect oriented programming helps you to remove unnecessary boiler plate code such as logging, transaction handling, exception handling and many more. The boiler plate code I&#8217;m talking about is also called cross-cutting concern because it cuts through your whole application. If you want to know more about aspect oriented programming I suggest you follow the links provided in this article. But now let&#8217;s dive into PostSharp.</p>
<p><span id="more-3157"></span></p>
<p>PostSharp comes with a simple installer which installs PostSharp HQ on your machine. Everything is then setup to start using PostSharp. PostSharp HQ is essentially nothing more than a simple browser window which provides you information about your license status and links to documentation and tutorials. When you start VS2010 the first time after the PostSharp installation, a new information area is placed beside your toolbox. The information area provides you with a check list and tutorials which allow you to dive into the features and possibilities of PostSharp.</p>
<table border="0">
<tbody>
<tr>
<td><a href="http://www.planetgeek.ch/wp-content/uploads/2012/02/PostSharpHq.jpg"  rel="lightbox[roadtrip]"><img title="PostSharpHq" src="http://www.planetgeek.ch/wp-content/uploads/2012/02/PostSharpHq-150x150.jpg" alt="" width="150" height="150" /></a></td>
<td><a href="http://www.planetgeek.ch/wp-content/uploads/2012/02/Vs2010Tutorial.jpg"  rel="lightbox[roadtrip]"><img title="Vs2010Tutorial" src="http://www.planetgeek.ch/wp-content/uploads/2012/02/Vs2010Tutorial-150x150.jpg" alt="" width="150" height="150" /></a></td>
</tr>
</tbody>
</table>
<p>The basics of PostSharp are really simple. I&#8217;m not going to cover the stuff of PostSharp which is already in the tutorials but I&#8217;ll provide a detailed list of tutorials at the end of this post.</p>
<p>PostSharp itself is really user friendly. They are trying to provide a maximum amount of information possible at compile time. For example if you forget to mark your aspects as serializable you receive a compile error which points you to the cause of the problem. It is even possible to extend this message based information system with your own compile errors or warnings (look for <em>MessageSource</em> and <em>Message.Write</em> in the documentation).</p>
<p><a href="http://www.planetgeek.ch/wp-content/uploads/2012/02/CompileErrorsPostSharp.jpg"  rel="lightbox[roadtrip]"><img class="alignnone size-medium wp-image-3167" title="CompileErrorsPostSharp" src="http://www.planetgeek.ch/wp-content/uploads/2012/02/CompileErrorsPostSharp-300x89.jpg" alt="" width="300" height="89" /></a></p>
<p>Another powerful feature is the provided Visual Studio plugin. The plugin visualizes aspects and code which is influenced by aspects. On every recompile new information is available. For example the aspect browser shows aspects which are part of the solution and the affected code for each aspect (first screenshot). The code editor integration of the plugin shows nicely all aspects directly in the editor window. It is even possible to directly jump to the disassembled code with your favorite disassembler (for example ILSpy, DotPeek&#8230;).</p>
<table style="width: 400px;" border="0">
<tbody>
<tr>
<td><a href="http://www.planetgeek.ch/wp-content/uploads/2012/02/AspectBrowser.jpg"  rel="lightbox[roadtrip]"><img class="alignnone size-thumbnail wp-image-3174" title="AspectBrowser" src="http://www.planetgeek.ch/wp-content/uploads/2012/02/AspectBrowser-150x150.jpg" alt="" width="150" height="150" /></a></td>
<td><a href="http://www.planetgeek.ch/wp-content/uploads/2012/02/AffectedCode.jpg"  rel="lightbox[roadtrip]"><img class="alignnone size-thumbnail wp-image-3173" title="AffectedCode" src="http://www.planetgeek.ch/wp-content/uploads/2012/02/AffectedCode-150x150.jpg" alt="" width="150" height="150" /></a></td>
</tr>
</tbody>
</table>
<p>All the rest should be covered in detail in the tutorials below. Happy PostSharping!</p>
<p><strong>Hints from my side</strong></p>
<ul>
<li>If you are using ReSharper I suggest you add some templates to your solution settings which help you write aspects (for example the template should include the serializable attribute)</li>
<li>Always keep in mind that the application of attributes is undeterministic so there is no guarantee of execution order (PostSharp will also let you know that in the warnings)</li>
<li>The order of execution can influence the operational behavior of an aspect!</li>
<li>When possible try to avoid using the AttributePriority to modify the priority when aspects are applied. This can quickly become a huge mess.</li>
<li>Read the tutorials about aspect scoping multiple times</li>
<li>If you are using FxCop there is a section in the documentation about FxCop compatibility with PostSharp (haven&#8217;t tried it out yet)</li>
</ul>
<p><strong>Aspect Oriented Programming</strong></p>
<ul>
<li><a href="http://www.sharpcrafters.com/postsharp/white-paper">WhitePaper from SharpCrafters </a></li>
<li><a href="http://www.aosd.net/" target="_blank">Aspect-Oriented Software Development Community &amp; Conference</a></li>
<li><a href="http://eclipse.org/aspectj/docs.php" target="_blank">AspectJ Documentation</a></li>
<li><a href="http://c2.com/cgi/wiki?AspectOrientedProgramming" target="_blank">C2.com Wiki</a></li>
</ul>
<p><strong>PostSharp Tutorials</strong></p>
<ul>
<li><a href="http://www.sharpcrafters.com/postsharp/documentation#documentation" target="_blank">Documentation</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-1-e28093-OnExceptionAspect.aspx" rel="Bookmark">PostSharp Principles: Day 1 – OnExceptionAspect </a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-2-Applying-Aspects-with-Multicasting-Part-1.aspx" target="_blank">PostSharp Principles: Day 2 &#8211; Applying Aspects with Multicasting Part 1</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-3-Applying-Aspects-with-Multicasting-Part-2.aspx" target="_blank">PostSharp Principles: Day 3 &#8211; Applying Aspects with Multicasting Part 2 </a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-4-OnMethodBoundaryAspect.aspx" target="_blank">PostSharp Principles: Day 4 &#8211; OnMethodBoundaryAspect</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-5-Visual-Studio-Add-ins.aspx">PostSharp Principles: Day 5 – Visual Studio Add-ins</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-6-Your-code-after-PostSharp.aspx">PostSharp Principles: Day 6 Your code after PostSharp</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-7-Interception-Aspects-e28093-Part-1.aspx">PostSharp Principles: Day 7 Interception Aspects – Part 1</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-8-Interception-Aspects-e28093-Part-2.aspx">PostSharp Principles: Day 8 Interception Aspects – Part 2</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-9-Aspect-Lifetime-Scope-Part-1.aspx">PostSharp Principles: Day 9 Aspect Lifetime &amp; Scope Part 1</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/Day-10-Aspect-Lifetime-Scope-Part-2.aspx">PostSharp Principles: Day 10 Aspect Lifetime &amp; Scope Part 2 </a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-11-e28093-Interception-e28093-Part-3.aspx">PostSharp Principals: Day 11 – EventInterceptionAspect</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-12-e28093-Aspect-Providers-e28093-Part-1.aspx">PostSharp Principals: Day 12 – Aspect Providers, Part 1</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-13-e28093-Aspect-Providers-e28093-Part-2.aspx">PostSharp Principles: Day 13 – Aspect Providers, Part 2</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-14-e28093-Introducing-members-and-interfaces-Part-1.aspx">PostSharp Principals: Day 14 – Introducing Members and Interfaces, Part 1</a></li>
<li><a href="http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-15-e28093-Introducing-members-and-interfaces-Part-2.aspx">PostSharp Principles: Day 15 – Introducing Members and Interfaces, Part 2</a></li>
<li><a href="http://programmersunlimited.wordpress.com/2011/07/27/applying-aspects-to-3rd-party-assemblies-using-postsharp/" target="_blank">Applying aspects to 3rd party assemblies using PostSharp</a></li>
<li><a href="http://michaelfcollins3.me/2010/10/method-tracing-using-log4net-and-postsharp/" target="_blank">Method Tracing Using log4net and PostSharp (shows also Unit Testing)</a></li>
</ul>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/02/24/unleash-your-code-with-postsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.NET Provider dependency injection with Ninject 3.0.0</title>
		<link>http://www.planetgeek.ch/2012/02/08/asp-net-provider-injection-with-ninject-3-0-0/</link>
		<comments>http://www.planetgeek.ch/2012/02/08/asp-net-provider-injection-with-ninject-3-0-0/#comments</comments>
		<pubDate>Wed, 08 Feb 2012 22:25:27 +0000</pubDate>
		<dc:creator>Remo Gloor</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MembershipProvider]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[Open source]]></category>

		<guid isPermaLink="false">http://www.planetgeek.ch/?p=3138</guid>
		<description><![CDATA[Unfortunately, ASP.NET providers like the MembershipProvider and RolesProvider aren&#8217;t designed for dependency injection. Many users have problems to assign dependencies to them. In this blog post I&#8217;ll show a way to how this can be done using Ninject.Web.Common 3.0.0. This solution works for MVC and WebForms. The provider itself is created by the ASP.NET framework [...]]]></description>
			<content:encoded><![CDATA[<!--S-ButtonZ 1.1.5 Start--><div style="float: left; width: 42px; padding-right: 10px; margin: 0 10px 0 0;">
		<script type="text/javascript">
		<!--
		var dzone_url = "http://www.planetgeek.ch/2012/02/08/asp-net-provider-injection-with-ninject-3-0-0/";
		var dzone_title = "ASP.NET Provider dependency injection with Ninject 3.0.0";
		var dzone_style = "1";
		var dzone_blurb = "";
		//-->
		</script>
		<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script></div><!--S-ButtonZ 1.1.5 End--><p>Unfortunately, ASP.NET providers like the MembershipProvider and RolesProvider aren&#8217;t designed for dependency injection. Many users have problems to assign dependencies to them. In this blog post I&#8217;ll show a way to how this can be done using Ninject.Web.Common 3.0.0. This solution works for MVC and WebForms.<span id="more-3138"></span></p>
<p>The provider itself is created by the ASP.NET framework which adds the restriction that all dependencies have to be passed using property injection because the ASP.NET framework expects a parameter less constructor. So the first thing you have to do is to add a property for all required dependencies to your provider</p>
<pre class="brush: csharp; title: ; notranslate">
    public class MyMembershipProvider : SqlMembershipProvider
    {
        [Inject]
        public SpecialUserProvider SpecialUserProvider
        {
            get; set;
        }

        public override bool ValidateUser(string username, string password)
        {
            return this.SpecialUserProvider.IsSpecialUser(username) ||
                   base.ValidateUser(username, password);
        }
    }
</pre>
<p>As second step you need to create an HttpModule that will get an instance of all your providers. The idea behind this is that the providers are resolved and injected long time before they are used somewhere else. In the following example it is done for the MembershipProvider only. But you can easily extend it to initialize all required providers.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class ProviderInitializationHttpModule : IHttpModule
    {
        public ProviderInitializationHttpModule(MembershipProvider membershipProvider)
        {
        }

        public void Init(HttpApplication context)
        {
        }

        public void Dispose()
        {
        }
    }
</pre>
<p>As last step you need to create the bindings for the http module and the providers.</p>
<pre class="brush: csharp; title: ; notranslate">
    kernel.Bind&lt;MembershipProvider&gt;().ToMethod(ctx =&gt; Membership.Provider);
    kernel.Bind&lt;IHttpModule&gt;().To&lt;ProviderInitializationHttpModule&gt;();
</pre>
<div style="clear:both;">&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.planetgeek.ch/2012/02/08/asp-net-provider-injection-with-ninject-3-0-0/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Object Caching 1273/1470 objects using disk: basic

Served from: planetgeek.ch @ 2012-05-09 15:16:37 -->

