Code Bullets Logo
 

In this post I want to talk about how reliable messaging can be achieved. With reliable messaging I mean transporting the message safely from one service to another as well as executing the assigned logic in a safe way. This message handling should not corrupt any state and be consisted even in case of system and network failures.

First we have to choose a network protocol that ensures our messages are correctly transported over the network. Nowadays this is a real no-brainer, everyone is using TCP/IP for that, with a good reason.

As can be seen in the picture above every packet sent to the server is answered with a special ACK response. This indicates that the packet has been successfully received with all data intact. Additionally TCP implements features like automatic retry in case there is packet loss on the network, it ensures the correct packet order and so forth. No wonder it became a first choice when working on a widely distributed network like the Internet.

However, when used in a messaging system there is a little drawback. The ACK response does not carry any other information besides the successful transport indication. Unfortunately a great many times we need to return additional data back to client. The bare minimum is whether the unit of work as been executed successfully or not. This is not possible with a single TCP ACK representing only a successful message transport.

To overcome this problem often a protocol on top of TCP is used. One of the most famous request protocols in this regard is HTTP. The basic messaging pattern is shown below. The client sends a packet to server which has at least a HTTP header. If received successfully the packet is answered with the already known TCP ACK.

Next the server processes the request. This may result in reads or writes on a file system or a database. Once the server has finished processing the message a separate response is returned which contains a HTTP status code like 200 OK or 400 Bad Request. Together with this code additional data may be transported like a HTML, JSON or XML document. This pattern and processing is enough for a great many messaging applications out there.

Lets think about possible errors here and analyze whether this is reliable in case the network fails or a system crash. If the server crashes after successfully receiving the message, but before any work is done, no response will be sent back. The client will probably have some sort of timeout mechanism and can either wait or try again on the same or a different server. This is secure, we know the server has crashed and no harm is done, no state has changed. Now consider another scenario. The server receives the message, finishes a transaction on a data store and  at the next moment the problem occurs right before a success can be sent back to the client. In most cases this is not a problem either. For example if it was just a query and no state has changed on the server side, it will not corrupt anything. The client retries the operation and if it succeeds the second time around everything is fine.

The problem starts if the work done on the server involves write operations or sending messages to other services. Depending on the message and the operation certain side effects may occur. Consider something like drawing money from an ATM. If the operation succeeds on the server and the client is not informed about the success it may rightfully assume a failure and try again resulting in 2 transactions. As a result the money will be booked twice from the account while the ATM hands it out only once. This is bad, we need a solution for this. Continue reading…

Comments Off

Wacom just released a new “real” and digital pen called “Inkling”. It works like a common ball-point pen on paper, but it also records and transfer your sketches to the computer.

Yesterday, I got my package with the Inkling and I started to play around. For the Inkling you don’t need any kind of special paper and it uses a standard ink refill.

Start Sketch Animation (if not started automatic)

The above simple sketch was created with the Inkling. The second chapter of this post shows how the animation effect was done with JavaScript.

How the Inkling works

To record a sketch the receiver unit has to be placed on the upper border of the paper. Then position and pressure (1024 levels) of your pen are saved to an internal 2GB memory. Your sketch is stored as a vector graphic, so the receiver can hold several hundrets sketches. I like the idea of using vector data. It’s just great to work with it directly in e.g.  Adobe Illustrator. Another great feature is drawing on separate layers. This means you can create a new layer with pressing a button on the receiver. Then every new drawn line is assigned to the new layer.

After your sketch is ready you can open it with the Sketch Manager and export it as PNG, JPG, PDF, SVG, BMP, TIFF or edit it directly in Adobe Photoshop or Illustrator (since CS3).  You can find out more about the Inkling here.

Wacom Inkling

Fazit

Very cool, I like it! Now, I am interested in how it will influence my daily work. After testing it two days, here is a list of pro and cons:

Pro:
++ Vector data
++ No special paper required
++ Standard ink refill.
++ Accurate position detection
+ Sketching on different layers
+ Lightweight pen for all the technical stuff inside.
+ Practical transport case with integrated recharger

Contra:
– Creating a new layer can sometimes result in an position offset between layers. Maybe I moved the receiver while pressing the new layer button. I will start to investigate this.
- Price (About €170 in Europe)
- You have to learn that nothing (for example: my non-sketching hand) shall be between the receiver and the peak of the pen.
- It is not possible to go back one layer

