Using bit fields in C#

Posted by Filip Ekberg on May 14 2013 9 Comments

Recently I came across a problem where I wanted to allow combinations of a certain criteria so I immediately thought of bit bit fields. This lead me to an interesting answer on StackOverflow for a question on how to use the FlagsAttribute with Enums.

What I mean about combinations of certain criteria is that let us say that we have a set of colors and I’d like to define that my pants have more than one color. Then somewhere in my application I’d like to check whether or not the pants had a certain color or not. This could of course be solved in many different ways. One other way could be to just store a collection of colors on the pants class. That would however make this article less fun. So let’s take a look at how to use bit flags. Both the answer on SO and the link to FlagsAttribute above which has some examples use colors for their demonstrations, this is because it’s a very common and easy scenario.

Let’s say that we define RGB, Red, Green and Blue by using bits. This could mean that we have three colors with bit representations as followed:

Now let’s say that we have all colors together, that means that we have the following bits:

Red, Green and Blue added together! So why does this matter? If you don’t know your bits and bytes it’s going to be quite difficult to understand. There’s an older article that I’ve written about bits and bytes, check that out if this is all Greek to you!

As you see it just “added” the bits together, but how do we do this in C# then? It looks “so easy” on paper! First we need to fine an enumerator for this.

[Flags]
enum Colors {
    Black = 0,
    Red = 1,
    Green = 2,
    Blue = 4
}

If you’ve peeked at the StackOverflow answer linked above, you might already know that using the attribute Flags doesn’t do anything at all. Except it’s handy if we use reflection and it changes the output when we print the value.

Now, how do we use this enum? It’s also easier than you might think!

By using something called “OR” we can add values together and get a nice bit representation. OR is written with a single | like this:

Colors color = Colors.Red | Colors.Green | Colors.Blue;

The value of color will now be 7. Why? If you add the numbers together in the figure which shows the bit representation of Red + Green + Blue, you’ll see that you will get the value 7!

If we go back to the original “Problem” now, how do we check if a certain color exists in this bit representation of colors? Let’s talk a bit about OR first. What OR does is that it checks two bit representations and once a 1 occurs, a 1 is set in the result. That might sound confusing. So let’s say that we have 0001 | 0010 the result of this would be 0011. So the 1 is dominating here, if there’s a 1 in either of the two bit representations that you are “OR”-ing then there’s going to be a 1 at that bit in the result.

As there’s something called OR, there’s most likely something called AND, right? There sure is! That however works a bit different it checks if there’s a 1 in both representations. AND is written with a single & and you use it pretty much like OR. So if we use AND on the following 0001 | 0011 the result would be 0001 because the first bit is the only one that has a 1 in both the representations.

Now you might have already jumped the gun and figured out how to find out if one color occurs in the combination of colors however I’ll just expect that you haven’t! It’s quite easy though when you think about it for a while. If you can use AND to “filter” out everything that is not exactly as the representation that you want, then you can probably use this to check if there’s an occurrence of our bits!

So let us say that we have all the colors 0111 now if we AND this with the color red, which is represented with 0001 the result of this AND operation will be 0001 and thus we found the color red! In C# this would look like this:

var hasRedColor = (color & Colors.Red) == Colors.Red;

As of .NET 4 you can also use Enum.HasFlag which work like this:

if (color.HasFlag(Colors.Blue))
{
    Console.WriteLine("Oh Hai there Blue!");
}

Here’s a more complete example of how you can play around with this:

class Program
{
    [Flags]
    enum Colors
    {
        Black = 0,
        Red = 1,
        Green = 2,
        Blue = 4
    }
    static void Main(string[] args)
    {
        Colors color = Colors.Red | Colors.Green | Colors.Blue;

        if ((color & Colors.Red) == Colors.Red)
        {
            Console.WriteLine("Oh hai Red");
        }
        if ((color & Colors.Green) == Colors.Green)
        {
            Console.WriteLine("Oh hai Green");
        }
        if ((color & Colors.Blue) == Colors.Blue)
        {
            Console.WriteLine("Oh hai Blue");
        }

        Console.WriteLine((byte)Colors.Black);
        Console.WriteLine((byte)Colors.Red);
        Console.WriteLine((byte)Colors.Green);
        Console.WriteLine((byte)Colors.Blue);
        Console.WriteLine((byte)color);
        Console.WriteLine(color);
    }
}

