Wednesday, August 31, 2011

SABC TV Licenses

So I get this nasty letter the other day, demanding I pay my TV license. I then proceed to tell them I have. I am then requested to provide proof of payment. So I attach it to an email and distribute it to the SABC and their debt collection agency. This was three weeks ago. Today I get this:

 

Your message
   To: Justin Dorkin
   Subject: Outstanding TV license account - TV License No: *******
   Sent: Thursday, August 11, 2011 9:24:23 PM (UTC+02:00) Harare, Pretoria
was deleted without being read on Wednesday, August 31, 2011 9:50:29 AM (UTC+02:00) Harare, Pretoria.

Though it was funny how it was “demanded” of me to pay and prove it yet when I do comply it is not even considered.

Monday, August 29, 2011

mDesktop–Multiple dekstops on Windows 7

I have been quiet annoyed for sometime now because I cannot have multiple desktops. I was using a product called Dexpot but it for some reason stopped working so I went fishing to see what I could find. Every desktop manager I came across was bloated, didn’t work properly and just didn’t fit the bill. I wanted a light weight desktop switching application for Windows 7.

 

I was just about to give up and start writing my own when I cam across mDesktop. Brilliant! Light weight, small foot print. Very cool.

 

You can find it here http://ping.fm/dx9au

 

Cheat sheet:

Alt+Desktop Index (e.g. Alt+1, Alt+2...) switches between desktops

Alt+Ctrl+Desktop Index sends the active window to the Desktop Index

 

Happy days! Perhaps Microsoft will catch a wake up one day regarding multiple desktops. The API is there, can’t for the life of me figure out why they haven’t done this.

Friday, August 26, 2011

C# Arrays, extension methods and the way not to do something

Right let me first start of by saying, the problem that this code solves should never exist, and I mean NEVER! There is no good reason to have to do this unless you have a legacy system that has all of a sudden had the carpet pulled out from underneath it, you have to add new functionality and if you don’t get it done on time (which is the next three days) the world will end. Seriously though, avoid this at all costs if you possibly can.

Right that being said, I had a problem where by thousands of lines of code had been written against a SOAP service which made use of collections had been written many moons ago. Recently the definitions changed and all the collections were now arrays! The proxies are generated against svcutil and yes I know there is a switch to use collections as opposed to arrays but I entered the project at a time were it had been decided to convert all the code using the collections. Right this posed a significant problem in that myObject.Collection.Add() no longer existed.

My first thought (yes perhaps not one of my greatest moments) was to do this

//given 
myObject.Collection.Add(myNewItem);

//Convert it to
myObject.Array.ToList().Add(myNewItem);




Now for some reason this made sense in my head till I did it and found out it wasn’t working. Why wasn’t it working? You guessed it! The instance of ToList() was not being assigned to the collection. DOH!





Well my next solution was to implement a generic method that converted the array to a list, added the item then converted the list back to an array. Something like this.





   1: public class ArrayHelper{



   2:     public static void Add(ref T[] array, T input) {



   3:         if (array == null)



   4:             array = new T[0];



   5:     



   6:         var list = array.ToList();



   7:         list.Add(input);



   8:         array = list.ToArray();



   9:     }



  10: }



  11: //Usage would be



  12: ArrayHelper.Add(ref myObject.Array, myNewItem);




Well that looks a bit better and the best part? It works! Well kinda Sad smile When running performance tests on it it turned out that adding 5000 items to this array it would take 71 milliseconds as opposed to the 2 milliseconds to do it natively. What a bummer. Well back to the drawing board I guess. This means if it takes 0.0004 milliseconds to add one item natively it would take 0.015 milliseconds to add one time using this method. This equates to 37.5 times longer!



I then came across Array.Resize and figured I would see what that does. So the method became:





   1: //Class definition



   2: public static void Add(ref T[] array, T input){



   3:     if(array == null)



   4:         array = new T[0];



   5:



   6:         Array.Resize(ref array, array.Length + 1);



   7:         array[array.Length - 1] = input;



   8: }



   9: //Usage remains the same




This method took 10 times longer to add 5000 items. This means it would take 0.004 milliseconds to add one item. A bit more acceptable. Now thinking I am the cheese I wanted to wrap this into an extension method. My first attempt failed so I started looking around if anyone else had done this. Seems someone had http://these-pretzels-are-making-me-thlrsty.blogspot.com/2010/05/c-extension-method-bummer.html and verified what I was too scared to admit, it wasn’t going to happen as an extension! Again this is an elegant solution to a problem that should never have existed.





