Silverlight 4 Runs Natively in .NET

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.

Nullable TypeConverter for Silverlight

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

Silverlight 3 and Expression 3

After months of top secret work at Microsoft my labors are nearly realized. Yesterday Silverlight 3 and Expression 3 were released as an RC. If you haven’t checked it out you should definitely go and play around with the new bits. Here is a overview from Soma himself:

http://blogs.msdn.com/somasegar/archive/2009/07/10/launching-silverlight-3-and-expression-studio-3.aspx

Specifically I worked on the Photoshop Import functionality found in Expressoin Blend, Design and Web. It has been an exciting and rewarding project and I’m really looking forward to what is coming up next!

One of the other cool features to check out which was created by fellow Minnesotans, is Sketch Flow for Expression Blend. It’s a cool tool you can use to quickly prototype new applications and features.

Derived Styles based on unnamed default Styles

This seems so obvious in retrospect but I just learned something very useful today so I thought I’d put it out there just in case anyone else wasn’t aware of this.

Specifically the problem occurs when you create a style in Xaml that is supposed to be the default style for a particular type of Control. For example:

<Style TargetType="{x:Type ComboBox}">
</Style>

This will allow you to create a style for all ComboBoxes. If a ComboBox does not specify a specific Style it will get this one automatically. The tricky part comes when you want a single particular ComboBox to deviate from the style just a little bit. So typically what I do is create the main Style that is named then create the default Style to be based on that main one like:

<Style x:Key="ComboBoxBase" TargetType="{x:Type ComboBox}">
</Style>
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource ComboBoxBase}">
</Style>

Then if you make any further custom styles they can just be based on ComboBoxBase and change as necessary. While this works I just found a way that is potentially cleaner. It turns out that you can pass in a Type to the StaticResource instead of a key and get at the default Style for that Type. Very handy, like so:

<Style TargetType="{x:Type ComboBox}">
</Style>
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
</Style>

How did I not know this sooner? This way you put all of your main styling into the official default Style, you also don’t need to remember the name of that default Style to use it.

Disclaimer: I haven’t tried this on Silverlight, only WPF.

Expression Studio and MIX09

Tomorrow is Day 1 of MIX09, if you’re not aware of this then you must be living on mars should amble on over and check out what’s in store this year. There’s a lot I can’t tell you but I can say there are tons of cool new features being announced for the first time tomorrow, including the one that I have been working on here in Minneapolis. Also, there are some features that will be demoed during the keynote that will not be apart of the public CTP released at the same time so you should definitely check that out to get a complete idea of the sweetness of the real release.

If you have any questions about features feel free to ask me sometime tomorrow after the keynote 😉 Until then it’s all hush hush.