Utilize Roslyn to create the next level plugin capability

Posted by Filip Ekberg on May 2 2013 4 Comments

dotnetConf

We are moving towards a new era where more and more people want to offer the possibility to expand the system with widgets and plugins. By utilizing Compilation as a Service can make it easier for all parties to create plug-ins. For instance operations performed at certain events in an application.Roslyn exposes a C # and VB.NET compiler and we can use this to implement something along those lines. Listen to me give an introductory talk about what Roslyn has to offer and how we can use Compilation as a Service to enable the next level of plugins.

Check out my talk from dotnetConf on the subject and let me know if you’ve got any cool ideas on how to utilize compilation as a service (Roslyn).

You can download the demos and slides here.

Vote on HN

C# Smorgasbord ebook limited-time offer now only €4.99!

Posted by Filip Ekberg on February 26 2013 10 Comments

PriceTag_Off

About 7 months ago I self-published C# Smorgasbord which is a C# Programming book focusing on a lot of different and interesting things. I’ve had a couple of giveaways and a couple of sales so far to spread the word even more.

It’s now time for an ebook limited-time offer, when the offer ends is not yet disclosed so if you’re interested in reading this very well spoken off book get it today for only €4.99! If you don’t have PayPal just send me a message and we’ll figure something out.

The offer includes access to PDF, ePub and Mobi!

After the PayPal purchase you’ll receive an e-mail with a download link within a couple of hours.

CSharpSmorgasbordLogo

Want to peek inside? Sample available!

There’s a “Look Inside” available on Amazon!

About the book

Looking at everything from testing strategies to compilation as a service and how to do really advanced things in runtime; you get a great sense of what you as a developer can do. By taking his personal views and his personal experience, Filip digs into each subject with a personal touch and by having real world problems at hand, we can look at how these problems could be tackled.

No matter if you are an experienced .NET developer, or a beginner, you will most certainly find a lot of interesting things in this book. The book covers important patterns and technologies that any developer would benefit from mastering.

Table of Contents

  • Introduction to Parallel Extensions
  • Productivity and Quality with Unit Testing
  • Is upgrading your code a productive step?
  • Creating a challenge out of the trivial tasks
  • Asynchronous programming with async and await
  • Dynamic programming
  • Increase readability with anonymous types and methods
  • Exploring Reflection
  • Creating things at runtime
  • Introducing Roslyn
  • Adapting to Inversion of Control
  • Are you Mocking me?

Enjoy the read and spread the word!

Want a printed copy?

There’s a discount on that one too!

Discount code: N9UV3WDP

Buy now!

Vote on HN

Decompiling .NET Applications

Posted by Filip Ekberg on February 14 2013 14 Comments

There are many reasons to why you might want to decompile an application after it’s been compiled. Compiling C# code “just” translates it into MS IL. The compiler of course does some magic and tweaks the code as much as possible. There’s no metadata stored after compilation which means that comments and such will not be available in the IL output.

The following image illustrates what happens when we compile something, we put the C# code into a basket and tell the compiler to give us a binary of this which is sort of a black box at the moment. We know that whenever we want to use this black box we have something behind the curtain that knows how to open it and use it properly (read: CLR).

Compiling C# Code

Let’s consider a basic variable instantiation and an equality check, when this is compiled it will output something partially readable. To me the output is readable but that’s just because I have a weird love for IL. When this basic snippet was compiled using LINQPad it generated some IL which you can see below.

Compiled C# Code

Imagine that you got a DLL from an old co-worker and the code is long gone but you need to make some changes to the code. What do you do? One option is to mimic the functionality if the application is not too big and create it from scratch but that is just cumbersome. Instead what we want to do is something like you can see illustrated below; we want to go back from IL to C#!

Decompiling C# Code

So how do we do this? By using a decompiler!

As I tend to do this quite often to understand how libraries work that I have no control over, I have tried some different tools for just this cause. Let’s take a look at four of the most common ones on the market. Don’t worry, there’s both free versions and paid ones out there!

Telerik JustDecompile

The first one that we’re looking at is a product from the Just* family created by Telerik. I do like the products from Telerik so this one should be quite interesting!

JustDecompile is completely free and available for download over at Teleriks website. One thing that I didn’t like thought was the installer, generally Telerik’s installers are pretty nice, but I don’t like being “guided” to install other stuff than what I’ve asked for.

Below is a screenshot of the installer and as you can see it advices you to install a lot of trials for other Telerik products.

JustDecompile Installer

After selecting only to install JustDecompile the installation will only take up 36MB. You’ll also need to create a Telerik account if you don’t already have one which can also be a hassle, but it’s free so why not!

I’ve setup a project that has the same variable declarations and the equality check from above and then compiled and opened the executable in JustDecompile. The result is quite similar to the original source as you can see in the following image.

Decompiling with JustDecompile

We can also select to show the result as IL instead of C# code!

Decompile with JustDecompile show IL

There are a couple of things that I didn’t find straight forward using JustDecompile.

Pros

  • It’s free!
  • It’s fast!
  • The UI is beautiful
  • It looks easy
  • Does what it should (partially)

Cons

  • There’s a button for creating a project, I expected it to be able to export my binary to a complete VS Solution but it’s grayed out and there’s no tooltip on why that is so.
  • Showing the source as VB instead of C# shows nothing at all, shouldn’t matter if the original code was C# or not.

JustDecompile Summary

Even though there are some cons; would I recommend you using it? Of course! If you haven’t installed it already go ahead and do so! It can only become better if more people support it and give them suggestions. There’s even a suggestion button where you can submit requests.

ILSpy

This one is interesting, ILSpy is an open source assembly browser and decompiler for .NET Applications! This means that if you don’t like what it does or if you have feature suggestions, “you can just” provide the fix yourself! The tool itself is equal to what JustDecompile offers but the installation process is much easier. You simply grab the binaries or source from the ILSpy website and unzip it wherever you want it!

ILSpy

I simply performed the same process as I did with JustDecompile; I started ILSpy and opened up my executable but this is where it gets interesting. The code that it decompiles to looks Exactly like the code that I wrote in Visual Studio as you can see in the following image.

ILSpy Decompile

Decompiling to VB also works right out of the box, this tool has what it takes!

ILSpy Decompile to VB

Now to the more interesting feature; Can we save/export this to a C# Project?

By the looks of it there’s a “Save Code” action in the File menu, selecting the assembly and then pressing ctrl+s or the “Save Code” action actually lets us save a csproj file! If you open up the location in your file explorer you will see that it actually generated a project file and the code file!

ILSpy Save project and Export Code files

I think we’ve looked enough at ILSpy to write up a pros and cons!

Pros

  • Free!
  • Open-Source, do I need to say more?
  • All features seem to work as they should
  • Easy to use interface
  • Fast!

Cons

  • The UI isn’t really that good lookig but it’s functional
  • The application seemed to freeze once but it just took a while to analyze a code file, I had to stretch for this one..

Summary

There really aren’t many bad parts regarding ILSpy, I like it but if I have to complain about something it’s the UI and that it felt like it froze once. I really recommend trying out ILSpy and looking over the code for it, it’s great for educational purposes and I have co-workers that use it all the time and like it a lot.

What are you waiting for, go download!

dotPeek

Just as the two mentioned above dotPeek is available for free, it’s not open source though. dotPeek comes from JetBrains and is available on their website where you can also find a lot of interesting information about how to use it.

Installing this is easy and doesn’t force you or ask you to install anything else than what you really want in this case.

dotPeek

If you are familiar with ReSharper (R#) which is also a product from JetBrains, the keyboard shortcuts will be something of value to you. In fact dotPeek uses the same navigation as you might be used to from using ReSharper!

Let’s have a look at what dotPeek thinks of our executable. When opening up dotPeek you’re meet with a beautiful interface that feels like it’s a part of the Visual Studio family (except for the very colorful icons). Opening up the executable and looking at the code you can see that it didn’t really give us the same result as any of the other decompilers we’ve looked at.

dotPeek looking at the code

So instead of actually displaying what the IL tells us, it analyzes the IL and optimizes the code for us which is really not what we want to do. There’s also no way of swapping between C#, VB.NET, F# or IL. So in this case we are “stuck” with looking at some C# code without knowing what IL it comes from.

What is also a downside to this is that you cannot export the code that you are looking at, which means that this is a pure code browser.

Pros

  • Beautiful UI
  • Fast
  • Code inspection and navigation that you might be used to from ReSharper
  • Supports plugins just like ReSharper

Cons

  • Lack features such as show code in different ways; swapping between VB.NET, F# and IL
  • Doesn’t resemble the actual code that was compiled
  • Doesn’t support exporting code or projects
  • The application itself seem to be very light-weight and lacking configuration possibilities

Summary

While I like JetBrains products in general, this one feels like there’s something missing. Personally when I use a decompiler I want it to be able to show me the output code in different ways and give me options to export it. But if you are looking for an assembly browser that decompiles to C# and just does that, this is perfect. Even better if you are used to ReSharper, you will certainly find the keyboard shortcuts for navigation handy.

.NET Reflector

Last but not least, my personal choice .NET Reflector! I’m not really sure why this is my personal favorite but keep on reading and you might find that it’s because the mixture of good functionality with a common and easy to use UI.

.NET Reflector is available by RedGate but costs money which is maybe why it’s “better” than the alternatives. This wasn’t always the case though once upon a time it was available for free. I was lucky enough to win a free license a while back so I’ve been able to use it quite a lot. You can buy it or grab a free trial over at RedGate’s website.

The installation is easy and doesn’t try to force you to install a lot of other things that you don’t expect. .NET Reflector comes with a Visual Studio extension that will let you use the features in Visual Studio instead of starting a new instance of .NET Reflector.

Just as with JustDecompile and ILSpy I opened up the executable that we looked at before and as expected it shows the same result as ILSpy does!

.NET Reflector

As you can see here the UI is quite minimal and easy to understand. What is interesting here is that it also allows us to view the code as F# code as you can see in the following image.

.NET Reflector F#

If we want to export the code that we have just as we did with ILSpy we can right click the assembly and select “Export source code” this then asks us where to store it and gives us information about the exported files. As you can see in the two following images it exported more files than ILSpy did.

.NET Reflector Export Code

.NET Reflector Export Code Window

And the resulted files look exactly as we expect them to, the code file has the same code as we did in the original source code.

Pros

  • Easy to use
  • Everything is intuitive
  • Everything work as intended
  • Exports more code than alternatives
  • Fast
  • Beautiful UI
  • Cons

  • It costs $368 + tax if you want the VS Extension and this is quite expensive when good alternatives are completely free
  • Summary

    The costs is the only downside that I’ve found during my time using it which means that if .NET Reflector was free tool for Decompiling .NET Applications it would be the number 1 choice. It isn’t free and the cost must be factored in when comparing the value of the product.

    Conclusion

    If I hadn’t won a free license for .NET Reflector I probably would have used JustDecompile or ILSpy as both of them are very good tools for Decompiling .NET Applications!

    We’ve looked at how we can decompile applications and browse the code in different ways when only having the executable available. This also works with libraries in the global assembly cache.

    Looking around in the .NET Framework to see how they’ve done certain implementations can be great for educational purposes but using this at work to understand how someone implements a certain feature can be priceless.

    I hope you’ve found this read interesting and that you’ll be digging deeper with tools for Decompiling .NET Applications. Let me know which one is your favorite or if you’ve used another tool than the four mentioned above!

    Vote on HN

    Congratulations to the winners of a free C# Smorgasbord copy!

    Posted by Filip Ekberg on February 4 2013 2 Comments

    Before I announce the winners, yes it’s plural because it was way too hard to decide one winner, I want to share some great news with all of you. Yesterday I summarized the amount of people that have my book based on the copies that I’ve sold/given away and this number is now above 500 and steadily increasing towards 600!

    The feeling I got when receiving my first proof copies of the book is indescribable, it was pure awesomeness and this feeling is almost as great. It makes me very happy that so many developers have decided to get a copy of C# Smorgasbord, thank you all very much for that. All the great feedback and the amount of copies out there are the basis to why I want and can have these giveaways!

    Now to the winners, I know that’s why you’re here anyways. As the giveaway was re-published on DZone I’m going to include those comments as well. Thanks everyone that participated and I really hope that if you didn’t get a free copy this time, you’ll enjoy the discounted price found at the end of this post.

    The winners are:

    Sergio with the following comment:

    Checking the content this book has, it would be a good reference to create great architectures using advanced techniques like Reflection or runtime thing creation. It also shows last features of .Net framework so it will have good examples of how to understand them (I honestly can’t understand async :$ and no good Spanish doc, besides that, I have no credit card to buy the book :P ) I read about the book on this Hacker News’s link: http://blog.filipekberg.se/2012/07/21/c-smorgasbord-will-soon-be-available/
    (I said: “I need that book!!”)

    Adam with the following comment:

    I would like a copy of your book because everything i learn from it will go onto my blog hopefully passing knowledge onto many others.

    I feel your book will fill in various gaps in my knowledge, and will hopefully help secure that senior developer position and finally, i mentor the other developers around me and the junior developers, and this book will be an excellent resource, and with titles such as “Creating a challenge out of the trivial tasks” will hopefully help inspire the developers to take pride in even the trivial tasks.

    Henric with the following comment:

    Don’t leave a former Sigma colleague hanging! I’ll give you a blog post reviewing the book (on my massive 2 visitors a day blog) and I will spread the Smorgasboard love to current co-workers. :)

    Stay awesome!

    Daniel with the following comment:

    I would like a copy of your book, because I think this would greatly benefit my student project in which we are creating an application where stuff can be augmented and moved / edited with simple gestures :-) Right now much of the code is hacked together, because no one in the group used C# before (the university teaches java :-| ), what leads to “not-so-good” performance and way too many bugs! :-) I am responsible for the code quality and C# teaching and the book would help me to be more helpful to the other guys.

    Malte with the following comment:

    Finished my CS degree last summer, and got a job as a software developer, primarily C#. I try to improve my programming skills every day, and found this blog and blogpost through the “Interesting Finds” blog series from Jason Haley.

    Hadn’t heard about your book, but after reading about it, it seems very “hands on”. And i would love to read it.
    I find it especially awesome that you self-published the book :)

    Congratulations on winning a free copy of C# Smorgasbord, I hope you enjoy it and help others become better programmers as well!

    Now to those of you that didn’t win a free copy. I’ve setup a discount code that can be used on CreateSpace (this is where the book is printed) and this will give you a 35% discount!

    Use discount code N9UV3WDP to get 35% off here (takes you to CreateSpace)!

    Pssst.. if you don’t want to wait for the printed copy to arrive due to (sometimes) long shipping, you can get the ebook the same day as you purchase the printed copy! Just fill out this form.

    Enjoy the read and spread the discount code to anyone and everyone!

    Vote on HN

    2012 was an amazing year, here’s a summary!

    Posted by Filip Ekberg on January 8 2013 1 Comment

    Saying that a lot happened in 2012 is probably an understatement. At least both on this blog and in my personal life, a bunch of amazing things have happened. I really hope that your previous year was good and let’s hope for an even better 2013. To start this year off I want to summarize all the great posts that were shared on this blog in 2012.

    Personally the two biggest achievements of last year was me getting engaged to my lovely Sofie and publishing my book C# Smorgasbord. As you might have seen already this year has already started very good as I have been awarded Microsoft MVP in Visual C#!

    Let me know what you found most interesting on this blog from the collection of posts below! Here is the 2012 summary!

    Architecture

    Tips & Tricks

    Screencasts

    Software & Tool information

    Windows 8, Windows RT, WinRT and Surface

    C# Smorgasbord and Self-publishing

    Other

    I hope you found this collection of posts useful and that you’ve learnt a lot in 2012! Enjoy 2013 and let me know what you think of the posts! Before we take part for this time, I want to share with you an image that describes the feeling I got when I held the first printed copy of C# Smorgasbord:

    Vote on HN

    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

    Introduction to SignalR – Creating a Cross-Platform game

    Posted by Filip Ekberg on November 29 2012 5 Comments

    Have you had a chance to play with SignalR yet? If not, you’re really missing out! While preparing for a Swedish .NET User Group presentation, I did a test screencast on all my content that was going into the presentation. This screencast is uploaded to youtube so go check it out! It’s a bit over 1 hour long but well worth it if you want to get started with SignalR or just get some new inspiration!

    Vote on HN

    C# Smorgasbord Sale!

    Posted by Filip Ekberg on November 20 2012 8 Comments


    C# Smorgasbord has been out for 3 months and has already gotten a lot of positive feedback and great reviews(See below)!

    To thank you all for your support, I’m giving away a discount code for 35% discount on C# Smorgasbord!

    This offer is for a limited time only, the discount will be available from November 20, 2012 to December 31, 2012!

    The discount code works only on CreateSpace; this is where the book is printed. CreateSpace is a DBA of On-Demand Publishing LLC, part of the Amazon group of companies. Buy yourself, your spouse or your kids an early Christmas present!

    Discount code: N9UV3WDP

    Buy now!

    Note that the Discount Code only works on CreateSpace!

    The printed copy includes access to the ebook bundle; so you don’t need to wait for the printed copy to arrive. After you’ve purchased the book just fill out the form on the book’s website! CreateSpace ships globally and their shipment times are in most cases a lot shorter than what it says in their website.

    Want to know more about C# Smorgasbord?

    Want to peek inside? Sample available!

    There’s a “Look Inside” available on Amazon!

    About the book

    Looking at everything from testing strategies to compilation as a service and how to do really advanced things in runtime; you get a great sense of what you as a developer can do. By taking his personal views and his personal experience, Filip digs into each subject with a personal touch and by having real world problems at hand, we can look at how these problems could be tackled.

    No matter if you are an experienced .NET developer, or a beginner, you will most certainly find a lot of interesting things in this book. The book covers important patterns and technologies that any developer would benefit from mastering.

    Table of Contents

    • Introduction to Parallel Extensions
    • Productivity and Quality with Unit Testing
    • Is upgrading your code a productive step?
    • Creating a challenge out of the trivial tasks
    • Asynchronous programming with async and await
    • Dynamic programming
    • Increase readability with anonymous types and methods
    • Exploring Reflection
    • Creating things at runtime
    • Introducing Roslyn
    • Adapting to Inversion of Control
    • Are you Mocking me?

    Want only digital versions?

    If you don’t want to get the printed version you can get the ebook bundle on the book website or the Kindle version on Amazon.

    Enjoy the read and spread the word!

    Update 2012-12-02

    I am extending the offer the rest of 2012! Enjoy the holidays!

    Vote on HN

    Friday with Filip – Do you deliver high quality?

    Posted by Filip Ekberg on October 19 2012 1 Comment

    Welcome to this week’s Friday with Filip!

    During the Fridays with Filip we’ve looked at how to ensure that certain parts of your project conforms to a high standard. I’m talking about the following:

    There are so much more things (even small things) that matter when you want a successful high quality project/solution. You can’t rely on a decent testing strategy, security awareness and rapid development to get high quality. There’s still a lot of other aspects in your project that you need to take into consideration.

    When I studied for my Software Engineering degree there was a lot of talk about requirements documentation, design documents and all other kinds of documents that you had to write in order to get a good overview of the project. But there were actually less talk about how to retrieve this information.

    One of the first things you’ll learn when talking about domain driven design is: use a language that both you and your customer understands. In order to get all requirements or the system design onto paper, you need to understand each other. Do you see where I’m getting at? We need to step back to the basics, to things that was important even before computers and software projects; we need to be able to talk to each other so that everyone understands!

    Previously this week I asked something a bit weird on twitter as you can see in the image below.

    At a glance, this might be a very weird question. Why would you explain something that is so far away from their reality? Someone responded and said that they would just not do it because they would probably be killed for knowing too much.

    Technology is amazing and as a Software Engineer with a burning heart for programming I tend to try (almost) everything new that arrives to the market but not everyone do and this is very important not to forget. Since not everyone is so used to technology, we need to work on the way that we communicate with each other. A couple of years back I built a website that had to do with cars and the people that wanted the website had no idea how the process of building a website looked. So I had to use analogies they understood, I had to talk in car terms.

    Therefore it’s very important to actually step back and find a common ground between you and your customer. Otherwise it will be near to impossible to deliver high quality; you’ll never get the right requirements!

    As I said in the start of this there’s not one or even 5 things that will ensure you deliver high quality, you need to work on all different aspects. Here are some concrete suggestions (that might seem obvious):

    • Find a common ground between you and your customer so that you speak the same language
    • Design the architecture in a way that you could talk about objects and structure in the application which the customer understands
    • Use the right person for the right job!
    • Write lots of documentation before, during and after the delivery
    • Have small iterations in the beginning where you continuously deliver parts of the system for reviewing
    • Do code reviews, swap people around and let everyone review everyone
    • Don’t be afraid to ask your customer questions if you don’t understand
    • Don’t be afraid to ask you colleges for help if you’re stuck!
    • Don’t get used to putting work off by writing TODO’s in the code
    • Take a couple of seconds to write a comment about a method or a complex code block
    • Remember that we’re all human, everyone can make mistakes; help each other out and solve them together
    • Stay on top of new/old technology and use what is best for the project/customer. If a newer framework or tool means more job, maybe it’s the wrong tooling for this job; even if you want to play with the latest toys

    This list can go on and on, frankly there have been books heavier than my laptop written about each point in the list.

    What’s your pro tip to increase quality in the code, project and customer communication?

    Vote on HN