IL.View October 2011 Features.


October 2011 was a very busy month for IL.View in terms of new features  introduced.

The major features that are worth mentioning in this recap is as following:

  • Automatic updates for OOB (out-of-browser) scenario
  • Rich browsing for Silverlight packages (.xap files)
  • Platform identifiers for assemblies
  • Version numbers for assembly references
  • Content preview for some file types (xml/xaml/ClientConfig/jpg/png)
  • Displaying and expanding embedded resource assemblies (for Silverlight assemblies only) by pressing Space bar
  • Preview of embedded resources (xml/xaml/ClientConfig/jpg/png) by pressing Space bar
  • User-defined reference paths for automatic assembly resolution (similar to Visual Studio “reference paths” feature)
  • Lot of stabilization and improvements for underlying infrastructures
  • New assembly versioning schema based on “YYYY.MM.DD.{Build}” format

Automatic Updates

Live preview builds that are continuously  pushed to the project page got support for automatic updates. Users that are using the full-trust OOB (out-of-browser) scenario will get the application up-to-date automatically upon every launch.

Browsing Silverlight Packages

IL.View now provides rich capabilities for browsing Silverlight packages (“.xap” files). Users are now able to drag and drop “.xap” package directly onto the application surface and view package contents. Package browsing includes full support for content and assembly navigation in the same way it is done for a regular assembly.
Silverlight Package Browsing

Platform identifiers for assemblies

As application is moving forward having a single list of assemblies within the browser the platform identifiers were added to assembly names. Silverlight assemblies will be marked as “(SL)” while .NET assemblies will be marked as “.NET”. Later on identifiers will be extended to display the actual version of the corresponding framework.

Platform Identifiers

Version numbers for assembly references

To improve dependency analysis process the application provides version numbers for assembly references within the reference title. That allows to avoid unnecessary decompilation or assembly resolution calls when it is only the version of reference the user is interested in.

Version numbers for assembly references

Content Preview

It is now possible to view the content of the files that are frequently added to the “.xap” files. IL.View provides support to show xml-based files (xml, xaml, ClientConfig) with syntax colouring:

Content Preview of xml-based files

 It is also possible to preview the content of image files in the formats supported by Silverlight (.png and .jpg). Images are displayed in real sizes.
Content preview for image files

Browsing embedded resource assemblies

October version of IL.View brings out support for embedded resource assemblies navigation. This feature is however limited to only Silverlight assemblies. A new node called “Resources” will appear next to every main module of the assembly. Resource assemblies can be expanded like regular assemblies and their xml/image-based content can be previewed by pressing a Space bar on the selected item.

Browsing embedded resources

 Reference Paths

Application now provides a way to define common reference paths that should be used for assembly lookup during decompilation and reference resolution. There will be a new options panel called “Reference Paths” within the “Settings” page. The user is able to add or remove a path to any directory containing .NET or Silverlight assemblies that needs to be checked during decompilation process. Every single reference path can be configured to use recursive search, meaning that the entire folder tree (including all sub-folders) is going to be inspected. However recursive search is a time consuming event and users discouraged to use it against deep nested folders.

Every time an external assembly is found the path to the file is cached. This gives much better performance during next sessions.

Reference Paths

This feature is however limited to full-trust mode running on Windows machines. “Reference Paths” section won’t be displayed when running IL.View on non-Windows computers (i.e. MacOs).

New Versioning Schema

New assembly versioning schema was applied based on “YYYY.MM.DD.{Build}” format. The version number can now be checked at the “About” page:

Versioning Schema

Besides new features there was a lot of stabilization work performed.

More and more features are being registered within the issue tracking system.

IL.View beta builds are now available online


Today I’m glad to announce that thanks to Github “project pages” feature I am able to host beta builds of “IL.View” that can be consumed both in browswer and out of browser.

You can browse and/or install IL.View by navigating this link: http://denisvuyka.github.com/IL.View

 

What’s new in the deployed build:

I have added an experimental support for Silverlight “.xap” packages. It will be possible to drop a “.xap” file onto IL.View surface and navigate it’s content within assembly browser like shown below:

Just have to note that the implementation of “.xap” browsing is in its early stage and is not feature complete.

What’s on the way:

Many features related to MEF framework. I’m a greatest fan of MEF and use it every day in the production. There’s some tooling that I would like to integrate into IL.View like displaying all the MEF imports/exports for the particular assembly, etc. More content viewers are pending (xaml/xml, images, etc.)

