Birthday time!
25 years on this earth now… That’s quite some time, isn’t it? I’m getting older and older… a quarter century. Interesting: 18 * 5 < 25 * 4
{
static void Main(string[] args)
{
// Get the singleton.
ChristianLiensberger c = ChristianLiensberger.Instance();
// Do something with the life.
c.Living +=
c.StartLife();
while(c.IsAlive())
{
// Check if we have to increment the age.
if (DateTime.Now.Date ==
5, 31, 11, 30, 0))
{
c.IncrementAge();
}
// Other, not so interesting code…
// Invoke the delegate.
c.InvokeLiving();
}
// Put christian into the archive.
HumanityArchive.Add(c);
}
}
public sealed class ChristianLiensberger : Human, IMale
{
// Hidden implementation.
}
It’s time to eat some cake now ![]()
Published on May 31st, 2007 —
Tags: Personal
Comments (6)
digg it!
kick it
Popfly: Starting to create own blocks
Popfly is Microsoft’s youngest sprout. The platform runs only on the internet (there is no offline client) and uses heavily Silverlight. Right now you can only use it when being invited by the team. I was lucky (as one of the top posters on Channel 9) to get an invitation. I thought, since I got the honor to participate in the early alpha program, I need to create something and give that back to the Popfly community.
Well, why not to create some blocks and post a short tutorial on how to create own blocks?
What’s a block? The long answer is found in the Popfly video on Channel 9. The short answer is the following: a block is basically a piece of code (a class) that is connectable with other blocks. A block might stand at the very beginning of a block chain and get data from some external source. It might stand at the very end of the chain and output the results to any visual representation or stand in the middle and just process data. The following screenshot shows three blocks that are connected:

The most right block displays the output in a web gadget. It’s basically a news reader that could be embedded in any website or even downloaded as gadget for the Windows Vista sidebar. The block on the very left gets the most recent posts of a Channel 9 user and the one in the middle removes the HTML tags from the post’s text (reason: the Channel 9 feed returns HTML which looks terrible in the news reader). The two left blocks are custom written. Let’s dive in and see how to write these blocks.

