Tuesday 22 December 2009

Worthy of a dailywtf post?

Just followed a link on Twitter to vote for best celebrity tweeter. So went through the list finding someone to vote for and got the following error:

image

Sweet! :-)

Monday 21 December 2009

Feedback module like MSDN in Asp.net MVC

Aim

Create a feedback module similar to the new one MSDN is using done in the asp.net MVC framework. This will including using some JQuery. Also I want to make it as steam lined and unobtrusive as possible. The functionality has to be user friendly but not interrupt current workflow.

image

This is the challenge … lets see how it goes!

Code

So the first issue which needed to be addressed was “how to get the view displayed?”. For this I initially turned to the Html.RenderAction() helper method and to render a partial view. I decided against this quite early on due to the restriction of posting actions back to the view which was nested into the main view. This seemed to cause issues with post backs and just felt wrong.

So decided to go the System.Web.Mvc.PartialViewResult route instead. To use this, the feedback controller required to return the PartialView for the actions which are required for this module of functionality.

Next was the flow of the interaction with the user; from clicking the initial link in the corner of the browser to submitting the comment, thanking the user and finally returning back to the original state.

To keep it simple, I kept the feedback model class very simple. This wasn’t the primary aim of this task so being able to submit a comment was good enough for this exercise.

namespace MvcApplication3.Models
{
public class Feedback
{
public string Comment { get; set; }
public DateTime Logged { get; set; }
public string UserAgent { get; set; }
public string Ip { get; set; }
}
}



Like I said, very simple :-)

So, time for the controller. Due to the flow I needed to display the feedback partial view, display the thanks partial view and the actual submit action code with the model binding.



using System.Web.Mvc;
using MvcApplication3.Models;

namespace MvcApplication3.Controllers
{
public class FeedbackController : Controller
{
//
// GET: /Feedback/

[HttpGet]
public ActionResult Get()
{
return PartialView("Feedback");
}

[HttpGet]
public ActionResult Thanks()
{
return PartialView("FeedbackThanks");
}

[HttpPost]
public void Submit(Feedback feedback)
{
// update to the date required for logging
feedback.Logged = DateTime.Now;
feedback.UserAgent
= Request.UserAgent;
feedback.Ip
= Request.UserHostAddress;

// and save

}
}
}



I limited the http verbs on the actions so that they are restricted properly. So, all the c# code has been written. Looking at this it seems straight forward and relatively simple :-)

All the views would need to be accessed from a central location, so I put them in the shared view folder (see solution explorer view below).



image



Site.Master



The site master is where the feedback button is situated as it appears on each of the pages which uses this master page. From a markup perspective we needed to add the button div itself and the div which the partial views will be loaded into.





    <div class="feedback-button" title="Click here to tell us what you think!"><a id="feedbackLaunch">feedback</a></div>

<div id="feedbackformDiv"> </div>




image



Where the magic happens is in the jQuery client side script. Instead of trying to explain it, I’ll just post it as we go and go through the highlights as the rest will be self explanatory.



        // global flag to display the feedback routine
var displayFeedback = true;

$(document).ready(
function() {

// display the feedback form
$('#feedbackLaunch').click(function() {

// depending on the feedback for, hide or show it
if (displayFeedback) {
$(
'#feedbackformDiv').load('/Feedback/Get').fadeIn("slow");
}
else {
$(
'#feedbackformDiv').hide();
}

// flip the bit
displayFeedback = !displayFeedback;
});
});


The main driving force of visibility is the displayFeedback variable. This has been declared at this level so that its scope is accessible from the partial views as well. The reason why I did this was that once the interaction flow had occured a double click on the feedback button was required to display the comment form again. This wasn’t required behaviour. I tried using the jQuery toggle functionality but this didn’t perform as required either.



Feedback.aspx



The partial view is where the main action happens. This is the main display form which prompts the user for the comment and to submit it.



imageThis is made up of the header which has a close button on it, and the main form with a simple submit button. The markup and script of the file is below:



<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication3.Models.Feedback>" %>

<script type="text/javascript">

$(document).ready(
function() {

$(
'#feedbackForm').submit(function() {

var action = $('#feedbackForm').attr('action');

$.post(action,
$(
'#feedbackForm').serialize(),
callBack);

return false;

});
// end of form submit function

});
//end of document ready function

// call back function to load in the thanks view
function callBack(e) {
$(
'#feedbackformDiv').load('/Feedback/Thanks');
}