Suggestions, issues and feedbacks?

I would really appreciate to get them registered here: IL.View Issues

IL.View: .NET Reflector OSS Alternative. In Silverlight!


Today I would like to announce a new project I’ve been working on to contribute to the .NET community.

The project is called “IL.View” and it is a .NET Reflector alternative made in Silverlight 4 as an Out-of-Browser Silverlight Application. “IL.View” sources will be published under the MIT (X11) license to the following GitHub repository in the next couple of hours. As soon as Google fixes “If-Modified-Since” bug the online version of “IL.View” will hopefully become immediately available with “Google App Engine”.

image

Background

I’ve started planning this project approximately 2 weeks before infamous Red Gate announcement that “.NET Reflector” goes commercial way and so approximately 2 weeks before an awesome OSS alternative appeared: ILSpy. So “IL.View” background is not an emotional move and is not going to be abandoned with the ILSpy arrival (like Monoflector for instance).

I am a Silverlight developer and my team does a lot of really crazy stuff related to Silverlight, Azure, REST and OData. During the “demo” and “testing” periods we have to deal with publishing a lot – different versions of Windows Servers, various IIS versions, different .NET frameworks at server sides, multiple remote desktops and issue addressing, etc.

One of the issues I’ve experienced in the past (and according to Google I’m not alone with that) is the process of brining .NET Reflector to server side in order to have a quick look at my assemblies. You should be able to download it from somewhere for every server (of course if you have rights to download and install anything), you need to have a proper .NET Framework installed on server side (Reflector itself requires .NET 3.5 or later to be present), etc.

Actually the very same problem may be valid for ILSpy as well. If it is compiled for .NET 4.0 framework you cannot use it at server having .NET 3.x only. So the idea of having a Silverlight version hosted in the company intranet (or in the cloud) was very appealing as it could save time and reduce efforts.

Another feature I was dreaming of is “Remote Assembly Cache” or the possibility to decompile .NET assembly without binding to local machine – even without having any .NET framework installed at all. For example having a remote web service (pure REST, OData, whatever) to resolve .NET dependencies upon being needed. This could open a brand new set of scenarios for me. Having no bindings to local machine could for example allow Mac users to disassemble .NET assemblies easily and drilling down to “mscorlib” or any other part of .NET framework without difficulties (this feature is in progress for “IL.VIew” and will be available later on).

Third major feature I was trying to address is extensibility. NET Reflector always deserved better extensibility support and more complex addins from both code and presentation points of view.

Overview

As I’ve mentioned above “IL.View” is an OOB (Out-of-browser) Silverlight 4 application (Full Trust). It supports drag and drop for .NET assemblies from the desktop or Windows Explorer and provides a local cache of assemblies that were loaded (with the possibility extending the cache manually). “Assembly Browser” control supports “lazy loading” so you get disassembling process on demand. There’s a native “IL” formatting and “C#” one (in progress).

There are several ways “IL.View” can be deployed and used:

  • Online (cloud, web site)
  • On-premise (intranet)
  • Local installation
    Some features that are in progress will allow “IL.View” users to get maximum benefit of both cloud and on-premise deployments.

Mono.Cecil

“IL.View” is not using .NET Reflection. It is being build on the top of Silverlight port of “Mono.Cecil”. This is a tremendous project and I would like to thank Jb Evain for his work. Thanks to Cecil I got an opportunity dealing with both .NET and Silverlight assembly inspection within Silverlight runtime.

Despite the asynchronous nature of Silverlight the Cecil integration went well. “IL.View” provides its own dependency resolution facility that is capable of properly locking the UI and waiting for the user to perform actions:

SNAGHTML103147e

SNAGHTML14fc8c1

ICSharpCode Decompiler and NRefactory for Silverlight

The biggest challenge for me was “C#” output support. Not to reinvent a wheel I’ve decided to stick to ICSharpCode.Decompiler and ICSharpCode.NRefactory projects that are the part of ILSpy.  The only problem I came across is the absence of Silverlight ports for the mentioned projects. So I’ve took the challenge to port them to Silverlight myself. You can find the sources at my GitHub repository. First attempts were quite tricky, but thanks to the ILSpy team the original codebase becomes more and more “portable-friendly”.

As a result I have managed to provide C# output based on ILSpy libraries:

image

JetPack Theme

“IL.View” UI is based on the great “JetPack Theme”. However I had to provide a set of bugfixes for templates and styles in order to make some of the components look properly and behave as expected.

Notes

The project is still in its early stage but is going to evolve rapidly. There’s a huge backlog of features and roadmap will be announced later on. “IL.View” does not compete with ILSpy and I would love to contribute eventually to both .NET Reflector alternatives in the nearest future.

VS 2010 bug related to Silverlight 4.0 compilation


Some time ago I came across the problem of compiling Silverlight 4.0 with Visual Studio 2010 when using XmlnsDefinitionAttribute attribute. I have reported the problem to Microsoft but for the time of writing this post I haven’t yet received confirmation of the bug. However more and more people around me start to experience the very same problem with VS 2010 so I’ve decided to publish some details towards the problem as well as possible workarounds that can be used until the bug is confirmed and some sort of hotfix is available.

The problem is that under some specific circumstances Visual Studio 2010 will fail compiling Silverlight 4 assembly if it refers to any other assembly via xmlns mapping in the root of the XAML.

Here you can find a sample solution that addresses this problem: VSBuildBug.

Here’s the brief overview of the sample code:

1. Silverlight 4.0 assembly “SharedComponents” contains a User Control called “SharedControl”

