.Net, Rhino Mocks

Simplifying the Rhino Mocks Code Base

It has been an interesting last couple of days.

I finished converting all of the existing unit tests from using Record/Replay syntax to the Arrange/Act/Assert (AAA) syntax. Oddly enough this lead to a few extra unit tests that were not previously being executed. These newly discovered unit tests could have been removed due to relevance or performance but for whatever reason, they have been added back. I did find that there were a few (eleven in fact) that were no longer relevant and needed to be “skipped.” They are all passing now so… mission accomplished.

With this done I started turning toward the main code base. And… here we go.

Intercepting the Interceptors

Things started out simple enough; moved similar concerns into a different namespace, removed “generated” files minor code corrections. I then moved onto simple refactoring like reducing nesting and leveraging TryGetValue on a Dictionary. Everything was going well. I then started to tackle the interceptors and invocation actions.

If you didn’t already know, Rhino Mocks (as with many other frameworks) utilizes Castle Windsor to create proxies and intercept method calls (via DynamicProxy). This gives us the ability to create proxies for interfaces, delegates and classes that can then have calls intercepted. Some of the methods, however, are from the base System.Object class which everything in the .Net framework inherits. As it turns out, you can actually configure Castle Windsor to ignore these methods. If any method is ignored, however, they are never called which leads to some interesting issues with this like equality and comparison.

Rhino Mocks current solution for this is to intercept these calls and check to see if the method belongs to System.Object. If the method does belong to System.Object then the method is allowed to proceed. This type of “checking” continues for things like properties and events.

I was a little taken back when I came across this. Not because it was being done but how it was being accomplished. As I started to refactor this code I came to the realization that Castle Windsor supports something very similar through something called the IInterceptorSelector interface. When this interface is implemented it allows you to choose which interceptor should handle the method. By adding an implementation of this interface and a few more interceptors, all of the existing code and constructs can be removed.

One Step Forward, Two Steps Back

It would have been great to stop right there. As you might have guessed; that didn’t happen.

After this minor success I turned my focus on the MethodOptions that are returned when you create an expectation. I decided that since the system knew when a Void method was being called there should be no reason to return MethodOptions with a Return method available. Along the same lines, Return method (when it is available) should be allowed to take a Func to return the value.

Diving into this lead me to understand Record/Replay is much more than just a syntax but is the only way Rhino Mocks currently works. When using the AAA syntax, behind the scenes, Rhino Mocks transition the “state” from Replay to Record and back to Replay. Kind of sounds like a lot of steps doesn’t it? Just a tad.

Rather than perpetuating the current approach, a simpler strategy is underway. This strategy does away with the various “states” and puts the onus on the code creating the expectation. The AAA syntax conforms to this nicely since there is really only one way create a expectation. Based on my estimates, this strategy should reduce the code base by around 30 classes. Clearly there will be additional classes added but will be geared towards usability rather than internal plumbing.

I am planning on having a working code set with a majority of the changes completed within the next few weeks. Some of these modifications can be done in the existing code base in which case I’ll cut a minor release. Should be exciting!

Advertisements
Standard
.Net, Rhino Mocks

Unwinding Rhino Mocks

Finally, progress!. Sure, the “progress” is 124 build errors but… it’s progress; right?

One of the things that I have been doing is cleaning up the code base by removing projects, assemblies and code that are no longer relevant. I am actually surprised of how much code was never built. It has also been interesting finding artifacts from previous build strategies and repositories. Things like NAnt scripts and merge diff files (from SVN). Even found an old version of NUnit hiding out.

To be honest, this is some of the most fun that I have had in a while. There is nothing better than deleting things!
(Perhaps I need to get out more)

Attempting to update to the latest version of Castle Dynamic Proxy (now in Castle.Core assembly), however, has caused a little problem. About 124 problems to be exact. Armed with my trusty editor (Vim), these issues have been quickly dispatched.

With the build errors fixed there are now nine tests failing (out of 806). Progress indeed. Hopefully these will be corrected tomorrow so I can commit the changes and start digging into some “real” changes.

Standard
.Net, Rhino Mocks

State of Rhino Mocks

Ayende Rahien (Oren Eini) recently posted about the state of Rhino Mocks. For those of you who don’t know, Rhino Mocks is a dynamic mock object framework for the .Net platform that Ayende created and developed which allows developers to “mock away concerns” in unit tests. I remember stumbling across Rhino Mocks around 2006 and ever since that time I have been hooked. I have tried other mocking frameworks but each time I have always returned to Rhino Mocks.

So it was shocking to read in his recent post that from his perspective, Rhino Mocks is done since he no longer has an interest in extending it and doesn’t really use mocking any longer. After reading that a few times (to make sure I was reading it correctly) he made a statement offering to have someone in the community step in and take it over.

What shocked me even further, however, were the comments of which nobody was offering to step in. How is this possible? Is the community really willing to let this code set simply fade away into history? Is unit testing and mocking so prevalent in the .Net community that we can scoff at the notion?

Losing Rhino Mocks, to me, has more to do with potentially losing the concepts and practices it promotes than simply the code and binaries. Having a framework that also promotes good practices is invaluable.

As a result… I did what I believe needed to be done.

Standard
.Net, Windows Live Writer

WLW Plugin for WordPress.com – New Version

Almost immediately after I published the WLW WordPress.com Syntax Highlighter to CodePlex a little voice inside my head was telling me that I can do better than that. Luckily for me, that voice was right.

You can find it here: WLW WordPress.com Syntax Highlighter Plugin

The problem with the initial version of the plugin was the fact that I could not get around the "auto-encoding" feature from WLW. This basically meant that any time you wanted to have quotes or angle brackets in your code it would get encoded. Worse still was you had to go to the "Source" tab, correct the encoded characters and then remember to not go back to the "Edit" tab. Sounds like a great plugin to me…

To resolve this issue I switched from using the ContentSource base class to using the SmartContentSource base class. This base class provides you with the ability to have two sets of content: the "Editor" version and the "Publish" version. The "Editor" version is obviously what you see within WLW while the "Publish" version is what is sent to your blog.

Two methods… how simple is that?

Well… when you start off using the ContentSource and WPF… not so simple. The SmartContentSource has what is called an "Editor" which appears in the right pane of WLW when the content is selected. This "Editor" must inherit from SmartContentEditor which in turn inherits from Windows.Forms.UserControl.

Rather than attempting to fight that battle I found it was simpler to just pull out the WPF stuff and go directly with a Forms version.

Funny how the original intent was to show how to create a plugin for WLW using WPF only to rip it out. Live and learn… I guess.

Standard
.Net, Windows Live Writer

WLW Plugin for WordPress.com on CodePlex

There have been some requests to have me publish the WordPress.com sourcecode highlighter plug-in that I created for Windows Live Writer. So I went ahead and created a CodePlex project for it and published the code and the assembly.

You can find it here: WLW WordPress.com Syntax Highlighter Plugin

There is no official release but you can go to the "Downloads" tab and select the alpha release.

Publishing this out on CodePlex was actually fun and nerve racking at the same time. Since this was the first project that I ever published out there I wanted to make sure that everything was in "tip top shape." I can’t tell you how much time I spent just getting the "summary" correct. I must have rewritten it about five or six times. I am sure I made some faux pas but how is a guy suppose to learn?

Then I realized… it is what it is. Either people are going to find it useful or people are going to think its junk. Either way… it is the spirit of it all that I am finding more interesting. I had a need, wrote a little plug-in to satisfy that need, and am now sharing it to those who are interested.

What I think is going to be even more fun is revisiting this code later and seeing what improvements can be made and how to make it better.

So enjoy and let me know your comments and suggestions.

Standard
.Net

NServiceBus – Fifteen Minutes…

After downloading the assemblies I was ready to create my first sample application using NServiceBus. From what I can tell, a lot of time and effort has gone into building the NServiceBus.Host executable so if you plan on using it… you’re in luck, there are plenty of examples out there on how to use it. If you don’t want to use it, however, get ready for some digging (take a guess on which direction I went in). Hopefully this post will serve as a good example of how to handle things when you don’t want to use NServiceBus.Host. Time will tell…

The most basic example is sending a message. Note that this is not publishing a message but simply sending a message. To send a message you will need something that sends the message and something that will receive the message. Go ahead and create two console projects: 1) “Sender” and 2) “Receiver”.

You will need to be able to define a message that both the sender and receiver will be able to understand so go ahead and create library project (name it “Messages” for now to keep things simple).

Again, doing the most simple thing possible, add a reference to “NServiceBus.dll” to the “Messages” project. Create a new class, add the “Serializable”  attribute, and have the class implement the “IMessage” interface. This interface is nothing more than a indication to NServiceBus that it can be used as a message. And since we are going to be passing this class around as a message we need to be able to serialize it across the wire so… don’t forget the “Serializable” attribute.

[Serializable]
public class ExampleMessage : IMessage
{
  public int Id { get; set; }
  public string Message { get; set; }
}

A “message” can be thought of as a Data Transfer Object (DTO) in that the message should only contain data and really shouldn’t contain any methods or logic. There can be some interaction with the data like formatting or structuring but avoid putting any logic. Remember that this is going to be serialized.

From here add the “Messages” project as a reference to the “Sender” and “Receiver” console applications. While we are at it, go ahead and add a reference to “NServiceBus.dll” and “NServiceBus.Core.dll”.

Up to now we have three projects: Messages (contains our message class), Sender (the application that will send the message) and, Receiver (the application that will receive the message). So far so good.

The Sender

So now we want the “Sender” application to send a message out into the world. Prior to being able to send a message we first have to instantiate a service bus (for NServiceBus this is an IBus). NServiceBus has a “fluent interface” class named “Configure” that uses an Inversion of Control (IoC) container to build up, configure, and create an instance of a service bus. By default this is done through Spring.Net which is all nice and good but I prefer to use StructureMap so… that is what I choose to use here. The only difference in this example is the “StructureMapBuilder” call which tells NServiceBus to use StructureMap as the IoC container. If you leave this line out… you will use Spring.Net.

var bus = Configure.With()
  .StructureMapBuilder()
  .XmlSerializer()
  .MsmqTransport()
    .IsTransactional(false)
    .PurgeOnStartup(false)
  .UnicastBus()
    .ImpersonateSender(false)
  .CreateBus()
  .Start();

Now we have a service bus that we can send messages with. In order to send a message all we need to do is new up an instance of our class from the “Messages” project and call the Send method from our service bus instance. For this simple example we do this in a while loop where each time we hit “Enter” we send a message:

while (Console.ReadLine() != null)
{
  var message = new ExampleMessage(1, "My First Example");
  bus.Send(message);
}

Finally it is time to configure our “Sender” application. Here we need to add an Application Configuration File (App.config). Since we are sending a message we need to configure our MSMQ Transport and our Unicast Bus.

NOTE: Unlike other configuration sections you cannot “name” the section something different. The following section “names” must be as they appear or they do not work. Not 100% why this is but… if you don’t then it will not work

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
  </configSections>
  <MsmqTransportConfig InputQueue="MySenderQueue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />
  <UnicastBusConfig DistributorControlAddress="" DistributorDataAddress="" ForwardReceivedMessagesTo="">
    <MessageEndpointMappings>
      <add Messages="MessageTypes" Endpoint="MyReceiverQueue" />
    </MessageEndpointMappings>
  </UnicastBusConfig>

Right now the important pieces to cover in the configuration are: InputQueue, Endpoint, and Messages.

InputQueue defines where this service bus can receive messages. Since the “Sender” is never going to receive a message in this example we can safely put anything we want here. For consistency I put “MySenderQueue”.

Endpoint defines where this service bus will send messages. This is a really important setting. We will be using this value later when we configure the “Receiver”.

Messages defines what type of messages this service bus will send to the Endpoint. Here we can break this up to be type specific but for this example we will simply instruct the service bus to send all of the messages from our “Messages” project to the Endpoint.

The Receiver

Now we want the “Receiver” to receive messages from the world. Prior to being able to receive messages we first have to instantiate another service bus similar to the way we did in our “Sender” project. The only real big difference in configuring this service bus is telling NServiceBus to load in our message handlers.

var bus = Configure.With()
  .StructureMapBuilder()
  .XmlSerializer()
  .MsmqTransport()
    .IsTransactional(false)
    .PurgeOnStartup(false)
  .UnicastBus()
    .ImpersonateSender(false)
    .LoadMessageHandlers()
  .CreateBus()
  .Start();

Since we don’t want our “Receiver” application closing as soon as we bring it up we need to add a little bit of code to make sure it sticks around while we test:

Console.ReadLine();

If you notice the only difference between the “Sender” and the “Receiver” is the LoadMessageHandlers call. So in order for NServiceBus to load our message handlers… we need to have a message handler. To do this simply add a new class and implement the “IHandleMessages<>” interface:

public class ExampleMessageHandler : IHandleMessages<examplemessage>
{
  public void Handle(ExampleMessage message)
  {
    Console.WriteLine("I got an example message... now what?");
  }
}