Will you be using this in your applications or do you think this is the completely wrong approach?

Vote on HN

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

Don’t deadlock with async and await

Posted by Filip Ekberg on April 3 2013 3 Comments

Deadlocking is really something you need to avoid and in case you don’t know what a deadlock is here’s a great illustration of a “real life deadlock”:

deadlock

Basically what has happened here is that all the roads are full with cars and all the cars try to cross the road at the same time. Let’s translate this into computer terms; the cars in this case are the threads and the cross-over is the “thing” that handles these threads. In the illustration above all the cars have driven into the cross-over at the same time and they can’t really back up, hence there’s a deadlock and there’s no way to go.

What happens in a computer program when you get a deadlock is that it freezes and there’s no where to go because all paths are occupied or waiting for something to finish. Let’s say that process X waits for process Y and process Y waits for process X and both of these lock up the GUI thread, this means that the application will die. Hence deadlocking is something you want to avoid.

Normally you solve this by introducing locking and semaphores. As discussed in the article linked above (where I got the very nice illustration) a semaphore can be seen as a traffic light which handles how the cross-over is loaded with cars.

A while back I wrote an article called “Avoid shooting yourself in the foot with Tasks and Async”, I suggest that you should always return a Task from your asynchronous methods and you really should. What I am about to tell you below though is what you should avoid when doing this.

When a method is marked as asynchronous and the await-part is reached, the method will “exit” and return the “awaiting Task“, which means it’s not the Task that runs inside the method but in fact a Task that keeps track of the status of the asynchronous operation.

Let’s look at a basic code sample!

Consider that you have the following basic asynchronous method, all it does is that it waits for 2 seconds and then prints something to the debug window:

private async Task RunAsync()
{
    var run = Task.Factory.StartNew(() => {
        Thread.Sleep(2000);
    });

    await run;

    Debug.WriteLine("Execution done!");
}

Once await is reached, what will happen? A Task will be returned, but which one? Not the one named run! A Task that keeps track on the state machine will be returned.

Now what happens if we call this method on the GUI thread and asks to wait for it to finish? Calling Wait freezes the current thread and since we are on the GUI thread this will freeze the GUI thread, but for how long? When is Wait happy enough to proceed? In fact it will wait for the asynchronous task that handles the state machine to give it a signal that it’s now ready.

However that Task can never be marked as done until the entire method has been completed. Which means that it needs to access the GUI thread again, since we’re back on the calling thread (GUI thread in this case) after await!

This means that all we have to do in order to deadlock is this:

RunAsync().Wait();

I hope that makes sense to you and gives you an insight into what really happens when you use async and await. As with everything: use it wisely and know what it is that you’re doing.

I’d love to hear about your deadlocking stories!

Vote on HN

Easy error tracking in your applications

Posted by Filip Ekberg on March 26 2013 11 Comments

Over and over again I see developers re-implementing error tracking, I’ve been there myself. One of the reasons to this I think is because many of the tracking tools out there add too much noise and are just cumbersome to use. In many cases the biggest problem is that you need error logging too late, meaning that you want the logging once the error has already occurred. It’s of course cleaver to say that you should always think about potential errors from the start, because let’s face it we all write applications that may have unexpected exceptions.

Another problem is that if we do decide to log errors in our applications, where do we store them and how do we collect the logs? Luckily there’s tools out there that can help us on the way. One that I most recently came across called Raygun. Raygun is a product from the company Mindscape that have some very interesting products in their family.

Error handling just got awesome!

The punch line of Raygun is quoted above, a tool that makes error handling awesome. Let’s clear something up right before we take a look at Raygun , there are multiple providers supplied for Raygun: JavaScript, .NET, Java, PHP and Cold Fusion. Didn’t find the language you work with? Don’t worry, there’s a REST API for you RESTafarians!

So there are providers for Raygun, but what does it actually do?

Imagine that you have your web application written in PHP, ASP.NET or just something that is using JavaScript. Now you want some centralized place where you can store errors in either of these applications, be it severe exceptions or just notices about something unexpected.

If you’ve found yourself writing an error tracker where you just dump the Stack Trace and the exception message into a database, then this is certainly something for you. Imagine that if your customer calls up and says that he recently got the yellow screen of death but don’t know what he was doing or really exactly what time it was.

Now imagine that you were to access your centralized error tracker and you’d have all of the information that you would need to find the error in the code base including:

  • Time of error
  • How many times the current error have occurred
  • Information about the system the user is using
  • The exception message
  • A Stack Trace

