Adding some dynamic to C#: interface wrapping

C# is not a dynamic language. That’s for sure! Recently, the adding of the var keyword, anonymous types and lambda expressions have added some “dynamic” to the language. But still it’s not a dynamic language.

I have heard people saying that C# is never going to be a dynamic language. But it seems as if the next version is going to add more dynamic to the language.

C# being completely static sometimes bothers me; it’s not that often but sometimes I would like to do something and it’s only possible with a lot of walk arounds and sometimes even minor hacks. One thing, for example, is that you can’t really return an instance of a anonymous type from a method without doing a little bit of weird looking hacking (greetings to Tomas; it was cool to chat with you in the metro at the end of TechEd).

Wouldn’t it be cool if an anonymous type could be wrapped into an interface and you could return that? Also, wouldn’t it be cool to wrap any type (also the one that are part of the .NET Framework) into an interface; independent of the type implementing that interface. Let’s say you have objects that implement a Close method and you want to define an interface called IClosable. Now if a class implements the Close method you want to wrap it into the IClosable interface and store all these instances in a Dictionary for later usage.

With C# you can’t do that because it’s not possible to cast an object to an interface if not implemented.

Still that feature would be interesting to have in some scenarios and that’s why I implemented a class that enables that. In enables you to wrap any class into an interface, when the class implements the methods and properties that are required by the interface. The class doesn’t need to implement the interface!

public interface IFoo
{
    string Name { get; }
    int Age { get; }
}

class Program
{
    static void Main(string[] args)
    {
        IFoo foo = CreateDynamicType();

        var name = foo.Name;
        var age = foo.Age;

        // output the results.
        Console.WriteLine(name + ” “ + age);
    }

    public static IFoo CreateDynamicType()
    {
        // create the anonymous type.
        var f = new { Name = “Test”, Age = 100 };

        // wrap the interface around the type.
        IFoo foo = f.WrapIntoInterface<IFoo>(false);
        if (foo == null)
            throw new Exception(“Houston, we’ve had a problem.”);

        return foo;
    }
}

The example shows the wrapping of an anonymous type into the IFoo interface.

Making this work involves a little bit of magic and some deeper knowledge of the CLR and IL. The .NET Framework offers in the System.Reflection.Emit namespaces classes that allow creating assemblies, modules, types, methods, properties etc. during runtime. I have used these classes to create the solution.

If the user wants to wrap a class with an interface a new in-memory class is generated and that new class implements the required interface. The generated class has also a constructor that takes the original class as argument. If one of the interface methods or properties are invoked the call is forwarded to the inner class.

The in-memory generated class for the example before looks like this:

// This class implements the IFoo interface and
// wraps the original instance.
public sealed class <>f__AnonymousType0`2<>IFoo__$wrapper$! : IFoo
{
    // The original instance.
    private <>f__AnonymousType0<string, int> _original;

    // The constructor takes the original instance.  In this case an
    // instance of the anonymous class.
    public <>f__AnonymousType0`2<>IFoo__$wrapper$!(
        <>f__AnonymousType0<string, int> type1)
    {
        this._original = type1;
    }

    // other methods, like Equals, ToString etc.; collapsed.

    // The property calls are forwarded to the original object.
    public override int Age
    {
        get { return this._original.Age; }
    }

    public override string Name
    {
        get { return this._original.Name; }
    }
}

I’m cheating a little bit under the covers by creating this dynamic class; C# hasn’t become dynamic from the sudden. But creating the in-memory class does the job very nicely and the user doesn’t see it.

To enhance speed I’m also adding the generated types to a dictionary. That increses speed because for further requests the type can be reused and doesn’t need to be generated again.

This approach could also be extended to enable aspect-oriented programming for C# or .NET in general. The idea would be to add call backs before and after the method/property/etc. calls are forwarded to the inner (wrapped) class.

Interesting in playing with this code? Click here to download the full source code (including the example of this post).

