Archive

Posts Tagged ‘MVVM’

Frameworks used inside my WP7 application

August 19, 2011 2 comments

A couple of days ago, I have released the first version of my free open source WP7 application “Cloud Fox” to the windows phone market place. It allows Windows Phone 7 users to synchronize their FireFox bookmarks, history and open tabs with their mobile phone.

Developing it was a fun and interesting exercise. I was able to use some of the best .Net open source frameworks available. They allowed me to reduce the development time and they helped me improving the overall quality and user experience.

I wrote this article because I want to share these frameworks with fellow WP7 developers:

  • MVVM Light: One of the best MVVM frameworks available.
  • JSON.Net: Makes parsing JSON data very easy and it is much more standard-compliant then the Microsoft JSON parser.
  • Silverlight Toolkit for Windows Phone: Offers a lot of high quality Silverlight controls. I used the ToggleSwitch implementation.
  • Coding4Fun Windows Phone Toolkit: For the ToastPrompt control.
  • Prism: For the ApplicationBarButtonCommand component, allowing me to bind commands to the application bar buttons
  • Ninject: For gluing everything together 🙂

And a special thanks to NuGet; it made downloading and installing .Net libraries super easy.

Which .Net frameworks are you using for WP7 development? I’d love to know them! 🙂

Dynamically adding RaisePropertyChanged to MVVM Light ViewModels using Microsoft Unity

July 28, 2011 3 comments

Introduction

In the past, I already wrote two articles about dynamically adding RaisePropertyChanged support to view models. Today, I will explain how this can be accomplished with the IoC container: Microsoft Unity. Unity has out of the box support for AOP. Using Unity is much easier than my two previous do-it-yourselves ways. For real applications, I recommend using Unity or similar frameworks!

Like in my previous articles, I want to write view models using the following code pattern:

[RaisePropertyChanged]
public virtual string SomeProperty { get; set; }

Instead of the standard pattern:

private string someProperty;

public string SomeProperty
{
    get
    {
        return someProperty;
    }
    set
    {
        someProperty = value;
        RaisePropertyChanged("SomeProperty");
    }
}

Implementation

In order to get started, the first thing we have to do is install both Unity and MVVM Light. To do this, I recommend using Nuget. In the official Nuget repository, Unity is split into two packages. For the AOP support, both packages need to be added to the Visual Studio project.

nuget_Unity

Now that we have all the required libraries, we can start coding. First, lets define our RaisePropertyChangedAttribute class.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class RaisePropertyChangedAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(IUnityContainer container)
    {
        return new RaisePropertyChangedCallHandler();
    }
}

Because we want Unity to intercept calls, we must extend our attribute from HandlerAttribute. A custom HandlerAttribute must create and return a custom ICallHandler instance. We will return an instance of our custom RaisePropertyChangedCallHandler that we will create next.

Before writing our ICallHander, we must first look at the MSIL code generated by the C# compiler in order to understand .Net properties better. When a property is defined, 2 hidden methods are automatically created by the compiler; a get method and a set method. These methods have by default the name get_<property name> and set_<property name>.

Ildasm_property

With this knowledge in mind, the custom ICallHandler implementation is straightforward. We ask Unity to call the original set method and after its invocation we extract the name of property out of the name of the set method and we invoke the RaisePropertyChanged method of MVVM Light using reflection.

class RaisePropertyChangedCallHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        IMethodReturn methodReturn = getNext()(input, getNext);

        string propertyName = input.MethodBase.Name.Substring(4);

        MethodInfo raisePropertyChangedMethod = input.Target.GetType().GetMethod("RaisePropertyChanged",
            BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] {typeof(string)}, null);
        raisePropertyChangedMethod.Invoke(input.Target, new object[] { propertyName });

        return methodReturn;
    }

    public int Order { get; set; }
}

Configuring Unity

All that now remains is configuring Unity for our view model and activating virtual method AOP support for it. In code, we can define this using the following code sample:

IUnityContainer container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<SampleViewModel>().
    Configure<Interception>().
    SetInterceptorFor<SampleViewModel>(new VirtualMethodInterceptor());

If we now use Unity for creating instances of our sample view model class, all the properties annotated with “RaisePropertyChanged” will atomically be “property change”-aware.

SampleViewModel vm = container.Resolve<SampleViewModel>();

Please note: This will not work in Silverlight, because of limitations in its runtime. (Silverlight does not allow the invocation of private methods using reflection for security reasons)

Categories: C#, IoC, MVVM, WPF Tags: , , , ,

Dynamically adding RaisePropertyChanged to MVVM Light ViewModels using Reflection.Emit

July 8, 2011 10 comments

Introduction

I like the clean separation between views and view models made possible by the MVVM pattern. But I don’t like the code pattern required to implement RaisePropertyChanged in simple properties.

private static string someProperty;

public string SomeProperty
{
    get
    {
        return someProperty;
    }
    set
    {
        someProperty = value;
        RaisePropertyChanged("SomeProperty");
    }
}

I would prefer an implementation like this:

[RaisePropertyChanged]
public string SomeProperty { get; set; }

Implementing this is possible with a principle called AOP (Aspect Oriented Programming). Although C# is an OOP (Object Oriented Programming) language, various people and companies have made AOP in C# easily possible. As I am a passionate technologist, I off course wanted to understand how this “magic” works Glimlach.

Two options are possible: post compilation by modifying the compiled assemblies or dynamic creation of proxy classes at runtime. In this article, I will present how you can implement this yourself. But because various high quality tools and frameworks are available, I recommend not to implement this yourself for production code.

Post compilation can be done by an AOP tool like PostSharp. Dynamic proxy creation is done by libraries such as Castle DynamicProxy or by IOC containers like Microsoft Unity.

Dynamic proxy Creation

I have chose to use dynamic proxy creation in my example. I will not make my code generic, but instead I will hardcode the required functionality. I assume that you will be capable of generalizing this yourself, if required. The code relies on MVVM Light, but you could replace this library with any other MVVM library.

The API that allows this dynamic behavior is Reflection.Emit and it allows you to create classes at runtime using MSIL code. MSIL is the assembly of the .Net CLR. Most .Net programmers have probably never seen this language. By using a smart trick, only a limited knowledge is required.

Microsoft has an MSIL disassembler called “ILDASM”. You can use this tool easily if you launch it from the “Visual Studio 2010 command prompt”. To know the required MSIL code for our prototype, we first create what we want in c#, compile it and then look at the generated MSIL code with ILDASM.

The proxy we want to create dynamically (SampleViewModelExtended) looks like:

// Dynamic proxy created manually
public class SampleViewModelExtended : SampleViewModel
{
    public override string SomeProperty
    {
        get
        {
            return base.SomeProperty;
        }
        set
        {
            base.SomeProperty = value;
            RaisePropertyChanged("SomeProperty");
        }
    }
}

public class SampleViewModel : ViewModelBase
{
    [RaisePropertyChanged]
    public virtual string SomeProperty { get; set; }
}

Please note: we have to make the properties virtual in the base class, because otherwise we cannot overwrite the setters in the derived class.

If we compile this and look at the MSIL, we get:

ILDASM_required_MSIL_code

Having the required MSIL code, the only thing we now have to do is generating the MSIL dynamically using Reflection.Emit.

public static class ReflectionEmitViewModelFactory
{
    public static T CreateInstance<T>()
        where T : ViewModelBase
    {
        Type vmType = typeof(T);

        VerifyViewModelType(vmType);

        // Create everything required to get a module builder
        AssemblyName assemblyName = new AssemblyName("SmartViewModelDynamicAssembly");
        AppDomain domain = AppDomain.CurrentDomain;
        AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            //AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

        string dynamicTypeName = Assembly.CreateQualifiedName(vmType.AssemblyQualifiedName, "Smart" + vmType.Name);

        TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicTypeName,
            TypeAttributes.Public | TypeAttributes.Class, vmType);

        MethodInfo raisePropertyChangedMethod = typeof(ViewModelBase).GetMethod("RaisePropertyChanged",
            BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string) }, null);

        foreach (PropertyInfo propertyInfo in FindNotifyPropertyChangCandidates<T>())
            UpdateProperty(propertyInfo, typeBuilder, raisePropertyChangedMethod);

        Type dynamicType = typeBuilder.CreateType();

        return (T)Activator.CreateInstance(dynamicType);
    }

    private static void VerifyViewModelType(Type vmType)
    {
        if (vmType.IsSealed)
            throw new InvalidOperationException("The specified view model type is not allowed to be sealed.");
    }

    private static IEnumerable<PropertyInfo> FindNotifyPropertyChangCandidates<T>()
    {
        return from p in typeof(T).GetProperties()
                where p.GetSetMethod() != null && p.GetSetMethod().IsVirtual &&
                p.GetCustomAttributes(typeof(RaisePropertyChangedAttribute), false).Length > 0
                select p;
    }

    private static void UpdateProperty(PropertyInfo propertyInfo, TypeBuilder typeBuilder,
        MethodInfo raisePropertyChangedMethod)
    {
        // Update the setter of the class
        PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyInfo.Name,
            PropertyAttributes.None, propertyInfo.PropertyType, null);

        // Create set method
        MethodBuilder builder = typeBuilder.DefineMethod("set_" + propertyInfo.Name,
            MethodAttributes.Public | MethodAttributes.Virtual, null, new Type[] { propertyInfo.PropertyType });
        builder.DefineParameter(1, ParameterAttributes.None, "value");
        ILGenerator generator = builder.GetILGenerator();

        // Add IL code for set method
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Ldarg_1);
        generator.Emit(OpCodes.Call, propertyInfo.GetSetMethod());

        // Call property changed for object
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Ldstr, propertyInfo.Name);
        generator.Emit(OpCodes.Callvirt, raisePropertyChangedMethod);
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ret);
        propertyBuilder.SetSetMethod(builder);
    }
}

Once you know the MSIL to generate, using Reflection.Emit is very straightforward. By using the sample code provided above, we can know create dynamic ViewsModels very easy:

SampleViewModel viewModel = ReflectionEmitViewModelFactory.CreateInstance<SampleViewModel>();