Lambdas / Anonomous delegates

Nice little trick when working with Expression API

So I like writing Expression tree API magic, but I am mortal and don’t find it that easy to do, and it normally takes me a while to do this. So I am up for any help that I can get.

I just learnt a neat little trick, which is that you can apply TypeDescriptor attributes at runtime, which is cool. This one thing allows us to use a fairly standard PropertyGrid to visualize Expression trees

For example here is a simple Winforms UI I crafted with a few Expressions to visualize and each one just gets set to the PropertyGrid SelectedObject when selected from the list

image

Ok its not perfect but it is good enough to help you out

Here is the relevant code from the simple Winforms UI

Expression<Func<string, string, int>> fun1 = (s1, s2) => s1.Length - s2.Length;

TypeDescriptor.AddAttributes(typeof(Expression),
    new TypeConverterAttribute(typeof(ExpandableObjectConverter)));


propertyGrid1.SelectedObject = fun1;
Advertisements
C#, 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

C#, Lambdas / Anonomous delegates, LINQ

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

C#, Lambdas / Anonomous delegates

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

C#, Lambdas / Anonomous delegates

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

C#, Lambdas / Anonomous delegates

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

Beginners Guide To Threading, C#, Lambdas / Anonomous delegates

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