The best way to write your blocks right now is to use Visual Studio. Popfly offers an embedded editor, but that editor is really alpha and doesn’t work that well. Popfly blocks are not written in C# or any other .NET language. They are written in Javascript! Each block needs also an xml manifest that describes the block itself: such as method names, parameters, output values etc.
Debugging doesn’t work very well too (right now). For some basic syntax checking, you could put the JavaScript code in a .js file and double click it. If there is a syntax error you get a nice message box that shows the error and the line where it happened.
First let’s create the block that converts an HTML string to a plain text string. Let’s start with that block because it’s a very simple one. The JavaScript looks like this:
function ClearHtml()
{
this.__getTextRepresentation = “”;
}
// Get the posts of the niner.
ClearHtml.prototype.getTextRepresentation = function(html)
{
// Clear the html from tags.
return html.replace(/<br.*?(\/)*>/g, “\r\n“).replace(/<(\/)*.*?>/g, “”)
.replace(“"”, “\”“).replace(“&”, “&”);
}
Popfly recommends to create a class for each block. Otherwise methods are defined globally and you could get in trouble, when another block defines the same global method.
In this case the ClearHtml function defines the ClearHtml class. Defining a class in JavaScript looks a little bit strange. Next we create the “getTextRepresentation” method. The method is attached to the ClearHtml’s prototype and takes one argument. In JavaScript the type of the argument is not required. JavaScript is very dynamic and the type is fetched during runtime! Inside the method some Regex is used to remove the tags and replace, for example, the <br /> tags with a line break.
Next let’s move to the xml document. The xml document contains metadata for the block. The meta data is shown when using the block and used by Popfly to do some reasoning over the block. It looks like this:
<block class=“ClearHtml”>
<providerName>Christian Liensberger</providerName>
<providerUrl>http://www.liensberger.it</providerUrl>
<providerLogoUrl></providerLogoUrl>
<blockIconUrl></blockIconUrl>
<operations>
<operation name=“getTextRepresentation”>
<description>
Gets the text representation of a HTML content. Removes all tags,
converts some of the HTML escape codes and replaces the HTML line breaks
with text line breaks.
</description>
<inputs>
<input name=“html” required=“true” type=“string”>
<description>The html content that is converted to plain text.</description>
<defaultValue></defaultValue>
<constraints />
</input>
</inputs>
<outputs>
<output isArray=“false” type=“string” />
</outputs>
</operation>
</operations>
</block>
The xml is very simple. It starts with the definition of the class (you could use more then one class in your code). Next some metadata is specified (like the name of the provider, the url, the logo and icon url). After that the interesting part starts: the operations. An operation is a method in the JavaScript code. For each operation the inputs (arguments) and outputs (result of the method) need to be specified. It’s very important to specify the appropriate types here: Popfly does type mapping when using the output data from one block as input data in the other block. The parameters whose types match are automatically associated.
This block is now ready to be used. Open your web browser and browse to your Popfly home page. From there click “Create Block” to create a new block and copy + paste the xml and code into the two tabs. Save it and you are ready to go.
The next block to do is the more complexer “Niner Feed” block. This block gets the recent posts of a Channel 9 user from its RSS and returns an array of posts as result. The JavaScript looks like this:
{
this.__getLatestPosts = [new NinerPost()];
}
// Get the posts of the Channel 9 user (aka niner).
NinerClass.prototype.getLatestPosts = function(id)
{
// Get the xml for the niner feed.
var url = “http://channel9.msdn.com/rss.aspx?UserID=” + id;
var xml = environment.getXml(url);
// Get the items and items count in the RSS.
var items = xml.getElementsByTagName(“item”);
var count = items.length;
// Create the array holding the results.
var result = new Array(count);
// Loop over all items.
for(var i = 0; i < count; i++)
{
// Get the values from the item.
var title = items[i].getElementsByTagName(“title”)[0] ?
items[i].getElementsByTagName(“title”)[0].firstChild.nodeValue : “”;
var pubDate = items[i].getElementsByTagName(“pubDate”)[0] ?
items[i].getElementsByTagName(“pubDate”)[0].firstChild.nodeValue : “”;
var link = items[i].getElementsByTagName(“link”)[0] ?
items[i].getElementsByTagName(“link”)[0].firstChild.nodeValue : “”;
var creator = items[i].getElementsByTagName(“dc:creator”)[0] ?
items[i].getElementsByTagName(“dc:creator”)[0].firstChild.nodeValue : “”;
var description = items[i].selectSingleNode(“description”) ?
items[i].selectSingleNode(“description”).firstChild.nodeValue : “”;
// Add the item to the result array.
result[i] = new NinerPost(title, pubDate, link, creator, description);
}
return result;
}
// This class represents one post of a Channel 9 user (aka niner).
function NinerPost(title, createdAt, url, creator, description)
{
this.Title = title;
this.CreatedAt = createdAt;
this.URL = url;
this.Creator = creator;
this.Description = description;
// Converts the class to a html representation.
this.toString = function()
{
var html = “”;
html += “<h1><a href=’” + url + “‘ target=’_blank’>” + title + “</a></h1>”;
html += “<h2>by “ + creator + ” at “ + createdAt + “</h2>”;
html += “<div id=’description’>” + description + “</div>”;
return html;
}
}
This code is a little bit complexer. In this case two classes are defined. One holds the results (NinerPost) the other one (NinerClass) has the “getLatestPosts” method that returns the most recent posts. The NinerPost class implements also a “toString” method. The Popfly documentation recommends to create that method for each class that is returned by a block. The method should return a HTML representation of the class - it may be directly used by some basic output blocks.
The xml file looks a little bit complexer. That is because the “NinerPost” class needs also its representation in the xml file.
<block class=“NinerClass”>
<providerName>Channel 9</providerName>
<providerUrl>http://channel9.msdn.com/</providerUrl>
<providerLogoUrl>http://channel9.msdn.com/flair/images/9_8×31_animated.gif</providerLogoUrl>
<blockIconUrl>http://channel9.msdn.com/flair/images/9_8×31_animated.gif</blockIconUrl>
<operations>
<operation name=“getLatestPosts”>
<description>
Gets the latest posts of a niner (Channel 9 user) you want to watch.
</description>
<inputs>
<input name=“id” required=“true” type=“int”>
<description>The user ID of the niner (Channel 9 user) you want to watch.</description>
<defaultValue>6070</defaultValue>
<constraints />
</input>
</inputs>
<outputs>
<output isArray=“true” type=“custom” object=“NinerPost” />
</outputs>
</operation>
</operations>
<objects>
<object name=“NinerPost”>
<field name=“Title” type=“title” isArray=“false” />
<field name=“CreatedAt” type=“date” isArray=“false” />
<field name=“URL” type=“url” isArray=“false” />
<field name=“Creator” type=“creator” isArray=“false” />
<field name=“Description” type=“description” isArray=“false” />
</object>
</objects>
</block>
The most important changes compared to the previous block’s xml file are:
- The type of the “output” node’s “type” is set to custom and the “NinerPost” class is set in the “object” attribute. That’s required when specifying a custom class that is returned by the block!
- The “NinerPost” class description itself is nested in the “objects” tag. The “objects” tag holds the classes that are returned by a block operation. It’s required here to describes in detail all the fields that are exposed by the class that’s returned. This piece is very important for the automatic matching of the block’s output values with another block’s input values.
The “NinerPost” block is also ready to be used. As you can see creating blocks for Popfly is really easy. Now it’s your turn to create awesome blocks for Popfly. ![]()
Published on May 27th, 2007 —
Tags: Popfly, Silverlight, Web programming
Comments (0)
digg it!
kick it
Channel 9 guy visiting our garden
I got a Channel 9 guy a few weeks ago. They, over at Channel 9, send to everyone a nine guy, who writes them a postcard or asks kindely. Now on Channel 9 there is a section that says: 9 guy around the world. It is literally a list of pictures showing the guy in different places on the world.
The pictures are taken by people who own a 9 guy. Today I have had some time to make a few pictures in our garden (here in the north of Italy). These are the results:
The 9 guy is waiting for the Italian wine to grow.

In the meantime he climbs the fig tree in our garden. He became hungry from the waiting and climbing and is in search for something to eat…

… he finally sees the oregano and eats some of it.

After having eaten the 9 guy is tired and relaxes on our swing.

Mario prototype for Xna
Some Channel 9 members (aka. niners) may already know that I did an Xna “Super Mario” prototype a while ago. I had it only posted as a Channel 9 thread, but thought it is worth to be put into my website’s projects area. Feel free to download and play around with it.
It’s a very simple prototype and please don’t judge me on its code! The game shows some basic things on how to animate a sprite, move it around, play some sound and draw background images (in different layers). It’s held very simple and thought as an introduction into Xna.
To compile the game, please download the Xna Game Studio Express. You can control Mario via an Xbox controller that is plugged into the PC or the keyboard (keyboard settings are found in the project section of my website). If you are member of the Creators club, you could also upload the game to your Xbox 360 console and play it there.
I hope you have as much fun to play and explore it as I had coding it!
Preconditions, postconditions and lambdas
To my surprise there is no way to specify a precondition or a postcondition for a lambda expression in C# 3.0. I have also contacted a member of the C# team and have been told that this is not supported. It might have to do with the fact that lambda expressions are just anonymous delegates, only the notation is different.
Now I thought why not to create something that allows me to specify a bunch of lambda expressions with preconditions and postconditions. Some sort of a group that can be executed as one thing, where the preconditions and postconditions are evaluted and which allows me to do some nice tricks in the end. When I did my university course on functional programming (we used Haskell) there was a way to specify preconditions that were evaluated before the function had been executed. Something similar is needed
I know you can always specify an if statement (or a tenary statement) in your lambda expression, but what if you have multiple ifs; are you going to put them all together in one function - it fast starts to grow and it’s getting very hard to understand and maintain.
It is time for some code now. My class that holds the list of conditions + lambda expressions is called FunctionGroup
/// Represents a group of functions.
/// </summary>
/// <typeparam name="TArg0">The type of the argument.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
public class FunctionsGroup<TArg0, TResult>
{
#region GroupItem
// One item of the group.
private struct GroupItem<VArg0, VResult>
{
public Func<VArg0, bool> PreCondition;
public Func<VResult, bool> PostCondition;
public Func<VArg0, VResult> Function;
}
#endregion
private List<GroupItem<TArg0, TResult>> _items =
// Adds a function to the group.
public void Add(Func<TArg0, bool> precondition,
Func<TArg0, TResult> func)
{
Add(precondition, null, func);
}
// Adds a function to the group.
public void Add(Func<TArg0, bool> precondition,
Func<TResult, bool> postcondition,
Func<TArg0, TResult> func)
{
if (precondition == null)
throw
if (func == null)
throw
_items.Add(
Function = func,
PreCondition = precondition,
PostCondition = postcondition });
}
// Invokes the function group.
public TResult Invoke(TArg0 argument)
{
// Get the next valid function to execute.
// The precondition is executed to understand if the
// function is a possible candidate.
var query = from c in _items
where c.PreCondition(argument)
select c;
// Loop over all candidates.
foreach(var item in query)
{
// Invoke the function of the first candidate.
TResult result = item.Function(argument);
// Invoke the postcondition.
if (item.PostCondition == null ||
item.PostCondition(result))
return result;
}
// No match! Throw an exception.
throw
” no pre- and post-condition pair matches!”);
}
}
Now this class is very simple. It has two methods to add functions. One allows to specify a precondition + function and the other a precondition, postcondition + function. More interesting is the Invoke method. That one starts the evaluation for the function group. It first selects the possible candiates by checking the preconditions. In this piece of code it might look like as if the preconditions for all methods are evaluated and the result is returned as “query” variable. But Linq on objects (IEnumerables in this case) does some sort of lazy evaluation. The preconditions are evaluated one by one when doing the foreach loop. It means that preconditions are only evaluated until a valid candidate has been found. To speed things up functions with preconditions that are often true, should be added as first ones to the function group!
Next we might use this class to do some calculations. Let’s calculate the factorial of a number; nothing special, but not bad to begin with:
factorial.Add(x => x > 1, x => x * factorial.Invoke(x - 1));
factorial.Add(x => x == 1, x => 1);
// Invoke and get the result.
int result = factorial.Invoke(10);
This piece of code does a recursion. As long as x > 1 it calls the “factorial” function group with x -1 and multiplies the result; otherwise 1 is returned.
Next let’s implement Quicksort. Quicksort is a divide an conquer algorithm. That means that the input is split up into little pieces and the algorithm is then executed on these pieces.
How does Quicksort exactly work?
It selects a pivot element (let’s take the first in the list). Next puts all items from the list that are lower or equal than the pivot element on the left of the pivot element (in a random order) and puts all elements that are higher than the pivot element to the right (also in a random order). Now quicksort is called again with the left part and the right part. A pivot element for the left part is selected and all elements (in the left part) lower or equal than the pivot are put on the left of the new pivot element all elements (in the left part) higher than the pivot element are put on the right side. This happens also for the right part and is done until the algorithm reaches 3 elements, where one is going to be the pivot element and one is going to be lower or equal and one higher or equal than the pivot element. If that is done for all triplets the list is sorted. Typically it takes n*log(n) comparisons to sort a list with n elements.
If you look at implementations for quicksort in procedural programming languages they look always very complicated compared to our implementation:
quicksort.Add(x => x.Count > 0,
x =>
.Append(quicksort.Invoke(x.FilterTail(g => g <= x[0])))
.Append(x[0])
.Append(quicksort.Invoke(x.FilterTail(g => g > x[0])))
);
quicksort.Add(x => x.Count == 0, x => x);
// Create the list that is going to be sorted.
var list =
// Start quicksort.
IList<int> result = quicksort.Invoke(list);
Append and FilterTail are method that I have written. Append just adds a list or a single item to an IList
This looks a lot more like the Quicksort definition than if this would be done in a procedural way! For completeness the next code sample shows how FilterTail and Append have been implemented:
{
public static IList<T> FilterTail<T>(this IList<T> list,
Func<T, bool> func)
{
return (from i in list.Skip(1)
where func(i)
select i).ToList();
}
public static IList<T> Append<T>(this IList<T> list,
IEnumerable<T> otherlist)
{
foreach(var item in otherlist)
list.Add(item);
return list;
}
public static IList<T> Append<T>(this IList<T> list,
T item)
{
list.Add(item);
return list;
}
}
Last but not least I’m going to implement a tree walker for our function group. The walker is going to walk a binary tree: first it is going down to the left. If nothing is left on the left side it is going up one node and next it is going down right. The nodes that are walked are printed as result.
The TreeItem class looks like this:
public class TreeItem
{
// The element on the left.
public TreeItem Left { get; set; }
// The element on the right.
public TreeItem Right { get; set; }
// The text of the element.
public string Text { get; set; }
}
And the compiled tree looks like this:
var c =
var r =
var h =
var i =
var n =
var a =
var s =
var t =
var root =
The function group is set up like this:
var walker =
walker.Add(x => x.Left == null && x.Right == null,
x => !string.IsNullOrEmpty(x),
x => x.Text);
walker.Add(x => x.Left == null && x.Right != null,
x => !string.IsNullOrEmpty(x),
x => x.Text + walker.Invoke(x.Right));
walker.Add(x => x.Left != null && x.Right == null,
x => !string.IsNullOrEmpty(x),
x => walker.Invoke(x.Left) + x.Text);
walker.Add(x => x.Left != null && x.Right != null,
x => !string.IsNullOrEmpty(x),
x => walker.Invoke(x.Left) + x.Text +
walker.Invoke(x.Right));
string myName = walker.Invoke(root);
The final output should be my name. In this case the functions are specified with pre- and postconditions. The postcondition only says that a node with an empty text is not taken returned!
The collision between the Milky Way and Andromeda
In 2 billion years our galaxy (Milky Way) is going to collide with the Andromeda Galaxy. Andromeda is the nearest galaxy and is moving nearer as you read this here. T.J. Cox and Abraham Loeb have simulated the collision in a recently published paper: “The Collision Between The Milky Way And Andromeda” (full paper as PDF).
The collision is not going to be a crash, like when two cars crash. There is to much empty space between each star (and planetary systems). It’s more going to be a fly through and interaction between the two galaxies. The spectacular is going to look like a dancing pair. In the end it’s going to be one galaxy that has the mass of ours and the Andromeda and looks like a Rugby ball.
While the two galaxies interact the stars’ gravitations are going to interact with each other: some stars might crash and some others might change the position and/or course. Our solar system is also going to be influenced by the collision. Sun and earth (and all other planets in our system) are going to be moved from the current position to a very distant position from the galaxy core. We are not very near the core right now (if we take a city, we are in the suburb), but the new position is going to be even farther away (somewhere in the country).
Our sun won’t be exploded and a white dwarf by that time, but it will be a lot bigger than right now. Life on our planet will be impossible (because of the heat) and some of the inner planets (Mercury, for example) might have been absorbed by the sun until then.
If humanity still exists (there are so many reasons why not) they must have perfectioned travelling into space and found a new planet to life on… an Earth 2 perhaps?
How to write a simple ADO.NET ORM by using Linq and extension methods - in 10 minutes
Yesterdays post from Alex James inspired me to create a very simple “ORM” by using C# 3.0’s extension methods and Linq. I wanted the ORM to be very simple and to build upon the existing ADO.NET infrastructure. That means that the “framework” is going to use the existing ADO.NET classes and extend them to return persistent object instances.
The classic methods are still available. The new methods are implemented as extension methods and add therefore only something without removing something else - which is great!
Now let’s get started. First I thought of creating an attribute to create the mapping between the persistent object and the returned data. Note that in C# 3.0 private fields don’t need to be created for a property, if not accessed from somewhere else then through the property itself (that’s why the setter and getter are empty!)
/// Attribute used to decorate the properties that are filled with
/// the result from the database.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class ColumnAttribute : Attribute
{
/// <summary>
/// Name of the column in the database.
/// </summary>
public string Name { get; set; }
}
Next we need to define some extension methods. I’m going to put that code into a static class called “ADONETExtensions”.
{
// Methods…
}
The first method that’s going to be added is a method that returns an enumerator for the classes that implement the IDataReader interface. I have the method called GetEnumerator.
/// Gets an enumerator for the given datareader.
/// </summary>
public static IEnumerable<T> GetEnumerator<T>(this IDataReader reader) where T :
{
// Ensure to close the reader when done.
using (reader)
{
// Read until we reach the end of the result.m
while (reader.Read())
{
// Create a new instance of the object to return.
T instance = Activator.CreateInstance<T>();
// Get a enumerable of properties that have
// the ColumnAttribute specified.
// Return an anonymous type that holds the
// property and the ColumnAttribute.
var props = from c in
where Attribute.GetCustomAttribute(c,
select
// For each property returned set the value
// returned by the database.
props.ToList().ForEach(x => x.Property.SetValue(instance, reader.TryGetValue(x.Attribute.Name), null));
// Return the current instance.
yield return instance;
}
}
}
The method uses a Linq statement to get all properties of the specified persistent type that are decorated with the “ColumnAttribute” attribute. The property and attribute itself is returned as new anonymous type. They are going to be used later in the ForEach method. Foreach loops through all mapped properties and does something. In this case we set the returned value (from the query) as the property value in the persistent object instance. ForEach expects a delegate. We are using a lambda expression here. A lambda expression is another notation for an anonymous delegate.
TryGetValue is an extension method that is also implemented in the ADONETExtensions class and looks like this:
/// Tries to get a value for the given column name.
/// </summary>
public static object TryGetValue(this IDataReader reader, string name)
{
// Get the schema table for the data reader.
DataTable table = reader.GetSchemaTable();
// The first column of the schema table
// contains the names of the returned columns.
// Loop through all rows of the first column to
// understand if the given column name (name
// argument) is found in the schema table.
for (int i = 0; i < table.Rows.Count; i++)
{
if (table.Rows[i][0].ToString().ToLower() == name.ToLower())
{
// If found return the value at the index i.
return reader[i];
}
}
// Return null if the column is not in the result.
return null;
}
What might be a little bit confusing is the “GetSchemaTable” call. This call returns a DataTable that holds the schema of the returned IDataReader’s data. The best way to understand what’s found in this table is to set a breakpoint into the code and have a look at the table.
What we need next is a way to get the objects from our database connection. That’s why we create a GetObjects extension method for IDbConnection. This method is very similar to the one that has been created by Alex. The differences are that the method expects a generic type (the type T of the persistent objects being returned), next it returns an IEnumerable
/// Gets objects from the database.
/// </summary>
/// <param name="sql">The SQL statement to get the objects.</param>
public static IEnumerable<T> GetObjects<T>(this IDbConnection connection, string sql) where T :
{
// Create a new command.
IDbCommand command = connection.CreateCommand();
command.CommandText = sql;
// Get the reader.
return command.ExecuteReader().GetEnumerator<T>();
}
Now we are done with our “ORM”. Next is to create a persistent object that uses our “ColumnAttribute” to specify the mapping:
{
/// <summary>
/// Property Name maps to column NAME.
/// </summary>
[Column(Name = “NAME”)]
public string Name
{
get;
set;
}
}
The column name and property name equal only in this example.
We are finally done with creating classes. Now let’s use them!
{
static void Main(string[] args)
{
// Create the connection to the database.
SqlConnection connection =
connection.Open();
// Filter the database results by using
// a Linq expression.
var result = from u in connection.GetObjects<User>(“select * from [USERS]“)
where u.Name == “Alex” || u.Name == “Christian”
orderby u.Name ascending
select u;
// Loop over the results.
foreach(var user in connection.GetObjects<User>(“select * from [USERS]“))
{
// Do something.
}
// Return a list with the results.
List<User> list = connection.GetObjects<User>(“select * from [USERS]“).ToList();
}
}
That’s it. Our little framework allows us to load persistent objects from the database. The framework is very simple and leaves still a lot of open points. There is, for example, no way to handle database parameters at the moment and it needs also a way to save the persistent objects back to the database.
That’s now up to you… Happy coding ![]()
Published on May 12th, 2007 —
Tags: lambda expressions, LINQ, Object Relational Mapper
Comments (5)
digg it!
kick it
Making DataReaders play nicely with LINQ
Ever thought of using ADO.NET in combination with Linq? I mean not to create the query, but to actually filter the results returned by the database? Alex James (from base4.net) is showing us some great examples on how ADO.NET, Linq and extension methods play nicely together. Check it out.
… and I agree with him that C# 3.0 (or is it C# 3.5?) is great! ![]()





