#dvlupday in San Diego

I attended a DVLUP day in San Diego this weekend. The event started pretty rough with an ex-military security guard yelling at poor unwoken devs to order in lines before 8:00 AM. Besides that it was a lot of fun. I quite miss the energy of those events. Over a hundred devs sitting in a room in the Nokia office in San Diego, laptops open, coding… Several good presentations most notably on appstudio, unity and maps.

I worked on a video poker app for windows phone. I started with a code from a poker kata we did at work few weeks ago. I also had a control for a playing card that flips when tapped with a nice animation. And I build a working video poker game in less than 8h and it turned out pretty nice. I’m going to submit it to the app store in the following days for a DVLUP challenge.

I’m also planning to create an universal app based on that code base trying to reuse as much code as possible between winphone and win8 apps.

Update (5/5): the app just got published, download from the link below.

258x67_WPS_Download_cyan

unit testing TypeScript

Few days ago TypeScript 0.97 was promoted to version 1.0RC which means that there will be no more changes for version 1.0, just bug fixes. At the same time Visual Studio 2013 Update 2 RC was announced with full TypeScript support out of the box, without having to separately download the tools. It is obvious that Microsoft are pushing TypeScript to be a first class citizen in the Visual Studio eco-system. What’s missing? Unit testing! Did they not notice? How could they call it 1.0 without a viable unit testing framework out of the box?

Here comes ReSharper 8.2 (which is not yet released, beta bits available on the JetBrains website). Best new feature – TypeScript unit testing of course!

Here is my setup:

  • Visual Studio 2013 Update 2 (RC)
  • ReSharper 8.2 (Beta)
  • PhantomJS (from PhantomJS.org) installed and configured
  • QUnit definition file – qunit.d.ts (from DefinitelyTyped)

Create a new HTML TypeScript Application project in Visual Studio and delete index.html, app.ts and app.css files (like to start clean).

Create a folder “libs” and put qunit.d.ts there.

Create a folder “tests” and put a file helloWorld.ts like this:

///<reference path="../libs/qunit.d.ts"/>

test("hello world test", ()=>
{
    ok(true, "hello world test");
});

The test icon appears in front of the test method. Run the test to make sure all is configured correctly.

Now create a folder “app” and put a file MyClass.ts in it:

module MyModule
{
    export class MyClass
    {
        private x: number;

        constructor(x: number)
        {
            this.x = x;
        }

        getX(): number
        {
            return this.x;
        }
    }
}

Finally create a test class MyClass.Tests for that class in folder “tests”:

///<reference path="../libs/qunit.d.ts"/>
///<reference path="../app/MyClass.ts"/>

module MyModule.Tests
{
    test("my test", ()=>
    {
        // arrange
        var myClass = new MyModule.MyClass(5);

        // act
        var result = myClass.getX();

        // assert 
        equal(result, 5, "result is 5");
    });
}

Magic! Love it or hate it ReSharper saves the day (again)…

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.

AgileThought hackathon

AT-hackathon-logo

This week I took part in the inaugural AgileThought hackathon. My team consisted of Esteban Garcia (ALM MVP) , Eric Landes (also ALM MVP) and me (what am I doing with those two?). We wanted to do “something mobile” and/or “something with TFS”. Our initial proposal was for a Windows 8 TFS dashboard app but it was rejected since another team submitted a similar idea before us. We ended up writing a Windows 8 client for the TFS team rooms using the newly released REST API. It turned out pretty good (both visually and functionally) and we won the Cool Use of Technology award at the end.

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…

WebSockets – metro style app

Building the metro app. To our existing solution I’ll add an empty Windows Store Application. As I mentioned earlier the WebSockets support is built in the WinRT so there are no nuget packages to install, we just need to include the Windows.Networking.Sockets namespace.

On my main page I’ll have a stack panel called Container, which sits inside a scroll viewer, and in that container I’ll be adding different custom controls. There is also a text block where we can watch the messages that we send and receive similar to what we did on the HTML5 page.

The programming model for the client is very similar to what we saw on the server and in HTML5. There are 2 important events that we need to handle (MessageReceived and Closed); to open a connection we call ConnectAnync() method and to send and receive messages we use a DataReader and a DataWriter to read and write to and from the input and output streams. I’ll create a simple class that will wrap all this complexity and expose a couple of more convenient methods and events.

using Windows.Networking.Sockets;
using Windows.Storage.Streams;

public class Socket
{
    private MessageWebSocket socket;

    private DataWriter writer;

    public event MessageDelegate OnConnected;

    public event MessageDelegate OnDisconnected;

    public event MessageDelegate OnMessage;

    public event MessageDelegate OnStatus;

    public Socket()
    {
        this.socket = new MessageWebSocket();
        this.socket.Control.MessageType = SocketMessageType.Utf8;

        this.socket.MessageReceived += (sender, args) =>
        {
            var reader = args.GetDataReader();
            var message = reader.ReadString(reader.UnconsumedBufferLength);

            // remove ""
            message = message.Remove(message.Length - 1).Remove(0, 1); 

            Status("<<< " + message);             

            if (OnMessage != null) OnMessage(message);         
        };

        this.socket.Closed += (sender, args) =>
        {
            Status("Disconnected");

            this.socket.Dispose();
            this.socket = null;

            if (OnDisconnected != null) OnDisconnected(null);
        };
    }

    public async void Connect(string url)
    {
        Status("Connecting to " + url + " ...");
        await socket.ConnectAsync(new Uri(url));
        writer = new DataWriter(socket.OutputStream);
        Status("Connected");

        if (OnConnected != null) OnConnected(null);
    }

    public async Task Send(string message)
    {
        Status(">>> " + message);

        writer.WriteString(message);
        await writer.StoreAsync();
    }

    public void Disconnect()
    {
        Status("Disconnecting...");
        socket.Close(1000, "user request");
    }

    void Status(string status)
    {
        if (OnStatus != null) OnStatus(status);
    }
}

The next thing I’ll need is a helper class that will dispatch the messages between the different controls on the main page. All controls will implement a simple IChatControl interface. It contains one method to receive a message and two events to send a message and to send a local message. Also there is a reference property so we know who we are talking to.

public interface IChatControl
{
    string Reference { set; } 

    event MessageDelegate SendMessage;

    event MessageDelegate SendLocalMessage;

    void ReceiveMessage(string message);
}

In my helper class ControlManager I’ll have a collection (dictionary) of controls. There is a single public method that sends a message to the correct control. Each message has a sender, a command and a body. What the method does, it finds the right control to receive the message and sends it to that control. If a control like that does not exist it creates a new one and adds it to the container.

public class ControlsManager
{
    Dictionary<string, UIElement> controls;
    Panel container;

    public event MessageDelegate SendMessage;

    public event MessageDelegate SendLocalMessage;

    public ControlsManager(Panel container)
    {
        this.controls = new Dictionary<string, UIElement>();
        this.container = container;
    }

    public void SendMessageToControl(string sender, string command, string message)
    {
        var control = FindControl(command, sender);
        if (control != null)
            ((IChatControl)control).ReceiveMessage(message);
    }

    private UIElement FindControl(string command, string reference)
    {
        UIElement control = null;
        string key = command + "_" + reference;

        if (controls.ContainsKey(key))
        {
            control = controls[key];
        }
        else
        {
            Type t = GetType(command);
            if (t != null)
            {
                control = (UIElement)Activator.CreateInstance(t);
                ((IChatControl)control).Reference = reference;
                ((IChatControl)control).SendMessage += (message) => 
                    { if (SendMessage != null) SendMessage(message); };
                ((IChatControl)control).SendLocalMessage += (message) => 
                    { if (SendLocalMessage != null) SendLocalMessage(message); };

                controls.Add(key, control);
                container.Children.Add(control);
            }
        }

        return control;
    }

    private Type GetType(string command)
    {
        switch (command)
        {
            case "#CHAT":
                return typeof(ChatControl);
            case "#FRIEND":
                return typeof(FriendsControl);
            case "#TICTACTOE":
                return typeof(TicTacToeControl);
            default:
                return null;
        }
    }
}

The last thing before we get to business is a class that will parse the messages that we receive. Every message has a sender, a command and a body, the sender is marked with @ and the command with # (just like twitter) so a typical message would be “@John #tictactoe 1 1” which means that I’m playing tic tac toe with John and I put an X in the middle square, more about that later on…

Now let’s look at our controls. All of them will implement the IChatControl interface.

First the FriendsControl. In the middle of the control there is a listbox that is databound to a collection of Friends. At the bottom, there is a text box and a button to add a new friend. When the button is pressed we send a message “FOLLOW name”. Also, at the top, there is a text box and a button to set the user’s status, when the button is pressed we send a “STATUS status” message. The type of message the control expects is with a name of a friend and that friend’s status so when a message like that is received we update the friend’s status or add a new friend. That control is initialized a bit different than the other controls. Let’s see how it works…

Now the ChatControl… it is a lot simpler than the FriendsControl. There is a scroll viewer where we put chat “bubbles”. When a message is received all we do is to add a bubble with the text of the message. There is a text box and a Send button where we can compose our own message and when the button is pressed the message is send and another bubble is added. One important thing to notice is that we can have multiple conversations with different people and all the messages get send to the right person and delivered to the right control. Demo…

In the next post we’ll look at the tic tac toe game…