Saying that a lot happened in 2012 is probably an understatement. At least both on this blog and in my personal life, a bunch of amazing things have happened. I really hope that your previous year was good and let’s hope for an even better 2013. To start this year off I want to summarize all the great posts that were shared on this blog in 2012.
Personally the two biggest achievements of last year was me getting engaged to my lovely Sofie and publishing my book C# Smorgasbord. As you might have seen already this year has already started very good as I have been awarded Microsoft MVP in Visual C#!
Let me know what you found most interesting on this blog from the collection of posts below! Here is the 2012 summary!
Architecture
Tips & Tricks
Screencasts
Software & Tool information
Windows 8, Windows RT, WinRT and Surface
C# Smorgasbord and Self-publishing
Other
I hope you found this collection of posts useful and that you’ve learnt a lot in 2012! Enjoy 2013 and let me know what you think of the posts! Before we take part for this time, I want to share with you an image that describes the feeling I got when I held the first printed copy of C# Smorgasbord:

?>
Vote on HN
A summary of 2011 and a look at what is about to come
Posted by Filip Ekberg on January 5 2012 5 Comments
Happy 2012 folks! I hope you all had a wonderful new years eve!
The year 2011 has been very interesting, we’ve had the opportunity to see some very exciting things that is about to reach the market. I’d like to summarize what I’ve been writing about in 2011 and breifly tell you guys what’s about to expect from me in 2012.
Let’s get to it, here’s a link summary to all my posts in 2011
Dynamic programming
Software Architecture
Compiler as a Service
Screencasts
Other
As you can see a lot of exciting things has been discussed in 2011 and my vision is that 2012 gets at least as exciting! We’ve still got a lot of fun areas to cover and even more useful products to look at.
Worth mentioning is that I am currently in the work of assembling a book about C# Programming, almost all the above articles and some more will be featured in this book but with a lot of extra content that makes it even more fun to read. If you are interested in being a technical reviewer, editor or anything else that might be helpfull, just drop me an email or a dm.
?>
Vote on HN
Adding properties and methods to an ExpandoObject, dynamically!
Posted by Filip Ekberg on October 2 2011 4 Comments
Meanwhile I am planning and writing manuscript and code samples for my upcoming video series that will cover “Programming fundamentals using C#”, I thought it was time for a short post on some dynamic programming in C#!
Another thing worth mentioning is that I will be using Visual Studio 11 Developer Preview, if you haven’t checked it out, I posted a quick blog post about it running side by side with Visual Studio 2010!.
So, for those that are completely new and haven’t yet checked out my videos on “C# 4.0 Using the Dynamic Keyword”, here’s a quick summary:
- C# is not dynamically typed even though you can have dynamic types. It’s a statically typed dynamic type!
- ExpandoObject is the object that you use with the dynamic keyword(contextual keyword) in order to add properties and methods dynamically.
- Dynamics are evaluated at runtime
A typical dynamic setup that creates a dynamic object and adds a static amount of properties might look like this:
dynamic person
= new ExpandoObject
();
person
.Name = "Filip";
person
.Age = 24;
What is interesting about the ExpandoObject is that it implements the interface:
IDictionary<string, Object>
So what this means is that if we cast the person-object to an IDictionary we will be able to do some really cool stuff with it. The same code above but re-written to make use of the dictionary instead could look like this:
dynamic person
= new ExpandoObject
();
var dictionary
= (IDictionary
<string,
object>)person
;
dictionary
.Add("Name",
"Filip");
dictionary
.Add("Age",
24);
Now you might ask why this would ever be useful? In fact I first encountered this when Rob Conery threw together a part of Massive on stage on the Norwegian Developers Conference this summer. In his case he wanted to create an extension for an IDataReader which would give you a List instead of having to fight with the IDataReader.
So to make this as dynamic as possible, all the fields from the table was read, added with their corresponding values from the IDataReader into the dictionary, which made the whole thing very dynamic.
There are actually more ORMs(Simple.Data) out there that uses this approach, but I will get to that later on when I’ll cover DynamicObject!
This is how you add dynamic properties, but how about adding a method? It’s simple!
What you do is that you add a new key to the dictionary and the object should just be an action, like this:
dictionary
.Add("Shout",
new Action
(() => { Console
.WriteLine("Hellooo!!!"); }));
person
.Shout();
When calling the Shout-method it will print out “Hellooo!!!” in the Console.
I hope you had fun reading this and that you learned something new! Stay tuned for more posts!
?>
Vote on HN
WPF vs WinForms – Which is easier to learn?
Posted by Filip Ekberg on July 10 2011 3 Comments
This question originates from StackOverflow, but as I see there are a lot of beginners that ask this question, I wanted to share the answer on my blog as well.
So, WPF vs WinForms – Which is easier to learn?
Neither and Both, easy is very subjective and depends on your background. First of all, I want to show an example of an application with the following in both WPF and WinForms:
- A textbox for input
- A button to do some “Processing” of the input
- A label that will display a result
WinForms
The window can look something like this:

The code for this is quite trivial and easy even for a beginner:
private Button _myButton
;
private Label _resultLabel
;
private TextBox _inputTextBox
;
public Form1
()
{
InitializeComponent
();
_myButton
= new Button
{
Text
= @"Process data",
Top
= 100
};
_inputTextBox
= new TextBox
();
_resultLabel
= new Label
{
Text
= "",
Top
= 200
};
Controls
.Add(_myButton
);
Controls
.Add(_inputTextBox
);
Controls
.Add(_resultLabel
);
_myButton
.Click += Process_Click
;
}
void Process_Click
(object sender, EventArgs e
)
{
_resultLabel
.Text = string.Format("Your data is: {0}", _inputTextBox
.Text);
}
So far, we haven’t touched anything in the designer.
WPF
If we copy and paste the exact same code into a new WPF-application, there are just a handfull of things that we have to change some of them being:
- How we add the controls to the interface
- How we change text in a label
- How we position it from the top ( margin )
However, these are just things that is Different between the two, it’s neither more difficult nor more easy in one or the other. So this is what the window looks like in WPF:

And the code is Almost identical:
private Button _myButton
;
private Label _resultLabel
;
private TextBox _inputTextBox
;
public MainWindow
()
{
InitializeComponent
();
_myButton
= new Button
{
Content
= @"Process data",
Margin
= new Thickness
(0,
100,
0,
0)
};
_myButton
.Click += Process_Click
;
_inputTextBox
= new TextBox
();
_resultLabel
= new Label
{
Content
= "",
Margin
= new Thickness
(0,
100,
0,
0)
};
var panel
= new StackPanel
();
panel
.Children.Add(_inputTextBox
);
panel
.Children.Add(_myButton
);
panel
.Children.Add(_resultLabel
);
Content
= panel
;
}
void Process_Click
(object sender, EventArgs e
)
{
_resultLabel
.Content =
string.Format("Your data is: {0}", _inputTextBox
.Text);
}
So far both WPF and WinForms seem to be equivilient hard / easy to learn. But this is just the code-behind approach, when we come to the designer, there’s a huge difference.
WinForms
When you develop WinForms applications you drag and drop controls onto your surface and use a property window to change the properties of your window. This looks something like this:

So you can drag-n-drop your controls, you can change the properties of each control and snap them to where you want them, easy enough right?
WPF
So what about WPF? Is it much harder to do the same thing there? I think not:

The main difference here is that you have an extra “window” at the bottom that. This window is an XML ( XAML ) view of your design. This is where WinForms and WPF take apart from each other. But just as you can avoid writing Design Code in WinForms, you can Avoid doing it in WPF as well, as a newbie that is.
As for newbies, I don’t think it’s harder nor easier to learn the one or the other, when we get a bit deeper into the technology that is choosen, sure, it gets more complex. But the way there is just as easy or hard no matter which of the two you choose.
So when do you choose the one or the other?
You choose WinForms because:
- It’s been around for a long time and you have a Large control supply that you can use.
- There are a lot of good resources on WinForms to learn from and to get new controls from.
You choose WPF because:
- You can make richer UI, nowdays it’s all about the user experience.
- You want to have full control of your controls design.
- You want rich, data-driven applications.
- You want hardware accelerated UI.
How about data-binding, Design Patters and all that?
You don’t need to know anything about Design Patterns nor how everything works to make a usabel application, especially not as a newbie. As time goes by, you will have to learn more about the technology that you choose. People tend to say that you need to know MVVM to use WPF, that is not true. As it is not true that you need to know the MVP pattern to create WinForms applications.
Both of the technologies can handle rich-data-driven controls, you have grid views and such in both of them. WinForms has some pretty nice “drag-n-drop”-features for data manipulation and listing and WPF has very nice data-binding.
What if I don’t want to choose one or the other?
The beauty is that you don’t have to! You can host WinForms controls in WPF and you can host WPF controls inside WinForms. This means that if you are developing a WinForms application and you want to take advantages of WPF, that’s ok you can!
So which is easier?
Neither and Both! As for a newbie, both can look a lot similar on the surface, even though it is so different when you go deeper.
They are similar but so different, the thing is that when you start out, you have other things to think about than how the Routing model works and how to adapt to MVVM.
Is XAML dead?
No. XAML isn’t dead. WP7 uses Silverlight which is also using XAML. Even though a lot of development in the future can be done with HTML5, I doubt that XAML is about to “die”. People asked if WinForms was going to die when WPF was released and it hasn’t.
?>
Vote on HN
Over-engineering trivial tasks can be challenging and educating
Posted by Filip Ekberg on June 1 2011 2 Comments
It’s been almost six months since my last blog post here, it’s not like I don’t have anything to write, but the time I have over at the end of the day just doesn’t end up so that I have time to write here. I’ll try to get some more time to write here since I really do have a lot of interesting things that I want to share!
Lately I’ve seen a bunch of questions over at StackOverflow that is quite trivial, at least trivial to us that work with these kinds of things on a day to day basis. My example here is from the question “how to read all the subdirectories in a given destination..” as I see it, there are a lot of different ways that you can solve this but no matter how trivial this problem is, you can always over-engineer it. So when I first saw this question I immediately started to think about interesting ways to solve this.
One of the possible solutions could be to get a directory list of the parent folder and use parallel extensions to recursively scan each folder to speed up the process a bit. The traversing method signature could also contain an action / delegate that are used when the given file you are looking for is found.
However, this does not completely solve the given task, the person asking the question wants the following requirements:
- Start looking for the ABC file in the parent directory
- If there is no ABC file, go on to the next subfolder
- If it is not in the subfolder, move on to the next one…. and so forth..
- Once a file is found, process the file
It is however not stated if the scanning should continue after the first file is found. Do you see where I am getting at? When you open to door to allow different interpretations of your problem, a lot of us that see interesting challenges in everything start to think about how we can effectively make this reusable and optimized.
Over-engineering a trivial problem can actually lead to something good, you might get optimized and reusable code!
One of the solutions presented was actually pretty cool, there’s something called “LINQ to File System” which will let you create a query and ask for these files, and you can use the built in System.IO.DirectoryInfo directly to ask for a certain file-pattern. But neither of these lets you process the file In-Place. What I mean about In-Place is to process it once you’ve found it and not after you’ve found it.
My final solution ended up being a recursive method that just takes a path; this was to give the trivial question a trivial answer.
void TraverseDirectory
(string directory
)
{
var currentDirectory
= new DirectoryInfo
(directory
);
foreach(var dir
in currentDirectory
.GetDirectories())
{
var currentPath
= dir
.FullName;
TraverseDirectory
(currentPath
);
var pathToMasterFile
= Path
.Combine(currentPath,
"Master");
if (File
.Exists(pathToMasterFile
))
DoSomethingWithMaster
(pathToMasterFile
);
}
}
Even though this problem was initially trivial, if we want to, we can make it very complex, challenging and educating. For instance, it’s been a while since I created something interesting with Delegates/Actions/Tasks so why not elaborate this a bit and make the result a bit more interesting?
You can always make trivial problems into something fun, exiting, educating and challenging! You just need to put your mind into it. Mainly I just want to say to all developers out there that are stuck with trivial tasks that they find a bit boring; you can make so much more out if it!
?>
Vote on HN
Use Test Driven Development to verify that the code will Always work!
Posted by Filip Ekberg on April 23 2010 Leave a Comment
After attending Scandinavian Developer Conference in Sweden 2010 and attending the talk from Roy Osherove ( http://osherove.com/ ) Test Driven Development ( TDD ) has been something that I have tried to focus a bit more on.
Roy talks about some really important aspects of programming that should be printed into the programmers brain. I for instance is one of these people that like to verify everything that I do; Did I Really lock the door? So when I’ve turned the keys in the lock, I verify that the locking mechanizm worked and that the door is no indeed locked.
So what does my weird habbit have to do with TDD?
Driving the development with tests is not the only part of TDD; as with anything else there are a lot of people that like to think a lot of different things about this method. I like to think of tests as a way to Verify that my code runs as expected.
This is not a case of miss-trust!
Don’t missunderstand the above as see me as someone that does’t trust anyone or anything created by others than myself, that’s not the case. But by verifying that things runs properly, the door is properly locked I know that everything is OK from my part in the scenario.
What if I didn’t run the tests on the code and handed it over to the next developer that Did not in fact know that the method he works in affects everything else? And what if I didn’t verify the lock; I was in a big hurry and someone just went into the appartment and stole my TV?
In my opinion, test driven development is way to:
- Verify that Code runs as it should
- Decrease mistakes in the future
- Help others gain knowledge of parts in the code faster
To take the locking mechanizm-checking even further and really turn it into something that is Driven you can follow these three very simple steps that Roy also talks about in his speeches:
- Make it fail
- Make it work
- Make it better
How do you make the lock fail to lock? Well you simply Don’t lock it!
So let’s head over to the development aspect of this, you want to make your code fail? No code means it will fail right? When I do this step 1 and 2 always go together, especially when I demo TDD for co-workers or others. I will use the same good example as Roy used in his demo on SDC 2010, let’s try to put our heads around a simple Calculator project.
Defining the requirements
For this “project” we only have fourrequirements:
- A method called Sum
- This method parses a String
- This method should return String.Empty when you pass Invalid or Empty data
- Adds two integers in the String together “1 1″ would be 2
So if we follow the above we would end up with a test that looks like the following:
[TestMethod]
public void Sum_EmtpyString_ReturnsZero()
{
var calculator = Calculator.GetInstance();
var actual = calculator.Sum("");
var expected = string.Empty();
Assert.AreEqual(expected, actual);
}
Since we haven’t really implemented Calculator, GetInstance or Sum yet, we made it fail, there is no Code. Visual Studio helps us out a bit and makes the process a bit faster, by simply pressing alt + enter when selecting Calculator or Sum we can select to create the Class and create the Method Stub.
So we actually finished both Step 1 and Step 2 at the same time, even though Step 2 isn’t complete yet, we are nearly there!
Now we need to make it work, what is the simpliest way possible to make it work for the above test-case?
public string Sum(string input)
{
return string.Emtpy();
}
This will actually work and it will indeed check this test as Passed. But it’s not really what we want. So how do we proceed?
Another Great point Roy pointed out is that, if there isn’t a test, there’s no code and if there’s code there’s gotta be a test! And if one test passes and you want to Change the code to behave different with other input; You need to prove it with a test!
So we can test if
will return 1, which we from looking at the code will see that it wont!
public void Sum_ValueContainsADigit_ReturnTheDigitThatIsPassed()
{
var calculator = Calculator.GetInstance();
var actual = calculator.Sum("1");
var expected = "1";
Assert.AreEqaul(expected, actual);
}
This test will most defently fail because of our implementation! So we need to go back to Sum and change this method.
Once all tests passes and the test case is approved, we head on to the next step, which is make it better! In other wors we need to refactor some code! Try to follow these steps to refactor ( i use ReSharper, which is a Great tool! ).
- Move the Library to an appropriet Class Library / Project
- Optimize the code
- Refactor your test to look better
- Comment the code
So you got a little peek at what TDD is and how it can be used, if everyone would use TDD, it would be so much easier to take on new projects that have already been started. You never know what your changes will impact on.
?>
Vote on HN
Using Parallel Extensions in LINQ
Posted by Filip Ekberg on March 25 2010 1 Comment
Once again, there was a little mistake in the last post I posted here which clearly didn’t effect the result that much. But it is still worth mentioning again. The ^ was not meant to be XOR, I was clearly thinking of Math.Pow.
In the last post I didn’t spend to much time talking about the Parallel Extensions for LINQ which are Really great and helpful; If you just love to replace traditional loops with LINQ-expressions you will probably find this post somewhat amusing.
So let’s dig down to the coding shall we!
First of all I have set up a smaller list with numbers, in this scenario we will just assume that we have a list of something and depending on the contents of that list, the time it takes to perform an action on that result, will differ. So here’s my list
var latency
= new[] {1,
2,
4,
8};
Side note: new[]{} is really helpful, especially when you are creating examples like this!
And then I have a method that I want to run for each element in my list, which I will call PerformLogic
static int PerformLogic(int latency)
{
var ms = 500 * latency;
Thread.Sleep(ms);
return ms;
}
In “traditional” programming, you would maybe do something like this:
for ( int i = 0; i < latency.Lenght; i++ )
{
PerformAction(i);
}
But I don’t find that so amusing anymore, using LINQ is so much neater so instead of that for-loop we can actually do this:
(from i in latency select PerformAction(i)).ToList();
We don’t really have to write the expession like this though, since LINQ + .NET 4.0 is so smart, we can Refactor this to look somewhat like this:
(latency.Select(PerformLogic)).ToList();
The previous one is a bit more elaborate but this is fine aswell.
Making it parallel
We’ve reached the place where we no longer can refactor our code to make it faster, we can’t replace anything in the logic to make everything faster; We need to parallelize it!
Let’s have a look at what LINQ provides us with, oh, there’s an method called
.
All I did now was changing the above code to this:
var result = (latency.Select(PerformLogic)).AsParallel().ToList();
And we have a parallelized query. For those with a fast mind can see that it will take about 7,5 seconds to run this since each of the “latency”-points will take itself times ½ second.
My final test-code looks like this
var latency
= new[] {1,
2,
4,
8};
var start
= DateTime
.Now;
var result
= (latency
.Select(PerformLogic
)).AsParallel().ToList();
var end
= DateTime
.Now;
Parallel
.ForEach(result, Console
.WriteLine);
Console
.WriteLine("Execution time: {0}",
(end
- start
));
And this is the output

?>
Vote on HN
Using the Parallel Extensions in .NET 4.0 with C#
Posted by Filip Ekberg on March 24 2010 Leave a Comment
As .NET 4.0 will be released in a couple of weeks and the RC has been out for a while. It’s about time that I write something about the new helpful features of .NET 4.0. One of these helpful things are the Parallel Extensions and Parallel helpers that allowes you to do parallel programming.
Parallel computing is a form of computation in which many calculations are carried out simultaneously
In this example I will be using a WebRequestPool which just helps me out a bit to carry on this example. You might think if it like this: You have different request types which takes different long to execute you might be doing some WebDAV uploading, Image Fetching and other Over-The-Web-Access which takes time. Instead of waiting for each request to stop, you might as well run them simultaneously.
internal delegate void WebRequest(int ms);
internal class WebRequestPool
{
public List Requests { get; set; }
}
So to make it easy I just have a simple Delegate which will allow us to Run/Invoke our WebMethods which all takes some input parameter that will, in some way, make the requests take longer / shorter.
Inside of the WebRequest class all we have is a Requests Pool, a simple list of delegates.
To make the whole a little bit interesting we have three different types of Requests: Standard Request, Long Request and ExtremeRequest
static void StandardRequest(int ms)
{
Thread.Sleep(ms);
}
static void LongRequest(int ms)
{
Thread.Sleep(ms^2);
}
static void ExtremeRequest(int ms)
{
Thread.Sleep(ms^10);
}
So now we have three different types of methods that all validate with our delegate! Let’s head on and fire up this pool
var pool
= new WebRequestPool
{
Requests
=
new List
{
StandardRequest,
LongRequest,
ExtremeRequest,
StandardRequest,
LongRequest,
ExtremeRequest
}
};
This actually demonstrates something new too, the object initializers. So the list now contains six requests, All we want to do now is Processes these.
First of all we want to do it like we did in the old days, so I’ve created a method called ProcessPool which looks like this
private static void ProcessPool(WebRequestPool pool)
{
var start = DateTime.Now;
foreach (var item in pool.Requests)
item.Invoke(2000);
var end = DateTime.Now;
var span = end - start;
Console.WriteLine(
string.Format("Execution time: {0}", span));
}
Of we run this the output is

Now, that’s a bit too slow for me, so Let’s Parallelize that! All i’ve done now is to creat a new method called ProcessPoolAsParallel which takes the same input and expects to give the same result. There’s a little bit difference though, the foreach is now replaced with the
method.
private static void ProcessPoolAsParallel(WebRequestPool pool)
{
var start = DateTime.Now;
Parallel.ForEach(pool.Requests,
item => item.Invoke(2000));
var end = DateTime.Now;
var span = end - start;
Console.WriteLine(
string.Format("Execution time: {0}", span));
}
So if we run this now the result is:

So this increased significally!
This is just a small example of the power in using Parallel programming patterns. Look into the Task class to head on!
Edit
There’s a slightly miss-used method in the code above, the ^ in C# is XOR and I was thinking of the Math.Pow, however, this doesn’t really matter in this case since the result is still Parallel = Faster.
?>
Vote on HN