# Friday with Filip – Being productive

## Posted by Filip Ekberg on September 28 2012 3 Comments

### Welcome to this week’s Friday with Filip!

Earlier this week I wrote about how to organize your thoughts by using tools such as Evernote and XMind. Both of these are very easy to work with but are somewhat limited to getting your thoughts into a persistent format. Since productivity is important to all of us, I wanted to spend this Friday on exploring more tools that can be of great use to primarily developers. We live in an era where everything needs to be done as quickly as possible, with the highest quality and costs as little as possible. This can pose as a problem in many cases because they don’t quite fit that well together.

In my previous article, Let’s write better software, I discuss how we’ve been entering a world with more and more hardware and software; whereas bugs are more an expectation than an exception. This is of course a big problem, since we all want bug-free world. As many have pointed out though, the biggest problem are the people that are unwilling to pay for quality; of course, that’s not the way it’s sold. In many cases it’s either getting the contract or not getting the contract which can lead to doing the same thing within a more narrow time period.

Before this get’s out of topic, let me explain why this is about productivity. When we need to do something faster but still maintain the same amount of quality. We need tools to help us with analysis, suggestions and in programming we want help with refactoring. Without such tools, we would be less productive. This expands over many areas, not only development.

### The right tool for the right job

This week I want to be more concrete and give hands on examples on what tools that I use in my day-to-day work environment. Feel free to leave suggestions on what productivity tools that work best for you and for your team.

There are a couple of areas where I try to be as productive as possible (of course I always want to be productive!):

• When I’m in a meetings
• When I’m coding
• When I follow up on a bug

As I stated in my previous post organize your thoughts, I use some tools to get my thoughts down quickly. But it is also important when you’re meeting with a customer or a college and a bug is presented, this needs to be documented in a good way.I’ve been using Pivotal Tracker for a while now and I like it; I would however like to give TFS 2012 a fair chance.

Pivotal Tracker allows us to track development, bugs, ideas and both give the project members and the customer a great overview of the project progress. This together with Evernote and XMind is very powerful and gives me a total set of powerful applications to use in a meeting.

Another tool that I like to use, which makes my understanding of a system better, is balsamiq mockup. This mockup tool lets you create nice overviews of how the UI will look when the system is done. When you’re brainstorming with your customer around what the UI will look like, this is a very productive tool to have in your collection.

When we’re done with a mockup, we can simply save it on the corresponding bug, task, feature or idea in Pivotal Tracker.

When I’m coding it’s very important to me that my tools are not in the way of my development. For instance, I don’t want a lot of non-natural keystrokes or popups to use. I’ve been swapping between ReSharper and JustCode.

When using ReSharper I get a lot of nice instant feedback on what I can do to improve my code, this makes it easier if someone is going to review the code at a later stage:

JustCode supplies the same amount of keyboard mappings, analysis and refactoring capabilities but one other thing that it provides is a way to stick a cheat-sheet on your desktop. This makes it very productive when I need to get use to some keyboard shortcut:

If you want to code productively, here are some recommendations:

• Spend a while analyzing what keyboard shortcuts your IDE provides
• Use productivity tools such as ReSharper and JustCode
• If you’re using Visual Studio, learn how to use Snippets
• Use a source control that is not in your way

These might seem obvious, but adapting to these sure helps me being productive. If I can solve a problem faster with just as much quality, I can spend the additional time that I just won on making the solution better.

What are your recommendations on being productive?

# Let’s write better software

## Posted by Filip Ekberg on September 27 2012 3 Comments

### Bugs are an expectation instead of an exception

Technology have been a big part of my life ever since I was a kid. If it wasn’t a console it was a computer and later came the mobile phone. All these things running on electricity have always interested me. My first mobile phone was a Nokia 5110, which is the only phone that actually never broke.There’s a joke around the net that the old Nokia phones never broke and that’s very true; however they didn’t do much more than calls, sms and snake.

When the phones with color displays appeared the mobile vendors noticed that people wanted to switch phones often; as soon as a new feature was released everyone had to have it. The vendors immediately started pushing out more and more phones, a lot more phones than were actually needed on the market. With this overwhelming amount of mobile phones and rapid development came a lot of more bugs.