That is Raygun! A way to track your errors in a very easy way and the presentation is just beautiful.

The information you’ll get out of each error report of course depends on the data that you supply Raygun with. Take a look at the REST API to get an idea of all the data that you possibly could supply Raygun with.

Enough with what, let’s look at the how! Let’s look at some code!

For this demo I’m going to setup 2 things an ASP.NET MVC 4 Application and a Class Library that will simulate a data store where I can search for people. The web front will allow me to search for people inside my collection and when I wrote this example Raygun actually helped me detect one of the errors I were getting, let’s call this “TrackCeption”.

First of all let’s look at the library. There’s a very easy class that represents the person, it simply has a property called “Name” inside it.

public class Person
{
    public string Name { get; set; }
}

Secondly there’s a class that handles the search requests, I call this RequestHandler. To set this up we need to create a new list of people, in this case it’s just going to be a static collection of people as you can see here:

private static IEnumerable<Person> _people;
public RequestHandler()
{
    _people = new Person[] {  
            new Person { Name = "Filip" },
            new Person { Name = "Sofie" },
            new Person { Name = "Johan" },
            new Person { Name = "Anna" },
        };
}

Now we need a way to retrieve all these people and I like creating asynchronous methods where the operations might be time consuming and in this case I know that it will take 2 seconds to retrieve the list of people:

public Task<IEnumerable<Person>> GetPeopleAsync()
{
    return Task<IEnumerable<Person>>.Factory.StartNew(() => {

        Thread.Sleep(2000);

        return _people;
    });
}

This leaves us with implementing a method that lets us search for people in the collection. So far we don’t care if the list has been empty or not but when we search we want to report an error when there’s no people in the list. Let’s just assume that this is an exception in the application and the end user will always search for people that are in the list.

Let’s install Raygun!

Installing Raygun is as easy as saying “I’ll soon blast all my errors with this Raygun!”; simply bring up the NuGet package manager and write the following:

PM> Install-Package Mindscape.Raygun4Net

This will install Raygun into your class library! There’s a couple of more things that we need to do in order to get Raygun up and running:

  • Create an account and an application at Raygun.io
  • Add the API Key to your application

Creating a Raygun account is free for 30 days and you’ll need to do it in order to start tracking your errors. Once you’ve setup an application on Raygun you can retrieve the API Key from the “Application Settings” menu like you can see in the following image:

RaygunAPIKey

We don’t need to add the API Key just yet, we’ll add that in the application configuration file of the project that will use our library later on (in this case the MVC 4 project).

Now, bringing in Raygun into our application using NuGet will allow us to write the following:

new RaygunClient().Send(new Exception(string.Format("People with name `{0}` not found", name)));

That will create a Raygun client and send a new exception with the message you can see to the Raygun servers and passing it the API Key that we will provide later on. So let’s take a look at how the method that will find people in the colleciton will look like. This one also takes 2 seconds to execute so we will have this one asynchronous as well, we don’t need to do it but I take every chance I got to play with asynchronous programming.

public Task<IEnumerable<Person>> FindPeopleAsync(string name)
{
    return Task<IEnumerable<Person>>.Factory.StartNew(() =>
    {
        Thread.Sleep(2000);

        var people = _people.Where(x => x.Name.Contains(name)).ToList();

        if (people == null || !people.Any())
        {
            new RaygunClient().Send(new Exception(string.Format("People with name `{0}` not found", name)));
        }

        return people;
    });
}

The method will look for people with the name of the value that we passed to the method and if there’s no people found it will send this notice to Raygun. You might think to yourself that this isn’t really a good exception at all, but for the purpose of the demo, let’s just look pass that. Also a bird whispered into my ears that Mindscape is working on adding other message types than exceptions to Raygun, but that’s in the future.

This leaves us with a structure looking like the following:

RaygunDemoLibrary

We are now ready to use our library!

Create a new ASP.NET MVC 4 Application, I named mine RaygunDemo. The first thing that we are going to do is to add Raygun to this project as well, install it into the ASP.NET MVC 4 project using NuGet as we did before and open up web.config once this is done.

In order for us to get Raygun working we need to add our API Key. To do this we first need to add an element inside <configSections>:

<section name="RaygunSettings" type="Mindscape.Raygun4Net.RaygunSettings, Mindscape.Raygun4Net"/>

This will allow us to add a configuration like this:

<RaygunSettings apikey="YOUR_API_KEY_HERE" />

It should look something like this in your web.config, with a lot of extra stuff as well of course:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="RaygunSettings" type="Mindscape.Raygun4Net.RaygunSettings, Mindscape.Raygun4Net"/>
  </configSections>
  <RaygunSettings apikey="YOUR_API_KEY_HERE" />
</configuration>

Remember I said that Raygun helped me find an exception in my application when setting up the demo application? This is because I told Raygun to submit all the application errors. In the ASP.NET MVC 4 project, open up Global.asax and add the following method, this one will be run every time there’s an error in the application:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    new RaygunClient().Send(exception);
}

This means that every time that we get an application error Raygun will be noticed of this and the entire Stack Trace, Computer info and such will be passed into Raygun!

All there’s left to add now is the Home controller and the view, the Home controller consists of two asynchronous actions that will use the library we just created. One will return a view and the other will return a Json result:

public async Task<ActionResult> Index()
{
    var requestHandler = new RequestHandler();
    var people = await requestHandler.GetPeopleAsync();

    return View(people);
}
public async Task<JsonResult> Search(string search)
{
    var requestHandler = new RequestHandler();
    var people = await requestHandler.FindPeopleAsync(search);
           
    return Json(people);
}

The view is equally simple, it only has a text box that allows us to search for names and then it has a list that shows all the people. Once a key is pressed inside the text box an event is fired that requests the people that have a name containing that part:

@model IEnumerable<RaygunDemoLibrary.Person>

<div>
    <span>Search: </span>
    <span><input id="search" type="search" /></span>
</div>
<h2>People</h2>
<div id="people">
    @foreach (var person in Model)
    {
        <div class="person">
            <span>@person.Name</span>
        </div>
    }
</div>

@section scripts{
    <script>
        $("#search").keyup(function () {
            searchValue = $("#search").val();
            $.post("/Home/Search", { search:  searchValue}, function (data) {
                var peopleDiv = $("#people");
                peopleDiv.html("");
                data.forEach(function (person) {
                    name = person.Name.replace(searchValue, "<strong>" + searchValue + "</strong>");
                    peopleDiv.append("<div class='person'><span>" + name + "</span></div>");
                });
            });
        });
    </script>
}

If I start this and search for a name that exists and one that doesn’t it will look like the following:

RaygunReportError

Funny thing is that we didn’t actually notice anything when we searched for something that didn’t exist. So how do we know that this worked?

Raygun comes with an Amazing dashboard that will give you an overview of everything including all the recent errors, how many errors/ignored errors you have and much more like you see in this image (click to enlarge):

RaygunReport

Finally this is what it looks like when you go into details about an exception, you’ll have a graph over how many times and when it occurred and then you have very much details that will help you Raygun the errors!

RaygunStackTrace

If you’re unable to add code to your current website you can simply add a HTTP Module and a config value! Which means you could simply add this in your web.config provided you have the dll as well of course!

<httpModules>
  <add name="RaygunErrorModule" type="Mindscape.Raygun4Net.RaygunHttpModule"/>
</httpModules>

I really recommend giving Raygun a try! Let me know what you think of it and if you have any alternatives that are equally awesome!

Vote on HN

What language features do you miss in C#?

Posted by Filip Ekberg on March 1 2013 21 Comments

35563491Every now and then I hear people shout “I really wish C# would have X and Y, it would make my life so much easier”. This makes me think about what features I’d like to see supported in the language. There are multiple factors to take into consideration when thinking about what should be a language feature and not.

If C# would be completely open source and driven by the community we would probably see a lot of pull-requests for new language features. But I’d imagine that many of these features were implemented by someone that felt like the problem solved some in their opinion generic case. This might not actually be the case though. When adding a new language feature, to any language, you need to take into consideration that a big part of the community should benefit from it.

A good example is how language features for asynchronous programming were added in .NET 4.5. But asynchronous programming was possible before this. “All” it really does is adding a nice state-machine and does all the heavy lifting for us. This is something that developers doing asynchronous programming would have to implement over and over again thus making it a perfect candidate to become a language feature.

Mindscape has an article about what F# features every C# developer should lust after which brings up some interesting language features such as:

  • Pattern matching
  • Immutability
  • Object expressions

