<?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>NullReference</title>
	<atom:link href="http://www.nullreference.se/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.nullreference.se</link>
	<description>Object reference not set to an instance of an object...</description>
	<lastBuildDate>Tue, 11 Oct 2011 07:34:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>SOA och molntjänster</title>
		<link>http://www.nullreference.se/2011/10/11/soa-och-molntjanster/</link>
		<comments>http://www.nullreference.se/2011/10/11/soa-och-molntjanster/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 07:29:01 +0000</pubDate>
		<dc:creator>peter</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[Cloud Computing]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Windows Azure]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/?p=217</guid>
		<description><![CDATA[Två hypade teknologier, SOA och molntjänster (på engelska Cloud Computing) . SOA har många förklarad som dött. Delvis fel enligt mig. Sedan finns det de som fyllt begreppet med så många associationer att man tycker begreppet i sig är dött. SOA har inget buzz längre, men innehåller viktiga principer för att kunna bygga hållbara distribuerade [...]]]></description>
			<content:encoded><![CDATA[<p>Två hypade teknologier, SOA och molntjänster (på engelska <em>Cloud Computing</em>) . SOA har många förklarad som <a href="http://www.infoq.com/news/2009/01/is-soa-dead">dött</a>. Delvis fel enligt mig. Sedan finns det de som fyllt begreppet med så många associationer att man tycker begreppet i sig är dött. SOA har inget buzz längre, men innehåller viktiga principer för att kunna bygga hållbara distribuerade system. Molntjänster, å andra sidan, är på toppen av sin hype, och där väntar vi fortfarande på en <a href="http://www.referenceforbusiness.com/management/Or-Pr/Product-Life-Cycle-and-Industry-Life-Cycle.html">accepterande majoritet</a>.</p>
<p>För att lyckas i sin molnsatsning är SOA en nödvändig pusselbit. Jag ska förklara min syn på detta.</p>
<h3>Vadå SOA?</h3>
<p>SOA handlar om att skapa tydligare koppling mellan verksamhet och IT. Det handlar mer om informationsarkitektur än att skapa web services eller slänga in en broker (t ex BizTalk) och skapa nya orkestreringar ovanpå sin arkitektur med tjänsteändpunkter. Det handlar om att skapa autonoma och löst kopplade informationsdomäner (eller allmänt kallat <em>services</em>).</p>
<p><a href="http://www.udidahan.com/">Udi Dahan</a> har som alltid en förnuftig syn på det här, <a href="http://msdn.microsoft.com/en-us/architecture/aa699424">exempelvis</a>. Han blandar in event-driven arkitektur med artefakter som commands och events (distribution med pub/sub och service bus). För att reda ut begreppsförvirring mellan SOA och DDD har han dessutom myntat begreppet <a href="http://www.udidahan.com/2011/10/02/why-you-should-be-using-cqrs-almost-everywhere%e2%80%a6/">ABC</a> (<em>Autonomous Business Component</em> = <em>service </em>(SOA) = <em>bounded context</em> (DDD)). Inom en ABC kan vi i vissa passande fall välja att använda <a href="http://martinfowler.com/bliki/CQRS.html">CQRS</a>.</p>
<p>En tidig ikon inom SOA är <a href="http://blogs.msdn.com/b/pathelland/">Pat Helland</a>, metaforernas mästare. Mest känd för <a href="http://msdn.microsoft.com/en-us/library/aa480026.aspx">Metropolis</a>. Helland har skrivit en annan artikel som diskuterar <a href="http://blogs.msdn.com/b/pathelland/archive/2007/05/20/soa-and-newton-s-universe.aspx">distribuerade system och SOA</a>. Utgångspunkten är löst kopplade (meddelande-baserade) system med minskade krav på konsistens (eller om jag för göra en egen tolkning, det vi kallar <em><a href="http://en.wikipedia.org/wiki/Eventual_consistency">eventual consistency</a></em>) till skillnad från att lägga en distribuerad transaktion och få synkronicitet och konsistens.</p>
<h3>Vad har det här med molnet att göra?</h3>
<p>Först ett konstaterande. De flesta företag kommer inte att gå all-in vad gäller molnet. Nej. De kommer inte flytta <em>alla</em> sina system till molnet. Möjligtvis med undantag av start-up-företag, som inte har något arv med legacysystem osv. Om ett företag inte har en bra SOA, hur kan man då börja partitionera ut delar till molnet? Det går att bryta isär system med ”forcerad integration”. Men det optimala är att kunna välja vad som kan flyttas ut i molnet utifrån <em>verksamhetens behov</em>. Fundera på det en stund. Det borde inte vara IT som hindrar verksamheten när nya behov uppstår. Och tvärtom. Om vi har alignment mellan verksamhet och IT borde inga hinder uppstå. I den bästa av världar i alla fall.</p>
<p>En annan aspekt på detta är molnets karaktär. Molnet är instabilt. Molnet kostar pengar utifrån förbrukning. För att vårt system ska klara av denna miljö behöver vi ett system som klarar att maskiner går ner oväntat (lösa kopplingar, asynkrona meddelanden, durabilitet). Vi behöver kunna <a href="http://blogs.msmvps.com/marcelmeijer/blog/2011/07/28/windows-azure-scale-up-scale-out/">skala upp och ut och ner och in</a> vartefter behoven varierar vad gäller resurser. Olika delar belastas olika, vi vill kunna styra detta utifrån verksamhetens behov, dvs styra det på ABC-nivå.</p>
<p>Ytterligare en aspekt är att ett företag har möjlighet att köpa vissa funktioner som en software-as-a-service. Kanske för att nytt behov uppstår. Kanske för att minska kostnad. Kanske för att klara av mer last.</p>
<h3>Hur menar du egentligen?</h3>
<p>Jag tror ett konkret exempel kan belysa hur jag menar. Kraftigt förenklat, men det är nödvändigt för att inte trassla in sig i det oväsentliga.</p>
<p>Tänk dig ett ordersystem som håller information om ett företags ordrar. Systemet har utvecklats evolutionärt så att det även innehåller information om företagets kunder. Då det uppkom krav att meddela kunder via e-post byggdes även en notifikationsfunktion in i ordersystemet. Figur 1 visar systemet.</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2011/10/figur_a_ordersystem.png"><img class="alignnone size-medium wp-image-218" title="Figur A. Ordersystem med mycket ansvar (inte SOA)" src="http://www.nullreference.se/wp-content/uploads/2011/10/figur_a_ordersystem-172x300.png" alt="" width="172" height="300" /></a></p>
<p>Figur 1. Ordersystem med mycket ansvar (inte SOA)</p>
<p>Tänk dig istället följande arkitektur av ordersystemet. Företaget har en duktig arkitekt som byggt upp en löst kopplad eventdriven asynkron arkitektur. Kundhanteringen sköts i en informationsdomän och kommunicerar med omgivande system enbart med hjälp av events. Pub/sub av events kan ske via en service bus (troligen flera instanser, kanske <a href="http://www.nservicebus.com/">NServiceBus</a>). Se figur 2.</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2011/10/figur_b_ordersystem.png"><img class="alignnone size-medium wp-image-219" title="Figur 2. Ordersystem med uppdelat ansvar" src="http://www.nullreference.se/wp-content/uploads/2011/10/figur_b_ordersystem-300x199.png" alt="" width="300" height="199" /></a></p>
<p>Figur 2. Ordersystem med uppdelat ansvar</p>
<p>Tillbaka till företagets situation. Då företaget växer märker man att olika avdelningar har olika behov. Marknadsavdelningen vill ha tillgång till kundinformation och planera marknadsåtgärder och bearbeta prospekts. Ekonomiavdelningen är mer intresserad av färdiga ordrar och det belopp som ska faktureras.  Försäljningsavdelning (säljarna) vill kunna lägga in prospekts och när de träffar kunder på fältet vill de direkt kunna fylla i den här informationen.</p>
<p>I detta scenario tänker vi oss att företaget skulle vilja prioritera kundhanteringen och börja använda ett CRM-system i molnet. På så sätt kan säljarna komma åt CRM-systemet var de än är och marknadsavdelningen får stöd i sin process att skapa efterbearbetning av kunderna och göra riktade marknadsåtgärder mot vissa segment.  Företaget behöver dessutom inte köpa in ny hårdvara för att drifta CRM-systemet och skapa infrastruktur för att skapa åtkomst för säljarna på fältet.</p>
<p>Vilken arkitektur (figur 1 eller 2) passar bäst om företaget vill genomföra detta?</p>
<p>Slutlösningen med en hybrid av on-premise och molnet kan se ut enligt bilden nedan.</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2011/10/figur_c_ordersystem.png"><img class="alignnone size-medium wp-image-220" title="Figur 3. Ordersystem med användning av molntjänst" src="http://www.nullreference.se/wp-content/uploads/2011/10/figur_c_ordersystem-259x300.png" alt="" width="259" height="300" /></a></p>
<p>Figur 3. Ordersystem med användning av molntjänst</p>
<h3>Vad har vi uppnått?</h3>
<p>Det finns många fördelar med vår SOA-style hybrid arkitektur.</p>
<ul>
<li>Flexibel arkitektur. Vi kan när som helst välja att flytta tillbaka CRM-hanteringen on-premise. Vi kan dessutom välja att flytta ut andra delar, t ex Notifikationsfunktionen, till molnet.</li>
<li>Säkerhet. Vi slipper öppna upp åtkomst till det interna kundsystemet mot internet. Vi kan använda t ex <a href="http://www.microsoft.com/windowsazure/appfabric/">Windows Azure Appfabric Service Bus</a> för att skapa koppling mellan molnet och on-premise.</li>
<li>Skalbarhet. Molnet har ”oändlig” skalbarhet. Den asynkrona hanteringen tillåter en elastisitet och att vi kan ha kontroll på var flaskhalsar uppstår i systemet och då vidta lämpliga åtgärder (skala upp och ut).</li>
<li>Tillgänglighet.  Det asynkrona lösningsmönstret tillåter att maskiner startas om när som helst utan att andra system påverkas. Molnet är oförutsägbart på det sättet att vi inte har kontroll över infrastrukturen, uppgraderingar på plattformsnivå gör att instanser placeras om i datacentret, nätverksteknik (switchar, mm) går sönder, osv.</li>
</ul>
<h3>Slutsatsen</h3>
<p>Molnet är en möjlighet; t ex för att skapa skalbarhet, åtkomstbarhet, kostnadsminskning, flexibilitet.</p>
<p>Företag har olika förutsättningar att lyckas med molnet. En viktig förutsättning är att de har en arkitektur som baseras på lösa kopplingar; helst event-drivet, helst asynkront, helst i alignment med verksamheten. En bra SOA helt enkelt.</p>
<p>Att bygga system enligt ovan principer är viktigt om man har molnet i åtanke. Det finns ramverk och lösningsmönster som hjälper oss, några redan nämna. Ett spännande ramverk är <a href="http://lokad.github.com/lokad-cqrs/">Lokad-cqrs</a>, som bygger på dessa principer och dessutom gör det möjligt att sömlöst flytta sitt system mellan molnet och on-premise.</p>
<p>//Peter</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2011/10/11/soa-och-molntjanster/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using NServiceBus and ServiceBroker.net &#8211; Part 2</title>
		<link>http://www.nullreference.se/2010/12/07/using-nservicebus-and-servicebroker-net-part-2/</link>
		<comments>http://www.nullreference.se/2010/12/07/using-nservicebus-and-servicebroker-net-part-2/#comments</comments>
		<pubDate>Tue, 07 Dec 2010 16:04:21 +0000</pubDate>
		<dc:creator>Jens Pettersson</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[nservicebus]]></category>
		<category><![CDATA[servicebroker]]></category>
		<category><![CDATA[servicebroker.net]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/?p=193</guid>
		<description><![CDATA[In the previous post I showed how to set up the SQL Server Service Broker and in this post I will use a simple NServiceBus sample to show how to get the messages from the Service Broker, using ServiceBroker.net. You can find the NServiceBus transport for ServiceBroker.net in the official NServiceBus-contrib at github. If you [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-1/">previous post</a> I showed how to set up the SQL Server Service Broker and in this post I will use a simple NServiceBus sample to show how to get the messages from the Service Broker, using ServiceBroker.net.</p>
<p>You can find the NServiceBus transport for ServiceBroker.net in the official <a href="https://github.com/NServiceBus/NServiceBus-Contrib" target="_blank">NServiceBus-contrib</a> at github.</p>
<p>If you want to look at the code while reading you can get it at my <a href="https://github.com/jenspettersson/ServiceBrokerNetSample" target="_blank">github repository</a> for this sample application.</p>
<h4>Configuring NServiceBus and ServiceBroker.net</h4>
<p>Begin by creating a new NServiceBus sample application. Look in the official samples included with NServiceBus if you need help with this. Beyond the references to NServiceBus you need to add references to the following dll&#8217;s:</p>
<ul>
<li>ServiceBroker.Net.dll</li>
<li>NServiceBus.Unicast.Transport.ServiceBroker.dll</li>
</ul>
<p>The first thing we want to do is to create our own Transport Factory. We do this to create a &#8220;bridge&#8221; between the SQL Server Service Broker and our MSMQ transport which we will use later to publish other events. You don&#8217;t have to use MSMQ at all, and only stick to the SSSB transport, but in our scenario we will use MSMQ as our main transport.</p>
<p>Create a new interfaced (I called mine <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/src/ServiceBrokerNetSample/IChinookTransportFactory.cs" target="_blank">IChinookTransportFactory</a>) which has one method, GetTransport.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IChinookTransportFactory
{
    ITransport GetTransport();
}
</pre>
<p>It’s the GetTransport method that will return the ServiceBrokerTransport for NServiceBus to use. Create a <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/src/ServiceBrokerNetSample/ChinookTransportFactory.cs" target="_blank">class</a> implementing your newly created interface:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class ChinookTransportFactory : IChinookTransportFactory
{
    private readonly string _connectionString;
    private readonly IMessageSerializer _messageSerializer;

    public ChinookTransportFactory(string connectionString, IMessageSerializer messageSerializer)
    {
        _connectionString = connectionString;
        _messageSerializer = messageSerializer;
    }

    public ITransport GetTransport()
    {
        return new ServiceBrokerTransport
                    {
                        InputQueue = &quot;ChinookEventServiceQueue&quot;,
                        ErrorService = &quot;ErrorService&quot;,
                        ReturnService = &quot;ChinookEventService&quot;,
                        NumberOfWorkerThreads = 1,
                        MessageSerializer = _messageSerializer,
                        MaxRetries = 2,
                        ConnectionString = _connectionString
                    };
    }
}
</pre>
<p>In the GetTransport method you specify what Service Broker Services to use (the ones we created in the previous post) along with some other settings.</p>
<p>Notice that the Transport Factory takes a connection string as a parameter. We will have to tell our NServiceBus service which connection string to use. We do this in our StructureMap <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/src/ServiceBrokerNetSample/Bootstrapper.cs" target="_blank">bootstrapper</a>:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class Bootstrapper : IWantCustomInitialization
{
    public void Init()
    {
        ObjectFactory.Configure(x =&gt;
                                    {
                                        x.For&lt;IChinookTransportFactory&gt;().Use&lt;ChinookTransportFactory&gt;()
                                            .Ctor&lt;string&gt;()
                                            .EqualToAppSetting(&quot;connectionString&quot;);
                                    });
    }
}
</pre>
<p>The connection string itself is set in our <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/src/ServiceBrokerNetSample/App.config" target="_blank">app.config</a>:</p>
<pre class="brush: xml; title: ; wrap-lines: false; notranslate">
&lt;appSettings&gt;
  &lt;add key=&quot;connectionString&quot; value=&quot;Server=localhost\SQLEXPRESS;Database=Chinook;Integrated Security=SSPI;&quot; /&gt;
&lt;/appSettings&gt;
</pre>
<p>We now have most of the “back bone” done and the next thing to do is to create our event message in our application and then create something that actually picks up the messages from the Service Broker and hands them over to NServiceBus.</p>
<p>When creating our event message we need to make sure we match the namespace we defined in our <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/scripts/Create_Store_Procedure.sql" target="_blank">store procedure</a> in the <a href="http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-1/">last post</a>. We used the following:</p>
<pre class="brush: xml; title: ; wrap-lines: false; notranslate">
&lt;Messages xmlns=&quot;http://tempuri.net/ServiceBrokerNetSample.Events&quot;&gt;
</pre>
<p>As my sample application is called ServiceBrokerNetSample, what we’ll do is creating a new folder called “Events” in our application root. In that folder, create a new class called <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/src/ServiceBrokerNetSample/Events/CustomerEmailChangedEvent.cs" target="_blank">CustomerEmailChangedEvent</a> that implements IMessage:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
namespace ServiceBrokerNetSample.Events
{
    public class CustomerEmailChangedEvent : IMessage
    {
        public int CustomerId { get; set; }
        public string PreviousEmailAddress { get; set; }
        public string NewEmailAddress { get; set; }
    }
}
</pre>
<p>First, make sure your event is called the same thing as what we named the MessageName variable in our <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/scripts/Create_Trigger_EmailChanged.sql" target="_blank">trigger</a> we created in the <a href="http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-1/">previous post</a>. The properties must also be named the same thing as we named the xml elements in the trigger:</p>
<pre class="brush: sql; title: ; wrap-lines: false; notranslate">
SET @CustomerIdXml = (select @CustomerId for xml path('CustomerId'))
SET @PreviousEmailAddressXml = (select @OldEmail for xml path ('PreviousEmailAddress'))
SET @NewEmailAddressXml = (select @NewEmail for xml path ('NewEmailAddress'))
</pre>
<p>This will make sure that the NServiceBus XmlSerializer correctly serialize the xml to our CustomerEmailChangedEvent.</p>
<p>Now that we have our message event let’s create a class called <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/src/ServiceBrokerNetSample/ChinookNotificationForwarder.cs" target="_blank">ChinookNotificationForwarder</a> that implements IWantToRunAtStartup:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
public class ChinookNotificationForwarder : IWantToRunAtStartup
{
    private readonly IBus _bus;
    private readonly ITransport _transport;

    public ChinookNotificationForwarder(IBus bus, IChinookTransportFactory transportFactory)
    {
        _bus = bus;
        _transport = transportFactory.GetTransport();

        _transport.TransportMessageReceived += TransportMessageReceived;
    }

    void TransportMessageReceived(object sender, TransportMessageReceivedEventArgs e)
    {
        var message = e.Message.Body[0];
        _bus.SendLocal(message);
    }

    public void Run()
    {
        _transport.Start();
    }

    public void Stop()
    {
        _transport.Dispose();
    }
}
</pre>
<p>This class has a dependency on the bus and on our Transport Factory we created earlier. In the constructor we use this Transport Factory to create our ITransport which in this case will be the ServiceBrokerTransport. Then we wire up an event handler for when a transport message is received on that transport and in that event handler we get our event message from the event args.</p>
<p>How do we know that our message is at position 0 in e.Message.Body? Well, in the previous post, where we created the store procedure, we defined our Transport Message as:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;TransportMessage&gt;&lt;Body&gt;&lt;![CDATA[&lt;Messages xmlns=&quot;http://tempuri.net/ServiceBrokerNetSample.Events&quot;&gt;&lt;'+@MessageName+'&gt;...
</pre>
<p>And then in our trigger, we passed in the MessageName to the store procedure. This gives us the following in our event handler:</p>
<p><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.nullreference.se/wp-content/uploads/2010/12/image3.png" border="0" alt="image" width="507" height="157" /></p>
<blockquote><p><strong>Note!</strong> If you named your event message in your application to something else than what it’s named in the trigger you most probably will get the following exception:</p>
<p><em>Could not extract message data. System.TypeLoadException: Could not handle type…</em></p>
<p>Your message will then end up in the ErrorServiceQueue in the SQL Server Service Broker.</p></blockquote>
<p>The last thing we do in the event handler is telling the bus to do a SendLocal on our message. From here it’s just regular NServiceBus stuff going on, but for the record (and for the sake of fulfilling our scenario mentioned in the previous post), I’ll show the <a href="https://github.com/jenspettersson/ServiceBrokerNetSample/blob/master/src/ServiceBrokerNetSample/EventHandlers/CustomerEmailChangedHandler.cs" target="_blank">event handler</a> that handles the CustomerEmailChangedEvent:</p>
<pre class="brush: csharp; title: ; wrap-lines: false; notranslate">
namespace ServiceBrokerNetSample.EventHandlers
{
    public class CustomerEmailChangedHandler : IHandleMessages&lt;CustomerEmailChangedEvent&gt;
    {
        private readonly IBus _bus;

        public CustomerEmailChangedHandler(IBus bus)
        {
            _bus = bus;
        }

        public void Handle(CustomerEmailChangedEvent message)
        {
            //Do what you want to do... We will just publish an event for anyone interested.

            _bus.Publish&lt;ChinookCustomerEmailChangedEvent&gt;(x =&gt;
            {
                x.CustomerId = message.CustomerId;
                x.NewEmailAddress = message.NewEmailAddress;
            });
        }
    }
}
</pre>
<p>All this event handler does is publish an event for the rest of the world to use in whatever way they want.</p>
<p>That’s it! We now have a working sample application that uses ServiceBroker.net to fetch messages from the SQL Server Service Broker and hands it over to NServiceBus.</p>
<p>To try it out, run your application and set a debug point in your notification forwarder and in your handler, and then do an update on an email address in the Customer table.</p>
<p>There are quite a lot of “magic strings” floating around in our Store Procedure and Triggers that have to match our class names and properties, but once you’ve set this up it’s pretty easy to add more functionality.</p>
<p>I’ve added the sample application to a <a href="https://github.com/jenspettersson/ServiceBrokerNetSample" target="_blank">github repository</a>. It also includes all the SQL scripts needed to set up the SQL Server Service Broker.</p>
<p>If you have any questions, feel free to post a comment here or contact me.</p>
<p>Twitter: <a href="http://www.twitter.com/jens_pettersson" target="_blank">@jens_pettersson</a></p>
<p>//J</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/12/07/using-nservicebus-and-servicebroker-net-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using NServiceBus and ServiceBroker.net &#8211; Part 1</title>
		<link>http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-1/</link>
		<comments>http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-1/#comments</comments>
		<pubDate>Mon, 06 Dec 2010 16:17:30 +0000</pubDate>
		<dc:creator>Jens Pettersson</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[nservicebus]]></category>
		<category><![CDATA[servicebroker]]></category>
		<category><![CDATA[servicebroker.net]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/?p=169</guid>
		<description><![CDATA[This will be (at least) a two part series on how to use NServiceBus and ServiceBroker.net, where I walk you through how we (Frontwalker) used those techniques in a recent project. The first part will be how to set up the SQL Server Service Broker and the next part I&#8217;ll use the ServiceBroker.net and NServiceBus. [...]]]></description>
			<content:encoded><![CDATA[<p>This will be (at least) a two part series on how to use <a href="http://www.nservicebus.com/" target="_blank">NServiceBus </a>and <a href="https://github.com/jdaigle/servicebroker.net" target="_blank">ServiceBroker.net</a>, where I walk you through how we (Frontwalker) used those techniques in a recent project. The first part will be how to set up the SQL Server Service Broker and the <a href="http://www.nullreference.se/2010/12/07/using-nservicebus-and-servicebroker-net-part-2/">next part</a> I&#8217;ll use the ServiceBroker.net and NServiceBus.</p>
<blockquote><p><em>ServiceBroker.net <em>was created by <a href="https://github.com/jdaigle" target="_blank">Joseph Daigle</a> and it&#8217;s </em></em><em>a simple wrapper API for the SQL Service Broker. It also has a transport for NServiceBus that uses the SSSB. This transport is now part of the official <a href="https://github.com/NServiceBus/NServiceBus-Contrib" target="_blank">NServiceBus-contrib</a> over at github.</em></p></blockquote>
<p>Our scenario was:</p>
<p>The client had a rather old application and they wanted that some of the changes made to that applications underlying data would be processed and sent to another application. In other words, pretty simple, one-way, integration. The old application didn’t publish any events when the client did something, it just inserted/updated/deleted rows in a SQL Server 2005 database. Just for the record, the application itself was a-not-so-task-based MS Access application…</p>
<p>To solve this we had to listen to changes in the columns we were interested in and then notify our integration service to take action. We are using NServiceBus in our projects and decided to use the ServiceBroker.net to solve this scenario. In this series I will be using the <a href="http://chinookdatabase.codeplex.com/" target="_blank">Chinook database</a> and a simple NServiceBus sample to illustrate how we did this.</p>
<h4>Setting up the Service Broker in SQL Server</h4>
<p>First, make sure that the Service Broker is enabled on your database. Right click your database in Microsoft SQL Server Management Studio and select Properties –&gt; Options. Set “Broker Enabled” to True.</p>
<p><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.nullreference.se/wp-content/uploads/2010/12/image.png" border="0" alt="image" width="474" height="67" /></p>
<p>The next thing we need to do is to define a message type and a message contract that the Service Broker will use. We do that by running the following SQL:</p>
<pre class="brush: sql; title: ; notranslate">CREATE MESSAGE TYPE NServiceBusTransportMessage
    VALIDATION = NONE ;
GO

CREATE CONTRACT NServiceBusTransportMessageContract
    ( NServiceBusTransportMessage SENT BY ANY);
GO</pre>
<p>After that, we create our service queue, our service and also an error service queue and an error service.</p>
<pre class="brush: sql; title: ; notranslate">CREATE QUEUE [dbo].[ChinookEventServiceQueue];
GO

CREATE SERVICE ChinookEventService
    ON QUEUE [dbo].[ChinookEventServiceQueue]
    (NServiceBusTransportMessageContract);
GO

-- Error service
CREATE QUEUE [dbo].[ErrorServiceQueue];
GO

CREATE SERVICE ErrorService
    ON QUEUE [dbo].[ErrorServiceQueue]
    (NServiceBusTransportMessageContract);
GO</pre>
<p>Run these scripts and refresh your database and you should see the following:</p>
<p><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.nullreference.se/wp-content/uploads/2010/12/image1.png" border="0" alt="image" width="253" height="261" /></p>
<p>It’s in the ChinookEventServiceQueue all your messages from your SQL server will end up before being picked up by ServiceBroker.net and NServiceBus.</p>
<p>Now we need something in our database to actually send messages to our newly created service queue. For this, we will use a Store Procedure. You can copy and paste this from below but make sure the @MessageContract and the @MessageType variables have the same name as the message type and message contract you created earlier.</p>
<p>Another very important part is that the @TransportMessage variable get the correct xmlns set (the &lt;Messages xmlns=”http://tempuri.net/<strong>Namespace.of_your.Events</strong>”&gt;). The xmlns need to be set to tempuri.net/ and then the correct namespace of where your events resides. (If you don’t know what your namespace will be, just alter this store procedure later).</p>
<blockquote><p><strong>Note!</strong> The http://tempuri.net/Namespace.of_your.Events is the default namespace of NServiceBus XmlSerializer. You can change this when configuring NServiceBus.</p></blockquote>
<pre class="brush: sql; title: ; wrap-lines: false; notranslate">CREATE PROCEDURE [dbo].[SendNServiceBusMessage]
 @TargetService NVARCHAR(200),
 @MessageName NVARCHAR(200),
 @MessageContent NVARCHAR(4000)
AS

BEGIN
-- Sending a Service Broker Message
DECLARE @InitDlgHandle UNIQUEIDENTIFIER;
DECLARE @MessageContract NVARCHAR(200);
DECLARE @MessageType NVARCHAR(200);
DECLARE @TransportMessage NVARCHAR(4000);

SET NOCOUNT ON

SET  @MessageContract = 'NServiceBusTransportMessageContract';
SET  @MessageType = 'NServiceBusTransportMessage';

BEGIN TRANSACTION;

 BEGIN DIALOG @InitDlgHandle
   FROM SERVICE @TargetService
   TO SERVICE @TargetService
   ON CONTRACT @MessageContract
   WITH ENCRYPTION = OFF;

SET @TransportMessage ='&lt;TransportMessage&gt;&lt;Body&gt;&lt;![CDATA[&lt;Messages xmlns=&quot;http://tempuri.net/ServiceBrokerNetSample.Events&quot;&gt;&lt;'+@MessageName+'&gt;' +
    @MessageContent +'&lt;/'+@MessageName+'&gt;&lt;/Messages&gt;]]&gt;&lt;/Body&gt;&lt;/TransportMessage&gt;';

 SEND ON CONVERSATION @InitDlgHandle
   MESSAGE TYPE @MessageType
    (@TransportMessage);

COMMIT TRANSACTION;

END

GO</pre>
<p>Now we need something to actually use this Store Procedure to create messages for our service queue. This is the scary part, we will need to use a trigger on the table we’re interested in!</p>
<p>Now you have a choice. You can either create one trigger per change you’re interested in or create one “global” trigger that listens to all changes to a given table and then use an event handler in NServiceBus to later decide what was changed. We used the latter in our project, but in this sample I’m just going to listen for changes in one column.</p>
<p>Let’s say we have the following scenario for this example:</p>
<p><em>When a customer changes his email address, we want to notify some other service&#8230;</em></p>
<p>The Chinook database have a table named “Customer” and it contains a column named “Email”. Let’s create the trigger that listens for changes to that column.</p>
<p>Here’s the SQL for creating the trigger:</p>
<pre class="brush: sql; title: ; wrap-lines: false; notranslate">CREATE TRIGGER [dbo].[TRG_EmailChanged]
   ON  [dbo].[Customer]
   FOR UPDATE
AS
IF UPDATE(Email)
BEGIN
	SET NOCOUNT ON;

	DECLARE @MESSAGENAME NVARCHAR(255)

	-- This is what event your application will use later
	SET @MESSAGENAME = 'CustomerEmailChangedEvent'

	DECLARE @CustomerId int
	DECLARE @OldEmail NVARCHAR(60)
	DECLARE @NewEmail NVARCHAR(60)

	SELECT @OldEmail = Email FROM deleted
	SELECT @NewEmail = Email, @CustomerId = CustomerId FROM inserted

	IF @OldEmail &lt;&gt; @NewEmail
	BEGIN

		DECLARE @CustomerIdXml XML
		DECLARE @PreviousEmailAddressXml XML
		DECLARE @NewEmailAddressXml XML
		DECLARE @XmlText NVARCHAR(MAX)

		-- I'm using select for xml because otherwise special characters might cause problems
		SET @CustomerIdXml = (select @CustomerId for xml path('CustomerId'))
		SET @PreviousEmailAddressXml = (select @OldEmail for xml path ('PreviousEmailAddress'))
		SET @NewEmailAddressXml = (select @NewEmail for xml path ('NewEmailAddress'))

		-- This is the text that we will use in our message
		SET @XmlText = cast(@CustomerIdXml as NVARCHAR(MAX))
			+ cast(@PreviousEmailAddressXml as NVARCHAR(MAX))
			+ cast(@NewEmailAddressXml as NVARCHAR(MAX))

		exec SendNServiceBusMessage
			@TargetService = N'ChinookEventService',
			@MessageName = @MESSAGENAME,
			@MessageContent = @XmlText;
	END
END
GO</pre>
<p><em>Updated the trigger and added CustomerId too. Kind of useless to send an event like this without saying wich customer it affects&#8230;</em></p>
<p>I’m by no means a SQL expert, so I’ve kept the trigger as simple as possible. Basically, what’s going on is that I check if the old value differs from the new value and if so I create a message body in XML and pass that and the name of the message to the store procedure we created earlier.</p>
<p>Now we have a trigger that, if a customers email address is changed, creates a message and hands that to the Service Broker. You can try it out by running a simple update on a customer:</p>
<pre class="brush: sql; title: ; notranslate">update Customer set Email = 'jens.pettersson@local.loc' where CustomerId = 60</pre>
<p>Now, under your Service Broker &gt; Queues, right click the ChinookEventServiceQueue and select “Select top 1000 rows” and you should see one row. Look in the last column, called “casted_message_body”. There you should see the XML your trigger passed on to your store procedure and more that the sp added for this message to work with NServiceBus.</p>
<p><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.nullreference.se/wp-content/uploads/2010/12/image2.png" border="0" alt="image" width="582" height="39" /></p>
<p>That&#8217;s it for the first part! It&#8217;s quite a lot of scary SQL stuff going on, but when you&#8217;ve set this up you really only need to worry about new triggers later on.</p>
<p>In the next part, I will build a simple NServiceBus sample that actually uses the ServiceBroker.net. This post didn&#8217;t really say anything about that or NServiceBus, but this stuff is needed to get something up and running.</p>
<p>//J</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-1/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Getting the NServiceBus-Contrib project up to speed!</title>
		<link>http://www.nullreference.se/2010/11/03/getting-the-nservicebus-contrib-project-up-to-speed/</link>
		<comments>http://www.nullreference.se/2010/11/03/getting-the-nservicebus-contrib-project-up-to-speed/#comments</comments>
		<pubDate>Wed, 03 Nov 2010 14:01:37 +0000</pubDate>
		<dc:creator>Frontwalker</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/?p=139</guid>
		<description><![CDATA[Here at Frontwalker we do alot of NServiceBus development for our customers. We think all successful open source projects needs an active community, NServiceBus got that. But one area that needs improvement is an active contrib where the commity can gather useful add-ons and extensions. Therefore we have decided to devote some our time to [...]]]></description>
			<content:encoded><![CDATA[<p>Here at Frontwalker we do alot of NServiceBus development for our customers. We think all successful open source projects needs an active community, NServiceBus got that.</p>
<p>But one area that needs improvement is an active contrib where the commity can gather useful add-ons and extensions.</p>
<p>Therefore we have decided to devote some our time to manage the contrib project for NServiceBus. For this to be successful the community needs to be behind this and contribute with both code and documentation. We&#8217;re just trying to facilitate that. So, please <a href="http://help.github.com/forking/">fork </a>away!</p>
<p>The official NServiceBus-Contrib project is located over at <a title="GitHub" href="https://github.com/NServiceBus/NServiceBus-Contrib">github</a>. We&#8217;re planning to move all the content from the old contrib here.</p>
<p>The discussion group is found at <a href="http://groups.google.com/group/nservicebus-contrib">http://groups.google.com/group/nservicebus-contrib</a></p>
<p>We&#8217;re using teamcity.codebetter.com as build server. From <a href="http://teamcity.codebetter.com/project.html?projectId=project104&amp;tab=projectOverview">here </a>you can download the latest binaries.</p>
<p>More details will follow in upcoming posts.</p>
<p>Keep those pull requests coming!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/11/03/getting-the-nservicebus-contrib-project-up-to-speed/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Working with Git submodules</title>
		<link>http://www.nullreference.se/2010/10/11/working-with-git-submodules/</link>
		<comments>http://www.nullreference.se/2010/10/11/working-with-git-submodules/#comments</comments>
		<pubDate>Mon, 11 Oct 2010 05:29:01 +0000</pubDate>
		<dc:creator>Mikael Nordberg</dc:creator>
				<category><![CDATA[Source control]]></category>
		<category><![CDATA[git]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/?p=101</guid>
		<description><![CDATA[In our current project we&#8217;re using some shared libraries that we have developed as open source. These libraries are something that we upgrade on a regularly basis, so referencing the built assembly would add some pain when, for example, a bug is found in a library. What we really want is to include the shared [...]]]></description>
			<content:encoded><![CDATA[<div id="_mcePaste">In our current project we&#8217;re using some shared libraries that we have developed as open source. These libraries are something that we upgrade on a regularly basis, so referencing the built assembly would add some pain when, for example, a bug is found in a library.</div>
<div>What we really want is to include the shared projects source code and be able to add all changes back to their own repositories. Git submodules lets us do just that.</div>
<div>This is the structure of our main_project</div>
<pre>/
/lib
/lib/nhibernate
/lib/log4net
/lib/.....
/src
/src/main_project
/src/main_project_classlibrary
/src/.....</pre>
<p>From main_project all assemblies are referenced from the /lib folder.</p>
<div>Our shared projects are configured to look for it&#8217;s references in ../lib which will be equal to /lib for the main_project.</div>
<div>To add a shared project to our main_project we do:</div>
<pre>git submodule add git@github.com/frontwalker/NullReference.Data.git src/NullReference.Data</pre>
<div><span style="font-family: 'Courier New'; font-size: xx-small;"> </span></div>
<div>This will add the NullReference.Data project into /src/NullReference.Data folder. But what if NullReference.Data is updated with some breaking changes? Do we need to update and recompile our main_project? Only if we want the new features!</div>
<div>The submodule that is added to our main project is added with the exact version that the project was in at the given time when it was added as a submodule. So if NullReference.Data was added at version 1.23 it will stay at that version in main_project until we decide to update it even if NullReference.Data it self is updated from another project.</div>
<h3>Cloning a tree with submodules</h3>
<div id="_mcePaste">To clone the main_project you do it as you normally would with the &#8220;git clone&#8221; command. But when opening one of the folders for a submodule you will find out that they contain no files at all. Git doesn’t automatically fetch all your submodules when you clone a project, so you need to &#8220;init&#8221; and &#8220;update&#8221; for the submodules before you can use them.</div>
<pre>git submodule init
git submodule update</pre>
<p>You only need to do this once or if someone adds another submodule.<br />
Alot of information about the command is found in the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-submodule.html" target="_blank"><span style="color: #000000;">documentation </span></a>and I also found <a href="http://woss.name/blog/2008/4/9/using-git-submodules-to-track-plugins.html" target="_blank"><span style="color: #000000;">this</span></a> blog post from &#8220;mathie&#8221; very helpful.</p>
<p>You can check out our <a href="http://github.com/frontwalker" target="_self">NullReference</a> libraries on GitHub.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/10/11/working-with-git-submodules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What to test your code change against</title>
		<link>http://www.nullreference.se/2010/10/05/what-to-test-your-code-change-against/</link>
		<comments>http://www.nullreference.se/2010/10/05/what-to-test-your-code-change-against/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 21:25:14 +0000</pubDate>
		<dc:creator>Kenneth Selin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/?p=94</guid>
		<description><![CDATA[In this blog entry, I&#8217;m gonna discuss how how big part of the rest of the system/application you need to integrate in your test, before checking in your code. We have all heard how much more expensive it gets when a fault is found at a later stage of the test chain (or even in [...]]]></description>
			<content:encoded><![CDATA[<p>In this blog entry, I&#8217;m gonna discuss how how big part of the rest of the system/application you need to integrate in your test, before checking in your code.</p>
<p>We have all heard how much more expensive it gets when a fault is found at a later stage of the test chain (or even in a production system). It is a fact that software companies of any notable size does use several test stages. What these stages are called and how many they are, varies from company to company. The first test stage however is the test the developer is supposed to perform before checking in the code. This might be called &#8220;unit test&#8221; or &#8220;basic test&#8221; for example. Then there is typically an integration test, where it is tested that several modules delivered independently are able to talk to each other. At the next test stage, maybe called &#8220;function test&#8221;, it could be tested that the system&#8217;s functionality works. Another test stage could test non-functional requirements, like stability and performance.</p>
<p>The further down the test chain, the closer to the real production environment we get. Real database management systems are used (I call these &#8220;databases&#8221; from now on), expensive hardware, and so on.</p>
<p>And again, if a bug is found late in the test chain, it is usually more expensive to fix, since you might want to pass all the test stages again. This could make you feel guilty as a developer, when a bug is found, and maybe lead to pretty strange behaviour to avoid finding the bugs &#8220;late&#8221;.</p>
<p>There are many examples of companies where the developers are supposed to test in production like environments, with real databases, expensive hardware and so on before checking in the code. It is easy to understand that this kind of testing takes a lot of time, and is typically performed manually.</p>
<p>All these test stages and the company culture revolving around the test stages can be very confusing. What is a developer actually supposed to do before checking in the code?</p>
<p><em><strong>The developer needs to test the changed code towards it&#8217;s interfaces until the developer is confident the change works.</strong></em></p>
<p><em><strong></strong></em>This statement holds a lot in it, so let me elaborate.<br />
<strong></strong></p>
<p>First we consider that the code must be tested towards its interfaces (for example other classes, protocols, etc). Here, it helps a lot if the interfaces are clearly understood. If you know (by documentation or experience) what the interfaces used by the code return, you can much faster get confident that the change works, by somehow getting the interface to return the values you need for your test. Now, you should preferrably mock the interface in an automated test case, which will let you get confident of your code change very quickly.</p>
<p>Understand that as long as you get the interface to return the values you like, it does not matter where the values originate from. A String is a String, regardless if you mock it into your stubs or if you dig it up from a database in some layer far below yours.</p>
<p><em>That is, it does not add value to the test if you dig up the string from the database, it just takes more time and money.</em></p>
<p>A recurring statement from people prefering to test (manually) using real databases is that &#8220;they want to be sure that it works&#8221;. This is in a sense a good ambition. They want to do a good job for their employer, and not get blamed later. However, time and money are critical resources for the employer, and time and money must be spent right. If you can test quickly and cheaply, getting you confident that the change works, you should do it. At odd times, a bug you could have found using (manual) database-based test might slip to later test stages, but this means 1) you did not understand the interfaces and/or 2) you were sloppy while testing.</p>
<p><em>Testing faster and cheaper frees up time and money for the employer, making the developers more productive.</em></p>
<p>Sometimes however, you might not be able to get confident of the test using just stubs. This is when the interface is not well understood, since it is not well documented or for some reason can not be trusted. Also, if you are new to the code base, it is harder (and should be harder) to get confident. In this case it might be fine to test using real databases (if not anything else, it will teach you more about how the real system functions), but it could be smarter try understanding the interface instead and then test the code change using stubs.</p>
<p>To sum it up, it is a waste of time and resources to integrate a lot of &#8220;real&#8221; software (like databases) into your test, and you should not do it routinely.</p>
<p>(The topic of manual versus automated testing is maybe for some other time <img src='http://www.nullreference.se/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/10/05/what-to-test-your-code-change-against/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to write an error message</title>
		<link>http://www.nullreference.se/2010/09/16/how-to-write-an-error-message/</link>
		<comments>http://www.nullreference.se/2010/09/16/how-to-write-an-error-message/#comments</comments>
		<pubDate>Thu, 16 Sep 2010 13:55:45 +0000</pubDate>
		<dc:creator>Kenneth Selin</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/?p=90</guid>
		<description><![CDATA[When you run someone else&#8217;s software, there are sometimes error messages which are hard to understand. Most likely, you will always understand error messages from your own software, not necessarily since the error message is good, but since you wrote the code for the software, you will know much about the conditions when it is [...]]]></description>
			<content:encoded><![CDATA[<p>When you run someone else&#8217;s software, there are sometimes error messages which are hard to understand. Most likely, you will always understand error messages from your own software, not necessarily since the error message is good, but since you wrote the code for the software, you will know much about the conditions when it is reported.</p>
<p>It is very annoying to stumble upon a bad error message, for two reasons: 1) the error message does not help you analyse the problem, 2) you realise that phrasing a better error message would probably been very easy for the developer, but she ignored it.</p>
<p>The hard and fast rule for error message is: <strong>the message needs to be specific, and using the language of the reader</strong>.</p>
<p>Examples of implications:</p>
<p>You need to tell <em>which</em> file you could not open. Stating something like &#8220;failed to open file&#8221; or including a stack trace with FileNotFoundException is bad.</p>
<p>Stack traces are in general bad, confusing and, all too often, lengthy. If an exception is thrown all the way up to the highest architectural level and you at this point don&#8221;t have more information than the instance of the exception and the strack trace, something is wrong, for example a bug in your or in a library&#8217;s code. At this point, you have to log what you know, and then finding a fix for your bug or your unhandled configuration problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/09/16/how-to-write-an-error-message/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Testing for exceptions in MSpec</title>
		<link>http://www.nullreference.se/2010/09/10/testing-for-exceptions-in-mspec/</link>
		<comments>http://www.nullreference.se/2010/09/10/testing-for-exceptions-in-mspec/#comments</comments>
		<pubDate>Fri, 10 Sep 2010 18:26:08 +0000</pubDate>
		<dc:creator>Jens Pettersson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[mspec]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/2010/09/10/testing-for-exceptions-in-mspec/</guid>
		<description><![CDATA[As I’ve said before, we’re using MSpec in our current project and today I needed to make sure a method threw the right kind of exception. This may be really easy, but as I’ve never done this in MSpec before, I had to ask the mighty Google for the answer. When ever I have to [...]]]></description>
			<content:encoded><![CDATA[<p>As I’ve said before, we’re using MSpec in our current project and today I needed to make sure a method threw the right kind of exception. This may be really easy, but as I’ve never done this in MSpec before, I had to ask the mighty Google for the answer. When ever I have to do that, I want to write it down somewhere (but I seldom do), and that’s why I’m posting this here.</p>
<p>Consider we have the following, very useful, method in a Very Fragile class:</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2010/09/image.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.nullreference.se/wp-content/uploads/2010/09/image_thumb.png" width="385" height="153" /></a>Now we want to make sure that when the bomb is dropped our calling code gets a Potential Dangerous Exception. The following specification will test that this really happens:</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2010/09/image1.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="" border="0" alt="" src="http://www.nullreference.se/wp-content/uploads/2010/09/image_thumb1.png" width="509" height="250" /></a>That’s it! Using the Catch-class in MSpec will return an Exception and then all you have to do is check that it is of the correct type.</p>
<p>Happy MSpec-ing!</p>
<p>//J</p>
<p><em>PS. If you wonder why I’m not using our syntax highlighting plugin the simple answer is that I love the <a href="http://github.com/jenspettersson/Visual-Studio-Themes" target="_blank">Visual Studio theme</a> I’m using and think Daniel should switch to it now! <img src='http://www.nullreference.se/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/09/10/testing-for-exceptions-in-mspec/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Event based interop with Service Broker</title>
		<link>http://www.nullreference.se/2010/09/03/event-based-interop-with-service-broker/</link>
		<comments>http://www.nullreference.se/2010/09/03/event-based-interop-with-service-broker/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 07:57:49 +0000</pubDate>
		<dc:creator>Andreas Öhlund</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/2010/09/03/event-based-interop-with-service-broker/</guid>
		<description><![CDATA[When integrating with legacy databases you’re often required detect changes by polling. This method have some quirks that can be problematic at times. The first issue is that you need to figure out when rows has been inserted or updated. If your legacy db has timestamp columns for inserts and updates this is quite straight [...]]]></description>
			<content:encoded><![CDATA[<p>When integrating with legacy databases you’re often required detect changes by polling. This method have some quirks that can be problematic at times. The first issue is that you need to figure out when rows has been inserted or updated. If your legacy db has timestamp columns for inserts and updates this is quite straight forward, just remember when the time you lasts checked for changes and get all changes that has occurred since then. If no such columns exists you’re in trouble and the pain of writing manual code for keeping track of all that awaits you. The other problem is that it’s hard to figure out which fields that was updated. This might not be a big issue but if you need to make decisions based on that info you need maintain a copy of the data in order to figure out what has changed. This is almost always the case if you want to move a way from CRUD style events like CustomerUpdated and the likes to a more business aligned model with events like CustomerActived, CustomerMoved etc etc.</p>
<p>We faced all the problems above and decided to tackle the problem from another angle. As a nice coincidence I had noticed the <a href="http://blog.cridion.com/">Joseph Daigle</a> had created a <a href="http://github.com/jdaigle/servicebroker.net">ITransport implementation</a> for NServiceBus that work with SQL Server Service Broker (SSSB). I had to <a href="http://github.com/jdaigle/servicebroker.net/commit/418ee0720962d2ea07830c3f34c84f84cef22d22">patch the transport</a>, to support xml serialization in order to be able to send messages direct from within SQL Server. With this in place we could add triggers to the relevant tables to add messages to the SSSB queue.</p>
<p>We added the following stored procedure to help with creating xml in the correct format for the NServiceBus xml parser and finally submitting the message to the queue.</p>
<p> <script src="http://gist.github.com/563557.js?file=SendNServiceBusMessage.sql"></script>
</p>
<p>For instructions on how to setup SSSB and create the necessary Services and queues please read more <a href="http://github.com/jdaigle/servicebroker.net/blob/master/README.md">here</a>.</p>
<h3>Receiving messages from SSSB</h3>
<p>The next step was to enable our regular NServiceBus endpoint to receive messages from SSSB. Our main transport is Msmq so we have to start up the SSSB Transport and forwards all incoming messages to our regular transport using SendLocal. This is easily done by implementing IWantToRunAtStartup causing the NServicebus Host to kick off a separate thread to handle this. Next we subscribe to the TransportMessageReceived event and send the incoming messages to our Msmq transport for regular message processing. This combined with the fact that SSSB supports distributed transactions gives us a nice and robust bridge between SSSB and Msmq.</p>
<p>The code is displayed below.</p>
<p> <script src="http://gist.github.com/563553.js?file=Forwarder.cs"></script>
<p>The image below outlines the moving parts of this solution</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2010/09/Sqlbroker.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Sqlbroker" border="0" alt="Sqlbroker" src="http://www.nullreference.se/wp-content/uploads/2010/09/Sqlbroker_thumb.png" width="571" height="261" /></a> </p>
<h3>In closing</h3>
<p>This is an example of using the SSSB transport to do event based interop with SQL Server. You can of course use the transport for pure SSSB backed solutions where you use SSSB queues as your main transport for messages between your regular NServiceBus endpoint. This removes the dependency on MSMQ but will make your SQL Server a single point of failure and a potential bottleneck.</p>
<p>Pick your poison!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/09/03/event-based-interop-with-service-broker/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ReSharper templates</title>
		<link>http://www.nullreference.se/2010/08/30/resharper-templates/</link>
		<comments>http://www.nullreference.se/2010/08/30/resharper-templates/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 14:47:41 +0000</pubDate>
		<dc:creator>Jens Pettersson</dc:creator>
				<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[resharper]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://www.nullreference.se/2010/08/30/resharper-templates/</guid>
		<description><![CDATA[I would like to share my small but helpful collection of ReSharper templates. I use ReSharper templates a lot and most specifically while I’m writing tests/specifications or while creating mappings or any other repetitive task that can’t be DRY:ed out. For the moment I only have a couple of Live Templates for MSpec that I [...]]]></description>
			<content:encoded><![CDATA[<p>I would like to share my small but helpful collection of ReSharper templates. I use ReSharper templates a lot and most specifically while I’m writing tests/specifications or while creating mappings or any other repetitive task that can’t be DRY:ed out. For the moment I only have a couple of Live Templates for MSpec that I use while writing our BDD specifications, but I plan to update this as soon as I need a new template. I lost my old templates in the volcanic ash earlier this year…</p>
<p>This is one example of a template I use when creating a new MSpec class:</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2010/08/image3.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="image" border="0" alt="image" src="http://www.nullreference.se/wp-content/uploads/2010/08/image_thumb3.png" width="423" height="263" /></a></p>
<p>All this code given to me by writing <strong>spec</strong> and hitting tab. The duplication of the class name in the FolderSubject attribute is generated as I name my class and is used for our report generator.</p>
<p>Never mind the weird indentation under Establish and Because, it’s Visual Studios way of saying: <em>I don’t like you</em>. </p>
<p>You import the templates by going to ReSharper &gt; Live Templates and then hitting the import-button.</p>
<p><a href="http://www.nullreference.se/wp-content/uploads/2010/08/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="image" border="0" alt="image" src="http://www.nullreference.se/wp-content/uploads/2010/08/image_thumb4.png" width="359" height="235" /></a> </p>
<p>You can get the templates from my <a href="http://github.com/jenspettersson/ReSharperTemplates" target="_blank">Github repository</a>. Feel free to contribute with your own ReSharper templates!</p>
<p>//J</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nullreference.se/2010/08/30/resharper-templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

