vrijdag 27 mei 2011

Must have WP7 apps

Been playing with my Windows Phone 7 for a month now and I wanted to share my thoughts on what my favorite apps are:



I’ve put this one on top because I think it’s great.  It’s a full blown navigation app with turn by turn directions.  The latest update also includes rotating maps.  Very handy to use and a must have if you want to use the phone as a GPS… at least until the Mango update delivers turn by turn navigation with Bing Maps


An application that allows you to share a PC folder with your Windows Phone device.  It’s nice to use but I wouldn’t recommend using this with 3G connection because it will actually download the file you get from the shared folder.  The free version is also limited in usage but still more than enough for the average user.  I use this mainly to share large pdf’s and so on.

Tech News

Simple RSS reader that reads from several tech sites and bundles the information for you.  Very good application when you’re bored in a waiting room.

Draw Free

Simple application that allows you to make little drawings with your finger.

Adobe PDF / Youtube

These don’t need any introduction I suppose.  Really must have applications.


Need For Speed Underground

Very addictive game.  Only a shame they’ve made it so easy.  I was really surprised by the graphics in this game. 

Rise Of Glory

Didn’t buy this game because the free level on its own is more than enough for me (I’m not really a gamer).  It’s a flight simulator with some very nice graphics.  Don’t play this in public though because you’ll look like a retard.

Mars runner

Free game in which you have to fly a space craft and avoid the rocks.  In my opinion one of the best free games out there.

Ultra Air Hockey 2

Very simple finger air hockey game.  This one is also free and it’s hilarious when drunk.

Some apps I’m going to try when I have the time for it are:


A coworker (where I work allot of people have WP7 :p) told me about this app and it looks very promising.  Look at this link to know more about it.

Hydro Thunder Go

So much commotion about this game that I’m looking forward to try it out 

I’ve installed this some time ago but haven’t had the time to use it.  It promises VOIP communication.

I probably didn’t even scratch the surface of all the apps out there so if you have any good applications you’d like to share, just let me know J.  Till next time.

maandag 23 mei 2011

Catching StackOverflowException in .NET

A stack overflow in .NET will result into a StackOverflowException.  The curious thing about this exception is that it is thrown at a time that it is too late for the user’s code to handle it.  The stack has already overflown and the code is halted.  There is however a way to catch this before executing.  This method however is only possible when knowing that a stack overflow might occur in the future (for example when doing recursive calls).

A  limitation that you have in safe code is that you cannot get the address location of a variable.  So that leaves out the option of calculating you stack size by subtracting the offset of the stack with the last variable added on the stack (http://stackoverflow.com/questions/1599219/c-catch-a-stack-overflow-exception).  
In C# you could try to work around this by creating unsafe method calls but in VB.NET you would be screwed.

This leaves only one available option and that’s approximating the size of the stack and setting a maximum allowed amount of stackframes.  Throw the StackOverflowException before the CLR does and you’ll be able to catch it.

Public Class OverflowHelper

    Public Shared Sub CheckStackForOverflow()

        Dim stackTrace As StackTrace = New StackTrace()
        Dim maxStackSize = 4000
        Dim nrOfStackFrames = stackTrace.GetFrames().Count
        If nrOfStackFrames > maxStackSize Then
            Throw New StackOverflowException
        End If
    End Sub
End Class

It’s certainly not pretty, I’ll admit that, but it’s the only solution thus far.

dinsdag 17 mei 2011

Developer license windows phone 7: how to deploy step by step

Yesterday I got a phone call telling me that the WP7 developer license is ready to be used.  Here is my user experience with deploying my first application.

At first I had to register the phone as a developer phone.  This was pretty easy, all I had to do was type Windows Phone Developer Registration in the start menu and select the tool to do this.

Then the tool launched and I was given the option to input my credentials.

One small notice is that I had 2 errors in the beginning
  1.    I got a network error telling me it could not connect or my credentials were wrong: this was due to the fact that I am behind a corporate proxy that blocks the zune traffic.
  2.    I got an error telling me my phone was not connected but that was solved by just reconnecting it.
Ow yeah, and don’t forget to unlock your screen to…
Then when the registration was completed I could open up my solution and start deploying my project.  You can deploy in two ways.  Either you deploy from within Visual Studio or you do it manually with the Application Deployment tool (just type it in the ├╝ber start menu).

Again a small notice is that I got an error (again) telling me that my phone wasn’t connected.  If that’s the case then just reconnect it.
In Visual Studio you just have to change the device you want to deploy at in the top menu and start debugging or deploying (= right click project and deploy…).

That’s how easy it was =)
Next time I’ll give a small showcase of the KCalorator app we’ve build.

maandag 16 mei 2011

MVVM navigation between pages in Silverlight

I see allot of question on the internet asking how we can perform navigation in MVVM for Silverlight.  There are allot of answers but most of them involve some coupling between the View and ViewModel.  The following answer I will provide will guarantee the following:
  • Completely loose coupled
  • View is responsible for calling another view
  • No need for knowing the URI of each page
So what is the basic setup.  Since a picture is worth more than a thousand words, I made on for you with my expert paint skills:

As you can see I’ve made both a base ViewModel as a Base View.  Both of them encapsulate the requests and handling of the request for navigating to another View.  The request is executed by using the MVVMlight Messenger class.  Enough gibberish here is the code of the 2 base classes:

    public class ViewModelBase : GalaSoft.MvvmLight.ViewModelBase
        public static string RequestedViewName { get; private set; }

        public static void NavigateToView(string viewName)
            RequestedViewName = viewName;
            Messenger.Default.Send<string>(viewName, "NavigationRequest");

    public partial class NavigationPage : Page
        public NavigationPage()


        protected override void OnNavigatedFrom(NavigationEventArgs e)

        protected override void OnNavigatedTo(NavigationEventArgs e)
            // Listen for navigation requests and redirect to the requested page
            Messenger.Default.Register<string>(this, "NavigationRequest", (viewName) => ViewManager.Navigate(viewName, this));

The base ViewModel will send a request with the name of view in it.  The View will the capture the request and ask the ViewManager to handle the logic.  The main reason why we want to do this in the page is because we have easy access to the NavigationService.

Then the ViewManager will parse the view string and navigate to the corresponding Uri.  The Uri is determined by using a class I wrote a while back called the PageUriLocator:

    public class ViewManager
        public static Uri GetUriFromViewName(string viewName)
            string uri;
            switch (viewName)
                case "About":
                    uri = PageUriLocator.GetUri<about>();
                case "Home":
                    uri =PageUriLocator.GetUri<home>();
                    throw new ArgumentException("Page does not exist");
            return new Uri(uri, UriKind.RelativeOrAbsolute);

        public static void Navigate(string viewName, NavigationPage page)
            Uri uri = GetUriFromViewName(viewName);
            if (uri != null)

Then when we want to navigate in our ViewModel we can just do this:

    public class HomeViewModel: ViewModelBase
        public RelayCommand NavigateToAbout
                return new RelayCommand(() => NavigateToView("About"));

I’ve included a sample here.
Have fun coding ;)

woensdag 11 mei 2011

Brain vs Logic

It amazes me every time how easy it is for our brains to do complex things. I am currently writing logic to draw out company processes on a visual canvas.  At first this task seemed easy.  I opened up the table and took a piece of paper and draw out a couple of these processes manually to get the hang of the underlying logic.   This went pretty smoothly and after drawing 3 of these processes out I was ready to implement some algorithms that would do this work for me.  Now a day later the logic that goes within this algorithm is mind blowing.  What was a trivial thing for my brain to comprehend ended out in complex recursive algorithms.

How come my brain can come up with these algorithms so easily and use them in a fairly small amount of time, while when trying to materialize these algorithms it’s like it’s impossible to come up with the solution?  Well without you knowing there are tons of rules in your head you apply to this logic.  When implementing this into code you have to take account all the rules you have in your head and try to figure out what your brain does with these rules and in what order it applies them to reach a solution.  Here are some quick tips that helped me reach my solution:
  • Draw out the logic into a diagram while solving it manually with you brain
  • When it seems too complex to draw it into a diagram then write all the rules that apply to this algorithm on a piece of paper
  • Using the rules you’ve written down, try implementing it in loop and conditional statements still using a piece of paper!
  • Start writing logic for a part of the algorithm first and then continue integrating extra bits to the algorithm to apply more rules.
  •  Now when you think you’ve mastered the logic on paper go implement it in you IDE
  • Write the logic as easy as possible; don’t start refactoring like hell so you can make the code shorter, this is something you can do later on.
  • When you have the logic start writing some tests against it.  What I did for this one was the process I had drawn on paper, I converted this to objects I would use to draw. Then I would feed my test with the same data my brain used to draw the diagram and see if the outcome is the same.
  • Then when the algorithm works, see if you can’t start refactoring it to make it more readable and shorter.

maandag 9 mei 2011

How to perform Cross Field validation in silverlight

When validating properties in Silverlight in some rare occasions we want to only validate properties referential to other properties in our viewmodel / entity.  If you do not know how to implement validation using data annotations in Silverlight then please take a look at this article .  It provides a good lead on how to do this.

