<?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>Gabriel Schenker&#039;s Blog</title>
	<atom:link href="http://lostechies.com/gabrielschenker/feed/" rel="self" type="application/rss+xml" />
	<link>http://lostechies.com/gabrielschenker</link>
	<description>Blog about architectural patterns, best practices, coding principles and techniques</description>
	<lastBuildDate>Sun, 15 Jul 2012 23:34:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>ADNUG Presentation July 9, 2012</title>
		<link>http://lostechies.com/gabrielschenker/2012/07/15/adnug-presentation-july-12-2012/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/07/15/adnug-presentation-july-12-2012/#comments</comments>
		<pubDate>Sun, 15 Jul 2012 23:29:56 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Event sourcing]]></category>
		<category><![CDATA[presentation]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/07/15/adnug-presentation-july-12-2012/</guid>
		<description><![CDATA[I want to thank all people who attended my presentation about CQRS and Event Sourcing at the ADNUG meeting on July 9, 2012. It was a great experience for me and I was pleased about the many questions you had.&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/07/15/adnug-presentation-july-12-2012/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I want to thank all people who attended my presentation about CQRS and Event Sourcing at the ADNUG meeting on July 9, 2012. It was a great experience for me and I was pleased about the many questions you had. The <a href="https://github.com/gnschenker/RecipesWithCqrsAndEs/tree/master/Slides">slides</a> and the <a href="https://github.com/gnschenker/RecipesWithCqrsAndEs">sample code</a> are now available on <a href="https://github.com/gnschenker">GitHub</a>. For more information about CQRS and ES please consult the following section.</p>
<h1>Training resources regarding CQRS and ES</h1>
<p>At our company we use CQRS and ES. For the newer products fully implemented in this new architecture we do not use any database but just the file system as data store. This new way of developing requires a significant and somewhat radical mind shift. What used to be best-practice in the <em>traditional way</em> of coding does not apply any more. Things are solved differently.</p>
<h2>Definitions</h2>
<p><strong>DDD</strong>: Domain Driven Design<br /><strong>CQRS</strong>: Command Query Responsibility Segregation<br /><strong>ES</strong>: Event Sourcing</p>
<h1>Web-Sites</h1>
<ul>
<li>Good site about DDD/CQRS/ES: <a href="http://domaindrivendesign.org/cqrs">http://domaindrivendesign.org/cqrs</a>
<li>DDD sample of event sourcing in C# (accompanies Vaughn&#8217;s new book on IDDD): <a href="http://lokad.github.com/lokad-iddd-sample/">http://lokad.github.com/lokad-iddd-sample/</a>
<li>DDD/CQRS Community around the world: <a href="http://cqrsguide.com/world">http://cqrsguide.com/world</a>
<li>Case studies of CQRS/DDD projects: <a href="http://cqrsguide.com/case-studies">http://cqrsguide.com/case-studies</a></li>
</ul>
<h1>Videos</h1>
<ul>
<li>6-hour video about CQRS by Greg Young: <a href="http://www.viddler.com/v/dc528842">http://www.viddler.com/v/dc528842</a>
<li>Video about DDD/CQRS by Greg Young: <a href="http://www.youtube.com/watch?v=KXqrBySgX-s">http://www.youtube.com/watch?v=KXqrBySgX-s</a>
<li>Search for other videos by Greg Young, e.g. on Sills Matter
<ul>
<li><a href="http://skillsmatter.com/podcast/design-architecture/simple-is-better">http://skillsmatter.com/podcast/design-architecture/simple-is-better</a>,
<li><a href="http://skillsmatter.com/podcast/design-architecture/cqrs-not-just-for-server-systems?goback=.gde_2470540_member_49148769">http://skillsmatter.com/podcast/design-architecture/cqrs-not-just-for-server-systems?goback=.gde_2470540_member_49148769</a></li>
</ul>
</li>
</ul>
<h1>Videos of Greg Young, Udi Dahan, Eric Evans, et. al.: <a href="http://skillsmatter.com/event/design-architecture/ddd-exchange-2011">http://skillsmatter.com/event/design-architecture/ddd-exchange-2011</a></h1>
<h1>People and Blogs</h1>
<p>Important people to follow</p>
<ul>
<li>Greg Young, <a href="http://codebetter.com/gregyoung/,he">http://codebetter.com/gregyoung/,he</a> coined the term CQRS
<li>Rinat Abdullin, <a href="http://abdullin.com/,we">http://abdullin.com/,we</a> use a customized version of his “framework” (Lokad.CQRS &#8211; <a href="http://lokad.github.com/lokad-cqrs/)">http://lokad.github.com/lokad-cqrs/)</a>
<li>Jonathan Oliver, <a href="http://blog.jonathanoliver.com/">http://blog.jonathanoliver.com/</a>
<li>Udi Dahan, <a href="http://www.udidahan.com/?blog=true">http://www.udidahan.com/?blog=true</a></li>
</ul>
<h1>Discussion Groups</h1>
<p>Important discussions about and around DDD, CQRS and Event Sourcing happen in this Google group: <a href="http://groups.google.com/group/dddcqrs?pli=1">http://groups.google.com/group/dddcqrs?pli=1</a></p>
<p>Most of the people having some relevance in this area are present on this group and answering questions.</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/07/15/adnug-presentation-july-12-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Presenting at ADNUG meeting</title>
		<link>http://lostechies.com/gabrielschenker/2012/07/06/presenting-at-adnug-meeting/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/07/06/presenting-at-adnug-meeting/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 22:18:06 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Event sourcing]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[presentation]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/07/06/presenting-at-adnug-meeting/</guid>
		<description><![CDATA[I’m pleased to be invited to speak/present at the ADNUG meeting on Monday July 9th, 2012 at 6pm. The topic of my presentation will be CQRS and Event Sourcing with a special focus on how we do it at TOPAZ&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/07/06/presenting-at-adnug-meeting/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I’m pleased to be invited to speak/present at the <a href="http://adnug.org/">ADNUG</a> meeting on Monday July 9th, 2012 at 6pm. The topic of my presentation will be <a href="http://cqrsguide.com/">CQRS</a> and <a href="http://martinfowler.com/eaaDev/EventSourcing.html">Event Sourcing</a> with a special focus on how we do it at <a href="http://www.topazti.com/">TOPAZ Technologies LLC</a>.</p>
<blockquote><h4>Abstract</h4>
<p>In our company we were looking for a way to radically simplify the way we implement our enterprise software. We wanted to get rid of accidental complexity introduced by using complex and expensive middleware and server software like RDBMS. In this talk I’ll give an overview on how we use CQRS and event sourcing and how we were able to significantly improve our velocity and at the same time concentrate more on the business requirements and less on technical implementation details.</p>
</blockquote>
<p>See you there!</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/07/06/presenting-at-adnug-meeting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How we got rid of the database&#8211;part 6</title>
		<link>http://lostechies.com/gabrielschenker/2012/06/30/how-we-got-rid-of-the-databasepart-6/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/06/30/how-we-got-rid-of-the-databasepart-6/#comments</comments>
		<pubDate>Sun, 01 Jul 2012 03:37:18 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Event sourcing]]></category>
		<category><![CDATA[no-database]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/06/30/how-we-got-rid-of-the-databasepart-6/</guid>
		<description><![CDATA[In this series of posts I discuss how we do CQRS and event sourcing. One of our main goals was to reduce the overall complexity of our solution which ultimately led us to the point where we got rid of&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/06/30/how-we-got-rid-of-the-databasepart-6/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this series of posts I discuss how we do CQRS and event sourcing. One of our main goals was to reduce the overall complexity of our solution which ultimately led us to the point where we got rid of our database. Please see my previous posts for further details (<a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">part 1</a>, <a href="http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/">part 2</a>, <a href="http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/">part 3</a>, <a href="http://lostechies.com/gabrielschenker/2012/06/20/how-we-got-rid-of-the-databasepart-4/">part 4</a> and <a href="http://lostechies.com/gabrielschenker/2012/06/24/how-we-got-rid-of-the-databasepart-5/">part 5</a>).</p>
<p>In this post we will discuss how events generated by our aggregates are serialized and then stored in the event store. Remember, we do not use any database to store data and thus have to provide our own persistence mechanism.</p>
<p>Note: the code snippets presented in this post represents a <u>simplified</u> version of code found in <a href="http://lokad.github.com/lokad-cqrs/">Lokad.CQRS</a>. This code is used to show the <strong>core concepts</strong>.</p>
<h1>Serializing and deserializing an event</h1>
<p>Since we are not going to use a database to store our data we are now on our own. Let’s first choose a serialization format that suits our needs. What do we need?</p>
<ul>
<li>Serialization and deserialization should be fast </li>
<li>The serialized data should be as compact as possible</li>
<li>The serialization process should be tolerant for changes in the events, e.g. allow us to rename properties of the event or add new properties to the event</li>
</ul>
<p>It turns out that Google’s <a href="http://en.wikipedia.org/wiki/Protocol_Buffers">protocol buffer</a> format is the ideal choice. And luckily we find a <a href="http://nuget.org/packages/protobuf-net">Nuget</a> package which gives us an implementation of the serializer/deserializer for .NET.</p>
<p>Let’s define an interface that provides what we need</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image42.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb42.png" width="625" height="135"></a></p>
<p>We have a method <strong>SerializeEvent</strong> which accepts an event and returns the serialized event as array of bytes. Of course we then need the counterpart, which does the opposite. The method <strong>DeserializeEvent</strong> accepts an array of bytes and returns the deserialized event.</p>
<p>Now please note that the <strong>SerializeEvent</strong> method accepts any event that implements<strong> IEvent&lt;IIdentity&gt;</strong>. The serialization of the event is no problem, but to be able to deserialize the event we need to know the concrete type of the event we had previously serialized. Thus we need to somehow serialized the type or rather the contract name of the event together with the content of the event. This fact slightly complicates the whole process. But as you will see, it is still no rocket science involved. Each step is simple.</p>
<p>Lets first define a helper class <strong>Formatter</strong> which contains a contract name of an event and a delegate to serialize and another to deserialize this event</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image43.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb43.png" width="865" height="350"></a></p>
<p>As you can see, the serializer delegate takes an object and serializes it into a stream. The deserializer delegate takes a stream (containing the serialized event) and deserializes its content and returns it as object.</p>
<p>We want to create an instance of <strong>Formatter</strong> for each event that we have in our system. To get all events we can use code similar to this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image44.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb44.png" width="864" height="347"></a></p>
<p>The result will be our know event types. Note that line 18 will be evident in a minute.</p>
<p>The <strong>Formatter</strong> class introduced above is hosted by the <strong>EventSerializer</strong> class which is responsible for the effective event serialization/deserialization. We inject the known event types via constructor into this class. The EventSerializer takes these known types and creates two dictionaries out of it</p>
<ul>
<li>one that gives a formatter instance provided the event type and</li>
<li>the other gives the event type provided its (contract-) name</li>
</ul>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image45.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb45.png" width="1057" height="611"></a></p>
<p>We use the <strong>RuntimeTypeModel</strong> class of the p<a href="http://nuget.org/packages/protobuf-net">rotobuf-net</a> library to get a formatter (the instance that serializes/deserializes the event to an array of bytes). We also use an extension method <strong>GetContractName</strong> to get the contract name of the event type. It is defined as follows</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image46.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb46.png" width="727" height="158"></a></p>
<p>In the above method we take the namespace of the event from the [<strong>DataContract</strong>] attribute with which we have to decorate each event in order to make it serializable using the protocol buffer format (see our <a href="https://github.com/gnschenker/cqrs-introduction/blob/04a08ca289dcdcf41d7182662219c6fcbc620653/CqrsIntroduction/NewTaskScheduled.cs">NewTaskScheduled</a> event).</p>
<p>With all this preparation the actual serialization of the event is quite easy</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image47.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb47.png" width="850" height="345"></a></p>
<p>The method Serialize shown above takes an event <strong>instance</strong> and its <strong>type</strong> and serializes it into the given destination stream.</p>
<p>The deserialization is a two step process. First we have the contract name of the event and want to get the corresponding (event-) type</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image48.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb48.png" width="538" height="105"></a></p>
<p>Having this type we can deserialize the event</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image49.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb49.png" width="810" height="344"></a></p>
<p>The above method gets the stream from which it reads the serialized content of the event as well as the event type. The method returns the deserialized event (as object).</p>
<p>That was not so bad, wasn’t it? No magic or rocket science needed so far.</p>
<p>Ok, then we can now discuss the implementation of the <strong>IEventStreamer</strong> interface that I introduced at the beginning of this section. This class that we will now discuss not only writes the (serialized) content of the event to a stream but also some message contract information (or message header; where an event is a message).</p>
<p>First of all the EventStreamer class uses our EventSerializer</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image50.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb50.png" width="601" height="208"></a></p>
<p>Let’s now show the SerializeEvent method and then discuss the various parts of it.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image51.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb51.png" width="1095" height="673"></a></p>
<p>The method consists of 3 parts</p>
<ul>
<li>line 22-27: we use the event serializer class discussed above to serialize the event (=<strong>content</strong>)</li>
<li>line 29-36: we serialize a message contract which contains the event type name (=contract name), the length of the content as well as the content position (=<strong>messageContractBuffer</strong>) </li>
<li>line 38-45: we open a stream and first write the (serialized) message header contract into it (line 41). Then we append the messageContractBuffer to the stream and finally we append the content to the stream. Last we return the content of the stream (line 44)</li>
</ul>
<p>The <strong>DeserializeEvent</strong> method has to do the exact opposite of the above method. Let’s have a look at it</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image52.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb52.png" width="981" height="497"></a></p>
<p>On line 50 we create a memory stream around the buffer containing the serialized data. Then we have again our 3 steps</p>
<ul>
<li>line 52-53: read and deserialize the message header contract. From it we get the length of the message header that will be deserialized in step 2</li>
<li>line 55-58: read and deserialize the message header. From the previous step we know exactly how many bytes we have to read (<strong>header.HeaderBytes</strong>)</li>
<li>line 60-65: read and deserialize the event. From step two we know the length of the content and thus how many bytes we have to read (<strong>contract.ContentSize</strong>).</li>
</ul>
<p>To be complete I also have to show the <strong>MessageContract</strong> and the <strong>MessageHeaderContract</strong> classes. the <strong>MessageContract</strong> class contains information about the event (i.e. the event).</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image53.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb53.png" width="975" height="376"></a></p>
<p>We specifically need the contract name and the size of the event when it is serialized (the content length). Since the message contract is serialized by using protocol buffer we have decorated it with [<strong>DataMember</strong>] attributes.</p>
<p>The <strong>MessageHeaderContract</strong> contains information about the <strong>MessageContract</strong>, namely the length of the message contract when it is serialized. It also contains logic to write and read itself to a stream. We do not need protocol buffer here since it is trivial and of fixed length (just an <strong>long</strong> &#8211; which is 8 bytes long).</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image54.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb54.png" width="748" height="515"></a></p>
<p>With this we have the basis to be able to store events in the event store and subsequently read them back from the event store when needed. Let’s now look at the event store in detail.</p>
<h1>Saving events to the event store</h1>
<p>We want to create a file per aggregate instance which contains all events generated by this particular aggregate. Any new event is serialized into an array of bytes (as discussed in the previous section) and then appended to this file. With each event we also store </p>
<ul>
<li>the length of the serialized event (the data length), </li>
<li>the version of the event (starting from 1 for the first event in the life cycle of an aggregate) and </li>
<li>the hash code of the serialized event to recognize whether the data is corrupt or has been tampered. </li>
</ul>
<p>Let’s start and create a class that allows us to append an array of bytes (the serialized event) to the file which contains all events of an aggregate. This class has an <strong>Append</strong> method which accepts as parameter the said array of bytes.</p>
<p>Note that for write operations the file is opened in a mode that allows a single writer but many concurrent readers (line 16).</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image55.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb55.png" width="1071" height="572"></a></p>
<p>We use a helper class <font face="Courier New">TapeStreamSerializer</font> to do the actual write operation. Note that in this first draft we always write version = 1 to the file, no matter how many events we already have stored before.</p>
<p>Lets now look into the <font face="Courier New">TapeStreamSerializer</font> class. The <font face="Courier New">WriteRecord</font> method uses a binary serializer to write the record into a memory stream. We also use the <font face="Courier New">SHA1Managed</font> class of the .NET framework to calculate the hash code of the serialized event.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image56.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb56.png" width="1034" height="523"></a></p>
<p>On line 22 to 24 we create a header containing the length of the serialized event (the <strong>data</strong> array) and write it into the memory stream. Then on line 26 we write the actual data array into the memory stream and on lines 27 to 31 we add a footer section to the stream. The footer contains once again the length of the data array, the version of the event and the hash code computed from the data array.</p>
<p>Once we have everything written to the memory stream we append this data to the file (line 34) and we are done.</p>
<p>The above method uses two simple helper methods to write a 64bit integer (lines 23, 28 and 29) and a hash code (line 30) into the memory stream.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image57.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb57.png" width="851" height="325"></a></p>
<h1>Reading events from the event store</h1>
<p>We now want a way to read all existing events of a given aggregate from the event store. For this purpose we implement the <font face="Courier New">ReadRecords</font> method in our <font face="Courier New">FileTapeStream</font> class.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image58.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb58.png" width="852" height="370"></a></p>
<p>On line 42 we make sure we arrived at the end of the file and no more records can be retrieved. On line 45 we again use the helper class <font face="Courier New">TapeStreamSerializer</font> to do the actual reading of a single event record from the file.</p>
<p>The above method returns an array of <font face="Courier New">TapeRecord</font> items. A <font face="Courier New">TapeRecord</font> item contains the serialized event as well as its version</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image59.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb59.png" width="558" height="273"></a></p>
<p>Let’s now look into the <font face="Courier New">ReadRecord</font> method of the helper class. We basically have to revert the write operation we described earlier. First we try to locate/read and validate the header information (line 72-74). The header has a fixed length, thus we know exactly how many bytes to read. Then we read the data (lines 76 and 77). We know how many bytes we need to read since the data length was stored in the header. Finally we read and verify the footer which is also of fixed length (line 79-92). Specifically we make sure that the stored hash code corresponds to the ad-hoc calculated hash code of the data array (line 83-91).</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image60.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb60.png" width="919" height="641"></a></p>
<p>We use the following helper method to read a 64bit integer</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image61.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb61.png" width="570" height="177"></a></p>
<p>and this one to read the hash code</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image62.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb62.png" width="821" height="184"></a></p>
<p>and finally this one to read and verify a specific signature like e.g. ‘header start’ or ‘footer end’.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image63.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb63.png" width="923" height="349"></a></p>
<h1>Summary</h1>
<p>In this post we discussed in detail how events generated by aggregates are serialized and the appended to the event store. I also showed how those serialized events can be read from the event store.</p>
<p>In my next post I will discuss how we can integrate this code into our sample application. Stay tuned.</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/06/30/how-we-got-rid-of-the-databasepart-6/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>How we got rid of the database&#8211;part 5</title>
		<link>http://lostechies.com/gabrielschenker/2012/06/24/how-we-got-rid-of-the-databasepart-5/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/06/24/how-we-got-rid-of-the-databasepart-5/#comments</comments>
		<pubDate>Sun, 24 Jun 2012 23:35:29 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Event sourcing]]></category>
		<category><![CDATA[no-database]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/06/24/how-we-got-rid-of-the-databasepart-5/</guid>
		<description><![CDATA[Preface In our company we were looking for a way to radically simplify the way we implement our enterprise software. We wanted to get rid of accidental complexity introduced by using complex and expensive middleware and server software like RDBMS.&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/06/24/how-we-got-rid-of-the-databasepart-5/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h1>Preface</h1>
<p>In our company we were looking for a way to radically simplify the way we implement our enterprise software. We wanted to get rid of accidental complexity introduced by using complex and expensive middleware and server software like RDBMS.</p>
<p>In <a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">part 1</a>, <a href="http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/">part 2</a> and <a href="http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/">part 3</a> of this series I introduced some of the core elements of our CQRS/ES architecture. In <a href="http://lostechies.com/gabrielschenker/2012/06/20/how-we-got-rid-of-the-databasepart-4/">part 4</a> I discussed some of the questions that readers and coworkers have when confronted for the first time with the ideas of command-query-responsibility-segregation (CQRS) and event sourcing (ES). </p>
<h1>Tying it together</h1>
<p>As promised in <a href="http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/">part 3</a> of this series I’ll try to bring everything together in this post. From <a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">part 1</a> (the magic triangle) we know that the client sends commands to the domain. Lets have a look at what happens here</p>
<p>The Silverlight client creates a command and sends it via a WCF service to the server. The WCF service on the service side forwards the command to a <strong>command dispatcher</strong> which in turn uses the <strong>IoC container</strong> to resolve the command handler that can handle this command. There can only be exactly one command handler per command registered in the IoC container. This is a direct consequence of the fact that a command always must have a single target. If no command handler is found, or more that one command handler for this particular command exists then this is a fatal error.</p>
<p>The command dispatcher then forwards the command to the <strong>command handler</strong>. In our system the command handler is implemented as a chain of responsibilities (also called a pipeline).</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image24.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb24.png" width="678" height="286"></a></p>
<p>When the command enters the pipeline in the first step we test whether it would violate any business rule. If yes then the execution is aborted and the command result type is set to <strong>ValidationFailed</strong> and the violated business rules (text messages) are returned.</p>
<p>In a second step we test whether this particular command needs an electronic signature (ESIG) and if yes we verify that a valid ESIG is provided. Again, the command execution is aborted if the ESIG is missing or wrong and an error message is returned to the client.</p>
<p>There are more steps in our system which lay outside of the scope of this post.</p>
<p>Finally, if everything is fine so far the command arrives at step <strong>n</strong>, the command execution action. Here the command is executed. In our case the command is forwarded to the <strong>aggregate factory</strong>. The aggregate factory executes the following tasks</p>
<ul>
<li>analyze the incoming command and determine which <strong>aggregate instance</strong> the command targets.
<li>load all existing events for this particular aggregate instance from the <strong>event store</strong>.
<li>Create a new instance of the aggregate and re-hydrate the aggregate with the events loaded in the previous step
<li>forward the command to the aggregate instance</li>
</ul>
<h1>Contract</h1>
<p>Before I can continue with code I have to introduce a couple of contracts (interfaces) that we use in our infrastructure to make the code as simple as possible.</p>
<p>First of all we recognize that every command or event that we deal with in our system is a message. Thus we introduce a message interface. Since the interface <font face="Courier New">IMessage</font> is already used by other code (e.g. messaging system) we use <font face="Courier New">ICqrsMessage</font> as the base interface.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image25.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb25.png" width="389" height="45"></a></p>
<p>It is just an empty (marker) interface. But now we want to distinguish commands and events and we introduce the following two contracts</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image26.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb26.png" width="623" height="127"></a></p>
<p>and</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image27.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb27.png" width="602" height="134"></a></p>
<p>It is important to note that both interfaces are <a href="http://msdn.microsoft.com/en-us/library/dd799517.aspx">covariant</a> (out) in the generic parameter <font face="Courier New">TIdentity</font>. This makes it possible to cast an <font face="Courier New">ICommand&lt;Foo&gt;</font> to an <font face="Courier New">ICommand&lt;IIdentity&gt;</font> if <font face="Courier New">Foo</font> implements <font face="Courier New">IIdentity</font>. </p>
<p>Finally we have the interface which all identities (IDs) used in our system implement</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image28.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb28.png" width="311" height="107"></a></p>
<p>Having introduced these interfaces (or contracts) we can now continue to show the aggregate factory. The command execution action gets the aggregate factory injected</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image29.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb29.png" width="849" height="349"></a></p>
<p>here the interface that each command action implements is simple and look like this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image30.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb30.png" width="470" height="109"></a></p>
<p>note that the Handle method is a void method. A command execution never returns data in CQRS.</p>
<p>In order to make our code compile we need to adjust the definition of the <strong>ScheduleNewTask</strong> command and the <strong>TaskId</strong> identity that we introduced earlier. The <strong>TaskId</strong> is an identity and needs to implement the interface <strong>IIdentity</strong></p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image31.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb31.png" width="378" height="189"></a></p>
<p>and the command needs to implement the command message interface</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image32.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb32.png" width="543" height="90"></a></p>
<p>Now we should be able to compile and can continue with the implementation of the aggregate factory. We have this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image33.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb33.png" width="798" height="618"></a></p>
<p>On line 13 the ID of the aggregate that is target of the command is determined. Since we use typed IDs throughout the system the ID not only gives us the value but also it tells us which type of aggregate it targets (Task aggregate versus e.g. Animal aggregate).</p>
<p>On line 14 we load the events from the event store that have been previously stored for the aggregate with the given ID. This collection can be empty if the command is the first command in the life cycle of the aggregate.</p>
<p>On line 15 we get the observer that later on is injected into the aggregate. The observer is an infrastructure function that takes the event(s) that the aggregate triggers and handles them. Specifically the observer stores the event(s) in the event store and then publishes them asynchronously.</p>
<p>On line 17 we determine whether the target is a task or not. If yes, we create the state of the task from the events (line 20) and then we create the aggregate and inject the state and the observer to it (line 21). Finally we forward the command to the aggregate for execution (line 22) and return (line 23).</p>
<p>If we have other aggregate types in our system we repeat line 17 through 24 for each aggregate type, e.g.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image34.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb34.png" width="583" height="200"></a></p>
<p>For the moment I do not want to discuss the details of the two methods LoadEventsFromEventSource(…) and GetObserver(). I will explain the details of these in detail in a future post. Suffice to say that the observer has the following signature</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image35.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb35.png" width="399" height="34"></a></p>
<p>It’s an action that has one input parameter, the event that it handles. We have learned above that each event is an <font face="Courier New">IEvent&lt;IIdentity&gt;&gt;</font>.</p>
<p>Let’s now revisit our Task aggregate and aggregate state that we introduced in an earlier post. Let’s start with the state.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image36.png"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 24px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb36.png" width="770" height="179"></a></p>
<p>the state has a constructor with one parameter, the collection of events injected by the aggregate factory. The state re-hydrates itself with these events (see the <font face="Courier New">foreach</font> loop).</p>
<p>The aggregate on the other hand gets the state and the observer injected</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image37.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb37.png" width="969" height="256"></a></p>
<p>The aggregate also implements the Execute method which is called by the aggregate factory</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image38.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb38.png" width="555" height="113"></a></p>
<p>The <strong>RedirectToWhen</strong> is a static helper class with uses reflection to determine to which <strong>When</strong> method of the aggregate the command has to be forwarded. The code is very simple due to the fact that we use the convention to call all our methods on an aggregate that execute a command ‘When’ and that each of these methods has one single parameter, that is the command they handle.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image39.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb39.png" width="907" height="298"></a></p>
<p>Of course, in our production system the code looks slightly more complex since we cache the meta data to avoid repetitive use of (slow) reflection. But this series of posts it about the <strong>principles</strong> and not so much about technical details!</p>
<p>We do not have to forget to make our events implement to events contract, e.g.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image40.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb40.png" width="539" height="99"></a></p>
<p>That’s it, simple, isn’t it? Well you might disagree with me here… but the apparent complexity stems from the fact that the whole process had so many steps. Each step in isolation is really really simple, agreed? There is absolutely no “magic” or “rocket science” involved. We need no expensive tools of frameworks so far to achieve our goals. And that is one the essence of this series of posts: we can achieve our goals by using simple code and leaving alone expensive middleware or server software.</p>
<p>I have to admit, so far there is a pretty important piece missing in the puzzle. It is the queuing system that we use. But this will be the target of my next post.</p>
<h1>Look back</h1>
<p>Let me try to visualize once again how a command flows through the system</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image41.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb41.png" width="1079" height="559"></a></p>
<h1>Code</h1>
<p>You can find the sample code on <a href="https://github.com/gnschenker/cqrs-introduction">GitHub</a>.</p>
<p>Till next time!</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/06/24/how-we-got-rid-of-the-databasepart-5/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>How we got rid of the database&#8211;part 4</title>
		<link>http://lostechies.com/gabrielschenker/2012/06/20/how-we-got-rid-of-the-databasepart-4/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/06/20/how-we-got-rid-of-the-databasepart-4/#comments</comments>
		<pubDate>Thu, 21 Jun 2012 03:31:33 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Event sourcing]]></category>
		<category><![CDATA[no-database]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/06/20/how-we-got-rid-of-the-databasepart-4/</guid>
		<description><![CDATA[This is the fourth episode of a series of posts about how we do CQRS and event sourcing. To my (positive) surprise the first three parts (part 1, part 2, part3) have caused quite some discussion amongst the readers. Since&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/06/20/how-we-got-rid-of-the-databasepart-4/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This is the fourth episode of a series of posts about how we do CQRS and event sourcing. To my (positive) surprise the first three parts (<a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">part 1</a>, <a href="http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/">part 2</a>, <a href="http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/">part3</a>) have caused quite some discussion amongst the readers. Since I constantly have discussions about the very same topics with my team members and external co-workers I decided to dedicate this fourth part to answer some of those topics.</p>
<h1>Eventual consistency</h1>
<p>Full consistency (also called <a href="http://en.wikipedia.org/wiki/Immediate_consistency">immediate consistency</a>) is overrated, period!</p>
<p>When I have some doubt about whether something “is right” or “can possibly work” then I try to find analogies in the real world. And it turns out that when looking for analogies in the business world where <a href="http://en.wikipedia.org/wiki/Eventual_consistency">eventual consistency</a> applies then we find those everywhere! Even in scenarios which are &#8220;business-critical” or “life-threatening”. But then if real world works in an eventual consistent way, why are we tying to achieve full consistency at all cost in our <a href="http://en.wikipedia.org/wiki/Line_of_business">LOB</a> applications?</p>
<p>Let me give some real world samples of eventual consistency:</p>
<ul>
<li>you are ordering a book at an online book store. After you have checked out and your payment by credit card has been accepted the application tells you that your order has been placed and will be shipped asap. At the moment you receive the confirmation the online store has not yet reserved the book for you nor is it guaranteed that this very book is on stock and if not that it is still available from the publisher. It some times happens that the book is not on stock and thus the delivery is delayed. In this case the online shop will notify you by sending an email. If the book is not available any more then the shop might offer you alternatives and compensate you with a special bonus.</li>
<li>The unit price of some share traded at the stock exchange changes. This change in price is appearing on the stock tickers only with a certain (short?) delay; maybe a couple of seconds or even minutes.</li>
<li>You order a coffee at your local coffee shop. The cashier forwards your order to the barista immediately and then takes your credit card to check out. To check the credit card and approve the payment might take a while. In the mean time the barista has already started to brew your coffee. It turns out that your credit card is invalid and you have no alternative payment method. The coffee cannot be undone and as a “compensating action” the barista gets the order to throw the coffee away.</li>
<li>A terrible accident happens. You call 911 and explain that there is a person having life threatening injuries. The person answering the call promises that EMS and fire fighters will be there as quickly as they can. At the moment you end the call the fire fighters and EMS have not yet been sent on their way nor are any surgeons put on hold that will take care of the injured person. All this is organized asynchronously. When the injured person finally arrives at the hospital he gets treated as soon as a team&nbsp; of surgeons/doctors is available. The patient might even have to wait for some time if no doctor is available.</li>
</ul>
<p>All these samples are not made up by me but are very real and happen daily! Thus I can assure you that we can develop applications that are eventual consistent and at the same time happily fulfill all business requirements. We just need to address the problem a little bit different. A recommendation is to design your application in a task oriented way. Each task should be very focused and well defined. Avoid having “fluffy” or vague use cases.</p>
<h1>After a successful transaction I need to refresh/reload the screen</h1>
<p>With CQRS and ES this is not possible since the read model is only eventually consistent with the domain model. The delay can be very short (a couple of milliseconds) or quite long (seconds to minutes) depending on the type of transaction. </p>
<p>But this is not a problem! Why not?</p>
<p>We design our application in a way that commands sent to the domain model have a high probability to succeed. This can be achieved by e.g. pre-validating the commands prior to sending them to the corresponding aggregate of the domain model. Assuming now that the command succeeds we can update the screen to reflect the new state without reloading everything from the database/data source. We already have all the necessary data at hand, otherwise we would not have been able to create and send the command in the first place. As a sample: if we send the command “PublishTask” to the domain model and the domain model sends back an ACK then we can set the status of the corresponding task on the screen to “published” without querying the database.</p>
<p>But what about if it takes a long time (seconds to minutes) until the read model is in sync with the domain model after a transaction has been executed?</p>
<p>In this case it is often the case that the person that triggers the transaction is not the same person/user that needs to see the result of the transaction (other than it has been completed successfully). As a sample take again our online book store. The manager decides to reduce the unit price of all books in stock by 10% to better compete with the competitors. Now who is most interested to see those changes in price? It is not the manager since he knows what he has just done. He does not have to browse through the list of all books to have a confirmation of the change. But the clients of course benefit from this price reduction. But it doesn’t matter if the price change is only reflected in the online catalog minutes after the manager has executed the price reduction.</p>
<h1>Why not use a database for the event store or the read model</h1>
<p>Well, first of all, please read the title of my series of blog posts: “How we got rid of the database”. This series is not only about the theory behind CQRS and event sourcing but also about the concrete application of an architecture based on CQRS/ES as well as our goal to reduce the overall complexity of the system. If we can achieve our goals with simpler means why not do it. Why shouldn’t we strive for simplicity when solving problems and achieving solutions?</p>
<p>It turned out that we did not leverage nor need all the features an RDBMS a la Oracle or SQL Server could offer. It was as if I took a truck when a bicycle would be sufficient or search for a calculator to calculate 5 + 5, instead of using my brain.</p>
<p>What we need when doing CQRS is </p>
<ul>
<li>in the domain model: an efficient way to access a stream of events identified by the unique ID or the aggregate instance which produced the events.<br />Solution –&gt; we serialize all events as they occur into an append only file whose full name is a codified version of the ID.</li>
<li>in the read model: an efficient way of accessing (denormalized) instances (=the current state) of view models by their respective unique ID in addition to (secondary) indices that are e.g. serialized hash tables (or dictionaries). <em>I will talk more about indices in a future post.</em></li>
</ul>
<p>All that and more can be easily achieved by avoiding any database (relational or document) and just using some simple code that can read and (atomically) write single files.</p>
<h1>How can we enforce referential integrity?</h1>
<p>We cannot, at least not at the data level!</p>
<p>Integrity of data is solely guaranteed by our application. It is the responsibility of the application to maintain integrity and consistency of the data. </p>
<p>One important aspect in this regard is that we eliminate the concept of “delete” from our vocabulary (I know, I know, there are always exceptions…). In the business world the concept of “delete” does not exists</p>
<ul>
<li>we do not delete an employee but rather release him</li>
<li>we do not delete an order but rather cancel it</li>
<li>we do not delete a coffee in a coffee shop but rather discard it (the ingredients have already been used)</li>
<li>an accountant does not delete a wrong journal entry but rather compensates it with a journal correction</li>
</ul>
<p>If ever we have to “delete” an item we do not physically delete it but mark it “as deleted”.</p>
<p>But if we never physically delete anything from our data store we do not run into problems like “orphaned children” or “missing references”.</p>
<p>As an added benefit we are better prepared for any audit, since no data is ever lost.</p>
<h1>What about backup?</h1>
<p>We only ever need to make sure that our event store is backed up. We really(!) don’t care about the read model since it can always be rebuilt from the event store in case of catastrophic failure. And if this is not sufficient, we can always create the read model redundant; we just send the events (which are used to build the projections) to at least two different servers.</p>
<p>The event store on the other hand is just a folder full of files and can be backed up by any decent backup program out in the market. No special and expensive software needed!</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/06/20/how-we-got-rid-of-the-databasepart-4/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How we got rid of the database&#8211;part 3</title>
		<link>http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/#comments</comments>
		<pubDate>Tue, 19 Jun 2012 03:52:18 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/</guid>
		<description><![CDATA[In my last two posts (part 1 and part 2) I described how a command that is sent from the client is handled by an aggregate of the domain model. I also discussed how the aggregate, when executing the command,&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In my last two posts (<a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">part 1</a> and <a href="http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/">part 2</a>) I described how a command that is sent from the client is handled by an aggregate of the domain model. I also discussed how the aggregate, when executing the command, raises an event which is then stored in the event store and furthermore published asynchronously by the infrastructure.</p>
<p>In this post I want to show how these published events can be used by observers (or projection generators) to create the read model.</p>
<h1>Querying</h1>
<p>When the user navigates to a screen the client sends a query to the read model. The query handler in the read model collects the requested data from the projections that make up the read model and returns this data to the client. The client never sends queries to the domain. The domain model is not designed to accept queries and return data. The domain model is optimized for write operations exclusively.</p>
<p>Assuming the user is navigating to the screen where existing tasks can be edited the query that the client triggers could be</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image13.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb13.png" width="421" height="116"></a></p>
<p>and the data returned by the query handler would look like this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image14.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb14.png" width="525" height="234"></a></p>
<p>where</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image15.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb15.png" width="418" height="133"></a></p>
<p>contains the full name and id of the candidates that are assigned to this task and</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image16.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb16.png" width="544" height="157"></a></p>
<p>contains all the details of an animal that is target of the task.</p>
<p>Where does this data come from I hear you ask… Well, that’s the topic I’ll discuss next.</p>
<h1>Generating the read model</h1>
<p>Whenever we design a new screen we need data to display on this screen. Thus we define projection(s) that are tailored in a way that best suits our needs. Ideally we want to create a projection that allows us to get all the data we want with one single read operation to the data store. That is the ideal, but in reality that is not always possible and thus we just want to state this principle: design the projections in such a way that we can retrieve the data needed for a screen using the minimal amount of read operations, ideally one operation only.</p>
<p>This principle requires as a consequence that we store our data in a highly de-normalized way. We regard data duplication in the read model as a necessary consequence and do <strong>not</strong> try to avoid it. Storage space is extremely cheap nowadays.</p>
<p>Since we are not using an RDBMS to store our read model the projections do not have to be “flat”. We can projections that are made of object graphs.</p>
<p>A first approach would thus consequently be to define a projection that looks somewhat similar to the query response object, that we define above. Let’s do so</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image17.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb17.png" width="525" height="260"></a></p>
<p>Please note that I use the typed Id (TaskId) introduced in <a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">part 1</a> in my view.</p>
<p>Now we need to define a class, that creates the task details projection for us. We want to make the implementation of this class as simple as possible. The class should be a POCO and only depend on a writer object</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image18.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb18.png" width="896" height="276"></a></p>
<p>The writer that we inject into our projection generator class is responsible to physically write our views into the data store. In our case the data store will be the file system but it could be as well a table in an RDBMS or a document database or a <a href="http://lucene.apache.org/core/">Lucene</a> index. From the perspective of this generator class it doesn’t really matter what type of data store it is.</p>
<p>The definition of the <a href="https://github.com/Lokad/lokad-cqrs/blob/lean/Core/Lokad.Cqrs.Portable/AtomicStorage/IAtomicWriter.cs">IAtomicWriter</a> interface is very simple</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image19.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb19.png" width="1012" height="108"></a></p>
<p>For convenience we can then write some extension methods to this interface</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image20.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 0px 24px; 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://lostechies.com/gabrielschenker/files/2012/06/image_thumb20.png" width="1396" height="495"></a></p>
<p>Why not add these methods to the interface directly instead of writing extension methods you might ask. The reason is that we should always try to keep our interfaces as simple as possible such as that our code remains more composable and less coupled.</p>
<p>Having defined the interface and also added the above extension methods we can now continue to implement our projection generator class.</p>
<p>Each projection is created by events. All data that make up a projection are provided by events. In our sample the first event in the life cycle of a task is the NewTaskScheduled event that we defined in part 1. Let’s add code to handle this event in our projection generator</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image21.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb21.png" width="930" height="525"></a></p>
<p>We use the same convention as we already introduced with the aggregate: we call all our methods When. Each of those methods has exactly one parameter, the event that it handles. This convention makes it easier for us to later on write some tools around our read model. I will discuss this in detail in a later post.</p>
<p>Note that we have used the Add (extension-) method of the writer since at the time when the <strong>NewTaskScheduled</strong> event happens the corresponding view does not yet exists.</p>
<p>Later on other events of interest might be published by the domain and our projection generator can listen to them. Let’s take as a sample the <strong>TaskPublished</strong> event. We add the following code to the projection generator</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image22.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb22.png" width="892" height="109"></a></p>
<p>very simple, isn’t it?</p>
<p>The resulting file on the file system could look similar to this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image23.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb23.png" width="825" height="232"></a></p>
<p>(remember that we are using JSON serialization).</p>
<p>In the next post I’ll try to wire up all pieces that we have defined so far such as that we can run a little end-to-end demo. Stay tuned…</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/06/18/how-we-got-rid-of-the-databasepart-3/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>How we got rid of the database&#8211;part 2</title>
		<link>http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/#comments</comments>
		<pubDate>Thu, 14 Jun 2012 03:33:01 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Event sourcing]]></category>
		<category><![CDATA[no-database]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/</guid>
		<description><![CDATA[A quick introductory sample – continued In part one of this series I started to explain what we do, when e.g. a user (in the particular case a principal investigator) wants to schedule a new task. In this case a&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h1>A quick introductory sample – continued</h1>
<p>In <a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">part one</a> of this series I started to explain what we do, when e.g. a user (in the particular case a principal investigator) wants to schedule a new task. In this case a command is sent from the client (the user interface of the application) to the domain. The command is handled by an aggregate that is part of the domain. The aggregate first checks whether the command violates any invariants. If not the aggregate converts the command into an event and forwards this event to an external observer. The observer is injected into the aggregate by the infrastructure during its creation. The observer accepts the event and stores it in the so called event store.</p>
<p>It is important to realize, that once the event is stored we can commit the transaction and we’re done. What(?) &#8211; can I hear you say now; don’t we have to save the aggregate too?</p>
<p>No, there is no need to save (the current state of) the aggregate; saving the event is enough. Since we store all events that an aggregate ever raises over time we have the full history at hand about what exactly happened to the aggregate. Whenever we want to know the current state of an aggregate we can just re-create the aggregate from scratch and re-apply all events that we have stored for this particular instance.</p>
<p>We can extend the diagram that I first presented in my <a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">last post</a>&nbsp; as follows</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image9.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 0px 24px; 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://lostechies.com/gabrielschenker/files/2012/06/image_thumb9.png" width="610" height="454"></a></p>
<p>If we now look at just the events of one single task instance we would have something like this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image10.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb10.png" width="495" height="497"></a></p>
<p>If we create a new task aggregate and apply all the n events that we find in the event store then the result is a task aggregate that has been completed.</p>
<p>It is important to know that new events are always only appended to the stream of existing events. Never do we delete or modify an already existing event! This is equivalent to the transaction journal of an accountant. The accountant always only adds new journal entries. He never modifies an existing one nor does he ever delete a previous entry.</p>
<p>But how do we store these events? There are various possibilities, we could serialize the event and store it in a column of type BLOB (binary large object) or CLOB (character large object) of a table in a relational database. We would also need to have a column in this table where we can store the ID of the aggregate.</p>
<p>We could as well store the (serialized) event in a document database or in a key value store (e.g. Hashtable).</p>
<p>But wait a second…, if we serialize the event why can we not just store it directly in the file system? Why do we need such a thing as a database which only adds complexity to the system (it is always funny to point out that a database ultimately stores the data in the file system too).</p>
<p>Let’s then define the boundary conditions:</p>
<ul>
<li>we serialize the events using <em>Google protocol buffer</em> format</li>
<li>we create one <em>file</em> per aggregate instance; this file contains all events of the particular instance</li>
<li>any new incoming event is always <em>appended</em> at the end of the corresponding file</li>
</ul>
<p>Advantages</p>
<ul>
<li>Google protocol buffer </li>
<ul>
<li>produces very compact output</li>
<li>is one of the fastest ways to serialize an object (-graph)</li>
<li>is relatively tolerant to changes in the event signature (we can change names of properties of add new properties without producing version conflicts)</li>
</ul>
<li>since we usually only operate onto a single aggregate per transaction we need only one read operation to get all events to re-construct the corresponding aggregate</li>
<li>append operations to a file are fast and simple</li>
</ul>
<p>Disadvantages</p>
<ul>
<li>we have to decorate our events with attributes to make them serializable using Google protocol buffer</li>
</ul>
<p>If we are using protbuf-net library, which is available as a nuget package, to serialize our events then we can use the standard DataContractAttribute and DataMemberAttribute to decorate our events</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image11.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://lostechies.com/gabrielschenker/files/2012/06/image_thumb11.png" width="761" height="261"></a></p>
<p>Note that the <em>order</em> of the properties and there <em>data type</em> is important but not their name.</p>
<p>Assuming we have our event serialized and it is available as an array of bytes we can use the following code to append it to an existing file</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image12.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 0px 24px; 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://lostechies.com/gabrielschenker/files/2012/06/image_thumb12.png" width="623" height="780"></a></p>
<p>The code is a simplified version of the productive code we use in our application. What is missing is the code that&nbsp; also stores the length of the data buffer to append as well as its version. Whilst incomplete the above code snippet nevertheless shows that there is no magic needed and certainly no expensive database required to save (serialized) events to the file system.</p>
<p>Since we did not want to reinvent the wheel we chose to use the <a href="http://lokad.github.com/lokad-cqrs/">Lokad.CQRS</a> “framework”. If you are interested in the full code just browse through the <a href="https://github.com/Lokad/lokad-cqrs/blob/lean/Core/Lokad.Cqrs.Portable/TapeStorage/FileTapeStream.cs">FileTapeStream</a> class.</p>
<p>Loading the stream of events from the very same file is equally “easy” and the implementation can be found in the same class.</p>
<p>In my next post I will talk about how we can <em>query</em> the data. Stay tuned…</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>How we got rid of the database</title>
		<link>http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/</link>
		<comments>http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/#comments</comments>
		<pubDate>Wed, 13 Jun 2012 03:23:15 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[CQRS]]></category>
		<category><![CDATA[Event sourcing]]></category>
		<category><![CDATA[no-database]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/</guid>
		<description><![CDATA[A quick introductory sample – Part 1 I want to write a series of posts which describe in detail how we do things in my company. What architecture do we use, which patterns do we follow, and more specifically, how&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h1>A quick introductory sample – Part 1</h1>
<p>I want to write a series of posts which describe in detail how we do things in my company. What architecture do we use, which patterns do we follow, and more specifically, how do we implement those features. I invite you to join me on this journey…</p>
<p>Note: the core ideas follow the various examples of <a href="http://codebetter.com/gregyoung/">Greg Young</a>, <a href="http://abdullin.com/">Rinat Abdullin</a>, et al.</p>
<p>It all start with a simple picture</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image.png"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 24px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb.png" width="608" height="428"></a></p>
<p>A similar image was used by Greg Young in his <a href="http://www.viddler.com/v/dc528842">6-hour video</a> about DDD, CQRS and Event Sourcing. This image nicely shows us what is happening in an application following CQRS. The client sends commands to the domain (-model). The domain either accepts a command and hence sends ACK (=acknowledged) or refuses it altogether and sends a NACK (not acknowledged) back to the client. If the domain model accepts a command then it produces an event as a result of the execution of the command. The event is consumed by the read model. The read model in turn is used by the client to get its data in the form of DTOs.</p>
<p>Lets write some code to demonstrate how we do things. I will start from scratch, that is from a blank solution, and incrementally develop the&nbsp; code we need to fulfill the requirements.</p>
<p>But first we have to give a somewhat realistic user story to start with:</p>
<blockquote><p>As a principal investigator I want to schedule a new task. The task has a group of animals as targets upon which the executor of the task acts. The task is addressed to a group of crew members from whom one can chose to execute the task…</p>
</blockquote>
<p>Evidently a user (= the principal investigator) wants to schedule a new task. This is done by the system by sending a command (ScheduleNewTask) to the domain. After discussion with the domain expert it is clear that the command should look like this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image1.png"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 24px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb1.png" width="532" height="233"></a></p>
<p>The name of the command gives us the context. From it it is clear what the intent is. The command name should thus be unambiguous.</p>
<p>The command is a DTO and its payload usually contains the minimal data necessary to successfully fulfill the request. In our case these are</p>
<ul>
<li>The (client side generated) unique ID of the new task. Note, that we do not just use a simple type for the ID like int or Guid but rather a class TaskId.
<li>The name of the task (in combination with the due date this should be unique)
<li>A description of what the executing person is supposed to do
<li>The date (and time) when the task is due
<li>A list of IDs of the candidates (staff) that can choose to accept (and execute) the task
<li>A list of IDs of the animals which this task targets.</li>
</ul>
<p>Now let’s look a little bit closer at our ID. The code to is looks similar to this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image2.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb2.png" width="742" height="368"></a></p>
<p>Evidently the “real” id is of type Guid and there is also an associated Tag (=”task”). The tag is mainly used to output a human readable version of the id. For this purpose the ToString() method is overriden. Having an ID of type TaskId for a task and e.g. StaffId for a staff makes those IDs distinguishable. Has we only used Guids for both type of IDs we wouldn’t have been able to tell which one belongs to which type of entity.</p>
<p>The command is targeting the domain. Inside the domain there is an aggregate which handles the command. We call this aggregate TaskAggregate.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image3.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb3.png" width="451" height="186"></a></p>
<p>To make things simple and discoverable we use some simple conventions. In the case of an aggregate we call the method who handles a command When and we always pass exactly one parameter to this method – the command itself. This results in very readable code (at least regarding the method signatures).</p>
<p>The method first makes sure that the command doesn’t violate the aggregate’s invariants, e.g. like this</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image4.png"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 24px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb4.png" width="852" height="311"></a></p>
<p>In the above code snippet the aggregate uses its internal state to determine whether this command is the very first command (Version = 0) or not. If not then we have a problem since the system wants to re-create an already existing task instance; which of course we do not allow.</p>
<p>Once the invariants are guaranteed the aggregate transforms the command into an event. The event tells any observer(s) that the corresponding command has been successfully executed. The name of the event is in past tense, i.e.</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image5.png"><img style="background-image: none; border-right-width: 0px; margin: 0px 0px 24px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb5.png" width="527" height="236"></a></p>
<p>In our case we have a one-to-one matching of the command’s payload with the event payload. This one-to-one matching is often the case but by no means the only possibility. Often an event can be enriched by additional data if needed by any observer.</p>
<p>It is very important that we always name our events in past tense. This makes it clear that an event is something that has already happened and cannot be undone!</p>
<p>Now lets look again at the aggregate. We extend the method’s code as follows</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image6.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb6.png" width="800" height="402"></a></p>
<p>Note that once we have created the event from the command, we are call a private helper method Apply. The method Apply forwards the event to the aggregate’s state and also to an external observer</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image7.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb7.png" width="387" height="130"></a></p>
<p>The initial aggregate state and the external observer are injected by the infrastructure into the aggregate at its creation time</p>
<p><a href="http://lostechies.com/gabrielschenker/files/2012/06/image8.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lostechies.com/gabrielschenker/files/2012/06/image_thumb8.png" width="811" height="205"></a></p>
<p>The (external) observer injected by the infrastructure will take this event, store it in the event store and forward it to our queuing system which eventually will dispatch it asynchronously to any registered consumer of the event. Typical consumers are the writers who create and update the read model.</p>
<p>In <a href="http://lostechies.com/gabrielschenker/2012/06/13/how-we-got-rid-of-the-databasepart-2/">part 2</a> we will discuss some more details about how events are stored in the event store. Till then, have a great time.</p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2012/06/12/how-we-got-rid-of-the-database/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Win Free Copies of NHibernate 3 Beginner&#8217;s Guide</title>
		<link>http://lostechies.com/gabrielschenker/2011/12/12/win-free-copies-of-nhibernate-3-beginners-guide/</link>
		<comments>http://lostechies.com/gabrielschenker/2011/12/12/win-free-copies-of-nhibernate-3-beginners-guide/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 14:07:31 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[book]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[misc]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2011/12/12/win-free-copies-of-nhibernate-3-beginners-guide/</guid>
		<description><![CDATA[Readers would be pleased to know that I have teamed up with Packt Publishing and we are organizing a Giveaway especially for you and three lucky winners stand a chance to win a copy of Keep reading to find out&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2011/12/12/win-free-copies-of-nhibernate-3-beginners-guide/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Readers would be pleased to know that I have teamed up with Packt Publishing and we are organizing a Giveaway especially for you and three lucky winners stand a chance to win a copy of Keep reading to find out how you can be one of the Lucky Winner.<br />
<h3>Overview of Nhibernate 3 Beginner&#8217;s Guide</h3>
<p><a href="http://lostechies.com/gabrielschenker/files/2011/12/clip_image002.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 0px 24px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://lostechies.com/gabrielschenker/files/2011/12/clip_image002_thumb.jpg" width="227" height="244"></a>
<p>· Clear, precise step-by-step directions to get you up and running quickly
<p>· Test, profile, and monitor data access to tune the performance and make your applications fly
<p>· Reduce hours of application development time and get better application architecture and performance
<p>Read more about this book and download free <a href="http://www.packtpub.com/sites/default/files/6020OS-Chapter-3-Creating-a-%20Model.pdf?utm_source=packtpub&amp;utm_medium=free&amp;utm_campaign=pdf">Sample Chapter</a><b></b>
<p><b>How to Enter?</b>
<p>All you need to do is head on over to the <a href="http://www.packtpub.com/nhibernate-3-beginners-guide/book">book page</a> and look through the product description of this book and drop a line via the <b>comments below to let us know what interests you the most about this book</b>. It’s that simple
<p>Product description for NHibernate book: http://www.packtpub.com/nhibernate-3-beginners-guide/book
<p>Winners from the U.S. and Europe can either choose a physical copy of the book or the eBook. Users from other locales are limited to the eBook only.
<p><strong>Deadline</strong>
<p><strong><br /></strong><b>The contest will close on 30/12/11 PT. Winners will be contacted by email, so be sure to use your real email address when you comment!</b>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2011/12/12/win-free-copies-of-nhibernate-3-beginners-guide/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>BUILD conference&#8211;day 3</title>
		<link>http://lostechies.com/gabrielschenker/2011/09/16/build-conferenceday-3/</link>
		<comments>http://lostechies.com/gabrielschenker/2011/09/16/build-conferenceday-3/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 15:58:27 +0000</pubDate>
		<dc:creator>Gabriel Schenker</dc:creator>
				<category><![CDATA[BUILD]]></category>
		<category><![CDATA[Conference]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://lostechies.com/gabrielschenker/2011/09/16/build-conferenceday-3/</guid>
		<description><![CDATA[The future of C# Yesterday Anders Hejlsberg gave a talk about future directions of C# and VB.Net. He started with look back and then immediately dive into the new features of C# 5.0 which is part of VS 2011 and&#160;&#8230; <a href="http://lostechies.com/gabrielschenker/2011/09/16/build-conferenceday-3/">Continue&#160;reading&#160;<span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>The future of C#</h2>
<p>Yesterday Anders Hejlsberg gave a talk about future directions of C# and VB.Net. He started with look back and then immediately dive into the new features of C# 5.0 which is part of VS 2011 and .NET 4.5. The most prominent new feature is of course the direct language support for asynchronous programming. The compiler provides two new keywords <strong>async</strong> and <strong>await</strong> which doesn’t sound exciting at all but in reality dramatically simplifies the way we developers can write “fast and fluid” code. Instead of dealing with threads, thread synchronization and callback functions ourselves we can now write fully asynchronous code in a sequential way. The compiler will do the heavy lifting for us and convert this “sequential and seemingly synchronous” code into a sequence of asynchronous calls and their corresponding continuations.</p>
<p>If you think that this is not worth talking about then try to write a sequence of asynchronous calls that depend on each other. And make sure that you provide adequate exception handling.</p>
<p>During his presentation Anders Hejlsberg also revealed some details about the future version of C# and he announced that a first developer preview will be available in about 4 weeks. The main part of the upcoming version of C# is a completely new compiler which is written in C# and can be used as a service. The project has the code name Rosalyn.</p>
<p>This “compiler as a service” will be of tremendous value for various scenarios. All kinds of tools, utilities or plugins will be able the leverage the compilers capabilities to their favor. Some samples are</p>
<ul>
<li>Intellisense, code coloring will leverage the output of the parser part of the compiler
<li>Refactoring tools like Resharper do not have to provide their own parser any more and can leverage the compiler
<li>Compile and execute scripts or code snippets (provided e.g. as string) on the fly
<li>Future versions of Visual Studio will leverage the compiler and provide an interactive console for C#
<li>Automatically translating code from one language to another; Anders demoed the translation from C# to VB.NET and vice versa
<li>Meta programming a la Boo or Ruby will be possible
<li>etc.</li>
</ul>
<p>I think this new compiler will once again dramatically improve the development experience with C# (and VB.NET). </p>
<h2>The new XAML editor in VS 2011</h2>
<p>If you have worked with WPF or Silverlight in Visual Studio 2010 or 2008 you know that the XAML editor was extremely slow and limited in its functionality. Now that has changed dramatically in VS 2011. First of all the new XAML editor is backed by the same engine (or at least part of it) as Expression Blend. The editor now runs in its own process to not compromise the stability and availability of VS. The editing capabilities have tremendously improved and members of the VS team&nbsp; confirmed me that they are tuning the editor as much as possible and make it performing well also in very large project with many assets.</p>
<h2>Expression Blend for HTML5/CSS applications</h2>
<p>Expression Blend is now available in a new flavor. HTML5/CSS3 based Metro style applications can now be visually designed in Blend. Many of the new CSS3 features are fully supported by this new editor. Not only is Expression Blend a layout tool but it fully supports the interactive mode (that is JavaScript is executed) which is very important in scenarios where most of the page is rendered dynamically, driven by JavaScript. </p>
<p><font color="#B4B4B4" size="-2">Post Footer automatically generated by <a href="http://www.freetimefoto.com/add_post_footer_plugin_wordpress" style="color: #B4B4B4; text-decoration:underline;">Add Post Footer Plugin</a> for wordpress.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/gabrielschenker/2011/09/16/build-conferenceday-3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
