C# – Consume non-async API’s as async


Now that we have the new nifty async support built into C# you might wonder how you can access your old API’s as if they were async.

Now before I show any code, I have to warn that the code posted here will only wrap your existing sync methods as a Task of T.
You will be able to consume them as if they were async, and in some cases this might be enough, and in other cases, such as IO scenarios, you really should rewrite the methods to use the proper async versions of the IO methods.

The wrapper code provided here may still be a decent start for you to do this, since you can start migrating code to use async calls, while you rewrite the methods that need rewriting later.


    class Program
    {
        static void Main(string[] args)
        {
            Consumer();
            Console.WriteLine("----");
            Console.ReadLine();
        }


        private async static void Consumer()
        {
            //consume the sync method as if it was async
            var b = await Wrap(() => NonAsyncMethod(1, ""));
            Console.WriteLine("got result back {0}",b);
        }

        //this might be one of your old or 3rd party methods
        private static int NonAsyncMethod(int a, string b)
        {
            System.Threading.Thread.Sleep(2000); //emulate some slow code
            return 5;
        }

        private static Task<T> Wrap<T>(Func<T> selector)
        {
            return Task.Factory.StartNew(selector);
        }
    }

swe: Wombit expanderar i Stockholm


This is a notification in Swedish.
Jag har precis bytt jobb till Wombit Systemutveckling AB.

Vi expanderar i Stockholm. Nu söker vi dig med djupare kompetens inom webbutveckling och då framför allt .Net, EPiServer eller Sharepoint.

Våra medarbetare erbjuds kreativa och utmanande uppdrag där de får chansen att utveckla sina kunskaper hos några av Sveriges största företag inom flera olika sektorer och branscher.

Vill du veta mer, kontakta roger.alsing@wombit.se eller fredrik.danemark@wombit.se

Functional DDD in F#


After watching Greg Youngs presentation on Functional DDD (http://skillsmatter.com/podcast/design-architecture/ddd-functional-programming) I decided to give it a try using F#

I have to say I was sort of pleasantly surprised how well the entire concept works with a functional language.

This is only a spike on my part so don’t expect too much, but the code shows how Gregs ideas can be implemented using F#

//state for order line items
type LineItem =
    {
        Quantity : float;
        ProductId : int;
    }

//events that can be consumed by the order aggregate root
type OrderEvents =
    | Created of System.DateTime
    | RemovedItemId of int
    | ItemAdded of LineItem

type Order = 
    { //the order state 
        Id : int;
        CreatedDate : System.DateTime;
        Items : list<LineItem>;
    }

    //helper func to create new instances
    static member Create() = 
        { 
            Id = 1; 
            CreatedDate = System.DateTime.Now; 
            Items = []; 
        }

    //event handler, this consumes an event and uses it to construct a new version of the "this" argument
    static member Apply (this,event) = 
        match event with
        | Created(createdDate)      -> 
            {this with CreatedDate = createdDate; }
        | ItemAdded(item)           -> 
            {this with Items = item :: this.Items; }
        | RemovedItemId(productId)  -> 
            {this with Items = this.Items |> List.filter(fun i -> i.ProductId <> productId); }

    
    static member AddItem (productId,quantity) this =
        if quantity <= 0.0 then 
            failwith  "quantity must be a positive number"

        this,ItemAdded { Quantity = quantity; ProductId = productId; }
    
    static member RemoveProduct (productId) this =
        this,RemovedItemId(productId)

[<EntryPoint>]
let main argv =
    let o = Order.Create() 
            |> Order.AddItem (123,5.0) 
            |> Order.Apply
            |> Order.AddItem (555,3.0)
            |> Order.Apply
            |> Order.AddItem (22,2.2)
            |> Order.Apply 
            |> Order.RemoveProduct(123)
            |> Order.Apply

    //do stuff with the order
   

The idea here is that instead of using “Do” functions like Greg does, I use an “Apply” function wich consumes an event which is an F# discriminated union type.
The actual entity state is implemented using F# records, the apply function creates new versions of such record based on previous state and the consumed event.

Programming languages and successful projects


This is just a random reflection on the current status in software dev.
The last few years there have been quite a bit of focus on languages rather than technologies, languages like Clojure, Groovy, Scala are making quite a bit of noise now.
Just recently I was watching a clip on InfoQ about Clojure based startups and success stories regarding Clojure.

Is it realy the languages that brings that success?
Isn’t it simply that the really smart guys can now find the tools that suits them the best which in turn helps them to succeed?
That is, Average Joe will most likely not chose Clojure for his projects since it’s not mainstream enough for him, so if or when he fails this will not count as a failed Clojure project.

What I’m saying is that it’s not the languages but rather people that makes projects successful.
Smart people chose the right tools, dumb people does not. Smart people have a higher success rate than dumb people.

If we remove all other languages and make everyone code Clojure, will we have more successful projects then?
I’m pretty sure we won’t.