So imagine we have some kind of parking application that allows a user to park using a beneficial rate when he has a child younger than 5 years old.  So if we would have a simple viewmodel that would accommodate this it would look something like this:

    public class ParkingViewModel : VMBase
        private string _kidsSsn;
        private bool _parkWithBenificialRate;

        public string KidsSsn
            get { return _kidsSsn; }
                _kidsSsn = value;
                RaisePropertyChanged(() => KidsSsn);

        public bool ParkWithBenificialRate
            get { return _parkWithBenificialRate; }
                _parkWithBenificialRate = value;
                RaisePropertyChanged(() => ParkWithBenificialRate);
                RaisePropertyChanged(() => KidsSsn);

        public bool ChildIsUnderFiveYearsOld(string ssn)
            // Retrieve some value from a service
            return ssn.Equals("1234567");

        public RelayCommand Pay
                return new RelayCommand(() =>
                                                // Empty his bank account

We would then need to have a validation attribute that can do 2 things:
  • Check if the user is trying to park with a beneficial rate
  • Check if the social security number is of a child younger than 5 years old

    public class RequiredWhenParkingWithBenificialRateAttribute : ValidationAttribute
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            // Get the parent type
            var vm = validationContext.ObjectInstance as ParkingViewModel;
            if(vm != null && vm.ParkWithBenificialRate)
                    return new ValidationResult("Child must be under five years old!!!",
                                                new [] {validationContext.MemberName});

            return ValidationResult.Success;
That’s it!

donderdag 5 mei 2011

Ugly lambdas in VB.NET

When I was 14 years old my sister bought me a gift for my Christmas.  It was called Dark Basic.  It promised the user to make games in a jiffy without any hardcore programming knowledge.  To my disappointment when I started the application all I got was a blank black screen with a white blinking cursor. 
I was a bit confused at that point, since I imaged some kind of drag and drop mechanism and some cool monsters and half naked woman I could select.  Nopes, that wasn’t it.  Instead it was a BASIC language which allowed the user to easily write 3D games without having to think about low level transformations.  After a couple of days, I started to get the hang of it and it was very addictive. 

Why am I telling you this?  Well just to show you that I have no grudge what so ever against BASIC languages.  I know DarkBasic, Visual Basic 6, VB.NET and I even experimented with QuickBasic, so I think I’ve had my share of experience with BASIC languages. 
Now the last 6 months, I’ve been working in VB.NET again (yes they putted a gun against my head and kidnapped my girlfriend).  And I can say to you that once you’ve got a taste of C#, it’s a bummer to go back to Visual Basic.  My biggest issue with VB.NET is Lambdas.  No matter how hard you try, there is just no way you can make this look pretty.  ‘So than just don’t use them’ I hear some VB.NET fans yelling while putting on an ice pack on their sore fingers from all the typing they did today.  Well in some situation, I believe the lack of lambdas will spaghetify your code.

Imagine we want to use the MVVM pattern in Silverlight and we are writing some RelayCommand.  In C# we can just write:

public RelayCommand GettingJiggyWithIt
          return new RelayCommand(() =>
                                          var me = GettingJiggy();
                                          WhoIsGettingJiggy = me + WithIt();

While in VB.NET we either inline it with the most ugliest and unclear syntax I’ve seen in my life or we can make it jump to a method defined elsewhere:

    Public ReadOnly Property GettingJiggyWithIt As RelayCommand
            Return New RelayCommand(Sub()
                                        Dim I = GettingJiggy()
                                        WhoIsGettingJiggy = I + WithIt()
                                    End Sub)
        End Get
    End Property

Sure this example isn’t such a PIA but then Imagine we want to start testing. Using MOQ or RhinoMock we want to create some mocks in our test.  While using C# we can do this:

mockDal.Setup(dal => dal.GetPersonsRoles).Returns(new Person { Name = "Maria" })

Just gorgeous.
While in VB.NET we are obligated to do this:

mockDal.Setup(Function(dal) dal.GetPersonsRoles).Returns(New Person With {.Name = "Maria"})

So I guess I’m still a bit whining as this example doesn’t look THAT bad.  Sure, now Image you want to do the same thing MOQ described on their QuickStart guide:

mock.Setup(foo => foo.Submit(IsLarge())).Throws<ArgumentException>();

public string IsLarge()
  return Match<string>.Create(s => !String.IsNullOrEmpty(s) && s.Length > 100);
In VB.NET this would become:
mock.Setup(Function(foo) foo.Submit(IsLarge())).Throws(Of ArgumentException)()
Public Function IsLarge() As String
        Return Match(Of String).Create(Function(s) Not [String].IsNullOrEmpty(s) AndAlso s.Length > 100)
End Function

The syntax is so ugly, the spellings and grammar processor of Words just crashed (seriously).
So what can we do to make this look a bit nicer?  Using the AddressOf operator will just turn your code into spaghetti.  One solution I came up with was to declare each lambda separately and then use it in one fluent sentence. Like this:

Dim whenSubmitingToLarge = Function(foo) foo.Submit(IsLarge())
mock.Setup(whenSubmitingToLarge).Throws(Of ArgumentException)()
It still isn’t pretty, but it is prettier in my opinion.  Still, if you have the choice to choose between VB.NET or C# then choose C# without a doubt.  Lambdas are just one of the many ugly constructs VB.NET holds itself to.  Some other syntactical catastrophes’ I can think of are attributes, extension methods and so on.

I needed to get that off my chest, until next post ;)