Home

Why compiler extensions shouldn't be scary

I've been blogging previously about how compiler extensions could solve a bunch of issues and how compiler extensions would just represent just another framework.

The reactions to the concept are mixed. Mostly it raises a lot of feelings to the surface. We as developers are really truely attached to our favourite programming language, and we also tend to be really loyal as well. That said and lets get to the point; when we're looking at the evolution of C# for instance, the path Microsoft has taken surely looks a lot like they are writing compiler extensions to solve the issues they want solved.

Anonymous delegates for instance, they are nothing but compiler magic.
Take the following sample:

ThreadStart threadStart = new ThreadStart(
      delegate()
            {
                  Console.WriteLine("Hello from thread #2");
            }));
Thread thread = new Thread(threadStart);
thread.Start()



If we open the compiled binary in a program like Reflector and take look at what the compiler has actually done:



The compiler generates a method called <Main>b_0() that has the content of the anonymous delegate:

If we set the optimization option i reflector to .net 1.0, we can see the content of the Main() method and what it is actually doing:

private static void Main(string[] args)
{
    ThreadStart threadStart = (CS$<>9__CachedAnonymousMethodDelegate1 != null) ? CS$<>9__CachedAnonymousMethodDelegate1 : (CS$<>9__CachedAnonymousMethodDelegate1 = new ThreadStart(Program.<Main>b__0));
    new Thread(threadStart).Start();
}




This is just one of many "compiler extensions" Microsoft has up their sleeve themselves. With C# 3.0, Microsoft introduced quite a bit of new language constructs. var, extension methods, Lambda, LINQ, anonymous methods - to name a few. All these features are built upon the .net 2.0 CLR and does not introduce anything new to the runtime, which means that they are all just compile-time magic.

Taking the above sample and making it more C# 3.0:

var thread = new Thread(
      () => Console.WriteLine("Hello from thread #2"));
thread.Start();



We take use of the var keyword and lambdas and the code looks a lot better. But opening this in Reflector, targetting CLR 2.0, you'll see what really goes on:



The var keyword is replaced with the actual type, as expected and the lambda expression is expanded to a delegate as expected.

LINQ takes the rewrite to the extreme, consider the following C# 3.0 code:

var employees = new List<Employee>();

var query = from e in employees
                  where e.FirstName.StartsWith("A")
                  select e;

query.ToArray();



The expanded version looks like this:

It expands the LINQ into using the fluent interfaces defined for LINQ.


So, where am I going with this. You probably already knew all this. Well, my point is; if Microsoft themselves are pretty much doing compiler extensions today, I do not see why we shouldn't. It is not as scary as one would first think. Compiler extensions could solve a bunch of domain specific problems one is facing and if one did the extensibility correctly, all extensions written would act as just another framework.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: .net | C#
Post Information: Permalink | Comments (4) | Post RSSRSS comment feed

INotifyPropertyChanged revisited

A recurring annoyance with me and quite a few other developers, is the way notification of changes from for instance your domain model to the UI should be handled in environments such as WPF or Silverlight.

The environments are heavily relying on the objects implementing INotifyPropertyChanged and hooks up to the event PropertyChanged to be notified about any changes in any properties.

This works out fine, with the exception of we as developers have to plumb in this code in all our objects.
Normally you would write something like :

public class Employee : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _firstName;
    public string FirstName
    {
       get { return this._firstName; }
       set
       {
          this._firstName = value;
          this.OnPropertyChanged("FirstName");
       }
    }

    private void OnPropertyChanged(string propertyName)
    {
        if( null != this.PropertyChanged )
        {
           this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}



One can easily see that the above code can become quite boring to write over and over again. A solution could be to put the frequently used bits in a base class for all your objects. But this steals inheritance.

Another thing that bothers me with the whole INotifyPropertyChanged concept is the fact that I will be having my code filled up with literals that will not give any compiler errors if they contain typos, nor will they be subject to any renaming of properties as part of refactoring.

In my search for a better way of doing this I came across quite a few ways of trying to simplify it. The best one I came across involved using Lambda expressions to express the property that was changed and thus fixing the latter problem with renaming/refactoring. But as far as Google took me, I couldn't find anything that didn't involved switching to an extensible language like Boo or similar to really tackle the problem more elegantly. But my quest couldn't end there.

I started playing again with the problem a bit today and came up with a solution that I think is quite elegant. It involves Lambda expressions, extension methods and reflection. My three favourite things in C# and CLR these days. :)

Update: 16th of December 2008, thanks to Miguel Madero for pointing out the problem with value types.

public static class NotificationExtensions
    {
        public static void Notify(this PropertyChangedEventHandler eventHandler, Expression<Func<object>> expression)
        {
            if( null == eventHandler )
            {
                return;
            }
            var lambda = expression as LambdaExpression;
            MemberExpression memberExpression;
            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = lambda.Body as UnaryExpression;
                memberExpression = unaryExpression.Operand as MemberExpression;
            }
            else
            {
                memberExpression = lambda.Body as MemberExpression;
            }
            var constantExpression = memberExpression.Expression as ConstantExpression;
            var propertyInfo = memberExpression.Member as PropertyInfo;
            
            foreach (var del in eventHandler.GetInvocationList())
            {
                del.DynamicInvoke(new object[] {constantExpression.Value, new PropertyChangedEventArgs(propertyInfo.Name)});
            }
        }
   }



When having the extension method above within reach, you will get the Notify() extension method for the PropertyChanged event in your class. The usage is then very simple. Lets revisit our Employee class again.
 

public class Employee : INotifyPropertyChanged

{

    public event PropertyChangedEventHandler PropertyChanged;



    private string _firstName;

    public string FirstName

    {

       get { return this._firstName; }

       set

       {

          this._firstName = value;

          this.PropertyChanged.Notify(()=>this.FirstName);

       }

    }

}




This is a highly reusable and pretty compact technique, and if you're not like me and aren't all that agressive with putting "this." all over the place, it will be even more compact. :)

Update, 16th of December 2008:

Since my original post, I also added a SubscribeToChange() extension method. The reason for this is pretty much that I literally don't like literals and wanted to have the ability to subscribe to changes for a specific property.

public static void SubscribeToChange<T>(this T objectThatNotifies, Expression<Func<object>> expression, PropertyChangedEventHandler<T> handler)
            where T : INotifyPropertyChanged
        {
            objectThatNotifies.PropertyChanged +=
                (s, e) =>
                    {
                        var lambda = expression as LambdaExpression;
                        MemberExpression memberExpression;
                        if (lambda.Body is UnaryExpression)
                        {
                            var unaryExpression = lambda.Body as UnaryExpression;
                            memberExpression = unaryExpression.Operand as MemberExpression;
                        }
                        else
                        {
                            memberExpression = lambda.Body as MemberExpression;
                        }
                        var propertyInfo = memberExpression.Member as PropertyInfo;

                        if(e.PropertyName.Equals(propertyInfo.Name))
                        {
                            handler(objectThatNotifies);
                        }
                    };
        }

 

The above code extends classes that implements INotifyPropertyChanged and gives you a syntax like  follows for subscribing to events:

myObject.SubscripeToChange(()=>myObject.SomeProperty,SomeProperty_Changed);

 And then your handler would look like this:

private void SomeProperty_Changed(MyObject myObject)
{
    /* ... implement something here */
}

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: .net | C# | CLR | Silverlight | WPF
Post Information: Permalink | Comments (7) | Post RSSRSS comment feed

Getting the current process filename on Windows Mobile

I´ve been working freelance on a Windows Mobile project for a client and for the project we wanted to have the application update itself over the internet and wanted the same experience one gets with ClickOnce on Windows and a simple API for any Mobile based application for handling updates and such.

In order for this to work I needed to have a seperate executable/entrypoint that was our update service running in the background handling all the gritty bits, this would then spawn the application. Because of a rather bad user experience having to start a different process than the one actually needed, I decided to have our update service installed with some registry entries to point out where it was installed and add an initialization method for our update service for the application to call. Anywho, long story short - I needed a way to figure out what process was running on the device and the filename of it to distinguish in which context the initialization was called.

Normally one would go about doing this by calling Assembly.GetEntryAssembly() - but the compact framewok does not have this method. Other ways are to go and call Assembly.GetCallingAssembly().GetModules()[0] and get the fully qualified name from there, but this didn´t work out in all conditions either. The solution is to p/invoke the GetModuleFileName() method from coredll - turns out it exists, even if the documentation does not list Windows Mobile in the supported platform section.. :)


Parallels DesktopScreenSnapz003.png

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: .net | C# | Mobile
Post Information: Permalink | Comments (3) | Post RSSRSS comment feed

Game Camp September Event - Registration now open

26th of September we´re holding our third Game Camp event. This time around we´re going across 2 simultaneous tracks. We´ve got a lot of exciting stuff for you, and as always; IT´S FREE.

