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
Exploring reflection – Finding a value in any of the objects properties
Posted by Filip Ekberg on October 8 2011 4 Comments
I want to explore reflection by playing with both reflection, anonymous types and dynamically typed things all at once! My goal is not to be confusing or anything, but it is to leave out the parts that are redundant.
So let’s get to it!
I sometimes find myself having a lot of data that I want to search through, it might be the same structure for each element and it might not, I can never assume that it’s the same structure though, because if I would, there would most certainly be a case where it differs.
Let’s assume that we have two anonymous types here:
var person
= new {Name
= "Filip", Surname
= "Ekberg", Age
= 24};
var animal
= new {Name
= "Baloo", Breed
= "Some breed", Age
= 14, Owner
= "Filip"};
In my last post, I talked about the properties on anonymous types being read-only, the fact is that the entire anonymous object is read only, so even if I would say that it’s a dynamic anonymous type, I wouldn’t be able to specify new properties or methods on it.
Anyways! We have the above two objects that I want to search for something in, it might be the age, it might be a common string. So there are a few things that I got to figure out before I can start retrieving my results, here are the things we need to know:
- How do we get all the properties from the object?
- How do we get the value for the current property on the current object?
- How do we get the type of the object, does it matter that it’s anonymous/dynamic?
Almost all of the above have been used here and there in my previous posts, but to answer them again:
How do we get all the properties from the object?
To get all the properties, we must first get the type, so we can retrieve all the properties for that type, like this:
obj.GetType().GetProperties()
How do we get the value for the current property on the current object?
To get the current value of the objects property you call GetValue like this, the second parameter is null because it’s not an array:
var value = property.GetValue(obj, null);
How do we get the type of the object, does it matter that it’s anonymous/dynamic?
When you’ve retrieved the value of the property, you get the type of the value by doing this:
Now we have the basics and need to put every piece together so that we can search our objects, I want to have a method like this to find objects in a list with any property containing the Exact value that I pass:
IEnumerable<dynamic> Find(dynamic pattern, IEnumerable<dynamic> source)
My code that calls this method will look like this:
var person
= new {Name
= "Filip", Surname
= "Ekberg", Age
= 24};
var animal
= new {Name
= "Baloo", Breed
= "Some breed", Age
= 14, Owner
= "Filip"};
var toLookup
= new List
<dynamic
> {person, animal
};
var found
= Find
("Filip", toLookup
);
So what can the implementation look like? We can either solve it with LINQ or with a foreach.
My method will start out by only declaring a new list that we will put the found elements in and then I just return it to make everything build nicely:
IEnumerable
<dynamic
> Find
(dynamic pattern, IEnumerable
<dynamic
> source
)
{
var found
= new List
<dynamic
>();
// Implementation goes here....
return found
;
}
Now I need to iterate over my source-variable and for each item, I need to go through each property and see if the value matches the pattern input. I add the two nested foreach-loops like this:
foreach (var obj in source)
{
foreach (var property in obj.GetType().GetProperties())
{
}
}
It’s now iterating over each property on each object, you don’t want to move the GetType().GetProperties() outside the foreach-loop, since in our case the structure changes over each iteration. Now we’ve come to the final part, we need to get the value of the current property on the current object and see if the type matches the pattern type and then check if the value matches the pattern:
var value = property.GetValue(obj, null);
if (pattern.GetType() != value.GetType()) continue;
if(pattern == value)
found.Add(obj);
You might not want to use the equality operator in your case, if it’s a string you might want to check if the pattern is anywhere in the current value or something like that.
This is how my Find-method turned out:
IEnumerable
<dynamic
> Find
(dynamic pattern, IEnumerable
<dynamic
> source
)
{
var found
= new List
<dynamic
>();
foreach (var obj
in source
)
{
foreach (var property
in obj
.GetType().GetProperties())
{
var value
= property
.GetValue(obj,
null);
if (pattern
.GetType() != value
.GetType()) continue;
if(pattern
== value
)
found
.Add(obj
);
}
}
return found
;
}
I hope you found this interesting and if you have any thoughts please leave a comment below!
?>
Vote on HN
Playing with anonymous types in C#
Posted by Filip Ekberg on October 6 2011 6 Comments
In C# 3.0 something called anonymous types was introduced, this means that a certain context can have a type that is not defined anywhere except in that context. This has been seen a lot in LINQ-queries over the years. Here’s an example of an anonymous type:
var person
= new { Name
= "Filip" };
If we hover the person-variable we should see something like this show up:

Having this anonymous type in our context means that we could write person.Name to get the value of the Name variable. One thing that is important when talking about anonymous types is that the variables are read only, which means that you cannot change Name after you’ve initialized the anonymous type.
I mentioned before that this has been seen a lot when using LINQ you might have seen code like this:
var persons
= from person
in context
.Persons
select new { Name
= person
.Name, Age
= person
.Age };
This would as you might imagine give us a list of anonymous types where each type has a Name and Age property.
All this is pretty neat itself, but what happens when you want to use the anonymous type outside the context of where it was created and still maintain accessibility? The answer to this was introduced in .NET 4.0.
And the answer is dynamic!
Before we dig into what dynamic will help us with here, let’s take a look at how we can return an anonymous type from a method without the use of dynamic. Consider the following method:
object GetAnonymousType
()
{
var person
= new { Name
= "Filip" };
return person
;
}
If I call this like this:
var person = GetAnonymousType();
Will I be able to do person.Name?
The answer is: No. ( here’s a trick you can use though. )
But if we debug the application and hover the person-variable, we will see this:

This is quite irritating, right? There’s a fun way to actually get the property value and that is by using reflection like this:
var person = GetAnonymousType();
var properties = person.GetType().GetProperties();
var name = properties.First(x => x.Name == "Name").GetValue(person);
This will actually give us what we want, but hey, this is quite ugly right? I am all about readable and clean code, now I am not telling you to pass around anonymous types everywhere, but now and then it can actually be usefull.
There’s actually just One thing that I need to change in the above code, and that is to set the return type to dynamic instead of object, like this:
dynamic GetAnonymousType
()
{
var person
= new { Name
= "Filip" };
return person
;
}
I can now use this and successfully retreive my properties on this object:
var person = GetAnonymousType();
Console.WriteLine(person.Name);
This is what I call simple and readable code! Instead of having to add a new class, add each of the properties in the anonymous type to the new class and so forth, you can just use dynamic to get the stuff to work as you imagine it should!
However, even if we return it as a dynamic type, the properties are still read only!
I hope you found this interesting and if you have any thoughts please leave a comment below!
?>
Vote on HN
Making code more readable with anonymous functions
Posted by Filip Ekberg on October 5 2011 8 Comments
If you come from a world filled with JavaScript you might be used to seeing the click handler logic defined at the same place as where you defined the click handler itself. For instance, look at this code:
$("#submit").click(function(){
performPostAndRedirect();
});
I think it’s safe to say that this kind of code is very usual and that it’s nothing wrong with it, in fact, it’s easy to read and easy to understand and for me readability is something that is very important.
So how does this apply to C# development?
Look at the following code from a WPF-application:
var button
= new Button
();
button
.Click += new RoutedEventHandler
(button_Click
);
This can be simplified a little bit, you actually don’t need to write the “newRoutedEventHandler”-part and nowdays you can just write:
button.Click += button_Click
Now this indicates that we have a method called button_Click that looks somewhat like this:
void button_Click
(object sender, RoutedEventArgs e
)
{
throw new NotImplementedException
();
}
In most of the cases that I’ve seen, you don’t want to do any actual logic inside the event-handler anyways, you might just want to fire off a method that starts off some task for you, or validate data. But this is rarely done inside the event handler itself, at least it shouldn’t be.
So, how can we make this easier on the eyes and just navigate to the Click event assignment and get a feeling of what is happening?
By using anonymous functions!
First of all you can write something like this:
button.Click += (object sender, RoutedEventArgs e) => { ValidateInput(); };
This can be simplified though and end up like this:
button.Click += (sender, e) => { ValidateInput(); };
Even if you do more than one method-call in the event handler (when using anonymous functions) I think this is a pretty nice approach, it’s less lines and you get an idea of what actually happens by just looking at that line of code. You don’t have to navigate down to the event-handler itself to see what’s going on.
This isn’t the only way you can use anonymous functions though, I use it frequently when I create new tasks like this:
Task.Factory.StartNew(() =>
{
PerformTimeConsumingOperation();
ValidateOperation();
});
Again, I think it would be redundant to do otherwise, to have a separate method that you call to actually start the real work, this is less code and more readable! At least in my eyes.
I hope you found this interesting and if you have any thoughts please leave a comment below!
?>
Vote on HN
Using dynamic in the real world with IronPython
Posted by Filip Ekberg on October 4 2011 Leave a Comment
My last posts have been a lot about what you can do to explore the dynamic world in .NET and what it might be good for. But I think it’s time for some real fun with dynamic!
So go ahead and fire up Visual Studio, see to it that you got NuGet installed, now let’s get rocking!
The first thing you want to do is to create a new console application with any name of your choice, then I want you to go into:
Tools -> Library Package Manager -> Package Manager Console
This is the NuGet console, here you can do all kinds of neat stuff, we are going to use it to install IronPython into our project, so simply write the following in the console:
Install-Package IronPython
After 30 seconds to a minute or so, you should see something like this:
PM> Install-Package IronPython
Successfully installed 'IronPython 2.6.1'.
Successfully added 'IronPython 2.6.1' to DynamicInRealWorld.
This means that IronPython was successfully added to our project! But wait a minute, what is IronPython? This is the definition of it according to Wikipedia:
IronPython is an implementation of the Python programming language targeting the .NET Framework and Mono.
A couple of lines below that something interesting is stated, have a look at this part:
IronPython is implemented on top of the Dynamic Language Runtime (DLR), a library running on top of the Common Language Infrastructure that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages. The DLR is part of the .NET Framework 4.0 and is also a part of trunk builds of Mono. The DLR can also be used as a library on older CLI implementations.
Hold your horses!
Let’s take a step back and think about what this means, basically it means that we can write Python code and have it interact with our code that we write in .NET! Let’s look at some code and see if this clears up a bit.
I’ve got a Python library that is somewhat going to be used for advance math-calculations and it looks like this:
class FEMathLibrary:
def __init__(self):
self.y = 3
self.z = 4
def add(self,a,b):
return a + b + self.y + self.z
For those that don’t know Python programming, what this basically does is that it creates a class, gives it two properties ( y and z ) and then it has a method called add that takes two parameters when it’s called ( a and b ). Now, I’ve spent years and years optimizing this very advance mathematical operation and I don’t want to re-write it in .NET, that would take a lot of time and cost to much. It’s also worth mentioning that Python is a dynamically typed programming language and c# is a statically typed programming language.
I imported this file into my visual studio project and the project should now look somewhat like this:

You also need to change the property on the file that states that it will be copied to the output directory, the properties for the file should look like this:

Let’s dig into the C# code, shall we?
This is what I want to do ( in human understandable terms ):
- Create a runtime that can run Python code
- Tell the runtime to run my file
- Create an instance of FEMathLibrary
- Run the very advanced Add-function
- Print the result
The only two things that you need to import are the following:
using System;
using IronPython.Hosting;
IronPython.Hosting contains a lot of classes that we can use to help us achieve the above. One of these things being a class called Python that has a very interesting method on it called CreateRuntime, we can use that like this to actually create our runtime:
var runtime = Python.CreateRuntime();
The second thing on the list is to tell the runtime to load the file, this is done by using the method UseFile on the runtime-instance. We should now have something that looks pretty much like this:
var runtime = Python.CreateRuntime();
dynamic source = runtime.UseFile("FEMathLibrary.py");
Here’s what’s interesting, the source variable is dynamic! If this was python, we could write something like this:
instance=FEMathLibrary()
result=instance.add(1,2)
print(result)
So what about the C# version? How do we create the instance of FEMathLibrary? Our dynamic object is what will let us do this, we simply write the following to create an instance of FEMathLibrary:
var instance = source.FEMathLibrary();
The rest is pretty much the same thing! Here’s how it turned out:
var runtime = Python.CreateRuntime();
dynamic source = runtime.UseFile("FEMathLibrary.py");
dynamic instance = source.FEMathLibrary();
var result = instance.add(1, 2);
Console.WriteLine(result);
The result variable contains the value 10 and that’s also what is printed out to the console! As you might see this is pretty powerful, we could even use the variables inside the FEMathLibrary instance if we wanted.
So this is one way that you can make use of dynamic in your application, IronPython has more usage areas but that’s not something that I want to cover in this post.
Hope you had fun and learned something!
?>
Vote on HN
Invoke a dynamic object as if it were a method
Posted by Filip Ekberg on October 3 2011 1 Comment
In my previous post I talked about how you can extend the DynamicObject so that you can override TryInvokeMember and TryGetMember. However, these are not the only methods that you can override. I wanted to take a brief moment and talk about one of the other methods that you can override as well, this being TryInvoke.
According to MSDN this is the reason why you want to override TryInvoke:
Provides the implementation for operations that invoke an object. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as invoking an object or a delegate.
So whatever does this mean and how do you use it?
When we overrid TryInvokeMember that meant that we could call a method that actually was not implemented in our class like this: myDynamicObject.SomeMethodToIvoke(). In this case we assumed that SomeMethodToInvoke was a member of myDynamicObject.
So this leaves us with a method that lets us invoke something, that is not a member but an actual object, this means that we can invoke our object as if it were a method. We could pretty much write this:
dynamic db
= new Database
();
db
(Operation
.Refresh);
The operation-enum looks like this:
enum Operation { FullReset, Refresh, Update };
Without changing anything in the Database-class that was created in the previous post, we will get this exception “Cannot invoke a non-delegate type” but if we add the following and compile again, everything will work out nicely!
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
result = null;
return true;
}
Exactly as I did with TryInvokeMember, I can get all information that I need out from the binder and args. In this case args will contain of one item with the value Refresh and if we add some more code here it could somewhat turn out like this:
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
result = null;
switch ((Operation)args[0])
{
case Operation.Refresh:
// Refresh the context
break;
}
return true;
}
Again, I am not saying this is what you should do, it’s just a way to demonstrate the different options you have when working with dynamic types in .NET.
I hope you had fun and learned something!
?>
Vote on HN
Extend your objects with DynamicObject to get a dynamic experience
Posted by Filip Ekberg on October 2 2011 Leave a Comment
If you have ever programmed in a dynamic programming language you know that you can pretty much ask for anything on any object, consider this code in any dynamic programming language:
var person
= new Person
();
person
.Name = "Filip";
person
.Location = "Gothenburg";
In the Person-structure used above, the property Location actually doesn’t exist, but in a dynamic programming language this is completely valid to do even if it doesn’t. You might wonder why you would ever want to be able to call on something that doesn’t exist; I will get back to that a bit further down this post.
First, let us take a look at how you would achieve something like this in C#!
Consider that we already have a class that is called “Database”, this class handles all communication with our data base or our data layer. To make my Database-class dynamic, I am going to extend it with DynamicObject. Extending with DynamicObject will allow me to override a lot of interesting methods, these two are the ones that are interesting to us now:
So what do these two methods actually allow us to do? TryGetMember will be invoked each time you try to access a member on the object, like a property or a field. TryInvokeMember will be invoked each time you try to invoke a method on the object.
If we take the first code sample from this post and compile it Visual Studio, we will get an error telling us that “Person does not contain a definition for Location” ( assuming that we have the same Person-structure here as well! ).
To avoid this, we say that the object that we are instantiating is dynamic, so in our case we have the following class defined:
class Database : DynamicObject
Our instatiation looks like this:
dynamic db
= new Database
();
Let’s take a look at the methods we want to override in our Database class now, both of these methods share two parameters these are:
The first parameter is used to get information about what the caller expects such as:
- What name was used? ( Property name, Method name )
- What return type is expected?
- How many arguments did we pass along? ( Only for InvokeMemberBinder )
- What are the argument names? ( Only for InvokeMemberBinder )
The second argument is used to set the return value and as for TryInvokeMember, we have another parameter as well, the actual arguments.
Both TryInvokeMember and TryGetMember returns a boolean that tell us if the operation succeeded or not. You might want to return false if you don’t support the property/method that was called.
So what can you do with this? Let’s take a look at some real code here!
When using the instance of our Database class I want to be able to do the following:
var products = db.Products.All();
I will not be doing any database code here, I just want to cover how to use the DynamicObject, so let’s take a look at that. First of all I override both TryInvokeMember and TryGetMember, the first method of these that will be called in the above statement is the TryGetMember.
In order to allow this fluent style of code I want me TryGetMember to look like this:
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
Table = binder.Name;
result = this;
return true;
}
What I do here is that I have a property inside my Database class that is called “Table” which just holds the name of the current table that I am working with, then I return myself as a result and finally I return true which indicates that the call worked.
The above will allow me to write db.Products and this will return our Database class with the Table-name set to “Products”.
Now the easy part is over, the next step can be as complicated as you want since you have the binder-parameter, you can get information about the Name, Arguments and Return type. What I want to do is to check if the Name of the method that I want to invoke starts with “Select” then I can ( if I want ) later on check if it is SelectAll, SelectFirst, SelectRandom and so on.
With that out of the way, all I want to do is to set the result to whatever my select returns, in this example I will just set it to null for the sake of this example.
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (binder.Name.StartsWith("Select"))
{
// SelectFirst, SelectAll, SelectAny, SelectRandom
result = null;
}
else {
result = null;
}
return true;
}
By using the above code, the following compiles and runs perfectly!
dynamic db
= new Database
();
db
.Products.SelectAll();
If you debug this, you see that TryGetMember is first accessed, the SelectAll is invoked on the returned object which takes us to TryInvokeMember where it checks what kind of method we tried to invoke.
As you can see, this opens up a whole new world of dynamic usage! In my last post, I mentioned Simple.Data and that they made use of dynamic very well, their ORM works pretty much like this and is very neat for smaller applications.
I am not saying that everything should be dynamic, but once in a while it might actually be a product step to take this approach. Just take a look at Simple.Data and you’ll see what I mean.
Hope you had fun and learned something!
?>
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