0

Extension methods for linq

by klh 28. juli 2010 01:51

OK, so it has botherd me for a long time, that MS decided to call the Map, Filter, Fold and Bind something completely nonsense, like Select, Where etc.

It seems I’m not the only one: http://stackoverflow.com/questions/1230729/where-is-the-fold-linq-extension-method

So I decided to make extension methods, so you can now use the real functional names, here goes:

 

public static class LinqExtensions
    {
        public static IEnumerable<TResult> Map<TSource, TResult>
            (this IEnumerable<TSource> source,
             Func<TSource, int, TResult> selector)
        {
            return source.Select(selector);
        }

        public static IEnumerable<TResult> Map<TSource, TResult>
            (this IEnumerable<TSource> source,
             Func<TSource, TResult> selector)
        {
            return source.Select(selector);
        }

        public static IEnumerable<TSource> Filter<TSource>
            (this IEnumerable<TSource> source,
             Func<TSource, int, bool> predicate)
        {
            return source.Where(predicate);
        }

        public static IEnumerable<TSource> Filter<TSource>
            (this IEnumerable<TSource> source,
             Func<TSource, bool> predicate)
        {
            return source.Where(predicate);
        }

        public static TAccumulate FoldLeft<TSource, TAccumulate>
            (this IEnumerable<TSource> source, TAccumulate seed,
             Func<TAccumulate, TSource, TAccumulate> func)
        {
            return source.Aggregate(seed, func);
        }

        public static TSource FoldLeft<TSource>
            (this IEnumerable<TSource> source, 
             Func<TSource, TSource, TSource> func)
        {
            return source.Aggregate(func);
        }

        public static TAccumulate FoldRight<TSource, TAccumulate>
            (this IEnumerable<TSource> source, TAccumulate seed,
             Func<TAccumulate, TSource, TAccumulate> func)
        {
            return source.Reverse().Aggregate(seed, func);
        }

        public static TSource FoldRight<TSource>
            (this IEnumerable<TSource> source, 
             Func<TSource, TSource, TSource> func)
        {
            return source.Reverse().Aggregate(func);
        }

        public static IEnumerable<TResult> Bind<TSource, TCollection, TResult>
            (this IEnumerable<TSource> source,
             Func<TSource, IEnumerable<TCollection>>
             collectionSelector,
             Func<TSource, TCollection, TResult>
             resultSelector)
        {
            return source.SelectMany(collectionSelector, resultSelector);
        }

        public static IEnumerable<TResult> Bind<TSource, TCollection, TResult>
            (this IEnumerable<TSource> source,
             Func<TSource, int,
             IEnumerable<TCollection>> collectionSelector,
             Func<TSource, TCollection, TResult> resultSelector)
        {
            return source.SelectMany(collectionSelector, resultSelector);
        }

        public static IEnumerable<TResult> Bind<TSource, TResult>
            (this IEnumerable<TSource> source,
             Func<TSource, int, IEnumerable<TResult>> selector)
        {
            return source.SelectMany(selector);
        }

        public static IEnumerable<TResult> Bind<TSource, TResult>
            (this IEnumerable<TSource> source,
             Func<TSource, IEnumerable<TResult>> selector)
        {
            return source.SelectMany(selector);
        }
    }

What I did was simply taking the method signatures from the object browser and renaming the methods. So some of the arguments might not be named “the functional way”.

In order for the code to fit on the page, I had to reformat it a bit.

 

This would allow us to do the following:

var enumerable = strs.
                Filter(x => x.StartsWith("Ni")).
                Map(x => x);

Wow I feel so much better now :-)

Under the hood these use the linq methods…

Probably somebody has done this before and better, but it was just an experiment…

0

Three aspects of software projects

by klh 29. november 2009 03:09

The way I see it there are three aspects of a software projects that are worth noting, (or at least that I will focus on in this blog post):

1. The technical aspect

2. The process aspect

3. The meta techincal aspect

The technical aspect are all the aspects that every developer (hopefully) knows, like the programming language, the framework, the application servers etc.

The process aspect is the stuff like scrum, kanban ,lean etc.

The meta technical stuff is what I’ll zoom in on now.

First of all I’m not sure this it the best term, and probably someone has coined a better one…

However the way I see it these three aspects has to be in place for a project to suceed. The first two are usually in place, the first handled by the developer and the second by the project manager or scrum master or someone in similar roles.

However I see the last aspect often being neglected.

The meta technical aspect is about the framework of doing the technical stuff. so I would say it is for instance:

-TDD (BDD)

- SOLID