Oh well …





References:





//given

myObject.Collection.Add(myNewItem);



//Convert it to

myObject.Array.ToList().Add(myNewItem);



    Thursday, August 25, 2011

    In Flames “Sounds of a playground fading”

    In Flames has without doubt, in my opinion produced a master piece with this new album. The sound is raw, something I noticed in the Iron Maiden album “Final Frontier”. It is not over produced, it is just right. I really hope this becomes a trend with current bands, letting the musicians abilities speak as opposed to post production covering everything up leaving you with a thick soup lacking any texture, very quickly becoming unpalatable.

     

    The new album sees In Flames go back to the roots of their art as first displayed in “Whoracle” (which is still one of my favourites). The guitar harmonies are back, holes of silence appear filled with nuances that add flavour back to their music.

     

    The great metal bands of old can be heard as their influences again which I truly enjoy. Yet even though the influences can be heard the overall sound is still undoubtedly their own. The best part out about the album is the price. I cringed as I asked what the price of the disk was and was pleasantly surprised to hear “R139.00” as opposed to the “R270.00” I had become accustomed to. Basically half price! Could this drop in price be due to the fact that people can now buy single tracks online and the demand for hard media is dropping? I certainly hope the downward trend in pricing continues because it became seriously out of hand at a stage in South Africa.

     

    Well that is that, fantastic job to In Flames and all involved in the new album. I am thoroughly enjoying it and cannot wait to get it onto my portable player and give it a listen while taking a long ride. I love the strong anthem flavour prevalent in most of the tracks and take my hat off to the craftsmanship. Perhaps a change in line up is what the band needed to stabilise itself again? Though it is sad to see a member leave sometimes change allows retrospect and a realigning back to the original vision that got them to where they are.

    Ard Matthews and the botched South African national anthem.

    Look, I am going state outright that I don’t like the guy’s music. I never have and I never will. You might and that is your prerogative. In terms of marketing and producing something that sells, well he seems to have got that right so credit where it is due I suppose.

     

    Right, now on to the South African national anthem. Lets be honest, I mean brutally honest. When performing a national anthem you generally are going to be unaccompanied with very little effects. This mean you best have a vocal range above or below a semi-tone. I am sorry but it is the truth. Singing in a studio now a days is one thing. Stacks of pitch correctors, reverb, echoes and many more things to make you sound like a rock opera singing. Multiple takes to get it right, pitch shifting and the list goes on and on!

     

    Then we move on to live gigs performing with your band. Generally the sound is so out of whack, levels are all over the place and then add in the alcohol and weed floating around ANYTHING is going to sound good.

     

    Then we look at the national anthem. First let us define national anthem:

    “A national anthem (also national hymn, song etc.) is a generally patriotic musical composition that evokes and eulogizes the history, traditions and struggles of its people, recognized either by a nation's government as the official national song, or by convention through use by the people.”

    http://ping.fm/veRiY

     

    So with that in mind let us consider what a good candidate to sing a national anthem would be:

    1. A child (as illustrated by the FNB advert)
    2. Someone with a voice that has the capacity to describe the emotion of what is being sung
    3. Someone with a vocal range and strength that doesn’t require accompaniment.

     

    The point being that the singer HAS to be able to evoke enough emotion and patriotism in the audience listen that they end up standing with their right hand clenched over their heart singing the national anthem with a tear running down their cheek as they sing the last line of their anthem.

     

    Well Ard Matthews 1) is not a child (although it looks like his mom still dresses him) 2) Has a voice that carries no emotion 3) Does not have a voice that is strong enough to go without accompaniment. So in my opinion no, he shouldn’t have done it. Perhaps pride got the better of him? Ag who knows.

     

    To Ard Matthews, sorry bud. I can’t even say nice try. At least you know now for next time.

     

    In Ard Matthews defence: our national anthem is not one that evokes a great deal of emotion. It is wishy washy and tries to please everyone. In my opinion it should have been rewritten in it’s entirety. Not borrowed from bits and pieces of everything.

     

    To close: I remember the days when you would stand when you heard the national anthem, the days you  would sing it in school laughing and joking about it yet feeling and overwhelming sense of pride because it belonged to your country.I also remember the days where the youth stood up for the elderly on buses, men let woman through the door first, adults where respected not because they could dish out a hiding but because they had been around longer, sportsman held down full time jobs and children ran around outside playing sports, climbing trees and building forts. Fond memories, stashed alongside the ones of singing my country’s national anthem.

     

    P.S. for all those that are going to bin the old regime labels on me, don’t bother. I am not condoning what previous political parties did, all I want is the same sort of pride in our country that was found then to prevail today and in the future. Everyone in our country just wants to make enough money to get out. Don’t believe me? Go ahead and ask your buddies how many of them would leave if they could.

     

    P.S.S If you turn this comment thread into a political soap box I will remove your comments. If your comments are objective they will stay, I don’t want emotional baggage here.

    Wednesday, August 24, 2011

    C# Arrays, extension methods and the way not to do something

    Right let me first start of by saying, the problem that this code solves should never exist, and I mean NEVER! There is no good reason to have to do this unless you have a legacy system that has all of a sudden had the carpet pulled out from underneath it, you have to add new functionality and if you don’t get it done on time (which is the next three days) the world will end. Seriously though, avoid this at all costs if you possibly can.

    Right that being said, I had a problem where by thousands of lines of code had been written against a SOAP service which made use of collections had been written many moons ago. Recently the definitions changed and all the collections were now arrays! The proxies are generated against svcutil and yes I know there is a switch to use collections as opposed to arrays but I entered the project at a time were it had been decided to convert all the code using the collections. Right this posed a significant problem in that myObject.Collection.Add() no longer existed.

    My first thought (yes perhaps not one of my greatest moments) was to do this

       1: //given



       2: myObject.Collection.Add(myNewItem);



       3:



       4: //Convert it to



       5: myObject.Array.ToList().Add(myNewItem);






    Now for some reason this made sense in my head till I did it and found out it wasn’t working. Why wasn’t it working? You guessed it! The instance of ToList() was not being assigned to the collection. DOH!





    Well my next solution was to implement a generic method that converted the array to a list, added the item then converted the list back to an array. Something like this.





       1: public class ArrayHelper{



       2:     public static void Add(ref T[] array, T input) {



       3:         if (array == null)



       4:             array = new T[0];



       5:     



       6:         var list = array.ToList();



       7:         list.Add(input);



       8:         array = list.ToArray();



       9:     }



      10: }



      11: //Usage would be



      12: ArrayHelper.Add(ref myObject.Array, myNewItem);




    Well that looks a bit better and the best part? It works! Well kinda Sad smile When running performance tests on it it turned out that adding 5000 items to this array would take approximately 35 times longer than doing it natively. What a bummer. Well back to the drawing board I guess. This means if it takes 0.0004 milliseconds to add one item natively it would take 0.015 milliseconds to add one time using this method.





    I then came across Array.Resize and figured I would see what that does. So the method became:





       1: //Class definition



       2: public static void Add(ref T[] array, T input){



       3:     if(array == null)



       4:         array = new T[0];



       5:



       6:         Array.Resize(ref array, array.Length + 1);



       7:         array[array.Length - 1] = input;



       8: }



       9: //Usage remains the same




    This method took 10 times longer to add 5000 items. This means it would take 0.004 milliseconds to add one item. A bit more acceptable. Now thinking I am the cheese I wanted to wrap this into an extension method. My first attempt failed so I started looking around if anyone else had done this. Seems someone had http://these-pretzels-are-making-me-thlrsty.blogspot.com/2010/05/c-extension-method-bummer.html and verified what I was too scared to admit, it wasn’t going to happen as an extension!





    Oh well …





    References:



    Monday, August 22, 2011

    Unobtrusive label to textbox association using JQuery

    Well things just seem to be getting easier and easier. Next up I have a form that I wanted to try the concept of unobtrusive JavaScript on. The form is relatively simple containing two labels and text boxes for a first name and a last name. Here we have the form in Razor (MVC3)

       1: <form id="registrationForm">



       2: @Html.LabelFor(x => x.FirstName)



       3: @Html.TextBoxFor(x => x.FirstName)



       4: <br />



       5: @Html.LabelFor(x => x.LastName)



       6: @Html.TextBoxFor(x => x.LastName)



       7: form>






    Then I started experimenting with the page JavaScript is located in a separate file. So it would be included in a script tag. It actually turned out way simpler than I initially thought.





    Here is my first iteration of the JavaScript file





       1: /**



       2: * Configure the function to handle the label insertion into



       3: * the text areas



       4: */



       5: $(function () {



       6:     $('#registrationForm label').each(function (i) {



       7:         var label = $(this);



       8:         var textBoxId = "#" + label.attr("for");



       9:         var text = label.text();



      10:         var textBox = $(textBoxId).val(text);



      11:



      12:



      13:         textBox.focus(function () {



      14:             if (this.value == text) {



      15:                 this.value = "";



      16:             }



      17:         })



      18:         .blur(function () {



      19:             if (this.value == "")



      20:                 this.value = text;



      21:         });



      22:



      23:         label.hide();



      24:     });



      25: });




    And that, honestly, was that. Of course looking at that I couldn’t help but feel it better to wrap it in a function so I don’t have to replicate that code on every form. So this is what I ended up with in my handy little helper class:





       1: function Helper() { }



       2:



       3: Helper.processFormLabels = function (formId) {



       4:     var query = "#" + formId + " label";



       5:     $(query).each(function (i) {



       6:         var label = $(this);



       7:         var textBoxId = "#" + label.attr("for");



       8:         var text = label.text();



       9:         var textBox = $(textBoxId).val(text);



      10:



      11:



      12:         textBox.focus(function () {



      13:             if (this.value == text) {



      14:                 this.value = "";



      15:             }



      16:         })



      17:         .blur(function () {



      18:             if (this.value == "")



      19:                 this.value = text;



      20:         });



      21:



      22:         label.hide();



      23:     });



      24: }




    Then the document on load script looks like this





       1: /**



       2: * Configure the function to handle the label insertion into



       3: * the text areas



       4: */



       5: $(function () {



       6:     Helper.processFormLabels("registrationForm");



       7: });




    Include all relevant JavaScript files and viola! Off you go.

    ASP.NET, MVC3, Razor and adding scripts where they supposed to go

    I was always under the impression that the HEAD of an HTML document contained the SCRIPT tags. Call me old fashioned but I actually quiet like it that way.

    Then I cam across a discussion at http://stackoverflow.com/questions/1213281/does-javascript-have-to-be-in-the-head-tags concerning this very thing. So say HEAD, some say BODY and some say WHERE_EVER_YOU_WANT. I then went and confirmed the HEAD and BODY issue at http://www.w3.org/TR/html4/interact/scripts.html

    I can see validity in the arguments but with the advent of the unobtrusive JavaScript model I am beginning to wonder if arguments like this are really valid any longer. I also question being able to see the page before being able to use it is such a good idea. I personally would prefer the user is not able to see anything till the code to assist them has loaded. Again with the unobtrusive JavaScript stuff, my argument is also flawed.

    Either way, I decided I wanted a mechanism where I could add the path to a collection and it would be inserted into the page in a central location, top or bottom, HEAD or BODY.

    So I had a look at the ViewBag now offered in MVC 3 and decided it would be the best place to have a collection like this. Seeing as it is dynamic and available on all pages it made the most sense. I didn’t want to have to go and create a store to store the collection in and then query it before rendering, I just wanted it to work so below is what I came up with:

       1: //Inside the view page



       2: @{



       3:     ViewBag.Title = "MyPage";



       4:     ViewBag.Scripts = new List { "Pages/MyPage.js" };



       5: }




    Then in the master or layout page you can quiet easily do this:







       1: <head>



       2:     <title>@ViewBag.Titletitle>



       3:     <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />



       4:     <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript">script>
       1:
       2:     @{
       3:         if (ViewBag.Scripts != null) {
       4:             foreach (var script in ViewBag.Scripts) {
       5:         ";



       9:         private const string PathPrefix = "~/Scripts/{0}";



      10:



      11:         /// 



      12:         /// Inserts the scripts. If using a viewbag remember to cast the input property



      13:         /// 



      14:         /// The HTML.



      15:         /// The scripts.



      16:         /// The URL helper.



      17:         /// 



      18:         public static IHtmlString InsertScripts(this System.Web.Mvc.HtmlHelper html, IList scripts, UrlHelper urlHelper) {



      19:



      20:             if (scripts == null)



      21:                 return new HtmlString(String.Empty);



      22:



      23:             var output = new StringBuilder();



      24:



      25:



      26:             foreach (var script in scripts) {



      27:                 output.AppendFormat(ScriptTag, urlHelper.Content(String.Format(PathPrefix, script)));



      28:             }



      29:



      30:             return html.Raw(output.ToString());



      31:         }



      32:     }



      33: }






    Which means the call in the view or layout page is reduced to





       1: <head>



       2:     <title>@ViewBag.Titletitle>



       3:     <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />



       4:     <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript">script>



       5:     @Html.InsertScripts((IList<String>)ViewBag.Scripts, Url);



       6: head>






    Nice and clean (well kinda)