// close the feedback and reverse the displayfeedback bool value
function closeFeedback() {
$(
'#feedbackformDiv').hide();

if (displayFeedback != undefined) {
displayFeedback
= !displayFeedback;
}
}

</script>

<div class="feedback-ui">
<div class="feedback-ui-header">
Please leave some feedback
<div class="feedback-ui-header-close">
<a href="javascript:closeFeedback();">x</a>
</div>
</div>
<div class="feedback-ui-panel">
<form action="<%= Url.Action("Submit", "Feedback") %>" id="feedbackForm" method="post">
<p>
<%= Html.LabelFor(model => model.Comment) %>
<%= Html.TextAreaFor(model => model.Comment, 5, 50, new { Width = "350px;", Height = "150px;" }) %>
<%= Html.ValidationMessageFor(model => model.Comment) %>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
</div>
</div>

This is all relatively straight forward, the main bit to notice is the  serialize method on the form jQuery object. This serializes the contents of the form to the action. I originally thought this may get in the way of the model binding with the mvc framework into the action, but it magically sorts itself out. Genius!

The other part of functionality is the call back function from the form submit action. Very simply, this just loads in the next partial view to thank the user for submitting their comment to the team.



FeedbackThanks.aspx



The thanks form is very simple. Just a way of displaying a thank you note to your users and then disappear again leaving the user where they were, as if it never happened.



3



All the client side javascript does is after a defined time hit the thanks form you see above and invert the boolean variable to make the show/hide work correctly.




<script type="text/javascript">

$(document).ready(
function() {

setTimeout(
function() {
$(
'#feedbackformDiv').hide();
if (displayFeedback != undefined) {
displayFeedback
= !displayFeedback;
}
},
2000);

});

</script>

<div class="feedback-ui-thanks">
<div class="feedback-ui-header">
Thanks
</div>
<div class="feedback-ui-panel">
Thanks for helping improve our application.
</div>
</div>



And that’s it.



Summary



So what have we learnt from this little exercise:




  • Creation of views through the Visual Studio tooling for Asp.net MVC


  • jQuery basics – selectors, built in functions and basic dom manipulation


  • Partial view actions through controllers


  • Strongly typed model formatting



Additional extension points which would be good to plug in would be:




  • Additional fields / different types of feedback options


  • Response validation



What’s next?!



Well over the next couple of months I will be working on some interesting things and techniques and I hope to find time to share some of them with you all. If you have any suggestions of things to do, or any improvements then please leave a comment or get in contact through twitter.

Tuesday 1 December 2009

WCF and serializing custom objects

I’ve been setting up an wcf service for a new n-tier system which I am currently architecting and developing at work. I’m trying to get to the point where all tiers store the data in the same objects (Entities) and they are worked on at different levels. These are simple POCO Entity objects which only store the data values and defined the data annotations to be used with validation. This will require the WCF service to be able to serialize the custom objects and transmit them between the tiers and in future, who knows maybe to a Silverlight client application as well?!

So, with the objects in place and with the correct DataContract and DataMember attributes in place I get the following error message when trying to pass them through the service between tiers:

“The underlying connection was closed: The connection was closed unexpectedly.”

After doing some Googling I came across the following blog post which had some handy pointers … thanks Bishoy Labib. But the biggest help was from a post by Damir Dobric. His post explaining how the "KnownTypeAttribute” is used when sending through data over a wcf service was very handy.

So after decorating the interface with each type of Entity I had which (3 so far) I built the project, got the service reference to update to get the latest definition and ran it with fingers crossed … it worked!

Damir had adding each of the types which might be used through the WCF service interface defined individually, then refactored it by adding them through the KnownTypeContainer (similar to below) and added them manually. This wouldn’t quite work for me as there are going to be, probably, lots of entities and I don’t want to have to add one individually each time. As all the entities are defined in a single project, I thought with a little reflection on the Assembly I could dynamically load them in so came up with this …

[ServiceKnownType("GetAllMyKnownTypes", typeof(KnownTypeContainer))] 
[ServiceContract(Namespace
= "http://mynamespace/2009/IApplication")]
public interface IApplication
{
[OperationContract]
string Echo(string value);

[OperationContract]
Entities.EntityBase Execute(
string action,
Dictionary
<string, object> parameters);
}