- IOC

So I would describe it as all the technical stuff that many hardcore developers do not care that much about, but that makes the quality of the code higher, and makes the code more maintainable.

The problem is that many people going into software development care about technical stuff, and care about breaking that small technical problem. But they don’t find the meta technical stuff as interesting.

Tags:

C# | generelt | TDD

0

TDD and unit testing is still OK

by klh 9. oktober 2009 13:13

OK there, for a while I was a bit worried about if I should stick with unit testing.

For a while I have been in doubt, for mainly two reasons:

1. I went to ANUG where Martin Olesen presented on BDD and stated that he didn’t always do TDD.

2. Ayende presented on JAOO Danish .Net User Group and stated that he only do unit testing in very few places in NHProf and used TDD even fewer places.

 

This all made me think about TDD and Unit testing, since two really smart guys felt this way about unit testing.

However aften some thought and scrum master training with Jeff Sutherland, where he stated: “All the best teams I see are running XP inside scrum”, meaning the best teams also practice TDD, I now conclude TDD is still OK! - Phew :-)

But OK now why do the two afore-mentioned smart guys not use unit testing intensively?

Well first and foremost these two guys are not new with software development, and since TDD is a design technique, they might not need it.

Ayende actually stated that he still did TDD on the hard parts (as I understand it, where he finds design hard).

Secondly Ayende presented on how he made implementing a feature in NHProf really simple, actuallly so simple it was not designed. And he stille tested it – using integration tests.

Thirdly Martin Olesen stated that his team was still not good enough to drop TDD, he would like to, but it was not possible.

So TDD is still OK!

Tags:

C# | TDD

0

Just did the string calculator kata

by klh 8. oktober 2009 13:55
I just did the string calculator kata, here is the output
 
[TestFixture]
    public class CalculatorTests
    {
        readonly Calculator _calc = new Calculator();
        [Test]
        public void Add_WhenGiven1_ShouldReturn1()
        {
            int result = _calc.Add("1");
            Assert.That(result, Is.EqualTo(1));
        }

        [Test]
        public void Add_WhenGiven15_ShouldReturn15()
        {
            int result = _calc.Add("15");
            Assert.That(result, Is.EqualTo(15));
        }

        [Test]
        public void Add_WhenGiven1comma5_ShouldReturn6()
        {
            int result = _calc.Add("1,5");
            Assert.That(result, Is.EqualTo(6));
        }

        [Test]
        public void Add_WhenGiven115comma23_ShouldReturn138()
        {
            int result = _calc.Add("115,23");
            Assert.That(result, Is.EqualTo(138));
        }

        [Test]
        public void Add_WhenGivenAlphaCharacter_ShouldThrowArgumentException()
        {
            Assert.Throws<ArgumentException>(() => _calc.Add("jens"));
        }

        [Test]
        public void Add_WhenGivenAlphaNumericCharacterWithNumericAtTheEnd_ShouldThrowArgumentException()
        {
            Assert.Throws<ArgumentException>(() => _calc.Add("jens1"));
        }

        [Test]
        public void Add_WhenGivenAlphaNumericCharacterWithNumericAtTheBeginning_ShouldThrowArgumentException()
        {
            Assert.Throws<ArgumentException>(() => _calc.Add("1jens"));
        }
    }

 

 

public class Calculator
    {
        public int Add(string s)
        {
            if(!Regex.IsMatch(s, @"^\d+(,\d+)?$"))
                throw new ArgumentException("s");

            var numbers = s.Split(',');
            int returnValue = 0;
            foreach (var number in numbers)
            {
                returnValue += int.Parse(number);
            }
            return returnValue;
        }
    }

Tags:

C# | generelt

0

My (Non-thread safe) wrapper for Castle Windsor IoC

by klh 24. marts 2009 03:58

I have a small wrapper API that I use around Castle Windsor, and thought I would share it. You could probably use it to wrap an IoC of your own choice.

First please note that this library is not checked for thread safety, secondly there is nothing original in what I do, it’s just my take on what’s already been done.

Here is how I configure the IoC container:

private static void SetupIOC() { Bind<HTTPClientWithBasicAuth>.To<IHTTPClient>(); Bind<TwitterClient>.ToAbstraction<ITwitterClient>(); }

Here is how I resolve an object:

ITwitterClient twitterClient = ResolveType.Of<ITwitterClient>();

Here is how you bind an instance to an interface or class:

Bind<UsernamePassword>.ToInstance(new UsernamePassword(args[0], args[1]));

 

