<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Coding Insomnia</title>
	<atom:link href="http://coding-insomnia.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://coding-insomnia.com</link>
	<description>Things that keep me from sleeping</description>
	<lastBuildDate>Mon, 06 May 2013 07:12:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Clustering RabbitMQ on Windows</title>
		<link>http://coding-insomnia.com/2013/02/23/clustering-rabbitmq-on-windows/</link>
		<comments>http://coding-insomnia.com/2013/02/23/clustering-rabbitmq-on-windows/#comments</comments>
		<pubDate>Sat, 23 Feb 2013 18:21:35 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[MassTransit]]></category>
		<category><![CDATA[RabbitMQ]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=393</guid>
		<description><![CDATA[Getting up and running with RabbitMQ (especially when using MassTransit) is a breeze. It may not exactly be the NancyFX Super-Duper-Happy-Path™, but it comes closer to it than any other ServiceBus/Broker I&#8217;ve come across. However, the first time I laid eyes on the RabbitMQ guidance for Distribution, High Availability, and Clustering I started thinking that ...<a class="post-readmore" href="http://coding-insomnia.com/2013/02/23/clustering-rabbitmq-on-windows/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>Getting up and running with RabbitMQ (especially when using MassTransit) is a breeze. It may not exactly be the NancyFX Super-Duper-Happy-Path™, but it comes closer to it than any other ServiceBus/Broker I&#8217;ve come across.</p>
<p>However, the first time I laid eyes on the <a href="http://previous.rabbitmq.com/distributed.html" title="Distributed RabbitMQ">RabbitMQ guidance for Distribution, High Availability, and Clustering</a> I started thinking that maybe this wasn&#8217;t such a good idea..</p>
<p>Anyway, a few days ago I finally spent a couple of hours together with our Ops guys building a lab environment. Turns out that setting up a RabbitMQ cluster on Windows Server isn&#8217;t that hard after all, but we did run into a few gotchas along the way. Thought I&#8217;d share the experience with you!</p>
<p><img class="alignright size-full wp-image-394" alt="RabbitMQ - Cluster" src="http://coding-insomnia.com/wp-content/uploads/2013/02/RabbitMQ-Cluster.png" width="304" height="244" /></p>
<h2>High Level overview of the setup</h2>
<p>We decided to use dedicated virtual machines for running the Rabbit cluster. The alternative would have been to run it on the same boxes that run our application services, but somehow it feels better to have it separated. I&#8217;m sure you can argue pros and cons here, but I&#8217;m going to leave that to someone else.</p>
<p>The RabbitMQ boxes have a load balancer in front so that the application services don&#8217;t need to know which physical machine(s) to connect to. The load balancer is currently configured with a simple round robin algorithm and will automatically remove non-responsive machines from the rotation.</p>
<h2>Installing</h2>
<p>First thing to do is to install Erlang and RabbitMQ. Just get the latest stable versions from <a href="http://erlang.org" title="Erlang">erlang.org</a> and <a href="http://rabbitmq.com" title="RabbitMQ">rabbitmq.com</a>. By default, RabbitMQ installs its database in the <code>%APPDATA%</code> folder of whoever installs the service, something that seems far from ideal when in a server environment. So before running the installation we made sure to set the <code>%RABBITMQ_BASE%</code> environment variable to a more appropriate location (for us it&#8217;s <code>d:\RabbitMQ</code>). Other than that the installation is just a matter of doing the Next-&gt;Next-&gt;Next-&gt;Confirm dance.</p>
<p>Next we want to enable the management web interface. This is done by first enabling the plugin:</p>
<pre>rabbitmq-plugins enable rabbitmq_management</pre>
<p>Next, the changes has to be properly applied by reinstalling the service:</p>
<pre>rabbitmq-service stop
rabbitmq-service install
rabbitmq-service start</pre>
<p>You can make sure that the management interface is working by pointing a web browser to <a href="http://localhost:15672">http://localhost:15672</a></p>
<h2>Erlang Cookie</h2>
<p>The documentation for RabbitMQ mentions that in order to connect a RabbitMQ cluster, all instances must share the same Erlang cookie. The cookie is a simple text file called .erlang.cookie that resides in your user folder (i.e. <code>c:\Users\[UserName]</code>). In order for the RabbitMQ Service to work, the same cookie-file must also be copied to your <code>%WINDIR%</code> (usually <code>c:\Windows</code>). All this is usually handled automatically by the installer and command line tools. However, there is one important gotcha. If you log on to the box with a new account, it will get a new Erlang cookie that doesn&#8217;t match the one that the RabbitMQ Service is running which means it won&#8217;t be able to administer the service. The easy solution is to copy the one in <code>c:\Windows</code> to the user directory for everyone who may want to use the RabbitMQ command line tools. We are probably going to set this up by pushing a login scripts to all users of the box.</p>
<h2>(Windows) Firewall settings</h2>
<p>This information is somewhat scattered in the RabbitMQ documentation, so here goes. You need the following things opened up:</p>
<table>
<thead>
<tr>
<th>Port</th>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<tr>
<td>5672</td>
<td>This is the main AMQP port that clients use to talk to the broker.</td>
</tr>
<tr>
<td>15672</td>
<td>The management web interface.</td>
</tr>
<tr>
<td>4369</td>
<td>Used by EPMD (Erlang  Port Mapper Daemon). This makes sure that the nodes can find each other.</td>
</tr>
</tbody>
</table>
<p>Finally, you also need to allow the <strong>Erlang runtime (erl.exe)</strong> to communicate between the nodes. You can either set a port range yourself in <a href="http://www.rabbitmq.com/configure.html#configuration-file" title="RabbitMQ configuration file">rabbitmq.config</a> (<code>inet_dist_listen_min</code> and <code>inet_dist_listen_max</code>) and open up that range in the firewall, or you can do what we did and allow <code>erl.exe</code> to communicate freely. Note that the Erlang runtime installs two bin folders that both contain erl.exe. The one that seems to be used by the service is in the subdirectory named something like <code>C:\Program Files\erl5.9.3.1\erts-5.9.3.1\bin</code></p>
<h2>Joining a cluster</h2>
<p>Creating and/or joining a cluster is actually the easiest bit. You just log on to one of the machines and issue these commands (if joining a cluster on RABBIT01):</p>
<pre>rabbitmqctl stop_app
rabbitmqctl join_cluster rabbit@RABBIT01
rabbitmqctl start_app</pre>
<p>NOTE that the host name of the server (RABBIT01 in this case) should be in UPPER CASE when working with Windows instances.<br />
We decided to go with only disc nodes. Mostly because it doesn&#8217;t seem like using RAM nodes would be much of a performance gain anyway. But I may be completely off here..</p>
<h2>Mirroring your queues</h2>
<p>When the cluster is up and running, queues and exchanges can be created the same way you usually do. However, the queues will still be localized to a single box, and if that box fails the queue is gone. This is likely not what you want if the reason for clustering was to make things Highly Available.</p>
<p>In previous versions of RabbitMQ, a queue was mirrored by setting the &#8220;x-ha-policy&#8221; as an attribute when creating the queue. As of version 3.0, you now set the policies either using the management web interface or the command line tool:</p>
<pre>rabbitmqctl set_policy ha-all "^ha\." "{""ha-mode"":""all""}"</pre>
<p>The above line will create a new policy called &#8220;ha-all&#8221; (what you call it is not important), it matches all queues with a name starting with &#8220;ha.&#8221; (using a regular expression) and sets the ha-mode policy to all (which will mirror the queue to all nodes in the cluster).</p>
<h2>Profit!</h2>
<p>After getting everything up and running we started trying to break things. Mostly everything worked just as expected. When stopping the service on one machine (or completely shutting down the machine), the cluster recovered as expected. It is important to realize that messages that arrived in the cluster while a node is down won&#8217;t be mirrored to that node when it comes back up. So in a scenario where you need to restart all machines in a cluster, you should follow a procedure such as this:</p>
<ol type="1">
<li value="1">Restart node 1.</li>
<li>Bring node 1 back to the cluster (usually does this automatically)</li>
<li>Monitor your queues and wait until all unmirrored messages have been processed.</li>
<li>Restart node 2.</li>
<li>Etc, etc.</li>
</ol>
<p>Please let me know if I&#8217;ve missed something crucial or if there are things you&#8217;d like to know more about!</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2013/02/23/clustering-rabbitmq-on-windows/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>A Trip to CQRS &#8211; New Views</title>
		<link>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views/</link>
		<comments>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views/#comments</comments>
		<pubDate>Tue, 29 May 2012 21:15:10 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=353</guid>
		<description><![CDATA[This is part 5 of 5. The entire series is here: Intro Commands Events Authoritative Events New Views We finally have a reasonably flexible architecture to play with. We’ve separated our Commands, we’re storing our Events and we’re using them to build our domain model. Let’s see what else we can do, shall we? What ...<a class="post-readmore" href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>This is part 5 of 5. The entire series is here:</em></p>
<ol>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro">Intro</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands">Commands</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events">Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events">Authoritative Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views">New Views</a></em></li>
</ol>
<p>We finally have a reasonably flexible architecture to play with. We’ve separated our Commands, we’re storing our Events and we’re using them to build our domain model. Let’s see what else we can do, shall we?</p>
<p>What if we would like to show a history of the last 20 changes made to the system on the front page? Prior to our refactoring that would have introduced quite a lot of problems. In fact, if you run the demo system (or come see me the next time I do this talk) you’ll see that we’ve had the service layer and UI ready for it, but since there was no nice way of implementing it, it’s been left as a hard-coded dummy.</p>
<h2>Use those Events</h2>
<p>But in our new model, this is actually a piece of cake! We just introduce a new Event Handler that subscribes to all events that are considered as “changes we’d like to show on the front page”, and use it to update a HistoryItem table in the database:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/history-view/src/HotelAdmin.Service/EventHandlers/HistoryItemEventHandlers.cs?slice=8:87&footer=minimal"></script>
<p>Any change from now on will also be passed on to the new view and will show up on the front page. Pretty sweet, isn&#8217;t it?</p>
<h2>Drop it like it’s hot</h2>
<p>Yes. Sweet. But we can do one better.</p>
<p>You know that database of yours? Drop it. Yes. You heard me. DROP it! (But let&#8217;s keep the Event Store, ok?)</p>
<p>Remember that we are now Event Sourced? And what is it that you do in an Event Sourced system when your view model changes? You reset it and you replay your events, and that is exactly what we&#8217;re going to do too:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/history-view/src/HotelAdmin.Loader/Events/EventReloader.cs?slice=7:17&footer=minimal"></script>
<p>And Hey Presto! We have our old database back, now with a complete set of HistoryItems since the day we started logging. Now THAT is sweet..!</p>
<h2>Summary</h2>
<p>I cannot stress this enough. This is NOT the way you do CQRS on .NET. It is most likely not even a good idea for you to even think about doing this. But, given the right circumstances and a similar set of problems that we faced. Well, I’ve certainly enjoyed it and the system is proving to be fairly flexible. </p>
<p>If you want to hear more, let me know! I’m happy to share and I would be MORE than happy to hear your thoughts on this! Either pop a comment on one of the posts, or engage me on Twitter (<a href="http://twitter.com/CodingInsomnia">@CodingInsomnia</a> as usual).</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Trip to CQRS &#8211; Authoritative Events</title>
		<link>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events/</link>
		<comments>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events/#comments</comments>
		<pubDate>Tue, 29 May 2012 20:25:07 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=349</guid>
		<description><![CDATA[This is part 4 of 5. The entire series is here: Intro Commands Events Authoritative Events New Views I left you in the previous post with a bit of a cliff-hanger, didn’t I? So what is the “rather major flaw” in our nice Event publishing system? Well, the big problem is that it may be ...<a class="post-readmore" href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>This is part 4 of 5. The entire series is here:</em></p>
<ol>
<ol>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro">Intro</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands">Commands</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events">Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events">Authoritative Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views">New Views</a></em></li>
</ol>
</ol>
<p>I left you in the previous post with a bit of a cliff-hanger, didn’t I? So what is the “rather major flaw” in our nice Event publishing system? </p>
<p>Well, the big problem is that it may be hard for us, and for the business, to really trust our Events. Let’s have a quick look back into the code where a Command Handler publishes an event:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/events/src/HotelAdmin.Service/CommandHandlers/AddHotelCommandHandler.cs?slice=41:51&footer=minimal"></script>
<p>What if we made a mistake here? I mean, not that I would ever consider using Copy&amp;Paste for any kind of coding, but.. Let&#8217;s say that we accidentally set the Description property in the event to message.Name instead of message.Description. Then imagine this conversation, three years from now:</p>
<blockquote><p><strong>PM:</strong> We have a customer complaining that the hotel she stayed at didn’t have AC even though the description clearly stated that it would. She claims we changed the text the day after she got home.</p>
<p><strong>Me:</strong> Yes! We finally get to use our Event Log! I’ll get right on it!</p>
<p><strong>PM:</strong> I was hoping you’d say something like that.</p>
<p><strong>Me:</strong> Ehh.. Uhm.. Hang on.. Ouch.. What if I told you we never actually saved the Description field…?</p>
<p><strong>PM:</strong> You’re FIRED!</p>
</blockquote>
<p>What we need is a way to really be able to trust that the data we store in our Event Log contains *all* the data that we may need in the future.</p>
<h2>Event Sourcing</h2>
<p>Usually, Event Sourcing is used together with DDD to replay state into aggregates. But taking the term literally, it just means that our Events are used as the source for all changes in our system. And that is exactly what we’ll do next.</p>
<p><img alt="CQRS Authoritative Events" src="http://trip2cqrs.apphb.com/img/cqrs-architecture-authoritative.png"></p>
<p>Instead of letting the Command Handler update the database, all that logic is moved into one or more corresponding Event Handlers. The Command Handler will now validate the Command to make sure it makes sense given the state of the system, then publish an Event:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/authoritative-events/src/HotelAdmin.Service/CommandHandlers/UpdateHotelCommandHandler.cs?slice=10:40&footer=minimal"></script>
<p>The Event will be picked up by the Event Handler which will perform any updates:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/authoritative-events/src/HotelAdmin.Service/EventHandlers/HotelEventHandlers.cs?slice=8:92&footer=minimal"></script>
<p>How you divide your Event Handlers is pretty much up to you. We decided to have one class per Aggregate-thingy (They are not true DDD-style aggregates, but in my mind that&#8217;s still how I prefer to think about them..)</p>
<h2>Testing</h2>
<p>Testing now becomes even cleaner. We can separate the Command Handler tests from the Event Handlers. When testing the Command Handler we make sure that the correct Event is published (if validation is ok):</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/authoritative-events/src/HotelAdmin.Service.Tests/CommandHandlers/UpdateHotel/When_Handling_UpdateHotelCommand.cs?slice=10:71&footer=minimal"></script>
<p>And testing the Event Handler we just have to make sure that given a specific Event, the correct changes are persisted:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/authoritative-events/src/HotelAdmin.Service.Tests/EventHandlers/Hotels/When_Handling_HotelUpdatedEvent.cs?slice=9:71&footer=minimal"></script><br />
<h2>Benefits</h2>
<p>A rather simple refactoring that makes ALL the difference. Our Events are now Authoritative. Since we base all changes to the system on them, we can be pretty sure that any change that our users see will also be stored for good in the Event Log. </p>
<p>Well, enough with the architectural changes. Let’s see if we can use this for something cool! Oh.. Right.. That’ll have to wait until the next, and final post of the series.</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Trip to CQRS &#8211; Events</title>
		<link>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events/</link>
		<comments>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events/#comments</comments>
		<pubDate>Tue, 29 May 2012 19:08:20 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=342</guid>
		<description><![CDATA[This is part 3 of 5. The entire series is here: Intro Commands Events Authoritative Events New Views In my last post, the system was introduced to Commands in order to structure the code a bit and make sure to separate the updates from the reads. Now it’s time to actually bring in some business ...<a class="post-readmore" href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>This is part 3 of 5. The entire series is here:</em></p>
<ol>
<ol>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro">Intro</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands">Commands</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events">Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events">Authoritative Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views">New Views</a></em></li>
</ol>
</ol>
<p>In my last post, the system was introduced to Commands in order to structure the code a bit and make sure to separate the updates from the reads. Now it’s time to actually bring in some business value!</p>
<p>Remember, the two new requirements we had was to 1) Log all changes, and 2) Pass change information to other systems in near real-time. And what better to handle this than Events?</p>
<p>Our events are simple DTOs, usually mapping more or less exactly to a Command:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/events/src/HotelAdmin.Messages/Events/HotelAddedEvent.cs?slice=4:20&footer=minimal"></script>
<p><img alt="CQRS Events" src="http://trip2cqrs.apphb.com/img/cqrs-architecture-events.png"></p>
<p>Now, usually in a “proper” DDD-ES-CQRS system (D-DDD or whatever you’d like to call it) we would let the domain objects publish these events whenever an interesting action has occurred. Unfortunately, we are not blessed with a nice DDD model, instead we have our Command Handlers that use the very <a href="http://martinfowler.com/bliki/AnemicDomainModel.html">Anemic Domain Model</a> (curtsey of Entity Framework) to push updates to the database. Instead, we’ll simply let the Command Handlers publish events themselves.</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/events/src/HotelAdmin.Service/CommandHandlers/AddHotelCommandHandler.cs?slice=24:52&footer=minimal"></script>
<p>Events are published to an event store (which happens to be <a href="https://github.com/joliver/EventStore">EventStore</a> in this case). The event store is responsible for, well, storing the events and also sending them off to anyone else who might be interested (represented as Event Handlers in the diagram). For integrating with downstream system, something like a Service Bus would probably be a good thing to put in here.</p>
<h2>Testing</h2>
<p>Testing with this scenario looks very much the same as testing in the last one, but now we also make sure that the published Events are looking good. </p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/events/src/HotelAdmin.Service.Tests/CommandHandlers/AddHotel/When_Handling_AddHotelCommand.cs?slice=10:103&footer=minimal"></script><br />
<h2>Benefits</h2>
<p>Well, we now have our complete log of all changes in the system (the Event Store). We also have a quite extensible mechanism for doing real-time integration (using a Service Bus, EventHandlers etc..)! So, we’re done, right? </p>
<p>Nope. I’m afraid not. Because there is one, quite major, flaw in this system. And that will be the topic for the next post!</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Trip to CQRS &#8211; Commands</title>
		<link>http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands/</link>
		<comments>http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands/#comments</comments>
		<pubDate>Mon, 28 May 2012 20:32:33 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=323</guid>
		<description><![CDATA[This is part 2 of 5. The entire series is here: Intro Commands Events Authoritative Events New Views This is post #2 in the series. I very much recommend you to read them in order, otherwise I’m pretty sure confusion will arise.. All the code for this step is found on the commands branch: https://github.com/andlju/hotel-admin/tree/commands ...<a class="post-readmore" href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>This is part 2 of 5. The entire series is here:</em></p>
<ol>
<ol>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro">Intro</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands">Commands</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events">Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events">Authoritative Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views">New Views</a></em></li>
</ol>
</ol>
<p>This is post #2 in the series. I very much recommend you to read them in order, otherwise I’m pretty sure confusion will arise.. All the code for this step is found on the commands branch:</p>
<p><a href="https://github.com/andlju/hotel-admin/tree/commands">https://github.com/andlju/hotel-admin/tree/commands</a></p>
<h2>Commands and Command Handlers</h2>
<p>Anyway, this is when we actually do something useful. Let’s introduce Commands!</p>
<p><img alt="CQRS Commands" src="http://trip2cqrs.apphb.com/img/cqrs-architecture-commands.png"></p>
<p>A Command is simply a DTO-type of object that contains the data necessary for the service to make one specific change to the state of the system. As an example, the AddHotelCommand looks like this:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/commands/src/HotelAdmin.Messages/Commands/AddHotelCommand.cs?slice=4:15&footer=minimal"></script>
<p>The commands are pushed to a simple <a href="https://github.com/andlju/hotel-admin/blob/commands/src/HotelAdmin.Service/Infrastructure/MessageDispatcher.cs">Dispatcher</a> who passes them on to an appropriate Command Handler:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/commands/src/HotelAdmin.Service/CommandHandlers/AddHotelCommandHandler.cs?slice=7:38&footer=minimal"></script>
<p>No we need to make sure that the old Transaction Script methods are updated to publish commands instead of using repositories themselves. This is when we run into the first issue.</p>
<p>Have a look at the signature of the Remote Façade:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/commands/src/HotelAdmin.Service/IHotelService.cs?slice=20:22&footer=minimal"></script>
<p>Spot the problem? Yes, it is supposed to return the id of the newly created Hotel, otherwise the UI will be in trouble. But we have already stated that Commands are not allowed to return stuff, so what to do?</p>
<h2>Identities</h2>
<p>The common answer to that problem when it arises in a CQRS system is to use Guids as identifiers. That way the client (or whoever sends the Command) can be the one creating the identifier and does not have to wait for the server to respond before continuing to work on the object.</p>
<p>We pretty much have two options here. Remodel the database to use Guids instead of auto-incremented Ids, or introduce some kind of mapping between the two. Since we&#8217;ve said from the start that the DB should remain as intact as possible, mapping had to be the solution of choice for us. </p>
<p>If you look at the end of the AddHotelCommandHandler above, you&#8217;ll see that the last thing that happens is a call to _identityMapper.Map. This will insert the mapping in a simple lookup table. The AddHotel method in the service can now use this map in order to return the Id:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/commands/src/HotelAdmin.Service/HotelService.cs?slice=95:111&footer=minimal"></script>
<p>If you&#8217;re paying attention, this will be the place where you say something like: &#8220;But, but. This means that all Command Handlers must be synchronous. And maybe even inside a.. a.. a Transaction??&#8221;. And you&#8217;ll be completely correct. But notice how &#8220;improved performance/scalability&#8221; was never one of the goals for this refactoring. I may revisit this though, so hang tight through the next couple of posts..</p>
<h2>Testing</h2>
<p>Testing the Commands are pretty similar to testing the old Service. We can put a little bit more thought into the base fixture though, since we know that the “When” will always be a Command, and the “Given” will be a Command Handler:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/commands/src/HotelAdmin.Service.Tests/CommandHandlers/AddHotel/When_Handling_AddHotelCommand.cs?slice=9:75&footer=minimal"></script><br />
<h2>Benefits</h2>
<p>Now I did promise that we would gain at least something in each step, didn’t I? Well, this may be a bit of a long-shot, but at least we have introduced a bit of Single Responsibility/Separation of Concerns to our architecture. The Command Handlers only have to inject the dependencies they actually need (as opposed to the old Service which is likely to become quite bloated). On the other hand, things did get a little more complex by introducing the Dispatcher, not to mention the Identity Map thingy… </p>
<p>You’d better keep reading the next post. Things may make a little bit more sense after that one.</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Trip to CQRS &#8211; Intro</title>
		<link>http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro/</link>
		<comments>http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro/#comments</comments>
		<pubDate>Mon, 28 May 2012 18:42:38 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[CQRS]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=310</guid>
		<description><![CDATA[This is part 1 of 5. The entire series is here: Intro Commands Events Authoritative Events New Views A couple of days ago I held a presentation at DevSum 2012 in Stockholm. The topic was “A Trip to CQRS” and is basically me talking about a project that we’ve been working on for the past ...<a class="post-readmore" href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>This is part 1 of 5. The entire series is here:</em></p>
<ol>
<ol>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro">Intro</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-commands">Commands</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-events">Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-authoritative-events">Authoritative Events</a></em></li>
<li><em><a href="http://coding-insomnia.com/2012/05/29/a-trip-to-cqrs-new-views">New Views</a></em></li>
</ol>
</ol>
<p>A couple of days ago I held a presentation at DevSum 2012 in Stockholm. The topic was “A Trip to CQRS” and is basically me talking about a project that we’ve been working on for the past year or so. We basically found ourselves refactoring a system from a traditional nTier, CRUD, Entity Framework-solution to something that could be called Event Sourced CQRS (but without the nice DDD-part..) The talk was fairly well-received so I thought I’d take some time to blog about it too.</p>
<p>In this first post I will introduce the sample system and the reasoning behind the refactoring. I have pushed the entire sample system to my github. The code in its “before”-state is in the master branch: </p>
<p><a title="https://github.com/andlju/hotel-admin/tree/master" href="https://github.com/andlju/hotel-admin/tree/master">https://github.com/andlju/hotel-admin/tree/master</a></p>
<h2>Based on a true story…</h2>
<p>The talk (and this article) will not show the actual system since it’s an internal system in a domain that isn’t really well-known by people outside of our company. Instead, I’ve created a mock system that should be easy enough to grasp quickly, but complex enough to show most of the difficulties we faced. The infrastructure code is more or less exactly the same though.</p>
<p>The domain I’ve chosen for the mock system is Hotel Information. </p>
<p><img style="margin: 4px 10px" src="http://trip2cqrs.apphb.com/img/domain-model.png"></p>
<p>We have a Hotel object that has some basic information about a hotel. The Hotel can have one or more Facts (i.e DistanceToVillage = 500m) and the Fact is of a specific FactType.</p>
<p>The reason why we decided to move to CQRS was the two new requirements that we were handed:</p>
<ul>
<li>Several “downstream” systems needs to be integrated in more or less real-time.
<li>We need to keep a complete log of every change that happens in the system for auditing purposes. </li>
</ul>
<p>Both of these seemed like a pretty good reason to introduce Events of some sort, and since I had recently listened a lot to Greg Young. Well.. I simply couldn’t help myself.. <img src='http://coding-insomnia.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Architecture (Before)</h2>
<p>First, let’s examine the state of the system pre-refactoring. As I mentioned, it’s pretty standard nTier/CRUD. A simplified diagram would look something like this:</p>
<p><img alt="Layers" src="http://trip2cqrs.apphb.com/img/layered-architecture-before.png"></p>
<p>The client connects to a façade (in the real case it’s a WebService, in the sample code I’m calling the “service layer” directly but that really doesn’t change a lot..). The façade uses DTOs so no domain objects travel across boundaries.</p>
<p>Below the façade sits some kind of business logic (the Application Service layer in this diagram). There is no true DDD-style Domain Model however, so all logic is contained in <a href="http://martinfowler.com/eaaCatalog/transactionScript.html">Transaction Scripts</a>. </p>
<p>Accessing data is done via a quite simple Repository-pattern framework I’ve done (<a href="http://nuget.org/packages?q=petite.repository">Petite.Repository</a>, available on NuGet) that sits on top of Entity Framework. </p>
<p>Let’s just show you some code. Here are a few snippets from the HotelService. The first one is the method that returns a single Hotel:</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/master/src/HotelAdmin.Service/HotelService.cs?slice=23:32&footer=minimal"></script>
<p>Next are the Add and Update methods from the same file.</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/master/src/HotelAdmin.Service/HotelService.cs?slice=90:110&footer=minimal"></script>
<p>Nothing fancy and not very exciting. </p>
<p>While I have your attention though, I might as well show you one of the test classes. I’m fairly happy with these actually and they get even better as we move to a more CQRSy model.</p>
<p><script src = "http://gist-it.sudarmuthu.com/github/andlju/hotel-admin/blob/master/src/HotelAdmin.Service.Tests/When_Updating_An_Existing_Hotel.cs?slice=6:56&footer=minimal"></script><br />
<h2>CQRS – The Silver Bullet?</h2>
<p>This is not going to be a “Introduction to CQRS” article. If you don’t have a clue of what I’m talking about I very much recommend you to visit the <a href="http://cqrs.wordpress.com/">CQRS Info site</a>. </p>
<p>Anyway, as you know, the main point of CQRS is to separate your stuff into Commands and Queries, where Commands are used to change the state of your system (but without returning said state to you) and Queries are used to, you guessed it, return the state of your system (but without changing it).</p>
<h2>Keeping compatible with UI and DB</h2>
<p>The following conversation never actually happened since I played it up in my head quite a few times, and the result was always the same:</p>
<blockquote><p><strong>Me:</strong> You know the system we’ve been working on for the past 6 months? I’d like to make a few changes.</p>
<p><strong>PM:</strong> OK, that’s cool I guess. You need to change a column in the DB or something?</p>
<p><strong>Me:</strong> Eh. No. I’d like to replace the DB with an Event Store and some read models in RavenDB. I’d also like to rethink the UI so that it is more in line with the Task Based model that is preferred in CQRS systems. </p>
<p><strong>PM:</strong> Ain’t gonna happen.</p>
<p><strong>Me:</strong> Bummer.</p>
</blockquote>
<p>Instead, I tried to find a model that would let me keep as much as possible of the work that had already been done while still bringing in some of the nicer attributes of a CQRS system. I wanted to keep the Façade compatible so that the UI wouldn’t have to change. Also, the DB was already used by a few SSIS-packages (and I hate making changes to our dbproj-files) so I wanted to keep as much of that as possible too. That pretty much meant that all the work would have to be done right in the middle!</p>
<p><img alt="Layers" src="http://trip2cqrs.apphb.com/img/layered-architecture-keep-compatibility.png"></p>
<h2>Step by step to CQRS bliss</h2>
<p>In the following series of posts I will take you step by step through the process we took. Each step in itself brings something to the table and I think it will be easier to follow my reasoning if we divide it. That said, if you want to do something like this yourself I would probably recommend to do it all in one swoop..</p>
<h2>Queries</h2>
<p>OK, this this first one is very easy. At least for now.</p>
<p><img alt="CQRS Queries" src="http://trip2cqrs.apphb.com/img/cqrs-architecture-queries.png"></p>
<p>The queries, i.e all the Get, List, and Find-methods: Keep ‘em! As we won’t change the database model this should be fine. Later on we will be able to do a lot of fun stuff with queries though, but we won’t go there yet.</p>
<p>Tune in to the next episode where I’ll show you Commands. That should be at least a bit more interesting. <img src='http://coding-insomnia.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2012/05/28/a-trip-to-cqrs-intro/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Petite &#8211; Why another IoC Container?</title>
		<link>http://coding-insomnia.com/2011/04/14/petite-why-another-ioc-container/</link>
		<comments>http://coding-insomnia.com/2011/04/14/petite-why-another-ioc-container/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 19:18:25 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Container]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Petite]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/2011/04/14/petitewhy-another-ioc-container/</guid>
		<description><![CDATA[Ouch, this turned into a long boring post. Here’s a tl;dr: “Unity was slow and clumsy, I couldn’t find an alternative that I really enjoyed so I wrote my own container. It’s on NuGet and github!” Since being sold on IoC and Dependency Injection around 2008 I’ve been using Unity as the container-of-choice. Why? Well, ...<a class="post-readmore" href="http://coding-insomnia.com/2011/04/14/petite-why-another-ioc-container/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>Ouch, this turned into a long boring post. Here’s a tl;dr: “</em><em>Unity was slow and clumsy, I couldn’t find an alternative that I really enjoyed so I wrote my own container. It’s on <a href="http://nuget.org/List/Search?packageType=Packages&amp;searchCategory=All+Categories&amp;searchTerm=petite&amp;sortOrder=package-download-count&amp;pageSize=10">NuGet</a> and <a href="https://github.com/andlju/Petite">github</a>!”</em></p>
<p>Since being sold on IoC and Dependency Injection around 2008 I’ve been using Unity as the container-of-choice. Why? Well, why does anyone use Unity? Because Microsoft wrote it and it has everything you could possibly ask for in a container. Well, except speed of course. And ease of use. And some way of understanding what the heck is going on behind the scenes. But, those where realizations that kind of crept up on me, and once they did I had gotten so used to them that I didn’t really mind them too much.</p>
<p>Then a few months ago I started setting up yet another web service project and started thinking that maybe I should look around a bit before just doing what I always do. I set up a couple of simple goals I wanted a new container to fulfill:</p>
<ol>
<li>Easy to use and troubleshoot. In Unity whenever someone made a mistake with a registration, more often than not they had to go find me to help them find the problem.</li>
<li>Fast. In this project in particular, speed is of the utmost importance. And I really mean that. Every fraction of a millisecond actually counts.</li>
<li>Simple. Most often we only use the basics of a DI container, we simply don’t need tons of features.</li>
</ol>
<p>Quite early I heard about <a href="http://funq.codeplex.com/">Funq</a> and I immediately fell in love with the idea of specifying a factory method instead of relying on reflection. First of all, it is of course blazingly fast. But more importantly a lot of common errors, such as adding a new parameter to a constructor without telling the registration about it, are all of a sudden found at compile-time instead of at runtime.</p>
<p>So, why didn’t I just use Funq (or <a href="http://munq.codeplex.com/">Munq</a>, a project with pretty much the same ideas as I had)? Why did I go ahead and write my own version? Well, the most obvious reason is of course – because I felt like it. But also, Funq seemed to be a bit more bloated than I needed (among other things it has a lot of <a href="http://funq.codeplex.com/SourceControl/changeset/view/643423d8435e#src%2fCore%2fFunq%2fContainer.Register.cs">strange code-genned overloads</a> and stuff). Even Munq has quite a bit of code which definitely might make it easier to get started with (such as automatic registration), but it also makes it a little less transparent and a little more tricky to troubleshoot.</p>
<p>What really tipped me over though was that one of the biggest complaints I hear all the time about Unity is that it is impossibly to debug your way through a program when so much of it is put together in an assembly that you cannot easily step into. Sure, the code is available and it is quite possible to set it up on a symbol server or something similar, but having the code right there in your project would make it oh-so-much easier for everyone involved.</p>
<p>Aaanyway.. <a href="http://nuget.org/List/Packages/Petite.Container">Petite.Container</a> and <a href="http://nuget.org/List/Packages/Petite.Container.CommonServiceLocator">Petite.Container.CommonServiceLocator</a> are now found on NuGet (together with <a href="http://nuget.org/List/Packages/Petite.Repository.Domain">Petite.Repository.Domain</a> and <a href="http://nuget.org/List/Packages/Petite.Repository.Data">Petite.Repository.Data</a> which I’ll try to write a little about some other time). And all the code with some unit tests etc is on <a href="https://github.com/andlju/Petite">github</a>. Feel free to use it, but be aware that these are early bits not yet tried and tested in production (they will be quite soon though).</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2011/04/14/petite-why-another-ioc-container/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entile &#8211; MVVM and Extra Information</title>
		<link>http://coding-insomnia.com/2011/02/09/entile-mvvm-and-extra-information/</link>
		<comments>http://coding-insomnia.com/2011/02/09/entile-mvvm-and-extra-information/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 22:33:41 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Entile]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=285</guid>
		<description><![CDATA[In my last post I did the easy and demo friendly 5-minute install of Entile. But what if you need some more control? Perhaps you’re using the MVVM pattern (actually, I really hope you do), and most likely you need to be able to pass some more information about your user in order to send ...<a class="post-readmore" href="http://coding-insomnia.com/2011/02/09/entile-mvvm-and-extra-information/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>In my last post I did the easy and demo friendly <a href="http://coding-insomnia.com/2011/01/28/entile-from-zero-to-toast-in-5-minutes/">5-minute install of Entile</a>. But what if you need some more control? Perhaps you’re using the MVVM pattern (actually, I really hope you do), and most likely you need to be able to pass some more information about your user in order to send them relevant toasts and tiles.</em> </p>
<p>Today I thought I’d take you through the things you need to know in order to get Entile working with this scenario – sending and using extra information to the server from an MVVM-based phone project. If you are interested in Windows Phone 7 development but have no idea what I’m talking about, start off by having a look at the <a href="http://coding-insomnia.com/entile/">Entile summary page</a>.</p>
<h2>Client side</h2>
<p>Let’s begin with your ViewModel. The main entrypoint for all things Entile on the client is, lo and behold, the EntileClient class. This should be a singleton somewhere in your Windows Phone application. It is pretty much up to you where you want to store it – the important thing is that you need to be able to access it whenever you want to change the status of your registration with the Entile Service (such as turning on/off notifications and passing extra information). In this reasonably simple case I only have a single ViewModel called MainViewModel, so I’ll add the Entile client directly to it:</p>
<pre class="brush: c-sharp; toolbar: false">public class MainViewModel : INotifyPropertyChanged
{
    private readonly EntileClient _entile;

    public MainViewModel()
    {
        _entile = new EntileClient();
    }

    public EntileClient Entile
    {
        get { return _entile; }
    }</pre>
<p>Next, let&#8217;s drop the EntileView user control on the MainPage (which is the view that uses the MainViewModel. While we&#8217;re at it, let&#8217;s also add a simple text box where we can enter some extra information to send to the server:</p>
<pre class="brush: xhtml; toolbar: false">    &lt;StackPanel&gt;
        &lt;TextBlock Text=&quot;Enter tile title&quot;/&gt;
        &lt;TextBox Text=&quot;{Binding TileTitle, Mode=TwoWay}&quot;/&gt;
                    
        &lt;TestApp:EntileView DataContext=&quot;{Binding Entile}&quot;/&gt;
    &lt;/StackPanel&gt;</pre>
<p>Last thing to do on the client side is to setup the TileTitle property so that it actually passes the information to Entile. This is done by the UpdateExtraInfo method on the EntileClient object. </p>
<pre class="brush: c-sharp; toolbar: false">    private string _tileTitle;
    public string TileTitle
    {
        get { return _tileTitle; }
        set
        {
            _tileTitle = value;
            NotifyPropertyChanged(&quot;TileTitle&quot;);
            UpdateRegistrationInfo();
        }
    }

    private void UpdateRegistrationInfo()
    {
        var info = new Dictionary&lt;string, string&gt;();
        info[&quot;TileTitle&quot;] = TileTitle;
        _entile.UpdateExtraInfo(info);
    }</pre>
<p>Running this without modifying anything on the server side will save that extra info in whatever storage you are using (most likely an Xml-file in the App_Data directory). </p>
<h2>Server side</h2>
<p>OK, to the server side implementation!</p>
<p>As you may have noticed, for each module on the server you generally have two main classes; the Module and the Service. The Module will be instantiated when your application starts up and will be kept in memory until it shuts down. The Service will be created on demand when one of its endpoints is invoked. </p>
<p>You have access to two important interfaces, INotificationQueue and IRegistrator. They are passed on the constructor of the Service or in the Initialize method of the Module.</p>
<p><strong>IRegistrator</strong> has methods to query the registration data store for information about any registered clients. You can also subscribe to events such as ClientRegistered or ClientExtraInfoUpdated. </p>
<p><strong>INotificationQueue</strong> is the interface that helps you send Tiles and Toasts. The only method you should use is EnqueueItem which takes either a ToastNotification or a TileNotification (and optionally a DateTime if you want to send the notification at a later point in time).</p>
<p>In this example, I’m going to subscribe to the ClientExtraInfoUpdated event and when that happens, immediately send a TileNotification where the Title has been set to whatever the client passed in as the TileTitle in its extra info.</p>
<pre class="brush: c-sharp; toolbar: false">    private INotificationQueue _notificationQueue;
    private IRegistrator _registrator;

    public void Initialize(INotificationQueue notificationQueue, IRegistrator registrator)
    {
        _registrator = registrator;
        _notificationQueue = notificationQueue;
            
        _registrator.ClientExtraInfoUpdated += (a, e) =&gt; SendTile(e.UniqueId);
    }

    private void SendTile(string uniqueId)
    {
        var extraInfo = _registrator.GetExtraInfo(uniqueId);
        string tileTitle;
        if (extraInfo.TryGetValue(&quot;TileTitle&quot;, out tileTitle))
        {
            var tile = new TileNotification(uniqueId)
                            {
                                Title = tileTitle
                            };
                
            _notificationQueue.EnqueueItem(tile);
        }
    }</pre>
<p>OK, I was going to add some nice screenshots of this in action, but for some weird reason my WordPress installation doesn’t want me to do that today…</p>
<h2>Conclusion</h2>
<p>So, this post introduced you to the concept of Extra Information passed from the Entile client to the server. First I showed how you can store the EntileClient object in your MVVM model. I then showed you the UpdateExtraInfo method and how to call it. Finally, I introduced you to the two main server-side interfaces, INotificationQueue and IRegistrator and one way of putting them to use.</p>
<p>As always I welcome all comments, suggestions and, well.. any life-signs at all actually..!</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2011/02/09/entile-mvvm-and-extra-information/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Entile &#8211; From Zero to Toast in 5 minutes</title>
		<link>http://coding-insomnia.com/2011/01/28/entile-from-zero-to-toast-in-5-minutes/</link>
		<comments>http://coding-insomnia.com/2011/01/28/entile-from-zero-to-toast-in-5-minutes/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 21:25:07 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Entile]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=252</guid>
		<description><![CDATA[Yesterday, I made two NuGet packages for Entile available in the NuGet gallery. Today, I thought I’d walk you through how to get started! I will show you how to create a completely functional app with a Live Tile as well as Toast notifications. Prerequisites You’ll need the following installed on your developer machine: Visual ...<a class="post-readmore" href="http://coding-insomnia.com/2011/01/28/entile-from-zero-to-toast-in-5-minutes/">read more</a>]]></description>
				<content:encoded><![CDATA[<p><em>Yesterday, I made two NuGet packages for Entile available in the NuGet gallery. Today, I thought I’d walk you through how to get started! I will show you how to create a completely functional app with a Live Tile as well as Toast notifications.</em></p>
<h2>Prerequisites</h2>
<p>You’ll need the following installed on your developer machine:</p>
<ul>
<li>Visual Studio 2010 with <a href="http://create.msdn.com">Windows Phone Developer Tools</a></li>
<li>NuGet package manager (installed with <a href="http://www.asp.net/mvc/mvc3">ASP.NET MVC3</a> – can also be <a href="http://nuget.org/">installed separately</a>)</li>
</ul>
<h2>Create the Windows Phone 7 App</h2>
<p>First of all, let’s create a simple Windows Phone 7 App. I’m using the Pivot template from the Silverlight Toolkit, but any template will do.</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step1-Create-App.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step1-Create-App" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step1-Create-App_thumb.png" border="0" alt="Step1-Create-App" width="374" height="271" /></a></p>
<h2>Create the Web Application</h2>
<p>While we are at it, we’ll create the Server part of the application too. In this case, I’m going for an empty ASP.NET MVC 3 application, but again, more or less any Web Application or WCF Service Application will do.</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step2-Create-Host.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step2-Create-Host" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step2-Create-Host_thumb.png" border="0" alt="Step2-Create-Host" width="379" height="268" /></a></p>
<h2>Add the NuGet packages</h2>
<p>Open up the Library Package console (Tools-&gt;Library Package Manager-&gt;Package Manager Console). Type the following into the console (replace EntileDemo.App with the name of your Windows Phone 7 Project and EntileDemo.Host with the name of your Web Application project):</p>
<p>Install-Package entile-client -Project EntileDemo.App</p>
<p>Install-Package entile-server -Project EntileDemo.Host</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step3-Install-Package.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step3-Install-Package" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step3-Install-Package_thumb.png" border="0" alt="Step3-Install-Package" width="607" height="293" /></a></p>
<p>This will download and install the client and the server part of Entile into your solution. You should now be able to build everything, but it won’t run properly just yet.</p>
<h2>Configuring the client</h2>
<p>Now it is time to make sure that the client knows how to talk to the server. By default, all client-side settings are found in the EntileSettings.xaml file. Open it up and change the RegistrationServiceUri and the AllowedTileUris entries to point to the name of your host. Working locally on your dev machine it will look something like this (where 1234 should be replaced by the port number of your Web Application):</p>
<pre class="brush: xhtml; toolbar: false">&lt;sys:String x:Key="RegistrationServiceUri"&gt;http://localhost:1234/Sample/Registration&lt;/sys:String&gt;

&lt;sys:String x:Key="AllowedTileUris"&gt;http://localhost:1234&lt;/sys:String&gt;</pre>
<p>You should also set the ChannelName to something that makes sense, perhaps “DemoChannel”?</p>
<p>Then we just need to hook up the settings to make the application aware of them. You do this by adding the following lines to the Application.Resources element in your App.xaml file:</p>
<pre class="brush: xhtml; toolbar: false">&lt;ResourceDictionary&gt;
    &lt;ResourceDictionary.MergedDictionaries&gt;
        &lt;ResourceDictionary Source="EntileSettings.xaml"/&gt;
    &lt;/ResourceDictionary.MergedDictionaries&gt;
&lt;/ResourceDictionary&gt;</pre>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step4-App-xaml.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step4-App-xaml" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step4-App-xaml_thumb.png" border="0" alt="Step4-App-xaml" width="473" height="146" /></a></p>
<h2>Configuring the server</h2>
<p>Now we need to configure the Sample module found in the server. First of all, in the root of your Web Application you should now have a file called EntileStartup.cs. This is where all modules are registered, all we need to do here is to change the host name:</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step5-EntileStartup.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step5-EntileStartup" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step5-EntileStartup_thumb.png" border="0" alt="Step5-EntileStartup" width="488" height="134" /></a></p>
<p>One more thing, let’s also make sure that we can send a nice Live Tile by, again, changing the host name – this time it’s in the EntileModules\SampleService.cs file:</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step6-EntileService.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step6-EntileService" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step6-EntileService_thumb.png" border="0" alt="Step6-EntileService" width="603" height="249" /></a></p>
<h2>Add the view</h2>
<p>Finally (yes, this is indeed the last setup step) we are going to add the EntileView to your App. First, make sure that you have built the project. Next, open up the MainPage.xaml file and find a nice place for the EntileView user control. I chose to put it on a PivotItem called “settings”. The easiest way to get it there is to find it in the toolbox and drag it onto the xaml:</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step7-EntileView.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step7-EntileView" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step7-EntileView_thumb.png" border="0" alt="Step7-EntileView" width="620" height="325" /></a></p>
<h2>Let’s run it, shall we?</h2>
<p>Both projects need to run at the same time, so if you haven’t done so already, open up the properties window for your solution and set it up so that they are both set to Start:</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step8-Multiple-Startup-Projects.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step8-Multiple-Startup-Projects" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step8-Multiple-Startup-Projects_thumb.png" border="0" alt="Step8-Multiple-Startup-Projects" width="476" height="307" /></a></p>
<p>Now, hit F5 and wait for both the emulator to start up with your phone app, and the web project to show a default page (a 404 in my case since I&#8217;m used an empty MVC project). Switch to the screen where you put the EntileView, and hit the checkbox. This will open up a channel and register the application with your server.</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step9-Connecting-To-Server.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step9-Connecting-To-Server" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step9-Connecting-To-Server_thumb.png" border="0" alt="Step9-Connecting-To-Server" width="400" height="318" /></a></p>
<p>So, we got this running, let’s show off the capabilities!</p>
<p>Hit the back button and pin the application to your home screen. Open up your browser and enter the following URL (as usual, substitute the host/port with your own):</p>
<p><a title="http://localhost:1234/Sample/SendSampleTileToAllClients" href="http://localhost:1234/Sample/SendSampleTileToAllClients">http://localhost:1234/Sample/SendSampleTileToAllClients</a></p>
<p>And then to finish it all off, send a toast as well:</p>
<p><a title="http://localhost:1234/Sample/SendSampleToastToAllClients" href="http://localhost:1234/Sample/SendSampleToastToAllClients">http://localhost:1234/Sample/SendSampleToastToAllClients</a></p>
<p>The result, hopefully, looks something like this:</p>
<p><a href="http://coding-insomnia.com/wp-content/uploads/2011/01/Step10-Toast-And-Tile.png"><img style="background-image: none; margin: 4px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="Step10-Toast-And-Tile" src="http://coding-insomnia.com/wp-content/uploads/2011/01/Step10-Toast-And-Tile_thumb.png" border="0" alt="Step10-Toast-And-Tile" width="402" height="319" /></a></p>
<h2>Conclusion</h2>
<p>I’ve shown how to use the Entile Notification Framework for Windows Phone 7 in order to get a Live Tile and Toast-enabled Windows Phone 7 Application in just a few minutes. Rest assured however that there is more to Entile than this. A few things you haven’t seen yet but that I hopefully will be blogging about soon enough:</p>
<ul>
<li>Data stores</li>
<li>Adding extra information to your registrations</li>
<li>The notification queue and using a worker.</li>
<li>Running in the cloud (Azure and/or AppHarbor?)</li>
<li>… and perhaps something else you’d like to know about?</li>
</ul>
<p>As always, please please do leave a comment, ping me (<a href="http://twitter.com/CodingInsomnia">@CodingInsomnia</a>) or <a href="http://twitter.com/entile_fx">@entile_fx</a> on Twitter or why not do a blog post of your own experiences with Entile? I would really like to hear from you!</p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2011/01/28/entile-from-zero-to-toast-in-5-minutes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Entile now on github</title>
		<link>http://coding-insomnia.com/2011/01/19/entile-now-on-github/</link>
		<comments>http://coding-insomnia.com/2011/01/19/entile-now-on-github/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 20:53:12 +0000</pubDate>
		<dc:creator>anders</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Entile]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://coding-insomnia.com/?p=244</guid>
		<description><![CDATA[Well, that took me long enough, didn&#8217;t it? Anyway, rejoice, because Entile Notification Framework for Windows Phone 7 is now on github! So, from now on please get your downloads from there. No major changes since the preview though, I&#8217;ve mostly spent some time getting to know how to use git and github&#8230; Feel free to contribute! ...<a class="post-readmore" href="http://coding-insomnia.com/2011/01/19/entile-now-on-github/">read more</a>]]></description>
				<content:encoded><![CDATA[<p>Well, that took me long enough, didn&#8217;t it?</p>
<p>Anyway, rejoice, because <a href="https://github.com/andlju/entile">Entile Notification Framework for Windows Phone 7 is now on github</a>!</p>
<p>So, from now on please get your downloads from there. No major changes since the preview though, I&#8217;ve mostly spent some time getting to know how to use git and github&#8230;</p>
<p>Feel free to contribute! I have no idea how to handle pull requests and so on, but I&#8217;m sure I&#8217;ll be able to figure it out. <img src='http://coding-insomnia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://coding-insomnia.com/2011/01/19/entile-now-on-github/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
