Archive

Posts Tagged ‘LINQ’

Redirect to a safe location Error Action Filter in ASP.NET MVC

February 15, 2011 Leave a comment

I have an example of an error action filter on how you can move the user to a previously know safe location in mvc with the following action filter. I and an error to tempdata which you could look for in the site master to show the error.

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace Learning.ActionFilters
{
    public class RedirectToRouteErrorAttribute : FilterAttribute, IExceptionFilter
    {
        public IEnumerable<string> RouteValues { get; private set; }
        public string ErrorMessage { get; private set; }

        public RedirectToRouteErrorAttribute(string errormessage, params string[] tokens)
        {
            ErrorMessage = errormessage;
            RouteValues = tokens;
        }

        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
                return;

            var items = from route in filterContext.RouteData.Values
                        join key in RouteValues on route.Key equals key
                        select route;

            var dict = new RouteValueDictionary(items);

            filterContext.Controller.TempData.Add("errormessage", ErrorMessage);
            filterContext.Result = new RedirectToRouteResult(dict);
            filterContext.HttpContext.Response.Clear();
            filterContext.ExceptionHandled = true;
        }
    }
}

// Here is an example of the usage
 [HttpPut]
 [ActionName("Edit")]
 [RedirectToRouteErrorAttribute("controller","action","id")]
 public virtual ActionResult EditUser(){}

You just specify which route values you want to keep so the RedirectToRouteResult work as required

Blair…

Advertisements

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

StructureMap Manual Registration – Setting Properties

October 28, 2010 Leave a comment

Hi all back again with another example of using structure map manually. Were going to follow on from the last example.

If you have a concrete type that need a property set then you use the SetProperty Method and use an action lambda statement like below to set it up. EASY.

Pretty easy hey.

using System;
using StructureMap;

namespace StructureMapSamples
{
    public interface ILogger
    {
        void Log(string message);
    }

    public class RemoteLogger : ILogger
    {
        private readonly string _server;

        public int Port { get; set; }

        public RemoteLogger(string server)
        {
            _server = server;
            Port = 80;
        }

        public void Log(string message)
        {
            Console.WriteLine("Writing {0} to {1}:{2}", message,_server,Port);
        }
    }

    public class Program
    {
        

        static void Main(string[] args)
        {
            Program program = new Program();
            program.InitializeContainer();
            program.RunExamplesWithCtorArgsPassedToTypeAndPropertyValuesSet();

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

        public void InitializeContainer()
        {
            ObjectFactory.Configure(
                    x => x.For<ILogger>()
                          .Use<RemoteLogger>()
                          .Ctor<string>("server").Is("www.google.com")
                          .SetProperty(y => y.Port = 8080)
                );
        }

        private void RunExamplesWithCtorArgsPassedToTypeAndPropertyValuesSet()
        {
            ILogger logger = ObjectFactory.GetInstance<ILogger>();
            logger.Log("Hello Google");
        }
    }
}

Hope this helps.

Blair

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..

MS CRM Extensions Project on CodePlex

September 10, 2010 Leave a comment

Hi all, Created my first Codeplex project. Extensions to make CRM more friendly.

URL: http://mscrmextensions.codeplex.com/

Blair