Identify Commands & Events

Identify Commans & EventsOnce I started down the path of segregating commands and queries, I soon enough ran into a few issues that I needed to solve.

  • Identifying Commands & Events
  • Correlating Commands & Events
  • Idempotent Commands
  • Idempotent Events

If you are familiar with CQRS, then you may have run into these issues as well.  If you are not completely familiar with CQRS but have heard of it, to be clear, I’m not talking about Event Sourcing, Domain Driven Design, or having multiple data stores or any of the overly complex version people think it is.

I’m simply talking about splitting up incoming requests into commands and queries.

Starting with CQRS, CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query (the same definition that is used by Meyer in Command and Query Separation, a command is any method that mutates state and a query is any method that returns a value). – Greg Young

Identifying Commands and Events

Since commands are simple objects that can be serialized.  I often will log the inbound command if there is a failure in the command handler.

This is really helpful for debugging failed commands as I can view the failed commands and retry them in my development environment for troubleshooting.

But it doesn’t stop there.

If you are emitting Events from your Command Handlers or Domain, it is often helpful to keep track of which Command caused which Event.

In Microsoft’s Patterns & Practices CQRS Journey, they created an Envelope<T> to accomplish this.

For a simplified version we can accomplish this with:

If needed, we can now wrap our commands in an Envelope before sending to the mediator.

Correlating Commands & Events

Now since we have wrapped our inbound command in an Envelop that contains a MessageId, in our Handler when emitting events, we can now add the MessageId from the Command to the CorrelationId of the new Event.

Idempotency

Next I’ll look at how I can use the Envelope for creating idempotent commands that do not contain a natural way of doing so.

How about you?

Do you apply a similar pattern as well? I’d love to hear about other implementations or uses.  Comment below or on twitter.


Other Posts

Thin Controllers with CQRS and MediatR

MediatRI’m not a fan of fat controllers.

One of the reasons I dislike having my core application logic in controllers is because I like using the web frameworks for what they are good at in my context.

My context is usually creating web api’s.

For me I use web frameworks as infrastructure that handles

  • HTTP routing and endpoints
  • Deserialization of input payloads
  • Serialization of output payloads
  • HTTP Headers and Status Codes
  • Web Stuff (eg File Uploads)

You get the gist, I like using it for handling the web.  Not for containing my features.

If you have any questions, please follow me on Twitter.

Follow @CodeOpinion on Twitter

Thin Controllers

The way that I remove any of my feature code from my controllers is thru commands and queries.

If you are familiar with CQRS, then this will make sense.  But I’m not talking about Event Sourcing, Domain Driven Design, or having multiple data stores or any of the overly complex version people think it is.

I’m simply talking about splitting up incoming requests into commands and queries.

Starting with CQRS, CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query (the same definition that is used by Meyer in Command and Query Separation, a command is any method that mutates state and a query is any method that returns a value). – Greg Young

This is pretty straight forward.  I’d guess most actually apply CQRS without really knowing it most of the time.

Repositories

I’m also not a a fan of fat repositories.

They generally end up as a giant low cohesive classes full of data access code that is used in one place.

Commands & Queries

I’ve previously posted about using Query Objects instead of Repositories.  The same applies for commands.

We will create a message (class) that will represent the command/query we want to execute.  The message will contain the arguments needed for processing the message.

In essence it’s like taking the parameters of a method and turning it into a class.

In order to facilitate mapping and handling the execution of command and queries,  I use the MediatR.

MediatR

Simple mediator implementation in .NET

In-process messaging with no dependencies.

Supports request/response, commands, queries, notifications and events, synchronous and async with intelligent dispatching via C# generic variance.

Command

Let’s take a look at a simple command for changing the pricing level of our customer.

Pretty straight forward.  It contains the minimum amount of data needed in order for us to perform the given task.

Handler

Now we will create a handler for this command message.

Now all that is left is to wire up our command to our web framework.

Controller

In this example I’m using NancyFX which uses Modules instead of Controllers.  This shouldn’t be too hard to translate if you are more familiar with Web Api.

More…

Here are some more helpful posts in regards to create commands, queries and MediatR.

How about you?

Do you apply a similar pattern as well? I’d love to hear about other implementations or uses.  Comment below or follow me on twitter.

Follow @CodeOpinion on Twitter

Couchbase Linq Provider

Couchbase

I recently decided to use Couchbase for a personal side project.  The primary reason I chose to use it was because I hadn’t yet.  Simple as that.

Again, this is for a personal side project where I try out different technologies.  The second reason was I was interested in N1QL (pronounced “nickel”) which is the Couchbase Server query language.

I’m not covering installing the Couchbase server.  if you don’t have a Couchbase server installed, check out the offical docs.

Couchbase .NET SDK

The most obvious route for accessing a Couchbase server is by using the the official Couchbase .NET Client.  Looking at the docs, its very simple to store and retrieve a documents.  However, one of the features I was most interested was if it had a Linq provider.  It does not.  Bummer.

Linq2Couchbase

Thankfully I discovered Lin2Couchbase by Couchbase Labs which is a Linq provider to produce N1QL using the official Couchbase .NET SDK.

Grab the NuGet Package

Install-Package Linq2Couchbase

Owin/Katana

My side project is a web app that is self host using Katana and NancyFX.  In order to initialize the Couchbase client, you can use the ClusterHelper in your Startup class.  The reason it is done here is that the it is only required be initialized once.  The cluster helper will create a Cluster object which will later be used to create a BucketContext.

BucketContext

If you are familiar with Entity Framework, the BucketContext from Linq2Couchbase is similar to a DbContext.  It provides an API for querying a Couchbase bucket.

You can now inject IBucketContext into your Nancy Modules or Controllers if using ASP.NET MVC/WebAPI.

Registration

Whichever DI container you are using, you will want to register IBucketContext.  I’m using Unity and my registration as follows.

 POCO

For this example, I’ve created a simple User class.  One important thing to note is that you must specify which property in your class is the key.  You can do so by adding the KeyAttribute.  Also, the Key must be a string.

Save

Adding a new object is pretty straight forward.   Just pass your new object the Save() method on the IBucketContext.

Querying

Using the BucketContext you can query your bucket which is also very straight forward.

Note: If you have just installed Couchbase, you must create a primary index on the bucket you are querying.  Refer to the documentation on how to do so.  This stumbled me a bit at the beginning.  Thankfully the Brant Burnett was kind enough to help me out.

Documentation

The GitHub page for Linq2Couchbase has a ton of goodness.  I highly recommend checking it out if you are interested in couchbase or are looking for linq support.

As of this post, the project looks very active (just recently adding async support) and hopefully I can contribute back.