Category Archives: Lambdas / Anonomous delegates

Barbarian IOC

At work I have used a variety of IOC Containers including

And I have used others such as Unity/StructureMap/AutoFac. They are all very  good and very rich.

For those of you who don’t know what IOC stands for, it stands for Inversion  Of Control. Which is described as follows:

In software engineering, inversion of control (IoC) is a programming  technique, expressed here in terms of object-oriented programming, in which  object coupling is bound at run time by an assembler object and is typically not  known at compile time using static analysis.

In traditional programming, the flow of the business logic is determined  by objects that are statically assigned to one another. With inversion of  control, the flow depends on the object graph that is instantiated by the  assembler and is made possible by object interactions being defined through  abstractions. The binding process is achieved through dependency injection,  although some argue that the use of a service locator also provides inversion of  control.

In order for the assembler to bind objects to one another, the objects  must possess compatible abstractions. For example, class A may delegate behavior  to interface I which is implemented by class B; the assembler instantiates A and  B then injects B to A.

In practice, inversion of control is a style of software construction  where reusable code controls the execution of problem-specific code. It carries  the strong connotation that the reusable code and the problem-specific code are  developed independently, which often results in a single integrated application.  Inversion of control as a design guideline serves the following purposes:

  • There is a decoupling of the execution of a certain task from  implementation.
  • Every module can focus on what it is designed for.
  • Modules make no assumptions about what other systems do but rely on  their contracts.
  • Replacing modules has no side effect on other modules.
  • Inversion of control is sometimes facetiously referred to as the  "Hollywood Principle: Don’t call us, we’ll call you", because program logic  runs against abstractions such as callbacks.

Wikipedia : up on date 25/02/2013

Thing is I have always wanted to try and make one of these  myself, just to see what is involved. I did not want to go too nuts on this, and  just wanted the following really:

  1. Instance configuration : singleton / transient
  2. Simple registration process, maybe some sort of fluent interface
  3. Use the Expression API to compile into delegates for quick creation of  objects
  4. Constructor / property injection
  5. Provide the ability to accept non IOC held constructor parameters

So those couple of points are ALL I wanted to get working. As I say there are  a whole slew of full fledged IOC containers out there (where I have named a few  above), this articles container is more of a learning exercise, that I thought  I would share, in case anyone else is interested in this sort of thing.

I am calling my container BarbarianIOC as the existing  containers all seems to have these short snappy names, and it’s kind of play on  my name, and if you saw me without a shave I do kinda look a bit like a  barbarian.

 

 

If you want to read more you can grab the rest of the article and the source over at codeproject : http://www.codeproject.com/Articles/552514/BarbarianIOC-A-simple-IOC-Container

Advertisements

Expression Tree Visualizer

Some of you may remember a rather handy ExpressionTree debugger visualizer that allowed the visualization of expressions. Basically it was extremely handy and a great way of getting to know the Expression API a bit better.

Unfortunately this was a VS2008 sample, and it does not seem to come with VS2010.

I had not been missing it as I have not been doing much with Expressions, that is until the other day, and I really started to miss it. So I set about trying to get it to work.

Here are the steps you will need to follow to get it to work

  1. Downloaded VS2008 samples from link above : http://code.msdn.microsoft.com/Visual-Studio-2008-C-d295cdba
  2. Open contained Expression Debugger Visualse project in VS2010
  3. Change the projects to target .NET4.0
  4. Change the references to point to this location for the DebuggerVisualizers.dll : C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.VisualStudio.DebuggerVisualizers.dll
  5. Add a DebuggerVisualizer assembly targeting attribute definition for each and ever subclass (and including) Expression
  6. Built the projects, checked that I can actually visualize an expression tree. All works fine in modified standalone project from samples
  7. Copied the ExpressionTreeVisualizer.dll to the following locations

    …\Documents\Visual Studio 2010\Visualizers …\Program Files\Microsoft Visual Studio 10.0\Common7\Packages\Debugger\Visualizers