Missing:

The Sketch Manager has no OCR for text recognition. Using the Inkling for taking textual notes requires additional work steps and a separate OCR software.

Leave a comment and let me know how you like the Wacom Inkling? And now something for developers:

How to animate an Inkling SVG with JavaScript

To create this animation I am using the jQuery library. Download it and add it to your HTML document.

<script type="text/javascript" src="jquery-1.6.4.js"></script>

Then add the SVG image to the html document:

<div id="svgContainer" style="overflow: visible; width:500px; height:200px;">
   <embed id="svgImage" src="codebullets2.svg" onload="start()" type="image/svg+xml"
      style="overflow:hidden; width: 500px; height: 200px;" ></embed>
</div>

After loading the SVG image the animation shall start. The start function needs to get the DOM of the SVG. jQuery is not build for manipulating the SVG DOM, but since HTML and SVG are similiar to XML, a lot of operations are working. That makes the rest very simple. So this is the start function:

// Get the SVG DOM Document
var svg = $("#svgImage");
var doc = svg[0].getSVGDocument();

// Get all SVG g items.
_items = $($("g", doc));

// Hide all items
_items.hide();

// Show the SVG Image itself. But every SVG group is hidden.
// So at this point the user will see nothing.
$("#svgImage").show();

// Show the first SVG item
showSVGItem(0);

In the “hide” section you will find a jQuery selector for “g”. The SVG file of the Inkling Sketch Manager stores every single path/polygon data within a single group (g) element. So select all the groups, store them in a private var _items  and hide them. The showSVGItem function now displays a single “group” tag of the items list given by an index.

// Show an SVG item at given index.
function showSVGItem(index)
{
   if (index < _items.length)
   {
      $(_items[index]).show();

      // Show the next item with a delay
      index++;
      setTimeout(showSVGItem, _delay, index);
   }
}

That’s it, have fun. Please check the example HTML site with the complete source.

By the way the codebullets SVG file contains 1040 groups and the animation effect was tested with current browser versions of Opera, Safari, Firefox and Chrome.(IE9 has some problems.)

Comments Off

As described in one of my previous posts the dependency inversion principle is one of the major design principles of software. It allows for easier testing as well as being much more responsive to requirement changes. Routing and wiring all these dependencies together is usually not performed manually by the developer. It is a very cumbersome task as one would have to take into account dependency chains as well circle dependencies and so forth. This is the task of a separate dependency injection (DI) container which is able to do all these things for us.

Injection by Andreas Levers - Licensed under CC

Until recently my favorite container has been StructureMap. It is very fast and has a great set of features. However it does not support all current .Net runtime scenarios. For example it will not run under the .Net 4.0 client profile or inside a Windows Phone 7 Silverlight app. For this reasons I searched around a bit and found Autofac to be a perfect replacement. Like with StructureMap it is very easy to set up with a fluent interface. Additionally it has features like automatic support for Lazy<T> types.

However, the most important feature for me to switch over to Autofac is a something called DelegateFactories. Sometimes there is an object which needs a parameter at runtime to be initiated. For example, think of a Queue class which needs a custom name as constructor parameter, or like in the example below a pseudo printer class having a text writer parameter where the text is printed to.

public class TextPrinter : IPrinter
{
  private readonly TextWriter _writer;

  public TextPrinter(TextWriter writer)
  {
    _writer = writer;
  }

  public void Print(string text)
  {
    _writer.WriteLine(text);
  }
}

With StructureMap I would usually solve this with a custom factory implementation. This factory would then be injected into any class which needs a reference to the specific printer. The factory itself is responsible for creating a new printer instance. Often this would mean for the factory to have a reference to the DI container itself to pass on the parameter. This is something I try to avoid if possible. My custom code should not depend on the infrastructure around it. Actually, using the dependency inversion principle it should be the other way round. The infrastructure should depend on my business code and try to fulfill its needs as best as possible.

Autofacs support for DelegateFactories solves this problem very nicely. Instead of injecting a custom factory it recognizes the structure of the delegate used as the parameter in my class constructor. In the example below I’m using a function which takes a TextWriter as parameter and returns an IPrinter instance as a result.

public class Invoice : IInvoice
{
  private readonly Func<TextWriter, IPrinter> _getPrinter;