What language features do you miss in C# and why? Keep in mind that a language feature should target a broad audience! Maybe you’re happy with what is in the language right now?

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

Vote on HN

Optimize your delegate usage

Posted by Filip Ekberg on February 15 2013 19 Comments

Kudos to David Fowler for spotting this! We had a chat on JabbR and David pointed out something quite odd about delegates which he had discovered while optimizing some code.

Let’s assume that we have the following code that declares a delegate and a method that uses it:

public delegate void TestDelegate();

public void Bar(TestDelegate test)
{
    test();
}

Now consider that you want to run this method and pass a method for it to execute that corresponds with the delegate. The process of running this will be in a loop that runs for 10 000 iterations.

The method we want to run is called Foo and looks like the following:

public void Foo() { }

Everything is set up, so what is it that we need to optimize when calling this 10 000 times? Well we have two different ways of using the method with a delegate.

Option 1
The first option is that we can use an anonymous method to call this method looking like the following:

for (var i = 0; i < 10000; i++)
{
    Bar(() => Foo());
}

If we compile this and open it up in Reflector to see what is generated, there’s also some other stuff generated behind the scenes but this is the important part:

TestDelegate test = null;
for (int i = 0; i < 0x2710; i++)
{
    if (test == null)
    {
        test = () => this.Foo();
    }
    this.Bar(test);
}

Looks good so far, right? Let’s take a look at Option 2 and compare.

Option 2
The second option that we have is just writing the method name to tell it to use this like you can see here:

for (var i = 0; i < 10000; i++)
{
    Bar(Foo);
}

This one is quite common and I’ve seen it used a lot, but what happens behind the scenes here?

If we open this up in Reflector we can see that the following code was generated:

for (int i = 0; i < 0x2710; i++)
{
    this.Bar(new TestDelegate(this.Foo));
}

UmpOi

This is significantly different from the lambda one! Is your mind blown yet?

Ok let me break it down, it’s quite simple. What happens with option 2 is that it will create 10 000 instances of TestDelegate and thus using a lot more memory. The lambda version was optimized but the “normal” one wasn’t?

Let’s just verify that it actually does use a lot more memory! I’ve set the solution to compile in Release mode with Optimization turned on and I’m using the following code to test it:

public class Program
{
    public delegate void TestDelegate();

    public void Bar(TestDelegate test)
    {
        test();
    }
    public void Foo()
    { }

    public static void Main()
    {
        var program = new Program();
        GC.WaitForFullGCComplete(100000);
        Console.WriteLine("Memory usage before Lambda version:\t{0}", GC.GetTotalMemory(false));

        program.LambdaVersion();
        Console.WriteLine("Memory usage After Lambda version:\t{0}", GC.GetTotalMemory(false));

        GC.WaitForFullGCComplete(100000);
        Console.WriteLine("Memory usage before Normal version:\t{0}", GC.GetTotalMemory(false));

        program.NormalVersion();
        Console.WriteLine("Memory usage After Normal version:\t{0}", GC.GetTotalMemory(false));

    }
    public void LambdaVersion()
    {
        for (var i = 0; i < 10000; i++)
        {
            Bar(() => Foo());
        }
    }

    public void NormalVersion()
    {
        for (var i = 0; i < 10000; i++)
        {
            Bar(Foo);
        }
    }
}

Here’s the result from that operation:

Memory usage before Lambda version:     29460
Memory usage After Lambda version:      37652
Memory usage before Normal version:     37652
Memory usage After Normal version:      357140

Conclusion

If we use delegates “wrong” or don’t think what code is actually generated this can leave us with large memory imprints. Of course you always need to think about the code you write but in some cases you might not really know what the compiler ends up doing.

By using the lambda version instead in this case we’ve avoided to create a lot of new delegate instances and thus minimized the memory imprint.

Fun fact: If we compile the “normal version” using MonoDevelop and Mono (2.10.9) it results in the same output. Which leads me to think that this is by design. The only difference is when we compile the lambda version but nothing significant that changes the behavior at all.

