Silverlight 4 Runs Natively in .NET

by Justin Chase 1. March 2010 09:04

This is a big deal.

I just learned this the other day and found surprisingly little information about it online. It was announced at PDC so it’s not a secret but it seems like a big deal to me. The feature is otherwise known as “assembly portability”.

When doing Silverlight one of the most frustrating things currently is the inability to run unit tests out of browser. This results in a break in continuous integration and a frustrating manual step in your testing process. Well no more!

This is only the beginning of the implications however. If you’re writing any application with a business logical layer, you should probably be writing it in Silverlight exclusively now. No more duplicating projects and creating linked file references. You can literally just create one project, compile it, and run it in both runtimes. Incredible.

Of course there are some limitations. But in this case I almost feel like the limitations are actually benefits. The thing is, you are likely to have features in one environment that are different or inaccessible in another. For example, file system access. In .net if you’re easily accessing the file system, but you might not be able to access it directly in Silverlight in the same way.

Enter System.ComponentModel.Composition. Otherwise known as MEF. By making your application logic composable you can solve all of the problems of framework differences and make your project imminently unit test friendly and better in general (if you buy into the principals of IoC at least).

For example, in Silverlight you cannot get a FileStream directly, you must make a call to OpenFileDialog which will give you the FileStream, if a user allows it. This is all well and good but when running in .net or unit tests you may want to allow it to access the file system directly or give it a mock stream instead. The solution is to make your calls to retrieve streams composable (otherwise known as dependency injection). Create a service interface, and create service instances for different environments.

For example, suppose you have the following (contrived) method in a Silverlight class:

public void DoWork()
{
    var dto = new SimpleDTO { Id = 100, Foo = "Hello World!" };

    Stream stream = Open();
    Save(stream, dto);

    stream = Open();
    dto = Load<SimpleDTO>(stream);

    Console.WriteLine("{0} : {1}", dto.Id, dto.Foo);
}

The process of opening a stream in Silverlight is different from the way it must be done when running in .net. So we make it composable.

public Stream Open()
{
    var stateService = container.GetExport<IStateService>().Value;
    stateService.State.Seek(0, SeekOrigin.Begin);
    return stateService.State;
}

Instead of opening the stream ourselves we import an exported service via MEF, that does know how to do it. To do this we simply need to have access to a container.

private CompositionContainer container;

public ComposableObject(CompositionContainer container)
{
    this.container = container;
}

Our constructor accepts a CompositionContainer as a parameter, which gives us access to all of the composable parts configured for our runtime. Keep in mind this is all Silverlight code at this point. And here is the IStateService.

public interface IStateService : IDisposable
{
    Stream State { get; }
}

The following code snippets are plain-old-dot-net-console-application snippets. First off, here is a snapshot of my solution explorer so you can see how things are structured.

image

You can see that I have created a reference from a Console Application project directly to a Silverlight 4 Class Library project. Visual Studio gives me a yellow banger, presumably because of the framework differences but it builds just fine. My program loads and calls my Silverlight library just this easily:

using SilverlightClassLibrary1;
class Program
{
    static void Main(string[] args)
    {
        var assembly = new AssemblyCatalog(typeof(Program).Assembly);
        using (var container = new CompositionContainer(assembly))
        {
            var co = new ComposableObject(container);
            co.DoWork();
        }

        Console.ReadKey(true);
    }
}

The bits at the beginning are creating a CompositionContainer using the current assembly. MEF allows you to load containers from all sorts of sources however, including entire directores full of Assemblies so you can have an easy add-in system. The ComposableObject is the one defined in my Silverlight Assembly! No interop nastiness, no AppDomain hassles, it just loads the dll as if it were true .NET code!

Next all I have to do is create an instance of the IStateService and export it.

[Export(typeof(IStateService))]
public class ParallelProcessingService : IStateService
{
    private Stream state;

    public Stream State
    {
        get
        {
            if (state == null)
                state = File.Create("state.dat");
            return state;
        }
    }

    public void Dispose()
    {
        if (state != null)
            state.Dispose();
    }
}

