• louis vuitton outlet
  • nike air max
  • ray ban uk
  • oakley sunglasses outlet
  • cheap jordan shoes
  • toms outlet
  • Cheap Oakleys Sunglasses
  • fifa coins
  • ray ban
  • cheap uggs
  • ray ban uk
  • nike air max
  • ray ban outlet
  • burberry uk
  • fut coins
  • fut 14 coins
  • fut coins
  • Christian Louboutin Outlet
  • michael kors outlet
  • coach outlet
  • louis vuitton outlet
  • fifa coins
  • ray ban
  • Custom iphone cases
  • nike
  • monster beats
  • nike outlet
  • Christian Louboutin Outlet
  • burberry outlet
  • coach outlet
  • iphone cases
  • LV
  • new balance
  • 2012 March

    Skills Cloud Résumé

    On March 30, 2012, in Uncategorized, by derekgreer

     

    For some time I’ve presented a list of technical skills on the front page of my CV/résumé.  I’ve had some varied experience which I believe is valuable to present to prospective employers as a way of reflecting versatility and exposure to different paradigms, but listing everything tends to solicit undesired offers when my résumé makes it into the wild.  For instance, I’m not really interested in ever working in C/C++ or Java ever again, but I don’t want to remove it from my résumé either.  Another issue I’ve had is determining how to highlight which skills best reflect who I am today out of everything I have listed.  What I’ve typically done is break things down into categories of languages, platforms, application types, DI containers, ORM frameworks, etc. with the most recent experience at the front of the list.  While this provides a way of showing what I’ve done most recently, it didn’t provide a way to express how well I felt I knew a particular technology.

    After thinking about this recently, I decided to try out something new for awhile.  Rather than just showing a list of categorized skills, why not express them as a tag cloud?  This allows  more emphasis to be placed on those technologies someone feels best represents who they are today while also including things they’ve done in the past or things they may only have moderate exposure to.

     

    Here’s what the first page of my résumé looks like now:

     

    SkillCloudResume

     

     

    Thoughts?

    Tagged with:  

    RabbitMQ for Windows: Exchange Types

    On March 29, 2012, in Uncategorized, by derekgreer
    This entry is part 4 of 8 in the series RabbitMQ for Windows

    This is the fourth installment to the series: RabbitMQ for Windows.  In the last installment, we reviewed our Hello World example and introduced the concept of Exchanges.  In this installment, we’ll discuss the four basic types of RabbitMQ exchanges.

    Exchange Types

    Exchanges control the routing of messages to queues.  Each exchange type defines a specific routing algorithm which the server uses to determine which bound queues a published message should be routed to.

    RabbitMQ provides four types of exchanges: Direct, Fanout, Topic, and Headers.

    Direct Exchanges

    The Direct exchange type routes messages with a routing key equal to the routing key declared by the binding queue.  The following illustrates how the direct exchange type works:

      DirectExchange_thumb37

     

    The Direct exchange type is useful when you would like to distinguish messages published to the same exchange using a simple string identifier.  This is the type of exchange that was used in our Hello World example.  As discussed in part 3 of our series, every queue is automatically bound to a default exchange using a routing key equal to the queue name.  This default exchange is declared as a Direct exchange.  In our example, the queue named “hello-world-queue” was bound to the default exchange with a routing key of “hello-world-queue”, so publishing a message to the default exchange (identified with an empty string) routed the message to the queue named “hello-world-queue”.

    Fanout Exchanges

    The Fanout exchange type routes messages to all bound queues indiscriminately.  If a routing key is provided, it will simply be ignored.  The following illustrates how the fanout exchange type works:

     

    FanoutExchange_thumb[2]

     

    The Fanout exchange type is useful for facilitating the publish-subscribe pattern.  When using the fanout exchange type, different queues can be declared to handle messages in different ways.  For instance, a message indicating a customer order has been placed might be received by one queue whose consumers fulfill the order, another whose consumers update a read-only history of orders, and yet another whose consumers record the order for reporting purposes.

    Topic Exchanges

    The Topic exchange type routes messages to queues whose routing key matches all, or a portion of a routing key.  With topic exchanges, messages are published with routing keys containing a series of words separated by a dot (e.g. “word1.word2.word3”).  Queues binding to a topic exchange supply a matching pattern for the server to use when routing the message.  Patterns may contain an asterisk (“*”) to match a word in a specific position of the routing key, or a hash (“#”) to match zero or more words.  For example, a message published with a routing key of “honda.civic.navy” would match queues bound with “honda.civic.navy”, “*.civic.*”, “honda.#”, or “#”, but would not match “honda.accord.navy”, “honda.accord.silver”, “*.accord.*”, or “ford.#”.  The following illustrates how the fanout exchange type works:

     

    TopicExchange_thumb[2]

     

    The Topic exchange type is useful for directing messages based on multiple categories (e.g. product type and shipping preference ), or for routing messages originating from multiple sources (e.g. logs containing an application name and severity level).

    Headers Exchanges

    The Headers exchange type routes messages based upon a matching of message headers to the expected headers specified by the binding queue.  The headers exchange type is similar to the topic exchange type in that more than one criteria can be specified as a filter, but the headers exchange differs in that its criteria is expressed in the message headers as opposed to the routing key, may occur in any order, and may be specified as matching any or all of the specified headers.  The following illustrates how the headers exchange type works:

     

    HeadersExchange_thumb[2]

     

    The Headers exchange type is useful for directing messages which may contain a subset of known criteria where the order is not established and provides a more convenient way of matching based upon the use of complex types as the matching criteria (i.e. a serialized object).

    Conclusion

    That wraps up our introduction to each of the exchange types.  Next time, we’ll walk through an example which demonstrates declaring a direct exchange explicitly and take a look at the the push API.

    Tagged with:  

    RabbitMQ for Windows: Hello World Review

    On March 18, 2012, in Uncategorized, by derekgreer
    This entry is part 3 of 8 in the series RabbitMQ for Windows

    This is the third installment to the series: RabbitMQ for Windows.  In the last installment, we discussed some basic messaging concepts and created our first RabbitMQ application.  In this installment, we’ll be taking a closer look at our Hello World application to help round out our understanding of the basic concepts involved.

    Hello World Review

    In the previous installment, we walked through creating a Hello World example.  Let’s review the Producer and Consumer code again:

    Producer

    class Program
    {
      static void Main(string[] args)
      {
        var connectionFactory = new ConnectionFactory();
        IConnection connection = connectionFactory.CreateConnection();
        IModel channel = connection.CreateModel();
        channel.QueueDeclare("hello-world-queue", false, false, false, null);
        byte[] message = Encoding.UTF8.GetBytes("Hello, World!");
        channel.BasicPublish(string.Empty, "hello-world-queue", null, message);
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        channel.Close();
        connection.Close();
      }
    }

    Consumer

    class Program
    {
      static void Main(string[] args)
      {
        var connectionFactory = new ConnectionFactory();
        IConnection connection = connectionFactory.CreateConnection();
        IModel channel = connection.CreateModel();
        channel.QueueDeclare("hello-world-queue", false, false, false, null);
        BasicGetResult result = channel.BasicGet("hello-world-queue", true);
        if (result != null)
        {
          string message = Encoding.UTF8.GetString(result.Body);
          Console.WriteLine(message);
        }
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        channel.Close();
        connection.Close();
      }
    }

    In both the Producer and Consumer projects, we started our Main() method by establishing a Connection to the RabbitMQ server.  We then created a Channel to establish a line of communication with the server and declared a Queue to send and receive our messages.  In our Producer, we called BasicPublish() to place a message on the queue.  In our Consumer, we called BasicGet() to retrieve a message from the queue and print the message to the console.  In both the Producer and Consumer projects, we ended the Main() method by closing the channel and connection to the server.

    Establishing the Connection

    Let’s first discuss how our example connects to the RabbitMQ server.  In our example, we’re establishing a connection using the default connection settings.

    var connectionFactory = new ConnectionFactory();

    This assumes we have a RabbitMQ server running on our local development machine.  To connect to this instance, the ConnectionFactory uses a default host name of “localhost” and a default port of 5672.  A user name and password must also be provided to connect to the server.  When not specified, the ConnectionFactory uses a default user name and password of “guest”.  The “guest” user was pre-configured with full administrator rights when we first installed our  instance of RabbitMQ.  The final parameter of interest is the Virtual Host.  RabbitMQ utilizes virtual hosts (i.e. virtual instances of RabbitMQ) to allow multiple projects or teams to manage and secure their own set of queues from within a single RabbitMQ installation. 

    When we first installed RabbitMQ, a default virtual host named “/” was created.  The ConnectionFactory uses this virtual host when one is not specified.

    Specified explicitly, we might have configured these default values as follows:

    var connectionFactory = new ConnectionFactory
                              {
                                HostName = "localhost",
                                Port = 5672,
                                UserName = "guest",
                                Password = "guest",
                                VirtualHost = "/"
                              };
    IConnection connection = connectionFactory.CreateConnection();

    RabbitMQ also supports the AMQP URI Specification which allows these parameters to be specified as a single URI.  Using the URI option, we need to percent-encode the virtual host as “%2f”.  The following is how me might have established our connection using the amqp URI:

    var connectionFactory = new ConnectionFactory {Uri = "amqp://guest:guest@localhost:5672/%2f"};
    IConnection connection = connectionFactory.CreateConnection();

    Creating a Channel

    After establishing a connection with the server, the next step we take in both the Producer and Consumer projects is to create a Channel.

    IModel channel = connection.CreateModel();

    A channel is a light-weight connection used by RabbitMQ to enable multiple communication sessions through a single TCP/IP connection.  Operating systems have a limit to the number of TCP/IP connections that can be opened simultaneously, and creating these connections can be relatively expensive.  Through the use of channels, we are free to create as many virtual connections with the server as we want without incurring this overhead or being limited by the number of available TCP/IP connections.

    Channels are intended to be used for sequencing communication with the server such as declaring queues or the sending and receiving of messages.  A single channels should not be used by multiple threads simultaneously. For this reason, it is recommended that channels simply not be shared across threads.

    Declaring the Queue

    After opening a channel within our connection, the next step we take is to declare a Queue. 

    channel.QueueDeclare("hello-world-queue", false, false, false, null);

    A queue can be thought of as a sort of “mailbox”.  Messages put in the mailbox sit there until a recipient retrieves the mail.

    In our example, we named our queue “hello-world-queue”.  The queue name (along with the RabbitMQ host name and port number) serves as a sort of “mailbox address”.  When we publish the encoded string “Hello, World!”, it is placed in the queue named “hello-world-queue’ and awaits until a consumer retrieves and acknowledges the message.

    Before discussing the parameters used in our call to QueueDeclare, it will be helpful to take a short detour and discuss how our message actually gets routed from the Producer to the Consumer.

    Message Routing

    When looking at our example, it appears as though the Producer sends our message directly to the “hello-world-queue”.  What actually occurs, however, is that the message is routed to the “hello-world-queue” through an Exchange.

    When using RabbitMQ, messages aren’t actually published to a queue, but rather are published to an exchange which then routes messages to queues.  An exchange can be thought as a “post office”.  Just as we don’t generally put mail directly in a recipient’s mailbox, in RabbitMQ we don’t publish messages directly to a queue.

    To receive messages, a queue must first have an exchange binding established.  Part of establishing the binding includes specifying which messages should be routed to the queue.  In most cases, this is achieved by specifying a routing key which serves as a filter for which messages are delivered to which queues.

    The following diagram depicts how messages are published in RabbitMQ:

    The reason our code looks like it sends messages directly to the queue is due to the fact that we’re taking advantage of a convenience provided by the RabbitMQ server.  Whenever a queue is declared, it is automatically bound to a default exchange with a routing key equal to the queue name.  Messages published to the default exchange with a routing key equal to the value of a declared queue name are routed to the associated queue.

    In addition to being implicitly bound to all queues, the default exchange also cannot be unbound, deleted, or explicitly declared through code.  The only operation that is allowed is the publishing of messages.

    Queue Parameters

    Returning to our discussion of queue declaration, the parameters used in our call to QueueDeclare() creates our queue as a non-durable, non-exclusive, non-auto-deleted queue. 

    The durability flag pertains to what happens to our queue if the server is restarted.  Queues marked as durable will be recreated upon a server restart, while non-durable queues will not be.

    The exclusive flag pertains to whether a queue can be declared by more than one channel.  Since messages are actually published to exchanges, not queues, there may be cases where you only want a single client instance to be capable of declaring a queue bound to a particular exchange (for example, when using queues to facilitate an RPC call). 

    Lastly, the auto-delete flag pertains to whether the queue is automatically deleted once all consumers are removed.  This flag can be a little misleading since we might suppose setting this to true would cause our “hello-world-queue” to be automatically deleted after our application exists.  In fact, it wouldn’t be.

    There are two different approaches to receiving messages: pulling and pushing.  With the pull API, messages are retrieved on demand through a call to BasicGet().  This is the method used in our example.  With the pull API, available messages are delivered to a local queue when a Consumer is bound to the channel.  When setting the auto-delete flag to true, a queue will be deleted once it detects that all consumers have been removed.  While we named the project which receives messages from our queue “Consumer”, the pull API doesn’t actually declare a consumer to retrieve messages.  Therefore, the server is never alerted to the fact that the queue is no longer being used.

    Publishing the Message

    The last noteworthy point in our Producer project is the parameters to our call to BasicPublish().

    channel.BasicPublish(string.Empty, "hello-world-queue", null, message);

    The first parameter is the name of the exchange to publish the message to.  An empty string is the designation for the default exchange discussed earlier in the section on message routing.  The second parameter is the routing key.  As previously discussed, all queues are bound to the default exchange using a routing key equal to the value of the bound queue name.  The third parameter is an instance of IBasicProperties.  This class is used to associate a number of properties with the message, such as the message encoding, content-type, and durability.  We’ll take a look at some of the uses of this class further in our series.  Lastly, the fourth parameter is the byte array representing the message body.

    Getting the Message

    The last noteworthy point in our Consumer project is the parameters to our call to BasicGet().

    BasicGetResult result = channel.BasicGet("hello-world-queue", true);

    The first parameter is the queue to pull a message from which should be self-explanatory.  The second parameter is a flag which controls the auto-acknowledgement of the message. 

    When a message is retrieved from a queue with an auto-acknowledge flag set to false, the server holds the message in an unacknowledged state until an acknowledgement or rejection of the message is received on the open channel (note that messages must be accepted or rejected on the same channel they were received on).  This is useful when a consumer needs to ensure the message is processed successfully before it’s fully removed from the server.  If the channel is closed without receiving an acknowledgment, the message will be requeued and delivered to the next consumer (using pull or get).  In the event that a consumer determines it can’t process the message, it can reject the message with a flag indicating whether to requeue the message or not.

    Conclusion

    That’s it for our Hello World example review.  Next time, we’ll take a look at the four basic exchange types.

     

    Today I stumbled upon Scott Haselman’s post: How to access NuGet when NuGet.org is down (or you’re on a plane) in which Scott discusses how he recovered from an issue with the nuget.org site being down during his demo at the Dallas Day of .Net.   As it turns out, while NuGet stores packages it downloads in a local Cache folder within your AppData folder, it doesn’t actually use this cache by default.  Scott was able to remedy the situation by adding his local cache as a source through the the Visual Studio Package Manager plugin.

    Last year, I wrote about my philosophy for dependency management and  how I use NuGet to facilitate dependency management without using the Visual Studio plugin wherein I discuss using the NuGet.exe command line tool to manage .Net dependencies as part of my rake build.  After reading Scott’s post, I got to wondering whether the NuGet.exe command line tool also had the same caching issue and after a bit of testing I discovered that it does.  Since I, with the help of a former colleague, Josh Bush, have evolved the solution I wrote about previously a bit, I thought I’d provide an update to my approach which includes the caching fix.

    As discussed in my previous article, I maintain a packages.rb file which serves as a central manifest of all the dependencies used project wide.  Here’s one from a recent project:

    packages = [
    [ "Machine.Specifications", "0.5.3.0" ],
    [ "ExpectedObjects", "1.0.0.2" ],
    [ "Moq", "4.0.10827" ],
    [ "RabbitMQ.Client", "2.7.1" ],
    [ "log4net", "1.2.11" ]
    ]
    
    configatron.packages = packages
    

     

    This is sourced by a rakefile which which is used by a task which installs any packages not already installed.

    The basic template I use for my rakefile is as follows:

    require 'rubygems'
    require 'configatron'
     
    ...
    
    NUGET_CACHE= File.join(ENV['LOCALAPPDATA'], '/NuGet/Cache/') 
    FEEDS = ["http://[corporate NuGet Server]:8000", "https://go.microsoft.com/fwlink/?LinkID=206669" ]
    require './packages.rb'
     
    task :default => ["build:all"]
     
    namespace :build do
     
      task :all => [:clean, :dependencies, :compile, :specs, :package] 
    
      ...
    
      task :dependencies do
        feeds = FEEDS.map {|x|"-Source " + x }.join(' ')
        configatron.packages.each do | name,version |
          feeds = "-Source #{NUGET_CACHE} " + feeds unless !version
            packageExists = File.directory?("#{LIB_PATH}/#{name}")
            versionInfo="#{LIB_PATH}/#{name}/version.info"
            currentVersion=IO.read(versionInfo) if File.exists?(versionInfo)
            if(!packageExists or !version or !versionInfo or currentVersion != version) then
              versionArg = "-Version #{version}" unless !version
              sh "nuget Install #{name} #{versionArg} -o #{LIB_PATH} #{feeds} -ExcludeVersion" do | ok, results |
                File.open(versionInfo, 'w') {|f| f.write(version) } unless !ok
            end
          end
        end
      end
    end
    

     

    This version defines a NUGET_CACHE variable which points to the local cache.  In the dependencies task, I join all the feeds into a list of Sources for NuGet to check.  I leave out the NUGET_CACHE until I know whether or not a particular package specifies a version number. Otherwise, NuGet would simply check for the latest version which exists within the local cache.

    To avoid having to change Visual Studio project references every time I update to a later version of a dependency, I use the –ExcludeVersion option.  This means I can’t rely upon the folder name to determine whether the latest version is already installed, so I’ve introduced a version.info file.  I imagine this is quite a bit faster than allowing NuGet to determine whether the latest version is installed, but I actually do this for a different reason.  If you tell NuGet to install a package into a folder without including the version number as part of the folder and you already have the specified version, it uninstalls and reinstalls the package.  Without checking the presence of the correct version beforehand, NuGet would simply reinstall everything every time.

    Granted, this rake task is far nastier than it needs to be.  It should really only have to be this:

      task :dependencies do
        nuget.exe install depedencyManifest.txt –o lib
      end
    

     

    Where the dependencyManifest file might look a little more like this:

    Machine.Specifications 0.5.3.0
    ExpectedObjects 1.0.0.2
    Moq 4.0.10827
    RabbitMQ.Client 2.7.1
    log4net 1.2.11
    

     

    Nevertheless, I’ve been able to coerce the tool into doing what I want for the most part and it all works swimmingly once you get it set up.

    Tagged with:  
    This entry is part 2 of 8 in the series RabbitMQ for Windows

    This is the second installment to the RabbitMQ for Windows series.  In our first installment, we walked through getting RabbitMQ installed on a Microsoft Windows machine. In this installment, we’ll discuss a few high-level concepts and walk through creating our first RabbitMQ application.

    Basic Concepts

    To being, let’s discuss a few basic concepts. Each of the examples we’ll be working through will have two roles represented: a Producer and a Consumer. A Producer sends messages and a Consumer receives messages.

    Messages are basically any blob of bytes you’d like to send. This could be a simple ASCII string, JavaScript Object Notation (JSON), or a binary-serialized object.

    Messages are sent to Queues.  A Queue is a First-In-First-Out (FIFO) data structure. You can think of a queue as a sort of pipe where you put messages in one side of the pipe and the messages arrive at the other end of the pipe. 

    The following diagram depicts these concepts:

     

    ProducerQueueConsumer_thumb5

     

    We’ll introduce other concepts further into the series, but that’s the basics. Let’s move on to creating our first example.

    Hello, World!

    Our first application will be an obligatory “Hello World” example.  We’ll create a Publisher application which sends the string “Hello, World!” to a RabbitMQ queue and a Consumer application which receives the message from the queue and displays it to the console.

    For all of our examples, we’ll be using the official RabbitMQ .Net client available here.  This library is also available via NuGet, so if you have the NuGet Package Manager installed you can retrieve it through the “Tools->Library Package Manager” menu item, or if you have the NuGet.exe command line utility then you can issue the following command in the directory you’d like it installed to:

    nuget install RabbitMQ.Client
    

     

    Create the Producer

    To start, let’s create a new empty solution named HelloWorldExample (File->New->Project->Other Project Types->Visual Studio Solutions->Blank Solution). Once you have that created, add a new project of type “Console Application” to the solution and name it “Producer”.

    Next, add a reference to the RabbitMQ.Client.dll assembly.

    The first thing we’ll need to do for our producer is to establish a connection to the RabbitMQ server using a ConnectionFactory:

    namespace Producer
    {
      class Program
      {
        static void Main(string[] args)
        {
          var connectionFactory = new ConnectionFactory();
          IConnection connection = connectionFactory.CreateConnection();
        }
      }
    }
    

     

    The ConnectionFactory has a number of properties that can be set for our connection. In this example, we’re establishing a connection using the default connection settings which assumes you have the RabbitMQ Windows service running on your local development machine. If you’ve installed it on a different machine then you’ll need to set the Host property of the connectionFactory instance to the DNS name where you’ve installed RabbitMQ.

    Next, we need to create a Channel:

    IModel channel = connection.CreateModel();
    

     

    A channel is a light-weight connection which RabbitMQ uses to enable multiple threads of communication over a single TCP/IP socket. Note that the actual type created is RabbitMQ.Client.IModel. In most RabbitMQ client libraries the term channel is used, but for some reason the authors of the .Net client library chose to use the term “Model”. Descriptive, eh? We’ll use the instance name of “channel” to be more descriptive.

    Next, we need to create a queue:

    channel.QueueDeclare(“hello-world-queue”, false, false, false, null);
    

     

    This creates a queue on the server named “hello-world-queue” which is non-durable (won’t survive a server restart), is non- exclusive (other channels can connect to the same queue), and is not auto-deleted once it’s no longer being used.  We’ll discuss these parameters in more detail further in our series.

    Next, we’ll declare a byte array containing a UTF8-encoded array of bytes from the string “Hello, World!” and use the BasicPublish() method to publish the message to the queue:

    byte[] message = Encoding.UTF8.GetBytes("Hello, World!");
    channel.BasicPublish(string.Empty, “hello-world-queue”, null, message);
    

     

    Again, don’t worry about understanding the parameters just yet. We’ll get to that soon enough.

    Finally, we’ll prompt the user to press a key to exit the application and close our channel and connection:

    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
    channel.Close();
    connection.Close();
    

     

    Here’s the full Producer listing:

    using System.Text;
    using RabbitMQ.Client;
    
    namespace Producer
    {
      class Program
      {
        static void Main(string[] args)
        {
          var connectionFactory = new ConnectionFactory();
          IConnection connection = connectionFactory.CreateConnection();
          IModel channel = connection.CreateModel();
          channel.QueueDeclare("hello-world-queue", false, false, false, null);
          byte[] message = Encoding.UTF8.GetBytes("Hello, World!");
          channel.BasicPublish(string.Empty, "hello-world-queue", null, message);
          Console.WriteLine("Press any key to exit");
          Console.ReadKey();
          channel.Close();
          connection.Close();
        }
      }
    }
    

     

    Create the Consumer

    Next, let’s create our Consumer application. Add a new Console Application to the solution named “Consumer” and add a reference to the RabbitMQ.Client assembly. We’ll start our consumer with the same connection, channel, and queue declarations:

    var connectionFactory = new ConnectionFactory();
    IConnection connection = connectionFactory.CreateConnection();
    IModel channel = connection.CreateModel();
    channel.QueueDeclare("hello-world-queue", false, false, false, null);
    

     

    Next, we’ll use the BasicGet() method to consume the message from the queue “hello-world-queue”:

    BasicGetResult result = channel.BasicGet("hello-world-queue", true);
    

     

    Next, we’ll check to ensure we received a result. If so, we’ll convert the byte array contained within the Body property to a string and display it to the console:

    if (result != null)
    {
      string message = Encoding.UTF8.GetString(result.Body);
      Console.WriteLine(message);
    }
    

     

    Lastly, we’ll prompt the user to press a key to exit the application and close our channel and connection:

    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
    channel.Close();
    connection.Close();
    

     

    Here’s the full Consumer listing:

    using System;
    using System.Text;
    using RabbitMQ.Client;
    
    namespace Consumer
    {
      class Program
      {
        static void Main(string[] args)
        {
          var connectionFactory = new ConnectionFactory();
          IConnection connection = connectionFactory.CreateConnection();
          IModel channel = connection.CreateModel();
          channel.QueueDeclare("hello-world-queue", false, false, false, null);
          BasicGetResult result = channel.BasicGet("hello-world-queue", true);
          if (result != null)
          {
            string message = Encoding.UTF8.GetString(result.Body);
            Console.WriteLine(message);
          }
          Console.WriteLine("Press any key to exit");
          Console.ReadKey();
          channel.Close();
          connection.Close();
        }
      }
    }
    

     

    To see the application in action, start the Publisher application first and then start the Consumer application. If all goes well, you should see the Consumer application print the following:

    Hello, World!
    Press any key to exit
    

     

    Congratulations! You’ve just completed your first RabbitMQ application.  Next time, we’ll take a closer look at the concepts used within our Hello World example.

    						
    Tagged with:  

    RabbitMQ for Windows: Introduction

    On March 5, 2012, in Uncategorized, by derekgreer
    This entry is part 1 of 8 in the series RabbitMQ for Windows

    If you’re interested in getting started with distributed programming and you develop on the Microsoft Windows platform, RabbitMQ may be what you’re looking for.  RabbitMQ is an open source, standards-based, multi-platform message broker with client libraries available for a host of development platforms including .Net.  

    This series will provide a gentle introduction to getting started with RabbitMQ for .Net developers, including a Windows environment installation guide along with an introduction to basic concepts and features through the use of examples in C#.  In this first installment, we’ll cover installation and basic configuration.

    Installation

    The first thing to know about RabbitMQ installation is that RabbitMQ runs on the Erlang virtual runtime.  “What is Erlang”, you ask, and “Why should I ask our admins to install yet another runtime engine on our servers”?  Erlang is a functional language which places a large emphasis on concurrency and high reliability.  Developed by  Joe Armstrong, Mike Williams, and Robert Virding to support telephony applications at Ericsson, Erlang’s flagship product, the Ericsson AXD301 switch, is purported to have achieved a reliability of nine "9"s.

    A popular quote among Erlang adherents is Verding’s “First Rule of Programming”:

    “Any sufficiently complicated concurrent program in another language contains an ad hoc informally-specified bug-ridden slow implementation of half of Erlang.” – Robert Verding

    Sound like the perfect platform to write a message broker in?  The authors of RabbitMQ thought so too.

    With that, let’s get started with the installation.

     

    Step 1: Install Erlang

    The first step will be to download and install Erlang for Windows.  You can obtain the latest installer from here (version R15B at the time of this writing) .

    After downloading and completing the Erlang installation wizard, you should have a new ERLANG_HOME environment variable set.  If not, you’ll want to set this now so RabbitMQ will be able to locate your installation of Erlang.

    ErlangEnv

     

     

    Step 2: Install RabbitMQ

    Next, download and install the latest version of RabbitMQ for Windows from here (version 2.7.1 at the time of this writing).

     

    Step 3: Install the RabbitMQ Management Plugin

    By default, the RabbitMQ Windows installer registers RabbitMQ as a Windows service, so technically we’re all ready to go.  In addition to the command line utilities provided for managing and monitoring our RabbitMQ instance, a Web-based management plugin is also provided with the standard Windows distribution.  The following steps detail how to get the management plugin up and going.

    First, from an elevated command prompt, change directory to the sbin folder within the RabbitMQ Server installation directory (e.g. %PROGRAMFILES%\RabbitMQ Server\rabbitmq_server_2.7.1\sbin\).

    Next, run the following command to enable the rabbitmq management plugin:

    rabbitmq-plugins.bat enable rabbitmq_management 

     

    Lastly, to enable the management plugin we need to reinstall the RabbitMQ service.  Execute the following sequence of commands to reinstall the service:

     
    rabbitmq-service.bat stop 
    rabbitmq-service.bat install 
    rabbitmq-service.bat start 

     

    To verify management plugin is up and running, start your favorite browser and navigate to http://localhost:55672/mgmt/.  If everything went ok, you should see a screen similar to the following:

     

     RabbitManagement

    From here, you’ll be able to configure and monitor your RabbitMQ instance.

    That concludes our installation guide.  Next time, we’ll walk through writing our first RabbitMQ C# application.

    Tagged with:  

    TDD Best Practices: Write Assertions First

    On March 5, 2012, in Uncategorized, by derekgreer
    This entry is part 1 of 2 in the series TDD Best Practices

    When practicing Test-Driven Development, developers often organize their tests following a style first described by Bill Wake as Arrange, Act, Assert.  This division between the setup, the exercising the System Under Test, and the assertions are also reflected in the Context/Specification and Given/When/Then (GWT) styles of Behavior-Driven Development (with the GWT style often containing multiple “Act” steps).  This division is generally a Good Thing, as it guides the developer toward the authoring of well-organized and readable tests which provide a good template for modeling most specifications.  Unfortunately, developers are often lead to implement tests in the order of Arrange, Act, Assert which serves to undermine the purpose of practicing TDD: to allow the needs of the test to guide the design of the system.

    When transforming a requirement into an executable specification, after establishing the logical class or object which will contain the test implementation, the first step should be to determine how the specification (i.e. the test) is to be validated.  That is to say, the first step is to write an assertion.

    The goal of Test-Driven Development is to produce clean code that works.  By ‘clean’, we mean code that’s free of unnecessary behavior or abstractions.  The TDD techniques of first doing the simplest thing that could possibly work, refactoring to remove duplication, and using triangulation for identifying the need for generalizations are set forth to restrain developers from writing code that isn’t actually needed.  This leads to simpler, more maintainable code.  Starting with the setup implementation before determining how you’re going to verify the desired outcome is putting the cart before the horse.  How do you know a particular setup implementation will be needed to test the desired outcome before you’ve established what that is?  Perhaps you’ll be building upon the existing type you’re jumping ahead to setup, but perhaps it should be a new type altogether.  Figure out how you’re going to verify the desired outcome first and then determine what components make sense to fulfill the desired outcome.

    To help illustrate this flow, let’s consider the following example.  Let’s say we’re writing an application which allows employee’s at a company to register for a training class.  When an employee registers for a class, they should be provided with a registration receipt.  Let’s start by establishing the shell of our specification:

    public class when_registering_for_a_class
    {
      Establish context;
    
      Because of;
    
      It should_return_a_registration_receipt;
    }

    Next, we need to determine how we want to verify that the logical condition “It should return a registration receipt” will be fulfilled.  Let’s assert that a variable named _registrationReceipt is not null:

    public class when_registering_for_a_class
    {
      Establish context;
    
      Because of;
    
      It should_return_a_registration_receipt = () => _registrationReceipt.ShouldNotBeNull();
    }

    It’s at this point some may have an objection to typing out an assertion without the aid of auto-completion (i.e. Intellisense).  Some are so dependent upon auto-completion that they’ll actually stop after typing _registrationReceipt, and go declare a variable just so their auto-completion will be there.  Resist that urge.  Assertions shouldn’t be difficult and this will actually force you to keep it simple.

    Next, we need to decide how we are going to assign our variable, so we’ll move to our Because delegate.  At this point, we’ll also determine what component and usage API we’d like to use to retrieve our receipt:

    public class when_registering_for_a_class
    {
      Establish context;
    
      Because of = () => _registrationReceipt = _registrar.Register(EmployeeId, ClassId);
    
      It should_return_a_registration_receipt = () => _registrationReceipt.ShouldNotBeNull();
    }

    Next, we need to establish our context.  We’ll initialize the _registrar to a non-existent type named Registrar:

    public class when_registering_for_a_class
    {
      Establish context = () => { _registrar = new Registrar(); };
    
      Because of = () => _registrationReceipt = _registrar.Register(EmployeeId, ClassId);
    
      It should_return_a_registration_receipt = () => _registrationReceipt.ShouldNotBeNull();
    }

    At this point, we can use ReSharper to generate a field name _registrar, generate the Registrar class, and generate the Registrar.Register() method.  Once the Register() method is generated, we need to choose the type we’ll use for the return value and parameters and then replace the throw statement with a return of null so our assertion will fail for the right reason later.  Let’s make the receipt be a RegistrationReceipt type and use integers for our Ids:

    public class when_registering_for_a_class
    {
      static Registrar _registrar;
    
      Establish context = () => { _registrar = new Registrar(); };
    
      Because of = () => _registrationReceipt = _registrar.Register(EmployeeId, ClassId);
    
      It should_return_a_registration_receipt = () => _registrationReceipt.ShouldNotBeNull();
    }
    
    class Registrar
    {
      public RegistrationReceipt Register(int employeeId, int classId)
      {
      }
    }

    Continuing, we generate the RegistrationReceipt type, _registrationReceipt field, and create some constants for our Ids:

    public class when_registering_for_a_class
    {
      const int EmployeeId = 1;
      const int ClassId = 2;
      static Registrar _registrar;
      static RegistrationReceipt _registrationReceipt;
    
      Establish context = () => { _registrar = new Registrar(); };
      
      Because of = () => _registrationReceipt = _registrar.Register(EmployeeId, ClassId);
    
      It should_return_a_registration_receipt = () => _registrationReceipt.ShouldNotBeNull();
    }
    
    class Registrar
    {
      public RegistrationReceipt Register(int employeeId, int classId)
      {
        return null;
      }
    }
    
    class RegistrationReceipt
    {
    }

     

    At this point everything compiles cleanly.  Running our test with the ReSharper test runner produces the following:

    should return a registration receipt : Failed
    Should be [not null] but is [null]

    We’re now ready to make our test pass (which we can do by just returning a new RegistrationReceipt from our Register method), factor out any duplication, and move on to our next assertion or specification either to flesh out this design or to move on to our next feature.

    By starting with our assertion first, moving to the execution of our System Under Test, and ending with our context setup, we’ve allowed our test to guide our design rather than allowing an existing design (coded or in our heads) to guide the implementation of our test.

    In summary, organize your tests using Arrange, Act, Assert, but implement them in the order of Assert, Act, Arrange.

    Tagged with: