Creating a Windows 8 Store Game with MonoGame (XAML) and SignalR

Posted by Filip Ekberg on December 21 2012 2 Comments

In previous posts we’ve looked at how we could create a cross-platform game that relied on HTML and JavaScript. What we also did was moving the server-side code over to a server that runs on Linux and uses Apache and Mono with SignalR! Now let’s take this a step further and convert this game client to a Windows 8 Store application using MonoGame with XAML!

Prerequisite; what you’ll need to install first

Before we can dig into the coding part we need to have some tooling installed first. I am going to use Visual Studio 2012 for this. There are however a lot of resources around that tells you how to use MonoGame with MonoDevelop on for instance a Mac.

All you really need to install if you already have Visual Studio 2012 installed is MonoGame. You can grab the latest version (3.0 Beta) over at the MonoGame CodePlex site.

After installing this you should be able to see the MonoGame (XAML) project template in the “New Project” dialog as seen in the image below.

For those of you that don’t have a clue what MonoGame is, here’s a quote from their CodePlex site:

MonoGame is an Open Source implementation of the Microsoft XNA 4 Framework. Our goal is to allow XNA developers on Xbox 360, Windows & Windows Phone to port their games to the iOS, Android, Mac OS X, Linux and Windows 8 Metro. PlayStation Mobile development is currently in progress.

Amazing, isn’t it?

Even more Amazing is that they’re currently working on getting this to work with Windows Phone 8, which this post was initially going to be about but as the support isn’t in the stable release yet, we’ll take a look at that some other time. Tom Spilman tweeted a while back that he got MonoGame working on Windows Phone 8!

There’s actually one more thing that we will need to have installed and this is the XNA Game Studio. This is because we want to be able to add content (Textures and such) to the game. In order to create a Content project we need to create a Dummy XNA project (there might be a much easier way, then please enlighten me!).

Go to File -> New Project -> XNA Game Studio 4.0 and create a new Windows Phone Game. This will create a projected called WindowsPhoneGame1Content inside the solution. Rename this to TicTacToeContent and add the images you’d like to have in the game (You can download all the resources below). After doing so you will need to edit the Dummy XNA project (not the content project and NOT the MonoGame project). This requires you to first unload the project by right clicking the project and then selecting unload. After that right click it again and select to Edit the csproj file.

Add the following right after the Project node:

<Import Project="$(MSBuildExtensionsPath)\MonoGame\v3.0\MonoGame.ContentPipeline.targets" />
<PropertyGroup>
  <ProjectGuid>{2CAE49BD-8B39-42BE-A010-D3E62657000E}</ProjectGuid>
  <ProjectTypeGuids>{6D335F3A-9D43-41b4-9D22-F6F17C4BE596};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
  <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
  <MonoGamePlatform>Windows8</MonoGamePlatform>
</PropertyGroup>

Then reload and build the solution!

Finally add a folder in the MonoGame project called Content and add the xnb files that was created when you compiled the Dummy XNA project. These are found in bin\Windows Phone\Debug\Content. Select them all and go to the properties tab (Alt+Enter) and change the “Copy to Output Directory” value to “Copy if newer”. Before closing the property window you’ll also need to change the Build Action to Content!

Let’s get some code running!

In order to stay consistent with the code that I previously wrote for the Tic-Tac-Toe demo we can start by renaming Game1.cs to something more suitable such as TicTacToeGame. The first thing we can do is to try and get the Logo in place, I added the following images as Content (xnb):

This means that we will have the following xnb’s and thus be able to load them by their names:

  • board (board.png) – This is the game board
  • logo (logo.png) – This is the game logotype
  • TicTacToeO (TicTacToeO.png) – This is the marker for a Circle
  • TicTacToeX (TicTacToeX.png) – This is the marker for a Cross

Adding a texture

The first thing that we can try out to ensure that the content works properly is to load a 2D Texture. Add a private variable that we can access from our Draw method:

private Texture2D _logoTexture;

Then inside the method LoadContent we can load the texture like this:

_logoTexture = Content.Load<Texture2D>("logo");

In order to actually draw something on the screen we use the sprite batch and we need to tell the sprite batch when to being and when to end. Then we can draw a texture in a rectangle that defines the size and the position like this:

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
           
    _spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null);

    _spriteBatch.Draw(_logoTexture, new Rectangle { X = 100, Y = 100, Height = _logoTexture.Height, Width = _logoTexture .Width}, new Color(255, 255, 2555));
           
    _spriteBatch.End();

    base.Draw(gameTime);
}

Running this in the simulator will make it look something like this:

Now we’re ready to start with the fun! Let’s install SignalR into the project, we can simply do this by getting it from NuGet!

There’s a known bug in the RC version of SignalR which effects the fallback to long polling. This means that we manually need to define that we are in fact using long polling. After SignalR is installed into the project through NuGet we can connect to the Tic-Tac-Toe server and create a proxy.

First define two private read-only fields in the GamePage class, this is the code behind for the XAML file that was created for us by MonoGame:

private readonly HubConnection _connection;
private readonly IHubProxy _proxy;

You’ll also need to add the reference to the following namespaces:

using Microsoft.AspNet.SignalR.Client.Hubs;
using Microsoft.AspNet.SignalR.Client.Transports;

Now, go down to the constructor of the GamePage class and add this to the bottom of it:

_connection = new HubConnection("http://signalr.fekberg.com/");
_proxy = _connection.CreateHubProxy("game");

If you recall from previous posts about SignalR we need to hock up the events before we start the connection. This is pretty much equal to what we saw in the WinRT with HTML and JavaScript demo. Here’s what I have to hook it up with the Tic-Tac-Toe server, to make it a bit more fluent we are going to send the request to start a game as soon as the name is registered:

_proxy.On("registerComplete", () =>
{
    AddMessage("Registration complete, ready to look for a game!");

    Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        _username = Username.Text;
        StartGame.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
    });

    _proxy.Invoke("findOpponent");
});

I would recommend to hook these up somewhere else than in the constructor, since the proxy is a member variable. There are two new things in this anonymous function. First we have the function AddMessage that takes a string. Then we have the dispatcher invocation. The method for adding a message is purely for debugging purposes, to understand what I am going with this, take a look at the following XAML for this game page:

<SwapChainBackgroundPanel
   x:Class="TicTacToe.Windows8.GamePage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="using:TicTacToe.Windows8"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="200" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <ListBox x:Name="Messages" Width="400" HorizontalAlignment="Right" />

        <StackPanel x:Name="StartGame" Background="Black" Grid.Row="1">
            <StackPanel Orientation="Horizontal" Height="50" Margin="10,20,0,0">
                <TextBlock FontSize="30" Margin="0, 10, 0, 0">Enter your name:</TextBlock>
                <TextBox x:Name="Username" FontSize="30"></TextBox>
            </StackPanel>
            <Button Height="50" Margin="10,0,0,0" Click="Register">Start game</Button>
        </StackPanel>
    </Grid>
</SwapChainBackgroundPanel>

This adds a surrounding grid to our view, this view is where we will mix the DirectX graphics and the XAML elements. Worth knowing here is that the XAML elements are always going to be topmost! The surrounding grid will have an empty area to the top left, this is where we will align the logotype that we added before. Then to the right of that we have a list box where we can add some debug messages.

Then finally we have the area where we can register the current player. This is just a simple button and some text fields. The result looks like this when running in the simulator:

As you can see in the top right corner there are some messages added, these are added from the events that we hooked up earlier, but what you didn’t see was when we connected to the server. This is exactly as you are used to when it comes to SignalR, except for the small thing that we are forcing long polling at the time being. This will hopefully be fixed in the next RC.

_connection.Start(new LongPollingTransport()).ContinueWith((t) =>
{
    AddMessage("Connected to server!");
});

Other than the method for adding a message we have seen that we have an event handler on the button. This following code sample shows how these two are implemented:

private void AddMessage(string message)
{
    Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Messages.Items.Add(message); });
}
private void Register(object sender, RoutedEventArgs e)
{
    _proxy.Invoke("registerClient", Username.Text);
}

Notice that Dispatcher.RunAsync is showing up again, this is just like the Dispatcher that you might be used to from WPF. We use it to run things on the GUI thread. In this case we want to add something to a GUI element and we can’t do that from another thread than the GUI thread.

I would also not recommend to hook up the events to the buttons like in this demo, but for the purpose of keeping it focused on what is interesting here, you can go ahead and check out MVVM and Commands later on!

The game page which we’ve been working on almost solely so far is pretty much complete, in the below longer code snippet you can see the complete implementation of this class. As you can see much of the code isn’t implemented such as what is going to happen when the game ends, you’re free to add that on your own later. Now we can start looking at the MonoGame and Touch code!

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using MonoGame.Framework;
using Microsoft.AspNet.SignalR.Client.Hubs;
using Microsoft.AspNet.SignalR.Client.Transports;

namespace TicTacToe.Windows8
{
    public sealed partial class GamePage : SwapChainBackgroundPanel
    {
        TicTacToeGame _game;
        private readonly HubConnection _connection;
        private readonly IHubProxy _proxy;
        private string _username;
        public GamePage(string launchArguments)
        {
            this.InitializeComponent();

            _game = XamlGame<TicTacToeGame>.Create(launchArguments, Window.Current.CoreWindow, this);

            _connection = new HubConnection("http://signalr.fekberg.com/");

            _proxy = _connection.CreateHubProxy("game");

            _proxy.On("registerComplete", () =>
            {
                AddMessage("Registration complete, ready to look for a game!");

                Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    _username = Username.Text;
                    StartGame.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                });

                _proxy.Invoke("findOpponent");
            });
            _proxy.On("waitingForOpponent", () =>
            {
                AddMessage("waitingForOpponent");
            });
            _proxy.On("waitingForMarkerPlacement", () =>
            {
                AddMessage("waitingForMarkerPlacement");
            });
            _proxy.On("foundOpponent", () =>
            {
                AddMessage("foundOpponent");

                _game.ResetGame();
            });
            _proxy.On("noOpponents", () =>
            {
                AddMessage("noOpponents");
            });

            _proxy.On("addMarkerPlacement", (message) =>
            {
                AddMessage("addMarkerPlacement");

                _game.AddMarkerPlacement((int)message.MarkerPosition, message.OpponentName == _username ? 1 : 0);
            });
            _proxy.On("opponentDisconnected", () =>
            {
                AddMessage("opponentDisconnected");

                _game.EndGame();
            });
            _proxy.On("refreshAmountOfPlayers", () =>
            {
                AddMessage("refreshAmountOfPlayers");
            });
            _proxy.On("gameOver", () =>
            {
                AddMessage("gameOver");

                _game.EndGame();
            });

            _connection.Start(new LongPollingTransport()).ContinueWith((t) =>
            {
                AddMessage("Connected to server!");
            });

            _game.MarkerAdded = (position) =>
            {
                _proxy.Invoke("play", position);
            };
        }

        private void AddMessage(string message)
        {
            Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Messages.Items.Add(message); });
        }
        private void Register(object sender, RoutedEventArgs e)
        {
            _proxy.Invoke("registerClient", Username.Text);
        }
    }
}

Adding the board, graphics and handling touch

Since this Tic-Tac-Toe game isn’t really that complex, the graphics and game code is going to be quite simple. The game class itself is going to consist of a couple of private fields which we will use a lot throughout the class. These are used to handle the textures that we have loaded, just as we did with the logo before and for handling the game state and the board!

These are the member variables in the game class:

GraphicsDeviceManager _graphics;
SpriteBatch _spriteBatch;
private Texture2D _logoTexture;
private Texture2D _board;
private Texture2D _markerX;
private Texture2D _markerO;
private bool _isGameStarted;
private int[] _boardPlacements;

There’s actually one more member to this class which you might have glanced upon in the longer code sample from the game page, which is the action we use to place a marker. This action will just work as a handler for the touch events. So when we touch the screen it tries to send a marker placement to the server. This might of course not be ideal since bandwidth and messages might cost in an enterprise application, but let’s keep it simple.

public Action<int> MarkerAdded { get; set; }

In case you don’t want to scroll up and see how this is used from the game page, here’s how it’s being used:

_game.MarkerAdded = (position) =>
{
    _proxy.Invoke("play", position);
};

Now, there are actually just a couple of methods in the game class that we are using. From the beginning, this class which is called TicTacToeGame is generated and has a set of methods overridden from its base class. Some of these methods are used when content is loading and unloading or when the state is updated. It is also used when we want to draw something on the screen. It’s a good idea to split this up into different “scenes” if your project grows. However, let’s keep it simple!

The easiest method we can start with is the one that doesn’t rely on anything else, resetting the game and the game board. This following method resets the game board by creating an integer array with 9 positions where each integer starts at the value -1.

The code that is commented out is used to test if the board is possible to fill with different markers:

public void ResetGame()
{
    _boardPlacements = new int[9]; // [] {0,1,0,1,0,1,0,1,0};
    for (var i = 0; i < 9; i++)
    {
        _boardPlacements[i] = -1;
    }

    _isGameStarted = true;
}

We also have two other methods that don’t rely on anything else and these are for ending the game and for adding marker placements:

public void EndGame()
{
    _isGameStarted = false;
}
public void AddMarkerPlacement(int position, int marker)
{
    _boardPlacements[position] = marker;
}

The following method is a bit more complex, it’s the method that we use to draw the board. This will use the board placement array to find out where to place the marker in x and y coordinates and then draw it on top of the board. As you can see we use the same methods for drawing the textures as we did with the logotype:

public void DrawBoard()
{
    if (!_isGameStarted) return;

    _spriteBatch.Draw(_board,
        new Rectangle {
            X = 10, Y = 150,
            Height = 400,
            Width =  400},
        new Color(255, 255, 255));

    for (var i = 0; i < 9; i++)
    {
        if (_boardPlacements[i] == -1) continue;

        if (_boardPlacements[i] == 0)
        {
            _spriteBatch.Draw(
                _markerO,
                new Rectangle
                {
                    X = 20 + ((i % 3) * 140),
                    Y = 180 + ((i / 3) * 120),
                    Height = 100,
                    Width = 100
                },
                new Color(255, 255, 255));
        }
        else
        {
            _spriteBatch.Draw(
                _markerX,
                new Rectangle
                {
                    X = 20 + ((i % 3) * 140),
                    Y = 180 + ((i / 3) * 120),
                    Height = 100,
                    Width = 100
                },
                new Color(255, 255, 255));
        }
    }
}

In order to actually draw something on the screen we need to implement the Draw method. This method will actually use the method we just looked at for drawing the board, just so that we don’t have too much code in one method:

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.White);

    _spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null);

    _spriteBatch.Draw(_logoTexture, new Rectangle { X = 10, Y = 10, Height = _logoTexture.Height, Width = _logoTexture.Width }, new Color(255, 255, 255));

    DrawBoard();

    _spriteBatch.End();

    base.Draw(gameTime);
}

One final method that we need to implement before we can run our game is the method for updating the game state. It is also here that we handle the touch events. However, in order for us to interpret the touches at taps we need to enable that type of gesture. This is preferable done in the initialization and looks like this:

TouchPanel.EnabledGestures = GestureType.Tap;

The gesture types are enums and are marked as flags, so you can combine different gestures like this:

TouchPanel.EnabledGestures = GestureType.Tap | GestureType.Pinch | GestureType.HorizontalDrag;

We can stay with just allowing tap for this demo though. Now let us take a look at how we handle the touches. The touches will be added to a collection and we can keep track of when there’s no longer any touches on the screen. When we have a touch collection we can see if the current touch (the first touch) is within the bounds of our game board.

Then we can calculate where on the game board the touch is and thus finding out the position:

protected bool Touching { get; set; }
protected override void Update(GameTime gameTime)
{
    var touches = TouchPanel.GetState();

    if (!Touching)
    {
        if (touches.Count <= 0) return;

        if (touches[0].Position.Y < 150 || touches[0].Position.Y > 650) return;
        if (touches[0].Position.X < 10 || touches[0].Position.X > 410) return;

        var column = (int)Math.Floor(touches[0].Position.X / 150);
        var row = (int)Math.Floor(touches[0].Position.Y / 150) - 1;

        var index = column + row * 3;

        MarkerAdded(index);

        Debug.WriteLine("Row: {0}, Column {1}", row, column);
    }

    if (touches.Count == 0) Touching = false;

    base.Update(gameTime);
}

Remote debugging on Surface

I want to try this on my ARM device, so what I first need to do is to change the Platform target to Any CPU as you can see in the image below.

Now verify that you are building against any platform by pressing the arrow next to “Debug” and go to “Configuration Manager”. It should look like this:

Next you need to install and run the application “Remote Debugging” which is available here. You’ll need to scroll down to “Remote tools for Visual Studio 2012″. This should be installed on the Surface (or whatever computer you want to remote debug on!), not the development machine. There’s a great post describing this in details that I suggest you check out.

Finally run the Remote Debugging application on the Surface and set Visual Studio to run on your Surface:

Playing against myself

Now that this is running on the Surface I can bring another instance up in the Simulator and try to play against myself. This is what that will look like:

Recap

This post has gone through a lot of interesting topics and just scratched the surface on many of them. But the idea was to wrap up all the cool things that we’ve looked at with SignalR and Windows 8 for the last couple of months. This post is far to long to fit in a tl;dr but here is a bullet list of the awesome things used in this post:

  • Getting started with MonoGame
  • Adding basic textures with MonoGame
  • Understanding how to add basic images such as PNGs as XNBs with the annoying work-around
  • Creating a basic application that uses both XAML and DirectX
  • Running MonoGame on Surface
  • Communicating with a server using SignalR which runs on Mono, Apache and Linux!
  • Wrapping it all together and porting the Tic-Tac-Toe client to a Windows 8 “XNA” Game that runs on Surface!

I probably forgot one or two things in the list above, but you get the point! We looked at some very interesting things and I think that you can take it from here and make some amazing cross platform games and not be limited by what server software you are running (read: this works on linux with Mono and Apache!).

Where can I get the code?

Don’t worry, you can download the entire solution that I worked on here. Remember that a lot of the code is based on the other SignalR posts that I’ve done:

Don’t forget to check out my screencast on SignalR, here it is again so you don’t forget:

I really hope that you enjoyed this post, I had a lot of fun writing it and if you have any questions, leave a comment, ping me on twitter, send me an e-mail or poke me on JabbR.

Vote on HN

Running SignalR on Mono

Posted by Filip Ekberg on December 10 2012 15 Comments

If you are one of those people, just like I am, that still use Linux for hosting despite that you love and only do .NET development; this is something extremely awesome. Ever since I started using SignalR I’ve wanted to host it on my own servers but all of them run on Linux with Mono and Apache. When David Fowler tweeted a couple of days ago that he was working on getting SignalR working on Mono; I had fireworks in my belly!

When I later told him that I actually run “real” web stuff on Linux with Mono and Apache, I was asked if I wanted to try get SignalR working on Mono! I love working on Windows so ideally I want to build and test stuff on my Windows development machine and then deploy to one of the Linux servers that uses Mono and Apache. The server that I got this running on is running Apache 2.2.14 and Mono 2.11.

tl;dr: You just need to compile the SignalR dev branch and use those libraries. Upload to a host that already runs Mono and Apache!

Preparing SignalR

The first thing that David instructed me to do was to clone the git repository and grab the latest dev-branch. In the future I expect that this work flow will change a bit, but for now this is how you do it.

Fire up you Git Bash and write the following in order:

  1. clone https://github.com/SignalR/SignalR.git
  2. cd SignalR
  3. git checkout dev
  4. git submodule init
  5. git submodule update
  6. build.cmd

After a while when the project has finished building, you should see something like this:

Since this is the dev branch some things have changed from what you might have seen before. For instance Microsoft.AspNet.SignalR.Hosting.Common.dll isn’t there anymore check inside src\Microsoft.AspNet.SignalR.SystemWeb\bin\Debug for the libraries that you will need to use. The Hosting library gave you the RoutingExtensions which is now moved to SystemWeb

Getting Persistent Connection to work

Now that SignalR is compiled and ready to be tested, we can create a new empty web project for .NET 4.0. Since I tried this on Mono 2.11 I am using .NET 4.0!

Let’s get the most basic thing working; the persistent connection. The idea here is that we want to get the broadcast demo that is available on the SignalR Wiki page working. I also showed this in my latest screencast about SignalR.

First we need to add the references to the SignalR libraries that we just compiled and set them to be copied locally.

As you can see the references are from src\Microsoft.AspNet.SignalR.SystemWeb\bin\Debug.

Before we start coding, we can add the JavaScript which you can find in src\Microsoft.AspNet.SignalR.Client.JS\bin. Now we can do just as the Wiki page instructs us to do.

Add a class called MyConnection with the following content:

using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
 
public class MyConnection : PersistentConnection
{
    protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)
    {
        // Broadcast data to all clients
        return Connection.Broadcast(data);
    }
}

You will also need to add a Global.asax file with a route added:

using System;
using System.Web.Routing;
using Microsoft.AspNet.SignalR;

namespace MonoTesting
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");
        }
    }
}

Finally we can add a HTML file with the following content:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
    <script src="jquery.signalR.js"></script>
    <script type="text/javascript">
        $(function () {
            var connection = $.connection('/echo');

            connection.received(function (data) {
                $('#messages').append('<li>' + data + '</li>');
            });

            connection.start().done(function () {
                $("#broadcast").click(function () {
                    connection.send($('#msg').val());
                });
            });

        });
    </script>

    <input type="text" id="msg" />
    <input type="button" id="broadcast" value="broadcast" />

    <ul id="messages">
    </ul>
</body>
</html>

Now we’re ready to compile and run it!

Running it on Apache with Mono

I’m not going to cover how to set up Apache with Mono, there are plenty of tutorials for that out there already. However, all I did was create a new virtual host that is Mono enabled and I copied the content over to that folder and it just works!

Converting a SignalR application to run on Mono and Apache

As you might have seen in my screencast on SignalR I’ve created a Tic-Tac-Toe game, which is also available on github. I downloaded the master and opened up the solution to make the changes needed to get it running on Mono and Apache.

First thing that needs to be done here is to change the Target framework to .NET Framework 4 instead of 4.5. This will cause some issues with the SignalR version that was grabbed from NuGet. So you will also need to remove those before proceeding.

Just as we did with the persistent connection, we need to add the libraries that we compiled and also add the new javascript:

Now we need to replace the SignalR script that we are using in the client HTML to the new script file that we just added to the solution. In the case of Tic-Tac-Toe we replace:

<script src="/Scripts/jquery.signalR-1.0.0-alpha2.min.js" type="text/javascript"></script>

with

<script src="Scripts/jquery.signalR.js"></script>

Finally if you haven’t already, force long polling for the time being:

$.connection.hub.start({ transport: 'longPolling' });

Compile and run it locally to test that it still works then upload to your favorite Mono hosting! There’s a live demo available at signal.fekberg.com that looks like this (and as you can see it runs on Mono + Apache!):

Need an introduction to SignalR?

Vote on HN

ASP.NET MVC, Web API & Web Pages released as open source on CodePlex

Posted by Filip Ekberg on March 28 2012 Leave a Comment

Microsoft have just released a lot of code openly on CodePlex.

I don’t think I need to stress how amazing this is!

The source code just released includes the following:

If you head over to the CodePlex page called ASP.NET Web Stack. You’re going to find a lot of useful information here regarding the code base. Since CodePlex now supports git, it’s Very easy for a lot of us to integrate with the development process and contribute patches, yes, you heard me right: contributions by anyone!

To get started, fire up your favorite git program and clone this repository: https://git01.codeplex.com/aspnetwebstack.git.

I’m using SmartGit in Windows and as you can see by the following screenshot, you’ve got a lot of nice information about the commits, branches, merges and fixes! Most important of all, it’s alive, there are a lot of contributions made the last couple of days and I really think this will increase the quality of what is already high quality.

When you’ve got all the code fetched from the repository, all you need to do is fetching all the NuGet packages. They’ve made this process pretty simple, all you need to do is open up a command prompt, go to the folder where your local repository is and write the following:

build RestorePackages
build

Now you’re ready to contribute to ASP.NET MVC/Web API/Web Pages! There are multiple ways to how you can contribute, head over to CodePlex and read more about it.

Vote on HN

Introducing the ASP.NET Web API

Posted by Filip Ekberg on March 19 2012 8 Comments

In the new version of ASP.NET you can use something called ASP.NET Web API. This allows you to expose your data in many different formats, such as XML or JSON. The idea is to provide a REST API where you use HTTP for real. Meaning that you use GET/POST/PUT/DELETE. These work pretty straight forward:

  • GET – Retrieve all or one item
  • POST – Add an item
  • PUT – Update an item
  • DELETE – Remove an item