Now when I run this application, my Silverlight code will use MEF to load an Exported IStateService instance for me. Running this code will the access the FileSystem directly even though I’m running a Silverlight class library.

So what you should do is to create a Class Library with all of your logic, composed in a similar fashion as the above. Then in your Silverlight Application you simply implement and Export all of the Silverlight specific code as services. You do the same for your unit testing in .net projects and you’ll be able to run the exact same assembly in both locations.

The bonus to this, of course, is that you’ll also be able to swap out logic that you want to actually be different in different locations as well. For example, if you’re creating a business application you could put all of your business logic into a single assembly that could be run on both the client and the server. However, what that logic does and how it does it might be different in both locations. You may need to do a server call to a database to determine if a particular value of your business object is unique. On the client you want to make an asynchronous web request back to the server but on the server you want to make a call directly to the Database. It’s the same object and assembly in both locations so in order to achieve this you need to make the ValidateUnique rule itself composable, then this is possible even though the object is simply applying the rule in the same way.

In fact this technique can be very pervasive and powerful in general. Running on multiple frameworks requires you to be composable, which may also inadvertently force you into some good practices in general.

One other thing to note. I had to set CopyLocal=True for some of my references in the Silverlight Class Library to get it to run correctly in .NET. Since those assemblies aren’t in the GAC by default, it won’t load them unless they tag along with your assembly.

image

I didn’t test this out myself but you wouldn’t want those files appearing in your .xap file for your Silverlight application. I’m pretty sure that it would be smart enough to exclude them but double check.

Be the first to rate this post

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

Tags:

Silverlight | Software Development | WPF | Visual Studio | .NET | C# | MSBuild

Nullable TypeConverter for Silverlight

by Justin Chase 26. January 2010 05:45

In Silverlight if you want a property of one of your Controls or Models to be Nullable<T> you will end up with a parser error without a little extra work. The reason for this is that there is no default TypeConverter for Nullable<T> so the parser doesn’t know how to convert the string in the Xaml to the appropriate type. To fix this you simply create your own TypeConverter and apply it to your property.

public class NullableTypeConverter<T> : TypeConverter
    where T : struct
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        Nullable<T> nullableValue = null;
        string stringValue = value as string;
        if (!string.IsNullOrEmpty(stringValue))
        {
            T converted = (T)Convert.ChangeType(value, typeof(T), culture);
            nullableValue = new Nullable<T>(converted);
        }

        return nullableValue;
    }
}

Then to apply it you simply do the following:

[TypeConverter(typeof(NullableTypeConverter<int>))]
public int? Example { get; set; }

Be the first to rate this post

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

Tags:

.NET | C# | Expression | Silverlight | WPF

Easy Composable Theming in WPF (.NET 4)

by Justin Chase 5. November 2009 06:28

In .NET 4 there is a new namespace to be aware of and that is System.ComponentModel.Composition. Also known as MEF (Managed Extensibility Framework). This post outlines a very simple way to take advantage of the new Composition tools to add simple themeing to your WPF applications.

 

 image image

 

Step 1: Create a shared project

The shared project should define interfaces and classes that are needed by both the application and each of the composable parts. In this sample application I have a project called Core which defines a single interface. All other projects reference this core project.

IThemeService.cs

namespace Core
{
    public interface IThemeService
    {
        ResourceDictionary Theme { get; }
    }
}

 

Step 2: Create Theme Projects

A theme project will reference the core project and implement the IThemeService interface.

ThemeXService.cs

using System.ComponentModel.Composition;
using Core;

namespace ThemeX
{
    [Export("ThemeX", typeof(IThemeService))]
    internal class ThemeXService : IThemeService
    {
        public System.Windows.ResourceDictionary Theme
        {
            get { return new Themes.Generic(); }
        }
    }
}

Additionally this project will contain a single resource dictionary class with all of our named resources defined.

Themes\Generic.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:ThemeX"
    x:Class="ThemeX.Themes.Generic">

    <system:String x:Key="ThemeTitle">Theme X!</system:String>
    <SolidColorBrush x:Key="ThemeBrush" Color="PowderBlue" />
