Monthly Archives: January 2009

[Talking games with Scott Bilas]

This show Einar is sitting down with Scott Bilas from Loose Cannon Studios and talks about game development in general. Scott has been in the gaming industry for a while and has worked on different titles. He is one of the developers behind the games shipped with Microsoft Windows Vista.

English
Download full MP3
Subscribe on iTunes

Notes
The intro and the outro music created by Kim M. Jensen.

Please do not hesitate to leave any comments on this post. If you have ideas for people you'd like to get interviewed, please leave a comment or contact me through the contact page.

Xna workshop at METU – Turkey

On the 9th of February till the 13th of February, I will be holding a workshop at Middle East Technical University for Microsoft Turkey. The workshop will focus on game programming with the use of Xna 3.0.

The workshop will be similar to the workshop I held last year, but with more focus on Xbox 360 development and more indepth.

After the workshop I will be posting the content and hopefully we’ll get it all on video and post that as well. Can’t wait to get down there and hold the workshop, it was really great doing it last year.

[Agile talk with Jon Aril Tørresdal]

I sit down with Jon Arild Tørresdal and talks about agile software development from his point of view in my first podcast show.

Norwegian
Download full MP3
Subscribe on iTunes

Notes
The intro and the outro music created by Kim M. Jensen.

Please do not hesitate to leave any comments on this post. If you have ideas for people you'd like to get interviewed, please leave a comment or contact me through the contact page.

[Agile talk with Jon Aril Tørresdal]

I sit down with Jon Arild Tørresdal and talks about agile software development from his point of view in my first podcast show.

Norwegian
Download full MP3
Subscribe on iTunes

Notes
The intro and the outro music created by Kim M. Jensen.

Please do not hesitate to leave any comments on this post. If you have ideas for people you'd like to get interviewed, please leave a comment or contact me through the contact page.

Silverlight Unit Test Runner for Resharper – January 2009 Update

UPDATE, 6th of May 2009: Project has been rewritten and put into another project, read more here.

 

I got some sparetime between all the family dinners during the christmas holidays and pretty much did a total rewrite of the Silverlight Unit Test Runner for Resharper.

The reason I had to go pretty drastic measures, was that the first version was closer to a proof of concept than production quality, and it also had a few flaws in it with regards to reporting results and also taking in input to the Silverlight part of the runner.

Anyways, the new and improved version can be downloaded here.

To install it, you need to have a Plugin folder in the Resharper bin directory, and within this a folder for the plugin, e.g. SlverlightUnitTest :

Once you have this in place, you need to unzip the file above. You'll now have a folder looking something like this:

The three DLLs you see in the folder need to go into the Global Assembly Cache. Simply open explorer and browse to c:WindowsAssembly and drag these files into this folder (do not move them, just normal drag'n'drop).

As you can see, there is also a WebSite folder inside the plugins directory. This is the website that everything is running in. The path for this will come handy when the plugin is first initialized. If it is the first time running the plugin after this upgrade, you'll get a dialog asking for the path for the WebSite for the Silverlight Unit Test Runner. The path of the WebSite above is the one it needs.

Simply click browse and select the path:

If by any chance you select a wrong path, or want to change the path, you can simply go to the registry and fix it by either removing the value or changing it yourself:

You should now be able to run your Silverlight Tests like any other test you've been running through the Resharper Unit Test Explorer.

Whats new
The entire architecture of the plugin has changed. The previous version relied on an Xml being outputed from the Silverlight application running into the enclosing HTML DOM. This is now changed to be using WCF services.
It will now run only the tests you have selected to run. These are sent as parameters into the plugin and forwarded to the Unit Test framework by Jeff Wilcox as tags.

How does it work
Instead of half-way trying to explain how it all works, a picture speaks more than a thousand words they say:


DependencyProperties – why art thou (so much hassle)?

 

UPDATE, 12th of July 2009: Full source with sample can be downloaded from the following post.

I've grown quite fond of WPF and Silverlight, and find the architecture behind both great. I love the notions of DependencyProperties and how these are implemented. The only thing I find a bit annoying, is how one declares them. I am not going to go into details how DependencyProperties or binding works, there is quite a few tutorials out there that covers that.

Lets say you have a ViewModel object, and on it you have a State property you wish to expose and make visible and bindable in Xaml:

[code:c#]
public class ViewModel
{
     public ViewState State { get; set; }
}
[/code]

DependencyProperty out of the box
In order for this to become a DependencyProperty and something we can bind against in Xaml, we have to do the following:

[code:c#]
public class ViewModel
{
    
public static readonly DependencyProperty StateProperty =
           DependencyProperty.Register("State",typeof(ViewState),typeof(ViewModel),null);
     public ViewState State
     {
         get { return (ViewState)this.GetValue(StateProperty); }
         set { this.SetValue(StateProperty,value); }
     }
}
[/code]

If you wanted to get notified if the property changed from databinding or similar, you would have to specify propertymetadata with a handler as the last argument for the Register method.
Its not too bad, but it is error-prone – there is a literal there specifying the name of the property. This has to match the actual name of the property. Hardly refactorable.

This alone made me want to do something about it. In addition, I wanted my properties to act as any other property I have on objects.  For instance, if a state change occured, I just wanted my set method on the State property to be called. This introduces a bit of a problem. Calling the SetValue() method causes a whole range of events to occur, if you have a binding expression attached to the dependency property, it causes the PropertyChanged event from the attached object to be decoupled. Needless to say, not a good solution.

What I've created for my project are 3 classes that can be used seperately or together.

DependencyPropertyHelper

[code:c#]
public static class DependencyPropertyHelper
{
    public static DependencyProperty Register<T, TResult>(Expression<Func<T, TResult>> expression)
    {
        return Register<T,TResult>(expression, null);
    }

    public static DependencyProperty Register<T, TResult>(Expression<Func<T, TResult>> expression, TResult defaultValue)
    {
        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;

        string dependencyPropertyName = propertyInfo.Name;

        DependencyProperty prop = DependencyProperty.Register(
            dependencyPropertyName,
            propertyInfo.PropertyType,
            typeof(T),
            new PropertyMetadata(defaultValue,(o, e) =>
                                                  {
                                                    Action a = ()=>propertyInfo.SetValue(o, e.NewValue, null);
                                                    if( o.Dispatcher.CheckAccess() )
                                                    {
                                                        a();
                                                    } else
                                                    {
                                                        o.Dispatcher.BeginInvoke(a);
                                                    }
                                                  }));
        return prop;
    }
}
[/code]

The helper have the assumption that any change callback should just set the property value directly.
With this helper, we can at least make our dependency properties refactorable:

[code:c#]
public class ViewModel
{
    
public static readonly DependencyProperty StateProperty =
           DependencyPropertyHelper.Register<ViewModel,ViewState>(o=>o.State);
     public ViewState State
     {
         get { return (ViewState)this.GetValue(StateProperty); }
         set { this.SetValue(StateProperty,value); }
     }
}
[/code]

But still, we have the problem with the SetValue() in the property. So we need a second helping hand to make it all tick. Introducing the DependencyPropertyExtensions class:

DependencyPropertyExtensions

[code:c#]
public static class DependencyPropertyExtensions
{
    public static void SetValue<T>(this DependencyObject obj, DependencyProperty property, T value)
    {
        object oldValue = obj.GetValue(property);
        if (null != oldValue && null != value)
        {
            if (oldValue.Equals(value))
            {
                return;
            }
        }
        obj.SetValue(property,value);
    }

    public static T GetValue<T>(this DependencyObject obj, DependencyProperty property)
    {
        return (T)obj.GetValue(property);
    }
}
[/code]

With this in place, we can do the following:

[code:c#]
public class ViewModel
{
    
public static readonly DependencyProperty StateProperty =
           DependencyPropertyHelper.Register<ViewModel,ViewState>(o=>o.State);
     public ViewState State
     {
         get { return this.GetValue<ViewState>(StateProperty); }
         set { this.SetValue<ViewState>(StateProperty,value); }
     }
}
[/code]

Our code will now work as planned, and we can start putting any logic we want in the set method.

TypeSafeDependencyProperty
Still, it could get better than this.
The DependencyProperty class can live anywhere, so we can actually wrap it all up in a new class that utilizes the other two classes:

[code:c#]
public class TypeSafeDependencyProperty<T1,T>
{
    private readonly DependencyProperty _dependencyProperty;

    private TypeSafeDependencyProperty(DependencyProperty dependencyProperty)
    {
        this._dependencyProperty = dependencyProperty;
    }

    public T GetValue(DependencyObject obj)
    {
        return obj.GetValue<T>(this._dependencyProperty);
    }

    public void SetValue(DependencyObject obj, T value)
    {
        obj.SetValue<T>(this._dependencyProperty,value);

    }

    public static TypeSafeDependencyProperty<T1,T> Register(Expression<Func<T1, T>> expression)
    {
        var property = DependencyPropertyHelper.Register<T1,T>(expression);

        var typeSafeProperty = new TypeSafeDependencyProperty<T1,T>(property);

        return typeSafeProperty;
    }

    public static TypeSafeDependencyProperty<T1,T> Register(Expression<Func<T1, T>> expression, T defaultValue)
    {
        var property = DependencyPropertyHelper.Register<T1, T>(expression,defaultValue);

        var typeSafeProperty = new TypeSafeDependencyProperty<T1, T>(property);

        return typeSafeProperty;
    }
}
[/code]

Our property can then be implemented as follows:
[code:c#]
public class ViewModel
{
    
public static readonly TypeSafeDependencyProperty<ViewModel,ViewState> StateProperty =
           TypeSafeDependencyProperty.Register<ViewModel,ViewState>(o=>o.State);
     public ViewState State
     {
         get { return StateProperty.GetValue(this); }
         set { StateProperty.SetValue(this,value); }
     }
}
[/code]

Conclusion
Code quality is a subject that I think is really important. In many of the APIs introduced by Microsoft, there is room for throwing code quality out the window. DependencyProperties and PropertyChanged on INotifyPropertyChanged interface are two things that open up for trouble – in my opinion. By using literals for code elements is a thing that I find to be really bad. If you were to rename the property and forget to rename the literal, you can end up debugging for hours. In Silverlight, the mismatch between the two does not cause any obvious exceptions. But, as shown above, they are relatively easy to wrap and make safe(r).

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:
[code:c#]
ThreadStart threadStart = new ThreadStart(
      delegate()
            {
                  Console.WriteLine("Hello from thread #2");
            }));
Thread thread = new Thread(threadStart);
thread.Start()
[/code]

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:

[code:c#]
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();
}
 
[/code]

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:
[code:c#]
var thread = new Thread(
      () => Console.WriteLine("Hello from thread #2"));
thread.Start();
[/code]

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:

[code:c#]
var employees = new List<Employee>();

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

query.ToArray();
[/code]

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.

Another Norwegian MVP

Today, a fellow NNUG community worker; Lars Wilhelmsen got awarded MVP for the Connected Systems Developer product group.

This is great for the Norwegian community.  Congratulations!