static class KnownTypeContainer
{
public static IEnumerable<Type>
GetAllMyKnownTypes(ICustomAttributeProvider p)
{
return new List<Type>(
Assembly.Load(
"Entities").GetTypes()
);
}
}




Nothing special, or clever, just need to make sure that all the Entities derive from the common EntityBase abstract class to work.



Thanks go to Damir for the original post and getting me through my issue I was having :-)

Thursday 26 November 2009

Code formatting

Wrote a while back about not using Windows Live Writer as it was a pain and the code formatting was poor etc. well I’ve started using it again the past month due to being able to start multiple posts and edit them all at once etc etc. I’ve needed to post some source code recently (which I’ve not actually posted yet) and I went on the hunt for another plug in to make the code nicely formatted and came across Code Formatter for Windows Live Writer. Downloaded, extracted the files to the live writer plug in folder and fired up windows live writer and seems to work fine. :-)

Some demo code as an example:

    [HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData[
"Message"] = "Welcome to ASP.NET MVC!";

return View();
}

public ActionResult About()
{
return View();
}
}


Will let you know how I get on with it when I post a more in depth post :-)

Sunday 22 November 2009

Naming convention rant (no. 2)

I know it comes down to personal preference when it comes down to naming and I know it has been ingrained into me due to the people I have worked with over the past few years, but why do some people continue to do such things in this day and age.

Enums

Everyone who codes should know what an enum is, if they don’t then they either don’t code much or never use much if any of any frameworks which are out there. Either way then they should be looked and used; they are good!

Anyway, when someone writes their own enum to use instead of special strings or numbers then why prefix the enum with the string ‘enum’.  It’s not a enumOrientation it’s Orientation! etc. etc.

Class Names

I know this comes back to my rant the other week about the use of namespaces, however I came across another example with class names in another project which all the names of the classes where prefixed with the name of the last part of the namespace they where in.

So for example it was for a twitter app, and the namespace was <blah>.Twitter, and one of the classes was called TwitterRequest. I know this doesn’t sound bad in itself, but the fully qualified name of it would be <blah>.Twitter.TwitterRequest. This shows the issue I’m trying to portray. If its a Twitter request, then it should be in the twitter namespace and called Request. If it’s not a request to do with Twitter then it shouldn’t be in that namespace. Hope I’m making sense.

I just don’t understand why someone would do this? I think I might just be turning into a naming obsessive :-)

If you can’t think of a good name for one of your new classes then why don’t you try the class namer :-)

Wednesday 18 November 2009

Smtp4dev

Ever had to setup a local SMTP server when you’re developing some functionality but don’t want the emails being sent out by accident?

I’ve had a couple of systems which I’ve written over the years and been a little paranoid each time that some test emails will be sent out to a live email address. This stems from a project I worked on a while back and had to send the system to the company development team so they could do some in depth testing/debugging and they ended up sending over thousand emails out to the client ;-)

Any how …

I went to setup an SMTP server locally to do some testing today and found out that Windows 7 doesn’t have a built in SMTP server option anymore so went on a Google hunt. After doing some searching I came across a few free server options, but the one which caught my eye was on Codeplex. My initial thought was “Woo, can see how they wrote it if I want to” and the description was spot on …

Project Description
Dummy SMTP server that sits in the system tray and does not deliver the received messages. The received messages can be quickly viewed, saved and the source/structure inspected. Useful for testing/debugging software that generates email.

Anyway, I downloaded the latest build of smtp4dev as it seemed to fill all my requirements; a) does not deliver email and b) doesn’t interfere with anything else. 

The description was spot on, and so far so good it works as required. Will post an update once have used it a bit more.

Hope it helps others out in the future. Let me know if this helps you!

Asp.Net MVC 2 Beta released

After checking my morning blog feeds the first one in the list which was of interest was Phil Haack’s post about the release of Asp.Net MVC 2 Beta for VS 2008. I was going to put off downloading it and updating until later but after the teaser about nuclear facilities in the Eula I had to investigate …

This was the full Use rights which he was referring to:

a. Because the software is a pre-release version, and may not work correctly, you may not use it, alone and/or in conjunction with other programs in hazardous environments requiring fail-safe controls, including without limitation, the design, construction, maintenance or operation of nuclear facilities, aircraft navigation or communication systems, air traffic control, and life support or weapons systems.

I should read EULAs more often; Genius!

Tuesday 10 November 2009