Published on Mar 21st, 2008 — Tags: , , ,
Comments (4)    digg it!    kick it   

LINQ to XML: An introduction

Why LINQ to XML? This addition was needed; the best way to understand that is to show what you had to do when you wanted to created a simple XML document as the following…

<users>
  <user>
    <name>Alice Wonderland</name>
  </user>
  <user>
    <name>Joe Smith</name>
  </user>
</users>

… in .NET 2.0:

class Program
{
    static void Main(string[] args)
    {
        // create the main xml document.
        XmlDocument xml = new XmlDocument();

        // create and add the users node.
        XmlElement users = xml.CreateElement(“users”);
        xml.AppendChild(users);

        CreateUserNode(xml, users, “Alice Wonderland”);
        CreateUserNode(xml, users, “Joe Smith”);

        // save the results to a temporary file.
        xml.Save(@“C:\Users\Chris\Desktop\output.xml”);
    }

    private static void CreateUserNode(XmlDocument xml, XmlElement users, string name)
    {
        // create and add the user node.
        XmlElement user = xml.CreateElement(“user”);
        users.AppendChild(user);

        // create and add the name node.
        XmlElement nameNode = xml.CreateElement(“name”);
        user.AppendChild(nameNode);

        // create and add the text node.
        XmlText text = xml.CreateTextNode(name);
        nameNode.AppendChild(text);
    }
}

Quite a complex task for such a simple XML file, isn’t it?!

That’s also what the .NET team thought, and for .NET 3.5 they have added the LINQ to XML featureset. LINQ to XML is not only a way to query XML but also a way to compile more easily XML files. Some languages, speaking of VB9, take this concept even a step further and hide the XML creation from the user. Check out the VB9’s XML literals to understand what I mean.

Compiling the XML file from above in C# 3.5 (by using LINQ to XML) looks like this (the key class here is XElement):

static void Main(string[] args)
{
    // create the main xml document.
    XElement xml = new XElement(“users”,
        new XElement(“users”,
            CreateUserNode(“Alice Wonderland”),
            CreateUserNode(“Joe Smith”)));

    // save the results to a temporary file.
    xml.Save(@“C:\Users\Chris\Desktop\output.xml”);
}

private static XElement CreateUserNode(string name)
{
    return new XElement(“user”,
        new XElement(“name”, name));
}

Way shorter, way better! It’s also a lot easier to understand because the items are nested in exactly the same way as they are nested in the final XML file. Creating XML files is finally fun in C#. 8)

Querying XML files

But let us come to the more interesting part now: querying xml files. To allow us to do some proper querying let’s use a more “elaborated” XML file:

<root>
  <user female=“true”>
    <firstName>Emma</firstName>
    <lastName>Heinz</lastName>
    <location>Salzburg</location>
  </user>
  <user female=“false”>
    <firstName>Joe</firstName>
    <lastName>Smith</lastName>
    <location>Vienna</location>
  </user>
  <user female=“true”>
    <firstName>Emma</firstName>
    <lastName>Smith</lastName>
    <location>Vienna</location>
  </user>
</root>

It would be interesting to query for all the females (having the female attribute not null and set to true) and order the result by location. The result is returned as anonymous type and displayed in the console window.

Querying XML files was also possible prior to .NET 3.5 and LINQ to XML. You had to use XPath to do that.

var xml = XElement.Load(@“C:\Users\Chris\Desktop\users.xml”);

// create a query on the xml document.
var query = from u in xml.Elements()
            where u.Attribute(“female”) != null && u.Attribute(“female”).Value == “true”
            orderby u.Element(“location”).Value descending
            select new
            {
                FirstName = u.Element(“firstName”).Value,
                LastName = u.Element(“lastName”).Value,
                Location = u.Element(“location”).Value
            };