As mentioned above, you can retrieve data in different formats such as XML or JSON. The type of data that will be in the response is determened by the HTTP header Accept. By default(built-in) you can use the two following accept headers:

  • application/json
  • applicaiton/xml

In order to try this out, I will be using curl to make the web requests, because this will allow me to specify the headers manually.

Start off by creating a new ASP.NET MVC 4 Web Applicaiton in Visual Studio 11 Beta:

Then you will be presented with what kind of ASP.NET MVC 4 project that you want to create, select to create a new Web API project:

When the project is created, you’ll have some new things that you haven’t seen before in a normal ASP.NET MVC application. It does look a lot like a normal ASP.NET MVC applications, but with some minor add-ons.

The first thing that we are presented with is the ValuesController and this controller inherits from the ApiController. The ApiController is what you will inherit from when you are creating API specific controllers. It will help you map the HTTP requests GET/POST/PUT/DELETE to the methods with the corresponding names.

The second thing that is added is inside the global.asax.cs, a new route to specify where we retrieve the API specific controllers:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

This just help us distinguish between our API calls and non-API calls. If you just start the web application and navigate to /api/values/ you will see a list like this:

If we open this in Internet Explorer 10 instead, it will request a JSON result instead of XML and if we open that up in notepad, it looks like this:

We can verify that this works by testing it out with curl.

Get JSON using curl

curl -H "Accept: application/json" -H "Content-Type: application/json" -X GET "http://localhost:13938/api/values"

JSON Result:

["value1","value2"]

Get XML using curl

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET "http://localhost:13938/api/values"

XML Result:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>value1</string>
    <string>value2</string>
</ArrayOfString>

This is good and all, but we might want to be able to specify what kind of format that we expect with a query string. To do this, we can register a formatter for a certain query string mapping. Go back to global.asax.cs and add the following at the end of Application_Start:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

This will allow you to add ?type=json or ?type=xml to request a certain output format:

If you want to retrieve a specific item, you can simply do /api/values/1.

This has been a short introduction to get you started with the ASP.NET Web API. If you found this interesting, stay tuned for the live stream that I will do from Webbdagarna (if the Internet connection allows) and also stay tuned for upcoming posts where we hook up with Entity Framework to make this API more alive.

Vote on HN

Don’t miss me coding on stage for 2 days at Webbdagarna!

Posted by Filip Ekberg on March 17 2012 2 Comments

There’s a Swedish event in Stockholm 22-23 March called Webbdagarna (translation: web days). The focus of the event is to talk about e-commerce, social media, mobile development and much more. It’s not so much programming focus, in fact the only coding part of the event is what me and my colleuge will do.

The idea is that we are going to sit on stage for 2 days right next to the speakers to create a very cool mobile app, live! My main focus on this will be to create the API for the application, I will of course use the latest technology for this:

Our focus is to deliver a proof of concept and not a finished product, but since the audience will be “social media experts”, “seo experts” and whatnot, they won’t be interested in seeing the code. But I know that many of you guys would like to see this so I will be live streaming from the event on JustinTV (if the organizers and bandwidth allows for it).

You can find the stream at justin.tv/fekberg.

I will be at the event to reprecent Star Republic which is where I work as a Software Engineer. We put together a pretty fun YouTube video presentation about what I will do there, I talk Swedish in it. So for you guys that don’t talk Swedish it might be like listening to the Swedish Chef(muppets)!

Video translation: I am Filip Ekberg and I work as a Software Engineer at Star Republic, follow us on this rock-n-roll journey, where we build Swedens coolest app, live on stage at Webbdagarna in Stockholm 22-23 March!

Don’t forget to follow me on twitter, this is where I will announce and communicate with everyone at the event (and outside the event).

Hope you’ll tune in – Rock On!

Vote on HN

Creating a NuGet Package

Posted by Filip Ekberg on February 26 2012 Leave a Comment

I put together a short video that shows how you can create your own NuGet Package. This requires that you download the NuGet Package Explorer. Be sure to check out the NuGet documentation, it is very good.

Vote on HN