Since I swapped from my first Nokia phone, I haven’t had a single phone for more than 1 – 2 years. This isn’t because I really needed to get a new phone but because after a long period of time it started feeling slow, less responsive and lacked all the cool features the new phones had. If the consumers want to buy new phones every second year, why should the vendors make phones that work for more than 2 years?

This has gotten too far, I’m not talking about the mobile phones but technology in general; the consumers are expected to change their behavior and their hardware/software often (every 1-2 years). What’s scary about this is that I’ve caught myself saying:

Oh, you’ve got the 2 year old version/model. That program/accessory doesn’t work on that version/model. You need to upgrade.

As consumers have somewhat adapted to this and expect rapid updates for software’s. The vendors no longer need to spend as much time on finding bugs as they did before. A very good example of this is the launch of Diablo 3 where Blizzard needed to push Diablo 3 to the customers without it being completely finished. If you played Diablo 3 when it first arrived and play it today, it’s almost as you play 2 completely different games; the story the same, but other things have changed.

It is not rare that vendors have open-betas of their in-development software or hardware. In Office 2013, Microsoft added an “instant feedback button” and this is Great! However, I’ve seen a lot of software’s where they “forgot” to remove the “report a bug”-button in the RTM (release to manufacturing). Of course it should be easy to report a bug once you find it, but nowadays it’s pretty much like the vendors expect the users to find bugs and that they need rapid ways to report these.

We no longer see bugs as exceptions, but it’s rather expected and when we do find a bug we immediately think “this will be fixed in the next version sometime this week”.

### Stop delivering less than awesome software

We’ve seen that consumers are not scared of changing their behavior, as that’s what we do; we adapt. Vendors need to start delivering better software and hardware!

As a software engineer, I know what I can do to ensure that each piece in the software that I create is high quality. If you don’t feel that you’ve done an awesome job, something is wrong; we need to be proud of the software that we deliver!

It’s quite often that bugs derive from “quick fixes”, but a quick fix can turn into a quickly evolving bug.

Here’s what I suggest we do to ensure quality of things we deliver:

• Test, test and TEST!
• Refactor your code according to the programming guidelines of the language your using
• Write documentation (even if short!) about your methods, flow and functionality
• Write test documents which includes both manual and automated tests
• Create automated UI tests
• Run complexity analysis tools such as NDepend on the code base to find too complex areas
• Don’t deliver if you’re not happy with the outcome
• Don’t try to optimize better than your compile can by writing complex and un-readable code
• Drink a cup of coffee before you deploy

Let’s make better software, together!

What’s your suggestion on ensuring that we deliver high quality?

## Posted by Filip Ekberg on September 25 2012 5 Comments

### Do you get a lot of ideas when you go to bed, that you forget in the morning?

I sure do and I know that this is very common. The reason that I’ve got explained to me is that because when we go to bed, we relax our entire body & mind. When doing so we also start reflecting upon the day or even week that has passed so far; subconsciously.

At least for me, seconds before I actually fall asleep (last thing that I can remember) I get the best ideas but often I lack things around me to get these thoughts on permanent record.

As I live, love and work with code this is where most of my ideas orbit. But occasionally I get other ideas as well, things like where I want to travel, what I want to see and what kind of changes I like to do in our home.

Last year, I attended NDC (Norwegian Developer Conference) and I somehow got to join the speaker/staff cruise. At this party, I met a lot of very interesting people and one of them gave me a very good insight into how he captures the moment; he always has a pen and some paper in his pocket. On these papers he writes all kinds of interesting ideas, suggestions and anything else that you can imagine.

As I hate “analog” writing, I didn’t really like the idea of carrying pen and paper with me everywhere, but the idea was great; I just had to find something that worked for me. I’m still in the process of finding exactly what works best for me!

### Finding the right tools

There is something that is always by my side, everywhere I go and it would be awesome if this accessory could have an easy way to log thoughts on. Of course, I would want to be able to access these thoughts anywhere, even if I drop the accessory.