foreach (var item in query)
{
    Console.WriteLine(“First: “ + item.FirstName + “; Last: “ + item.LastName + “; Location: “ + item.Location);
}
Console.ReadLine();

The first line of the query asks for all elements underneath the root element: for all “user” elements in our case. Then the query checks if a “female” attribute is present and compares the value of the attribute with the “true” constant. After that the results are ordered by the value in the “location” node. Finally, the result is returned as anonymous type where the values of the “firstName”, “lastName” and “location” node are used to initialize the properties of that type.

LINQ to XML supports all the different query operators that you know from LINQ to Objects or LINQ to SQL.

The current LINQ to XML implementation has still one big problem: you need to specify the names of the nodes as string and can’t use properties for them. That means that you only get errors for invalid nodes during runtime and not during compile time. This could be solved if the XML file would implement a schema and a tool would convert this schema into classes that you could use. This might come in the future but right now nothing is avaible (for LINQ to XML) that does this task.

Another interesting example is to extend the The LINQ to XML concept to read data from another data source and use the new classes to create the XML stream. This might be very interesting if you want to return an ATOM/RSS feed for data that is found in your database or any other data source:

// create a simple list with three elements.
var list2 = new List<Foo>
{
    new Foo { FirstName = “Joe”, LastName = “Smith” },
    new Foo { FirstName = “Emma”, LastName = “Who” },
    new Foo { FirstName = “Andrea”, LastName = “Smith” }
};

// query from the list all with the last name "Smith" and
// create an XML element for each result. The generated
// list of XElements is then added to the root "users" element.
var xml = new XElement(“users”,
            from f in list2
            where f.LastName == “Smith”
            select new XElement(“user”,
                new XElement(“firstName”, f.FirstName),
                new XElement(“lastName”, f.LastName)));

// save the result to the desktop.
xml.Save(@“C:\Users\Chris\Desktop\output.xml”);

Published on Mar 16th, 2008 — Tags: , ,
Comments (3)    digg it!    kick it   

LINQ design guidelines

Mircea Trofin, a program manager on the .NET team at Microsoft, has posted an interesting article on what guidelines should be followed when implementing LINQ features in own classes and framework (he covers extension methods, Func, Action, Expression, IQueryable, IEnumerable etc).

These guidelines have been reviewed by the .NET team and are somehow official. They seem very logical and it’s also the way how I think that LINQ should be implemented in own classes.

Check them out.

Published on Mar 15th, 2008 — Tags: ,
Comments (0)    digg it!    kick it   

MIX Keynote: WPF and Shaders

Finally I have been able to watch the keynote that Scott Guthrie gave at MIX08. It was awesome and very well done. I liked how during the keynote he showed off a lot of different example; very much Scott like…

One thing that was really interesting is that the WPF team is going to add shader support for WPF. They showed examples where shaders were applied to an image and a text box control:


The shader support is going to be available in the summer when the .NET team is going to ship a refresh of WPF (the refresh will include a lot of new controls for WPF too) and other services.

Published on Mar 13th, 2008 — Tags: ,
Comments (0)    digg it!    kick it   

IE8’s JavaScript errors message window

Awesome; they did it! The old JavaScript errors window from IE7 (and before; actually there since ever) was replaced with a new and way cooler version:

Still some stuff is missing, like it would be awesome if they could add also the stack trace of the exceptions, the file where the exception happened etc., but it’s already a great step forward.

Published on Mar 13th, 2008 — Tags: , ,
Comments (1)    digg it!    kick it   

IE8’s missing feature: the download manager

Don’t get me wrong, I love the effort that is put into Internet Explorer 8. It’s awesome that standard mode is switched on by default and that IE8 finally passes the ACID2 test. But there is something that bothers me since Internet Explorer 3.02 and that’s, believe it or not, a missing feature: the download manager.

I have been downloading Singularity today (yes, they are public, for people who have missed that; like me) and look what I got:

downloadwindowie8.png

