.net, 3D, Balder, C#, Game Development, WPF

Balder gets declarative

We're getting closer to the BETA mark for Balder, and we're starting to get most of the features we want in for version 1 ready. The latest feature is the ability to declaratively through Xaml get Balder up and running. Current release is versioned 0.8.7 and can be found over at the Balder page at Codeplex.

By adding the following namespace declaration in your Xaml file:

[code:c#]xmlns:Core="clr-namespace:Balder.Core;assembly=Balder.Core.Silverlight"[/code]

You now get a set of extra controls that can be used.

First off is the RenderingContainer:

[code:c#]
<balder:RenderingContainer x:Name="_renderingContainer" Width="800" Height="600" BackgroundColor="Black"/> 
[/code]

You need to specify the Width and Height, as that is used to setup the display properly. The BackgroundColor property can be any color, including transparent – which is great if you want to mix with existing Silverlight controls on your page. 

The next control we've added is the Mesh control, it enables you to add any Mesh from a file/resource to the RenderingContainer. You do this by accessing the Nodes property on the Container and putting up a RenderedNodeCollection and put your Mesh(es) within that.

[code:c#]
<balder:RenderingContainer.Nodes>
       <balder:RenderedNodeCollection>
             <balder:Mesh x:Name="_audi" AssetName="audi.ASE"/>
        </balder:RenderedNodeCollection>
</balder:RenderingContainer.Nodes>
[/code]

For now, there is a limited amount of DependencyProperties exposed, so manipulation via Storyboards aren't possible today, but will be very soon. The only way to access this is by hooking up the Updated event on the RenderingContainer and implement codebehind logic for it, something like this:

[code:c#]
private float _angle = 0f;

private void Updated(RenderingContainer renderingContainer)
{
    _audi.Node.World = Matrix.CreateRotationY(_angle);
    _angle += 0.5f;
    _renderingContainer.Camera.Position = new Vector(0,-5,-20);
}
[/code]

Last but not least, to get it all working, you need to initialize Balder. In your App.xaml.cs file, during the Application_Startup event, you need to add one line of code. It is very important for now that you add that line before your page (RootVisual) is created and set.

[code:c#]
  private void Application_Startup(object sender, StartupEventArgs e)
  {
   TargetDevice.Initialize();
   RootVisual = new Page();
  }
[/code]

I you want to use it the "conventional" way – non Xaml based, you need to add a similar line of code, but that line of code needs to be added after the page has been created. This is something that makes absolutely no sense and is something we're trying to fix and make it a lot more sense. Our goal is to get rid of that line of code all together.

A little note, we're not trying to mimick the WPF 3D namespaces at all, we're going our own direction. We don't feel the urge to replicate those, as the purpose of Balder is very different. 

Standard
.net, WPF

MSDN Live – fall 2009

Microsoft Norway has a tradition for hosting 2 MSDN Live events every year, one in the spring timeframe and one in the fall. This year they're having it in Stavanger, Bergen, Trondheim and Oslo.

The tour is kicked off in Stavanger on the 16th of September and is then moved on to Bergen on the 22nd and then Trondheim on the 24th, then concluding in Oslo on the 29th. This time around I will be part of the tour, which I'm really looking forward to.

 

Content
Later this year Microsoft will be releasing a whole bunch of new technologies and products, and MSDN Live this time around will focus on these new technologies and how you can take advantage of them and what they will mean for you as a developer. The sessions will be on .net 4 + C#4, ASP.net 4, WPF 4 and Silverlight 3 (released earlier this year).

Speakers
Børge Hansen, also part of the last tour and did a great job then, he will not disappoint anyone this time around either. He will kick off everything with an introduction to Visual Studio 2010, .net 4 and C# 4.

Fredrik Kalseth, an ex-colleague of mine will focus on ASP.net 4. He is truely the one to show you new stuff in ASP.net 4, great developer and speaker!

Myself; I will be doing a talk about WPF 4 and Silverlight 3.

 

This tour will not have any Microsoft speakers, all independent content, custom created for the tour.

 

What are you waiting for?
There really aren't any excuses for not joining this great tour. Great content. Sign up here now. 🙂

Standard
.net, General, WPF

Problem installing programs after installing Visual Studio 2010 beta1?

I'm working on a WPF 4 project, targetting .net 4 and need to use Visual Studio 2010 beta1 for this. For now I've been handcoding all my Xaml (I know, the designer in VS2010 is quite good – but I kinda love doing Xaml), but I wanted to do some more advanced graphics and I am somewhat used to working with Blend for doing that. So I decided to download the Blend 3 Trial and get going. Only thing was that the installer kept saying "Another installation is in progress. You must complete that installation before continuing this one". I downloaded the Windows Installer Cleanup Utility , but it didn't solve anything. In fact, I couldn't install it even, since it was a Windows Installer, had to install it on another computer and copy the files. Tongue out

The event viewer was referring to the 'VSTA_IDE_12590_x86_enu' component and a missing directory. This is a package installed by Visual Studio, called Microsoft Visual Studio for Applications 2.0. 

Turns out, the solution is really simple. Just create the directory and try installing again, in my case I had to reboot and then do the installation of Blend. 

And, by the way, if you want to open your project in Blend 3, you need to change the target framework to something that Blend recognize, 3.5 or less. Read more over at Charles Sterling's blog.For me, I must maintain a seperate .net 3.5 project for my frontend for working with Blend as I am targetting .net 4.

 

Standard
.net, C#, WPF

Extensions and Helpers for Silverlight and WPF

Earlier I posted about some extensions I did for Silverlight handling INotifyPropertyChanged and helpers for DependencyProperties. Recently I've had a couple of request to release a downloadable source with samples of their use. Since the original posts (found here and here), I've refined them a little bit and worked out some quirks that was left in the originals.

So, why should one use these kind of extensions and what do they solve?

INotifyPropertyChanged and creating DependencyProperties rely on the usage of literals. When for instance notifying the PropertyChanged event with a change on a particular property, the argument one passes in is the literal holding the name of the property. This is bad for at least a couple of reasons:

  • Refactoring goes out the window – renaming the property means renaming the literals by hand
  • Obfuscation – if one were to obfuscate the code, literals will still stay the same but your propertynames will change – your code is broken

I've wrapped it all in a nice download with both a Silverlight and a WPF version of the code (actually pretty much the same code, you'll find #if(SILVERLIGHT) #else #endif statements where specifics are needed). Also in the download, you'll find a Silverlight sample with a usercontrol implementing a dependencyproperty and a data object using the INotifyPropertyChanged extensions. In addition to this, there are a few other nifty helper classes and extensions for other aspects of both Silverlight and WPF development. Hope you'll find it handy.

The download can be found here.

Standard
.net, C#, WPF

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).

Standard
.net, C#, CLR, WPF

INotifyPropertyChanged revisited

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

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 :

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

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.

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

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.
 
[code:c#]

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);

       }

    }

}

[/code]

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.

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

 

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

[code:c#]
myObject.SubscripeToChange(()=>myObject.SomeProperty,SomeProperty_Changed);
[/code]

 And then your handler would look like this:

[code:c#]
private void SomeProperty_Changed(MyObject myObject)
{
    /* … implement something here */
}
[/code]
Standard