Archive

Posts Tagged ‘Functional Programming’

Task Parallel Library – PLINQ Part 1

October 30, 2010 Leave a comment

We are going to cover the following:

  • Basic data parallelism
  • Configuration Settings

Lets look at basic parallelism. To use PLINQ you need to use the .AsParallel() extension method on IEnumerable<T> which indicates everything following will be ran in parallel. Lets look at some basic code.

Enumerable.Range(1,1000).AsParallel().Sum();

So this is pretty easy. Obviously this is suited to long running operations / computations. If it is small like this its probably going to be quicker to use plain LINQ as there is an overhead in using PLINQ and concurrency in general.

Ok. No we have some of the basics lets look at some tweaks we can apply.
Firstly sometime even though you think the engine will run it in parallel it may not if the enginee thinks parallelizing the query will be slower you can force this using the WithExecutionMode() extension method.
Also if you have a lot of IO bound operations you may want to up the number of work been done in parallel which defaults to you core count. You do do with with SetMaxDegreeOfParallelism() extension method.

More code

items.AsParallel() // Select PLINQ
         .WithExecutionMode(ParallelExecutionMode.ForceParallelism) // Force to run in parallel mode in case sequential selected
         .WithDegreeOfParallelism(6) /
          .Sum();

So there we have some really easy sample to get you of investigation PLINQ.
Next time lets look at Exceptions.

Blair

Advertisements

Enumerable extensions to remove duplicates with a function return the key value

September 22, 2010 Leave a comment

Wow.. Long title…

If you have an enumerable and you want to remove duplicates out of the list with a function that returns the key of the type use the extension method I have developed below. Really handy 🙂

public static class EnumerableExtensions
    {
        public static IEnumerable<ElementType> EnsureDuplicateAreRemoved<ElementType,TKeyType>
            (this IEnumerable<ElementType> enumerable, Func<ElementType, TKeyType> keyProducer)
        {
            Dictionary<TKeyType, TKeyType> cache = new Dictionary<TKeyType, TKeyType>();

            foreach (var element in enumerable)
            {
                var value = keyProducer(element);
                if(cache.ContainsKey(value))
                    continue;
                cache.Add(value,value);
                yield return element;
            }

        }
    }

Blair…

The Case Against Count Method in LINQ

September 22, 2010 Leave a comment

The Count method in LINQ is really slow as it iterates of all the items and adds a tally unless the IEnumerator is really an ICollection.

If you need to know whether there is at least 1 item use Any method as it traverses through and if there is an item it exists returning true.

So if you have a huge list the performance difference will be large.

public static int Count(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    ICollection<T> is2 = source as ICollection<T>;
    if (is2 != null)
    {
        return is2.Count;
    }
    int num = 0;
    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num++;
        }
    }
    return num;
}

public static bool Any(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
        {
            return true;
        }
    }
    return false;
}

The source code from LINQ pretty much spells it out. 🙂

Blair…

Microsoft CRM LINQ

September 17, 2010 Leave a comment

If you have been under a rock the latest version of MS CRM SDK contains new bits that allow you to use LINQ plus other goodness over MS CRM.

So how do we set all this Up?

Setup Steps:

  1. Download the latest SDK from MS
  2. Reference the following Assemblies: microsoft.xrm.client.dll, microsoft.xrm.portal.dll, antixsslibrary.dll, microsoft.crm.sdk.dll,microsoft.crm.sdktypeproxy.dll,microsoft.crm.sdktypeproxy.xmlserializers.dll
  3. Create an entry in you web.config / app.config file pointing to your CRM server
  4. <connectionStrings>
          <add name="Crm" connectionString="Authentication Type=AD; Server=http://localhost:5555/Test; User ID=Test\blair; Password=somepassword;"/>
      </connectionStrings>
    

Lets create a query and look at a dynamic version of contacts now 🙂

            var context = new CrmDataContext("Crm");
            var results = from contact in context.GetEntities("contact") select contact;
            return results.ToList().Select(x => x.ToDynamicEntity()).ToList();

So there you go. Review MS Documentation. But I hope this helps you get started.

MS Documentation is here.

Blair..

C# Functional Programming and Collections

July 24, 2010 Leave a comment

Hi all,

Some examples of functional style development with collections…

List<int> values = new List<int> { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
values.FindAll( x => x > 10).ForEach(x => Console.WriteLine(x));
values.Sort((x, y) => x.CompareTo(y));

Blair..

Tuples C#

July 14, 2010 Leave a comment

Provide a way to group data items together. For example you may want a data item with a persons id and name.
A tuple provides a convenient way to do so. It is also benefical over anonymous types if you need to use it outside the current function scope.

Se the following example.

using System;

namespace Tuples
{
    class Program
    {
        static void Main(string[] args)
        {
            Tuple<int, string> t1 = new Tuple<int, string>(1,"Blair Davidson");
            Tuple<int, String> t2 = Tuple.Create(2, "Chia Ling");

            Console.WriteLine(t1.Item1 + " " + t1.Item2);

        }
    }
}

Blair…

Learning… I mean Embracing Javascript

May 10, 2010 Leave a comment

Well this is a little interesting for me. Well when I first started programming with PHP back in the early 2000’s i really hated Javascript. and since Ajax had not come into play we use to do everything server side where possible. Then came Ajax which I got my first taste in 2007 with ASP.NET Ajax using update panels. Now everyone expects fairly rich UI’s and trying to do them in ASP.NET is really horrible especially when update panels run the whole page request from start to finish.

Also now my feelings towards Javascript are starting to change. I guess not opinions but ignorance is probably better. I have take the plunge and actually decided to learn Javascript. Now we have frameworks like JQuery we can complain about the DOM and the like we should embrace it as the functional programming language that it is.

I am using WebStorm from Jetbrains which has goot code completion so VS 2010 is not the only one out there that can claim this now.

Well the journey will be a long one but why I am doing this since I can hack my way through using UpdatePanels. Well I am a huge fan of ASP.NET MVC and am keen to update my skills so thus the plunge begins.

Blair..