</ResourceDictionary>

Themes\Generic.cs

using System.Windows;

namespace ThemeX.Themes
{
    public partial class Generic : ResourceDictionary
    {
        public Generic()
        {
            this.InitializeComponent();
        }
    }
}

 

Step 3: Create Your Application and Load a Theme

In this application I am loading the first theme at startup then changing the theme based on a selection of a ComboBox. In a real application it might make more sense to store the name of the theme in user settings somehow and load the theme using that value.

Here is the very simple window that is to be themed.

MainWindow.cs

<Window 
    x:Class="ComposableThemes.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:app="clr-namespace:ComposableThemes"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <ComboBox ItemsSource="{Binding ThemeNames, Source={x:Static app:App.Current}}"
                SelectionChanged="ComboBox_SelectionChanged" />
        <Border 
            Grid.Row="1"
            Margin="25"
            BorderThickness="2"
            CornerRadius="5"
            Background="{DynamicResource ThemeBrush}">
            <TextBlock 
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Text="{DynamicResource ThemeTitle}" />
        </Border>
    </Grid>
</Window>

Notice the {DynamicResource …} references. These will give warnings in your design view because they cannot be resolved. They will be resolved at runtime because we will be loading the resource dictionary object created in step 2 at startup.

Here is how you can load an exported object and load a resource dictionary at runtime.

App.xaml.cs

public void SetTheme(string themeName)
{
    string location = Path.GetDirectoryName(typeof(App).Assembly.Location);
    using (var addinCatalog = new DirectoryCatalog(location))
    {
        using (CompositionContainer container = new CompositionContainer(addinCatalog))
        {
            if (!string.IsNullOrEmpty(themeName))
            {
                IThemeService theme = container.GetExport<IThemeService>(themeName).Value;
                if (theme != null)
                {
                    var themeDictionary = theme.Theme;
                    if (themeDictionary != null)
                    {
                        this.Resources.MergedDictionaries.Add(themeDictionary);
                    }
                }
            }
        }
    }
}

In this method we are using the applications directory to look for composable parts (plug-ins). A catalog is basically a container that loads assemblies and finds Exports / Imports for you. There is a very handy AggregateCatalog class that will allow you to have multiple directories or multiple assemblies or whatever type of catalog you want.

It’s useful to know that you can also use an Import attribute on a class to have the container automatically bind together the imported and exported parts. I find that to be a little more magical than I prefer so I did it this way instead.

Also, you can get a list of all theme names by inspecting the metadata of exported parts. Here is a snippet I used to populate my ComboBox with theme names:

App.xaml.cs

public IEnumerable<string> ThemeNames
{
    get
    {
        string location = Path.GetDirectoryName(typeof(App).Assembly.Location);
        using (var addinCatalog = new DirectoryCatalog(location))
        {
            foreach (var part in addinCatalog.Parts)
            {
                foreach (var definition in part.ExportDefinitions)
                {
                    var value = (string)definition.Metadata["ExportTypeIdentity"];
                    if (value == typeof(IThemeService).FullName)
                    {
                        yield return definition.ContractName;
                    }
                }
            }
        }
    }
}

 

Conclusion

All in all, I am very happy with the new Composition framework. It’s very easy to use and because of that, very powerful. One thing you should keep in mind however is that there is no magic here when it comes to loading and unloading assemblies, if you use a directory catalog it will load all assemblies in that directory into your current AppDomain and you cannot unload them (as is normal).

For another example of MEF in action check out my MetaTask in the MetaSharp source code. This is how all pipelines are loaded in MetaSharp.

Be the first to rate this post

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

Tags:

.NET | C# | WPF

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

Justin Chase

sweetest hat ever

I am a software developer from St. Paul MN and I work for Microsoft on the Expression team. This blog is about various technical topics I find myself encountering here and there. In addition to loving WPF and Xaml and Expression studio in general I have a special interest in DSLs, programming languages and games.

RecentComments

Comment RSS

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar