Saturday 31 January 2009

Exercise update for the festive period, New Year and Jan 2009

I've been thinking over the past few weeks that I want to change the angle of my blog to a more technical nature and having posted a couple of programming related posts recently I've decided that 2009 is the time to do this. I will keep a record of the exercise / beer ratio which I've been doing for a while as I've been using it as a log of my exercise. It's nice to keep a record of what has been happening.

So this is Januarys monthly post, it cover the festive period of 2008 as well. The main aims of 2009 is to loose some weight, get better at disc golf, improve the UK and local Disc golf scene and continue to work hard at my career. It's a tough time at the moment with the current economical climate and part of my aim for 2009 is to help my work push the envelope and work our way through it.

I'm also going to use these monthly posts to keep track of my aims; including the exercise and beer consumption and weigh ins. So as of the beginning of the year I was a chubba of 12stone 4 pounds. My target weight is at least 11stone 7 by the summer; more would be good tho!

So end of the month is here and I've been keeping track of the weight over the past 31 days and after hitting an all time low on my birthday (28th) I hit a 12 stone 3/7 pounds, so almost a loss of 4 pounds in a month. I can live with that ratio of a pound a week!

So here's the monthly roundup ...

1st Jan - Round of Disc golf, shot 63 (+9) with 3 2's (holes 2, 8 & 15) pretty happy start
2nd Jan - gym workout + 10 lengths
3rd Jan - Round of Disc Golf, shot 69 (+15) with 1 2 (hole 2) - drive disappeared through the 3 tree enclosures which I thought was good, when I got there it had skidded about 1.5 metres passed the basket - easy 2! :-). Swam as well, 10 lengths.
4th Jan - gym workout
6th Jan - gym workout
8th Jan - gym workout
10th Jan - doubles practice (2 rounds)
11th Jan - gym workout
13th Jan - swim 10 lengths (4b, 4f, 2b)
18th Jan - Hyzer Cup leg 2 @ Croydon - 2 rounds of DG
19th Jan - Swim 20 lengths (4b,4f,4b,2butterfly,4back, 4b)
20th Jan - gym workout
27th Jan - Swim 20 lengths (4b,4f,4b,4back,4b)
28th Jan - gym workout (birthday!!)

Total : Gym : 7
Swim : 70 lengths
DG: 6 rounds

Christmas - Eve - 5 beers
Christmas Day - 2 beers
Boxing Day - 1 beer
Holiday - 3 beers
New Years Eve - 6 beers
friday 16th - 2 beers (well 1.5 bottles, but will count 2)
20th Jan - lunchtime beer at Rev's
21st Jan - beer on the train home! Cross Country now serve Stella! WOO!!
21st Jan - beer at home ... fed up!
23rd Jan - 3 beers - Julie's birthday at Jongleurs in Birmingham
24th Jan - 1 Lager shandy - dinner with friends at Picolino's and pub after (driving!)
25th Jan - 1 lager shandy - Quarry Park Club first meeting at the White Horse, Leamington (driving!)

*Update*
31st Jan - 3 beers - Met up with some old uni friends in London (cough getting better, woo!)

Total: 27

Current Status : Bad!

Beers: 161
Miles: 33
DG Rounds: 25
Gym visits: 23
Lengths : 47 (month: 70; total: 470)

Key
Good => Exercise > Beers
Level => Exercise == Beers
Bad => Exercise < Beers

Tuesday 27 January 2009

Accessing object properties from string representations

Late last week I was looking into sorting a custom POCO (Plain Old CLR Object) collection which derived from System.Collection.ObjectModel.Collection<T>; but initiating the sorting in a crazy way ... passing in a parameter list of object property names in the order in which to sort them.

My initial sorting method had a switch on the property on the singular object which I wanted to get rid of due to you would have to add a new switch statement for each property you wanted to sort on ... no ideal.

private void Sort(string propertyName)
    {
        // convert to List
        List<MyClass> myCurrentClass = Items as List<MyClass>;
        // sort
        if (myCurrentClass != null)
        {
            switch (propertyName)
            {
                case "Name":
                    myCurrentClass.Sort(delegate(MyClass myClassOne, MyClass myClassTwo)
                                 {
                                     return
                                         Comparer<string>.Default.Compare(myClassOne.Name,
                                                                          myClassTwo.Name);
                                 }
                        );
                    break;
                case "Increment":
                    myCurrentClass.Sort(delegate(MyClass myClassOne, MyClass myClassTwo)
                                 {
                                     return
                                        Comparer<int>.Default.Compare(myClassOne.Increment,
                                                                     myClassTwo.Increment);
                                 });
                    break;
            }
        }
    }


