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

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

    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