Finally it is time to configure our “Receiver” application. Here we need to add an Application Configuration File (App.config). Since we are only receiving messages we only need to configure our MSMQ Transport (no need to configure the Unicast Bus).

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
  </configSections>
  <MsmqTransportConfig InputQueue="MyReceiverQueue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />

In order to receive messages properly we need to make sure that the InputQueue value is the same as the Endpoint value from the “Sender” configuration. For this example it is “MyReceiverQueue”.

Done

Now you are ready to go and start sending messages from the “Sender” to the “Receiver”.

To do so simply right click the “Sender” project and click “Start new instance” from the “Debug” submenu. After this console app is up and running right click the “Receiver” project and click “Start new instance” from the “Debug” submenu. With both console applications up and running hit “Enter” from the “Sender” window and watch the message appear in the “Receiver” window.

Summary

All and all I would say that this took about fifteen to twenty minutes to get setup and running. That is pretty impressive especially when you start digging into what is actually happening in the background.

In future posts we can go over Publish and Subscribe, Request and Reply, and talk about the Distributor (which is some really neat stuff).

Standard
.Net, Windows Live Writer

WLW Plugin for WordPress.com – Part 1

As stated in my previous post, I have been looking for a plug-in for WLW that would allow me to take advantage of the built in source code highlighter that is available from WordPress.com (the free on-line version). Not being able to find one I decided to write one for myself.

Not knowing where to begin or how to start, I searched for how to build a plug-in for WLW and came across Rick Strahl’s post about creating a WLW plug-in using WPF and decided to do a similar thing. I was fairly confident in my abilities to write a little WPF app but knew nothing about the WLW plug-in architecture so I started there.

For what I needed to do, writing a plug-in was actually really straight forward. I simply added a reference to the “WindowsLive.Writer.Api” assembly, created a class and inherited from the ContentSource class (which inherits from the WriterPlugin class). Looking at the ContentSource class I found that there were three virtual methods that I could choose from: 1) CreateContent, 2) CreateContentFromLiveClipboard, and 3) CreateContentFromUrl. Not knowing what any of these methods did, I choose to override the CreateContent method.

using System;
using WindowsLive.Writer.Api;
using System.Windows.Forms;

namespace SourceCodePlugin {
  public class Plugin : ContentSource {
    public override DialogResult CreateContent(IWin32Window dialogOwner, ref string content) {
      return DialogResult.OK;
    }
  }
}

Now knowing that I could create a WLW plug-in I thought about what I wanted the plug-in to do and how it was going to act. In really basic terms, I wanted to wrap what ever “code” I wrote with “[ sourcecode language=”csharp” ]<–code–>[ /sourcecode ]” as the WordPress.com site had suggested.

Thinking about it a little more, I wanted to ensure that the “code” appeared exactly the way I entered it so… it was clear that I needed to wrap the whole thing with “<pre></pre>” tags. So I wrote a little method to do just that.

public class Plugin : ContentSource {
  ...
  private string FormatOutput(string language, string code) {
    var builder = new StringBuilder();
    builder.AppendLine("&lt;pre&gt;");
    builder.AppendFormat("[ sourcecode language=\"{0}\" ]{1}[ /sourcecode ]",
      language, code);
    builder.AppendLine();
    builder.AppendLine("&lt;/pre&gt;");
    return builder.ToString();
  }
}

I decided to give that a shot so I built the project, deployed the assembly to my “Plugins” folder and started Windows Live Writer.

Sure enough… it didn’t work. I totally forgot about the two attributes that you need to add to your class in order for WLW to load your plug-in. Referencing back to Rick’s post I also realized that I should create an image to make it look like all of the others.

[WriterPlugin(
  "9EDA38F6-AE13-4003-B74A-83E8474F528D", 
  "Wordpress Sourcecode Plugin",
  Description = "A  plugin for WordPress.com blogs",
  PublisherUrl = "https://meisinger2.wordpress.com/",
  ImagePath = "Images.SourceCode.png",
  HasEditableOptions = false)]
[InsertableContentSource("Wordpress Sourcecode Plugin")]
public class Plugin : ContentSource {
  ...
}

After adding that and building it again, sure enough I had my “Hello World” code getting inserted into WLW through my plug-in

Next steps… integrating WPF

Edit: It appears that WordPress.com “sourcecode” bracket magic is a little too good… I had to edit this post and put a space between the bracket (“[” and “]”) and the word “sourcecode” in order for it to come up propertly

Standard