Do you say this is a bug or a feature? Did you know it behaved like this?

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

    Compilation as a Service and the next generation plugins

    Posted by Filip Ekberg on February 7 2013 3 Comments

    I’ve written a lot about Compilation as a Service with Roslyn before on this blog and I just had a presentation about it, again. This time I talked about how to use Roslyn in order to create plugins. Actually how to create two different types of plugins; plugins using Roslyn to analyze code and plugins written for applications created in Visual Studio using Roslyn to compile code.

    I’ve also written about Roslyn in my recently published book (which is currently on a discounted price!), be sure to check that out. For your information the book is available in Print, Kindle, PDF, ePub and Mobi; the three last ones here are included in a purchase of the printed copy!

    Watch the below presentation and let me know what kind of ideas you get based on it and also let me know if you like it or not!

    Enjoy these 50 minutes of Compilation as a Service with Roslyn!

    Vote on HN

    Want a free copy of C# Smorgasbord?

    Posted by Filip Ekberg on January 18 2013 32 Comments

    Filip Ekberg showing C# SmorgasbordC# Smorgasbord has been out for about 6 months and as you might have seen previously on this blog and on my twitter, the book has gotten great feedback!

    I’m very happy that so many people have decided to buy the book and that some of you have taken the time to review it.

    To give something back to the community for all the support during my writing process and after (self-)publishing the book, I had a give-away after about 3 months and now I want to give away one (or maybe more!) copies of the book!

    I want to win a free copy!

    Unfortunately I can’t give everyone a copy of the book so if you want to win a free copy of C# Smorgasbord, all you need to do is follow the two steps below:

    1. Leave a comment down below with the reason as to why you should be the lucky winner. It’s a bonus if you include why you like to read this blog.
    2. Share this post with your friends on twitter:

    The best motivation wins and the winner will be notified via e-mail, so be sure to leave your e-mail address when you’re commenting below. You’re e-mail address will never be visible to anyone else than me!

    That’s it! Good Luck to you all!

    The draw ends February 1 (6pm CET) and all comments will be published once they’ve been received

    What’s C# Smorgasbord?

    C# Smorgasbord covers a vast variety of different technologies, patterns and best practices that any C# developer should master.

    Looking at everything from testing strategies to compilation as a service and how to do really advance 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.

    Is there a digital version(ebook)?
    Yes there is! Everyone that purchases the printed copy will get the ebook for free. Instructions for how to receive the ebook is inside the printed book.

    Table of Contents

    1. Introduction to Parallel Extensions
    2. Productivity and Quality with Unit Testing
    3. Is upgrading your code a productive step?
    4. Creating a challenge out of the trivial tasks
    5. Asynchronous programming with async and await
    6. Dynamic programming
    7. Increase readability with anonymous types and methods
    8. Exploring Reflection
    9. Creating things at runtime
    10. Introducing Roslyn
    11. Adapting to Inversion of Control
    12. Are you Mocking me?

    Who this book is for
    This book is for those developers that find themselves wanting to explore C# but do not know how or where to start looking. Each chapter contains hands on code examples that can be compiled and tested on your machine.

    Although each chapter has code samples, you do not need to use a computer to appreciate the content of this book. The code samples are divided into smaller portions of code, so that you can follow each example and the thoughts around it in an easy way.

    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.

    It is not required that you have worked with C# before but being familiar to the fundamentals in any of the .NET programming languages will help you on the way.

    If you are just now starting to learn C#, this can be a great way for you to learn about different techniques, best practices, patterns and how to think in certain scenarios. But if you have worked with C# development for many years, this book can give you a refreshing view on how to always improve and challenge yourself into becoming a better software engineer.

    I can’t wait and want to buy it now!

    Thanks for the support! Below is a link to Amazon where you can buy the book. It’s available on all Amazon regions.

    There’s also an ebook bundle available here.

    Vote on HN

    I’m using dynamic and unexpectedly lost intellisense!

    Posted by Filip Ekberg on January 17 2013 2 Comments

    I’ve written and talked quite a bit about dynamic before, both in this blog, on user groups and in my book C# Smorgasbord. I never get tired of talking about it though because there are always interesting new things to be found out. TheCodeJunkie (author of Nancy) asked something quite interesting on JabbR today which lead to an interesting discussion about dynamic (among other things).

    The question and code sample is pretty easy, let’s say that we have a class in which we have a static method that returns a new instance of that class. This method takes one parameter which is a dynamic type which means that we can end up with a class looking something like this:

    class Person
    {
        public Person Mother { get; set; }
        public static Person CreateBaby(dynamic mother)
        {
            return new Person { Mother = mother };
        }
    }

    So the question that he asked was, what if we create an instance of it like you see in the following code, what type will the variable be? Because if it is dynamic, we will have lost intellisense.

    static void Main(string[] args)
    {
        dynamic parent = null;

        var baby = Person.CreateBaby(parent);
    }

    Without trying this in Visual Studio, what do you think? Leave a comment below telling me what you expected it to be and what it really was once you (continued reading) tried it for yourself!

    At a first glance, it looks like the compiler will know that Person.CreateBaby returns a statically typed object of type Person. Before we take a look what happens, let’s inspect the IL with reflector:

    .method private hidebysig static void Main(string[] args) cil managed
    {
        .entrypoint
        .maxstack 8
        .locals init (
            [0] object parent,
            [1] object baby,
            [2] class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo[] CS$0$0000)
        L_0000: nop
        L_0001: ldnull
        L_0002: stloc.0
        L_0003: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`4<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object, object>> DynamicDemo.Program/<Main>o__SiteContainer0::<>p__Site1
        L_0008: brtrue.s L_0049
        L_000a: ldc.i4.0
        L_000b: ldstr "CreateBaby"
        L_0010: ldnull
        L_0011: ldtoken DynamicDemo.Program
        L_0016: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
        L_001b: ldc.i4.2
        L_001c: newarr [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo
        L_0021: stloc.2
        L_0022: ldloc.2
        L_0023: ldc.i4.0
        L_0024: ldc.i4.s 0x21
        L_0026: ldnull
        L_0027: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)
        L_002c: stelem.ref
        L_002d: ldloc.2
        L_002e: ldc.i4.1
        L_002f: ldc.i4.0
        L_0030: ldnull
        L_0031: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)
        L_0036: stelem.ref
        L_0037: ldloc.2
        L_0038: call class [System.Core]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::InvokeMember(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, class [mscorlib]System.Collections.Generic.IEnumerable`1<class [mscorlib]System.Type>, class [mscorlib]System.Type, class [mscorlib]System.Collections.Generic.IEnumerable`1<class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)
        L_003d: call class [System.Core]System.Runtime.CompilerServices.CallSite`1<!0> [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`4<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object, object>>::Create(class [System.Core]System.Runtime.CompilerServices.CallSiteBinder)
        L_0042: stsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`4<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object, object>> DynamicDemo.Program/<Main>o__SiteContainer0::<>p__Site1
        L_0047: br.s L_0049
        L_0049: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`4<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object, object>> DynamicDemo.Program/<Main>o__SiteContainer0::<>p__Site1
        L_004e: ldfld !0 [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`4<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object, object>>::Target
        L_0053: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`4<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object, object>> DynamicDemo.Program/<Main>o__SiteContainer0::<>p__Site1
        L_0058: ldtoken DynamicDemo.Person
        L_005d: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
        L_0062: ldloc.0
        L_0063: callvirt instance !3 [mscorlib]System.Func`4<class [System.Core]System.Runtime.CompilerServices.CallSite, class [mscorlib]System.Type, object, object>::Invoke(!0, !1, !2)
        L_0068: stloc.1
        L_0069: ret
    }

    That does look like a lot of code for just two lines, right? So most likely it wasn’t as simple as the variable being a static type. By looking over the IL above, you’ll see that a lot of runtime stuff is going on and that we in fact see a lot of dynamic here. Let’s compare the IL to what it will look like, if we make a simple modification to the code by just changing the variable parent to a static type instead:

    static void Main(string[] args)
    {
        Person parent = null;

        var baby = Person.CreateBaby(parent);
    }

    The IL produced from this is much easier on the eyes:

    .method private hidebysig static void Main(string[] args) cil managed
    {
        .entrypoint
        .maxstack 1
        .locals init (
            [0] object parent,
            [1] class DynamicDemo.Person baby)
        L_0000: nop
        L_0001: ldnull
        L_0002: stloc.0
        L_0003: ldloc.0
        L_0004: call class DynamicDemo.Person DynamicDemo.Person::CreateBaby(object)
        L_0009: stloc.1
        L_000a: ret
    }

    We still have a dynamic parameter on the method that we are calling so we would have an equal amount of IL as we saw before on that type!

    So what did we actually answer here? Simply put what happens when the use of dynamic is in place, the line of code will be evaluated at runtime. If you try casting the statically typed local variable when we pass it to the method, it will be the same behavior as if it was dynamic all along, as you can see in the below screenshot.

    A dynamic variable

    Did it work as you expected? Leave a comment and let me know!

    Vote on HN