MvvmCross – Part One

In Xamarin studio I’ll create a new solution called Jokes with a class library (PCL) called Jokes.Core. The “Core” is the convention that MvvmCross uses for the project containing your business logic, can be changed to something else. After the project is created I’ll add the MvvmCross nuget package. That added references to the MvvmCross HotTuna libraries but also created an App.cs file and a ViewModels/FirstViewModel.cs file. App.cs is the entry point of our application, all it does is to initialize the IoC container that comes with MvvmCross and set the start page for the application, in this case FirstViewModel, which I’ll rename to MainPageViewModel.

Next thing I’ll do is to add Models folder with a Person class. The person class is very simple, first and last name properties and a full name that is the first and the last name concatenated.

Then I’ll go to the MainPageViewModel and I’ll add properties for FirstName, LastName and Greeting. The greeting will be composed from the text “Hello” and the full name of the person. The important thing about the ViewModels is that they need to implement the interface INotifyPropertyChanged which is the interface responsible for making the databinding work. MvvmCross gives us a basic implementation of INotifyPropertyChanged with the base class MvxViewModel.

Now I’ll go ahead and a unit test project called Jokes.Core.Tests and I’ll write a test for the MainPageViewModel that when the FirstName is “John” and the LastName is “Smith” the greeting will be “Hello John Smith”. Test passes.

Next step – I’ll add a new Android project called Jokes.Droid and I’ll add MvvmCross nuget to it. I have to add a reference to the the Core project and rename FirstView to MainPage (by convention that needs to match the MainPageViewModel from the Core project so the view model locator can find it)

Adding a page title for WinPhone in Xamarin.Forms

I’ve been playing with Xamarin.Forms for the last few days. While it is pretty impressive that you can build an iPhone, Android and WinPhone app from the same codebase, I get a feeling that WinPhone is a second class citizen. One of the first things that bugged me is that you do not get the standard WinPhone page titles “for free”. Here is some XAML to fix that:

<!-- WinPhone page title -->
<StackLayout>
   <StackLayout.IsVisible>
       <OnPlatform x:TypeArguments="x:Boolean">
           <OnPlatform.iOS>false</OnPlatform.iOS>
           <OnPlatform.Android>false</OnPlatform.Android>
           <OnPlatform.WinPhone>true</OnPlatform.WinPhone>
       </OnPlatform>
   </StackLayout.IsVisible>
   <Label Text="APPLICATION TITLE" TranslationX="4" TranslationY="4" />
   <Label Text="page title" Font="64" TranslationY="-12"/>
</StackLayout>

Hopscotch

Hopscotch is a little phone game that I started about two years ago and never got to finish. This week I started from scratch and published it in one day. The design of the game as well as the icon which I created from a screenshot turned out pretty great. And my six year old daughter absolutely loves the game, makes me feel so proud…

258x67_WPS_Download_cyan

MvvmCross

In the seventies, just before I was born, Xerox (where I spent half of my career) invented MVC (model-view-controller). There are many variations of the pattern one of which is MVVM (model-view-viewmodel). While the differences between the various flavors of MVC, MVP, MVVM, etc. are in my opinion purely academic, there is absolutely no doubt in my mind that following a pattern like that can make the dev’s life a lot easier. There is somewhat of a high price for entry and a bit of a learning curve, but once you commit to it, there is no going back.

The essence of MVVM is that you separate your data (the model) from you presentation (the view) and you put all your UI logic in the view-model, where it can be developed and tested separately from the view itself. When targeting multiple platforms, in the ideal case you can reuse your models and view models across the different platforms and only code separate views.

There are several different MVVM libraries (MVVM Light, Caliburn, etc.) but it is important to understand that you do not need to bring a library in order to do MVVM, it just makes things easier. I’ve never used mvvmcross before but it promises to deliver databinding on windows, android and ios with reusable view models. It also contains a simple IoC container as well as few other tools and plugins.

mvvmcross is available as a nuget package. you add it to your projects, follow the provided (short) to-do list and you are in business. I was able to wire up a win store app with two views, view models, a service, etc. in maybe 15 or 20 minutes. Tomorrow – droids for breakfast 🙂 …

Roman numbers kata

This exercise is from vNext_OC mob programming session today. The goal of this kata is to convert a roman number (XLVII) to a decimal number (48). In the spirit of TDD I will start with a test for the number one and the simplest possible code that satisfies that test:

[TestMethod]
public void I()
{
    Assert.AreEqual(1, Roman.ToDecimal("I"));
}

public class Roman
{
    public static int ToDecimal(string roman)
    {
        return 1;
    }
}

The second test I’ll write is for the number two:

[TestMethod]
public void II()
{
    Assert.AreEqual(2, Roman.ToDecimal("II"));
}

That test fails. One possible solution is to return the length of the passed string:

public class Roman
{
    public static int ToDecimal(string roman)
    {
        return roman.Length;
    }
}

Test succeeds. Next test – three. That succeeds as well. Next one – four. Fails. I don’t quite know what to do with four yet so I’ll do the simplest possible thing – will explicitly check for IV:

public class Roman
{
    public static int ToDecimal(string roman)
    {
        if (roman = "IV") return 4;

        return roman.Length;
    }
}

Green. Next one – five. I have 2 different digits now. What I’ll do is I’ll assign value 1 to I, value 5 to V and will add those values:

public class Roman
{
    public static int ToDecimal(string roman)
    {
        if (roman = "IV") return 4;

        int result = 0;

        foreach (var c in roman)
        {
            switch(c)
            {
                case "I": 
                    result += 1;
                    break;
                case "V":
                    result += 5;
                    break;
            }
        }

        return result;
    }
}

All tests are green again. VI, VII, VIII are green too.

Now is a good time to introduce ApprovalTests. I’ll install the package from nuget and I’ll write a test like this:

[TestMethod]
public void TestAll()
{
    var romans = new[] { "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" };
    var results = romans.Select(r => new { roman = r, number = Roman.ToDecimal(r) });
    Approvals.VerifyAll(results, "");
}

That test will fail but will bring a file that looks like this:

[0] => { roman: "I", number: 1 }
[1] => { roman: "II", number: 2 }
[2] => { roman: "III", number: 3 }
[3] => { roman: "IV", number: 4 }
[4] => { roman: "V", number: 5 }
[5] => { roman: "VI", number: 6 }
[6] => { roman: "VII", number: 7 }
[7] => { roman: "VIII", number: 8 }
[8] => { roman: "IX", number: 1 }
[9] => { roman: "X", number: 0 }

I will fix the last two results of to be 9 and 10 and save the approved “gold master”. Test fails again (as expected) but we can replace all previous tests with just one more powerful and more visual test. To satisfy the test I’ll add another “exception” for IX and I’ll add a value for the digit 10.

public class Roman
{
    public static int ToDecimal(string roman)
    {
        if (roman = "IV") return 4;
        if (roman = "IX") return 9;

        int result = 0;

        foreach (var c in roman)
        {
            switch(c)
            {
                case "I": 
                    result += 1;
                    break;
                case "V":
                    result += 5;
                    break;
                case "X":
                    result += 10;
                    break;
            }
        }

        return result;
    }
}

Green. I’ll refactor the code now to include two dictionaries for the digits and the exceptions:

public class Roman
{
    static var exceptions = new Dictionary() { { "IV", 4 }, { "IX", 9 } }; 

    static var digits = new Dictionary() { { 'I', 1 }, { 'V', 5 }, { 'X', 10 } };

    public static int ToDecimal(string roman)
    {
        int result = 0;

        foreach (var x in exceptions)
        {
            if (roman.Contains(x.Key))
            {
                result += x.Value;
                roman = roman.Replace(x.Key, "");
            }
        }

        foreach (var c in roman)
        {
            if (digits.ContainsKey(c))
            {
                result += digits[c];
            }
        }

        return result;
    }
}

Run the test – all green. Now I’ll add the numbers from XI to XX to the test. First time it will fail. I’ll approve the result (since it is correct) and run the test again. Green. Repeat with XXI to XXX. Red, approve, green. XXXI to XL – all looks good except the number 40. I’ll manually edit the result file and approve it. Run the test again – red. To fix the code I need to add XL to the list of exceptions. Green. XL to L – to make the test pass need to add L to the digits. Then we are good all the way to XC. Adding XC to the exceptions and C to the digits and we have all the numbers to 100 working.

I’ll stop here. There is room to refactor but this is a good demonstration of the power of TDD. Without sitting down and designing the one algorithm that solves all roman numbers, in half an hour we have a very simple code that solves the problem for all numbers up to 100. Good enough to translate the number of the superbowl (XLVIII) that is coming next weekend.

SharePoint 2010 on Windows 7

For those about to rock, we salute you! For those about to get into SharePoint development, I solute you too! With a bit of mixed feelings, but still… salute!

SharePoint requires Windows Server to run but most developers do not use Windows Server on their dev machines. You can always mess with virtual machines but I am not a big fan of that either.

Then I found out that (for dev purposes only!) you can manually install SharePoint 2010 on a Windows 7 machine (or even Vista). Luckily there is a free 180 day trial which should be plenty of time to get your feet wet. Here is what you need to do:

Download SharePoint 2010 Foundation:

http://www.microsoft.com/en-us/download/details.aspx?id=5970

Download SharePoint Trial:

http://technet.microsoft.com/en-us/evalcenter/ee388573.aspx

Now follow this instruction:

http://msdn.microsoft.com/en-us/library/ee554869(v=office.14).aspx

My advice is to follow the instruction as closely as possible and do not skip the steps that are “optional” (because they are not!). Also after installing and before running the setup wizard run Windows update several times + several restarts to get all available updates installed.

The road is certainly rocky but google bing is your friend and you’ll get there… took me about 2 hours to setup… And when you get the “Unable to create configuration database” error, install the MSChart control… Duh!?!

And at last, optionally download and install the SharePoint 2010 Designer which is free:

http://www.microsoft.com/en-us/download/details.aspx?id=16573 (32-bit)

http://www.microsoft.com/en-us/download/details.aspx?id=24309 (64-bit)

Now off to Pluralsight to watch SharePoint videos… 57 courses at 4-6h average equals to a lot…