2. The assembly “SharedComponents” maps one of its namespaces to an Uri (in my case it is “https://denisvuyka.wordpress.com/vsbugs”)

3. Silverlight application “VSBuildBug” references “SharedComponents” assembly

4. Application contains a “MainForm” that is declared my means of the namespace mapping: <shared:UserControl xmlns:shared=”https://denisvuyka.wordpress.com/vsbugs”…

When you open the solution attached with VS 2010 and try compiling it you will receive the following error:

The type or namespace ‘SharedControl’ could not be found (are you missing a using directive or an assembly reference?” (see the screenshot below)

clip_image002

However theoretically everything should compile without any problem. Some of the guys I’ve contacted towards this problem just gave up using xml namespace mappings thinking that the problem is in Silverlight itself but it’s wrong. This use case is absolutely correct and can be compiled.

The first workaround is calling “Build – Rebuild solution” several times in a row. At some stage you will receive “successful compilation” result and after that you will stop getting errors both for “Build” and “Rebuild”. However everything will be ok until the “Build – Clean solution” call or until you get a brand new version of the solution from the source control for example. Also different versions of Windows require different number of rebuild cycles. I didn’t bother figuring out the correct numbers, I can only confirm that on Windows 7 you may need about 3-4 “rebuild” calls while Windows XP may require 5+ “rebuild” calls.

After you made it compile you can reproduce the problem any time again. Just call “Build – Clean” solution and try “building” or “rebuilding” it again. The compilation problem will come back and you may need repeating the “rebuild” cycle one more time.

I’ve decided to go further with my investigation as I was wondering why TFS builds do not fail under the same conditions. I’ve ended up with a more reliable solution that I am using nowadays – msbuild tool.

If you unpack my solution once again and compile it from the VS command prompt using msbuild (just “msbuild VSBuildBug.sln”) you will never get an error. You won’t get errors calling “Build – Clean” solution and then using msbuild to build it as well.

So the second and most reliable solution is using msbuild tool to produce a solution. In case of avoiding full cleanups with “Build – Clean” solution developer may need calling msbuild only once getting a brand new version of codebase from TFS.

After finding a reliable workaround I’ve decided to go deeper into the details and see why auto-generated code is not compiling.

I’ve opened “MainPage.g.i.cs” with Visual Studio to get notifications when it is changed and to have an opportunity to see how it was changed. After a couple of experiments I’ve noticed that first two compilations (and code generations) does not produce the very same code behind actually.

Steps to reproduce:

Step 1. Open demo solution and call “Build – Clean solution”

Step 2. Call “Build – Rebuild”

You should see the same error I’ve described earlier:

clip_image002[4]

If you open the auto-generated “MainPage.g.i.cs” you should notice that “MainPage” inherits “SharedControl” but no references to external component library are present (neither within “using” clause nor type declaration). See the screenshot below:

clip_image002[6]

clip_image002[8]

I completely agree that this code should not compile even theoretically and Visual Studio gives me the correct output stating about missing references.

Step 3. Call “Build – Rebuild” for the second time.

You should get the very same compilation error again:

clip_image002[10]

However if you have “MainPage.g.i.cs” file opened in VS 2010 you will get a notification that its content was changed. Alternatively you can locate this file and open it manually.

After the second rebuild the type definition looks like the following:

clip_image002[12]

As you can see now VS generated another version of code behind that correctly references the “SharedControl” type. The namespace is provided and code should theoretically compile fine. But it does not.

Step 4. Call “Build – Rebuild” 3rd time

You should receive notification that compilation was successful (please don’t forget about my notes at the beginning that I am using Windows 7, it was noticed that Windows XP environments sometimes require more “rebuild” calls).

Third compilation does not produce a new code behind file and its content is equal to those produced during the Step 3.

I’m pretty sure VS is doing something wrong between steps 2–4. Two different code generation outputs for the same action that was just called twice seems to be very suspicious.

The only idea I have for the moment is that “MainPage.g.i.cs” was generated AFTER the rebuild procedure has finished. And the 3rd rebuild is just using the file generated during the 2nd pass. If that is true then it makes a perfect sense why 3rd pass was successful. And if I’m right then developers may potentially encounter even more serious problems in the future because there will be always a possibility testing the code that was built without exception but does not contain changes or bug fixes that needs to be verified by developer if you see what I mean.

The only thing I don’t understand for the moment is why VS 2010 produces compilation errors while msbuild works fine. I expected VS 2010 is using msbuild under the hood for building Silverlight but my investigation results make me think that there are two ways of building (please correct me if I’m wrong, I didn’t try reflecting VS to find an answer for this question) and the build procedure embedded into VS is definitely having issues.

 

Conslusion

I still think that xml namespace binding is a very important feature that needs to be reused as much as possible (see more details here: “Prefixes and Mappings for Silverlight Libraries”) at least because of the following benefits:

  • helps a lot with xaml/code generation scenarios;
  • helps a lot with component discovery (we all love intellisense);
  • reduces a variety of problems related to code refactorings and type namespace changes;

I’m pretty sure Microsoft will provide a hotfix as soon as this issue is confirmed but meanwhile you can use “msbuild” or “continuous rebuild” workarounds to keep using xml namespace mappings within your projects.

Any feedback is appreciated.

Dynamic Silverlight Forms. Embedding S# Scripts into Xaml.


I’ve been receiving a lot of questions regarding the possibility of usage S# in a declarative way directly from xaml rather than from code behind. Such approach is extremely valuable when dealing with BPM-like usages and dynamic forms that are presented by raw Xaml stored in database and instantiated via XamlReader.

In this article I’m going to show you how easy it can be to embed a S# script into Xaml and execute it dynamically. For this purpose I will be using some blocks of the new upcoming “S# Silverlight Toolkit” that will be available soon as a part of the S# package. The toolkit will be distributed as a free addition with source code provided.

For the sake of simplicity I’m going to show the very basic injection of S# scripts into Xaml markup. I will be using Silverlight 3 for this purpose. The sample code will be updated to Silverlight 4 as soon as S# 2.0 reaches RTM.

1. Required Assembly References

You will need adding references to the following assemblies:

  • Orbifold.SSharp.dll
  • Orbifold.SSharp.Silverlight.Toolkit.dll (you can find it in the form of source code within the sample solution attached at the end of the article)

2. Required Namespace Declaration

You will need to declare 3 additional namespaces

  • sys” pointing to the “System” namespace in “mscorlib” to be able using basic .NET types from within Xaml;
  • scriptingRuntime” pointing to the “Orbifold.SSharp.Runtime” namespace to be able using “ScriptContext” from within Xaml;
  • scriptingToolkit” pointing to the “Orbifold.SSharp.Silverlight” namespace to be able using Silverlight facilities like “CodeBlock” and “ScriptManager” from within Xaml;

image

3. Introducing Script Execution Context for the Form

Obviously you will want providing some context variables or custom functions for the scripts executed by the form. For this purpose I’m declaring a ScriptContext instance in the resources section of the form:

image

Here’s the code behind I’ve used to initialize default script context for the form:

image

First of all you will need initializing Runtime Host. I’ve promoted the entire “System.Windows” assembly (via MessageBox type) to be able calling Message Boxes from within scripts.

Next I’ve got access to “defaultContext” declared in the markup and created a script variable “Form” pointing to the instance of this very Silverlight form. Additionally you may need assigning “ExecutionContext” attached property for the form if you want embedding scripts for the form-level events like “Loaded”.

4. Attaching S# Scripts to the UI elements

S# Silverlight Toolkit provides a set of facilities regarding script injection. You will need 2 of them for now: Code Block and Script Manager. CodeBlock class serves as a wrapper around plain S# script while Script Manager provides a set of attached properties (see Ramora Pattern) to wire UI elements with the S# runtime engine.

OnLoaded Attached Property

Allows you to associate a S# script with a FrameworkElement and execute it each time “FrameworkElement.Loaded” event is fired. Here’s a basic example:

image

ScriptManager.OnLoaded attached property setter accepts “CodeBlock” instance as a valid value. Every Code Block can contain a body of the S# script and can be optionally bound to the execution context.

The script above uses common Silverlight FrameworkElement.FindName method to find an element called “TextBox” and assigns its Text property to “Dynamically populated text!!!”.

ScriptManager.OnButtonClick attached property setter accepts “CodeBlock” instance as a value and wires a S# script with a “Button.Click” event:

image

Sample above shows a simple scenario of finding a TextBox element on the form and modifying its “Text” property.

ScriptManager.OnGotFocus attached property setter accepts “CodeBlock” instance as a value and wires a S# script with “UIElement.GotFocus” event:

image

5. Running Sample

After launching the sample you will see the following UI elements:

image

There is a Button and a TextBox controls. The text box will contain some text assigned by the Form-level script (ScriptManager.OnLoaded)

When clicking (and so focusing) the TextBox the “OnGotFocus” script will be executed:

image

When clicking a Button element the message box will appear and the TextBox.Text will be changed according to the “OnButtonClick” script:

image

image

Conclusion

The S# Silverlight Toolkit opens the door for more efficient and rich scripting for your applications. Being similar to ASP.NET development it provides facilities for dynamic invocation of your scripts during the UI life cycle, allows you storing the xaml in databases and instantiate the entire UI with corresponding scripts during runtime by means of XamlReader (note that all attached properties will be restored during form instantiation, and all event handlers will be re-assigned during XamlReader.Load process).

You can get the source code for this article here:

S# 2.0 features. It’s all about performance, dynamics and integration.


In this article I would like to give you some details towards next version (2.0) of the S# language and scripting runtime.

Version 2.x will be based on .NET 4.0 and will be supported separately of Version 1.x that is still built on the top of .NET 3.5. Both versions will have a set of common features powered by both .NET 3.5 and .NET 4.0 however version 2.x will introduce a set of brand new capabilities built on the top of .NET 4.0 only. The entire 2.x family will be backward compatible. There will be no breaking changes in the scripts and migration difficulties.

Performance

A lot of work is related to script execution performance. S# runtime is used in various reporting and visualization tools where execution time of large or repetitive blocks is very important. Version 2 provides tremendous improvements and optimizations in comparison to Version 1.0.

Here’s one of our comparison benchmarks for basic loops (execution results are given in milliseconds)

Script v.1 v.2 %
for (i = 0; i <= 100000; i++) { } 48.7 26.7 182
for (i = 0; i <= 100000; i = i + 1) { } 63.84 41.38 154
for (i = 0; i <= 100000; i++) {  i.ToString(); } 4129.5 227.06 1517
a = [1,2,3]; x = 0; for (i = 0; i < 100000; i++) { x = a[1]; } 1571.1 72.62 2164
a = [1,2,3]; for (i = 0; i < 100000; i++) { a[0] = i; } 2630.9 87.38 3011
x = null; p = new Person(); for (i = 0; i < 100000; i++) { x = p["testme"]; } 1242.8 75.56 1645
x = null; p = new Person(); for (i = 0; i < 100000; i++) { p["name"] = "test"; } 1322.8 82.2 1609
for (i = 0; i <= 100000; i++) { i.ToString(null); } 3257.8 773.06 421.4

As you can see the performance improvements for loops, method calls and array manipulations range from 200% for 3000% and this is not the complete list.

Here’s the graphical charts for the first 50 calls of each script benchmark (vertical axis is given in milliseconds):

image

image

image

image

image

image

image

image

All the tests were performed on Windows 7 Ultimate ( x64), Intel Core 2 Duo T9400, 2.5GHz, 4GB RAM

Dynamics

I’m glad to announce that S# 2.0 will support “dynamic” objects powered by .NET 4.0 and its DLR (Dynamic Language Runtime) part. There will be a new type alias called “dynamic” that will allow you creating objects on the fly similar to the following sample:

person = new dynamic();
person.Name = “John Doe”;
person.Age = 40;

This should significantly improve scripting experience an reduce efforts required to perform complex reporting or visualization scripts as types can be created dynamically during script execution instead of creating custom types and registering them within the runtime host.

The performance of dynamic objects is also very important for us. For the moment object property access (both getting and setting property value) is much quicker than of plain CLR type:

image

 

Integration

You will get more samples related to S# integration with other technologies and products. Soon there will be a set of articles regarding new features in S# for WPF and Silverlight, Microsoft Office 2007/2010 etc.

S# framework will provide a new libraries targeting OpenXml SDK 2.0 reuse within the scripts. It will be possible getting and setting data for Microsoft Excel 2010 document by accessing cells in scripts similar to the following way:

workbook = new Workbook(“Book1.xslx”);
workbook.Sheet1.A1 = “Hello world”;
workbook.Sheet1.A2 = 100;
workbook.Sheet1.B1 = workbook.Sheet1.A2 + 200;

More news are on the way…

Dynamic event handlers for Xaml-only Silverlight content (XamlReader, “Ramora” pattern and MEF)


The complete source code for the article can be found here.

 

Since developers started using XamlReader and XamlWriter in WPF the question towards events and event handlers seem to be one of the most hottest both for WPF and Silverlight. In this article I’m going to show you one of the possible ways to provide event handlers for Silverlight controls that are instantiated from a Xaml dynamically by means of XamlReader. I will be using MEF Preview 9 to glue parts together in my sample.

Imagine the following scenario:

 

Some “business form” is designed within some thick/thin client and deployed to a server-side repository (database) as a string representation of xaml. Later on a Silverlight client loads this form data, turns into live UI layout and presents to a user. There is a set of logic should be involved during the “business form” life cycle taking into account such events as “Form Load”, “Submit Button Click”, “Cancel Button Click” etc. These events should be wired by the owner form during string-to-content conversion.

Hint: When a “business” form is being converted from its string-based representation to a live Silverlight content the types for resulting object graph are taken from the active application domain. This means that you can declare any type of control if you are sure the assembly containing this control is loaded during runtime. For example if your shell references “Silverlight Toolkit”, the XamlReader will allow you creating Charts from string-based content.

I’ll be using the awesome “Ramora” pattern I’ve been a greatest fun of since it was suggested by Ben Constable here. The reason is that XamlReader provides support for Attached Properties for parsed content. This means that every Attached Property can serve as a some sort of entry point for application specific logic by means of “Ramora” pattern.

 

You may want creating a separate “Silverlight Class Library” to hold contract classes and services that will be loaded during runtime and could be accessible by XamlReader when parsing strings. In my sample this library will be called “XamlOnlyUtils” but you can call it whatever you want.

 

Customizing Export attribute to suit our needs

Latest MEF previews unseal “ExportAttribute” in order to support highly customizable solutions and allow hiding MEF from the “end-developer” levels. For more details please refer to “Exports and Metadata” section in MEF documentation.

 

I’ve created an application specific attribute that will allow you exporting event handlers:

“XamlEventHandlerAttribute.cs”

using System;
using System.ComponentModel.Composition;
using System.Windows;

namespace XamlOnlyUtils
{
  [MetadataAttribute]
  [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
  public sealed class XamlEventHandlerAttribute : ExportAttribute
  {
    public string Name { get; private set; }

    public XamlEventHandlerAttribute(string name)
      : base("XamlEventHandlers", typeof(Action<DependencyObject>))
    {
      this.Name = name;
    }
  }
}

The attribute above will hold the “Name” of event handler and will be scoped by the “XamlEventHandlers” contract addressing "”Action<DependencyObject>” handlers. This is a minimalistic implementation and you can easily modify it to cover complex scenarios later on.

As a result you will be able creating a handler that looks similar to that below:

[XamlEventHandler("CustomOnLoad")]
   public void CustomOnLoadHandler(DependencyObject sender)
   {
     MessageBox.Show("Loosely bound event handler fired!");
   }

 

Providing strongly-typed metadata

 

To simplify handlers discovery and invokation I’ve created a simple interface to expose “Name” property of each imported action:

namespace XamlOnlyUtils
{
  public interface IXamlEventHandlerMetadata
  {
    string Name { get; }
  }
}

If you want getting more details towards strongly-typed metadata and its usage please refer to “Exports and Metadata” section in MEF documentation.

 

Creating and consuming a simple event

Now we need exposing “Ramora” pattern to instrument a simple “Loaded” event. Let’s assume we want handling the “FrameworkElement.Loaded” event in a dynamic way.

Create a new Dependency object in the “XamlOnlyUtils” library and call it “XamlEventServices”:

public class XamlEventServices : DependencyObject

This class will store all attached properties required to accomplish the task. I’ve inherited it from a DependencyObject in order to have access to Dispatcher in future.

Now let’s define a simple “Loaded” event handler. It will be an attached property holding the name of the handler:

public static readonly DependencyProperty OnLoadedProperty =
     DependencyProperty.RegisterAttached(
       "OnLoaded",
       typeof(string),
       typeof(XamlEventServices),
       new PropertyMetadata(null, OnLoadedPropertyChanged));

Exposing getter and setter in the common way:

public static string GetOnLoaded(DependencyObject target)
    {
      return (string)target.GetValue(OnLoadedProperty);
    }

    public static void SetOnLoaded(DependencyObject target, string value)
    {
      target.SetValue(OnLoadedProperty, value);
    }

As you might have noticed I’m declaring a “property change” handler called “OnLoadedPropertyChanged” for attached property. This is where the “Ramora” implementation begins. The idea is to wire additional logic as soon as “OnLoaded” attached property is defined for an object. As XamlReader takes care of parsing and assigning attached properties we can be sure that event handler will be fired during parsing phase and we’ll get the expected entry point.

Here’s how the implementation of “OnLoadedPropertyChanged” handler looks like on my side:

private static void OnLoadedPropertyChanged(
      DependencyObject sender, 
      DependencyPropertyChangedEventArgs e)
    {
      FrameworkElement fe = sender as FrameworkElement;
      if (fe == null) return;

      bool wasWired = (e.OldValue != null);
      bool needsWiring = (e.NewValue != null);

      if (wasWired) fe.Loaded -= OnLoadedHandler;
      if (needsWiring) fe.Loaded += OnLoadedHandler;
    }

This method wires “FrameworkElement.Loaded” event upon every attached property value change and covers 2 scenarios at once. It can either wire a new event handler if the property has changed for the first time or unwire the previously assigned handler if we want removing it by passing null value.

 

Here’s how my “FrameworkElement.Loaded” handler looks like:

static void OnLoadedHandler(object sender, RoutedEventArgs e)
   {
     DependencyObject dobj = sender as DependencyObject;
     if (dobj == null) return;

     string handlerName = GetOnLoaded(dobj);
     if (string.IsNullOrEmpty(handlerName)) return;

     var resolver = new EventHandlersResolver();
     CompositionInitializer.SatisfyImports(resolver);

     var handlers = resolver.EventHandlers
       .Where(row => row.Metadata.Name.Equals(
         handlerName, StringComparison.InvariantCultureIgnoreCase));

     foreach (var handler in handlers)
       handler.Value(dobj);
   }

Couple of details towards the code above: the first thing I’m trying to do is to get the name of the handler that was defined via the attached property. After that I create a "resolver” class that will hold all the external actions marked with “XamlEventHandlerAttribute”. After satisfying all imports for this resolver (simply getting all the action exports) I enumerate the result to find the actions matching the name defined by attached property and invoke every found action. This means that you can have multiple actions being fired for a single event.

 

Resolving exported actions

 

Attached properties is a world of statics. The property holder class (in my case it is “XamlEventServices”) is not instantiated each time a dependency property is used so it is quite difficult satisfying imports on it. I strongly recommend following MEF team suggestions not to try wiring static classes with MEF bus as It brings out additional implications in the future. Instead I’m using the “resolver” class and satisfy imports on the fly. Here’s how my simple resolver looks like:

 

using System;
using System.ComponentModel.Composition;
using System.Windows;

namespace XamlOnlyUtils
{
  public class EventHandlersResolver
  {
    [ImportMany("XamlEventHandlers", typeof(Action<DependencyObject>))]
    public Lazy<Action<DependencyObject>, IXamlEventHandlerMetadata>[] EventHandlers { get; set; }
  }    
}

It contains a single property collecting all “Action<DependencyObject>” exports scoped by “XamlEventHandlers” contract. You don’t need enabling recomposition here because imports will be collected dynamically when “FrameworkElement.Loaded” event is fired.

 

Testing loose handlers on “live” control

 

To ensure the loose event handler binding actually works you can do the following steps. Create a new Silverlight Application and reference the “contract” assembly “XamlOnlyUtils” (you can add reference to a project if you create application in the same solution).

 

Go to the code behind of the “MainForm.xaml” (“MainForm.xaml.cs”) and declare the following method:

[XamlEventHandler("CustomOnLoad")]
   public void CustomOnLoadHandler(DependencyObject sender)
   {
     MessageBox.Show("Loosely bound event handler fired!");
   }

You’ll be showing a dummy message box to ensure the infrastructure is working. Now return back to the xaml side and assign the “OnLoaded” attached property directly for the main form like on the screenshot below:

 

image

 

The workflow you expect to be executed is as follows: when the “OnLoaded” attached property is assigned, our “XamlEventServices” will attach a custom handler to control’s native “Loaded” event. As soon as control is loaded and a corresponding event is fired, “XamlEventServices” will resolve the imports for handler actions, find any action named as “CustomOnLoad” and execute them.

 

Configuring MEF for application

 

In order the sample above to work as expected you will need to actually enable MEF for the application. As my “MainForm.xaml.cs” contains some actions that need to be exported, I’ve decided to export the entire form to be able satisfying all the imports easily. For this purpose I’m marking “MainForm” with “ExportAttribute”:

 

[Export]
public partial class MainPage : UserControl
{

 

After that you will need opening the “App.xaml.cs” to configure composition host and satisfy imports (providing all the corresponding exports we are interested in). Here are the changes I’ve made to accomplish that:

 

1. Importing form into the application class:

 

public partial class App : Application
 {
   [Import]
   public MainPage MainPage { get; set; }

 

2. Rewiring root visual to the form being imported:

 

private void Application_Startup(object sender, StartupEventArgs e)
   {      
     this.RootVisual = this.MainPage;
   }

 

3. Finally providing a quick configuration of MEF including both assemblies I’ve been working with:

 

image

 

Note: for more details towards MEF hosting please refer to “Hosting MEF in an application” section of MEF documentation.

 

I assume that both projects I’ve been demonstrating already contain references to MEF “Composition” and “Initialization” for Silverlight assemblies:

 

image

 

When running the application you should see the Message Box displayed by “CustomOnLoadHandler” defined in the code behind of the main form:

 

image

 

This means that the loose infrastructure is working as expected. The method was successfully exported, discovered and fired.

 

 

Testing XamlReader and string-based xaml content

 

Now we need turning some string-based content into the live object graph and ensure the events can be wired during XamlReader parsing phase. I’ve changed the main form to contain a test Button that will start string-to-xaml conversion and a placeholder to put the resulting UI into:

 

image

 

Here’s the sample content I will be trying to process:

 

image

 

As I’ve mentioned at the beginning of the article, I can freely rely on the attached properties that are present within the application domain during runtime. I’ve imported a namespace from the “contract” library and configured “OnLoaded” attached property to point to the “CustomOnLoad” action that is expected to be defined somewhere in the hosting application.

 

Finally I provide some logic for “btnLoadXaml” Button Click handler:

 

private void btnLoadXaml_Click(object sender, RoutedEventArgs e)
  {
    FrameworkElement fe = XamlReader.Load(XamlContent) as FrameworkElement;
    if (fe != null)
      this.xamlContainer.Content = fe;
  }

 

In the code above I turn “XamlContent” string into a fully-fledged object graph (with all the attached properties processed) and assign the result to the Content property of my “xamlContainer” placeholder. As soon as It is done, the UI will be loaded and a corresponding “Loaded” event will be fired so causing the “OnCustomLoad” action be discovered and executed.

 

As soon as you click the “Load Xaml” button you should see the following result:

 

image

 

This article dwells on the very basic scenarios to demonstrate the things working indeed. Feel free extending it to support more complex scenarios.

 

The complete source code for the article can be found here.