Here is the class I use to resolve an object. This code is tightly coupled to the Windsor container, and for my pet project it is fine, but you might want to couple loosely to the container.

public static class ResolveType
{
private static readonly IWindsorContainer _container;
static ResolveType()
{
_container = new WindsorContainer();
}
public static T Of<T>() where T : class
{
if (typeof (T).Equals(typeof (IWindsorContainer)))
{
return new WindsorContainer() as T;
}
return _container.Resolve<T>();
}
internal static void AddComponent(string key, Type serviceType, Type classType)
{
_container.AddComponent(key, serviceType, classType);
}
internal static void AddComponentInstance<T>(object instance)
{
_container.Kernel.AddComponentInstance<T>(instance);
}
}

The two AddInstance methods are internal since the Bind class lives in the same assembly.

Here is how i configure the IoC container:

 

public class Bind<T>
{
public static void ToAbstraction<S>()
{
ResolveType.AddComponent(typeof (S).ToString(), typeof (S),
typeof (T));
}
public static void ToInstance(object instance)
{
ResolveType.AddComponentInstance<T>(instance);
}
}
You can find a small solution using this here 

Edit:

Renamed Bind.To to Bind.ToAbstraction, but not in the downloadable solution.

Tags:

C# | IoC

0

Generating interfaces for legacy classes

by klh 13. februar 2009 09:11

From time to time you bump into legacy code, where somebody thought that static methods was the solution to all your problems. We all know that an architecture with static methods calling static methods is very tightly coupled, and we would like decouple it.

What I would like to do is make an interface, with all public methods, and make an adapter that  implements the interface and uses the static methods of the legacy class.

EDIT:

Of course I should mention that this is a Proof of Concept, hence the code is not complete nor perfect:

-  The generated code uses the long form of the built in types instead of the short form

- There are duplicates distributed all around the code

- The code does not work with out/ref parameters (there were no usage of the two in the code I needed code generation for)

- The classname, namespace and assemblylocation should have been T4 properties

This was just to put an example of T4 usage out.

So here is an example of a legacy class:

namespace t4ConsoleApp
{
class StaticStuff
{
public static string Test()
{
return "test";
}
public static int GetNumber()
{
return 42;
}
public static bool IsAbove42(int x)
{
if(x > 42)
return true;
return false;
}
}
}

 

So what i would like is something like this:

namespace t4ConsoleApp
{
public interface IStaticStuff
{
System.String Test();
System.Int32 GetNumber();
System.Boolean IsAbove42(System.Int32 x);
}
}
namespace t4ConsoleApp
{
public class StaticStuffAdapter : IStaticStuff
{
public System.String Test()
{
return StaticStuff.Test();
}
public System.Int32 GetNumber()
{
return StaticStuff.GetNumber();
}
public System.Boolean IsAbove42(System.Int32 x)
{
return StaticStuff.IsAbove42(x);
}
}
}

Creating this in a manual way could be big work, so I decided to do it using T4.

First I make a class that can do reflection over the legacy class:

using System;
using System.Text;
using System.Reflection;
namespace t4ConsoleApp
{
public class StaticReflection
{
public Type GetType(string assemblyLocation, string typeName)
{
Assembly assembly = Assembly.LoadFrom(assemblyLocation);
if (assembly == null)
{
throw new Exception("assembly not found");
}
Type tp = assembly.GetType(typeName);
if (tp == null)
throw new Exception("type not found");
return tp;
}
public ClassInfoValue GetAllPublicStaticMembers(Type mytype)
{
ClassInfoValue classInfoValue = new ClassInfoValue(7);
MethodInfo[] miArray = mytype.GetMethods(BindingFlags.Public 
| BindingFlags.Static);
foreach (MethodInfo mi in miArray)
{
string parameterNames = GetParameterNames(mi);
string parametersWithNames = GetParametersWithNames(mi);
classInfoValue.ParameterNamesList.Add(parameterNames);
classInfoValue.Returntypes.Add(mi.ReturnType.ToString());
classInfoValue.MethodNames.Add(mi.Name);
classInfoValue.ParameterswithNamesList.Add(parametersWithNames);
}
return classInfoValue;
}
private static string GetParameterNames(MethodInfo mi)
{
ParameterInfo[] piArray = mi.GetParameters();
StringBuilder sb = new StringBuilder();
int i = 0;
foreach (ParameterInfo info in piArray)
{
if (i == 0)
{
sb.Append(info.Name);
}
else
{
sb.Append(", " + info.Name);
}
i++;
}
return sb.ToString();
}
private static string GetParametersWithNames(MethodInfo mi)
{
ParameterInfo[] piArray = mi.GetParameters();
StringBuilder sb = new StringBuilder();
int i = 0;
foreach (ParameterInfo info in piArray)
{
if (i == 0)
{
sb.Append(info.ParameterType + " " + info.Name);
}
else
{
sb.Append(", " + info.ParameterType + " " + info.Name);
}
i++;
}
return sb.ToString();
}
}
}

And lastly the T4 template to do this, I made a console app to contain the T4 stuff

<#@ template language="C#v2.0" hostspecific="True" #>
<#@ output extension=".generated.cs" #>
<#@ assembly name="system.dll" #>
<#@ assembly name="D:\Src\t4consoleapp\t4consoleapp\bin\debug\t4ConsoleApp.exe" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="t4ConsoleApp" #>
<#
string classname = "StaticStuff";
string nameSpace= "t4ConsoleApp";
string classNameWithNamespace = nameSpace + "." + classname;
string assemblylocation =  @"D:\Src\t4consoleapp\t4consoleapp\bin\debug\t4ConsoleApp.exe";
StaticReflection staticReflection = new StaticReflection();
Type myType = staticReflection.GetType(assemblylocation, classNameWithNamespace);
ClassInfoValue classInfo = staticReflection.GetAllPublicStaticMembers(myType);
#>
<#= "//Generated at: " + DateTime.Now #>
using System;
namespace <#= nameSpace #>
{
public interface I<#= classname #>
{
<# for(int i = 0; i< classInfo.MethodNames.Count; i++){ #>
<# if(classInfo.Returntypes[i] == typeof(void).ToString()) {#>
void <#= classInfo.MethodNames[i] #>(<#= classInfo.ParameterswithNamesList[i] #>);
<#} else {#>
<#= classInfo.Returntypes[i] #> <#= classInfo.MethodNames[i] #>(<#= classInfo.ParameterswithNamesList[i] #>);
<# } #>
<# } #>
}
}
namespace <#= nameSpace #>
{
public class <#= classname #>Adapter :I<#= classname #>
{
<# for(int i = 0; i< classInfo.MethodNames.Count; i++){ #>
<# if(classInfo.Returntypes[i] == typeof(void).ToString()) {#>
public void <#= classInfo.MethodNames[i] #>(<#= classInfo.ParameterswithNamesList[i] #>)
{
<#= classname #>.<#= classInfo.MethodNames[i] #>(<#= classInfo.ParameterNamesList[i] #>);
}
<#} else {#>
public <#= classInfo.Returntypes[i] #> <#= classInfo.MethodNames[i] #>(<#= classInfo.ParameterswithNamesList[i] #>)
{
return <#= classname #>.<#= classInfo.MethodNames[i] #>(<#= classInfo.ParameterNamesList[i] #>);
}
<# } #>
<# } #>
}
}
namespace <#= nameSpace #>
{
public class <#= classname #>Factory
{
public I<#= classname #> Get<#= classname #>()
{
return new <#= classname #>Adapter();
}
}
}

1

[Danish] om læsbar kode

by klh 30. oktober 2008 06:16

Brian Rasmussen skrev for nylig et blog indlæg om en kort kommentar, jeg havde skrevet til et tidligere blog indlæg han havde skrevet. (Hvis jeg havde arbejdet med det kunne jeg nok have formuleret det lidt mere kringlet :-)

Det jeg egentlig ville fremhæve med min meget korte kommentar var at jeg går meget ind for læsbar kode.
Vi ved alle at kode læses flere gange end det skrives …

Det som jeg specifikt tænkte på med one-liners (men ikke skrev), er nogle af de konkurrencer der har foregået, hvor man skulle få en linje kode til at lave så meget som muligt, hvilket naturligvis gik ud over læsbarheden.

Nogle gange synes vi som udviklere at det bare er fedt at lave kompliceret kompakt kode - og det føles da også tit fedt. Men det er meget svært at læse.
Jeg kan huske en samtale jeg havde med en anden udvikler på et tidspunkt, om en arktiekt, hvor den anden udvikler fortalte mig at arkitekten var så dygtig til at kode at de andre i hans team tit ikke forstod hans kode, jeg kan huske at jeg dengang tænkte: "Wow!, hvor må det være fedt at være så dygtig".

Idag ville jeg tænke noget ganske andet ...

Så det var altså det jeg mente med “one-liners er bare så 1995″

Min kommentar udsprang lidt af en snak jeg havde med Henrik Lykke og Søren Skovsbøll, om ?? null coalescing operatoren til et ANUG møde.

Henrik fortalte at han brugte den aldrig, selvom han kendte den godt; ganske enkelt fordi andre skulle overtage hans kode, og han vidste at ikke alle kender null coalescing operatoren.

Undskyld Henrik, hvis jeg har citeret dig forkert.

 

Jeg syntes at noget af det kod, Brian lavede i den første post mindede lidt om noget en nybegynder kunne have vanskeligt ved at læse.

Man kunne naturligvis starte en hel debat om man skal kode efter laveste fællesnævner, og om man ikke løfter nybegyndere ved at tvinge dem til at lære mere avancerede features i C#. (mange betragter faktisk null coalescing operatoren som en avancerret feature)

Tags:

C#

1

ListViews and sorting by Date

by klh 19. februar 2008 06:05

In our company we have several GUIs with ListViews in them.

Now in some of the columns we have DateTimes that we wish to sort the ListView by.

To find the answer to sorting a ListView is rather simple. A google search reveals the following link (Please note: From Microsoft):

http://msdn2.microsoft.com/en-us/library/ms996467.aspx#Mtps_DropDownFilterText

Here an example of sorting by DateTime is displayed (Near the bottom), the code is as follows:

 

public int Compare(object x, object y)
    {
        int returnVal;
        // Determine whether the type being compared is a date type.
        try
        {
            // Parse the two objects passed as a parameter as a DateTime.
            System.DateTime firstDate =
                    DateTime.Parse(((ListViewItem)x).SubItems[col].Text);
            System.DateTime secondDate =
                    DateTime.Parse(((ListViewItem)y).SubItems[col].Text);
            // Compare the two dates.
            returnVal = DateTime.Compare(firstDate, secondDate);
        }
        // If neither compared object has a valid date format, compare
        // as a string.
        catch
        {
            // Compare the two items as a string.
            returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
                        ((ListViewItem)y).SubItems[col].Text);
        }
        // Determine whether the sort order is descending.
        if (order == SortOrder.Descending)
            // Invert the value returned by String.Compare.
            returnVal *= -1;
        return returnVal;
    } 

 

However THIS IS WROING!!!

That is not the correct way to use Exception handling.

How many time would the column be something else than a DateTime - well is's hard to say, but maybe more than 80% of the time.

Knowing that Exception handling is for exceptionel behaviour and that it is slow, you should never use this way of doing things.

You should do a DateTime.TryParse:

public int Compare(object x, object y)
    {
        int returnVal;

        DateTime firstDate;
        DateTime secondDate;
        bool conversion1Succesful, conversion2Succesful;
        conversion1Succesful = DateTime.TryParse(((ListViewItem)x).SubItems[columnToSort].Text, out firstDate);
        conversion2Succesful = DateTime.TryParse(((ListViewItem)y).SubItems[columnToSort].Text, out secondDate);

        if ((conversion1Succesful && conversion2Succesful))
        {
            returnVal = DateTime.Compare(firstDate, secondDate);
        }
        else
        {
            returnVal = String.Compare(((ListViewItem)x).SubItems[columnToSort].Text, ((ListViewItem)y).SubItems[columnToSort].Text);
        }

        if (orderOfSort == SortOrder.Descending)
            returnVal *= -1;

        return returnVal;
    } 

It will speed up your sorting by decades ;-)

Tags:

C# | software

0

Partial methods - what good are they?

by klh 31. januar 2008 15:52

So i attented the Aarhus .net User Group the other day.

Henrik Lykke Nielse of Captator gave an introducion to most of the updates to .net framework 3.5 and C# 3.0.

Most of it was known to me - however one thing that I had not heard about before was partial methods.

Partial methods are methods where you define the declaration of the method in one part of a partial class( a bit like C++ header files) and maybe choose to implement it in another part of the partial class. I say 'maybe' since you can choose to not implement the partial method, and if so all calls to the method is simply erased.

"So what good is this?", I thought to myself and asked Henrik. To this he responded that for instance you can implement functionality without thinking about instantiating classes.

Let me explain: One could do similiar stuff by making virtual methods, but the framework would then have to depend on factories and such to instantiate the correct objects for you.

However if you declare a partial method in the framework, and let be up to the user of the framework to implement the partial method or not - you get rid of all the factory fuzz.

Nice trick I think!

Tags:

C# | generelt

0

David Pallmann's WCF tips

by klh 6. januar 2008 05:32

Tags:

WCF | SOA | C#

Powered by BlogEngine.NET 1.4.5.0
Original Design by Laptop Geek, Adapted by onesoft