Scott Bilas is coming to do the keynote and a session as well. Scott has worked on a lot of tripple A games for numerous companies (Sierra Online, Oberon Media, Gas Powered Games). He has had a few talks at the Games Developers Conference and is a strong believer in creating games in a managed environment such as the .net CLR and utilizing Xna. In addition FunCom is coming to talk about their experience in developing Age of Conan. The agenda is so great, you´ve gotta go and read to not miss out. Most game companies in Norway are attending with speakers. This will be our best event yet!

Registration is now open, don´t hesitate to register and show up at this great event.

Read the agenda and register here. And remember to spread the word.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: XNA | C# | Game Development
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Silverlight 2 - texturemapping

I’ve been quite busy the last week working on the Balder engine. I’ve focused my energy on improving the rendering pipeline, both for functionality and speed and have managed to overhaul it quite a bit. In addition, texturemapping is becoming a fact. Thanks to Whizzkid for pointing out problems that was in the Matrix class in version 1.1 that was now fixed and to this article by Florian Kruesch

You can have a look at a very crude sample here with a lot of bugs in it due to heavy refactoring. I’ve decreased the framerate of the sample by purpose, I’ll be working to improve the samples as well as improving the engine and its features the next couple of weeks. All sourcecode will as always be checked in and available at the Balder Codeplex project.

image

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: .net | C# | Silverlight
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

SlotMachine for Silverlight 2 beta 2

Finally managed to fix the 2D parts of the Balder engine and also the SlotMachine game I entered the European Silverlight Challenge with earlier. There are so many breaking changes between the versions of Silverlight that I see now that I need to rewrite quite a bit of my projects. You can find the game here.

image

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: C# | Silverlight
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Silverlight 3D Engine : Balder – Finally up and running on SL 2 Beta 2

I’ve been swamped with work the last 6 months and haven’t had time to do any Silverlight stuff, but now I’m bouncing back and have started to get all my projects up and running again on SL 2 Beta 2.

First off is the 3D engine I started on last year; Balder. I’ve got a couple of issues I need to solve, but it is basically working again, have a look here. You might find quite jerky at the moment, I need to alter the entire rendering pipeline as it was originally optimized for Silverlight 1.1 back in the days :). Quite a lot of water has gone under the bridge since then.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: C# | Silverlight
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

2D Animation Content Pipeline

During my stay in Turkey for the Xna workshop I created a simple content importer that makes it easier to work with 2D animations. Very often you see people use spritesheets as the solution for animating 2D, which is of course not a bad way, it is a very optimal way to do things. I’ve always liked the simplicity of working with single frames, at least while I’m working on a solution, that way I can easily change stuff around. The content importer I created works with a simple Xml file (in fact just a serialized version of an object called SpriteAnimation), in this Xml file you can specify a base assetname as a format string, and you specify how many frames there are in the animation. The assetname must include the asset path as well.

The SpriteAnimation class is the one to use, it is also found in the content pipeline project, not exactly best practice. But it works for the demonstration purpose it was intended. :)

Using it is very simple:

image

In your draw method call the animations draw method with the spritebatch to draw into.

image

You can dowload the project from here.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: XNA | C#
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

Chief Consultant in Objectware

After some 6 and a half years working at the same job (Notus, acquired by Visma this year), I’ve just signed a contract with Objectware a part of the Itera Consulting Group. I will start there on the 1st of September this year.

Some of you might have noticed a comment on one of my latest posts; congratulating me on my new job, way before it was ready to be announced to the world. :) Well, the cat is out of the bag.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: .net | C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Xna Workshop, Ankara, Turkey – some pictures

Here are some of the pictures from the workshop we held in Turkey. Click the images to see larger versions.

We started on Tuesday with a 2 hour presentation (30 minutes) and live coding (90 minutes).

Below you see all the people involved for the workshop; students, METU staff, Microsoft staff and myself. The students got diplomas for attending, signed by me. I even had to hand them out and called out their names in the best Turkish-dialect my vocal-cords could come up with. :)

We divided all the students into groups that would work together to create a game each. Below you see the winning team. All the students voted for which game they liked the best and we had a tie between two teams. The students wanted me to vote as well between the two and the result was the team below (sorry for the other team – your golf game with PhysX was great!! It was a tough call!).

Below you’ll see me assisting one of the developers on one of the teams; I’m trying to figure out a problem with a struct for a bullet system. The bullets didn’t want to move, for some strange reason…   We figured it out eventually, but couldn’t exactly tell what was wrong or not…

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Categories: XNA | C#
Post Information: Permalink | Comments (4) | Post RSSRSS comment feed