I’m of course talking about my smartphone and storing the content in the cloud!

As for just writing down my thoughts, taking photos and storing smaller portions of information; I tend to fall back to evernote. This is by far the best application that I’ve used for rapidly store notes in the cloud!

Here are some reasons to why I use Evernote:

• It’s easy to rapidly create new notes/images
• There’s a free version!
• It works on all devices (PC, Mac, Android, iOS, Windows Phone)

Since I always have my phone with me, no matter where I am; I can instantly add a note with my most recent ideas. Then it’s of course up to myself to actually follow up and checking my own notes now and then.

This is what the PC version of Evernote looks like:

One very cool feature is that you can actually search inside both your notes and your images! If there’s text in images, Evernote will be able to find that!

### Mapping your mind with a mind map!

Up until recently I felt it was difficult keeping track of all my thoughts that I had in meetings together with all the feedback from customers and co-workers. This is because either I put everything in a text document using Notepad or an Excel spreadsheet. Neither of these two alternatives have been very fun to work with. Another problem is also that it’s not quite so fun sharing just plain text with your co-workers or customers. So I wanted to find something else that was fast and that gave me great possibilities at the same time.

I actually stumbled upon a software called XMind, which is a tool for creating all sorts of diagrams. Best of all, there’s a free version! It doesn’t include all the fancy export possibilities or some of the more interesting modes; but the free version sure does the job well enough!

XMind can be used to create the following diagrams (more can be downloaded):

• Blank
• Project Plan
• Project Status Report
• Project Dashboard
• Organization chart
• Short meeting
• Meeting Manager
• SWOT Analysis
• Cause & Effect
• Timeline
• Make a Decision
• Weekly Plan

As you can see by the image below, there are a lot of very nice diagrams that can be created.

When I just want to brainstorm and get my thoughts organized, I create a Blank document and just start adding nodes. By pressing Enter/Tab you create a child to the current node. So if you double click the first big blue box in the middle and name it, press Enter and then Tab, it will create a child to that.

You can see on this image below that I’ve created a map over what I have and want to write about and then added sub-sections to each topic to make it easier for me to remember what I want to write about.

The alternative that I used before is not as nice and does not provide as good of a overview. This could as mentioned above have been doing it in a notepad document, spreadsheet or even the built in Sticky Notes application in Windows.

I think it is very important that we find good ways, especially ways that we are personally comfortable with, to keep track of our thoughts and ideas. It might feel a bit unusual to start, but stepping out of one’s comfort zone can lead to something very good.

It’s a great feeling being able to enter a meeting, taking notes and directly after the meeting not be ashamed of sending your mind map to your co-workers.

How do you normally organize your ideas and thoughts and what tools do you recommend for taking notes during a meeting?

# What’s the difference between doing this and that in C#?

## Posted by Filip Ekberg on September 24 2012 5 Comments

I often get the questions or enter discussions where the topic is: What is the difference between doing this and that in C#? It is not always that easy spotting the difference between code samples. I’m not referring to the actual code you have in Visual Studio, but the code that will be executed, or the IL produced when you compile. Most recently I answered a question on StackOverflow that asked if there would be any difference between nesting and not nesting (using AND) if-statements.

Nested version

if (x == 5)
{
if (y == 3)
{
Console.WriteLine("Hello!");
}
}

Not nested version

if ((x == 5) && (y == 3))
{
Console.WriteLine("Hello!");
}

Before we actually prove if there is a difference/no difference, I think it is important to ask ourselves: Which version is most readable? Readability and maintainability is to me what is most important, as long as I’m not working with RTS or Embedded Systems.

At a first glance it does look like there is a difference between the two, because if you use your head as a compiler, there would have to be at least two branches. However (and this is important) it is not our brains that does the actual compiling! Really, we shouldn’t have to bother trying to beat the compilers optimization.

With that said, let us take a look at the IL generated when we run this in optimization / release mode for the first code snippet:

IL_0000:  ldc.i4.5
IL_0001:  stloc.0
IL_0002:  ldc.i4.3
IL_0003:  stloc.1
IL_0004:  ldloc.0
IL_0005:  ldc.i4.5
IL_0006:  bne.un.s    IL_0016
IL_0008:  ldloc.1
IL_0009:  ldc.i4.3
IL_000A:  bne.un.s    IL_0016
IL_000C:  ldstr       "Hello!"
IL_0011:  call        System.Console.WriteLine

Now, let us take a look at the second one:

IL_0000:  ldc.i4.5
IL_0001:  stloc.0
IL_0002:  ldc.i4.3
IL_0003:  stloc.1
IL_0004:  ldloc.0
IL_0005:  ldc.i4.5
IL_0006:  bne.un.s    IL_0016
IL_0008:  ldloc.1
IL_0009:  ldc.i4.3
IL_000A:  bne.un.s    IL_0016
IL_000C:  ldstr       "Hello!"
IL_0011:  call        System.Console.WriteLine

Instead of us comparing instruction by instruction, let’s use a tool for that which will spot all the differences for us; WinMerge! With WinMerge we can select two different files on disk that we want to compare with each other. So I saved both the IL outputs that I got from LINQPad (as you can see in the below image) as different text files:

Now that you’ve saved both the IL outputs as text files, I copied into Notepad and saved it like that. You can create a new Compare session by selecting the left and right file like this in WinMerge:

This will start comparing the files and then bring up a very nice interface where we can spot the differences, but in our case we will get a message box telling us that the files were identical!

However, if we instead would have compiled these without optimization we would see a difference. Here’s how you turn on/off optimization in LINQPad:

Swap to “without optimization”, recompile and save the IL to the text files and re-run the comparison in WinMerge. This will show us that there is in fact a difference when we turn off optimization:

This is what I normally do when someone asks me about the difference between two similar (or what you expect to be similar) code snippets. The IL might not be good enough for your arguments sake, so you might even want to take a look at the bits and bytes actually used when executing your application. This is possible by using a tool called Native Image Generator (NGen). NGen is good for many reasons, the MSDN Page for it describes the biggest reason like this:

The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer.

So using it to compare the byte code is not what it was designed for.

If the question is regarding the difference between methods in earlier .NET versions contra the older ones, you can use a tool like Reflector to step through the .NET assemblies and see for yourself what the difference is. If you want to prove that for instance the built in BubbleSort algorithm is in fact O(n^2) in some third party library, you could use Reflector to step through the code and do so!

When you don’t really know if there is a difference or not and someone asks you about it, how do you tackle it and answer that question?

# Self-publishing a book – Part 3 – Using a good typesetting system

## Posted by Filip Ekberg on September 23 2012 5 Comments

This is the third part of the blog series “Self-publishing a book” if you haven’t already check out Part 1 & Part 2.

Word was acting up, I spent too much time trying to work around it and less time on the content — this was not going to work. I decided to drop Word. But for what and how would it make anything easier when all CreateSpace supplied was a Word template?

### Stepping out of the comfort zone

Before I actually dropped Word completely I had gotten a lot of feedback from friends on IRC; Most of them recommended me to check out LaTeX. At this point I really had a very little knowledge about what LaTeX was and how to use it. Wikipedia describes LaTeX like this:

LaTeX is a document markup language and document preparation system for the TeX typesetting program. The term LaTeX refers only to the language in which documents are written, not to the editor used to write those documents. In order to create a document in LaTeX, a .tex file must be created using some form of text editor.

Being a geek by heart, I immediately got interested in trying this out. It sounded pretty much like I could code my own programming book. Which would be very cool. Comparing it to something else, LaTeX is pretty much like HTML and CSS. This makes it perfect for writing something both where you have and not have a known layout when you start writing.

Since I didn’t know anything about LaTeX I needed a crash course and somewhere to get a little bit of inspiration/help. Fortunate for me, I found a LaTeX channel on IRC, #latex on freenode. As mentioned in the Wikipedia quote above, LaTeX is actually just a language used for the typesetting system TeX. This explains why the other place where I got a lot of feedback is called tex.stackexchange.com. Both of these (plus google of course) has been very helpful!

