Being Cellfish

Stuff I wished I've found in some blog (and sometimes did)

June, 2011

Change of Address
This blog has moved to blog.cellfish.se.
Posts
  • Being Cellfish

    CCR tips and tricks - prologue

    • 0 Comments

    Today I've been little over a year on the Robotics team. I've learned a lot of new things and I had a plan for an advent calendar in 2010 focusing on some tips and tricks for CCR that I've learned as a new member on the Microsoft robotics team. Since I didn't have 24 good things back then I did not do an advent calendar. Today I have a little more material and could probably stretch it to 24 parts but then why wait since I've already broken my tradition of advent calendars... Instead I'll give you the material spread out over the next few months.

    But even before we start looking at some good CCR examples there are a few non-code things I've learned while working with CCR:

    • Being familiar with Erlang and Prolog seems to aid in learning to write programs using CCR.
    • There is no guaranteed ordering of handlers. While receivers on the same port are typically used in the order they were registered you should not rely on this fact in your code. Some receivers deviate from this behaviour.
    • If there is a listener waiting for a message on a port, the message will never be stored in the port. Instead the handler is immediately scheduled for execution without the message ever be stored in the port.
    • The PortSet type is just a convenient collection for a number or ports. There is no ordering of handlers or anything special with a PortSet. It's only a useful way of passing more than one port around.

    More on why these things matter in future posts that also include code.

  • Being Cellfish

    CCR tips and tricks - part 1

    • 1 Comments

    Since I practice TDD it's important to have a good way to test my CCR based code. The first problem to solve then is to call CCR code which is asynchronous in nature from a unit test that is very synchronous in its nature. The way I've ended up is to use a PortUtility class that have synchronous versions of two very common CCR methods; Choice and Receive. Since my unit tests also should execute very fast I have a short default timeout so that I know that my tests don't hang around for too long. Attached is a file implementing the PortUtility class that will be used in future CCR tips and tricks.

    UPDATE: If you like this, you probably love part 25.

  • Being Cellfish

    CCR tips and tricks - part 3

    • 0 Comments

    Causalities are very powerful in CCR. It's essentially an unhandled exception handler that travels with your messages as you post them. That is; once a causality is added it will travel with your message if posted to a port and even be applied to any spawned tasks. A very typical way to use causalities is to add them as you enter a major service/component. If you add multiple causalities the last one added will be called first and then removed from the causality stack. Here is an example on how to setup causalities.

     1:     [TestClass]
     2:     public class Given_a_causality_when_unhandled_exception_is_thrown
     3:     {
     4:         private DispatcherQueue dispatcherQueue = new DispatcherQueue();
     5:         private Exception causalityException = null;
     6:         private string exceptionMessage = "My unhandled exception";
     7:  
     8:         [TestInitialize]
     9:         public void Setup()
     10:         {
     11:             var mre = new ManualResetEvent(false);
     12:             Port<Exception> exceptionPort = new Port<Exception>();
     13:             Causality causality = new Causality(
     14:                 string.Format("CausalityForTests: {0}", Guid.NewGuid()), 
     15:                 exceptionPort);
     16:             Arbiter.Activate(dispatcherQueue, exceptionPort.Receive(
     17:                 (e) =>
     18:                 {
     19:                     causalityException = e;
     20:                     mre.Set();
     21:                 }));
     22:             Dispatcher.AddCausality(causality);
     23:  
     24:             Arbiter.Activate(dispatcherQueue, 
     25:                 Arbiter.FromHandler(() => Arbiter.Activate(dispatcherQueue, 
     26:                     Arbiter.FromHandler(() =>
     27:                         {
     28:                             throw new Exception(exceptionMessage);
     29:                         }))));
     30:             Assert.IsTrue(
     31:                 mre.WaitOne(TimeSpan.FromSeconds(5)), 
     32:                 "Causality did not get exception");
     33:         }
     34:  
     35:         [TestMethod]
     36:         public void Then_exception_is_handled_by_causality()
     37:         {
     38:             Assert.IsNotNull(causalityException);
     39:             Assert.AreEqual(exceptionMessage, causalityException.Message);
     40:         }
     41:     }
    

    Four simple steps. Create an exception port, register a receiver on it, create a causality with that port and add the causality. Note that if the handling port is persistent you may get multiple exceptions if your task spawns multiple tasks where more than one throw an unhandled exception. So remember, causalities are to be used to handle unhandled exceptions, not to handle errors.

  • Being Cellfish

    Green card medical exam

    In order to get a green card (permanent residency in the US) you need to undergo a medical exam. And only a few certified physicians can do this. Part of the exam they must verify your gender which apparently can be quite uncomfortable if you're a woman and your physician has a bad day. So here's a tip; find a clinic that have somebody who can do the green card exams. Use that clinic as your regular doctor and make sure to do an annual health check a few months prior to your green card exam. This way they may use some information from that annual exam as part of your green card exam so you save both time and discomfort. i don't know if this is how it's supposed to work everywhere but it worked for us.

  • Being Cellfish

    CCR tips and tricks - part 2

    • 0 Comments

    Apart from the utility mentioned in part one I use another utility to make sure my unit tests report failures in a good way. When using CCR in a MSTest process unhandled exceptions may be silently swallowed by the CCR framework unless you have a handler for that case. Before I started to use causalities to deal with unhandled exceptions I would only see a timeout failure but with today's utility you see a failure with the actual message instead (if used right). This implementation is intended to be used in a using statement since it raises any encountered errors when disposed. In future tips and tricks you'll see how it's used.

     1:     class CausalityForTests : IDisposable
     2:     {
     3:         private Exception exception = null;
     4:  
     5:         public CausalityForTests(DispatcherQueue dispatcherQueue)
     6:         {
     7:             Port<Exception> exceptionPort = new Port<Exception>();
     8:             Causality causality = new Causality(
     9:                 string.Format("CausalityForTests: {0}", Guid.NewGuid()), 
     10:                 exceptionPort);
     11:             Arbiter.Activate(
     12:                 dispatcherQueue, 
     13:                 exceptionPort.Receive(e => this.exception = e));
     14:             Dispatcher.AddCausality(causality);
     15:         }
     16:  
     17:         public void Dispose()
     18:         {
     19:             if (this.exception != null)
     20:             {
     21:                 throw this.exception;
     22:             }
     23:         }
     24:     }
    
  • Being Cellfish

    CCR tips and tricks - part 5

    • 0 Comments

    There is one thing in CCR I think should not be there in its current form and that is the SuccessFailurePort. The reason I don't like its current implementation is that it can easily become a generic container of results where really other types should be used. Before I give an example you need to know what setup I used for all tests in today's post.

     1:     [TestClass]
     2:     public class SuccessFailurePortUsage
     3:     {
     4:         private DispatcherQueue dispatcherQueue = new DispatcherQueue();
     5:         private PortUtility portUtility;
     6:  
     7:         [TestInitialize]
     8:         public void Setup()
     9:         {
     10:             portUtility = new PortUtility(dispatcherQueue);
     11:         }
    

    Now an example on what it looks like when the SuccessFailurePort is misused.

     1:         private SuccessFailurePort WhenItShouldNotBeUsed(string numberOfThingsOk)
     2:         {
     3:             var resultPort = new SuccessFailurePort();
     4:             int thingsOk = 0;
     5:             if (int.TryParse(numberOfThingsOk, out thingsOk))
     6:             {
     7:                 resultPort.Post(new SuccessResult(thingsOk));
     8:             }
     9:             else
     10:             {
     11:                 resultPort.Post(
     12:                     new Exception("Somehting is not OK: " + numberOfThingsOk));
     13:             }
     14:             return resultPort;
     15:         }
     16:  
     17:         [TestMethod]
     18:         public void When_it_should_not_be_used()
     19:         {
     20:             using (var testCausality = new CausalityForTests(dispatcherQueue))
     21:             {
     22:                 portUtility.Choice(
     23:                     WhenItShouldNotBeUsed("42"), 
     24:                     s => Assert.AreEqual(42, s.Status), 
     25:                     e => Assert.Fail("Unexpected failure: {0}", e));
     26:                 portUtility.Choice(
     27:                     WhenItShouldNotBeUsed("Not a number"), 
     28:                     s => Assert.Fail("Unexpected success"), 
     29:                     CcrServiceBase.EmptyHandler);
     30:             }
     31:         }
    

    As you can see the status field of the SuccessResult is used as a transport for a result. The correct PortSet to used in this case is really PortSet<int, Exception>. There is also the opposite situation where a SuccessFailurePort is not used but it really should be used. Typically it is a PortSet<bool, Exception> port where false (or true) is never actually posted like in this example.

     1:         private PortSet<bool, Exception> WhenItShouldBeUsed(bool allOk)
     2:         {
     3:             var resultPort = new PortSet<bool, Exception>();
     4:             if (allOk)
     5:             {
     6:                 resultPort.Post(true);
     7:             }
     8:             else
     9:             {
     10:                 resultPort.Post(new Exception("Somehting is not OK"));
     11:             }
     12:             return resultPort;
     13:         }
     14:  
     15:         [TestMethod]
     16:         public void When_it_should_be_used()
     17:         {
     18:             using (var testCausality = new CausalityForTests(dispatcherQueue))
     19:             {
     20:                 portUtility.Choice(
     21:                     WhenItShouldBeUsed(true), 
     22:                     CcrServiceBase.EmptyHandler, 
     23:                     e => Assert.Fail("Unexpected failure: {0}", e));
     24:                 portUtility.Choice(
     25:                     WhenItShouldBeUsed(false), 
     26:                     s => Assert.Fail("Unexpected success"), 
     27:                     CcrServiceBase.EmptyHandler);
     28:             }
     29:         }
    

    In my opinion the only time you should use a SuccessFailurePort is when you use the shared instance like this.

     1:         private SuccessFailurePort TheRightWay(bool allOk)
     2:         {
     3:             var resultPort = new SuccessFailurePort();
     4:             if (allOk)
     5:             {
     6:                 resultPort.Post(SuccessResult.Instance);
     7:             }
     8:             else
     9:             {
     10:                 resultPort.Post(new Exception("Somehting is not OK"));
     11:             }
     12:             return resultPort;
     13:         }
     14:  
     15:         [TestMethod]
     16:         public void The_right_way()
     17:         {
     18:             using (var testCausality = new CausalityForTests(dispatcherQueue))
     19:             {
     20:                 portUtility.Choice(
     21:                     TheRightWay(true), 
     22:                     CcrServiceBase.EmptyHandler, 
     23:                     e => Assert.Fail("Unexpected failure: {0}", e));
     24:                 portUtility.Choice(
     25:                     TheRightWay(false), 
     26:                     s => Assert.Fail("Unexpected success"), 
     27:                     CcrServiceBase.EmptyHandler);
     28:             }
     29:         }
    

    This is why I think the SuccessFailurePort is implemented in the wrong way. Since only the shared instance is used the SuccessFailurePort could have been implemented using the EmptyValue type like this.

     1:         private PortSet<EmptyValue, Exception> TheRightWayAlternative(bool allOk)
     2:         {
     3:             var resultPort = new PortSet<EmptyValue, Exception>();
     4:             if (allOk)
     5:             {
     6:                 resultPort.Post(EmptyValue.SharedInstance);
     7:             }
     8:             else
     9:             {
     10:                 resultPort.Post(new Exception("Somehting is not OK"));
     11:             }
     12:             return resultPort;
     13:         }
     14:  
     15:         [TestMethod]
     16:         public void The_right_way_alternative()
     17:         {
     18:             using (var testCausality = new CausalityForTests(dispatcherQueue))
     19:             {
     20:                 portUtility.Choice(
     21:                     TheRightWayAlternative(true), 
     22:                     CcrServiceBase.EmptyHandler, 
     23:                     e => Assert.Fail("Unexpected failure: {0}", e));
     24:                 portUtility.Choice(
     25:                     TheRightWayAlternative(false), 
     26:                     s => Assert.Fail("Unexpected success"), 
     27:                     CcrServiceBase.EmptyHandler);
     28:             }
     29:         }
    

    Notice the code on line 27 in the last example? That's another good practice in CCR code. Whenever you have a handler that is empty you should use CcrServiceBase.EmptyHandler.

  • Being Cellfish

    What is a code poet

    • 0 Comments

    Somebody called me a code poet the other day. That made me think if that is a good thing or not. I think the intention was to say that I like spending some extra time on making sure that the code has a good flow and reads like a short story. But there is also an awful lot of poetry out there that is hard to understand. People writing that are still poets but their poems are not necessarily enjoyable by the big masses. And I want my code to be accessible and enjoyable to the big masses... I can get satisfaction out of writing some nifty, smart snippet that elegantly uses the features of the environment to achieve a lot. But that thing has to be enclosed in something easily understandable so that it's easy understandable. So a poem is not necessarily the best analogy. I want to write short stories that everybody can enjoy and sometimes I'll throw in a twist but I'll make sure I'll explain it so that you also can enjoy the brilliance of the twist... So what is a good word on somebody who want to write code as small stories? Code author? Wait isn't that what we often say about code? Who was the author of this? I wish more people saw themselves as authors rather than code slaves...

     

    Create your free online surveys with SurveyMonkey, the world's leading questionnaire tool.
  • Being Cellfish

    Why I started to blog

    • 0 Comments

    The reason I started to blog a long time ago was that I sometimes solved a problem and had to spend a lot of time searching the web and experimenting. Since I had to do it I was hoping somebody else would not if I wrote down what I did. The comments on how helpful a specific blog post was keeps me going. But then once in a while something extraordinary happens. The first time was four or five years ago when a Computer Sweden (a Swedish "newspaper" for people in the computer industry) quoted me on BDD. The second time was when one of the most popular posts I have was mentioned in the MSDN magazine. One thing that surprised me both times however was that nobody sent me an email telling me about this. Don't get me wrong here. I do love that somebody finds my blog useful once in a while and I do not want you to ask permission before you use any of this in any context. But a note of appreciation once in a while keeps morale up... Especially if you find it useful enough to use in a "real" article...

  • Being Cellfish

    CCR tips and tricks - part 4

    • 0 Comments

    Sometimes when working with causalities you want to clear all causalities. One common case where you want to do this is when you use a throttling port (more on that in a later post). Here is a simple test showing how to clear causalities (line 30).

     1: [TestClass]
     2: public class 
     3: Given_a_causality_when_unhandled_exception_is_thrown_after_clearing_causalities
     4: {
     5:     private DispatcherQueue dispatcherQueue = new DispatcherQueue();
     6:     private Exception causalityException = null;
     7:     private string exceptionMessage = "My unhandled exception";
     8:  
     9:     [TestInitialize]
     10:     public void Setup()
     11:     {
     12:         var mre = new ManualResetEvent(false);
     13:         Port<Exception> exceptionPort = new Port<Exception>();
     14:         Causality causality = new Causality(
     15:             string.Format("CausalityForTests: {0}", Guid.NewGuid()), 
     16:             exceptionPort);
     17:         Arbiter.Activate(dispatcherQueue, exceptionPort.Receive(
     18:             (e) =>
     19:             {
     20:                 causalityException = e;
     21:                 mre.Set();
     22:             }));
     23:         Dispatcher.AddCausality(causality);
     24:  
     25:         Arbiter.Activate(
     26:             dispatcherQueue,
     27:             Arbiter.FromHandler(
     28:                 () =>
     29:                     {
     30:                         Dispatcher.ClearCausalities();
     31:                         throw new Exception(exceptionMessage);
     32:                     }));
     33:         Assert.IsFalse(
     34:             mre.WaitOne(TimeSpan.FromSeconds(3)), 
     35:             "Causality should not get exception");
     36:     }
     37:  
     38:     [TestMethod]
     39:     public void Then_exception_is_handled_by_causality()
     40:     {
     41:         Assert.IsNull(causalityException);
     42:     }
     43: }
    
  • Being Cellfish

    Drunken estimation

    • 0 Comments

    As I've pointed out before, estimation is usually a waste of time in my opinion. The time can be spent on other things that are more productive and lead to better understanding of velocity. Well, I'm almost prepared to start being an advocate for estimation again... Drunken estimation to be precise. I think it's a brilliant approach to estimation. The only problem is that I don't think it will work in Sweden (and certainly not in Finland). A six pack is just not enough for one evening and will only get you happy, not to drunk to work. But it's an easy problem to fix; you just need to add a shot with every beer and I think the technique can be applied as described. Now I just need to come up with a plan to convince my team to adopt this new idea...

Page 1 of 1 (10 items)