<?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:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" version="2.0">

<channel>
	<title>PhatBoyG.com</title>
	
	<link>http://blog.phatboyg.com</link>
	<description>Software Architecture, .NET, SOA</description>
	<lastBuildDate>Sun, 01 Nov 2009 02:44:57 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<geo:lat>35.992283</geo:lat><geo:long>-95.805426</geo:long><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/PhatBoyG" type="application/rss+xml" /><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FPhatBoyG" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FPhatBoyG" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FPhatBoyG" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Building a Service Gateway Using MassTransit, Part 3</title>
		<link>http://blog.phatboyg.com/2009/10/31/building-a-service-gateway-using-masstransit-part-3/</link>
		<comments>http://blog.phatboyg.com/2009/10/31/building-a-service-gateway-using-masstransit-part-3/#comments</comments>
		<pubDate>Sat, 31 Oct 2009 19:48:53 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[MassTransit]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=854</guid>
		<description><![CDATA[This post is the third in a series on building a highly available service gateway. The implementation will be built in C# using MassTransit, StructureMap, ASP.NET MVC, and NHibernate.
Did somebody say code?
The past two posts began to explain how to build a service gateway using MassTransit. In this post, I&#8217;m going to share some of [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post is the third in a series on building a highly available service gateway. The implementation will be built in C# using <a href="http://code.google.com/p/masstransit/">MassTransit</a>, <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a>, <a href="http://www.asp.net/mvc/">ASP.NET MVC</a>, and <a href="http://nhforge.org/">NHibernate</a>.</em></p>
<h3>Did somebody say code?</h3>
<p>The past two posts began to explain how to build a service gateway using MassTransit. In this post, I&#8217;m going to share some of the initial code that makes up the gateway service. The gateway itself consists of two components. The first implements the communication to the external service with a set of messages that are only used internally by the service. The second is the saga that provides the interface to the service gateway.</p>
<h3>Service Contract</h3>
<p>The interface exposed to the application consists of two messages, the first for the command and the second for the response. The message contracts are defined using interfaces, allowing the class for the message to be an internal implementation detail.</p>
<p>The message contract representing a request for order details includes the CustomerId and the OrderId.</p>
<pre class="brush: csharp;">
public interface RetrieveOrderDetails
{
	string OrderId { get; }
	string CustomerId { get; }
}
</pre>
<p>When the order details are received, the following message is published.</p>
<pre class="brush: csharp;">
public interface OrderDetailsReceived
{
	string OrderId { get; }
	string CustomerId { get; }
	DateTime Created { get; }
	OrderStatus Status { get; }
}

public enum OrderStatus
{
	Unknown = 0,
	Submitted = 1,
	Accepted = 2,
	InProcess = 3,
	Complete = 4,
}
</pre>
<p>The CustomerId and OrderId are the same as the values passed in the request. Created is when the order was created, and Status is an enum representing the status of the order.</p>
<blockquote><p><em>Notice that no internal values are included &#8212; no primary key from the order table and no primary key from the customer table. The request and response are correlated on identifiers that make sense in the application domain. While SQL purists will point out that numeric primary keys are quicker for retrieving rows in a database, they make for a very fragile interface with other components in the system. Reliance on a primary key outside of the context of the system storing the order details is a path to friction or outright failure.</em></p></blockquote>
<h3>Time To Make The Saga</h3>
<p>At this point in the design of our service, the need for a saga to manage the request state is not entirely obvious. While the TDD purists might want to call YAGNI at this point, let me assure you that &#8220;it will all be&#8230; revealed!&#8221; So for now, let us take a look at the first pass of our saga definition.</p>
<pre class="brush: csharp;">
public class OrderDetailsRequestSaga :
	SagaStateMachine&lt;OrderDetailsRequestSaga&gt;,
	ISaga
{
	static OrderDetailsRequestSaga()
	{
		Define(Saga);
	}
</pre>
<p>Our saga state machine uses a static initializer to define the states, events, and transitions of a saga. The previous code merely defines our class as a saga and calls our saga initialization method (shown below).</p>
<pre class="brush: csharp;">
	private static void Saga()
	{
		Correlate(RequestReceived)
			.By((saga, message) =&gt; saga.CustomerId == message.CustomerId &amp;&amp;
			                       saga.OrderId == message.OrderId &amp;&amp;
			                       saga.CurrentState == WaitingForResponse);

		Correlate(ResponseReceived)
			.By((saga, message) =&gt; saga.CustomerId == message.CustomerId &amp;&amp;
			                       saga.OrderId == message.OrderId &amp;&amp;
			                       saga.CurrentState == WaitingForResponse);
</pre>
<p>Since our request criteria include our customer id and our order id, we use those to correlate the message to the saga. We also include the state of the saga to ensure that we do not match to a request that has already completed. We will look at some other ways we can enhance the performance of the service later on by using some additional states.</p>
<pre class="brush: csharp;">
	public static State Initial { get; set; }
	public static State WaitingForResponse { get; set; }
	public static State Completed { get; set; }
</pre>
<p>The three states we have defined, including an initial state when a new saga instance is created, a waiting for response state one our request has been sent to the service, and a completed state once the response has been received and published.</p>
<pre class="brush: csharp;">
	public static Event&lt;RetrieveOrderDetails&gt; RequestReceived { get; set; }
	public static Event&lt;OrderDetailsResponse&gt; ResponseReceived { get; set; }
	public static Event&lt;OrderDetailsRequestFailed&gt; RequestFailed { get; set; }
</pre>
<p>The three events that we have defined, including the message contract that maps to the event. The subscription logic for the saga will automatically map message handlers for these events that will invoke the actions depending upon the current state of the saga.</p>
<pre class="brush: csharp;">
		Initially(
			When(RequestReceived)
				.Then((saga, request) =&gt;
					{
						saga.OrderId = request.OrderId;
						saga.CustomerId = request.CustomerId;
					})
				.Publish((saga, request) =&gt; new SendOrderDetailsRequest
					{
						RequestId = saga.CorrelationId,
						CustomerId = saga.CustomerId,
						OrderId = saga.OrderId,
					})
				.TransitionTo(WaitingForResponse));
</pre>
<p>The first event handler, RequestReceived, is invoked when the saga is created in response to the RetrieveOrderDetails message. The handler copies the properties of the request, and then publishes the request message to the proxy that will call the external web service. After the message is published, the state of the saga transitions to the waiting for response state. When using transactional queues, the receipt of the message, creation of the saga in the database, sending of the command message to the proxy, and saving the saga are all part of a single distributed transaction. This ensures that everything completes as a single operation to ensure no requests are lost.</p>
<pre class="brush: csharp;">
		During(WaitingForResponse,
			When(ResponseReceived)
				.Then((saga, response) =&gt;
					{
						saga.OrderCreated = response.Created;
						saga.OrderStatus = response.Status;
					})
				.Publish((saga, request) =&gt; new OrderDetails
					{
						CustomerId = saga.CustomerId,
						OrderId = saga.OrderId,
						Created = saga.OrderCreated.Value,
						Status = saga.OrderStatus,
					})
				.TransitionTo(Completed));
	}
</pre>
<p>The second event handler, ResponseReceived, is invoked when the OrderDetailsResponse message is received. The results of the request are stored in the saga and a message is published containing the details of the order back to the original requestor. Another approach would be to capture the requestor address (via the ResponseAddress header from the original message) and then resolve that address using the endpoint factory to send the response directly to the requestor. I don&#8217;t really encourage this approach without having a truly unique identifier for each request.</p>
<pre class="brush: csharp;">
	public OrderDetailsRequestSaga(Guid correlationId)
	{
		CorrelationId = correlationId;
	}

	protected OrderDetailsRequestSaga()
	{
	}

	public virtual string CustomerId { get; set; }
	public virtual string OrderId { get; set; }
	public virtual OrderStatus OrderStatus { get; set; }
	public virtual DateTime? OrderCreated { get; set; }

	public virtual Guid CorrelationId { get; set; }
	public virtual IServiceBus Bus { get; set; }
}
</pre>
<p>The rest of the saga class is shown above for completeness. The properties are part of the saga and get saved when the saga is persisted (using the NHibernate saga persister, or in the case of the sample the in-memory implementation). The constructor with the Guid is used to initialize the saga when a new one is created, the protected one is there for NHibernate to be able to persist the saga.</p>
<h3>The Service Proxy</h3>
<p>The saga uses the external service proxy to perform the actual work, which is shown in the proxy class below.</p>
<pre class="brush: csharp;">
public class OrderDetailsWebServiceProxy :
	Consumes&lt;SendOrderDetailsRequest&gt;.All
{
	public void Consume(SendOrderDetailsRequest request)
	{
		// make the call to the service to get the order details here

		var details = new OrderDetailsResponse
			{
				OrderId = request.OrderId,
				CustomerId = request.CustomerId,
				Created = (-1).Days().FromUtcNow(),
				Status = OrderStatus.InProcess,
			};

		CurrentMessage.Respond(details, x =&gt; x.ExpiresAt(5.Minutes().FromNow()));
	}
}
</pre>
<p>The message handler uses the criteria from the SendOrderDetailsRequest message (which was published by the saga) to call the external service and retrieve the order details. The details are then returned to the saga in the form of an OrderDetailsResponse message which is internal to the service (and therefore not part of the interface assembly that is provided to applications that want to use the order details service).</p>
<h3>Test That Thang</h3>
<p>Now that our saga has been developed, we need to be able to test it. A unit test will be created that creates a testing instance of the service bus (see the sample for the implementation details) and verifies that the saga responds properly to the request. To request order details, a very simple client would subscribe to the response message and then publish the request.</p>
<pre class="brush: csharp;">
const string orderId = &quot;ABC123&quot;;
const string customerId = &quot;12345&quot;;

LocalBus.Subscribe&lt;OrderDetailsReceived&gt;(message =&gt;
	{
		response.Set(message);
	},
	x =&gt; x.OrderId == orderId &amp;&amp; x.CustomerId == customerId);

RetrieveOrderDetails request = new RetrieveOrderDetailsRequest(customerId, orderId);
LocalBus.Publish(request, x =&gt; x.SendResponseTo(LocalBus.Endpoint));
</pre>
<p>The subscribe method used above specifies that when a message of type OrderDetailsReceived is received, if the contents of the message match the predicate specified (which in this case, is checking the OrderId and CustomerId contained in the message) then the statement specified should be called. Our example is from the integration test (built using NUnit) that verifies the service performs from end-to-end.</p>
<p>The syntax above is functional, and it will work, but it does not represent the most scalable approach. In the next post, I&#8217;ll start to explain how to build a much more scalable method of handling thousands of concurrent requests on a single machine using IIS.</p>
<p>In the meantime, the sample code is available in the MassTransit trunk as a standalone solution. You can find it in the trunk\src\Samples\ServiceGatewaySample folder. There are unit tests that verify the calling syntax shown above and a service that hosts the services (both the saga, and the proxy service).</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/nbS9gH7EJW4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/10/31/building-a-service-gateway-using-masstransit-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building a Service Gateway Using MassTransit, Part 2</title>
		<link>http://blog.phatboyg.com/2009/10/29/building-a-service-gateway-using-masstransit-part-2/</link>
		<comments>http://blog.phatboyg.com/2009/10/29/building-a-service-gateway-using-masstransit-part-2/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 22:33:58 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[MassTransit]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=852</guid>
		<description><![CDATA[This post is the second in a series on building a highly available service gateway. The implementation will be built in C# using MassTransit, StructureMap, ASP.NET MVC, and NHibernate.

Continued&#8230;

In part one, I discussed two exchange patterns that are often exposed as a web service. In this installment, I&#8217;m going to cover a more complex exchange [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post is the second in a series on building a highly available service gateway. The implementation will be built in C# using MassTransit, StructureMap, ASP.NET MVC, and NHibernate.</em>
</p>
<h3>Continued&#8230;</h3>
<p>
In part one, I discussed two exchange patterns that are often exposed as a web service. In this installment, I&#8217;m going to cover a more complex exchange pattern that including makes a request to an external system in response to a request on our web service.
</p>
<p>
<em><br />
<blockquote>One of the comments on the previous post raised the question of using messaging for queries. Udi, Ayende, and I agree that this so-called &#8220;Data-SOA&#8221; is a bad thing. The queries I am presenting in this article are made against an external service and not an internal database. In many cases, this service might have limited availability and limited throughput, making it important to isolate our service to increase availability.</p></blockquote>
<p></em></p>
<h3>Complex Request</h3>
<p>In the simple request, order status is a small enough data point that caching it at the web service makes sense. The details of an order, however, are much more involved and it is not practical to keep the details cached in case they are requested (which in this case, is much less often that the order status). To support the order detail request, we will apply a pattern that separates the inbound request from the outbound request, ensures that requests are performed only once (minimizing the click, click, click refresh mentality of some users), and even retain requests if the outbound service is unavailable until the request expires or the outbound service becomes available.
</p>
<p>
The first thing we want to build is the service that will be responsible for calling the external web service. To start, we&#8217;ll define two messages representing the happy path of calling the service. The first message contains the criteria of the request (such as the order id and perhaps the customer id) and the second message contains the details of the order that were returned by the web service. In addition to the messages on the happy path, we may also define additional messages used to publish exception information related to the request.
</p>
<p>
Once the message contracts are defined to call the web service, we need to build a service that will handle the request messages. To do this, we&#8217;ll build a message consumer for the request message, host it inside Topshelf, and subscribe to a service bus bound to the input queue of the service.<br />
The message handler will use the request message properties to prepare the request to the external web service and produce the response message once the request returns. In this example, the external web service only supports synchronous requests (in a later article I will try to cover calling remote services that support asynchronous requests).
</p>
<p>
At this point, we have a service that responds to a command message (the request) and produces a result depending upon the outcome of the request. What we need now is a way to coordinate the requests to the service to ensure that requests are not lost due to an unavailable service, errors are retried once a failed service becomes available, and duplicate requests are ignored.
</p>
<p>
To coordinate the service requests, a saga will be created to manage the state of each request. A new message will be created to initiate the saga containing the same data that is needed to produce the request message that is sent to our gateway service. And as with the service, messages will be created to return the results of the request to the consumer of the external service. The saga will use our state machine driven saga syntax, making the business logic understandable at a glance. The saga will also define the retry parameters that should be used to recover from service outages by specifying an exception policy. The messages that are used by the requester to interact with the saga will become the interface that is used by our system to make requests to the external service. This includes the web service we are in turn providing to our customers. The internal messages used to communicate between the saga and the gateway service are not intended for use outside of our gateway service component.
</p>
<p>
<em><br />
<blockquote>A nice side benefit of this architecture involves the actual call made by the gateway service. Since the interface is defined by the messages that are orchestrated by the saga, the backing implementation can be changed without impacting the consumers of the saga-based front end. This can be a huge benefit when it comes time to change service providers or bring an external service in-house either through acquisition or new product developments.</p></blockquote>
<p></em></p>
<p>
With the saga in place (and for this example, we will go ahead and host it in the same process that we are hosting the gateway service), we are now ready to build the web service request handler. Rather than go straight into that now, I think I&#8217;m going to stop here and save that for part three. After part three is finished, I&#8217;ll start posting some of the code for the examples and include it in the samples folder to make it easy to pull down and experiment with on your own machine.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/QNgxaHd2m8I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/10/29/building-a-service-gateway-using-masstransit-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building A Service Gateway Using MassTransit, Part 1</title>
		<link>http://blog.phatboyg.com/2009/10/28/building-a-service-gateway-using-masstransit-part-1/</link>
		<comments>http://blog.phatboyg.com/2009/10/28/building-a-service-gateway-using-masstransit-part-1/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 03:18:50 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[MassTransit]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=850</guid>
		<description><![CDATA[This post is the first in a series on building a highly available service gateway. The implementation will be built in C# using MassTransit, StructureMap, ASP.NET MVC, and NHibernate.
Introduction
A common way of applying a messaging solution to an existing system is to find a tightly coupled service reference in the system and insulate the system [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post is the first in a series on building a highly available service gateway. The implementation will be built in C# using MassTransit, StructureMap, ASP.NET MVC, and NHibernate.</em></p>
<h3>Introduction</h3>
<p>A common way of applying a messaging solution to an existing system is to find a tightly coupled service reference in the system and insulate the system from that dependency. For example, the system may utilize a web service via a call from the user interface, blocking the user interface until the web service request completes. Another situation might involve a web service provided by the system which in turn calls another web service to complete the request. While these two examples are common in systems today, it is important consider how the system is using a dependent service when determining how best to insulate the system from that service.
</p>
<p>
To help make that decision, allow me to share some common exchange patterns implemented using a web service. While most web services are modeled after the request/response pattern, there are actually several types of exchanges that can occur within a web service method.
</p>
<h3>Drop Box</h3>
<p>If the web service is called by the client to provide information to the application, availability is likely the most important concern. Clients may have limited connectivity (such as a wireless client), limited resources (such as an embedded system that is unable to store data for future delivery), or a combination of these and other factors. To deal with these limitations, the web service should be designed for maximum availability to avoid failed requests due to an outage behind the web service boundary.
</p>
<p>
To support this high availability, the web service should count on the only thing that is available at the time web service method is invoked &#8212; the local machine. If the web service attempts to write the information to a database located on a server across the network that is not available, the information in the request may be lost. In this case, it would be a better choice to write a message that contains the request information to a local queue. By doing this, the request information is retained and can be processed separately from the web service request. This allows allows the web service method to return to the caller, keeping resources available for other clients to report.
</p>
<p>
Once the data from the request is safely stored in the queue, a separate service is built that consumes the messages from the queue and sends the information to the internal system, which in this case might be a database server. If the database server is unavailable, the message is left in the queue until the database is available. This new service can also be stopped and even updated without disrupting the web service from receiving requests.
</p>
<h3>Simple Request</h3>
<p>If we look at another scenario, one where the request contains search criteria and the response includes the data specified matching the request. In order to break this down in different way, we will look at two different types of requests. First, we will define a request to retrieve the status of an order. Second, we will define a request to retrieve the details of an order.
</p>
<p>
When only the status of the order is requested, we are dealing with a relatively small amount of data per order &#8212; in this case, the order id and the status of the order. If this consisted of maybe 50 bytes of data per order, we could easily store the status of 100,000 orders in only 5 megabytes of RAM. Since users might check the status of an order often, at least once an hour, this could generate thousands of requests an hour. Since the status of an order may only change once or twice a day, the need to query the database each time the order status is checked can put an unnecessary strain on the database server. In addition, the order status request service is now tightly coupled to the database, making the availability of the service dependent upon the availability of the database. This dependency chain can get even longer as more complex systems are designed, so limiting the dependencies of a service is a key parameter in increasing availability.
</p>
<p>
To reduce database load, eliminate the dependency on the database, and increase the availability of our order status web service, we can design our service to subscribe to order status updates. When the status of an order is updated, the update will publish a message containing the new status. As the status of orders are updated, our service would update an in-memory cache containing the status of every order in the system (well, every is not necessarily every &#8212; it could just be the orders placed over the last week that have not yet been received by the customer). On startup, the web service would query the database for the status of all orders placed and use the results of that query to seed the cache. Once the cache is seeded, as new orders are added and order status updates occur, the cache would update dynamically in response to the update messages. Since the cache is local to the web service, requests need only check the status by querying the cache and immediately returning the status of the order to the caller. In the case of an status request for an order that does not exist in the cache, the service could queue a request to get the order status from the database which would then publish that orders status so that it could be returned. If the order is not found, the service could return an unknown order response to the caller with instructions to perhaps try their request again later.
</p>
<h3>Up Next</h3>
<p>
The two exchanges described above are relatively easy to implement using messaging (and likewise, using MassTransit). The next exchange pattern I&#8217;m going to cover is the more complex request where the dependent service must be called to complete the request. Due to that complexity, I&#8217;m going to wait until the next installment to describe that in greater detail. After that, I&#8217;ll start to share some code as we build a solution to these exchanges.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/RT9zEMoloIY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/10/28/building-a-service-gateway-using-masstransit-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performance Counters Added to MassTransit</title>
		<link>http://blog.phatboyg.com/2009/10/14/performance-counters-added-to-masstransit/</link>
		<comments>http://blog.phatboyg.com/2009/10/14/performance-counters-added-to-masstransit/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 14:55:32 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MassTransit]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=835</guid>
		<description><![CDATA[One feature that is often overlooked in software development is the output of information that can be observed by operations once the application is in production. Fortunately, many open source projects are leveraging log4net to provide a configurable level of runtime information that can be useful in figuring out why a system is behaving a [...]]]></description>
			<content:encoded><![CDATA[<p>One feature that is often overlooked in software development is the output of information that can be observed by operations once the application is in production. Fortunately, many open source projects are leveraging <a href="http://logging.apache.org/log4net/index.html">log4net</a> to provide a configurable level of runtime information that can be useful in figuring out why a system is behaving a certain way (and face, if you&#8217;re looking, it&#8217;s more than likely behaving badly). Logging, however, is only one view into an application &#8212; one that might not deliver the appropriate information in a useful way.</p>
<p>Anyone who has used a computer with any interest is familiar with system monitoring tools. Task Manager (or if you&#8217;re really cool Process Explorer) is the first place Windows users look when their system starts to crawl, Mac users turn to Activity Monitor, and I&#8217;m sure Linux users have some really obscure command-line tool as well. These coarse grained tools are usually enough for users, however, an operations team needs a higher degree of visibility into application &#8212; particularly if they are expected to determine how to tune the application for better performance.</p>
<p>For operations on Windows, Performance Monitor provides detailed information for running applications in real-time. On a web server, it is easy to find out how many threads your ASP.NET application is using, as well as how many requests are queued. That information can be correlated with processor utilization to help determine if the bottleneck is the CPU, the network, or possibly even the database server. When it comes to troubleshooting issues on a live system, more information is always helpful to determine the source of the problem.</p>
<p>To support this level of visibility in <a href="http://code.google.com/p/masstransit/">MassTransit</a>, performance counter support has been added. Performance counters in .NET are part of the System.Diagnostics namespace. There are various counter types that can be defined, including counts, rates, and averages. When an application wants to output performance counters, it has to create a category and specify the counters that are included in the category. For instance:</p>
<pre class="brush: csharp;">
ConsumerThreadCount = new RuntimePerformanceCounter(&quot;Consumer Threads&quot;,
	&quot;The current number of threads processing messages.&quot;,
	PerformanceCounterType.NumberOfItems32);

ReceiveRate = new RuntimePerformanceCounter(&quot;Received/s&quot;,
	&quot;The number of messages received per second&quot;,
	PerformanceCounterType.RateOfCountsPerSecond32);
</pre>
<p>These are two of the counters defined by the MassTransit category. The first is a count that is updated when the number of threads in use changes. The second is a rate which gets incremented once for every message received. The actual calculation and display of the rate is handled by the performance monitoring tools &#8211; the application does not need to calculate it.</p>
<pre class="brush: csharp;">
ConsumerDuration = new RuntimePerformanceCounter(&quot;Average Consumer Duration&quot;,
	&quot;The average time a consumer spends processing a message.&quot;,
	PerformanceCounterType.AverageCount64);

ConsumerDurationBase = new RuntimePerformanceCounter(&quot;Average Consumer Duration Base&quot;,
	&quot;The average time a consumer spends processing a message.&quot;,
	PerformanceCounterType.AverageBase);
</pre>
<p>This counter is used to report the average consumer duration of a message. For an average, two counters are used. One is the base which is incremented for each occurrence and the counter is the actual count that is added. So for each message, the base is incremented once and the duration is incremented by the amount of time spent executing the consumer.</p>
<p>In adding performance counter support, I wanted to do it in a way that didn&#8217;t leak the details of updating performance information throughout the framework. It was at this point that I turned to the <a href="http://blog.phatboyg.com/2009/07/27/event-aggregator-using-the-magnum-pipeline/">Magnum Pipeline</a>. Using the pipeline to publish the metrics allowed me to isolate the actual performance counter interface to a single method in a single class for the service bus. So instead of passing interfaces around all the components that make up the bus, a single event aggregator is passed instead. When you start up the bus, the performance counter code subscribes to the events as shown:</p>
<pre class="brush: csharp;">
_eventAggregatorScope.Subscribe&lt;MessageReceived&gt;(message =&gt;
	{
		_counters.ReceiveCount.Increment();
		_counters.ReceiveRate.Increment();
		_counters.ReceiveDuration.IncrementBy((long) message.ReceiveDuration.TotalMilliseconds);
		_counters.ReceiveDurationBase.Increment();
		_counters.ConsumerDuration.IncrementBy((long) message.ConsumeDuration.TotalMilliseconds);
		_counters.ConsumerDurationBase.Increment();
	});
</pre>
<p>Now, when the bus receives a message, it sends the event to the event aggregator (an instance of the Magnum Pipeline).</p>
<pre class="brush: csharp;">
var message = new MessageReceived
	{
		MessageType = messageType,
		ReceiveDuration = receiveTime,
		ConsumeDuration = consumeTime,
	};

	_eventAggregator.Send(message);
</pre>
<p>Since the Magnum Pipeline is publish/subscription, additional consumers could also opt-in to the MessageReceived event and perform other actions as well. I also plan to add counters per message type, allowing a finer grained view at message counts and consumer durations.</p>
<p>While the main story behind this post is the new counters available in MassTransit, my hope is that this brief introduction to performance counters was useful as well. You can learn more about performance counters from various articles that have been posted (such as <a href="http://www.codeproject.com/KB/aspnet/DOTNETBestPractices3.aspx">a good one </a>on CodeProject). You can check out the <a href="http://blog.phatboyg.com/2009/07/27/event-aggregator-using-the-magnum-pipeline/">Magnum Pipeline</a> in the <a href="http://magnum-project.net/">Magnum</a> project which is <a href="http://code.google.com/p/magnum/">hosted at GoogleCode</a>.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/7Dg0lsq3v0E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/10/14/performance-counters-added-to-masstransit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some of the Best Free Mac Software</title>
		<link>http://blog.phatboyg.com/2009/09/19/some-of-the-best-free-mac-software/</link>
		<comments>http://blog.phatboyg.com/2009/09/19/some-of-the-best-free-mac-software/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 18:00:46 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Mac]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=833</guid>
		<description><![CDATA[So you bought a Mac, and you are staring at a fairly lonely dock wondering what other goodies you can add. Sure, the Mac comes with a lot of great software, including Snow Leopard, iTunes, iPhoto, iMovie, GarageBand, iWeb, iChat, and more but there has to be some other great stuff too right?
Here is my [...]]]></description>
			<content:encoded><![CDATA[<p>So you bought a Mac, and you are staring at a fairly lonely dock wondering what other goodies you can add. Sure, the Mac comes with a lot of great software, including Snow Leopard, iTunes, iPhoto, iMovie, GarageBand, iWeb, iChat, and more but there has to be some other great stuff too right?</p>
<p>Here is my list of (mostly free) software to add to your Mac to take it up a notch:</p>
<ul>
<li><a href="http://www.skype.com/download/skype/macosx/">Skype</a><br />The best way to make phone calls on your Mac</li>
<li><a href="http://docs.blacktree.com/quicksilver/what_is_quicksilver">Quicksilver</a><br />Free fast application launcher and more</li>
<li><a href="http://handbrake.fr/downloads.php">HandBrake</a><br />Don&#8217;t let those old DVDs go to waste, use HandBrake to rip them to your iTunes library (and play them on your TV or iPhone)</li>
<li><a href="http://www.atebits.com/tweetie-mac/">Tweetie</a><br />If Tweetie for the iPhone is good, Tweetie for the Mac is an even better Twitter client</li>
<li><a href="http://www.evernote.com/">Evernote</a><br />Keep track of everything and sync it automatically between Mac, Windows, iPhone, and web. Includes character recognition on images for searching text on pictures taken with your iPhone</li>
<li><a href="http://www.transmissionbt.com/download.php">Transmission</a><br />The best torrent client for the Mac</li>
<li><a href="http://cyberduck.ch/">Cyberduck</a><br />FTP, WebDAV, iDisk, whatever this client is fast, free, and easy to use</li>
<li><a href="http://colloquy.info/">Colloquy</a><br />IRC isn&#8217;t dead yet, and this free client works great on the Mac and iPhone</li>
<li><a href="http://adium.im/">Adium</a><br />The best IM client on the Mac, works with just about anything that chats</li>
</ul>
<p>And then there are the less often useful, but sometimes helpful ones:</p>
<ul>
<li><a href="http://trac.kismac-ng.org/">KisMAC</a><br />Because sometimes you really, really need a hot spot</li>
<li><a href="http://en.wikipedia.org/wiki/MacTheRipper">MacTheRipper</a><br />For those stubborn DVDs that won&#8217;t rip with HandBrake</li>
</ul>
<p>Those are all the free ones, I&#8217;ll post another list of all the paid items that I find myself using nearly every day soon.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/INYJJ-3W6Vs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/09/19/some-of-the-best-free-mac-software/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Interface Subscriptions Now Supported by MassTransit</title>
		<link>http://blog.phatboyg.com/2009/09/16/interface-subscriptions-now-supported-by-masstransit/</link>
		<comments>http://blog.phatboyg.com/2009/09/16/interface-subscriptions-now-supported-by-masstransit/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 01:42:21 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ActiveMQ]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSMQ]]></category>
		<category><![CDATA[MassTransit]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=826</guid>
		<description><![CDATA[Last year when we were reviewing the backlog of items that we wanted to build for MassTransit, one item that kept rising to the top of the list is a solid story for evolving message producers over the lifecycle of an enterprise system. Being able to publish events that current and down-level subscribers could consume [...]]]></description>
			<content:encoded><![CDATA[<p>Last year when we were reviewing the backlog of items that we wanted to build for MassTransit, one item that kept rising to the top of the list is a solid story for evolving message producers over the lifecycle of an enterprise system. Being able to publish events that current and down-level subscribers could consume was a key goal to avoid having to upgrade systems all at once when a publisher is updated. Fortunately, it hasn&#8217;t been a real concern in our application since we deploy the entire system as a whole with each delivery.</p>
<p>Nonetheless, a way to update a service that publishes messages without requiring every subscribing service to be updated at the same time was need.</p>
<h3>Eliminating Impediments</h3>
<p>Before we could implement interface subscriptions, there were a few things in the way that needed to be addressed, things that were not easy to implement.</p>
<p>First, we were still doing binary message serialization. While we had the ability to use the .NET XML Serializer, it tends to be slow and difficult to fit into the model we had built with MT. Back in May, <a href="http://blog.phatboyg.com/2009/05/27/masstransit-now-speaks-xml-by-default-2/">XML became the default serialization format</a> using an entirely new serializer built from scratch.</p>
<p>Second, we wanted to ensure that a publisher could publish a single message and have it delivered to all of the interested subscribers regardless of whether they had subscribed to the message class or one of the interfaces implemented by the class. In MassTransit, subscriptions are added by type a defined using a plain old CLR object (POCO). <a href="http://blog.phatboyg.com/2009/03/30/masstransit-06-release-candidate/">In the 0.6 release</a>, we replaced the message dispatcher with a new type-based pipeline for both inbound and outbound messages. Starting with an object and working down the type structure of the message, messages are pushed through the pipeline to interested message sinks. In the case of the outbound pipeline, it makes it easy to push a class through that has interfaces, since the interfaces can be assigned from the message object. Another hurdle eliminated.</p>
<h3>Implementing Interfaces</h3>
<p>
Once the hurdles were eliminated, it was actually very easy to add interface subscriptions. Since most of the internal bits had been reworked leveraging the power of expressions and generics, it was simply a matter of tweaking a few parts of the serializer and we were ready to rock and roll. Ensuring that message objects retain their type through the various pathways inside the system was also important, and resulted in fixing a couple of low hanging bugs related to message retry and fault publishing.
</p>
<p>
The one bit of code that needed to be built was a way to provide a backing class for an interface to store the property values. At first, I looked at using something like LinFu or DynamicProxy2 to create a proxy for the interface and intercept the property accessors, but this had a problem. I did not want property setters on the interface. At that point, I started looking at using the Emit classes, AutoMapper, the FastProperty expression-based accessors, and how Udi had dealt with it inside NServiceBus. What I ended up with was a very fast, cached object builder implementation that is integrated within the message deserializer. In the words of Cartman, &#8220;It&#8217;s pretty cool.&#8221;
</p>
<p>
There isn&#8217;t really a difference in the code between using classes and interfaces from either the producing or consuming end. While a producer will likely continue to publish a class, it just has to implement the message interface on that class, allowing the consumer to subscribe to the interface, breaking the dependency on the actual class published by the producer. The pipeline will then properly serialize out a message for that interface and send it directly to the consumer.
</p>
<p>
I&#8217;m pretty excited about this, and hope to update some of the pre-built services to use interfaces instead of classes in the near future. In the meantime, pull down the latest trunk and check it out.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/ggoIZHpz8Xo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/09/16/interface-subscriptions-now-supported-by-masstransit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Under the Covers with MassTransit Endpoints</title>
		<link>http://blog.phatboyg.com/2009/09/12/under-the-covers-with-masstransit-endpoints/</link>
		<comments>http://blog.phatboyg.com/2009/09/12/under-the-covers-with-masstransit-endpoints/#comments</comments>
		<pubDate>Sat, 12 Sep 2009 17:20:38 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSMQ]]></category>
		<category><![CDATA[MassTransit]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=810</guid>
		<description><![CDATA[
This post details some of the internal changes to how MassTransit, an open-source lightweight service bus, communicates with transports such as MSMQ, ActiveMQ, and TIBCO. These changes are not likely to impact anyone using MassTransit, they are all well below the abstraction layer provided by the bus. At the same time, I felt it was [...]]]></description>
			<content:encoded><![CDATA[<p>
<em>This post details some of the internal changes to how <a href="http://code.google.com/p/masstransit/">MassTransit</a>, an open-source lightweight service bus, communicates with transports such as MSMQ, ActiveMQ, and TIBCO. These changes are not likely to impact anyone using MassTransit, they are all well below the abstraction layer provided by the bus. At the same time, I felt it was important to share the change, along with the reasons it was made, with those that are using MassTransit.</em>
</p>
<p>
When <a href="http://code.google.com/p/masstransit/">MassTransit</a> was first started, MSMQ was the only transport we intended to support. In due time, however, it was determined that support for transports such as ActiveMQ and TIBCO was important. The ability to run on Linux and OS X under Mono (which does not support the System.Messaging namespace) as well as interoperability with Java systems using JMS (a specification for messaging, implemented by messaging systems like ActiveMQ and TIBCO) were the primary drivers of this decision. At the same time, insulating developers from the particulars of each transport was equally important.
</p>
<p>
To communicate with an endpoint, MassTransit uses the <em>IEndpoint</em> interface. The service bus would receive messages from an endpoint using this method:
</p>
<pre class="brush: csharp;">
IEnumerable&lt; IMessageSelector &gt; SelectiveReceive(TimeSpan timeout);
</pre>
<p>
This involved making a call that returned an enumeration of message selectors, allowing the caller to step through the messages until an interesting message (in the case of the bus, a message with a subscribed consumer). The concerns of receiving a message were seemingly spread at random across three or four different classes (and yes, I wrote this crap). The reason for the complexity was solid though &#8211; I need the ability to selectively receive a message from a queue and skip over ones in which I have no interest.
</p>
<p>
The complexity of dealing with the yield return/break syntax of enumerators and managing scope is difficult. The programming semantics behind it are difficult to understand. I wanted something better. With all the time I&#8217;ve been spending since this was written dealing with nested closures, lambda functions, and continuations I realized there was a better way to reduce the complexity while at the same time improving extensibility.
</p>
<p>
The new signature for the receive method on an endpoint looks like this:
</p>
<pre class="brush: csharp;">
void Receive(Func&lt; object, Action&lt; object &gt; &gt; receiver, TimeSpan timeout);
</pre>
<p>
With this new interface, the caller need only pass a method that accepts an object and returns a method that also accepts an object. The first method provides the caller an opportunity to inspect the message object to determine if the message will be consumed by the bus. If the bus is not interested, it can simply return null. If it is interested, it returns a method (either anonymous or a regular class method) that will consume the message. The endpoint will then call the returned method with the message once it has been received successfully. If the endpoint determines that the message is no longer available (if it were picked up by another process reading from the same queue for example), the returned method is not called.
</p>
<p>
The calling method looks something like this:
</p>
<pre class="brush: csharp;">
_endpoint.Receive(m =&gt; message =&gt; { doSomethingWith(message); });
</pre>
<p>
This interface is far less complex to implement, and also made it easy to make a clean separation of what is an endpoint and what is a transport. Which leads me to&#8230;
</p>
<h3>Endpoint and Transport Split?</h3>
<p>Sadly that reads like a Hollywood headline, but it is true. <strong>Endpoints</strong> now deal only with address resolution of sending and receiving messages and translating between the transport format and a message object (including de/serialization). New <strong>transport</strong> classes are now responsible for the actual communication with the various queue implementations supported by MassTransit.
</p>
<p>
For example, previously there was one class, MsmqEndpoint, that contained all the aspects of talking to MSMQ regardless of the type of queue (local non-transactional, local transactional, remote). Now beneath the endpoint itself, there are three MSMQ transports, one for each of these scenarios. Each of these transports cleanly deals with the particulars only, for example, the non-transactional transport has no transactional concerns in it at all.
</p>
<h4>Introducing ITransport</h4>
<p>The new ITransport interface is narrow, dealing only with the simplest form of communication &#8212; streams. The send and receive methods from the endpoint are matched, but instead of dealing with objects, streams are used. Every transport should provide stream support at a minimum. The receive method of the transport looks like:</p>
<pre class="brush: csharp;">
void Receive(Func&lt; Stream, Action&lt; Stream &gt; &gt; receiver, TimeSpan timeout);
</pre>
<p>
While all transports implement streams, there is a benefit to communicating at a level above streams for certain types of endpoints. For example, when using MSMQ there are advantages to communicating directly with the Message object such as having access to the transport level message ID, the message label, and other interesting properties. To support this, the MsmqEndpoint only accepts an IMsmqTransport interface, which inherits from ITransport and adds:
</p>
<pre class="brush: csharp;">
void Receive(Func&lt; Message, Action&lt; Message &gt; &gt; receiver, TimeSpan timeout);
</pre>
<p>
Other transports may benefit from a custom interface as well, but it is only implemented for MSMQ at this point. ActiveMQ, Loopback, and Multicast UDP all use the base stream interface.
</p>
<h3>Looking Forward</h3>
<p>
This rewrite was not purely for entertainment value (well, it was fun). Latency when sending a message from a machine to a remote queue is orders of magnitude slower than writing to a local queue. And in addition, local queues have the advantage of being local &#8212; which is important considering the first fallacy of distributed computing &#8212; the network is reliable (NOT!). To compensate for this, a more reliable method of sending messages to a remote queue is needed. By ensuring that messages sent/published by an application are durable regardless of network failure, developers can use this fire-and-forget approach to messaging that is key to building event driven applications.
</p>
<p>
To handle this, MassTransit now uses a store and forward transport for remote MSMQ queues. The store and forward transport will automatically create a local queue to cache the outbound messages destined for the remote queue. When a message is sent to the remote queue, the transport writes it to the local queue and returns to the caller. An asynchronous method then delivers the message in the background. The same transports that are used by the endpoint are reused by the store and forward transport, maintaining that high level of code reuse.
</p>
<p>
<em>Note that on Windows Server 2003, I have observed that MSMQ will accept messages destined for a unreachable remote queue and attempt redelivery itself, but only for transactional queues (at least, that is what I have seen). </em>
</p>
<h3>Wrapping Up</h3>
<p>
While it is always hopeful that changes like this will go by unnoticed, there is always the chance that there are some unintended consequences (read: bugs). Hopefully any of these will be weeded out quickly. In the meantime, I hope to start work on some availability features to support load balancing of command services.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/13MU37Bt4tY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/09/12/under-the-covers-with-masstransit-endpoints/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Event Aggregator Using the Magnum Pipeline</title>
		<link>http://blog.phatboyg.com/2009/07/27/event-aggregator-using-the-magnum-pipeline/</link>
		<comments>http://blog.phatboyg.com/2009/07/27/event-aggregator-using-the-magnum-pipeline/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 04:55:16 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=798</guid>
		<description><![CDATA[In the past few weeks, both Udi Dahan and Jeremy D. Miller have posted on events. Udi posted about domain events, while Jeremy posted about his use of the event aggregator pattern in StoryTeller. In each case, events are represented as messages and each message is a class in C#. And in each post, a [...]]]></description>
			<content:encoded><![CDATA[<p>In the past few weeks, both <a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/">Udi Dahan</a> and <a href="http://codebetter.com/blogs/jeremy.miller/archive/2009/07/23/how-i-m-using-the-event-aggregator-pattern-in-storyteller.aspx">Jeremy D. Miller</a> have posted on events. Udi posted about domain events, while Jeremy posted about his use of the event aggregator pattern in StoryTeller. In each case, events are represented as messages and each message is a class in C#. And in each post, a small publish/subscribe system is described that allowed objects (be it a domain object, domain service, or a controller) to subscribe to messages. Other objects could then use that same system to publish events to the subscribed objects.</p>
<p>Now while you could use <a href="http://code.google.com/p/masstransit/">MassTransit</a> out of the box to handle this type of event aggregation, it is a bit heavy. The in-memory message transport serializes the message, which makes it impossible to pass a continuation or an object reference as part of an event. There is also a very service-oriented thread model where each consumer runs on a different thread making synchronization an important concern for unit testing. While it would work, it is not always the shiniest hammer in the toolbox for UI-based application.</p>
<p>To address this, one of the things I&#8217;ve been adding to <a href="http://code.google.com/p/magnum/">Magnum</a> over the past few weeks is a new version of the pipeline that handles message distribution in MassTransit. In this implementation, I wanted a way to implement the event aggregator pattern with the same flexibility that I get with MassTransit but designed for an in-process mode of execution. At the same time, I wanted to make sure that I could scale this solution via adapters to extend events to MassTransit for publishing out-of-process.</p>
<p><em>Note, I use the word event and message interchangeably in this post.</em></p>
<p>First, I wanted it to be able to handle any object without any constraints on the type. To this end, I came up with a very narrow API that only deals with the publishing of a message.</p>
<pre class="brush: csharp;">
public interface Pipe
{
	void Send&lt; T &gt;(T message) where T : class;
}
</pre>
<p>The <strong>Send</strong> method is fairly obvious, it is used to send a message to any consumers that are subscribed to the message. With this implementation, consumers that are subscribed to any type to which the message can be assigned will also get the message. Consider the following class structure:</p>
<pre class="brush: csharp;">
public class CustomerChanged
{
	public Customer Customer { get; set; }
}

public class CustomerRatingDowngraded :
	CustomerChanged
{
}
</pre>
<p>A consumer that subscribed to the <em>CustomerChanged</em> type would receive the message if a <em>CustomerRatingDowngraded</em> message was published. It also works for interfaces, as long as the message object being published supports the interface.</p>
<p>An obvious omission from this API is any method of subscribing consumers to the pipeline. To subscribe to the pipeline, an extension method on the <em>Pipe</em> interface creates a new subscription scope. A subscription scope, represented by the <em>ISubscriptionScope</em> interface, makes changes to the pipeline resulting in the creation of a new pipeline. A series of visitors are used to create a new version of the pipeline with the consumers added, along with another visitor to remove the consumers when they unsubscribe. ISubscriptionScope implements <em>IDisposable</em> so to unsubscribe your application can just dispose of the object.</p>
<p>It is interesting to note that much like the Expression class in .NET, pipelines are immutable. Since pipelines cannot be changed, the need to lock parts of the pipeline during message distribution is removed. By removing the need for locking to ensure safe operation in a concurrent environment, performance improves and blocking is eliminated. At the same time, consumers can subscribe and unsubscribe from the pipeline as needed without disrupting the system.</p>
<pre class="brush: csharp;">
public void Start()
{
	// this creates an empty pipeline that accepts any object
	_eventAggregator=PipeSegment.Input(PipeSegment.End());

	_scope=_eventAggregator.NewSubscriptionScope();
	_scope.Subscribe&lt; CustomerChanged &gt;(message=&gt;Trace.WriteLine(&quot;Customer changed: &quot;+message.CustomerName));
}
</pre>
<p>In this example, pipe and scope would likely be member variables that would be released when the containing object is stopped or disposed. Multiple subscriptions can be added to a single scope, each one modifying the pipeline as it is added.</p>
<p>When I discuss event-based programming, I often mention the need for visualization tools in order to ensure the system is performing as expected. In the example above, I could use the TracePipeVisitor to verify that the consumer was indeed subscribed to the pipeline (by calling new TracePipeVisitor() .Trace(_eventAggregator) and viewing the results in the output window).</p>
<p>
<pre>
Input< Object >:
RecipientList< Object >:
     Filter< CustomerChanged >: Allow Magnum.Specs.Pipeline.Messages.CustomerChanged
     RecipientList< CustomerChanged >:
          MessageConsumer< CustomerChanged >:
</pre>
</p>
<p>As consumers are added, the pipeline is built up using a series of PipeSegment classes. The Input segment is the initial entry point to the pipeline and by having the responsibility is the only segment that actually changes in the pipeline. The RecipientList is a one-to-many switch that delivers incoming messages to each consumer. The Filter segment only passes a specific type through the filter, preventing unwanted messages from receiving the consumer. The MessageConsumer actually invokes the method that was subscribed to the message.</p>
<p>In the above example, the message consumer was accepted using the MessageConsumer<t> delegate type, which is analogous to Action</t><t> with T being the message type. Another way to subscribe is to implement the IConsume</t><t> method as shown below.</t></p>
<pre class="brush: csharp;">
public class ListViewController :
	IConsume&lt; CustomerChanged &gt;
{
	public ListViewController(ListView customerListView)
	{
		_customerListView = customerListView;
	}
	public void Consume(CustomerChanged message)
	{
		_customerListView.DoSomeUpdate(message.Customer);
	}
}
</pre>
<p>A class can implement the IConsume<t> method to indicate that it is interested in messages of type T. In this case, the CustomerChanged message is of particular interest as it is used to update the user interface in response to a customer change event. The instance of the controller can be subscribed to the pipeline by calling the Subscribe method passing the object reference itself.</t></p>
<pre class="brush: csharp;">
public void BootstrapUserInterfaceControllers()
{
	_customerListViewController = new ListViewController(customerListView);

	_scope=_eventAggregator.NewSubscriptionScope();
	_scope.Subscribe(_customerListViewController);
}
</pre>
<p>This is the first in a series of posts about the pipeline in Magnum. As I add the remaining functionality, including asynchronous message consumers, aggregate consumers, and automatic binding to the Magnum StateMachine (similar to how sagas are done using MassTransit), I&#8217;ll post about how they are used. I encourage you to <a href="http://code.google.com/p/magnum/">take a look at the code</a> and particularly the unit tests to see the different ways the pipeline can be used.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/twhif9AvWTY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/07/27/event-aggregator-using-the-magnum-pipeline/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Accessing ActiveMQ on Mac OSX from a Windows VM</title>
		<link>http://blog.phatboyg.com/2009/07/12/accessing-activemq-on-mac-osx-from-a-windows-vm/</link>
		<comments>http://blog.phatboyg.com/2009/07/12/accessing-activemq-on-mac-osx-from-a-windows-vm/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 19:43:19 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ActiveMQ]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSMQ]]></category>
		<category><![CDATA[Mac]]></category>
		<category><![CDATA[MassTransit]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=792</guid>
		<description><![CDATA[With MassTransit, we support multiple messaging transports, including MSMQ (comes with Windows), ActiveMQ (an open-source Java message broker), and TIBCO EMS (a not-so-open-source message broker). With that in mind, teams building on the Windows platform can comfortably choose MSMQ and enjoy familiar management tools. If your needs expand to multiple platforms, however, the other choices [...]]]></description>
			<content:encoded><![CDATA[<p>With <a href="http://code.google.com/p/masstransit/">MassTransit</a>, we support multiple messaging transports, including MSMQ (comes with Windows), ActiveMQ (an open-source Java message broker), and <a href="http://www.tibco.com/software/messaging/enterprise-message-service/default.jsp">TIBCO EMS</a> (a not-so-open-source message broker). With that in mind, teams building on the Windows platform can comfortably choose MSMQ and enjoy familiar management tools. If your needs expand to multiple platforms, however, the other choices become more important. One of our goals is to enable MassTransit to communicate between services running on Windows, OS X, and Linux. By using the <a href="http://mono-project.com/Main_Page">Mono Project</a> to run .NET code on OS X and Linux, and ActiveMQ to handle the messaging, we&#8217;re pretty confident that we can reach that goal.</p>
<p>To start working towards this endeavor, I had to first get a working test environment. ActiveMQ can run on Windows, Linux, and OS X. Since <a href="http://codebetter.com/blogs/dru.sellers/">Dru Sellers</a> and I both develop on <a href="http://www.apple.com/macbookpro/">Macs</a> using <a href="http://vmware.com/products/fusion/">VMware Fusion</a> to host various versions of Windows, I wanted to install and run ActiveMQ on the Mac host, making it available to any of the virtual machines. I had not really dealt with setting up services on OS X yet, but was happy to learn that it is a pretty slick process to get things installed and running. Hopefully this will help if you decide to do the same.</p>
<p><em>I should note that I am not an ActiveMQ installation/administration expert. I am configuring ActiveMQ for use in a development environment. If you are going to use ActiveMQ in production, make sure it is configured for proper production operation with the appropriate security, storage, etc. That being said, let&#8217;s get started.</em></p>
<h3>Getting Started</h3>
<p>You need to <a href="http://activemq.apache.org/index.html">download ActiveMQ</a>. I got the Linux version by typing in the URL manually to get it to download using Safari. The archive will be unpacked into a tar file automatically by Safari (if not, just double-click it), which you can then open the tar file into a folder by double-clicking it again. If you are a command-line wizard, you already know how to handle the tar.gz files so enjoy.</p>
<p>Move the unpacked folder (apache-activemq-5.2.0 in my case) to the /usr/local folder by opening Terminal and entering:</p>
<p><tt>sudo mv apache-activemq-5.2.0 /usr/local/</tt></p>
<p>While still in terminal, change to the ActiveMQ folder. We need to modify the configuration.</p>
<p><tt>cd /usr/local/apache-activemq-5.2.0<br />
mate conf/activemq.xml</tt></p>
<p>If you aren&#8217;t using <a href="http://macromates.com/">TextMate</a>, well, do whatever you need to do to open that file. I removed a lot of unused things from the file, but your needs may vary. You can <a href="http://blog.phatboyg.com/wp-content/activemq.xml">download my configuration file</a> if you want to use what I am using. You will need to modify the IP addresses to match your environment. I originally tried to use just localhost, but had issues with it connecting from my Windows 7 VM. If this is just a fluke, I&#8217;ll update my file later with my new settings.</p>
<h3>Installing the launch daemon into OS X</h3>
<p>To run ActiveMQ as a service, you need to create a property list that describes the application. This is just an XML file, but we need to create it and put it into the <tt>/Library/LaunchDaemons</tt> folder and call it <tt>com.apache.activemq</tt> so we can identify it later. You can <a href="http://blog.phatboyg.com/wp-content/com.apache.activemq">download my version of the file</a> to save some typing if you prefer.</p>
<div style="text-align:center;">
<p><img src="http://blog.phatboyg.com/wp-content/uploads/2009/07/activemqterminalsetup.png" alt="ActiveMQTerminalSetup.png" border="0" width="640" height="229" /></p>
</div>
<p>Some of these settings can be adjusted if you don&#8217;t want to keep ActiveMQ running all the time. <tt>KeepAlive</tt> will automatically restart the service if it stops for some reason (including manually stopping it) and you can set that to <tt>false</tt> if you want to control it manually.</p>
<p>After creating the file, we need to configure OS X so it knows about the new service. To do this, type the following:</p>
<p><tt>sudo launchctl load /Library/LaunchDaemons/com.apache.activemq<br />
sudo launchctl start com.apache.activemq</tt></p>
<p>Once you have done this, you can verify that it is started by running the OS X Console application (find it in QuickSilver/Spotlight if you don&#8217;t know where it is). Look at the message logs and you can see the startup messages from the service:</p>
<p>
<div style="text-align:center;"><img src="http://blog.phatboyg.com/wp-content/uploads/2009/07/activemqconsolelog.png" alt="ActiveMQConsoleLog.png" border="0" width="640" height="451" /></div>
</p>
<p>So how do we know that we have a working installation? Well, there is an admin console that you can reach by navigating to <tt>http://localhost:8161/admin</tt> that will let you view the queues, topics, etc. that are running. You can also use the JMX tools to dig into the queues as well, including the ability to send messages to the queues directly from the Java console! To get the console started, you need to run <tt>jconsole</tt> from Terminal. Once it is started, you need to connect to the URL that is configured:</p>
<p>
<div style="text-align:center;"><img src="http://blog.phatboyg.com/wp-content/uploads/2009/07/jconsoleconnect.png" alt="JConsoleConnect.png" border="0" width="480" height="380" /></div>
</p>
<p>Once you are in the JConsole, you can view all the queues. It should look like this (well, assuming you&#8217;ve created some queues, which I&#8217;ve done here with the Starbucks sample from MassTransit).</p>
<p>
<div style="text-align:center;"><img src="http://blog.phatboyg.com/wp-content/uploads/2009/07/jconsoleview.png" alt="JConsoleView.png" border="0" width="640" height="542" /></div>
</p>
<p>You can see the default URL that was connected to in the title bar, along with the tree view of all the objects. The more interesting tab is the Operations tab, which lets you run commands against the queue. In fact, you can past some XML straight into an input box and click &#8220;sendTextMessage&#8221; and the message will be stuffed into the queue right there.</p>
<p>
<div style="text-align:center;"><img src="http://blog.phatboyg.com/wp-content/uploads/2009/07/jconsoleoperations.png" alt="JConsoleOperations.png" border="0" width="640" height="495" /></div>
</p>
<p>So now that we know ActiveMQ is running and happy, we can modify our application to use the ActiveMQ transport instead of the MSMQ transport by simply changing the URI for the endpoint. So instead of <tt>msmq://localhost/mt_subscriptions</tt> you would specify <tt>activemq://192.168.0.195:61616/mt_subscriptions</tt> (in my case, that is the IPv4 address of my host machine). As long as the transport is in the same folder and you&#8217;re using the <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a> base registry without specifying a specific transport, it should connect up to the host and start working. The other containers will hopefully get this support soon, it was just easy to add with the Scan() feature of StructureMap&#8217;s registry DSL.</p>
<p>I hope to dig deeper into the ActiveMQ transport support in MassTransit, as well as start testing it while running under Mono on OS X over the next few weeks. I already have the Windows bits working, I just want to test more exception cases such as losing the connection to ActiveMQ, as well as other runtime issues to make the code more production ready. I also want to try sending messages to/from other languages, such as <a href="http://www.ruby-lang.org/en/">Ruby</a> via <a href="http://stomp.codehaus.org/">STOMP</a>, but my Ruby skills are not the greatest.</p>
<p>At the very least, I hope this article helps you get ActiveMQ installed and running on your Mac using OS X Leopard. If you do run into issues or have problems, be sure to visit the <a href="http://groups.google.com/group/masstransit-discuss">MassTransit mailing list</a> and post your questions/issues there.</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/lmAlkZEliSU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/07/12/accessing-activemq-on-mac-osx-from-a-windows-vm/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>I’m a Microsoft C# MVP!</title>
		<link>http://blog.phatboyg.com/2009/07/01/im-a-microsoft-c-mvp/</link>
		<comments>http://blog.phatboyg.com/2009/07/01/im-a-microsoft-c-mvp/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 00:14:00 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://blog.phatboyg.com/?p=784</guid>
		<description><![CDATA[Opening my Inbox this morning resulted in a pleasant surprise from Microsoft. I have been presented with the 2009 Microsoft&#174; MVP Award as a recognition for sharing my expertise in Visual C# with others. It is an honor to be recognized by Microsoft for doing something that I truly enjoy &#8211; building really cool software.


Microsoft [...]]]></description>
			<content:encoded><![CDATA[<p>Opening my Inbox this morning resulted in a pleasant surprise from Microsoft. I have been presented with the 2009 Microsoft&reg; MVP Award as a recognition for sharing my expertise in Visual C# with others. It is an honor to be recognized by Microsoft for doing something that I truly enjoy &#8211; building really cool software.</p>
<div style="text-align:center;"><img src="http://blog.phatboyg.com/wp-content/uploads/2009/07/mvpbanner.png" alt="MVPbanner.png" border="0" width="584" height="108" /></div>
<p style="text-align:center;">
<blockquote><em>Microsoft Most Valuable Professionals (MVPs) are exceptional technical community leaders from around the world who are awarded for voluntarily sharing their high quality, real world expertise in offline and online technical communities. Microsoft MVPs are a highly select group of experts that represents the technical community&#8217;s best and brightest, and they share a deep commitment to community and a willingness to help others.</em></p></blockquote>
<p>A community-based award like this would not be possible without the support of my peers, and I look forward to meeting up with some of those very peers at the next MVP Summit! In the meantime, congratulations to all the new and renewed MVPs!</p>
<img src="http://feeds.feedburner.com/~r/PhatBoyG/~4/FAIJnBpr_kg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.phatboyg.com/2009/07/01/im-a-microsoft-c-mvp/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
