
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Alkampfer&#039;s Place</title>
	<atom:link href="http://www.codewrecks.com/blog/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codewrecks.com/blog</link>
	<description>Wrecks of code floating in the sea of Internet By Ricci Gian Maria</description>
	<lastBuildDate>Wed, 16 May 2012 20:46:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
		<item>
		<title>Troubleshoot WCF The underlying connection was closed: A connection that was expected to be kept alive was closed by the server</title>
		<link>http://www.codewrecks.com/blog/index.php/2012/05/16/troubleshoot-wcf-the-underlying-connection-was-closed-a-connection-that-was-expected-to-be-kept-alive-was-closed-by-the-server/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2012/05/16/troubleshoot-wcf-the-underlying-connection-was-closed-a-connection-that-was-expected-to-be-kept-alive-was-closed-by-the-server/#comments</comments>
		<pubDate>Wed, 16 May 2012 20:46:00 +0000</pubDate>
		<dc:creator>Ricci Gian Maria</dc:creator>
				<category><![CDATA[Nhibernate]]></category>
		<category><![CDATA[Wcf]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2012/05/16/troubleshoot-wcf-the-underlying-connection-was-closed-a-connection-that-was-expected-to-be-kept-alive-was-closed-by-the-server/</guid>
		<description><![CDATA[I’ve already blogged in the past on how to easily troubleshoot WCF Exception and that suggestion is valid for every exception you encounter in WCF. Today I have a function that gave the error System.ServiceModel.CommunicationException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. &#8212;&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve already blogged in the past on how to <a href="http://www.codewrecks.com/blog/index.php/2012/04/23/troubleshoot-wcf-exception/" target="_blank">easily troubleshoot WCF Exception</a> and that suggestion is valid for every exception you encounter in WCF. Today I have a function that gave the error</p>
<blockquote><p>System.ServiceModel.CommunicationException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. &#8212;&gt; System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. &#8212;&gt; System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. &#8212;&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host</p>
</blockquote>
<p>This problem is usually caused by some error in the communication channel, but even in such a situation, enabling the trace listener immediately gave to you an idea of the problem.</p>
<p>&#160;</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2012/05/SNAGHTML20daa9b1.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="SNAGHTML20daa9b" border="0" alt="SNAGHTML20daa9b" src="http://www.codewrecks.com/blog/wp-content/uploads/2012/05/SNAGHTML20daa9b_thumb.png" width="1039" height="318" /></a></p>
<p><strong>Figure 1: </strong><em>How to identify the problem thanks to WCF Trace Listener</em></p>
<p>In my situation the error is ClientProxy …. is not expected and this is due to the fact that I’m returning from WCF a couple of classes that are mapped with NHIbernate, the entity returned has a property of type Customer that is a lazy property, thus at runtime it is represented by a dynamic proxy that is not known to WCF. The solution is trivial, just issue a Fetch(obj =&gt; obj.Client) in the LINQ query to fetch Client and avoiding NH to create a proxy, but the key point is that with WCF trace listener, finding problems in WCF is matter of few seconds.</p>
<p>Gian MAria.</p>
<p><font style="background-color: #f0f0e0">&#160;</font></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2012/05/16/troubleshoot-wcf-the-underlying-connection-was-closed-a-connection-that-was-expected-to-be-kept-alive-was-closed-by-the-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Misusing an ORM</title>
		<link>http://www.codewrecks.com/blog/index.php/2012/05/12/misusing-an-orm/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2012/05/12/misusing-an-orm/#comments</comments>
		<pubDate>Sat, 12 May 2012 07:44:49 +0000</pubDate>
		<dc:creator>Ricci Gian Maria</dc:creator>
				<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[NoSql]]></category>
		<category><![CDATA[ORM]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2012/05/12/misusing-an-orm/</guid>
		<description><![CDATA[I’ve blogged some time ago that I’m starting to consider ORM an Antipattern, and recently Mr Fowler posted similar thoughts in his bliki, moreover I have the pleasure to be one of the organizer of the first RavenDB official Course in Italy, with my dear friend Mauro as teacher. Since I’m strongly convinced that in [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve blogged some time ago that I’m starting to <a href="http://www.codewrecks.com/blog/index.php/2011/10/27/square-peg-in-a-round-hole/" target="_blank">consider ORM an Antipattern</a>, and recently Mr Fowler <a href="http://martinfowler.com/bliki/OrmHate.html" target="_blank">posted similar thoughts</a> in his bliki, moreover I have the pleasure to be one of the organizer of the <a href="http://ravendb.net/events/82/3-days-ravendb-training-in-italy" target="_blank">first RavenDB official Course in Italy</a>, with my dear friend <a href="http://milestone.topics.it/" target="_blank">Mauro</a> as teacher. </p>
<p>Since I’m strongly convinced that in a full OOP approach to problem<strong> objects should not have nor setter nor getter</strong>, most of the work and complexities of an ORM is simply not needed, because you usually retrieve objects from the storage with only one function <strong>GetById</strong> and nothing else. In my long experience with NHibernate, I verified that most of the problem arise when you need to <strong>show data in UI in specific format and you start to write complex Query</strong> in HQL or ICRiteria or LINQ, then you need to spend time with NHProfiler to understand if the queries are good enough to run on production system and when objects changes a little bit <strong>you need to rewrite a lot of code to suite the new Object Model. </strong>This last point is the real pain point in DDD, where you usually should create Object Model that will be manipulated a lot before reaching a good point, after all the main value of DDD approach is being able to create a dialog with a DOMAIN EXPERT and it is impossible to find a good Object Models at the first tentative. If refactoring a model become painful, you are not allowed to modify it with easy, you are going away from DDD approach.</p>
<p>This is where <a href="http://codebetter.com/gregyoung/2010/02/13/cqrs-and-event-sourcing/" target="_blank">CQRS</a> can help you, for all objects belonging to the domain you need only to Save, LoadById, Update and delete, because every read model should be defined somewhere else. In such a scenario an ORM is really useful, because if you need to store objects inside Relational Database you can leave the ORM all the work to satisfy the CRUD part, where the R is the method GetById. <strong>To start easily with this approach you can create SQL View or stored procedures for all the Read Models</strong> you need; this imply that whenever the structure of the Domain Model changes, you need only to change all affected Read Models, some view and some stored procedure, but you have no need to refactor the code.</p>
<p>In this situation the ORM can really helps you, because if you change the Domain Model, you should only change the mapping, or let some Mapping by convention do this for you (<a href="http://fabiomaulo.blogspot.it/2010/02/conform-nhibernate-un-mapping.html" target="_blank">ConfORM</a> for NH is an example), regenerate the database and update only affected Read Models. If your domain is really anemic, if you expose properties from objects, even only with getters, whenever you change a domain class you should answer the question “If I change this property, what other domain objects will be affected? How many service class will be affected? How many query issued from Views will be affected?”. If you are not able to create a Read Model with SQL View or stored procedure, you can write a denormalizer that listens for DOMAIN EVENTS and populate the Read Model accordingly. In my opinion this is the scenario where an ORM can really helps you.</p>
<p>In such a situation a NoSql database can dramatically simplify your life, because you do not need an ORM anymore, cause you are able to save object graps into the storage directly, and you can create Read Models with Map/Reduce or with denormalizers.</p>
<p>But sadly enough, ORM are primarily used to avoid writing SQL and persist completely anemic domain, where all the logic reside on services. In such a scenario it is <strong>easy to abuse an ORM </strong>and probably in the long term the ORM could become much more a pain than a real help.</p>
<p>Gian Maria.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2012/05/12/misusing-an-orm/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Shim and InstanceBehavior fallthrough to isolate part of the SUT</title>
		<link>http://www.codewrecks.com/blog/index.php/2012/05/10/shim-and-instancebehavior-fallthrough-to-isolate-part-of-the-sut/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2012/05/10/shim-and-instancebehavior-fallthrough-to-isolate-part-of-the-sut/#comments</comments>
		<pubDate>Thu, 10 May 2012 17:11:26 +0000</pubDate>
		<dc:creator>Ricci Gian Maria</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[shim]]></category>
		<category><![CDATA[VS11]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2012/05/10/shim-and-instancebehavior-fallthrough-to-isolate-part-of-the-sut/</guid>
		<description><![CDATA[I’ve dealt in a previous post with the new Shim library in Vs11 that permits you to test “difficult to test code” and I showed a really simple example on how to use Shim to isolate the call to DateTime.Now to simulate passing time in a Unit Test. Now I want to change a little [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve dealt in a previous post with the new <a href="http://www.codewrecks.com/blog/index.php/2012/04/27/using-shims-in-visual-studio-11-to-test-untestable-code/" target="_blank">Shim library in Vs11</a> that permits you to test “difficult to test code” and <strong>I showed a really simple example on how to use Shim to isolate the call to DateTime.Now</strong> to simulate passing time in a Unit Test. Now I want to change a little bit the perspective of the test, in the test showed in previous post I simply exercise the sut calling Execute() a couple of time, simulating the time that pass between the two calls. Here is the test</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a8138ad7-d6ee-42c8-98e9-8d92e9a19f2c" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
[Fact]
public void Verify_do_not_execute_task_if_interval_is_not_elapsed()
{
    using (ShimsContext.Create())
    {
        Int32 callCount = 0;
        PerformHeavyTask sut = new PerformHeavyTask(10, () =&gt; callCount++);
        DateTime startDate = new DateTime(2012, 1, 1, 12, 00, 00);
        ShimDateTime.NowGet = () =&gt;  startDate;
        sut.Execute();
        ShimDateTime.NowGet = () =&gt; startDate.AddMinutes(9);
        sut.Execute();
        Assert.Equal(1, callCount);
    }
}
</pre>
</pre>
</div>
<p>I can also change the point of view and<strong> write a test that uses a shim to isolate the SUT</strong>, this is a less common scenario but it can be also really interesting, because it shows you how you can write simple White box Unit Tests isolating part of the <a href="http://xunitpatterns.com/SUT.html" target="_blank">SUT</a>. The term <strong>White Box is used because this kind of Unit Test are created with a full knowledge of the internal structure of the <a href="http://xunitpatterns.com/SUT.html" target="_blank">SUT</a></strong>, in my situation I have a private method called CanExecute() that return true/false based on the interval of time passed from the last execution and since it is private it makes difficult for me to test the <a href="http://xunitpatterns.com/SUT.html" target="_blank">SUT</a>.</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:8b25e446-2fcb-4fd3-878a-ec36d2559adb" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
private Boolean CanExecute() {

    return DateTime.Now.Subtract(lastExecutionTime)
        .TotalMinutes &gt;= intervalInMinutes;
}
</pre>
</pre>
</div>
<p>But I can create a Shime on the SUT and isolate calls to the CanExecute(), making it return the value I need for the test, here is an example</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:b8f4c9f6-f11d-419a-a39e-55308e02a5ec" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
[Fact]
public void Verify_can_execute_is_honored()
{
    using (ShimsContext.Create())
    {
        Int32 callCount = 0;
        PerformHeavyTask sut = new PerformHeavyTask(10, () =&gt; callCount++);
        ShimPerformHeavyTask shimSut = new ShimPerformHeavyTask(sut);
        shimSut.InstanceBehavior = ShimBehaviors.Fallthrough;
        shimSut.CanExecute = () =&gt; false;
        sut.Execute();
        Assert.Equal(0, callCount);
    }
}
</pre>
</pre>
</div>
<p>To write this test I’ve added another fake assembly on the assembly that contains the PerformHeavyTask class to create shim for the SUT. This test basically create a <strong>ShimPerformHeavyTask</strong> (a shim of my SUT) passing an existing instance to the SUT to the constructor of the shim, then I set the InstanceBehavior to <strong><em>ShimBehaviors.Fallthrough</em></strong> to indicate to the Shim Library to call original <a href="http://xunitpatterns.com/SUT.html" target="_blank">SUT</a> method if the method was not isolated. At this point I can simply <strong>isolate the call to the CanExecute() private and non-virtual method</strong>, specifying to the shim to return the value false, then I call the Execute() method and verify that the heavy task is not executed. </p>
<p><strong>This test shows how to create a shim of the SUT to isolate calls to its private methods, thanks to the Fallthrough behavior</strong>; if you forget to change the InstanceBehavior the test will fail with an exception of type <em>ShimNotImplementedException</em>, because the default behavior for a Shim is to throw an exception for any method that is not intercepted. Thanks to shim library you can simply isolate every part of the SUT, making easier to write Unit Test for classes written with no TDD and no Unit Testing in mind.</p>
<p>Gian Maria.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2012/05/10/shim-and-instancebehavior-fallthrough-to-isolate-part-of-the-sut/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting the list of Type associated to a given export in MEF</title>
		<link>http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/#comments</comments>
		<pubDate>Tue, 08 May 2012 17:36:19 +0000</pubDate>
		<dc:creator>Ricci Gian Maria</dc:creator>
				<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Wcf]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/</guid>
		<description><![CDATA[Basic Request Response WCF service Reason behind a request – response service in WCF Evolving Request Response service to separate contract and business logic How to instantiate WCF host class with MEF One of the problem I had to solve to make WCF and MEF live together,&#160; is knowing all the types discovered by MEF [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/03/12/basic-request-response-wcf-service/">Basic Request Response WCF service </a></li>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/04/05/reson-behind-request-responseservice-in-wc/">Reason behind a request – response service in WCF </a></li>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/04/23/evolving-request-response-service-to-separate-contract-and-business-logic/">Evolving Request Response service to separate contract and business logic </a></li>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/05/08/how-to-instantiate-wcf-host-class-with-mef/">How to instantiate WCF host class with MEF </a></li>
</ul>
<p>One of the problem I had to solve to make WCF and MEF live together,&#160; is knowing all the types discovered by MEF at runtime for a given export. This information is really important because <strong>I need the list of type that derived from Request and Response to inform WCF of all the KnownTypes available to the service.</strong>&#160; First of all let’s see how I initialized MEF engine</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:2d03cb47-d231-43f4-8158-7e5e0af6c185" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
private static CompositionContainer theContainer;
private static DirectoryCatalog catalog;

static MefHelper()
{
    catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
    theContainer = new CompositionContainer(catalog);
}
</pre>
</pre>
</div>
<p>The catalog is instructed to load everything that is located in the current directory, a configuration that is suitable for my simple WCF Request / Response service; then I need to change the DynamicKnownType class to get the list of exported types loaded by MEF.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:d8fed1de-2cde-4cd8-baed-1af024fb2d92" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
class DynamicKnownType
{
    static List&lt;Type&gt; knownTypes;

    static DynamicKnownType()
    {
        knownTypes = new List&lt;Type&gt;();
        knownTypes.AddRange(MefHelper.GetExportedTypes&lt;Request&gt;());
        knownTypes.AddRange(MefHelper.GetExportedTypes&lt;Response&gt;());
    }
</pre>
</pre>
</div>
<p>The GetExportedType() method is a little tricky, because MEF does not offer such a functionality out of the box, so <strong>I need to search inside information available from the catalog to identify all loaded types related to a specific Export</strong>. The code is quite simple and it is composed only by few lines.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:6bfa863e-40f2-42fb-8723-4a315c73ef50" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
public static IEnumerable&lt;Type&gt; GetExportedTypes&lt;T&gt;()
{
    return catalog.Parts
        .Select(part =&gt; ComposablePartExportType&lt;T&gt;(part))
        .Where(t =&gt; t != null);
}

private static Type ComposablePartExportType&lt;T&gt;(ComposablePartDefinition part)
{

    if (part.ExportDefinitions.Any(
        def =&gt; def.Metadata.ContainsKey(&quot;ExportTypeIdentity&quot;) &amp;&amp;
            def.Metadata[&quot;ExportTypeIdentity&quot;].Equals(typeof(T).FullName)))
    {
        return ReflectionModelServices.GetPartType(part).Value;
    }
    return null;
}
</pre>
</pre>
</div>
<p>You can find all type related to an export because MEF Catalog contains a property named <strong>Parts</strong> that is an IEnumerable of ComposablePartDefinition, where<strong> each instance contains full details on a type discovered by MEF. </strong>For each ComposablePartDefinition I can cycle inside all ExportDefinitions list to find if one ExportDefinition is related to the type I’m looking for. This specific information is not exposed directly, but it <strong>is contained in the Metadata associated to the ExportDefinition in a key called “ExportTypeIdentity” that contains the FullName of exported Type</strong>. </p>
<p>If one of the ExportDefinition exports the type I’m searching for <strong>I can finally use the ReflectionModelService.GetPartType() static method to find the type of dynamically imported class</strong>. This simple method make possible to discover the list of all concrete classes loaded by MEF that inherit from Request or Response to create the list of KnownTypes for WCF.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2012/05/08-05-2012-19-26-211.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="08-05-2012 19-26-21" border="0" alt="08-05-2012 19-26-21" src="http://www.codewrecks.com/blog/wp-content/uploads/2012/05/08-05-2012-19-26-21_thumb.png" width="681" height="221" /></a></p>
<p><strong>Figure 1: </strong><em>From the Wcf Test Client you can choose between all the requests that were dynamically loaded by MEF</em></p>
<p>Example <a href="http://www.codewrecks.com/Files/requestresponsemef.zip"><strong>can be downloaded here</strong></a><strong>.</strong></p>
<p>Gian Maria.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to instantiate WCF host class with MEF</title>
		<link>http://www.codewrecks.com/blog/index.php/2012/05/08/how-to-instantiate-wcf-host-class-with-mef/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2012/05/08/how-to-instantiate-wcf-host-class-with-mef/#comments</comments>
		<pubDate>Tue, 08 May 2012 17:08:18 +0000</pubDate>
		<dc:creator>Ricci Gian Maria</dc:creator>
				<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Wcf]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2012/05/08/how-to-instantiate-wcf-host-class-with-mef/</guid>
		<description><![CDATA[Basic Request Response WCF service Reason behind a request – response service in WCF Evolving Request Response service to separate contract and business logic I described in the last post of the series the structure behind the Request/Reponse service based on MEF, now it is time to explain how to make MEF and WCF happily [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/03/12/basic-request-response-wcf-service/">Basic Request Response WCF service </a></li>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/04/05/reson-behind-request-responseservice-in-wc/">Reason behind a request – response service in WCF </a></li>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/04/23/evolving-request-response-service-to-separate-contract-and-business-logic/">Evolving Request Response service to separate contract and business logic </a></li>
</ul>
<p>I described in the last post of the series the structure behind the Request/Reponse service based on MEF, now it is time to explain how to make MEF and WCF happily live together. In the first version I hosted the service with these simple lines of code</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:577b679f-b3be-4fd2-b39d-751177fa0f9f" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
using (ServiceHost host = new ServiceHost(typeof(CoreService)))
{
    host.Open();
</pre>
</pre>
</div>
<p>Basically all I needed to do is to create a ServiceHost specifying in the constructor the type of the class that implements the service and let WCF to take care of every details about the creation of the concrete instances that will answer to the requests.</p>
<p> In this new version of the service <strong>the CoreService class cannot be anymore created with default constructor, because I need to construct the instance with MEF</strong>; so I need to instruct WCF to create the CoreService class with MEF.</p>
<p>What I need is concrete implementation of the<strong> </strong><a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank"><strong>IInstanceProvider</strong></a><strong>, an interface used by WCF to manage the creation of concrete classes that implements my service</strong>.</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:51733b3c-958a-498a-963c-6ccc32b3527d" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
class CoreServiceInstanceProvider : IInstanceProvider
{
    public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
    {
        return MefHelper.Create&lt;ICoreService&gt;();
    }

    public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
    {
        return GetInstance(instanceContext, null);
    }

    public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
    {

    }
}
</pre>
</pre>
</div>
<p>My implementation is super simple, I only need to use the <strong>MefHelper.Create() method to let MEF create the class</strong> and compose everything, but I need another couple of classes to instruct WCF to use my CoreServiceInstanceProvider to instantiate classes for my service. First class is a Service Behavior, represented by a class that <strong>implements </strong><a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank"><strong>IServiceBehavior</strong></a><strong> to make WCF use my CoreInstanceProvider</strong>, then I create another class that<strong> inherits from ServiceHost to automatically add this behavior to the WCF host</strong>.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:41b989fa-edef-46ee-b749-b75b707b06d8" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
public class CoreServiceBehavior : IServiceBehavior
{
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher cd = cdb as ChannelDispatcher;
            if (cd != null)
            {
                foreach (EndpointDispatcher ed in cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider = new CoreServiceInstanceProvider();
                }
            }
        }
    }

    public void AddBindingParameters(ServiceDescription
        serviceDescription,
        ServiceHostBase serviceHostBase,
        Collection&lt;ServiceEndpoint&gt; endpoints,
        BindingParameterCollection bindingParameters)
    {
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

public class CoreServiceHost : ServiceHost {

    public CoreServiceHost() : base(typeof(CoreService))
    {

    }

    protected override void OnOpening()
    {
        Description.Behaviors.Add(new CoreServiceBehavior());
        base.OnOpening();
    }
}
</pre>
</pre>
</div>
<p> With these helper classes, hosting the service in a simple console application is a breeze.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:86f60a4e-e5f3-4d4b-b624-a69fa75a71dd" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
using (ServiceHost host = new CoreServiceHost())
{
    host.Open();
</pre>
</pre>
</div>
<p>Et voilà, two lines of code and I’m able to start the service where every instance of the service is created by MEF.</p>
<p>Gian Maria.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2012/05/08/how-to-instantiate-wcf-host-class-with-mef/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Traffic light vNext</title>
		<link>http://www.codewrecks.com/blog/index.php/2012/05/07/traffic-light-vnext/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2012/05/07/traffic-light-vnext/#comments</comments>
		<pubDate>Mon, 07 May 2012 16:45:03 +0000</pubDate>
		<dc:creator>Ricci Gian Maria</dc:creator>
				<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[DDD]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/?p=3201</guid>
		<description><![CDATA[TrafficLight Experiment. Advantage of DDD approach to the problem Traffic Light, say goodbye to public properties It is a long time I did not post about simple Traffic Light experiment. I’ve ended with a super simple Domain with no Getters and no Setters, but there is still something I really do not like about that [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li><a href="http://www.codewrecks.com/blog/index.php/2011/11/07/traffic-light-experiment/">TrafficLight Experiment.</a> </li>
<li><a href="http://www.codewrecks.com/blog/index.php/2011/11/08/advantage-of-ddd-approach-to-problem/">Advantage of DDD approach to the problem</a> </li>
<li><a href="http://www.codewrecks.com/blog/index.php/2012/01/30/traffic-light-say-goodbye-to-public-properties/">Traffic Light, say goodbye to public properties</a> </li>
</ul>
<p>It is a long time I did not post about simple <strong>Traffic Light experiment</strong>. I’ve ended with a super simple Domain with no Getters and no Setters, but there is still something I really do not like about that sample and it is represented by this test.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:75ee6e63-27be-4842-b12f-93b88b16e01b" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
[Fact]
public void When_both_semaphore_are_red_one_become_green()
{

    //move all to yellow fixed
    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(1)))
    {
        sut.Tick();
    }
    _domainEvents.Clear();
    //now move again to both red
    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(10)))
    {
        sut.Tick();
    }
    _domainEvents.Should().Have.Count.EqualTo(2);
    _domainEvents.All(e =&gt; e.NewStatus == LightColor.Red).Should().Be.True();
    _domainEvents.Clear();
    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(1)))
    {
        sut.Tick();
    }
    //only one semaphore should be go to green state
    _domainEvents.Should().Have.Count.EqualTo(1);
    _domainEvents[0].NewStatus.Should().Be.EqualTo(LightColor.Green);
}
</pre>
</pre>
</div>
<p>This test is quite ugly and it requires some initialization code, contained in the constructor of the test class.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:db8e1cd0-4a97-4f51-9abd-1eaacce9ba8e" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
public TwoTrafficLightFixture()
{
    DomainEvents.ClearAllRegistration();
    CommunicationBus.ClearAllRegistration();

    DomainEvents.Register&lt;ChangedLightStatus&gt;(this, e =&gt; _domainEvents.Add(e));
    sut = CrossRoadFactory.For(2.Roads()).Create();
    sut.Start();
}
</pre>
</pre>
</div>
<p>The bad part about this code is that I want to test this situation: <em>when both traffic light are in red state, only one of them can become green after a given amount of time passed</em>. The awful part about this test is how I setup the fixture; to bring both the Traffic Light in the Red state, I need to create the CrossRoadFactory in the constructor of the test (this is because all tests share this common initialization), then I need to call Tick() several time simulating passing time and moving the system from the initial status to the status that represents the fixture (both light red). </p>
<p>This test is simply wrong, because if if fails you cannot tell if the failure is caused by the initialization code or the real part of the domain logic you want to test, because <strong>I’m actually exercising the SUT until it reach the status I want to test with my unit test</strong> and this can cause a failure in the Fixture. This is done because if the Traffic Light has no public properties and it is not possible to manipulate the status directly in the test. </p>
<p>To simplify the test I need a way to change the status of a Traffic Light, so I can simply fixture creation and the obvious solution is to use <a href="http://codebetter.com/gregyoung/2010/02/20/why-use-event-sourcing/" target="_blank">Event Sourcing</a>. I do not want to evolve the Traffic Light to a full Event Sourcing enabled domain, but I wish to verify if <strong>having the ability to reconstruct the state of a Domain Object from domain events he raised in the past can solve my test smell</strong>. I decided to add a constructor on the TrafficLight domain class that permits to create an instance from a sequence of Domain Events.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:af00b266-d00c-4a7a-a954-409fd8d0fefa" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
public TrafficLight(params BaseEvent[] eventStream)
{
    ActualState = YellowBlinkingState.Instance();
    CommunicationBus.Register&lt;MayITurnGreen&gt;(this, MayITurnGreen);
    Load(eventStream);
}

public void Load(params BaseEvent[] eventStream)
{
    foreach (var eventInstance in eventStream)
    {
        HandleChangedLightStatus(eventInstance as ChangedLightStatus);
    }
}
</pre>
</pre>
</div>
<p>This is really primitive, it is really far from being a real entity based on Event Sourcing, but the key concept is, <strong>I want to be able to reconstruct the private state of an entity simply passing a series of domain events that he raised in the past. </strong>Now the previous test can be modified to make it really simpler:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:a8b8bf13-0dd8-464e-a7eb-dc22505630f0" class="wlWriterEditableSmartContent">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
[Fact]
public void When_both_semaphore_are_red_one_become_green()
{

    TrafficLight first = new TrafficLight(new ChangedLightStatus(LightColor.Red, null));
    TrafficLight second = new TrafficLight(new ChangedLightStatus(LightColor.Red, null));
    CrossRoad theSut = new CrossRoad(
        new TrafficLightCreated(first),
        new TrafficLightCreated(second));

    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(1)))
    {
        theSut.Tick();
    }

    //only one semaphore should be go to green state
    _domainEvents.Should().Have.Count.EqualTo(1);
    _domainEvents[0].NewStatus.Should().Be.EqualTo(LightColor.Green);
}
</pre>
</pre>
</div>
<p>Now I’m able to create two traffic light passing a ChangedLightStatus event that bring the Traffic Light to the status requested by the fixture, then I can create the CrossRoad class passing two TrafficLightCreated domain events and this is all the code I need to setup the fixture of my test. Now I can simulate that one second is passed, call Tick() function on the CrossRoad and <strong>verify that only one Domain Event is raised</strong>, <strong>because only one Traffic Light Should have changed the value of the light from Red to Green</strong>.</p>
<p>Even with this super simple example you can understand that <strong>Event Sourcing simplify your tests</strong>, because they give you the ability to recreate a specific state of the domain under test from a stream of Domain Events.</p>
<p>Gian Maria.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2012/05/07/traffic-light-vnext/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Team foundation service new login page and more</title>
		<link>http://www.codewrecks.com/blog/index.php/2012/04/30/team-foundation-service-new-login-page-and-more/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2012/04/30/team-foundation-service-new-login-page-and-more/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 12:20:55 +0000</pubDate>
		<dc:creator>Ricci Gian Maria</dc:creator>
				<category><![CDATA[Team Foundation Server]]></category>
		<category><![CDATA[TfsService]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2012/04/30/team-foundation-service-new-login-page-and-more/</guid>
		<description><![CDATA[If you are using the TfsPreview (Tfs on azure), you can notice that the login page is drastically changed. Even if this seems only a simple and stupid change, it shows one of the advantage of using TfsService over having it on-premise: the automatic update process made periodically by Microsoft. The change in the login [...]]]></description>
			<content:encoded><![CDATA[<p>If you are using the TfsPreview (Tfs on azure), you can notice that the login page is drastically changed.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2012/04/image5.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2012/04/image_thumb4.png" width="478" height="229" /></a></p>
<p>Even if this seems only a simple and stupid change, it shows one of the advantage of using TfsService over having it on-premise: the automatic update process made periodically by Microsoft. The change in the login page is only a fancy change of an update that was deployed last week on TFS Service, this actually means two distinct advantage:</p>
<ol>
<li>Upgrade to new TFS version is automatic and painless (update of on-premise is now really simple, but still requires some work)</li>
<li>TFS Service will have a more frequent upgrade, you can have bugfix and new feature without the need to wait for Service Pack or for next major version</li>
</ol>
<p>For Small teams, avoiding any risk and time needed to update On-Premise TFS can be a good advantage over an on-premise installation.</p>
<p>Gian Maria</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2012/04/30/team-foundation-service-new-login-page-and-more/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: basic (Requested URI is rejected)
Object Caching 441/499 objects using disk: basic

Served from: www.codewrecks.com @ 2012-05-18 10:01:15 -->