Just in case you are curious about what I mean in  by Step 5 above, this is what I had to do

 [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(Expression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(BinaryExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(BlockExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(ConditionalExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(ConstantExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(DebugInfoExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(DefaultExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(DynamicExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(GotoExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(IndexExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(InvocationExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(LabelExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(LambdaExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(ListInitExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(LoopExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(MemberExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(MemberInitExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(MethodCallExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(NewArrayExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(NewExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(ParameterExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(RuntimeVariablesExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(SwitchExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(TryExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(TypeBinaryExpression), Description = "Expression Tree Visualizer")] [assembly: DebuggerVisualizer(typeof(ExpressionTreeVisualizerForVisualStudio2010), typeof(ExpressionTreeVisualizerObjectSource),      Target = typeof(UnaryExpression), Description = "Expression Tree Visualizer")] 

Worked a treat and for those of you that are simply to lazy to do this work, here is zip file containing a valid VS2010 copy of a C# project that will build this Expression Debugger Visualizer for you:

http://dl.dropbox.com/u/2600965/ExpressionTreeVisualizer.zip

Generic Method Calls Using Expression Trees / Method Caching

The other day I wrote a bit of reflection inside an ASP .NET custom ModelBinder class to call a generic method, and my work colleague asked, isn’t that going to be slow.

I was like yeah but not that bad, besides if it proves to be a problem we can always speed it up using method caching and Expression Trees.

He then asked to see an example of that as he had not done too much with Expression Trees, I said sure I would knock one up for him.

The idea is a fairly simply one, we can to call a method, I was using Reflection which takes the Reflection hit every time, so what we need is to build up a Dynamic Delegate which we can store and which we can then call each time which will be lightning quick when compared to using Reflection, as all we are doing is calling a Delegate.

Enter ExpressionTrees.

Suppose this is my method that I want to call

//Will call this method via ExpressionTree
private T GetSomething<T>(string data)
{
    return (T)Activator.CreateInstance(typeof(T));
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

You can see that this method is generic and takes a string as a parameter. So what would an expression tree builder method look like, and what it would it return. Well it would look like this, and would return a Func delegate which we could cache somewhere, and call next time, which as I say would be very fast, as we are not doing any Reflection any more, we basically take the hit one when we 1st create the Func delegate.

//create delegate using Expression Trees
private static Func<Object, P1, T> ReflectGenericFunction<P1, T>(
    Type[] genericParams, Type objType, String methodName)
{
    ParameterExpression param = 
        Expression.Parameter(typeof(Object), "object");
    ParameterExpression param1 = 
        Expression.Parameter(typeof(P1), "paramP1");
    Expression convertedParam = 
        Expression.Convert(param, objType);
    Expression methodCall = 
        Expression.Call(convertedParam, methodName, genericParams, param1);
    LambdaExpression lambda = 
        Expression.Lambda(methodCall, param, param1);
    Expression<Func<Object, P1, T>> dynamicSetterExpression = 
        (Expression<Func<Object, P1, T>>)lambda;
    return dynamicSetterExpression.Compile();
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And here is how we might call this method to get a Func delegate we could cache

If we know the correct generic values for the ReflectGenericFunction we can simply do this:

Type[] genericArgs = new Type[] { typeof(Person) };

//If we know the correct generic types can simply do this
Func<Object, String, Person> func = 
    ReflectGenericFunction<String, Person>(
        genericArgs, typeof(Program), "GetSomething");
var x = func(this,"Same");

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

If we need to dynamically create the types for the ReflectGenericFunction we can simply do this:

Type[] genericArgs = new Type[] { typeof(Person) };

///If we DO NOT know the correct generic types can simply do this
MethodInfo method = this.GetType().GetMethod("ReflectGenericFunction", 
    BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance);
method = method.MakeGenericMethod(new Type[] { 
    typeof(String), typeof(Person) });

Func<Object, String, Person> funcReflected = 
    (Func<Object, String, Person>)method.Invoke(
        this, new Object[] { genericArgs, 
        typeof(Program), "GetSomething" });

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

NOTE : The same thing can obviously be done using Delegate.CreateDelegate(..) but I thought this was interesting and I had to do it for my work collegue so thought I would just show you how.

Here is what you would do using Delegate.CreateDelegate

Declare a delegate type

public delegate object GetSomethingDelegate(string json);
Now create a method that will dynamically create the delegates
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

private GetSomethingDelegate GetSomethingDelegateType(Type modelType, object instance)
{
    MethodInfo method = this.GetType().GetMethod("GetSomething", 
        BindingFlags.NonPublic | BindingFlags.Instance);
    method = method.MakeGenericMethod(new Type[] { modelType });
    return (GetSomethingDelegate)Delegate.CreateDelegate(
        typeof(GetSomethingDelegate), instance, method);
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

And finally call the delegate creation method

GetSomethingDelegate funcDel = GetSomethingDelegateType(typeof(Person), this);
var x3 = funcReflected(this, "Using Delegate.CreateDelegate");
Console.WriteLine(x3.Id);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

As always here is a small demo project :

http://dl.dropbox.com/u/2600965/Blogposts/2011/08/DynamicMethodCachingUsingExpressionTrees.zip

List Exporter To CSV

Today I wrote a small utility class that allows any List<T> to be exported to a CSV string or a CSV file using a nice Fluent interface.

This is what it allows:

  1. Take any List<T>, where T could be any class
  2. Let the using code specify what columns should be exported
  3. Use a Fluent API (as they are all the rage these days
  4. Allow auto header named to be obtained using using Expression trees
  5. Allow the the user to supply custom header names
  6. Allow the user to also supply custom format strings for the data being exported
  7. Allow the data to be exported to a CSV file OR allow the data to be exported to a CSV string

 

And here is an example of how you might use it

//Get it as a String result, using automatic Headers, but formatted Columns, 
//and standard "," seperator
String resultsWithDefaultHeadersAndFormattedColumns = people.GetExporter()
    .AddExportableColumn((x) => x.Age, 
                  customFormatString:"The Person Age Is {0}")
    .AddExportableColumn((x) => x.Name, 
                  customFormatString: "The Persons Name {0}")
    .AsCSVString();

If you want to know more you can read the full article over at :

http://www.codeproject.com/KB/miscctrl/CSVListExporter.aspx

ChainedPropertyObserver

The other day I was messing around with an idea I had where I had a object graph of related objects which looked something like this (where each object was an INotifyPropertyChanged object).

dbSchema

And I thought wouldn’t it be nice if I could observer changed from any of those object conveniently, and without the need to hook/unhook when new object were introduced into the object graph.

So I had a think and came up with a bunch of classes that do allow me to observe changes in a chain of objects, and do so in a kind of fault tolerant manner, where replacement objects could be brought into the chain, without any adverse affect to the INPC listeners.

The main class I came up with is called ChainPropertyObserver and can be used as simply as this:

//create INPC model
Person p = new Person();
p.Age = 12;
p.Name = "sacha";
p.Address = new Address() { 
    Addressline1="21 maple street",
    Addressline2 = "Hanover",
    GeoLocation = new GeoLocation 
        { 
            Longitude=0.555, 
            Latitude=0.787 
        } 
    };

MyPerson = p;

List<string> personChanges = new List<string>();
List<string> addressChanges = new List<string>();
List<string> geoLocationChanges = new List<string>();

//create observer
ChainPropertyObserver chainPropertyObserver = 
    new ChainPropertyObserver();
chainPropertyObserver.CreateChain(
    () => MyPerson.Address.GeoLocation, Changed);


//create some INPC listeners
chainPropertyObserver.RegisterChainLinkHandler(
    () => MyPerson,
    () =>
    {
        Console.WriteLine("The Person that changed is now : {0}", 
            MyPerson.ToString());
        personChanges.Add(MyPerson.ToString());
    });

chainPropertyObserver.RegisterChainLinkHandler(
    () => MyPerson.Address,
    () =>
    {
        Console.WriteLine("The Address that changed is now : {0}", 
            MyPerson.Address.ToString());
        addressChanges.Add(MyPerson.Address.ToString());
    });

chainPropertyObserver.RegisterChainLinkHandler(
    () => MyPerson.Address.GeoLocation,
    () =>
    {
        Console.WriteLine("The GeoLocation that changed is now : {0}", 
            MyPerson.Address.GeoLocation.ToString());
        geoLocationChanges.Add(MyPerson.Address.GeoLocation.ToString());

    });

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

If you want to know more you can read the full article over at codeproject at this url : http://www.codeproject.com/KB/cs/ChainedObserve.aspx

A Look At Tasks In The System.Threading.Tasks VS2010 Namespace

I had a bit of time today to look at the System.Threading.Tasks VS2010 Namespace, and I started throwing a bit of code together and wrote an article about which you can read over at

http://www.codeproject.com/KB/threads/TPLTasks.aspx

But if you just want a quick overview, what the Tasks in the System.Threading.Tasks VS2010 Namespace are all about (from what I read anyhow), is a replacement for queuing work items up using the currently available ThreadPool. The issue with the current ThreadPool is that

  • Work items can’t return a value
  • Can not cancel tasks
  • No waiting on work items
  • Composing a group of items in a structured way
  • Handling exceptions thrown concurrently or any other richer construct built on top of it

 

So Tasks are there to help out in this area. Let’s have a quick look at how to do some common things such as

 

Run A Task That Returns A Value

   1:     /// <summary>
   2:          /// This handler shows you to use a Task that
   3:          /// doesn't use any state inside the Task
   4:          /// 
   5:          /// This Task blocks the calling thread until the 
   6:          /// Task completes
   7:          /// </summary>
   8:          private void TaskFactWithReturnValue_Click(object sender, 
   9:              RoutedEventArgs e)
  10:          {
  11:              Func<ObservableCollection<String>> obtainTaskResults 
  12:                  = TaskWithResults;
  13:              Task<ObservableCollection<String>> task =
  14:                  Task.Factory.StartNew<ObservableCollection<String>>
  15:                  (obtainTaskResults,
  16:                  TaskCreationOptions.DetachedFromParent);
  17:              items.Clear();
  18:              task.Wait(); //Blocks while waiting for Task to complete
  19:              items = task.Result;
  20:              lstItems.ItemsSource = items;
  21:              MessageBox.Show("TaskFactWithReturnValue DONE");
  22:          }
  23:   
  24:          /// <summary>
  25:          /// Runs the Tasks Func delegate, which returns 
  26:          /// a list of ObservableCollection String
  27:          /// </summary>
  28:          private ObservableCollection<String> TaskWithResults()
  29:          {
  30:              ObservableCollection<String> results = 
  31:                  new ObservableCollection<string>();
  32:              for (int i = 0; i < 10; i++)
  33:              {
  34:                  results.Add(String.Format(
  35:                      "TaskFactWithReturnValue Item {0}", i));
  36:              }
  37:              return results;
  38:   
  39:          }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And we can even chain tasks together using a technique called Continuations, here is an example of that:

   1:         /// <summary>
   2:          /// This handler shows you to use a Task that will 
   3:          /// use 2 chained Tasks the first Task accepts some
   4:          /// State, and the 2nd Task in the chain doesn't
   5:          /// ONLY when both Tasks have completed is the work 
   6:          /// considered done
   7:          /// 
   8:          /// This Task blocks the calling thread until the 
   9:          /// 2 chained Task complete
  10:          /// </summary>
  11:          private void TaskContinue_Click(object sender, 
  12:              RoutedEventArgs e)
  13:          {
  14:              //SYNTAX EXAMPLE 1
  15:              #region SYNTAX EXAMPLE 1
  16:              Func<Object, ObservableCollection<String>> 
  17:                  obtainTaskResultsFunc = 
  18:                  TaskWithResultsWithState;
  19:              Task<ObservableCollection<String>> task =
  20:                  Task.Factory.StartNew(obtainTaskResultsFunc, 
  21:                  new ObjectState<Int32>
  22:                  {
  23:                      CurrentTask = "TaskState",
  24:                      Value = 2
  25:                  });
  26:   
  27:              Func<Task, ObservableCollection<String>> 
  28:                  contineResultsFunc = ContinueResults;
  29:              Task<ObservableCollection<String>>
  30:                  continuationTask =
  31:                  task.ContinueWith<ObservableCollection<String>>
  32:                  (contineResultsFunc,
  33:                  TaskContinuationOptions.OnlyOnRanToCompletion);
  34:   
  35:              continuationTask.Wait();
  36:              items.Clear();
  37:              items = continuationTask.Result;
  38:              #endregion
  39:   
  40:              //SYNTAX EXAMPLE 2
  41:              #region SYNTAX EXAMPLE 2
  42:              //Task<ObservableCollection<String>> taskAll =
  43:              //    Task.Factory.StartNew((o) =>
  44:              //        {
  45:              //            return TaskWithResultsWithState(o);
  46:              //        }, new ObjectState<Int32>
  47:              //            {
  48:              //                CurrentTask = "TaskState",
  49:              //                Value = 2
  50:              //            }).ContinueWith<ObservableCollection
  51:              //              <String>>((previousTask) =>
  52:              //                {
  53:              //                    return ContinueResults(
  54:              //                      previousTask);
  55:              //                },TaskContinuationOptions.
  56:              //                  OnlyOnRanToCompletion);
  57:   
  58:   
  59:              //taskAll.Wait(); 
  60:              //items.Clear();
  61:              //items = taskAll.Result;
  62:              #endregion
  63:   
  64:   
  65:              lstItems.ItemsSource = items;
  66:              MessageBox.Show("TaskContinue DONE");
  67:          }
  68:   
  69:   
  70:   
  71:          /// <summary>
  72:          /// Runs the Tasks Func delegate, which returns a list
  73:          /// of ObservableCollection String
  74:          /// </summary>
  75:          private ObservableCollection<String> 
  76:              TaskWithResultsWithState(Object o)
  77:          {
  78:              var state = o as ObjectState<Int32>;
  79:              ObservableCollection<String> results = 
  80:                  new ObservableCollection<string>();
  81:              for (int i = 0; i < state.Value; i++)
  82:              {
  83:                  results.Add(String.Format("{0} Item {1}", 
  84:                      state.CurrentTask, i));
  85:              }
  86:              return results;
  87:   
  88:          }
  89:   
  90:          /// <summary>
  91:          /// Runs the Contination Tasks Func delegate, 
  92:          /// which returns a list
  93:          /// of ObservableCollection String
  94:          /// </summary>
  95:          private ObservableCollection<String> 
  96:              ContinueResults(Task originalTask)
  97:          {
  98:   
  99:              Task<ObservableCollection<String>> taskOriginal 
 100:                  = originalTask as Task<ObservableCollection<String>>;
 101:   
 102:              ObservableCollection<String> results = 
 103:                  new ObservableCollection<string>();
 104:   
 105:              ObservableCollection<String> orginalResults =
 106:                  taskOriginal.Result as 
 107:                  ObservableCollection<String>;
 108:   
 109:              foreach (var item in orginalResults)
 110:                  results.Add(item);
 111:   
 112:              for (int i = 0; i < 10; i++)
 113:                  results.Add(
 114:                      String.Format(
 115:                      "ContinueResults Item {0}", i));
 116:   
 117:              return results;
 118:          }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

As I say I go through all this a lot more in my article, which is available at the following Url should you want to know more:

 

http://www.codeproject.com/KB/threads/TPLTasks.aspx

LINQ : 2 nice things I just found

I was at work today and had to deal with obtaining the values from some anonomous types that I was using in some WPF databinding, and although I knew I could do it with reflection, I thought someone else may have already done something, and low and behold I found something pretty cool. I found this chap that wrote a nice wrapper around an anonomous type that lets you access the property values using generics for the type of the property and strings for the key of the property. He also allows you to add new methods to the anonomous type using delegates/lambdas, all in all its a good effort. Have a look for yourself over at his blog

http://somewebguy.wordpress.com/2009/05/29/anonymous-types-round-two/

Oh and he also wrote a LINQ for JavsScript which looks very nice especially if you are trying to parse large JSON result sets. You can read more about this over at this post

http://hugoware.net/

WPF : Dynamic Search Driven List Results (Now uses AppDomain)

A couple of posts ago I showed you all how to use CodeDom/CompilerServices and LINQ to create a dynamically created dll. A few people stated that this should have been in a new AppDomain (and it was already this way at work), so I have updated the example post to show you how to create a dynamic assembly in a new AppDomain. Have a look at the original post here : http://sachabarber.net/?p=496

Double Whammy Goodness

I just got an email from Chris Maunder today to tell me that my Sonic article (http://www.codeproject.com/KB/smart/Sonic.aspx) has won the 2 following awards, that’s 2 awards

  • Best C# article of February 2009
  • Best overall article of February 2009

Excellent today winning articles, tomorrow the world. Muah Ha Ha

 

Too be honest I was very pleased with Sonic, so I am happy it has done well.

MVVM Mediator Pattern

About 1 year ago a good friend of mine Marlon Grech wrote a lovely article on MVC + M. You can read all about Marlons great article over at http://marlongrech.wordpress.com/2008/03/20/more-than-just-mvc-for-wpf/

Essentially what Marlon did was create a message system to allow disparate MVC classes to communicate with each other. The original code by Marlon was spot on, but I just didn’t like the way he was using strings for his messages, but other than that there is very little change from my code here to his code. So well done Marlon, you are ace.

Anyway the idea behind Marlons original post was using the MVC pattern along with an additional class called the Mediator whom knew about messages and who to notify when something happened that warrants a message being sent out.

These days most folk will use the MVVM pattern when developing WPF. I have a small demo app that does the following.

  1. It has 2 textboxes, one of which is a writable textbox, which is used to send messages via the Mediator
  2. The 2nd textbox is refreshed via the message that is sent via the Mediator when the 1st textbox changes

Lets have a look at some code:

1st a helper class (lifted from Marlons blog)

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  
   6:  namespace MediatorDemo
   7:  {
   8:      /// <summary>
   9:      /// The multi dictionary is a dictionary that contains 
  10:      /// more than one value per key
  11:      /// </summary>
  12:      /// <typeparam name="T">The type of the key</typeparam>
  13:      /// <typeparam name="K">The type of the list contents</typeparam>
  14:      public class MultiDictionary<T, K>
  15:          : Dictionary<T, List<K>>
  16:      {
  17:  
  18:          #region Private Methods
  19:          //checks if the key is already present
  20:          private void EnsureKey(T key)
  21:          {
  22:              if (!ContainsKey(key))
  23:              {
  24:                  this[key] = new List<K>(1);
  25:              }
  26:              else
  27:              {
  28:                  if (this[key] == null)
  29:                      this[key] = new List<K>(1);
  30:              }
  31:          }
  32:          #endregion
  33:  
  34:          #region Public Methods
  35:          /// <summary>
  36:          /// Adds a new value in the Values collection
  37:          /// </summary>
  38:          /// <param name="key">The key where to place the 
  39:          /// item in the value list</param>
  40:          /// <param name="newItem">The new item to add</param>
  41:          public void AddValue(T key, K newItem)
  42:          {
  43:              EnsureKey(key);
  44:              this[key].Add(newItem);
  45:          }
  46:  
  47:  
  48:          /// <summary>
  49:          /// Adds a list of values to append to the value collection
  50:          /// </summary>
  51:          /// <param name="key">The key where to place the item in the value list</param>
  52:          /// <param name="newItems">The new items to add</param>
  53:          public void AddValues(T key, IEnumerable<K> newItems)
  54:          {
  55:              EnsureKey(key);
  56:              this[key].AddRange(newItems);
  57:          }
  58:  
  59:          /// <summary>
  60:          /// Removes a specific element from the dict
  61:          /// If the value list is empty the key is removed from the dict
  62:          /// </summary>
  63:          /// <param name="key">The key from where to remove the value</param>
  64:          /// <param name="value">The value to remove</param>
  65:          /// <returns>Returns false if the key was not found</returns>
  66:          public bool RemoveValue(T key, K value)
  67:          {
  68:              if (!ContainsKey(key))
  69:                  return false;
  70:  
  71:              this[key].Remove(value);
  72:  
  73:              if (this[key].Count == 0)
  74:                  this.Remove(key);
  75:  
  76:              return true;
  77:          }
  78:  
  79:          /// <summary>
  80:          /// Removes all items that match the prediacte
  81:          /// If the value list is empty the key is removed from the dict
  82:          /// </summary>
  83:          /// <param name="key">The key from where to remove the value</param>
  84:          /// <param name="match">The predicate to match the items</param>
  85:          /// <returns>Returns false if the key was not found</returns>
  86:          public bool RemoveAllValue(T key, Predicate<K> match)
  87:          {
  88:              if (!ContainsKey(key))
  89:                  return false;
  90:  
  91:              this[key].RemoveAll(match);
  92:  
  93:              if (this[key].Count == 0)
  94:                  this.Remove(key);
  95:  
  96:              return true;
  97:          }
  98:          #endregion
  99:      }
 100:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

This simply allows more than 1 object to be registered for a particular message

Next comes the Mediator which is a singleton, and know how to send and register messages against callback, which is what I have changed. In Marlons original code he used Strings, where as I am now using Action<Object> delegates as callbacks. A minor improvement I feel.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  
   6:  namespace MediatorDemo
   7:  {
   8:      /// <summary>
   9:      /// Available cross ViewModel messages
  10:      /// </summary>
  11:      public enum ViewModelMessages { UserWroteSomething = 1 };
  12:  
  13:  
  14:      public sealed class Mediator
  15:      {
  16:          #region Data
  17:          static readonly Mediator instance = new Mediator();
  18:          private volatile object locker = new object();
  19:  
  20:          MultiDictionary<ViewModelMessages, Action<Object>> internalList
  21:              = new MultiDictionary<ViewModelMessages, Action<Object>>();
  22:          #endregion
  23:  
  24:          #region Ctor
  25:          //CTORs
  26:          static Mediator()
  27:          {
  28:  
  29:  
  30:          }
  31:  
  32:          private Mediator()
  33:          {
  34:  
  35:          }
  36:          #endregion
  37:  
  38:          #region Public Properties
  39:  
  40:          /// <summary>
  41:          /// The singleton instance
  42:          /// </summary>
  43:          public static Mediator Instance
  44:          {
  45:              get
  46:              {
  47:                  return instance;
  48:              }
  49:          }
  50:  
  51:          #endregion
  52:  
  53:          #region Public Methods
  54:          /// <summary>
  55:          /// Registers a Colleague to a specific message
  56:          /// </summary>
  57:          /// <param name="callback">The callback to use 
  58:          /// when the message it seen</param>
  59:          /// <param name="message">The message to 
  60:          /// register to</param>
  61:          public void Register(Action<Object> callback,
  62:              ViewModelMessages message)
  63:          {
  64:              internalList.AddValue(message, callback);
  65:          }
  66:  
  67:  
  68:          /// <summary>
  69:          /// Notify all colleagues that are registed to the 
  70:          /// specific message
  71:          /// </summary>
  72:          /// <param name="message">The message for the notify by</param>
  73:          /// <param name="args">The arguments for the message</param>
  74:          public void NotifyColleagues(ViewModelMessages message,
  75:              object args)
  76:          {
  77:              if (internalList.ContainsKey(message))
  78:              {
  79:                  //forward the message to all listeners
  80:                  foreach (Action<object> callback in
  81:                      internalList[message])
  82:                          callback(args);
  83:              }
  84:          }
  85:          #endregion
  86:  
  87:      }
  88:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

So how does this work, well lets see a ViewModel that sends a message via the mediator, notice the NotifyColleagues(..) method usage below.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel;
   4:  using System.Linq;
   5:  using System.Text;
   6:  using System.Windows.Input;
   7:  using System.Windows.Data;
   8:  
   9:  
  10:  namespace MediatorDemo
  11:  {
  12:      public class WritersViewModel : ViewModelBase
  13:      {
  14:          private String writerText = null;
  15:  
  16:  
  17:          public WritersViewModel()
  18:          {
  19:  
  20:  
  21:          }
  22:  
  23:          public String WriterText
  24:          {
  25:              get { return writerText; }
  26:              set
  27:              {
  28:                  writerText = value;
  29:                  NotifyChanged("WriterText");
  30:                  //alert others about this change
  31:                  //via Mediator
  32:                  Mediator.Instance.NotifyColleagues(
  33:                      ViewModelMessages.UserWroteSomething,
  34:                          writerText);
  35:              }
  36:          }
  37:  
  38:      }
  39:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

And how about dealing with a message from the Mediator, this is fairly simple, though we do have to cast the results from Object to the Type we are expecting. This is necessary as the Mediator uses Action<Object> delegates as callbacks, where Object could be any Type of course.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel;
   4:  using System.Linq;
   5:  using System.Text;
   6:  using System.Windows.Input;
   7:  
   8:  
   9:  namespace MediatorDemo
  10:  {
  11:      public class ReadersViewModel : ViewModelBase
  12:      {
  13:          private String readText = String.Empty;
  14:  
  15:  
  16:          public ReadersViewModel()
  17:          {
  18:              //register to the mediator for the 
  19:              //UserWroteSomething message
  20:              Mediator.Instance.Register(
  21:  
  22:                  //Callback delegate, when message is seen
  23:                  (Object o) =>
  24:                  {
  25:                      ReadText = (String)o;
  26:                  }, ViewModelMessages.UserWroteSomething);
  27:          }
  28:  
  29:  
  30:          public String ReadText
  31:          {
  32:              get { return readText; }
  33:              set
  34:              {
  35:                  readText = value;
  36:                  NotifyChanged("ReadText");
  37:              }
  38:          }
  39:      }
  40:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

And that is really all there is to it. You now have a Writer ViewModel that will notify a totally disconnected Reader ViewModel about a change, via the messaging providing by the Mediator/Action<Object> delegate callbacks, that were registered for the message by the class that wants to do something based on the message being registered with the Mediator.

As I say this is all thanks to Marlon, well done Marlon.

And here is a small demo app for you to play with

mediatordemo.zip