<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Daniel Cazzulino's Blog</title>
	
	<link>http://blogs.clariusconsulting.net/kzu</link>
	<description>XML? What XML?</description>
	<lastBuildDate>Fri, 20 Apr 2012 20:47:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/DanielCazzulino" /><feedburner:info uri="danielcazzulino" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license><feedburner:emailServiceId>DanielCazzulino</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>How to map a shared SkyDrive folder as a network drive in Windows</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/cQWP7PyON24/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/how-to-map-a-shared-skydrive-folder-as-a-network-drive-in-windows/#comments</comments>
		<pubDate>Thu, 22 Mar 2012 13:37:21 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/how-to-map-a-shared-skydrive-folder-as-a-network-drive-in-windows/</guid>
		<description>Open the folder in the skydrive site using the browser (it would be under Shared menu on the left). The url will look something like: https://skydrive.live.com/?cid=529BD9445B66F60D&amp;#38;id=529BD9445B66F60D%21189#cid=529BD9445B66F60D&amp;#38;id=529BD9445B66F60D%21189. Now the “cid” query parameter in the URL. Right-click on Network (in windows explorer), then “Map Network Drive” Specify Folder as: https://d.docs.live.net/[cid]/[folder_name]. For the sample URL above, it would [...]</description>
			<content:encoded><![CDATA[<ol>
<li>Open the folder in the skydrive site using the browser (it would be under Shared menu on the left). The url will look something like: https://skydrive.live.com/?cid=529BD9445B66F60D&amp;id=529BD9445B66F60D%21189#cid=529BD9445B66F60D&amp;id=529BD9445B66F60D%21189. Now the “cid” query parameter in the URL.</li>
<li>Right-click on Network (in windows explorer), then “Map Network Drive”</li>
<li>Specify Folder as: https://d.docs.live.net/[cid]/[folder_name]. For the sample URL above, it would be https://d.docs.live.net/529bd9445b66f60d/CQRS (note the folder name isn’t in the URL, you need to know it beforehand, and it has to match what it’s named on the site).</li>
<li>Check the “Use alternate credentials” option in the dialog:
<p><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://blogs.clariusconsulting.net/kzu/files/2012/03/image.png" width="632" height="464" />      </li>
<li>Click Finish. Enter your Live ID credentials when asked. Done!</li>
</ol>
<p>&#160;</p>
<p>Not everything works that great (i.e. copying large files via drag&amp;drop doesn’t work, renaming folders, etc., at least in my experience), but it’s pretty darn convenient most of the time. I’m not sure the same thing works for your own personal folders. I don’t use SkyDrive at all, but it certainly does for shared ones (nice when you need a simple way to share docs within a team, privately and without requiring any software to be installed for syncing…).</p>
<p>&#160;</p>
<p>Enjoy.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=cQWP7PyON24:mB0LvuJF7h4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=cQWP7PyON24:mB0LvuJF7h4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=cQWP7PyON24:mB0LvuJF7h4:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=cQWP7PyON24:mB0LvuJF7h4:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/cQWP7PyON24" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/how-to-map-a-shared-skydrive-folder-as-a-network-drive-in-windows/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/how-to-map-a-shared-skydrive-folder-as-a-network-drive-in-windows/</feedburner:origLink></item>
		<item>
		<title>A better way to encourage contributions to OSS</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/14ZkFEMFHps/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/a-better-way-to-encourage-contributions-to-oss/#comments</comments>
		<pubDate>Fri, 16 Mar 2012 03:18:16 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/a-better-way-to-encourage-contributions-to-oss/</guid>
		<description>Currently in the .NET world, most OSS projects are available via a NuGet package. Users have a very easy path towards *using* the project right away. But let’s say they encounter some isssue (maybe a bug, maybe a potential improvement) with the library. At this point, going from user to contributor (of a fix, or [...]</description>
			<content:encoded><![CDATA[<p>Currently in the .NET world, most OSS projects are available via a <a href="http://nuget.org/" target="_blank">NuGet</a> package. Users have a very easy path towards *using* the project right away.</p>
<p>But let’s say they encounter some isssue (maybe a bug, maybe a potential improvement) with the library. At this point, going from user to contributor (of a fix, or a good bug repro or even a spike for a new feature) is a very steep and non trivial multi-step process of registering with some open source hosting site (codeplex, github, bitbucket, etc.), learning how to grab the latest sources, build the project, formulate a patch (or fork the code), learn the source control software they use (mercurial, git, svn, tfs), install whatever tools are needed for it, read about the contributors workflow for the project (do you fork &amp; send pull requests? do you just send a patch file? do you just send a snippet? a unit test? etc.), and on, and on, and on. Granted, you may be lucky and already know the source control system the project uses, but in really, I’d say the chances are pretty low. I believe most developers *using* OSS are far from familiar with them, much less with contributing back to various projects. We OSS devs like to be on the cutting edge all the time, ya’ know, always jumping on the new SCC system, the new hosting site, the new agile way of managing work items, bug tracking, code reviews, etc. etc. etc.. But most of our OSS users are largely the “<a href="http://kzu.to/zb1zQM" target="_blank">dark matter developers</a>”, they simply don’t have the time to put through all that friction just to contribute back. Even if they want to, it’s just WAY too much. It’s discouraging.</p>
<p>We can do better.</p>
<p>How about this flow? </p>
<ol>
<li>User installs library: install-package Moq </li>
<li>He/she uses it happily for years (let’s say <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://blogs.clariusconsulting.net/kzu/files/2012/03/wlEmoticon-winkingsmile.png" />), until one day an issue comes up that’s becoming annoying or doesn’t look like it has a known workaround. So it’s time for a time-boxed investigation to see if it’s truly a library bug or a user bug. </li>
<li>User uninstalls library: uninstall-package Moq </li>
<li>User installs library source package: install-package Moq.Source
<ul>
<li>At this point, they get the entire *source* for the project, as content (source) files in the SAME project they were previously using the library reference. Everything should still compile just like before. All that changed is that now you’re building against the actual sources, not the library. </li>
<li>Any dependencies the library uses for compiling got added automatically by NuGet to the users’ project. </li>
</ul>
</li>
<li>In order to understand a bit the library source code and how it’s being tested, the user installs the library unit tests source package: install-package Moq.Tests
<ul>
<li>At this point, they can run the entire test suite for the library, inspect the tests to learn how to isolate various pieces, and learn about the structuring of the code a bit. </li>
<li>Note that the tests source would typically be installed in a test project on the user’s solution. </li>
</ul>
</li>
<li>Now the user goes and creates a new unit test to try to repro in isolation the issue he/she found. </li>
<li>After a successful repro, the time-box may be over. But still, the clean repro he/she got is very useful in its own.
<ul>
<li>If the user has enough time, they may even be able to fix the issue in the code itself, or add the missing behavior. </li>
<li>Because of the way NuGet works, when you install a package that brings “content” (code, markup, config files, etc.) into your project, you now have two copies of that content: the original one under the packages folder alongside the solution file, and the potentially modified one in your own project. </li>
</ul>
</li>
<li>At this point,<strong> a little bit of VS extensibility and automation could detect that you made changes to that code, and offer a context menu to “Send Feedback”,</strong> which could pre-package the diff (patch file, .zip, clone/commit/whatever), allow the user to enter briefly an explanation of the issue, and be done. </li>
<li>Now, if the issue was really a showstopper, the user now has a way forward, that didn’t even require them to leave their own solution. Granted, checking into a company source control the actual source for an entire OSS project is typically unfeasible. So the alternative is for them to just uninstall-package Moq.Source, go back to install-package Moq and go on by implementing a workaround. But they have actively contributed back to a project they appreciate, they now have a real explanation (for dev leads, upper management) of why something proved harder than expected, and they probably even came out of the experience learning a new trick or two that they found in that codebase while they were investigating. An all around win-win situation. </li>
</ol>
<p>&#160;</p>
<p>I believe this is totally worth exploring. I’m willing to give this a try for Moq v5, as we talked about in <a href="http://kzu.to/xNP9BT" target="_blank">our first hangout</a>. What do you think? Is this something that looks reasonable and useful?</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=14ZkFEMFHps:6bwR-ZPsq48:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=14ZkFEMFHps:6bwR-ZPsq48:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=14ZkFEMFHps:6bwR-ZPsq48:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=14ZkFEMFHps:6bwR-ZPsq48:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/14ZkFEMFHps" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/a-better-way-to-encourage-contributions-to-oss/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/a-better-way-to-encourage-contributions-to-oss/</feedburner:origLink></item>
		<item>
		<title>You don’t need an IoC container or ServiceLocator for everything</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/sKtjLJqFWNw/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/you-dont-need-an-ioc-or-servicelocator-for-everything/#comments</comments>
		<pubDate>Fri, 09 Mar 2012 13:36:16 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/you-dont-need-an-ioc-or-servicelocator-for-everything/</guid>
		<description>Say you have a class that needs to collaborate with another, say a repository: public class OrderProcessor { public void ProcessPayment(Guid orderId, Payment payment) { using (var repo = new OrmRepository()) { var order = repo.Find&amp;#60;Order&amp;#62;(orderId); order.Pay(payment); repo.Save(order); } } } Now that clearly is very hard to test ‘cause it’s directly instantiating the repository. [...]</description>
			<content:encoded><![CDATA[<p>Say you have a class that needs to collaborate with another, say a repository:</p>
<pre class="brush: csharp;">public class OrderProcessor
{
    public void ProcessPayment(Guid orderId, Payment payment)
    {
        using (var repo = new OrmRepository())
        {
            var order = repo.Find&lt;Order&gt;(orderId);
            order.Pay(payment);

            repo.Save(order);
        }
    }
}</pre>
<p>Now that clearly is very hard to test ‘cause it’s directly instantiating the repository. So we know we have to refactor that and pass the repository instead, so that tests can replace the implementation and make assertions about the interaction (if we want to):</p>
<pre class="brush: csharp;">public class OrderProcessor
{
    private OrmRepository repository;

    public OrderProcessor(OrmRepository repository)
    {
        this.repository = repository;
    }

    public void ProcessPayment(Guid orderId, Payment payment)
    {
        var order = this.repository.Find&lt;Order&gt;(orderId);

        order.Pay(payment);

        this.repository.Save(order);
    }
}</pre>
<p>Now we realize that for unit tests to actually go against the actual real repository (i.e. a database) would be pretty slow and inefficient: we’d have to drop/clean the DB for every test run, etc. Unnecessary complication (not that you don’t need to have *integration* tests that DO run against the real DB, though). So we go ahead and make an interface out of the dependency (the repository in this case), so that we can completely replace its implementation in the tests:</p>
<pre class="brush: csharp;">public class OrderProcessor
{
    private IRepository repository;

    public OrderProcessor(IRepository repository)
    {
        this.repository = repository;
    }

    public void ProcessPayment(Guid orderId, Payment payment)
    {
        var order = this.repository.Find&lt;Order&gt;(orderId);

        order.Pay(payment);

        this.repository.Save(order);
    }
}</pre>
<p>Let’s not forget WHY we did all this: just so the behavior we’re creating can be easily tested, that’s all. It was never our goal to dynamically replace the repository, make it configurable externally or whatever. That’s NOT the point of the refactoring. </p>
<p>So what do you do when the need comes along to use some runtime framework (i.e. ASP.NET MVC, WCF, etc.) that by default expect your component to have a default parameterless constructor? (say this processor is an MVC controller or a web service). Well, it’s pretty damn easy, you just add a default ctor with the default implementation you know is the only one you have and will use at runtime!</p>
<pre class="brush: csharp;">public class OrderProcessor
{
    private IRepository repository;

    public OrderProcessor()
        : this(new OrmRepository())
    {
    }

    public OrderProcessor(IRepository repository)
    {
        this.repository = repository;
    }

    public void ProcessPayment(Guid orderId, Payment payment)
    {
        var order = this.repository.Find&lt;Order&gt;(orderId);

        order.Pay(payment);

        this.repository.Save(order);
    }
}</pre>
<p>And that’s IT. What? You thought at this point you NEEDED to choose an IoC container from the myriad available, hook up a controller/instance factory on the runtime MVC/WCF, etc.?? NO, you DON’T.</p>
<p>An IoC container WILL help if you have complex dependency graphs to instantiate (in your default constructor) or you have truly pluggable components (i.e. you want to allow a component to be picked up automatically at runtime from some binary if it’s in a folder, etc.).</p>
<p>If you don’t, it’s perfectly fine to have a default constructor that is used at runtime and has a hardcoded instantiation of a dependency. It was never a requirement to make that thing configurable or dynamic. So don’t invent business requirements just ‘cause using an IoC container is fancier. As far as I’m concerned, you didn’t violate any sacred principle by having that default constructor in there.</p>
<p>&#160;</p>
<p>If you were doing TDD (which you should) the process would be slightly different. Instead of refactoring to make it testable, you’d have the constructor receiving the IRepository right from the beginning. But the end result would be the same: just add a default ctor for the runtime framework to use and move on. </p>
<p>&#160;</p>
<p>That said, an IoC container and a mocking framework are my first two choices when doing File | New Project <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blogs.clariusconsulting.net/kzu/files/2012/03/wlEmoticon-smile.png" />. I know I’ll need them for anything non-trivial.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=sKtjLJqFWNw:hd6Yg6cXZb8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=sKtjLJqFWNw:hd6Yg6cXZb8:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=sKtjLJqFWNw:hd6Yg6cXZb8:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=sKtjLJqFWNw:hd6Yg6cXZb8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/sKtjLJqFWNw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/you-dont-need-an-ioc-or-servicelocator-for-everything/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/you-dont-need-an-ioc-or-servicelocator-for-everything/</feedburner:origLink></item>
		<item>
		<title>Event Centric: storing and consuming events</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/yRHBdRbuDcA/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/event-centric-storing-and-consuming-events/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 20:47:05 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[eventsourcing]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/event-centric-storing-and-consuming-events/</guid>
		<description>[Disclaimer: I don’t think this disclaimer is needed, but just to be on the safe side. The opinions expressed herein are my own personal opinions and do not represent in any way my company's view, that of any customer current or past, or any current, past or future project related to these concepts that I [...]</description>
			<content:encoded><![CDATA[<p>[Disclaimer: I don’t think this disclaimer is needed, but just to be on the safe side. The opinions expressed herein are my own personal opinions and do not represent in any way my company's view, that of any customer current or past, or any current, past or future project related to these concepts that I may participate in]</p>
<p>In <a href="http://kzu.to/uSx4g2" target="_blank">my previous post</a> I showed how you can evolve the way you code your domain objects (or entities) so that they can benefit from the <a href="http://kzu.to/og0QJ5" target="_blank">Event Sourcing</a> pattern, and I also showed that it’s pretty simple at its core. That post ended up being a little disconnected from the one where <a href="http://kzu.to/srVn3P" target="_blank">I show how do to cool analysis</a> based on those events. It was on purpose, as I needed to introduce another concept, and the post was getting too big already <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blogs.clariusconsulting.net/kzu/files/2012/01/wlEmoticon-smile1.png" />.</p>
<p>Lets recap briefly what happens on a domain object when we invoke an operation:</p>
<p><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://blogs.clariusconsulting.net/kzu/files/2012/01/image7.png" width="804" height="661" /></p>
<p>So after we invoked Move(), calling GetEvents() on the object would give us the CustomerMoved event data class that was the result of the operation. Pushing this event through the event stream manually is pretty straightforward:</p>
<pre class="brush: csharp;">var stream = new EventStream();

// print to the console every time a customer
// changes his address
stream.Of&lt;CustomerMoved&gt;().Subscribe(x =&gt; Console.WriteLine(&quot;Customer has moved to a new address: {0}&quot;, x.NewAddress));

var customer = new Customer(1); // load somehow
customer.Move(&quot;999 NE 9TH ST, Redmond, WA&quot;);

foreach (var @event in customer.GetEvents())
{
    stream.Push(@event);
}</pre>
<p>The next important thing as <a href="http://kzu.to/og0QJ5" target="_blank">mentioned by Folwer</a> is that events are persisted somehow, and never change, ever. They are the definite and authoritative source of truth about what happened to your system. And you can perform analysis on that stream at any point in time in the future, even for events that happened long ago. This is very valuable to business: being able to derive new conclusions and trends retroactively, from day one of the system. It’s a very easy sell. So let’s get on to define the simplest possible interface for an event store.</p>
<h2>The DomainObject</h2>
<p>The domain object base class from <a href="http://kzu.to/uSx4g2" target="_blank">my previous post</a> needs to evolve now, so that it’s more flexible. First, we have no way of knowing what type of object identifiers developers will prefer. So we can just make that a generic TObjectId argument. Ditto for the base type for events: maybe you want to enforce they are all EventArgs-derived, or they all implement a certain interface (i.e. <a href="http://kzu.to/zhqc1m" target="_blank">ITimestamped</a>?), and so on. So we make that a generic parameter as well:</p>
<pre class="brush: csharp;">abstract partial class DomainObject&lt;TObjectId, TBaseEvent&gt;
{
    private Dictionary&lt;Type, Action&lt;TBaseEvent&gt;&gt; handlers = new Dictionary&lt;Type, Action&lt;TBaseEvent&gt;&gt;();
    private List&lt;TBaseEvent&gt; events = new List&lt;TBaseEvent&gt;();

    protected DomainObject()
    {
    }

    public virtual TObjectId Id { get; set; }

    public virtual void AcceptEvents()
    {
        this.events.Clear();
    }

    public virtual IEnumerable&lt;TBaseEvent&gt; GetEvents()
    {
        return this.events.AsReadOnly();
    }

    protected virtual void Handles&lt;TEvent&gt;(Action&lt;TEvent&gt; handler)
        where TEvent : TBaseEvent
    {
        this.handlers.Add(typeof(TEvent), @event =&gt; handler((TEvent)@event));
    }

    protected void Load(IEnumerable&lt;TBaseEvent&gt; events)
    {
        foreach (var args in events)
        {
            var handler = default(Action&lt;TBaseEvent&gt;);
            if (this.handlers.TryGetValue(args.GetType(), out handler))
                handler.Invoke(args);
        }
    }

    protected virtual void Apply&lt;TEvent&gt;(TEvent @event)
        where TEvent : TBaseEvent
    {
        var handler = default(Action&lt;TBaseEvent&gt;);
        if (this.handlers.TryGetValue(@event.GetType(), out handler))
            handler.Invoke(@event);

        this.events.Add(@event);
    }
}</pre>
<p>
  <br />The first thing you’d do in a project using that base class, is “fix” the base class type parameters for the ones you’ll use for your entire domain model, like:</p>
<p></p>
<pre class="brush: csharp;">abstract class DomainObject : DomainObject&lt;Guid, EventArgs&gt;
{
}</pre>
<p>So from your domain you don’t have to repeat those generic parameters all over the place. It would make things easier if you decide to change the type of either the identifier or the event data base class.</p>
<h2>The Event Store</h2>
<p>An event store has two core responsibilities: save a bunch of events produced by a domain object (maybe in a single &quot;transaction&quot;, if we adhere to the <a href="http://kzu.to/vrpGDR" target="_blank">DDD</a> principle that a single so-called <a href="http://kzu.to/vsrenE" target="_blank">aggregate root</a> defines the <a href="http://kzu.to/s72iXI" target="_blank">consistency boundary</a> for a domain operation), and allow minimal querying to retrieve the events that apply to a given object, and within a range of time (to allow replaying an object to a previous state) so that we can load it as it was at a certain point in time.</p>
<p>For saving, we could model the API in a few different ways: pass in the list of events, or each event individually, or the entire domain object. I chose the latter because it allows the implementations to decide how they will handle consistency and transactions for the whole set of events raised by the domain object, which may be a DDD aggregate root if you design it that way. But it’s not restrictive in any way, as you can still design things differently.</p>
<p>The store interface will use the TObjectId type for querying the events for a specific object instance.</p>
<pre class="brush: csharp;">partial interface IEventStore&lt;TObjectId, TBaseEvent&gt;
{
    void SaveChanges(DomainObject&lt;TObjectId, TBaseEvent&gt; entity);

    IEnumerable&lt;TBaseEvent&gt; Query(EventQueryCriteria&lt;TObjectId&gt; criteria);
}</pre>
<p>
  <br />For the query, I provided a simple <a href="http://kzu.to/vLh01z" target="_blank">query object</a> style pattern that store implementations can use to issue the actual underlying query. We basically want to be able to load events for a specific object instance, for objects of a given type (maybe, like &quot;give me all Published events of all products&quot;, for specific event types (i.e. LoginFailure) and all of that within certain time ranges:</p>
<p></p>
<pre class="brush: csharp;">partial class EventQueryCriteria&lt;TObjectId&gt;
{
    public EventQueryCriteria()
    {
        this.ObjectInstances = new List&lt;ObjectFilter&gt;();
        this.ObjectTypes = new List&lt;Type&gt;();
        this.EventTypes = new List&lt;Type&gt;();
    }

    public List&lt;ObjectFilter&gt; ObjectInstances { get; private set; }
    public List&lt;Type&gt; ObjectTypes { get; private set; }
    public List&lt;Type&gt; EventTypes { get; private set; }

    public DateTime? Since { get; set; }
    public DateTime? Until { get; set; }
    public bool IsExclusiveRange { get; set; }

    public class ObjectFilter
    {
        public ObjectFilter(Type objectType, TObjectId objectId)
        {
            this.ObjectType = objectType;
            this.ObjectId = objectId;
        }

        public Type ObjectType { get; private set; }
        public TObjectId ObjectId { get; private set; }
    }
}</pre>
<p>
  <br />Just a plain DTO of the query information. The nice thing about this is that I can provide a fluent API over the store interface, like so:</p>
<p></p>
<pre class="brush: csharp;">var store = new EventStore(...);

var query = store
    .Query()
    .For&lt;Product&gt;()
    .Since(new DateTime(2010, 1, 1))
    .OfType&lt;Published&gt;();

var results = query.Execute();</pre>
<p>The query.Execute method simply calls Query(criteria) on the underlying store <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blogs.clariusconsulting.net/kzu/files/2012/01/wlEmoticon-smile1.png" />. Needless to say, not all stores need to implement all the query behavior. You’ll use what you need. I just put in the criteria I thought would be useful against an event store (things like being able to query by event type regardless of object instance, or all events for all objects of a given type, are useful in some scenarios we’ll see later, but aren’t common in other event store implementations).</p>
<p>To make things even simpler, I’ve created a <a href="http://kzu.to/vtYxP4" target="_blank">separate nuget package</a> that provides the necessary LINQ expression building so that implementing a store over an underlying IQueryable storage is trivial. But again, being a separate package means you don’t have to use it or that your underlying storage has to be an IQueryable of some sort. And that’s about it for the store API itself.</p>
<p>I currently have an <a href="http://kzu.to/xa06ab" target="_blank">Entity Framework-based store</a>, an <a href="http://kzu.to/zc7ygc" target="_blank">in-memory store</a> (useful for tests, for example) and a sample file system based one. Being NETFx packages, they are all provided as source code (few lines each), so building a new store based on that source should be pretty straightforward against almost any store. I may include more store implementations in the future.</p>
<p>&#160;</p>
<p>Some might say that I’ve gone too far with the event store querying capabilities. I believe that the basic querying I’ve put in makes it much more useful in its own right, rather than having to resort to full CQRS to perform simple ad-hoc querying like “how many new customers have registered last month?” (store .Query().OfType&lt;CustomerRegistered&gt;().Since(DateTime.Now.Substract(TimeSpan.FromDays(30))) and the like. Once you have the domain raising all sort of interesting events, business owners will surely want to be able to perform various querying over that data, and there’s no reason why we wouldn’t want to leverage existing technology that solves that easily (i.e. Linq to data in .NET).</p>
<p>Of course, loading a given domain object state up to a certain date is pretty simple too:</p>
<pre class="brush: csharp;">var events = store.Query()
    .For&lt;Customer&gt;(customerId)
    .Until(DateTime.Now.Substract(TimeSpan.FromDays(30)))
    .Execute();

var customerAsOfLastMonth = new Customer(events);</pre>
<p>&#160;</p>
<p>This type of querying capability on top of the basic event stream that your <a href="http://kzu.to/uSx4g2" target="_blank">“empowered” domain model</a> starts populating is extremely easy to sell to stakeholders. And I believe it’s entirely additive on top of whatever modeling and persistence strategy you’re currently using. This is <a href="http://kzu.to/yzm76e" target="_blank">not the prevalent criteria among CQRS/ES practitioners</a>, but I think it’s a pragmatic approach that can quickly bring real benefits in terms of business value and intelligence without having to do anything significantly different than what you’re already doing.</p>
<p>&#160;</p>
<p>I’ll explore more of this smooth evolution path in my next post. Stay tunned.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=yRHBdRbuDcA:frSpzxZlj34:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=yRHBdRbuDcA:frSpzxZlj34:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=yRHBdRbuDcA:frSpzxZlj34:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=yRHBdRbuDcA:frSpzxZlj34:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/yRHBdRbuDcA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/event-centric-storing-and-consuming-events/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/event-centric-storing-and-consuming-events/</feedburner:origLink></item>
		<item>
		<title>A better way to implement the Singleton (anti?) pattern for easier testing using AmbientSingleton</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/NFToRENUkoM/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 18:03:07 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/</guid>
		<description>In .NET singletons are typically implemented with a static variable that you control access to: public class SystemClock : IClock { private SystemClock() { } static SystemClock() { Instance = new SystemClock(); } public static IClock Instance { get; private set; } } Fairly easy. Problem is, of course that there’s no way you can [...]</description>
			<content:encoded><![CDATA[<p>In .NET singletons are typically implemented with a static variable that you control access to:</p>
<pre class="brush: csharp;">public class SystemClock : IClock
{
    private SystemClock() { }

    static SystemClock()
    {
        Instance = new SystemClock();
    }

    public static IClock Instance { get; private set; }
}</pre>
<p>Fairly easy. Problem is, of course that there’s no way you can test a class that uses this singleton now. The easy thing that you might be tempted to do is to just make the setter internal and starting replacing the singleton clock with mocks of it. Problem is, as you may have guessed, that now the tests cannot be run in multiple threads simultaneously. You have made no provisions for shielding changes across threads, so if one test setups up the singleton with a mock with certain values, and another goes and changes it before the asserts get through, you’ll be seeing intermittent failures on random tests when run together, but no single failure when run individually.</p>
<p>Being such a common problem, the .NET framework provides a few ways to work around that, via a mechanism called <a href="http://kzu.to/yD4at4" target="_blank">Thread Local Storage</a> (or TLS). Joe Albahari provides a great summary of the available options, so make sure you <a href="http://kzu.to/yD4at4" target="_blank">read that link</a>. In summary, they are:</p>
<ul>
<li>Mark a static backing variable with [ThreadStatic] attribute:<br />
    </p>
<pre class="brush: csharp;">public class SystemClock : IClock
{
    [ThreadStatic]
    private static IClock instance = new SystemClock();

    private SystemClock() { }

    public static IClock Instance
    {
        get { return instance; }
        internal set { instance = value; }
    }
}
<font face=\"Calibri\"></font></pre>
</li>
<li>Use ThreadLocal&lt;T&gt; instead for the private field:<br />
    </p>
<pre class="brush: csharp;">public class SystemClock : IClock
{
    private static ThreadLocal&lt;IClock&gt; instance = new ThreadLocal&lt;T&gt;(() =&gt; new SystemClock());

    private SystemClock() { }

    public static IClock Instance
    {
        get { return instance.Value; }
        internal set { instance.Value = value; }
    }
}
</pre>
</li>
<li>Use Thread.SetData/GetData to hold the state:<br />
    </p>
<pre class="brush: csharp;">public class SystemClock : IClock
{
    private static readonly LocalDataStoreSlot slot = Thread.AllocateDataSlot();

    private SystemClock() { }

    public static IClock Instance
    {
        get
        {
            var value = (IClock)Thread.GetData(slot);
            // Lazy init first time for this thread.
            if (value == null)
            {
                value = new SystemClock();
                Thread.SetData(slot, value);
            }

            return value;
        }
        internal set { Thread.SetData(slot, value); }
    }
}</pre>
</li>
</ul>
<p>These options have slightly different performance characteristics (in my tests, ThreadStatic is fastest and the other two about 5x slower than that). However, they all share a very serious limitation, that was highlighted by <a href="http://kzu.to/yLqVIw" target="_blank">Scott ages ago, back in 2003</a>. They simply don’t work if what you need is per-context state, such as per web request, per test, essentially, per Call Context. Some call this the Ambient Context pattern, but its essence in .NET is the Logical Call Context, thoroughly dissected by <a href="http://kzu.to/z5gMct" target="_blank">Jeffrey Richter in a blog post</a>. </p>
<p>Given its misleading <a href="http://kzu.to/yM3fdO" target="_blank">MSDN summary</a>, and its location with the namespace System.Runtime.Remoting.Messaging, it’s not surprising that developers quickly dismiss it as a valid (and much better as we’ll see!) alternative. A logical call context flows as a thread-like state bag, but it’s not limited to a single thread. In fact, even the new threading Tasks library honors this capability, and the most prominent use of this in .NET is in <a href="http://kzu.to/wl5Veh" target="_blank">WCF E2E Tracing</a>, which uses the <a href="http://kzu.to/xXghu1" target="_blank">CorrelationManager.ActivityId</a>, which is persisted in the logical call context and flows even across AppDomains. </p>
<p>You basically use <a href="http://kzu.to/xfvdTu" target="_blank">CallContext.LogicalGetData</a> and <a href="http://kzu.to/ygvdMd" target="_blank">LogicalSetData</a> instead of the Thread.SetData/GetData from the example above. It is, however, a bit cumbersome, and I just wish we had something like ThreadLocal&lt;T&gt; to leverage for this “smart singleton” (or “ambient singleton”) capability.</p>
<p>Enter the <a href="http://kzu.to/w5NcfX" target="_blank">NETFx AmbientSingleton</a> class, which gives you just that <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blogs.clariusconsulting.net/kzu/files/2012/01/wlEmoticon-smile.png" />:</p>
<pre class="brush: csharp;">public class SystemClock : IClock
{
    private static readonly AmbientSingleton&lt;IClock&gt; instance = new AmbientSingleton&lt;IClock&gt;(() =&gt; new SystemClock());

    private SystemClock() { }

    public static IClock Instance
    {
        get { return instance.Value; }
        internal set { instance.Value = value; }
    }
}</pre>
<p>It is safe to set the value of the singleton in multiple threads simultaneously, and the value you set will be preserved in the entire call chain, even if the test or code under test spawns new threads via the thread pool or the task pool (which ultimately also uses the thread pool by default).</p>
<p>There is also a static AmbientSingleton.Create factory method with a couple overloads, to cut on the generic parameters noise.</p>
<p>The entire source for the class is very straightforward, as you’d expect: </p>
<pre class="brush: csharp;">static partial class AmbientSingleton
{
    public static AmbientSingleton&lt;T&gt; Create&lt;T&gt;(T defaultValue)
    {
        return new AmbientSingleton&lt;T&gt;(defaultValue);
    }

    public static AmbientSingleton&lt;T&gt; Create&lt;T&gt;(Func&lt;T&gt; defaultValueFactory)
    {
        return new AmbientSingleton&lt;T&gt;(defaultValueFactory);
    }
}

partial class AmbientSingleton&lt;T&gt;
{
    private string slotName = Guid.NewGuid().ToString();
    private Lazy&lt;T&gt; defaultValue;

    /// &lt;/summary&gt;
    public AmbientSingleton()
        : this(() =&gt; default(T))
    {
    }

    public AmbientSingleton(T defaultValue)
        : this(() =&gt; defaultValue)
    {
    }

    public AmbientSingleton(Func&lt;T&gt; defaultValueFactory)
    {
        Guard.NotNull(() =&gt; defaultValueFactory, defaultValueFactory);

        this.defaultValue = new Lazy&lt;T&gt;(defaultValueFactory);
    }

    public T Value
    {
        get
        {
            var contextValue = CallContext.LogicalGetData(this.slotName);
            if (contextValue != null)
                return (T)contextValue;

            return this.defaultValue.Value;
        }
        set
        {
            CallContext.LogicalSetData(this.slotName, value);
        }
    }
}</pre>
<p>As you can see, the <em>Ambient Singleton</em> behaves like a regular singleton, without the overhead of per-thread initialization, when it’s not needed. This is another drawback of the TLS approaches: if the object initialization is expensive, you’ll be paying for that once per thread. In the ambient singleton, however, only when a particular call context requires a different value for the singleton, the added behavior kicks in. In my tests this approach is the closest to the speed of [ThreadStatic], measuring only about 1.8x the ThreadStatic approach (compared with 5x for the ThreadLocal&lt;T&gt; and Thread data). All in all, a very compelling way of implementing singletons, when they are unavoidable (although you could say there’s always another way of doing it <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://blogs.clariusconsulting.net/kzu/files/2012/01/wlEmoticon-winkingsmile.png" />, but that’s another post).</p>
<p>&#160;</p>
<p>You can install the <a href="http://kzu.to/w5NcfX" target="_blank">nuget package to get the source AmbientSingleton&lt;T&gt; class</a>, which is partial and defaults to internal, as you’d typically not expose it as a public type in your libraries, and is rather an internal implementation detail of your singletons. You can of course create another partial of it and make it public if you wish. It’s fully documented, and lives in the System namespace.</p>
<p>In order to keep your code coverage goals, you can also install the <a href="http://kzu.to/ym4hcr" target="_blank">xUnit tests</a> which provide 100% coverage for this source.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=NFToRENUkoM:nYckxZi7tL4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=NFToRENUkoM:nYckxZi7tL4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=NFToRENUkoM:nYckxZi7tL4:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=NFToRENUkoM:nYckxZi7tL4:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/NFToRENUkoM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/</feedburner:origLink></item>
		<item>
		<title>A general purpose event bus leveraging Reactive Extensions</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/8a2c-XkXrYA/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/a-general-purpose-event-bus-leveraging-reactive-extensions/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 19:15:12 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/a-general-purpose-event-bus-leveraging-reactive-extensions/</guid>
		<description>I talked before on the usefulness of having rich events published throughout your domain. In that blog post, I also showed a very simple implementation. I realized that there seems to be quite some interest in the event&amp;#160; (or message) bus pattern as an application architecture pattern and not necessarily in the usual enterprise integration [...]</description>
			<content:encoded><![CDATA[<p>I talked before on the usefulness of having <a href="http://kzu.to/srVn3P" target="_blank">rich events published throughout your domain</a>. In that blog post, I also showed a very simple implementation.</p>
<p>I realized that there seems to be <a href="http://code.google.com/p/simpleeventbus/" target="_blank">quite</a> <a href="http://stackoverflow.com/questions/368265/a-simple-eventbus-for-net" target="_blank">some</a> <a href="http://docs.guava-libraries.googlecode.com/git-history/v10.0.1/javadoc/com/google/common/eventbus/EventBus.html" target="_blank">interest</a> in the event&#160; (or message) bus pattern as an application architecture pattern and not necessarily in the usual enterprise integration style. This means that you leverage the concept of an event bus for internal application decoupling (along the lines of an <a href="http://kzu.to/v1VPoF" target="_blank">Event Collaboration</a>), and not for integration with external systems. The difference is that everything happens in-memory, there is no intermediate persistent message queue, there are not message/event routers, partition, scalability requirements or anything like that. It’s a very simple way to make your components more loosely coupled.</p>
<p>In this post I’ll introduce a minor tweak to the original implementation of an <em>event stream</em> (I wanted to remove the <em>Bus</em> word from it as it confuses people that think it’s an enterprise style message bus) to make it more useful and general purpose.</p>
<p>To recap: the event stream is consumed by subscribers by simply subscribing to the desired event type:</p>
<pre class="brush: csharp;">var subscription = eventStream.Of&lt;ProductPurchased&gt;().Subscribe(….)</pre>
<p>Or by performing a more complicated reactive query over the events:</p>
<pre class="brush: csharp;">var query =
    from discharged in events.Of&lt;PatientLeftHospital&gt;()
    from admitted in events.Of&lt;PatientEnteredHospital&gt;()
    where
        admitted.PatientId == discharged.PatientId &amp;&amp;
        (admitted.When - discharged.When).Days &lt; 5
    select admitted;

var subscription = query.Subscribe(...)</pre>
<p>My initial implementation would only invoke subscribers that register for the specific event being pushed through the stream:</p>
<pre class="brush: csharp;">partial class EventStream : IEventStream
{
    private ConcurrentDictionary&lt;Type, object&gt; subjects = new ConcurrentDictionary&lt;Type, object&gt;();

    public void Push&lt;TEvent&gt;(TEvent @event)
    {
        Guard.NotNull(() =&gt; @event, @event);

        var subject = this.subjects.Find(@event.GetType()) as Subject&lt;TEvent&gt;;
        if (subject != null)
            subject.OnNext(@event);
    }

    public IObservable&lt;TEvent&gt; Of&lt;TEvent&gt;()
    {
        return (IObservable&lt;TEvent&gt;)subjects.GetOrAdd(typeof(TEvent), type =&gt; new Subject&lt;TEvent&gt;());
    }
}</pre>
<p>The Find extension method on ConcurrentDictionary simply does a TryGetValue on it and returns null if not found. We need to be smarter there to make this event stream more useful.</p>
<p>It’s probably that we’ll want to subscribe to more generic events (say for tracing purposes, for some global statistics, etc.), so you should be able to subscribe to (say) EventArgs and get all events that derive from it. Or do it based on interfaces, etc.</p>
<p>The change to generalize it is pretty simple too: we just make the Push method look for all subjects that have compatible event types:</p>
<pre class="brush: csharp;">public void Push&lt;TEvent&gt;(TEvent @event)
{
    Guard.NotNull(() =&gt; @event, @event);

    var eventType = @event.GetType();

    var compatible = subjects.Keys
        .Where(subjectEventType =&gt; subjectEventType.IsAssignableFrom(eventType))
        .Select(subjectEventType =&gt; subjects[subjectEventType]);

    foreach (dynamic subject in compatible)
    {
        subject.OnNext((dynamic)@event);
    }
}</pre>
<p>We cast the subjects from object to dynamic so that we can do a dynamic invocation, because we don’t have a common interface for all. They all implement <a href="http://kzu.to/u269Tz" target="_blank">ISubject&lt;T&gt;</a>. We also need to make the event itself dynamic, so that the runtime will pick the right method signature given both the subject type and the event type (might involve covariant cast, etc.). </p>
<p>&#160;</p>
<p>In my opinion, the coolest part of having this type of event bus is that you can now layer on top the concept of schedulers (i.e. introduce async event listeners, or even create your own custom scheduler and perform crazy things like out of process queue-based events if you wanted) with no effort and keeping the same simple public interface. </p>
<p>Both the <a href="http://kzu.to/twxrOu" target="_blank">IEventStream</a> and <a href="http://kzu.to/uVWBoV" target="_blank">EventStream</a> implementation are very straightforward and simple. I have put them together as source code <a href="http://netfx.codeplex.com" target="_blank">NETFx</a> nugets so you can get any updates to this post or future posts concerning these classes in the future. They are separate because in your application you may have a separate assembly for all your interfaces and separate ones for the implementations. In that case, you’ll install the interface nuget in the former, and the other in one of the implementation ones. For convenience, I also made an <a href="http://kzu.to/rPiZEs" target="_blank">aggregated package</a> that installs both interface and implementation on the same project. To make either the interface or the implementation public (they are both partial internal by default, to avoid increasing your API surface unnecessarily), you just add a partial declaration marking them public. The interface nuget even comes with a Visibility.cs file which you can just uncomment to get make the interface public:</p>
<pre class="brush: csharp;">// In order to make types introduced by this package public
// uncomment the following:

//namespace System.Reactive
//{
//    public partial interface IEventStream { }
//}</pre>
<p>&#160;</p>
<p>Enjoy!</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=8a2c-XkXrYA:yKjOA7GRFUU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=8a2c-XkXrYA:yKjOA7GRFUU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=8a2c-XkXrYA:yKjOA7GRFUU:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=8a2c-XkXrYA:yKjOA7GRFUU:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/8a2c-XkXrYA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/a-general-purpose-event-bus-leveraging-reactive-extensions/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/a-general-purpose-event-bus-leveraging-reactive-extensions/</feedburner:origLink></item>
		<item>
		<title>Event Centric: super-charge your model with domain events to enable business intelligence</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/Pd6U0qLypi0/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/event-centric-super-charge-your-model-with-domain-events-to-enable-business-intelligence/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 18:06:30 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[eventsourcing]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/event-centric-super-charge-your-model-with-domain-events-to-enable-business-intelligence/</guid>
		<description>I’ve shown in my previous post how interesting domain events can be mined using the Reactive Extensions for .NET. Now we need to raise those events when things happen to our domain. The typical way you’d publish events from your domain is simply adding .NET events. Say we have a Patient class, with a method [...]</description>
			<content:encoded><![CDATA[<p>I’ve shown in <a href="http://kzu.to/srVn3P" target="_blank">my previous post</a> how interesting domain events can be mined using the Reactive Extensions for .NET. Now we need to raise those events when things happen to our domain. The typical way you’d publish events from your domain is simply adding .NET events. Say we have a Patient class, with a method Admit that causes the patient to be in the hospital and tracks the date when he was admitted:</p>
<pre class="brush: csharp;">public class Patient
{
    public DateTimeOffset? AdmittedDate { get; private set; }
    public bool IsInHospital { get; private set; }

    public void Admit(DateTimeOffset when)
    {
        if (this.IsInHospital)
            throw new InvalidOperationException(&quot;Already in hospital!&quot;);

        this.IsInHospital = true;
        this.AdmittedDate = when;
    }
}</pre>
<p>The domain object method typically does some precondition validation (like the one above, the patient can’t be admitted twice), then mutates the state as needed. At some point the resulting object state will be persisted somehow, but it’s a good goal to have <a href="http://kzu.to/tNqNE0" target="_blank">persistence ignorant</a> entities, as you probably know by now <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://blogs.clariusconsulting.net/kzu/files/2011/12/wlEmoticon-winkingsmile.png" />.</p>
<p>If we now want to let other components know whenever a patient is admitted, we can just add a .NET event, like so:</p>
<pre class="brush: csharp;">public class Patient
{
    public event EventHandler&lt;PatientAdmitted&gt; Admitted = (sender, args) =&gt; { };

    //...

    public void Admit(DateTimeOffset when)
    {
        //...
        this.OnAdmitted();
    }

    private void OnAdmitted()
    {
        this.Admitted(this, new PatientAdmitted(this.AdmittedDate.Value));
    }
}

public class PatientAdmitted : EventArgs
{
    public PatientAdmitted(DateTimeOffset when)
    {
      this.When = when;
    }

    public DateTimeOffset When { get; set; }
}</pre>
<p>&#160;</p>
<p>From the domain public method, we just raise the event when we’re done mutating state, and this is typical practice in .NET. </p>
<blockquote>
<p>Note: I have initialized the event with a non-null initializer lambda, (sender, args) =&gt; { }, and that means the event will never be null, so I can avoid the null check in the OnAdmitted method. The overhead is negligible compared to the increased readability and simplicity. I’ve been using this trick forever, and I always find it weird that developers don’t use it everywhere since we have lambdas…</p>
</blockquote>
<p>Now, in order to achieve the kind of analysis that I showed in <a href="http://kzu.to/srVn3P" target="_blank">my previous post</a>, we need a way to grab ALL events that have been raised by any domain object, so as to publish them for analysis. Someone could still hook to our .NET event, but it would be cumbersome to have to do that in a generic fashion, using reflection, for all events of all domain objects we instantiate (not to mention it would be slow). If we think about the events, the actual interesting data about it is the event args class itself. The sender is always the same, the current object. So we could refactor a bit the code like so:</p>
<pre class="brush: csharp;">public void Admit(DateTimeOffset when)
{
    // ...
    this.OnAdmitted(new PatientAdmitted(this.AdmittedDate.Value));
}

private void OnAdmitted(PatientAdmitted args)
{
    this.Admitted(this, args);
}</pre>
<p>So that now the OnAdmitted receives the actual event data instead. We still need a central way to track all raised event data for this object, so that we can do something like:</p>
<pre class="brush: csharp;">var patient = new Patient(); // load somehow
patient.Admit(DateTimeOffset.Now);

var events = patient.GetEvents();
// Publish events somehow somewhere</pre>
<p>Let’s add a way to track the raised event data in a list that we can return later. We can do this by introducing a private Raise method that receives the event data, and the method to call to handle the actual event raising (our OnAdmitted method), which we can pass as an Action&lt;T&gt; delegate. When we introduce this method, the code above will change to:</p>
<pre class="brush: csharp;">public void Admit(DateTimeOffset when)
{
    // ...
    this.Raise(new PatientAdmitted(when), this.OnAdmitted);
}

private void OnAdmitted(PatientAdmitted args)
{
    this.Admitted(this, args);
}</pre>
<p>The Raise implementation just adds the raised event data to a list: </p>
<pre class="brush: csharp;">private List&lt;EventArgs&gt; events = new List&lt;EventArgs&gt;();

private void Raise&lt;TEvent&gt;(TEvent args, Action&lt;TEvent&gt; handler)
    where TEvent : EventArgs
{
    this.events.Add(args);
    handler(args);
}

public IEnumerable<eventargs> GetEvents()
{
    return this.events.AsReadOnly();
}</pre>
<p>We could probably say we’re done, but we’ll go a bit further. How do you know up-front which events are interesting to raise and which aren’t? How can you possibly foresee the business needs in the future? What if you also want to do analysis of how many <em>new</em> patients you’re receiving vs admission of existing patients? What if you now need to report on the frequency patients get certain symptoms? Or how frequent they move, and to which neighbors, and so on? In the end, it might be that some day, you need to do analysis on ANY state changes in the system. What if we “forced” ourselves to ensure that ALL state changes have a corresponding event associated with them? </p>
<p>One easy way to do that would be to refactor a little bit the code above, and perform the state changes always in the private event handler, instead of the public domain method:</p>
<pre class="brush: csharp;">public void Admit(DateTimeOffset when)
{
    if (this.IsInHospital)
        throw new InvalidOperationException(&quot;Already in hospital!&quot;);

    this.Raise(new PatientAdmitted(when), this.OnAdmitted);
}

private void OnAdmitted(PatientAdmitted args)
{
    this.IsInHospital = true;
    this.AdmittedDate = args.When;

    this.Admitted(this, args);
}</pre>
<p>The change seems minor, but it has profound implications as we’ll see shortly. First and foremost, if you force yourself to do every state change like this, you can be sure you’ll have a very rich set of domain events to perform analysis from in the future. Not only that, but you’re forcing yourself to put ALL the data you need to perform the state changes IN the event data class itself. Seems like an obvious thing to do. Let’s add one more domain method, which is to assign a bed to the patient:</p>
<pre class="brush: csharp;">public event EventHandler&lt;BedAssigned&gt; BedAssigned = (sender, args) =&gt; { };

public int Bed { get; private set; }

public void AssignBed(int bed)
{    if (!this.IsInHospital)        throw new InvalidOperationException(&quot;Patient must be in the hospital to assign a bed&quot;);
    if (bed &lt; 0)
        throw new ArgumentException(&quot;Invalid bed number&quot;);

    this.Raise(new BedAssigned(bed), this.OnBedAssigned);
}

private void OnBedAssigned(BedAssigned args)
{
    this.Bed = args.Bed;

    this.BedAssigned(this, args);
}</pre>
<p>Another minor thing we changed here: the concept of <strong>When</strong> things happen is key in any domain event. Events clearly have a When property pretty much always. In our first event, we passed the date as an argument to the Admit method, but assigning a bed would be no different, right? You’d soon realize that you’d be passing a date time to pretty much every method. But if you think about it, the actual domain state doesn’t necessarily need that piece of data. In the assign bed example, the domain class may just need to keep the current bed, but not necessarily when it was assigned. That might be something that analysis from the events needs. Ditto for other events. Forcing our domain to keep two properties (one for the actual data, another for the <em>when</em> it changed) seems unnatural and it’s something we don’t typically do, essentially because our domain objects have state that is current <em>as of now</em>. So in this case, I just moved the responsibility of knowing when an event happened to the event arguments class itself, and we free our domain from having to worry or pass that data over and over:</p>
<pre class="brush: csharp;">public class BedAssigned : EventArgs
{
    public BedAssigned() { }
    public BedAssigned(int bed)
    {
        this.Bed = bed;
        this.When = DateTimeOffset.Now;
    }

    public int Bed { get; set; }
    public DateTimeOffset When { get; set; }
}</pre>
<h2>The passing of time</h2>
<p>We mentioned above that the domain objects represent state that is current <em>as of now</em>. If you think about the Patient.Bed property, its current value will change over time as the OnBedAssigned handler is called repeatedly over time. What if in addition to the GetEvents() method we also provided a Load(events) method that received events that we just want to apply to the object?</p>
<pre class="brush: csharp;">public void Load(IEnumerable&lt;EventArgs&gt; events)
{
    foreach (var args in events)
    {
        // OnAdmitted(args)
        // OnBedAssigned(args)
        // etc.
    }
}</pre>
<p>Notice how moving the state changes from the public domain method into the event handler allows us to cause the state of the object to change by just loading (or applying) events to it. We can essentially change the concept of <em>now</em> for our domain objects! We can grab a set of events (say, until yesterday), load them into the object, and see what the state of the patient was as of <em>yesterday</em>. And if we were strictly following our pattern of making ALL state transitions in the private event handlers, we can be sure the object state will be <em>exactly the same</em> as it was yesterday. This is the manifestation of the apparently minor but profound change we did above when we moved the state change from the public method to the private event handler. We have replay capabilities now in our domain objects!</p>
<p>This is very useful capability that we gained with very little effort. So now we not only have business analytics capabilities built-in, but also historical replay for every entity we code this way. This is huge. But there’s even more, as we’ll see later.</p>
<p>Let’s first finish our implementation of the Load method: we need a way to know which handlers to call for which events, and we can do that by registering the mapping between event types and handler methods in the constructor:</p>
<pre class="brush: csharp;">public Patient()
{
    this.Handles&lt;PatientAdmitted&gt;(this.OnAdmitted);
    this.Handles&lt;BedAssigned&gt;(this.OnBedAssigned);
}

private Dictionary&lt;Type, Action&lt;EventArgs&gt;&gt; handlers = new Dictionary&lt;Type, Action&lt;EventArgs&gt;&gt;();

private void Handles&lt;TEvent&gt;(Action&lt;TEvent&gt; handler)
    where TEvent : EventArgs
{
    this.handlers.Add(typeof(TEvent), @event =&gt; handler((TEvent)@event));
}

public void Load(IEnumerable&lt;EventArgs&gt; events)
{
    foreach (var @event in events)
    {
        var handler = default(Action&lt;EventArgs&gt;);
        if (this.handlers.TryGetValue(@event.GetType(), out handler))
            handler(@event);
    }
}</pre>
<p>The Handles method simply stores a delegate that knows how to call our handler. Our dictionary contains the event type –&gt;Action map. The action has to be generic (can’t have a separate list for Action&lt;PatientAdmitted&gt;, another for Action&lt;BedAssigned&gt; and so on), so we just make the action receive the generic EventArgs type, which we just cast to the type we know it will have for our event handler: </p>
<pre class="brush: csharp;">this.handlers.Add(typeof(TEvent), @event =&gt; handler((TEvent)@event));</pre>
<p>When the Load method finds an Action handler for a given event type, it will just call our lambda with no reflection involved. We’ll then cast from the generic base event data type the Load event passes us, down to the one the specific handler expects:</p>
<pre class="brush: csharp;">handler(@event) –&gt;(calls our lambda in Handles)-&gt; @event =&gt; handler((TEvent)@event))</pre>
<p>With that in place, the following works perfectly:</p>
<pre class="brush: csharp;">var patient = new Patient(); // load somehow
patient.Admit();
patient.AssignBed(1);

// grab events as of now.
var yesterdayEvents = patient.GetEvents().ToList();

// Do something more with the patient.
patient.AssignBed(2);
patient.AssignBed(3);

// Later on, we want to see
// patient as it was yesterday.
var yesterdayPatient = new Patient();
yesterdayPatient.Load(yesterdayEvents);

Debug.Assert(yesterdayPatient.Bed == 1);</pre>
<p>Note how depending on what events we load on the patient, we get the state currently reflecting as of that time. One thing you might have noticed at this point, is that as we’re loading events and calling the various OnXXX handlers, we’re also causing the corresponding .NET events to fire! That shouldn’t be the case, as the .NET events are the external notification that happens when the event was <em>originally</em> created. So it seems appropriate to move the raising of the .NET event to the domain method instead:</p>
<pre class="brush: csharp;">public void Admit()
{
    if (this.IsInHospital)
        throw new InvalidOperationException(&quot;Already in hospital!&quot;);

    var args = new PatientAdmitted();
    this.Raise(args, this.OnAdmitted);
    this.Admitted(this, args);
}

private void OnAdmitted(PatientAdmitted args)
{
    this.IsInHospital = true;
}</pre>
<p>And it’s now pretty obvious that the Raise method is not actually raising anything, but actually <em>applying</em> the event data to the object. So we can rename that method now and call it Apply instead. </p>
<p>Now that we have the event type and handler map in place from the constructor we added, we can even simplify the way we raise events too. We had:</p>
<pre class="brush: csharp;">public void Admit()
{
    if (this.IsInHospital)
        throw new InvalidOperationException(&quot;Already in hospital!&quot;);

    this.Apply(new PatientAdmitted(), this.OnAdmitted);    this.Admitted(this, args);
}</pre>
<p>But now we already know what handler to call for events of type PatientAdmitted (as demostrated when we loaded events), so the call should instead just be: Raise(new PatientAdmitted()): </p>
<pre class="brush: csharp;">private void Raise&lt;TEvent&gt;(TEvent args)
    where TEvent : EventArgs
{
    this.events.Add(args);

    var handler = default(Action&lt;EventArgs&gt;);
    if (this.handlers.TryGetValue(args.GetType(), out handler))
        handler(args);
}</pre>
<p>And if we move all that generic code to a base class, we end up with a pretty straightforward way of implementing our domain classes:</p>
<pre class="brush: csharp;">public class Patient : DomainObject
{
    public event EventHandler&lt;PatientAdmitted&gt; Admitted = (sender, args) =&gt; { };
    public event EventHandler&lt;BedAssigned&gt; BedAssigned = (sender, args) =&gt; { };

    public Patient()
    {
        this.Handles&lt;PatientAdmitted&gt;(this.OnAdmitted);
        this.Handles&lt;BedAssigned&gt;(this.OnBedAssigned);
    }

    public int Bed { get; private set; }
    public bool IsInHospital { get; private set; }

    public void Admit()
    {
        if (this.IsInHospital)
            throw new InvalidOperationException(&quot;Already in hospital!&quot;);

        var args = new PatientAdmitted()
        this.Apply(args);
        this.Admitted(this, args);
    }

    public void AssignBed(int bed)
    {
        if (!this.IsInHospital)
            throw new InvalidOperationException(&quot;Patient must be in the hospital to assign a bed&quot;);
        if (bed &lt; 0)
            throw new ArgumentException(&quot;Invalid bed number&quot;);

        var args = new BedAssigned(bed);
        this.Apply(args);
        this.BedAssigned(this, args);
    }

    private void OnBedAssigned(BedAssigned args)
    {
        this.Bed = args.Bed;
    }

    private void OnAdmitted(PatientAdmitted args)
    {
        this.IsInHospital = true;
    }
}</pre>
<p>Note also that we wouldn’t typically want to allow our objects to be mutated by applying arbitrary events at arbitrary times (i.e. after performing operations on it), so we’d typically make the Load method protected on the base class, and expose two constructors for our objects instead:</p>
<pre class="brush: csharp;">private Patient()
{
    this.Handles&lt;PatientCreated&gt;(this.OnCreated);
    this.Handles&lt;PatientAdmitted&gt;(this.OnAdmitted);
    this.Handles&lt;BedAssigned&gt;(this.OnBedAssigned);
}

public Patient(int id)
    : this()
{
    if (id &lt; 0)
      throw new ArgumentException(&quot;Invalid patient identifier&quot;);

    this.Apply(new PatientCreated(id));
}

public Patient(IEnumerable&lt;EventArgs&gt; events)
    : this()
{
    this.Load(events);
}</pre>
<p>As true OO design mandates, our object cannot be constructed in an invalid state: you can either create a new patient (first time he comes in), with a valid identifier, or you create a patient by loading a set of events. Notice how both public constructors call the private parameterless constructor which hooks up the event-handler map. Also key is that even for the new patient creation constructor, we also follow the pattern we’ve explained: we don’t just blindly set the Id property. Instead, we validate the argument, apply a proper event data class, which in turn sets the Id:</p>
<pre class="brush: csharp;">private void OnCreated(PatientCreated args)
{
    this.Id = args.Id;
}</pre>
<p>Another subtlety to notice, is that in this case we don’t expose a corresponding .NET event for the object creation event. The reason is quite obvious: nobody would be able to attach to the event before the object is constructed, at which point it would be too late to catch the event using plain .NET event handlers. Our mechanism to retrieve object events and push them to an event stream would still work, however. This highlights another important thing: </p>
<blockquote>
<p>Raising a .NET event for a domain event is <em>optional</em>.</p>
</blockquote>
<p>Given that you’re performing the analysis and storage of events (as we’ll see in my next post) using a different API than plain .NET event handlers (our current GetEvents() method), there’s no requirement that you expose your event data as .NET events at all. And if you’re not doing so, there’s not even a requirement that the event data classes derive from EventArgs either! It’s really up to you.&#160; </p>
<p>&#160;</p>
<p>And that, dear reader, is the essence of the <strong>Event Sourcing pattern</strong>. Nothing more, nothing less. As Folwer says:</p>
<blockquote>
<p>The fundamental idea of Event Sourcing is that of ensuring every change to the state of an application is captured in an event object, and that these event objects are themselves stored in the sequence they were applied for the same lifetime as the application state itself.</p>
</blockquote>
<p>And I’ll talk about the storage in my next post. To peek at what’s coming, you can install the <a href="http://kzu.to/tl7euc" target="_blank">Event Sourcing NETFx package</a>, which includes the DomainObject base class we’ve been discussing in this post (and a bit more).</p>
<p>&#160;</p>
<p>Stay tunned.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=Pd6U0qLypi0:b2Oec-3Ssso:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=Pd6U0qLypi0:b2Oec-3Ssso:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=Pd6U0qLypi0:b2Oec-3Ssso:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=Pd6U0qLypi0:b2Oec-3Ssso:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/Pd6U0qLypi0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/event-centric-super-charge-your-model-with-domain-events-to-enable-business-intelligence/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/event-centric-super-charge-your-model-with-domain-events-to-enable-business-intelligence/</feedburner:origLink></item>
		<item>
		<title>Event Centric: finding key business value by leveraging domain events and reactive extensions</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/eKaH8rNZBzw/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/event-centric-finding-key-business-value-by-leveraging-domain-events-and-reactive-extensions/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 13:58:30 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[eventsourcing]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/event-centric-finding-key-business-value-by-leveraging-domain-events-and-reactive-extensions/</guid>
		<description>Reactive Extensions (Rx) is one of the coolest additions to .NET ever. However, they have been largely ignored by the mainstream, in a significant part because (IMO) it’s seen as a UI technique, with samples that show how to handle mouse moves, drag &amp;#38; drop and so on. Its focus on asynchronous programming too makes [...]</description>
			<content:encoded><![CDATA[<p><a href="http://kzu.to/rsPavA" target="_blank">Reactive Extensions</a> (Rx) is one of the coolest additions to .NET ever. However, they have been largely ignored by the mainstream, in a significant part because (IMO) it’s seen as a <a href="http://www.reactiveui.net/" target="_blank">UI technique</a>, with samples that show how to handle mouse moves, drag &amp; drop and so on. Its focus on asynchronous programming too makes it look like a niche technique that might even be worth skipping over as we wait for <a href="http://kzu.to/vBpKrj" target="_blank">C# 5.0 async keyword</a> (see <a href="http://kzu.to/vJuwi7" target="_blank">Mike’s blog entry</a> on a possible clarification of where it might fit in the async world).</p>
<p>There is, however, one mainstream application of reactive extensions that seems to have been missed by most: business intelligence. Here’s one concrete example: pretty soon, <a href="http://kzu.to/uxwOmY" target="_blank">hospitals will face penalties for patient readmission</a>, so you need a way to get an alert whenever patients are readmitted before a certain elapsed time (say 5 days or whatever). Another one: you want to preventively block a user’s account after 5 consecutive login failures within a minute (looks like an automated attack), or shoot an sms to the support team when failure rates for your app go above 5 crashes a day, or keep a report of top trending products in a store, and so on.</p>
<p>The common theme across all those kinds of business queries is that they involve the concept of time passing and events happening (patients admitted and discharged from hospitals, users trying to log-in, an app crashing, a product being downloaded), things that the Reactive Extensions models as first class citizens. These events are not .NET events, but <em>domain events</em>, the representation of something meaningful that happened to your system.</p>
<p>And how would the query for readmitted patients look like? Pretty much like a SQL query would, actually:</p>
<pre>var events = new EventStream();
var query =
    from discharged in events.Of&lt;PatientLeftHospital&gt;()
    from admitted in events.Of&lt;PatientEnteredHospital&gt;()
    where
        admitted.PatientId == discharged.PatientId &amp;&amp;
        (admitted.When - discharged.When).Days &lt; 5
    select admitted;</pre>
<p>Note how we’re joining the patient discharge events with the admission ones based on the patient id, and filtering those where the difference between a readmission event (that is, it’s When is greater than a previous discharge’s When) and a previous discharge is less than 5 days. Looks pretty darn easy to author and grasp.</p>
<p>The login failures one:</p>
<pre>var query = events.Of&lt;LoginFailure&gt;()
    // Sliding windows 1' long, every 10''
    .Buffer(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10), scheduler)
    // From all failure values
    .SelectMany(failures =&gt; failures
        // Group the failures by user
        .GroupBy(failure =&gt; failure.UserId)
        // Only grab those failures with more than 5 in the 1' window
        .Where(group =&gt; group.Count() &gt;= 5)
        // Return the user id that failed to log in
        .Select(group =&gt; group.Key));</pre>
<p>And the app crash one would be very similar to the one above. The most interesting ones are of course those that combine data from multiple events, like the hospital example.</p>
<p>The EventStream class is simply a pass-through of events that turns things that are pushed through it into observable streams of specific events. This allows the queries to receive just one dependency, the event stream, and grab the events they are interested in by using the Of&lt;TEvent&gt; method:</p>
<pre>partial interface IEventStream
{
    void Push&lt;TEvent&gt;(TEvent @event);
    IObservable&lt;TEvent&gt; Of&lt;TEvent&gt;();
}</pre>
<p>The implementation is surprisingly simple with <a href="http://kzu.to/uD6ysq" target="_blank">Reactive Extensions</a>:</p>
<pre>partial class EventStream : IEventStream
{
    private ConcurrentDictionary&lt;Type, object&gt; subjects = new ConcurrentDictionary&lt;Type, object&gt;();

    public void Push&lt;TEvent&gt;(TEvent @event)
    {
        Guard.NotNull(() =&gt; @event, @event);

        var subject = this.subjects.Find(@event.GetType()) as Subject&lt;TEvent&gt;;
        if (subject != null)
            subject.OnNext(@event);
    }

    public IObservable&lt;TEvent&gt; Of&lt;TEvent&gt;()
    {
        return (IObservable&lt;TEvent&gt;)subjects.GetOrAdd(typeof(TEvent), type =&gt; new Subject&lt;TEvent&gt;());
    }
}</pre>
<p>I’ve put this together as a <a href="http://kzu.to/rPiZEs" target="_blank">NuGet for your convenience</a>. I’ve also published a <a href="http://kzu.to/sYGqDW" target="_blank">unit tests package</a> for it, so you get the above examples to play.</p>
<p>This seems like a rather simple thing, and even one that isn’t so revolutionary by itself. Might seem like just an improved way to query a log, but in real-time. Like many things, the true power comes when it’s combined with other patterns, specifically <a href="http://kzu.to/og0QJ5" target="_blank">Event Sourcing</a> (ES), as I’ll explain in my next blog post. And that’s the reason behind the title’s prefix, a hint to Greg’s upcoming <a href="http://kzu.to/to2aQj" target="_blank">Event Centric</a> book, which talks about the ES pattern (although I doubt it will mention how combining it with Rx makes for the killer business argument for adopting it).</p>
<p>&nbsp;</p>
<p>Stay tunned!</p>
<p>&nbsp;</p>
<p>[Update] The “surprisingly simple” implementation explained above is surprisingly limiting too <img src='http://blogs.clariusconsulting.net/kzu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Namely: the subscriber has to use the exact same type as the publisher in order for a subscription to be called. In other words: no support for covariant subscriptions, subscriptions to interfaces implemented by the concrete events, etc. (i.e. the EventPattern&lt;TEventArgs&gt; from Rx wouldn&#8217;t work for subscriptions to the base EventPattern&lt;EventArgs&gt;). So I had to make it a bit more complicated to support everything the CLR supports in terms of assignable types. The updated nuget package contains the full implementation.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=eKaH8rNZBzw:3urZOEv1W3c:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=eKaH8rNZBzw:3urZOEv1W3c:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=eKaH8rNZBzw:3urZOEv1W3c:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=eKaH8rNZBzw:3urZOEv1W3c:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/eKaH8rNZBzw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/event-centric-finding-key-business-value-by-leveraging-domain-events-and-reactive-extensions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/event-centric-finding-key-business-value-by-leveraging-domain-events-and-reactive-extensions/</feedburner:origLink></item>
		<item>
		<title>How to make object initializers more useful</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/O1gnwk5KoxQ/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/how-to-make-object-initializers-more-useful/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 05:37:31 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/how-to-make-object-initializers-more-useful/</guid>
		<description>Quite often, it&amp;#8217;s necessary to validate an object state when it&amp;#8217;s initialized. With constructor arguments, this is easy to do as it can be done at the end or beginning of the constructor code. With object initializers, it&amp;#8217;s nearly impossible, as there&amp;#8217;s no way to know programmatically when the object initialization is finished. There&amp;#8217;s a [...]</description>
			<content:encoded><![CDATA[<p>Quite often, it&#8217;s necessary to validate an object state when it&#8217;s initialized. With constructor arguments, this is easy to do as it can be done at the end or beginning of the constructor code. With object initializers, it&#8217;s nearly impossible, as there&#8217;s no way to know programmatically when the object initialization is finished.</p>
<p>There&#8217;s a built-in mechanism for this that is being used in WinForms and WPF: the ISupportInitialize interface. The initialization code generated by both toolkits checks to determine if the object implements the interface. If it does, it will call BeginInit() before invoking all property setters, and EndInit() at the end. This provides a nice hook for validating all properties and maybe interrelated ones.</p>
<p>Adding this to the IL generated by the compiler for object initializers would make them immensely more useful. I&#8217;d be willing to replace many ctor overloads with properties if I had that hook, given the much more readable code that results from using object initializers.</p>
<p>&#160;</p>
<p>Microsoft Connect site used to be the place where you suggested things. I did for this one, and Mads Torgersen, C# Language PM, <a href="http://kzu.to/nEz3oC" target="_blank">liked the idea</a>. But alas, they closed the bug as Won’t Fix back in 2008 (as it was way too late for C# 4.0/VS2008) and never reopened it. I cannot reopen it either now for consideration for C# 5.0. And it seems in the meantime, they changed their mind and now suggestions should go to a UserVoice site. Sigh.</p>
<p>So I basically cloned the suggestion in the new site. Please go vote to <a href="http://kzu.to/rpOYNs" target="_blank">get support for ISupportInitialize on object initializers in C# 5.0</a>!</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=O1gnwk5KoxQ:VljeVSxvP3A:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=O1gnwk5KoxQ:VljeVSxvP3A:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=O1gnwk5KoxQ:VljeVSxvP3A:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=O1gnwk5KoxQ:VljeVSxvP3A:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/O1gnwk5KoxQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/how-to-make-object-initializers-more-useful/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/how-to-make-object-initializers-more-useful/</feedburner:origLink></item>
		<item>
		<title>Cloud-aware music done right: Spotify is the iTunes, Zune, Amazon Cloud Player and Google Music killer</title>
		<link>http://feedproxy.google.com/~r/DanielCazzulino/~3/eI4_8Hqhfsw/</link>
		<comments>http://blogs.clariusconsulting.net/kzu/cloud-aware-music-done-right-spotify-is-the-itunes-zune-amazon-cloud-player-and-google-music-killer/#comments</comments>
		<pubDate>Wed, 27 Jul 2011 07:13:00 +0000</pubDate>
		<dc:creator>kzu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[gadgets]]></category>

		<guid isPermaLink="false">http://blogs.clariusconsulting.net/kzu/cloud-aware-music-done-right-spotify-is-the-itunes-zune-amazon-cloud-player-and-google-music-killer/</guid>
		<description>Oh boy, how I’ve been waiting for something like Spotify!!! Just got an account setup (like 10’ ago) and I’m already blown away by it. Everything I’ve always wanted, truly. To help you tell whether my evaluation is worth reading, these are the (music capable/usable) devices I own/owned and use/used actively: iPod Touch (first gen) [...]</description>
			<content:encoded><![CDATA[<p>Oh boy, how I’ve been waiting for something like <a href="http://www.spotify.com" target="_blank">Spotify</a>!!! Just got an account setup (like 10’ ago) and I’m already blown away by it. Everything I’ve always wanted, truly. </p>
<p>To help you tell whether my evaluation is worth reading, these are the (music capable/usable) devices I own/owned and use/used actively:</p>
<ol>
<li>iPod Touch (first gen) </li>
<li>iPad 1 </li>
<li>Zune Player </li>
<li>T-Mobile G1 </li>
<li>Google Nexus One </li>
<li>Galaxy Tab 7’’ </li>
<li>Galaxy Tab 10.1 </li>
<li>Windows 7 HTPC </li>
</ol>
<p>And these are online music services I’ve used (either currently -soon to be dropped- or very recently). Note that they offer varying services and capabilities, so they cannot be compared easily, but they are all related to music, and I’m just noting the plus/minus I found for each:</p>
<ol>
<li><a href="http://grooveshark.com/#/settings/subscriptions" target="_blank">Grooveshark Anywhere</a>: $9 per month       <br />+ Offline caching (per playlist or per song)       <br />+ Playlists that can be made offline entirely       <br />+ Android support       <br />- iPhone/iPod not supported (<a href="http://blog.grooveshark.com/post/964834618/what-happened-to-the-grooveshark-iphone-app" target="_blank">blame Steve</a>)       <br />- Sound quality very disparate       <br />- Duplicate songs, albums, kinda messy </li>
<li><a href="https://live.zune.net/account/buySubscription" target="_blank">Zune Pass</a>: $15 per month for unlimited downloads       <br />+ 10 free songs to keep (plain mp3, no DRM)       <br />+ Up to 5 devices simultaneously       <br />+ Pretty extensive music catalog (far from everything, though)       <br />+ Sleekest mobile and desktop app       <br />+ Awesome music quality, even while streaming       <br />+ Found good new bands from “Smart-DJ” mode (radio with a “seed” artist)       <br />- Microsoft-only </li>
<li>iTunes &#8211; No streaming      <br />- Sync with a freakin’ cable, etc.       <br />- Pay per song/album       <br />- Epic #fail.       <br />(The first two alone discouraged me enough that I never bought a single song through it. Yeah, there’s a beta 10.4 of “iTunes in the Cloud” now, which still doesn’t do streaming. Too little, way too late) </li>
<li>Amazon Cloud Player      <br />+ Upload my existing songs       <br />+ Nice Android app       <br />+ Multiple (Android platform only currently <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-sadsmile" alt="Sad smile" src="http://blogs.clariusconsulting.net/kzu/files/2011/07/wlEmoticon-sadsmile.png" />) devices supported       <br />+ Amazon recommendation system behind your purchases       <br />- No radio mode       <br />- No subscription mode for unlimited streaming (have to buy songs/albums)       <br />- To sync my songs across devices, I have to upload to cloud and pay for storage </li>
<li>Google Music: haven’t used it yet, but looks to be more or less like Amazon’s (-recommendations) </li>
<li><a href="http://www.last.fm/subscribe" target="_blank">Last.fm subscription</a>: $3 per month       <br />+ Multiple devices supported (even XBox!)       <br />- No offline support       <br />- No custom playlists that I could find </li>
</ol>
<p>&#160;</p>
<p>So I set out to try out for a month Spotify. Got a Premium account, and downloaded the desktop, Android and iPod clients. I hate iTunes with a passion, so I would have preferred a more creative desktop client than essentially a cleaned-up version of iTunes. I wish they copied Zune software instead which is truly gorgeous and (r?)evolutionary as a media player.</p>
<p>Now, here’s how you do sync in this age, Apple:</p>
<p><a href="http://blogs.clariusconsulting.net/kzu/files/2011/07/image3.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://blogs.clariusconsulting.net/kzu/files/2011/07/image_thumb.png" width="1064" height="684" /></a></p>
<p>At no point, ever, you need to connect a cable between your computer and your device. Ever. Here I’m sync’ing for offline play on the laptop the most excelent <a href="http://open.spotify.com/album/3RZRfLtJ1arwxWwIhPaVQg" target="_blank">Nightwish End of an Era CDs</a> right off the cloud (I don’t own this album). </p>
<p>Here’s another view but now sync’ing to my Nexus One phone:</p>
<p><a href="http://blogs.clariusconsulting.net/kzu/files/2011/07/image7.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://blogs.clariusconsulting.net/kzu/files/2011/07/image7_thumb.png" width="1078" height="681" /></a></p>
<p>And now with ALL my current devices (except for the Zune) connected (couldn’t rename the Galaxy Tab 10.1 device, option appears greyed out <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-sadsmile" alt="Sad smile" src="http://blogs.clariusconsulting.net/kzu/files/2011/07/wlEmoticon-sadsmile.png" />):</p>
<p><a href="http://blogs.clariusconsulting.net/kzu/files/2011/07/image4.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://blogs.clariusconsulting.net/kzu/files/2011/07/image_thumb1.png" width="883" height="733" /></a></p>
<p>Truly amazing. Totally sold.</p>
<p>Needless to say, you can of course do everything you can do from the desktop client (except manage sync on other devices, AFAICS) from each mobile client (search, create playlists, cache for offline, etc.).</p>
<p>One thing I didn’t like is that you can only play on one device at a time. Starting on another pauses whichever other device is using the same username. I prefer the Zune’s approach of letting up to 5 simultaneous devices to be used. Imagine my wife is playing something on the HTPC for my kids and at the same time I’m working on my office. Can’t use my account on both. Means I have to pay more unnecessarily. Resorting to caching the music ahead of time and offlining one client or the other to avoid notifying Spotify and pause the other, is not going to work <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-sadsmile" alt="Sad smile" src="http://blogs.clariusconsulting.net/kzu/files/2011/07/wlEmoticon-sadsmile.png" />.</p>
<p>&#160;</p>
<p>As a general purpose music player for my local files, it also looks pretty decent, so although I’m sure I’ll miss the desktop Zune software, I think I’m ready to let it go.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=eI4_8Hqhfsw:iYCjyDlVzVQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=eI4_8Hqhfsw:iYCjyDlVzVQ:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?i=eI4_8Hqhfsw:iYCjyDlVzVQ:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DanielCazzulino?a=eI4_8Hqhfsw:iYCjyDlVzVQ:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/DanielCazzulino?d=7Q72WNTAKBA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DanielCazzulino/~4/eI4_8Hqhfsw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.clariusconsulting.net/kzu/cloud-aware-music-done-right-spotify-is-the-itunes-zune-amazon-cloud-player-and-google-music-killer/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blogs.clariusconsulting.net/kzu/cloud-aware-music-done-right-spotify-is-the-itunes-zune-amazon-cloud-player-and-google-music-killer/</feedburner:origLink></item>
	</channel>
</rss>