  public Invoice(Func<TextWriter, IPrinter> getPrinter)
  {
    _getPrinter = getPrinter;
    this.Id = Guid.NewGuid().ToString();
  }

  public string Id { get; private set; }

  public void Print()
  {
    _getPrinter(Console.Out).Print("InvoiceId: " + this.Id);
  }
}

Have a look at the example code linked to this post. Please note that there is no code necessary to resolve this dependency to the factory delegate. Autofac automatically recognizes the delegate and creates the implementation code behind the scenes. All it takes as configuration is to tell Autofac the concrete implementations of IPrinter and IInvoice. This may be done in a custom Autofac module like this:

protected override void Load(ContainerBuilder builder)
{
  builder.RegisterType<Invoice>().AsImplementedInterfaces();
  builder.RegisterType<TextPrinter>().AsImplementedInterfaces();
}

The call parameter of the delegate is matched with the constructor parameter of the Printer class without any single line of additional code. As a bonus, it is not  necessary for the factory delegate to exactly match the constructors parameter layout. The printer may have additional dependencies not part of the the called delegate. As long as Autofac has a definition of them somewhere it will automatically fill in the gaps. This is really great and it makes my life working with the DI container so much easier.

Well, I guess all software developers have came across code which is considered to be ‘bad’. From my point of view code is bad if it has at least one of 3 characteristics. For me that is pretty much the opposite what Eric Lipperts defines in his article as good code.

  • Does not work according to the the functional requirements.
  • Is hard for the reader to understand.
  • Is very difficult to change as requirements are changing.

Most of the time I find this stuff in legacy code and of course not the one the team is currently working on. But then, how has this code been born into existence if no one ever wrote it? The answer is difficult and in my experience caused by a lot of different factors. When I talk to my fellow developers they tell me that the version of their piece of software is of course “perfect”. However, afterwards the problems start. Change requests from customers are coming in, errors are found, quick fixes are made, critical milestones are approaching way too fast and so forth. What happens now is, as Robert C. Martin (“Uncle Bob”) describes it, that the design starts to rot and decay. Given enough time the once so beautiful architecture is just a big pile of spaghetti code which is hard to maintain and costs huge amounts of money to keep in working condition as external environments are changing.

But how to avoid this? Is there a way to keep the code base clean, even if it is being worked on for a long time. In my experience this is a constant uphill battle.

An uphill battle - by Frank Kehren - licensed under CC

Keeping the code from decay takes constant effort. I often feel like going upwards endlessly with no end in sight.

Teams and companies often try to fight the starting chaos creeping into the code with rules and guidelines and maybe other quality gates like code reviews. However, the larger the code base gets the more effort it takes to enforce this. This results in increased costs in what originally seems to be just a little change or fix. The older the code gets, the more likely it is that the original senior developers have moved on to other projects and do not have the time to look over every commit and little feature added. Maybe they are not even working in the company at all. As a result the code starts to decay and we are back at square one.

The only thing which really seems to help in this fight is to automate the quality measurements available as much as possible. It is also important to try to detect violations as early as possible. I often heard the sentence: “I’m going to fix this later.”. Chances are good it will never be changed at all. The only way to really enforce coding rules is, if the compiler generates an error as the violation occurs. This is the only way to force a developer to do it as it was originally intended.

I’m primarily working with .Net and C# and in my opinion there are some good tools around to help with this. This ensures a continued quality of the code even for longer projects and projects which have long switched from development into maintenance mode.

The first one is StyleCop. This is a static code analysis tool originally developed by Microsoft but has been made available as open source later on. It can easily be integrated into the Visual Studio build process. It already ships with a lot of reasonable rules and I’ve implemented even more. For example in our team we have rules limiting the maximum allowed cyclomatic complexity and maximum effective lines of code per method. Additionally there is a rule to limit the total number of lines per file. This alone provides a very effective protection against god classes and methods.

Another one is FxCop which is available in Visual Studio Professional (and greater) under the code analysis project options. This one checks more advanced patterns like correct disposing of objects and other probable mistakes.

Probably the most important tool is NUnit or any other unit testing framework. For me, it currently seems the only way to ensure that existing features still work after code has been changed. In comparison to a full system regression test it is also very cheap and pays off very quickly.

Well, I guess these are the most important ones coming to my mind. Of course there are other tools available like for example NDepend to continuously check your architecture. However, in my opinion if you have the ones mentioned above in place together with a separate  build server you are very much on the right track.

A bad part of CSS is that it has no support for variables or placeholders. So we can not define a color value somewhere,  to use it easily with different styles. Every style using a color has to define a concrete color value in the format of #rrggbb or rgb(0-255,0-2555,0-255).

An example:

h1 { color: #0000F1; }
div { border-color: #0000F1; }
span.highlight { background-color: rgb(0, 0, 241); }

This example uses the same color for all elements. If you have worked on a bigger web project then you know what can happen:

  • CSS files tend to grow and there is always more than one css style file.
  • Colors tend to be changed more often than the designer likes it.

Color Scheme JavaScript

To discover what color values a website really uses, I wrote a short JavaScript Code that analyses the used css styling and shows a color palette. This chapter explains how the code works, skip this chapter to go directly to “How To Use colorScheme.js”

The script uses the jQuery library to get css values of an element. It is really easy to get the background color, for example an element with id = “MyId”. The $ sign stands for jQuery.


var color = $("#MyId").css("backgroundColor");

Visit jQuery site to learn more about jQuery.

The colorScheme.js module has two important functions:

  • analyse – recursive function that analyses all child elements for colors, starting with the <body> tag.
  • create – creates the color palette within the element specified by its Id.

The analyse method is automatically called when the html document is loaded and ready.

   // Stores the colors
   this.colors = [];

   var that = this;

   $(document).ready(function ()
   {
      that.analyse();
      that.create("colorPalette");
   });

The analyse method uses the getAllColorsRecursive method with $(“body”) as argument. It stores the backgroundColor, color, borderColor of all elements in the colors object.

   function getAllColorsRecursive(jqObj)
   {
      addColorFromCss(jqObj, "backgroundColor");
      addColorFromCss(jqObj, "color");
      addColorFromCss(jqObj, "borderColor");

      // Analyse all children.
      jqObj.children().each(function ()
      {
         getAllColorsRecursive($(this));
      });
   }

The create method adds an item for each color to the given colorPalette element. The color item structure looks like this:

#????? will be replaced with the specific color value. Now you can style your own color palette, or use the styling from the example at the end of this post. ;-)

How To Use colorScheme.js

Download the colorScheme.js script file.
The script uses the jQuery library, can be download at http://jquery.com/.

Add the scripts to your page with:

<script src="jquery-1.5.js" type="text/javascript"></script>
<script src="colorScheme.js" type="text/javascript"></script>

Add a div element with id=”colorPalette” to define a place where the color palette shall be shown.

<div id="colorPalette" ></div>

The script will generate the color palette automatically when the html document is loaded and ready.

Add some styling for colorItem, colorItemColor, colorItemText to get a pretty color palette or use this to get the following look:

Script used on this page.

This is the color palette of codebullets.com

I’ve come accross a nice post from Mike Hadlow called I Don’t Have Time for Unit Tests. Backed up with data from the Microsoft Visual Studio team, he concludes that doing TDD and unit tests is one of the things actually helping developers spending time on real coding. If no unit tests are in place developers spend most of their time trying to understand existing code and fixing bugs which should not have been there in the first place. As he describes most of the productivity gains using TDD come from:

  • Allows safe modifications. If you break something when you modify some code, the unit tests fail.
  • Shortening the iteration cycle between writing/running code. No more need to step through your application to part where your new code gets exercised.
  • Mistakes in your code are shallow and obvious. No more need to step through code in the debugger, wondering which part of your application is broken.
  • Code is self-documenting. The unit tests explicitly show how the author expected the code to be used.
  • Code is decoupled. You can’t do TDD without decoupling. This alone makes the code easier to understand as a unit and much safer to modify.

I do agree completely on these points. It matches with my own experience doing TDD. However, recently I find myself doing some coding without any tests in place. Why is that? After all I’m a big fan of TDD and high quality code. Shouldn’t I do unit tests under any circumstances, no matter what?

Well, I found that there a are some (minor) cases where TDD does actually get in the way. One of those cases are Proof of Concepts (POC) where I try to learn something completely new to me, or figure out if an idea could actually work at all. The important part here is that these POC are rather small in effort (<40h) and are not used directly in real production code. Once the POC is finished I take the lessons learned and start anew. The second time around you are going to make things even better,  put it into production and have proper tests in place right from the start.

Another area where I’m bad with unit tests are internal tools like test clients for our services and other such little helpers. The important thing here is that they are very small (<40h) and are typically used only by myself or a very limited number of people. Again it is not production code we are talking about here. Sometimes it happens that such a tool or test client begins being used by more people as it satisfies a demand by other fellow developers, engineers or admins. If this happens it is better to trash the old tool and make something new and probably even better. After all, not much effort went into creating it in the first place and chances are good that I am even faster and and can improve the existing design the second time around. But this time I do it with all proper tests and QA tools in place.

Comments Off

I’m a very big fan of unit testing. In my opinion such automated tests are one of the very few ways to ensure a continued and measurable quality of your production code. Without them the production code starts to rot. If there are multiple developers involved with the project and code base having a different quality mindset rotting is even faster.

In his book Clean Code, Robert  C. Martin (2008) has a very good example of this.  He goes even further and comes to the conclusion that badly written test code may be even worse than no tests at all. I wholeheartedly agree on this. If your unit tests are hard to read, difficult to change and maintain, they become a burden to the developer instead of being a real help. In this post I want to describe some guidelines I have adapted for myself. Some of them seem to be no-brainers but after seeing test code from another team, I definitely like the put them here anyway. They are in no particular order,  I consider them all equally important.

  • Put the tests into a separate assembly. Your production code could should not mingle with the tests. Instead the tests should be sitting on top of your classes, not in between them.
  • Think of a consistent structure to organize your tests. I like to duplicate my folder structure I have for my production classes and create test fixture classes for each production class. This usually serves me very well. I know this may not be appropriate when using certain test frameworks like SpecFlow for example.  In this case it is much more appropriate to organize the files more feature oriented. In any case, once decided stick to it and be consistent throughout the project. Later on when there are hundreds or even thousands of tests in place you don’t want to spent a long time looking for a specific one.
  • Choose meaningful names for the tests. Do not name them Test1, Test2, …. You usually don’t name your production code methods this way. Your test code should have the same quality standards as your production code (Martin, 2008, p. 121ff). I adopted the naming scheme described by Roy Osherove which looks like this:

    [MethodName_GivenState_ExpectedBehaviour]

    The tests name starts with the method I’m going to call for my System Under Test (SUT) followed by the starting state and then by the expected outcome. As an example, consider a message handler for a print invoice message, a possible test would look like this:

    public void Handle_InvoiceId_PrintCalledWithGivenId()
    {
      // test code goes here
    }
    
  • Follow the Arrange Act Assert (AAA) pattern.It is also called Build-Operate-Check or in Behavior Driven Development (BDD) the Given-When-Then pattern. While using this pattern the initial state and possible parameters are first initialized then the target method is called and at last the result is checked against certain expectations. An implementation of the above test using AAA could look like below. This test assumes that there is a setup method initializing the system under test (SUT) injecting a mock of the printer dependency.
    public void Handle_InvoiceId_PrintCalledWithGivenId()
    {
      // given
      var printInvoiceCmd = new PrintInvoice { Id = "TargetInvoiceId" };
    
      // when
      _sut.Handle(printInvoiceMd);
    
      // then
      _printer.AssertWasCalled(x => x.PrintInvoice(printInvoiceCmd.Id));
    }

    Here I am using Rhino Mocks assertion to test my expectations, but of course there are other mocking frameworks out there.

  • Keep the tests short. My tests are usually not longer than a few lines of code. The biggest ones are maybe half a code page in visually studio. Most of my tests do not have much more lines than the example above. This helps to grasp the meaning of the test very fast. If a test gets too complicated it is a good indication to change the object design. If all tests are short they are much easier to maintain as soon as change request start popping up.
  • Write tests for edge cases. This also means think about the test data. Again consider the example above. There should be other tests in place which define the expected behavior for an empty or null invoice id. Different tests with slightly different ids are probably a waste of time.
  • Every test has to fail at least once. This usually means to write a test before any actual implementation has been done. This is important. If a test never fails it does not bring any meaningful addition to the code.
  • Provide additional info for assertions. Often a failing test does not clearly state what the actual intention was. A little extra text goes a long way to make the test speak for itself. Look at this for example given an invoice  using an external printer service in its Printmethod.
    public void Print_PrintRequestId_RetValSameAsRequest()
    {
      // given
      int requestId = 42;
      _printer.Mock(x => x.SendPrint(null)).IgnoreArguments().Return(requestId);
    
      // when
      int retVal = _sut.Print();
    
      // then
      Assert.That(retVal, Is.EqualTo(requestId), "Return not equal to request id.");
    }

    If the test fails there is now a much more descriptive error message than for example “Expected value 42 but was 0″. The error messages may be even more confusing when asserting GUID values or method calls.

Of course there a lot of other things to consider when writing tests. Have a look at the books in the bibliography of this post for more extensive guidance. However, for me it all starts with the points mentioned here. Follow those recommendations and I guarantee you that your tests will become a real asset for your code base instead of a liability eating away your time.

BIBLIOGRAPHY
Robert C. Martin, 2008, Clean Code: A Handbook of Agile Software Craftsmanship
Roy Osherove, 2009, The Art of Unit Testing
Steven Freeman, Nat Pryce, 2009, Growing Object Oriented Software, Guided by Tests

Comments Off

When messaging communication between different processes is required .Net offers a lot with its Windows Communication Foundation (WCF) library. WCF has a very rich feature set which satisfies a lot more than just the basic requirements.  However if you need platform independence, things are not that simple anymore. Probably the most common way is to export functionality as Web Service which is either SOAP or REST based. .Net has pretty good support for this types of communication. There are appropriate endpoints for WCF as well as support in ASP.NET through asmx files.

However, this communication is restricted by its HTTP foundation. All there is, is the Request-Reply messaging pattern. What about all those other patterns like Publish-Subscribe? This is not possible out of the box with HTTP. To do this the client needs to provide its own Web Service endpoint. This may not be as easy as it sounds. While thanks to WCF  this is usually not a problem in .Net, developers from the Java world do not seem to be very happy with it. A logical alternative to a Web Service is a messaging middle ware like MSMQ (not platform independent), ActiveMQ or RabbitMQ. All of those solutions have the drawback of needing a separate installation and a more or less separate configuration. Another option would be to go for plain sockets communication, but anyone who has done this knows that this is a cumbersome process. Detecting disconnects, doing reconnects, managing multiple clients on the same socket and so forth is not something you want to do if it can be avoided.

This is the case where ØMQ (called ZeroMQ or ZMQ) comes into play. ØMQ is a very thin messaging layer on top of TCP. While offering not the full feature set of a full grown messaging system (like transactions) it is very fast and needs practically no configuration at all. It is a library which can easily be deployed with your own application. The only configuration needed is for the server and client to decide on a free TCP port. Additionally it supports different messaging patterns besides the basic Request-Reply approach. Another advantage is that it runs on practically every platform and has bindings for more than 20 programming languages.

The example I’m showing here is a full duplex asynchronous messaging channel. This is something I need for my current project. A client should be able to send commands at any time to the server, while the server asynchronously notifies clients of certain events occurring in the back end system. For easier router and firewall configuration, all communication is required to run through a single TCP connection. The following picture shows the thread layout of the attached example code:

Client and server threads showing the ZMQ connection points.

The server as well as the client have a separate thread to read user input from the command console. In a real world application these would be the clients UI thread or one or more custom background workers.

ØMQ has the concept of sockets which are used to send and received data. Although a ØMQ socket is much more than its TCP counterpart. For example it actually sends and receives data asynchronously in the background. In principle ØMQ sockets can only be created and used by a single thread. Therefore I like to think of them not as classic sockets but rather as endpoints of a specific thread. The nice thing is that from operation point of view it does not matter whether this endpoint works in the same process or is accessed by a different one. The difference is a simple configuration string used to start the socket. The next snippet shows the sockets from the server communication thread.

using (Socket frontend = _context.Socket(SocketType.XREP),
              backend = _context.Socket(SocketType.XREQ))
{
  frontend.Bind("tcp://*:11700");
  backend.Bind("inproc://backend");

  // other code
}

As can be seen, the difference is all in the string used to bind the socket. The frontend socket, where we like our clients to connect to, opens a specific port while the backend one is defined as inproc. The client communication thread looks very similar. The only difference is, that the frontend socket does not bind to a specific port. Instead it connects to the one supplied by the server.

Once the communication setup is complete the thread is ordered to wait for data messages from either socket by using the Context.Poller method.

// start listening for message from client as well as internal notification thread
var sockets = new List<Socket> { frontend, backend };
while (!_stopProgram)
{
  Context.Poller(sockets, 100000);
}

In my example I continuously let the thread wake up every 100ms to see whether someone has issued a stop program order. If defined as a system background thread this would not be necessary. Once a message arrives at one of the two sockets the registered event handler is called.

Another important thing to note is that a lot of messages in the frontend buffer do not block processing messaging received on the backend socket. During my tests I had tens of thousands of messaging in my frontend queue waiting to be handled. ØMQ took messages from my backend socket as soon as they came in and forwarded them to the client right away. This is an important feature where some kind of flow control is required. This may be the case if the server needs to tell a client to throttle its messages or inform it that some of its messages may be dropped in the future due to its high load.

All in all I’m very impressed with ØMQ. It is very easy to get started with, but on the other hand offers a lot of features and possibilities for every sort of communication and advanced messaging patterns. Just have a look at the extensive ØMQ guide. ØMQ is available for a lot of platforms and languages which makes it even more useful. In fact knowing this library I don’t see any reason why to go back to plain sockets ever again.

Comments Off

A common scenario for my AsyncExecutionLib is to manipulate data in a database while handling a message. There are several ways to achieve this. One possibility would be to open and close a NHibernate session to the database in each message handler.

public class CreateInvoideHandler : IMessageHandler<CreateInvoice>
{
  // [...] ctor storing injection nhibernate session factory [...]

  // Handle() called by asnyc lib
  public void Handle(CreateInvoice message)
  {
    using(ISession session = _sessionFactory.OpenSession())
    {
      // perform database operations
    }
  }
}

This is probably not the best solution. This leaves a lot of common code spread through our program. Additionally it hides important logic from our view as each handler is busy in creating and closing a database session. But probably the most important reason is, that it prevents us to use a single database transaction across multiple message handlers. This is very unfortunate. One of the big advantages in using the lib is that it allows multiple handlers for the same message.

Consider this scenario: you want to create an activity log in your database for every message inherited from a user activity message. Some user actions trigger something in the database themselves others don’t. While using the async lib you would solve this by creating individual handlers for specific messages and a single handler for the base message class. Both handlers will be executed for such a message. However if the execution fails both handlers would have their own database session and their own transaction. If the execution of the second handler fails the transaction of the first would already have been completed and can not be rolled back. This may lead to inconsistencies in the database.

A much better solution would be to have a single transaction across all message handlers for a single message. Ideally it would also reduce the code to create and dispose the session in the handlers themselves. This is where message modules come into play.

Continue reading…

Comments Off

In this post I will explain how to position elements with X, Y values on a canvas using the ItemsControl. It sounds simple, but if you are not aware of the content model you will be surprised.

To place three circles on the Canvas you can use this XAML example (a):

<Canvas>
   <Ellipse Canvas.Left="0" Canvas.Top="0" />
   <Ellipse Canvas.Left="50" Canvas.Top="50" />
   <Ellipse Canvas.Left="100" Canvas.Top="150" />
</Canvas>

Lets try to make it with a ItemsControl that binds to an ObservableCollection<PlaceMarker> PlaceMakers. The PlaceMarker object just has properties for X an Y. The collection is set in the code behind file.

<ItemsControl ItemsSource="{Binding PositionMarkers}">
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <Ellipse Width="10" Height="10" Fill="#BF4C00"
            Canvas.Left="{Binding Path=X}"
            Canvas.Top="{Binding Path=Y}" />
      </DataTemplate>
   </ItemsControl.ItemTemplate>
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <Canvas />
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
</ItemsControl>

The above XAML example (b) shows the ItemsControl using a Canvas as the ItemsPanelTemplate and again the Ellipse with Left and Top for positioning. Nice, but (b) will not work and display this:

Continue reading…

Search

Featured + Free

A easy and fast tool to create sequence diagrams.
This library simplifies the process of executing code on a different thread.

Categories

  • C#
  • Code Quality
  • Database
  • Graphic
  • JavaScript
  • Software Design
  • Tools
  • WP7
  • WPF