Being Cellfish

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

Change of Address
This blog has moved to
  • Being Cellfish

    Adopt a chaos monkey


    Remember the Netflix Chaos Monkey? Last week they released the source code for it. maybe we'll see a port to .Net and Azure on codeplex soon?

  • Being Cellfish

    Adding a timout to a task


    Remember how I added a timeout to an existing Choice in CCR? Well with the new Task based world in .Net 4.5 you will probably want to do the same thing with a task returned by somebody else. Good for me this time is that somebody else already figured out how to do it. I especially like the approach under A Different Approach, especially if modify to deal better with some edge cases.

  • Being Cellfish

    Evolution of a hand rolled fake - part 2


    In a recent discussion at work I realized that the main reason I started with the constructor based fakes descried here was not to clutter the object with properties called SomethingHandler. By having my fake implement the interface explicitly I could create a fake like this:

     1: public class FakeTheInterface : ITheInterface
     2: {
     3:     public Action<int> DoSomething { get; set; }
     5:     public Func<int, int, int> ComputeSomething { get; set; } 
     7:     void ITheInterface.DoSomething(int x)
     8:     {
     9:         Assert.IsNotNull(this.DoSomething, "Unexpected call to DoSomething");
     10:         this.DoSomething(x);
     11:     }
     13:     int ITheInterface.ComputeSomething(int a, int b)
     14:     {
     15:         Assert.IsNotNull(this.ComputeSomething, "Unexpected call to ComputeSomething");
     16:         return this.ComputeSomething(a, b);
     17:     }
     18: }

    And this way I can write a test like this:

     19: [TestMethod]
     20: public void UsingFake()
     21: {
     22:     var fakeThing = new FakeTheInterface
     23:                     {
     24:                         ComputeSomething = (a, b) => 42
     25:                     };
     26:     ITheInterface thing = fakeThing;
     27:     Assert.AreEqual(42, thing.ComputeSomething(0, 0));
     28: }

    Please disregard the "cast" to the interface in this test. It's because it's a stupid test. Any real test would take this fake object as a dependency somewhere so it would be used in the context of the interface. But the real beauty is that when working with the fake and setting it up you do not get intelli-sense cluttered with the methods and properties of the interface itself, just the things you need to setup the fake.

  • Being Cellfish

    Task-based Asynchronous Pattern - WhenRandom


    I couldn't resist to create a method to deal with a scenario even less common than WhenSome. The crazy scenario here is that you have N tasks of type Task<T> and you want to return when a random task completes. The easiest way to do this is to just pick a random task and wait for it like this:

     1: public static Task<T> WhenRandom<T>(params Task<T>[] tasks)
     2: {
     3:     var random = new Random();
     4:     return (from task in tasks
     5:             orderby random.Next()
     6:             select task).FirstOrDefault();
     7: }

    However what if you want to be able to cancel the WhenRandom call you need to be a little more creative I guess:

     8: public static async Task<T> WhenRandom<T>(CancellationToken cancellationToken,
     9:                                           params Task<T>[] tasks)
     10: {
     11:     var random = new Random().Next(0, tasks.Length);
     12:     var remainingTasks = new List<Task<T>>(tasks);
     13:     while (remainingTasks.Count > 0)
     14:     {
     15:         await Task.WhenAny(remainingTasks);
     16:         for (int i = 0; i < remainingTasks.Count; i++)
     17:         {
     18:             if (remainingTasks[i].IsCompleted)
     19:             {
     20:                 if (random-- == 0)
     21:                 {
     22:                     return await remainingTasks[i];
     23:                 }
     25:                 remainingTasks.RemoveAt(i--);
     26:             }
     27:         }
     29:         cancellationToken.ThrowIfCancellationRequested();
     30:     }
     32:     return default(T);
     33: }

    In this last version I don't pick a random task and wait for it but I rather pick a random completed task, i.e. given the same random number the order in which tasks complete will affect which task is returned.

  • Being Cellfish

    Type casting with extension methods


    Once in a while I need to convert one object from one type to another because they represent slightly different views of the same data but they do not share a common parent. An example would be an object used internally representing some complex state for something (let us call it FooComplex) and someting simple you just want to return in an API (let us call it FooSimple). So how do I convert between these? There are several options:

    fooSimple.ToComplex() and fooComplex.ToSimple()
    My first option is to att a member function to each of the classes that converts to the other. The first obvious downside with this is that these classes now both need to know about eachother which is probably really bad since they might be in different assemblies. It also means that when I need to add a property in both classes I need to also change the converters in two different files.

    Explicit casts
    You can also implement explicit cast operators which is really just a variant of the option above. Some may argue that it is better since it uses a language feature to illustrate that you convert between two classes. While that is true I think it will be confusing since cast operators are typically used to change the type when the two types actually have an inheritance relationship. So casting between two logically related but in practice seperate types might actually be more confusing than using ToXxx methods.

    Partial classes
    To get around the downside of having ToComplex and ToSimple in two different code files you can always make FooSimple and FooComplex partial classes. But this might not always be possible.

    fooSimple.ToComplex() and FooSimple.FromComplex(FooComplex)
    To get around the problem of two way dependencies and needing to implement the conversion in two different classes (and files) you can just replace one direction with a static FromXxx method. This works pretty well but now you have two different patterns for converting depedning on direction (To vs From).

    Extension methods to the rescue!
    However if you make your ToComplex and ToSimple methods be extension methods I think you get the best of all worlds; Both directions in the same file, same pattern and not using explicit cast operators. I also like to call them AsXxx rather than ToXxx to indicate there is some transformation happening.

  • Being Cellfish

    2012 statistics


    Time for my 2012 according to this blog's statistics. As last year we'll start of with the five most read posts:

    1. Native code coverage reports
    2. Viking laws
    3. Getting logged on windows user on apache
    4. Ten commandments of egoless programming
    5. Upsert in SQL server

    For the fourth year in a row native code coverage reports is the most read article I have on my blog. I was sad to see Object calisthenics not make top five. Another interesting thing though is that Ten commandments of egoless programming was linked by some popular sites which made it into the top. It in its turn links to the Viking laws which turned out to be much more popular than the commandments post. Exactly the way I feel. The top ten search terms to land on this blog in 2011 were (2010 ranking within parenthesis):

    1. sql server upsert (2)
    2. upsert sql server (3)
    3. xunit code coverage (8)
    4. upsert sql server 2008 (4)
    5. php get windows username (new)
    6. memcmp performance (7)
    7. kanban explained (1)
    8. visual studio achievements (new)
    9. upsert in sql server 2008 (new)
    10. tpl vs 2010 (new)
  • Being Cellfish

    XCOM interactive trailer


    I loved the original XCOM game (and terror from the deep was OK). Will definitely play this new game when it releases next week. They did something interesting for their recent trailer; an interactive trailer where you actually get to change how the flow goes.

  • Being Cellfish

    Task-based Asynchronous Pattern - WithCancellation again!


    Last week Stephen Toub covered WithCancellation in a more thorough way than I did. You should read his article too!

  • Being Cellfish

    The tale of an UnobservedTaskException


    Last week I helped a colleague who was experiencing UnobservedTaskExceptions I his code. The problem was essentially that the code started several tasks and then in a loop checked each one if it was faulted or not. If a task was faulted the method threw an exception. This meant that if two tasks faulted in the collection of tasks then the second one was never observed causing an UnobservedTaskException that brought down the process. While this sounds simple it turned out to be a hard nut to crack for a number of reasons.

    First of all you need to know some things about the UnobservedTaskExceptions; while they by default crash your process in .Net 4.0, they don't in .Net 4.5. The fun thing is that you get the 4.5 behavior on your 4.0 assemblies by just having 4.5 installed. There is a way to configure your application to use the old 4.0 behavior and you can read about that and why the default behavior changed here. Forgetting this can frustrate you if your build environment does not have 4.5 but you have it on your own machine.

    Second you have to remember that even if you use async/await you can still end up writing code that have the same "problem". The "problem" is that you only bubble up the first error you see and not all errors. For many reasons I think this is what you actually want (WhenAllOrError anybody?) but if you really want to get all exceptions you can just use Task.WhenAll and you'll be good.

  • Being Cellfish

    Task-based Asynchronous Pattern - WithCancellation


    if you're working with a Task based API that does not follow the TAP rules and hence does not expose an option to cancel you can always add your own this way:

     1: public static Task<T> WithCancellation<T>(
     2:     this Task<T> task, 
     3:     CancellationToken cancellationToken)
     4: {
     5:     var taskCompletionSource = new TaskCompletionSource<T>();
     6:     var cancellationRegistration = cancellationToken.Register(
     7:         () => taskCompletionSource.TrySetCanceled());
     8:     task.ContinueWith(
     9:         t =>
     10:             {
     11:                 cancellationRegistration.Dispose();
     12:                 if (t.IsCanceled)
     13:                 {
     14:                     taskCompletionSource.TrySetCanceled();
     15:                 }
     16:                 else if (t.IsFaulted)
     17:                 {
     18:                     taskCompletionSource.TrySetException(
     19:                         t.Exception.InnerException);
     20:                 }
     21:                 else
     22:                 {
     23:                     taskCompletionSource.TrySetResult(t.Result);
     24:                 }
     25:             });
     26:     return taskCompletionSource.Task;
     27: }

    This naturally will not actually stop the task you wrap this way but at least it returns control to the code waiting for completion faster.

Page 43 of 49 (481 items) «4142434445»