Windows 7 Aero snap shortcuts

I was browsing through my regular blog feeds this morning and the tweets which had happened over night this morning and I came across the following link. It’s posted in the context of Visual Studio 2010 Beta 2, however it works for any window which is currently selected.

As I use a duel screen setup at work and manually dragging/snapping the windows to the side of the screen only work at the far edges of the entire desktop real estate these short cuts enable halving both screens spot on.

The short cuts which are starting to be high up on my most used list are:

Dock to Screen Left : Windows + Left Arrow
Dock to Screen Right: Windows + Right Arrow

I’m lovin’ Windows 7!

Monday 9 November 2009

Have people not heard how to use namespaces?!?!

I’m trying to work out how something works and it’s over mulitple dlls. This is fine in the grand scheme of things. They aren’t large dlls either and the names of them gave me hope that it would be well designed. One has the data access code, one with common code and one with the business rules. Three projects working together isn’t large at all. I’ve worked with Visual Studio solutions with almost 100 projects in, so how hard could this be … ?!

So far so good …

That was until I started looking at the names of the class definitions. This is the point when I wanted to bang my head on the desk!

In the data access dll, it has a data access namespace, yet all the class definitions are prefixed with ‘dal’.

Why?!

In the business rules dll, it has a business rules namespace, yet all the class definitions are prefixed with ‘br’.

No seriously, why?

And to top it all off, the data entities are in the the 3rd dll, all post fixed with ‘Data’ … this in itself isn’t bad, except the namespace is ‘Data’ so that kinda makes the post fix redundant.

And don’t get me started on the name of the dll … and no it doesn’t even have the word ‘data’ in it (see the opening paragraph ;-))

Why would you do that?!?!

*hithead*

I’m on Twitter!!

I’ve signed up to the revolution, you can follow me @WestDiscGolf.

What are you up to today? :-)

Wednesday 4 November 2009

Visual Studio 2010 Beta 2 initial thoughts

Just thought I’d post a small brief entry about my initial thoughts of Visual Studio 2010 Beta 2. So far so good I like it, the layout is nice, the tooling improvements are good, the response speed of the IDE has improved quite a lot … however, I won’t be using it full time until there is a version of Resharper which works with it; I’m lost without the R# power!

:-)

Tuesday 27 October 2009

TFS 2010 Beta 2 unit testing automated builds

I’ve been setting up Team Foundation System 2010 Beta 2 at work over the past couple of days. First starting off with doing it on a virtual machine locally to do some testing, but then deploying it into the virtual server environment we’ll be using it in for every day development.

I was initially very impressed by the ease of setup of the system. Talking to people and ready some blogs about setting up previous versions of TFS it was a complete pain with caused serious issues with server setup, permissions etc. TFS 2010 is soooo simple in comparison. Microsoft have thought about this side of things a lot and made setting it up very simple.

We went for the basic setup as we don’t need a lot of power or more than source control, automated builds and work item tracking.

Anyway, setup of the machine was fine and enabling communication between the tfs server and my laptop running Visual Studio 2008 sp1 was fine (just needing to make sure that Team Explorer is installed, followed by running the VS SP1 setup again, then the forward compatibility patch) and the first solution of code was checked in. A small utility dll project and associated unit test project. As the plan is to use this utility in all future development, a “tool kit” as you would, it made sense that this should be setup to have an automated build. It would also enable me to learn how to setup automated builds.

Enter first issue, no reference issues relating to “Microsoft.VisualStudio.QualityTools.UnitTestFramwork.dll”. Due to this issue the test project could not build as it had references to a namespace it couldn’t find.

C:\Windows\Microsoft.NET\Framework64\v3.5\Microsoft.Common.targets: Could not resolve this reference. Could not locate the assembly "Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

To resolve this initially I installed the C# components of Visual Studio 2010 Beta 2 on the server. I had originally just done the unit testing parts but this didn’t resolve the issue. The obvious issue with this is that we don’t want to have the full version (or any part of) Visual Studio installed on the server so I did this on a VM locally to see if resolved the issue … it didn’t :-(

Break through

After doing some more search on Google, I found this post from Grumpy Wookie about the location of the gacutil in the SDK, and another link (which I can’t seem to find in my history, sorry) relating to the fact that there aren’t the correct versions installed in the GAC on the server. So after checking the versions and seeing there weren’t any there …

I copied the following dll from my dev machine (with VS2008 on):

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

To

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5

I then opened a cmd prompt on the server and navigated to where the SDK resides and ran the following cmd:

C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin>gacutil.exe /i "C:\Program File
s (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PublicAssemblies\Microsoft.Visua
lStudio.QualityTools.UnitTestFramework.dll"

This loaded version 9 of the UnitTestFramework into the GAC. This allowed for the automated build to run and to run the unit tests in my solution. Only issue now is the fact that it seems to be running with v10 MSBuild/MSTest with the v9 unit test assemblies and because of that it doesn’t like the one test which is using the ExpectedExceptionAttribute. At the moment I can live without this test being run on the server … but roll on march when the full version of TFS/VS 2010 come out and I can upgrade my development environment.

Hope this helps.

Visual Studio 2008 + IIS 7 development

At my new job part of my role is to bring most of the current website development in house for the 8 websites we currently have. Due to this I have decided to instead of just run them on the built in development web server which ships with Visual Studio and launches when you hit f5 with an address something similar to http://localhost:58697/Website1 to setup individual websites in IIS to best replicate the production environment. This is possible as IIS 7 on Windows 7 allows multiple websites on the client OS.

To do this I did the following:

1. Create a new website in iis 7 manager console; setting the host name to <identifier>.localhost

image

2. Update the hosts file to point the local loop back ip address to know about this new host name. Open the hosts file found in C:\windows\system32\drivers\etc\ and add the following line:

127.0.0.1                         website1.localhost

3. Open the Visual Studio solution (as Administrator) with the website in and navigate to the property page of the website. Navigate to Start Options > Server > Use custom server and set the Base Url to http://website1.localhost

image

4. Hit f5 in Visual Studio and run it.

I hope this helps anyone looking to do a similar thing.

Enjoy :-)

Saturday 24 October 2009

Health, Life and beer – Update

It’s has been a very long time since I last posted with regards to anything, so I hope you have read my latest “geek” post about Windows 7 on the eve of its full release to the public. From reading a couple of tweets from various people I can see that if it was pre ordered it has already arrived in some cases … so enjoy!

Well there has been a lot going on since my last post, so I’m going to give you a quick “run across the roof tops” to use a project management phrase :-)

July ‘09

First wedding anniversary, doesn’t time fly! Lau and I went to Barcelona for the weekend and did the tourist thing. Saw all the important sites. Walked around the outside of the Gran Familia (defo spelt wrongly) and the Gaudi style constructions. Went past the Nou Camp which is an impressive sized stadium!

August ‘09

Found out that I would be to take part in a consultation period at work to potentially be made redundant. This was a bit of a shock to the system to be honest. On initially being told I thought I’d be ok, but when we had a more detailed discussion it was made clear that, unless something big happened, that I’d probably be going at the end of the process.

Also, went to Beaminster to play disc golf and Lau and I went to Bulgaria for our proper summer holiday :-)

September ‘09

Played in the Croydon Cyclone disc golf event which was awesome. Avery Jenkins (Current Open World Champion), Val Jenkins (Current Open Women World Champion) and Nate Doss (2 x Open World Champion) came over from the Euros on the way back to the US, via London to play in the event. I had the pleasure of playing my first round in the same group as Avery. It was awesome to watch someone with that much talent for the sport play, it was also good fun with the banter between us all.

Unfortunately, I also found out I’d be leaving my employment in October as my role would be redundant. This was a bit of a kick in the teeth. Both due to the fact that I had put a lot of time and effort into my job for the past 2 years 9 months, but also as I wouldn’t get to see my all my friends which I had made every day. This was the biggest rubbish point!

October ‘09

Bit of an up and down month so far, obviously the down was the leaving my employment in Reading and nearly all contact with Reading. This is the first time in over 7 years which I haven’t had very regular visits. This in itself was a little sad. On the upside we had a pretty good send off, drank quite a bit, danced a lot … it was good!

On the upside, I have started my new job based in Warwick. Obviously this is a lot closer for me than Reading. It does however mean that I need to drive to work now, although toying with the idea of cycling in the summer (when I’m a bit fitter). Been here a week and so far so good, everyone is really nice. Yesterday I finished the first bit of development work to be used in the building and demo’d it. I’ve also started going to the gym for a run/workout a couple of mornings a week. This will help me loose weight, get fitter and recover from the shoulder damage ready for disc golf practice ready for next year.

As for beers and exercise I’ve kept a rough log of what has been going on, so this is now the updated “goings on” with the first thousand beer “challenge” (see below).

Also since August I have been kinda doing Weight Watchers with Lau (who is a member). As we both could do with loosing some weight and we are both very competitive, this has obviously turned into a competition which I was winning until we went on holiday and my redundancy etc. but now less than a pound behind, I will catch up!!

Current weight loss (since Aug) : 9 7/8lbs

Current Status : Bad!
Beers: 386
Miles: 97.3 (gym: 64.3; road: 33)
DG Rounds: 62
Gym visits: 70
Lengths : 51 (total: 512)
Key
Good => Exercise > Beers
Level => Exercise == Beers
Bad => Exercise < Beers

Wednesday 21 October 2009

Windows 7 used in anger

I’ve been using Windows 7 from the RC now on my Mac Mini for a couple of weeks. I’ve got all the usually required applications installed; Firefox, Visual Studio etc. and have been relatively impressed by the experience.

On starting my new job last week I was given a pretty powerful Dell Vostro 1720. Its hasn’t got the highest of build quality, but it is packed fully of goodies including 2.6Ghz duel core cpu, 8gb ram, 512mb dedicated graphics card with a 1920 x 1200 resolution 17inch screen which is very crisp.

Anyway, I digress … at work I’ve got an MSDN subscription which allowed be to download the released version of Windows 7 64-bit and install it. I’ve now been using it close on a week and it feels like forever. The user experience is good and it feels very natural to go to from Windows XP. I had used Vista a couple of times before and just hated it with a passion. It was just slow and clunky.

I know the user experience including the speed is down to the components in the machine, but it runs in RC on my Mac Mini at home pretty comfortably and that doesn’t have much power or ram. I’ve also seen people running it on netbooks, something you wouldn’t even think about doing with Vista. Due to being pretty impressed so far with the OS I thought I’d put together a top n things I like about Windows 7. It would also give me the opportunity to look back on it in a few months time and see if I’m still impressed by it and if its still the same things which are good.

Top 4 “likes” about Windows 7

1. Speed  - The general speed of it is good. Quick recovery from hibernation, good reboot speed, general usage gives good response time.

2. Taskbar organisation – I love the way the task bar is organised. The pinning of applications to it, keeping all the icons together, being able to drag and drop them into which ever order you like is brilliant.

3. Multiple Monitor support – Brings an all new meaning to ‘plug ‘n’ play’ support. Plug in your second monitor for the first time, configure it correctly (location, resolution etc.) and thats it; done! Un plug it, take your laptop home, come back in, plug the monitor back in and it auto recognises it, goes back to the previous setup. No pushing laptop function buttons and waiting for the screen to refresh!

4. Window docking – There are little applications out there to automatically set the active window to half the screen, move it left and right etc. but the built in window docking in Windows 7 does for me. The high screen real estate which I’ve not got makes putting applications half screen usable … just drag them over to the side of the screen you want and *poof* automatically half the screen. My only niggle about this functionality is that when you’ve got 2 monitors it acts like a single screen so you can’t dock left and right on both screens which is a bit of a short fall, but other than that all good!

Sunday 21 June 2009

Weekend ups and downs ...

So little weekend up and down; didn't drink at lunch time on Friday but met up with Phipps for a cheeky catch up beer. He's buying a house and moving on Tuesday! It's an exciting time!

As for the rest of the weekend, I wasn't working so it was a good weekend! I've just got back from the gym and had a nice 5km (3.1 miles) run and a work out. It all helps towards the ratio! :-)


Current Status : Bad!
Beers: 271
Miles: 47.4 (gym: 14.4; road: 33)
DG Rounds: 49
Gym visits: 64
Lengths : 48 (month: 0; total: 486)

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

Tuesday 16 June 2009

Week so far ...

Last night was another evening of disc golf practice which involved essentially starting the final 9 jungle holes which the finalists in the Adv Am and Open divisions play, but ended up playing a few additional holes. All in all another nice evening of golf, it all helps :-)

Current Status : Bad!
Beers: 270
Miles: 44.3 (gym: 11.3; road: 33)
DG Rounds: 49
Gym visits: 63
Lengths : 48 (month: 0; total: 486)

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

Monday 15 June 2009

Quick Update

So after the day of work yesterday I thought about going to play some disc golf but decided I'd go to the gym instead for a short ish run and work out.

So 1 weights work out + 3.2Km later ... It's another 2 miles to a ratio :-)

Ratio still bad though! :-(

Current Status : Bad!
Beers: 270
Miles: 44.3 (gym: 11.3; road: 33)
DG Rounds: 48
Gym visits: 63
Lengths : 48 (month: 0; total: 486)

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

Sunday 14 June 2009

A weekend of strength and weakness

This weekend has been a bit up and down with stuff.

Friday evening Lau, my sister and I went to the theatre in Birmingham to see Return to the Forbidden Planet. I'd been quite excited about this as it is probably one of my favourite musicals and I've seen it a few times. I hadn't clocked when we booked the tickets that it was an amateur performance, so it didn't have the double drum kits built into the stage, it didn't have the characters playing the instruments through the show etc. so was a little dissappointed. On the up side it was a bit of a giggle. After we went out for dinner and I was weak and had a couple of pints of San Miguel. It was Friday night afterall!! So with 2 weeks of no beer the drought had been broken.

Yesterday to make up for it I went to the gym, went for a run and a weights workout. I've not ran for a couple of weeks and it's suprising how quickly you loose the base fitness so did 5km in under 33 mins which was ok. Felt it at the end though.

An to top off the madness of the weekend I'm now sitting in my study looking out the window at the nice weather and our resident birds flying to / from their nest, which is attached to our house, waiting for unit tests to run! Yep, that's right ... tight deadlines etc. means working the weekend again. I don't mind doing it as it will mean we exit dev on time etc. but I would prefer to be playing disc golf. :-)

Anyway back to it, they've finally finished!

Current Status : Bad!
Beers: 270
Miles: 42.3 (gym: 9.3; road: 33)
DG Rounds: 48
Gym visits: 62
Lengths : 48 (month: 0; total: 486)

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

Friday 12 June 2009

A couple of weeks on ...

So the past couple of weeks have been a bit mad. I've not been able to get to the gym due to work and being too tired when I have finally finished work. Last week was a long old week with working the evenings once I got home each night except for Friday and pulled over 55 hrs. Due to this no additional miles where run, however with a some practicing / warm ups over the weekend and 3 competition rounds of disc golf and also club night on Wednesday I've done 5 rounds of disc golf!

As for the tournament, I didn't play great but I did learn a lot through different shots etc. I drove a couple of times with drivers and they all went a bit way ward, so decided to drop down and use my Buzzzz. This had the downside of not getting far enough to get birdies, it did however add some acuracy to my play and on Sunday morning when I only used a Buzzz for drives I shot my best round of the weekend.

On Wednesday evening after some driving practice and trying out a couple of different discs I had another round with Rich and only used my Buzzz (mainly) again. Starting on hole 10 it was an interesting start which was ok but could have been better. Once we got round to hole 1 I only used my Buzzz exclusively for drives and shot an even par. I was 1 under until I grip locked on hole 8 so had to recover for a 4. So for that I was very happy. Now why can't I play like that in tournaments?!?!


Current Status : Bad!
Beers: 268
Miles: 39.2 (gym: 6.2; road: 33)
DG Rounds: 48
Gym visits: 61
Lengths : 0 (month: 0; total: 486)

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

Monday 1 June 2009

First 10km

Yesterday afternoon was my first 10km run. It was mainly just to see if I actually could do it. I set the speed at 8km/hr and just kept at it. It was the discipline which was required which was the most interesting part of it. Both the sticking at a steady speed and not changing it and potentially bringing the run to an end early, but also mind over body determination to carry on when your body is saying "why are you doing this?!".

So first 10km was done in 75mins ... this equates to 6.2miles (which is what I measure on below).

I've decided to take running at the gym into account, otherwise I'll never recover the deficit, also if I run 10km I'd only get 1 in the positive pot ... that sucks ... and I make the rules :-)


Current Status : Bad!
Beers: 268
Miles: 39.2 (gym: 6.2; road: 33)
DG Rounds: 43
Gym visits: 61
Lengths : 0 (month: 0; total: 486)

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

Sunday 31 May 2009

Beer free starting measurements ...

Right; beer free, exercising and weight loss starts now ...

Starting weight : 12 stone 4 1/2
Chest : 39 1/2 inches
Belly : 36 inches

Monday 25 May 2009

Long time no post ...

... because of many reasons. The lack of posting over the past few months is due to a few reasons mainly work related and not wanting to look at a computer screen after a day at work. This in addition to being shattered (due to work) and that's pretty much it.

We've had some pretty tight deadlines recently and due to this long hours and weekends have needed to be worked. This has prevented me from going to the gym and playing disc golf as much as I'd have liked. It makes going to the fridge and grabbing a beer very easy and this is very much the anti exercise :-)

What's been happening over the past few months?!

Well I've been working quite a lot. We've had some pretty big projects coming through dev recently and the deadlines have been incredibly tight. Some of the have involved working late, working weekends, working late weekends and the days I have left the office at a reasonable time I've got home and the last thing I wanted to do was open my laptop and do anything.

Unfortunatly my PDGA rating has gone down again in the latest update. This is bad! I thought I played ok in Feb at Frostbreaker, and I did, but I was a little out of practice and my fitness levels weren't as high as they should have been for an event there. To top it off it was made up of 2 rounds of 27 holes was over 5 hrs straight of golf with no breaks each day. It was a lot of fun though!

On top of that the Quarry Park Spring Fling was 4 rounds of 18; 2 per day. This was also tough, added in with the really crap weather we had it didn't help my rating. On the Saturday I shot my worse competative round there in about 3 years. On the Sunday thinking things couldn't get any worse I ended up shooting my worse competative round there ever! Something needs to be done!

I've been out recently and thrown pretty well although I have been injured twice, once hurt my right shoulder after slipping down the bank on hole 13 and putting out my arm to stop myself (stupid reflexes!) and it jarring my shoulder quite badly. And recently second to last hole threw a forehand approach on hole 17 and just pulled my arm. It hurt a lot! So hopefully will be fit again (arm wise) by the QP open in a couple of weeks time!

Health review - Feb, March, April and May

Well the health review for the past few months has been lacking a lot. I've got rough numbers for Feb but March, April and May will be educated guesses. But recently I have increased my running. I've been averaging between 5 and 10km a week. All on the treadmill as my knees and shins are trying to get use to running again. I've only counted this as a gym visit though so still being out weighed by beer :-)

The reason behind increased running is I want to loose some weight and hit my target I set myself back at the beginning of Feb. I managed to get down to 12 stone before I went to Frostbreaker, but recently that has creeped back up to a steady 12stone 4. I'm still aiming for 11 stone 7 before going down to dorset in August, so that gives me 2 months to loose the best part of a stone. Can this be done? Well thats the challenge. As part of this I'm going to give up beer in June and beyond if it helps :-)

Rough numbers / estimates of beer and exercise over the past few months :

Feb : 6 dg rounds, 6 gym visits, 16 lengths, 27 beers
Mar: 6 dg rounds, 10 gym visits, 0 lengths, 30 beers (including dev social)
Apr: 4 dg rounds, 12 gym visits, 0 lengths, 25 beers
May: 2 dg rounds, 10 gym visits, 0 lengths, 25 beers (including dev social)

So that estimately equates to :

18 rounds of disc golf (including hurt shoulder and elbow so should have been higher!)
38 gym visits
16 lengths
107 beers

June - no beer!

So no beer in June; it's going to be interesting. We've got some interesting deadlines coming up at work and for a dev beer is a good way to relax. I've decided that if I get home and want a beer I need to make myself go to the gym for a run. It will take my mind off it.

In additon to the weight loss and general fitness I've taken up running again as Lau and I are going to run in a 10km "fun run" in September and my initial target was to do it in 1 hr 10mins which seems reasonable. But if I push it and train well I think I could do it in an hour. 10km / h isn't back breaking but it's going to take a bit of dedication and effort to do it. That is the challenge!

The running is going ok generally. I've been running 3 to 5 km each time I go to the gym with my best so far of 5km is about 32/33 minutes. I need to start getting my body use to running for a longer period though. So I'm going to cut down the speed and try and increase the stamina and then work up the speed. I'm quite excited about training for the run and not drinking beer will help me loose some weight as well.


Current Status : Bad!
Beers: 268
Miles: 33
DG Rounds: 43
Gym visits: 61
Lengths : 16 (month(s): 0; total: 486)

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

Sunday 1 February 2009

1st Feb - Initial weigh in

Woke up, weighed myself ... 11 stone 13 pounds 5/8ths!! WOO!!! It's been ages since I was in the elevens!!

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!