Getting a crash course in LaTeX wouldn’t be enough, I still needed my book to conform with the CreateSpace guidelines. I hadn’t decided the trim size(page size) of the book yet. I was thinking about going for 7″ x 10″ but then I created a poll on this blog which later changed my mind. It actually turned out that the size I had in mind was the one you guys wanted the least.

So before I could completely step from Word to LaTeX, I had to know if there was some information about LaTeX + CreateSpace. I googled and stumbled upon a forum post on the very good CreateSpace community forum. This post mentioned a CreateSpace package for LaTeX. Best of all, this was open source and available on github!

Now I knew that I could use LaTeX to create my CreateSpace work, I knew that I wanted to step away from Word but I didn’t yet know how to write anything in LaTeX or what tools to use.

### LaTeX Crash Course

Since I didn’t really know anything about how to write LaTeX markup, I searched for a free tools that could help me; I found a program called TeXnicCenter. However, just downloading and installing TeXnicCenter is not enough, you also need to install the “compiler”. According to TeXnicCenter, I could get something called Tex Live for this. Tex Live has binaries for both Windows, Unix and GNU/Linux.

When I had both Tex Live and TeXnicCenter installed, I just had to learn how to write LaTeX code and what kind of “stuff” it produced for me. If you install TeXnicCenter and open it up, this is the first thing you will see:

This looks pretty much like any word processor from early 2000.

Just as with HTML, you need to define where your document starts, where it ends and if you have something in the preamble (header section). Here’s an example of how to define a document and just have some text in it:

\documentclass{book}
\begin{document}
Hello there!
\end{document
}

If we build(compile) and run this, we will see that we got no errors and that 1 page was produced. You run it by clicking the “Build & View current file” button or pressing Ctrl+Shift+F5:

As you might have noticed, it says “LaTeX => PDF” just left of the build icon. This means that when we build the file, we will actually have a PDF created for us! This PDF will be styled as we’ve said, in this case it will use the default styling of a book.

LaTeX allows us to produce much more than just books, we can create articles, papers and much more. This can be decided my changing the document class. In the above example I used the document class book.

This seemed very easy and there was a lot of good information around the net that I could benefit from since TeX wasn’t something new. My next concern was the document structure, code samples, chapters, sections and much more. I soon found out that all of these was pretty easy to achieve; at least when using the standard layout it came with.

I decided that I wanted to split my document up into seperate files, 1 file per chapter to keep the master document clean and each chapter as clean as possible. Luckily for me, this was probably the easiest thing to solve.

All I had to do was create a new file, I named each file ChapterX.tex and just included it into the master file like this:

\documentclass{book}
\begin{document}
\input{Chapter1.tex}
\end{document
}

When installing TeX Live, I also got a lot of very nice packages that I could include that provided additional functionality. One of the most used packages that I found was listings. This package allowed me to embed code samples into the text with a lot of nice options to it.

The following code sample produced a very nice looking output:

\documentclass{book}
\usepackage{listings}
\usepackage{color}
\lstset{language=C,keywordstyle=\color{blue}}
\begin{document}

\begin{lstlisting
}
int x = 10;
if(x % 20){

}
\end{lstlisting}
\end{document
}

There were of course a lot of things not yet in place, the final design for the book was not done; since there was no content to style yet. Lots of packages and lots of tweaks was waiting along the way.

### Actually writing the content

I was very happy with what LaTeX allowed me to do, I felt comfortable with the way that I could change layout as I went on. One of the most important things during the time that I wrote this book was to share early and share often. A good example of this is the initial draft; if I had not shown this until everything was done, the book would not have turned out as good as it did.

Moving to LaTeX was a very good move and I have never regretted it. It took a couple of days to get used to everything but once everything was in place the focus was a lot more on the content than on the buzz around it. It also felt a lot better writing everything from scratch when doing it like this.

I still had a lot of work to do, but I at least had a typesetting system that I was feeling comfortable with and I shared as much screenshots and snippets as possible to make content looking as good as possible. There are a couple of math equations in the first chapter of the book, in the first draft this equation was just plain text; but after sharing almost 15 different versions of the same equation (style wise), it turned out as it did. Again, if I hadn’t asked the potential readers and those people that have worked with typesetting before, it would never have turned out as it did!