The IE team added something to the bottom of the standard download dialog that is telling me that the download is safe, which is awesome and made me curious. I thought: since they have enhanced the download dialog, perhaps, they have also added a window that’s showing the current downloads and allows to resume etc. I scanned IE8 but nothing is there…

I wonder why a download manager has never been added to IE although they thought once about it; remember the good old Longhorn concept screens:

longhorndownloadmanager.png

Is it just because they have been busy with creating the new layout engine and the download manager is at the bottom on the list? Or why is it? Anybody having an idea?

Published on Mar 11th, 2008 — Tags: ,
Comments (9)    digg it!    kick it   

Writing data to an XML file in Visual Basic 9 (Part 5) - Sorting a list

Alex asked the following question in the Channel 8 forums:

[...] cheers for that, I fixed up the code and gave my save button the DialogResult of OK so it works as it should except that it doesn’t organize the new waterpoints into alphabetical order until the program is restarted. The old version used to do this, how can I make it change order on the fly?

Luckily we have already the list of users in an instance of the List(Of T). This class has a method (Sort) that allows us to sort items, by using a Comparison delegate (more on delegates here) or an instance of a class that implements the IComparer interface.

Now we don’t want to have this method executed everywhere in the UI. Rather we want it to be encaspulated in a class (following part 4 where we separated the UI from the logic). I have therefore created a new class called UserList that inherits from List(of T) and added a method that sorts by the first name. That method invokes the original Sort method on the List(Of T) and returns after having done the sorting:

Imports System.Collections.Generic

‘ holds a list of user.
Public Class UserList
    Inherits List(Of User)

    ‘ sorts the list of items by first name.
    Public Sub SortByFirstName()

        ‘ sort by using our sorter method.
        Me.Sort(AddressOf FirstNameSorter)

    End Sub

    Private Function FirstNameSorter(ByVal x As User, ByVal y As User) As Integer

        ‘ if the first’s element first name is null return -1
        If x.FirstName Is Nothing Then
            Return -1
        End If
        ‘ if the second’s element first name is null return 1
        If y.FirstName Is Nothing Then
            Return 1
        End If

        ‘ otherwise use the build in comparison.
        Return x.FirstName.CompareTo(y.FirstName)

    End Function

End Class

The next step was to replace all the List(Of T) occurences with the UserList where it was required. After that I changed also the code to call the SortByFirstName method each time after an item has been added or edited.

Dim user = New User()

‘ show the edit for as dialog with this form as parent.
Using dialog = New EditXML(user)
    ‘ check if the dialog has been returned with a click on the OK button.
    If dialog.ShowDialog(Me) <> Windows.Forms.DialogResult.OK Then
        Return
    End If
End Using

‘ the dialog has been "OKed"; let’s add the user to our list.
_users.Add(user)

‘ sort the list.
_users.SortByFirstName()

UpdateControls(True)

The full source code can be downloaded form here.

Published on Mar 5th, 2008 — Tags: , , ,
Comments (0)    digg it!    kick it   

Academic Community Launch 2008

Alex, Mario, Horst and me are organizing (Alex and Mario are doing a lot of the work) the so called “Academic Community Launch 2008″ in Austria. 8)

communitylaunch.png

The community launch is free for students and interested people (free as you don’t have to pay any entry fee and you get something to drink and eat for free). We are going to talk about the new features in Visual Studio 2008 (Mario), the new data features in .NET 3.5, SQL Server 2008 and beyond (Alex) and the new features in .NET 3.5 such as LINQ, anonymous types, lambda expressions, XML literals, own LINQ providers, … (me).

The talks are going to be in German and we will tour all Austria; including Salzburg, Linz, Hagenberg, Innsbruck, Wien, Graz and Klagenfurt.

If you are interested in visiting one of our events go to the official website and register.

Published on Mar 1st, 2008 — Tags: , , ,
Comments (0)    digg it!    kick it