After hunting around for a solution and being guided toward reflection but without any luck I decided to take the plunge and post my first ever question on StackOverflow. The community which has grown around the site has some very clever people in it so I thought I'd get at least a couple of replies ... and I had a guess that Jon Skeet would be first (as it's all he seems to do!) and I was right, woo! Anyway, I digress.



Jon suggested that I look into using Type.GetProperty and suggested that the whole concept might get a little icky. By this point I had gone past the point of wanting to put it into the original bit of code I was looking (as it would over complicate matters), but wanted to know how I could get to where I originally wanted to be. I was just about to dive back into the madness of reflection when another StackOverlow member, Frederik Gheysels posted a none generic starting point for me to head towards.



Frederik's idea almost compiled and after having a little re-jig managed to get it compiling and working how I expected it to ...



        private void Sort_version1(string propertyName)
        {
            // convert to List
            List<MyClass> myCurrentClass = Items as List<MyClass>;
            // sort
            if (myCurrentClass != null)
            {
                myCurrentClass.Sort(delegate(MyClass one, MyClass two)
                                        {
                                            PropertyInfo pi = typeof (MyClass).GetProperty(propertyName);
                                            return Comparer.Default.Compare(pi.GetValue(one, null), pi.GetValue(two, null));
                                        });
            }
        }


After looking at this, thinking before I was using the generic comparer and after the comment from Jon about the Generic one I decided that I would try and get to use the generic one and get the switch working from the type of the property ... if I could. So after putting in a break point into different places and inspecting the information I got back from PropertyInfo I decided that I would add a static method on MyClass to which would return true if the property existed, but also then return out to me the property class full name and the property info details (this could definitely be better!)



        public static bool HasDetailAndExtract(string propertyName, out string propertyType, out PropertyInfo propertyInfo)
        {
            PropertyInfo pi = typeof (MyClass).GetProperty(propertyName);
            propertyType = (pi != null) ? pi.PropertyType.FullName : string.Empty;
            propertyInfo = pi;
            return (pi != null);
        }


With this I could be a little defensive with the checking in the Sort method, but also perform the switch on the system type while still using the generic comparers which is what my original aim was.



        private void Sort_version2(string propertyName)
        {
            // convert to list
            List<MyClass> myCurrentClass = Items as List<MyClass>;
            string typeOfProperty;
            PropertyInfo pi;
            // sort
            if ((myCurrentClass != null) && (MyClass.HasDetailAndExtract(propertyName, out typeOfProperty, out pi)))
            {
                switch(typeOfProperty)
                {
                    case "System.String":
                        myCurrentClass.Sort(delegate(MyClass one, MyClass two)
                                                {
                                                    return
                                                        Comparer<string>.Default.Compare(pi.GetValue(one, null).ToString(),
                                                                                         pi.GetValue(two, null).ToString());
                                                });
                        break;
                    case "System.Int32":
                        myCurrentClass.Sort(delegate (MyClass one, MyClass two)
                                                {
                                                    return
                                                        Comparer<int>.Default.Compare(
                                                            Convert.ToInt32(pi.GetValue(one, null)),
                                                            Convert.ToInt32(pi.GetValue(two, null)));
                                                });
                        break;
                    default:
                        throw new NotImplementedException("Type of property not implemented yet");
                }
            }
        }


This all works as expected and overall I'm pretty happy with the implementation. I won't be putting it into the code I was originally writing at work purely due to the fact that this is getting more generic and would be overkill as the implementation I was doing at work was pretty specific but I'm glad I managed to get the result that I set out to get in the first place.



I guess the next challenge, when I've got time, will be to try again in vs2008 / c#3 and see how much more elegant I can get the code looking with the use of lambas and the other fun stuff in .net3.5.



As usual, any thoughts or questions then please comment and I'll reply as soon as possible!

Wednesday 7 January 2009

Sofa surfing

After a lot of talk I finally got round to moving my Mac Mini downstairs from the study and hooked it up to my tv over the festive period. It was good as it worked well at our new years party as we watched some youtube videos and played some of my music collection as we drank beer and ate vodka jelly :-)

At the weekend I decided I would buy a wireless keyboard / mouse combination so that it would be a better media pc in my livingroom and not have a random keyboard / mouse on the tv stand.

I found a reasonably cheap keyboard from ebuyer.com and its like a laptop layout without the monitor so I am able to type pretty fast without too many errors in a short amount of time. The keyboard I got is a KeySonic CK-540 RF. It was simple plug'n' play and worked within seconds of plugging it into my Vista install. Also today I booted into Mac OS X to do some updates and it recognised it and then had a couple of configuration questions to workout the keyboard layout but then worked first time. Very impressed with it so far, will post again when I've used it for a while and see how things go :-)

Friday 2 January 2009

IEnumerable Extension Methods

After looking over some questions on StackOverflow it got me thinking about extension methods. It's not really something which I have looked into much as I only use Visual Studio 2008 at home for personal projects. I stumbled upon one post about potential extension methods to add to a colaboration on CodePlex for everyones use. I was scrolling through some of the potentials to be submitted and came across this post. It intrigued me as the main method was converting an IEnumerable to a string with a separator ... so would convert an array of ints 1,2,3 into the string "1, 2, 3" if the separator was ", " ... I think you get the point.

However the way they were doing it was the usual "go through all the items, add the separator after everyone, then at the end take the last off". Personally when I see this I get a little sad. It's just not very elegant but also it means you don't harness the power of the framework ... which is what it is there for!

Side Note With the advent of .net 2.0 Generics was brought in. This opened up a whole world of fun for developers and a lot of useful things especially around the area of collections. If you've not looked at Generics I would highly recommend working your Google-Fu and doing some reading.

Anyway ... using generics I decided to refactor the ToString method for IEnumerable to use ToArray() of a List and string.join(). This might be a new way for some people of concatenating values together with a supplied separator. It leverages the power of the .net framework to do the work and avoids having to add an extra separator and then removing it once you have iterated through all the items in the list and performing the specified delegate function.

        public static string ToString<T>(this IEnumerable<T> collection,
Func<T, string> stringElement, string separator)
        {
            List<string> result = new List<string>();
            foreach (T item in collection)
            {
                result.Add(stringElement(item));
            }
            return string.Join(separator, result.ToArray());
        }


So moving on from this I thought that a List has a ForEach extension method which executes a delegate on each of the elements in the list; but not on an IEnumerable. This has been discussed and documented in so many places I'm not going to write about it here.  So what I wanted to do was break out the ForEach functionality out of the ToString implementation so it can be used injunction with it, but also by itself.


        public static IEnumerable<T> ExecuteForEach<T>(this IEnumerable<T> collection,
Func<T, T> function)
        {
            List<T> result = new List<T>();
            foreach (T item in collection)
            {
                result.Add(function(item));
            }
            return result.AsEnumerable();
        }


I made it return an IEnumerable<T> so it could be piped together to keep with the design of linq and lambda expressions etc. The limitation of this implementation is that it returns the same type as the type passed into the Func so you can't change the type, such as converting int to string. So take two came along ...


        public static IEnumerable<U> ExecuteForEach<T, U>(this IEnumerable<T> collection,
Func<T, U> function)
        {
            List<U> result = new List<U>();
            foreach (T item in collection)
            {
                result.Add(function(item));
            }
            return result.AsEnumerable();
        }


Same as the previous example, but with two different generic types, this enables the conversion of int to string, but also performing actions on the same types and returning the updated values eg. increment a list of ints.

With using the updated ExecuteForEach<T, U> (I decided on calling it ExecuteForEach as it will update / perform a function on each of the items in the collection and update them, not just perform an function on them) we can now update the ToString method call to be just two lines;  it abstracts the looping away into a different function which can be used again for different actions, but also uses the power of the framework with the string.join functionality.


        public static string ToString<T>(this IEnumerable<T> collection,
Func<T, string> stringElement, string separator)
        {
            List<string> possible = collection
.ExecuteForEach(t => stringElement(t))
.ToList();
            
            return string.Join(separator, possible.ToArray());
        }


A simple usage of this is ...


        public static string ToString<T>(this IEnumerable<T> collection, string separator)
        {
            return ToString(collection, t => t.ToString(), separator);
        }


... and the unit test to go with it ...


        [TestMethod]
        public void ToStringTest()
        {
            var ints = new int[] { 1, 2, 3 };
            var result = ints.ToString(", ");
            Assert.AreEqual("1, 2, 3", result);
        }


Hope this all makes sense, please let me know if you have any comments or thoughts about this :-)

Windows Live Writer

Well I've finally taken the plunge and found the MSI installer so that Windows Live Writer installs on my windows 2003 server dev virtual machine. This way I can write my posts offline while I'm on the train and hopefully have better control of the layout especially as I'm in the middle of a couple of posts which have code in it and formatting that via the web interface I'm finding tricky so will see how this goes.