Now I just needed to write the content. As I wrote Chapter 1, I started to think about how I could ensure quality of the overall book and where to go from now. I knew that I wanted to write high quality content where each sentence had been revised many, many times.

The focus so far had been to find a way to comfortably write the content; I now had to find a way to make the content as good as possible. Possibly with the help of the community, but where do I get such help and how do I organize all the feedback?

# Do you care about web security?

## Posted by Filip Ekberg on September 21 2012 1 Comment

I was once put in a project where a lot of the architecture and development was already in place. Immediately when I started working with the project I gave the other team members my thoughts on improvements, some of them regarding testing and some of the regarding security. Last week we focused on the testing, so this week, let us talk a little bit about security.

One of the biggest concerns I had about this project was that usernames and passwords were stored in clear text; this gave me the shivers. I talked to my team members and everyone agreed that this was Very bad. I have no idea why someone would design a login system with username and password where the information is stored in clear text. Or even in a way where passwords where stored in anything else than a hash.

But before I could change this, I had to get a go from the customer to put a couple of hours on changing everything in the system. When doing so, something scary happened. I got this response from our customer:

Don’t put any time on security, we’re going to get hacked anyways and that means free media.

When you hear something like that, it’s obvious the person does not know a lot about IT security or marketing in general. Assuming that the system would get a lot of media slots because of a major leak, the cost to get your reputation up again would be much greater than what it would have been if you just invested in security to start with.

Have you ever experienced something like this as well?

A lot of systems get hacked quite often, but when they do get hacked, it’s pretty darn important that customer data is intact and not easily accessible.

Design your system assuming that you will be attacked by hackers. I think this is quite important, don’t assume that hackers won’t care about you. I would even advise paying a good hacker to test your security to find vulnerabilities.

Always take time to think about security, do it rather sooner than later. When you do think about security, it can be quite nice to fall back on some best practices or rather a check-list of common things that developers do wrong.

To help us all out with this, there’s a project called “The Open Web Application Security Project“. This project has a Top 10 list of most common security problems on web sites. Here’s the list:

Follow the OWASP Top 10 list, ensure that your application is tested against each item in the list above. This is at least one step in the right direction.

Security is often a sensitive subject, but I find that most most organizations that don’t want to dicuss security don’t think that they have a secure enough system; transparency is key.

Is security a key when you develop applications and is your company transparent when it comes to security?

OWASP Top 10 is a good place to start, but it’s just the tip of the iceberg. If you have any stories to share regarding security or any tips & trix along the way, feel free to leave a comment!

# Avoid shooting yourself in the foot with Tasks and Async

## Posted by Filip Ekberg on September 20 2012 6 Comments

Since the release of .NET 4.5, you’ve been able to use the RTM version of Async & Await. There are some things though that can lead to very weird behaviors in your applications, and a lot of confusion. Kevin (Pilchie) over at Microsoft just gave me heads up on some of these and I thought that I would share it with the rest of you!

There was a very interesting discussion around this subject in the ##roslyn channel on freenode with @ermau and @jrusbatch.

### Avoid async void

When you’re doing asynchronous methods that just return void, there is no way to track when these methods are done.

Look at the following example:

class FooBar
{
public async void Biz()
{
await Foo();
}
{
{
Console.WriteLine("Done!");
});
}
}

If we create an instance of FooBar and call Biz(), there’s no way for us to wait for the task to finish. Normally we would want a reference to a Task that we could wait for to finish, but in this case we don’t! Avoid async void whenever you can.

Just change the method signature to async Task instead and you will be able to do:

var foo = new FooBar();
foo.Biz().Wait();

The only reason you want to use async void is when you have an event handler that needs to await something. Such as a Click event handler like this:

private async void MyButton_Clicked(object sender, RoutedEventArgs e)
{
{

return string.Empty;
});

MessageBox.Show(data);
}

### Never getting that second exception when awaiting multiple results?

Consider that we have two asynchronous methods that both thrown an exception (almost at the same time), like these two methods here:

{
throw new Exception("From Foo!");
});
}
{
{
throw new Exception("From Bar!");
});
}

What would happen if we called the following method?

{
return await Foo() + await Bar();
}

We would indeed get an exception thrown. But we would only get One exception thrown! In fact, the only exception that we will get is the First exception being thrown.

This means that we would not see an aggregated exception list as we might expect.

### Exceptions in Tasks don’t travel back to the caller

When working with multiple threads and the thread causes a problem that is unhandled, these are thrown back at the caller.

Look at this following example for instance:

When running this, we will see the following exception:

Unhandled Exception: System.Exception: Exception of type ‘System.Exception’ was thrown.

This is perfectly reasonable, it tears down the calling process!

But what about if this was a Task instead?

The following code spawns a new task and just throws a similar exception to what the thread example did above:

Task.Factory.StartNew(() => { throw new Exception(); });

What happens when we run this? Nothing!

No exception were traveled back to the caller, this can cause potential confusions. This is actually by design and MSDN says the following about it:

In the .NET Framework 4, by default, if a Task that has an unobserved exception is garbage collected, the finalizer throws an exception and terminates the process. The termination of the process is determined by the timing of garbage collection and finalization.

To make it easier for developers to write asynchronous code based on tasks, the .NET Framework 4.5 changes this default behavior for unobserved exceptions. Unobserved exceptions still cause the UnobservedTaskException event to be raised, but by default, the process does not terminate. Instead, the exception is ignored after the event is raised, regardless of whether an event handler observes the exception.

If we want the the .NET 4 behavior, we can re-enable the unobserved task exceptions by changing the applications app.config. Add the following to the app.config:

<configuration>
<runtime>
</runtime>
</configuration>

Since the exception will be thrown in the finalizer, we can test this by running the following:

Task.Factory.StartNew(() => { throw new Exception(); });

GC.Collect();
GC.WaitForPendingFinalizers();

This will tear down the process as it did in .NET 4.0.

Unhandled Exception: System.AggregateException: A Task’s exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. —> System.Exception: Exception of type ‘System.Exception’ was thrown.

Have you ever shot yourself in the foot with Tasks or Async? Leave your horror stories in the comment field!

# I’m going to BUILD, are you?

## Posted by Filip Ekberg on September 19 2012 1 Comment

I’m happy to finally be able to say that I will be going to BUILD 2012! Thanks to my employer Star Republic, I will be able to attend this amazing event. During the event I will be blogging and tweeting as much as possible. Of course, there will be tons for stuff to blog about even after the event, so stay tuned for all these cool new things that will hopefully be announced at BUILD 2012!

### Are you going to BUILD?

If you’re going to BUILD, let me know. I’d be happy to meet up and have a chat. If you’ve got a C# Smorgasbord book that you want signed, I’m sure we can work something out.

I’ll be in town from October 27 to November 3!

# Things in C# you might have missed

## Posted by Filip Ekberg on September 18 2012 14 Comments

A while back I did a short programming quiz on my blog and a lot of you responded to each question with interesting ways to solve those puzzles. Here is a list with those questions among other interesting things that you might now have used in your day-to-day development.

### Bits n’ Bytes

The more you know about the internals in the system you are working on, the greater your advantage is. Let’s focus on the bits and bytes for now. A bit is either a 1 or a 0 which represents value/no-value or on/off; a byte is a sequence of 8 bits.

Take a look at these three tables:

As you might see this is a base-2 representation. It starts at 1, then 2, then 4 and so forth to how far you’d like to go. For simplicity, the table only goes to 128. By letting some of them be 1s and some be 0s, you can represent any number you like.

Fun fact: the ASCII decimal value for the capital letter A is 65 which means the bit-representation would look like this: 01000001 if added to the above table!

Now when we do this, we can do something really powerful called bit-shifting. This means moving the bit N steps to either direction (left/right).

This takes us to the first question that I shouted out on twitter:

How can we multiply any given value by 2 without using any arithmetic operations?

The answer is simple, we use bit-shift! Below is an example of how we can do this.

int x = 10;
int result = x << 1;

The << means that we shift it to the left and the following value defines how many steps. Below is another table showing what changed, all bits were moved 1 step to the left.

There are lot of more interesting things you can do when knowing your bits n’ bytes, such as logical and/or.

### A number, but not really

Almost 3 years ago I answered a question on StackOverflow where the question was the following:

Suppose you have this loop definition:
while (i == i) ;

What is the type of i and the value of i if the loop is not an infinite loop and the program is using only one thread?

Let us assume that this is built in types in .NET and that we are not allowed to override the equality operators. This makes it pretty hard to figure out, right?

This introduces NaN — Not a Number. But how can it be a number but not a number at the same time? NaN was introduced because of imaginary numbers such as

Sqrt(-1)

So, let us try to get the square root of -1 in C#:

var result = Math.Sqrt(-1);
Console.WriteLine(result == result);

Can you guess what this prints?

It actually prints false! This is because NaN == NaN will always return false! Because comparing something that is not correct with something else that is not correct doesn’t make any sense.

But what type is it?

We know that Math.Sqrt returns a double. So the answer is Double.NaN.

### Cleaner code without temporary lists

Do you find yourself having tons of methods that contain temporary lists that you want to return in the end of the method?

For simplicity I’m going to use a method in the following example that I would normally just use LINQ to achieve.

Here I have a method that just check is a list of names contain my pattern:

IEnumerable<string> _names = new[] {"Filip", "Sofie"};
IEnumerable<string> GetList(string pattern)
{
var found = new List<string>();

foreach(var name in _names)
{
if(name.Contains(pattern))
{
}
}

return found;
}

It’s not really that messy, but it can be cleaned up. If we have a lot of methods like this, we can make the code base much easier to read through. What we can do is to make use of the yield keyword like this:

IEnumerable<string> _names = new[] {"Filip", "Sofie"};
IEnumerable<string> GetList(string pattern)
{
foreach(var name in _names)
{
if(name.Contains(pattern))
{
yield return name;
}
}
}

### Why are there uppercase and lowercase versions of object/string etc?

object, string, int, double and the other value types are just keyword aliases for their representations in System.*.

For example, object is really System.Object, string is System.String and int is System.Int32.

When the code is compiled, it doesn’t matter if you wrote string or System.String, it’s going to be the same IL!

# Roslyn CTP 3 released — breaking changes

## Posted by Filip Ekberg on September 17 2012 1 Comment

Microsoft has released yet another CTP version of Roslyn and this doesn’t come as a big surprise. Since the previous CTP (CTP2) does not work very well with Visul Studio 2012. Now with Roslyn CTP3, we have Visual Studio 2012 support! However, this upgrade does come with a price, there are some breaking changes in the third version of the Roslyn CTP.

This unfortunately breaks some code samples in my book C# Smorgasbord, but not to worry. The changes are pretty easy to figure out and I’ve put together an Errata that covers all the code samples that are affected by the breaking changes.

You can find the Errata here.

If you’re using Visual Studio and you have intellisense enabled, it’s going to be pretty easy to figure out what has changed. Below is a short list of what I’ve found and what is in the Errata.

### No longer possible to run Scripts through ScriptEngine directly

To execute a snippet you need to create a session first, like this:

var engine = new ScriptEngine();
var session = engine.CreateSession();
var result = session.Execute("var x = 10; x");

Console.WriteLine(result);

### ParseCompilationUnit is removed

You can now use ParseText and ParseFile instead.

### The auto generated GetIssue method has changes.

When creating a Code Issue project, the generated file is changed a bit. Instead of GetText() on the token, you now use ToString() and instead of CodeIssue.Severity.Warning you use CodeIssueKind.Warning.

### Method AnalyzeStatementDataFlow is renamed

The method AnalyzeStatementDataFlow on SemanticModel has been renamed to AnalyzeDataFlow().

There are probably a lot more changes to Roslyn than the ones listed above.

If you have any questions regarding the code samples in C# Smorgasbord or if you want to chat about Roslyn, leave me a comment or an e-mail. Even though these are breaking changes, it does not ruin the reading expreience of C# Smorgasbord!