Simple Workflow Designer with Silverlight and MEF


Introducing simple workflow designer

I’m excited to announce another project from my collection went public today. This time it is a demo POC (proof of concept) implementation for a simple workflow designer written in Silverlight 4 and MEF.

01.slwfdesigner

The project contains the following features that may be interesting for review:

  • Design surface with drag and drop (MVC)
  • Toolbox with automatic runtime discovery of items (MVVM)
  • Drawing connections, live update of connections during drag and drop
  • Separate model layer with custom serialization support (functions, activities, workflows)
  • Separate presentation layer (visual elements for activities), styling and templating nodes
  • Runtime discovery of models and corresponding node views (decoupled layers)
  • Simple rules (i.e. “Output ” node may have only 1 incoming connection)

There are two modes supported out of box – Design and Source views.

Design view

This mode showcases the process of visual modeling. The process is divided into two separated areas – Toolbox and Design Surface.

02.slwfdesigner-designview

Toolbox hosts all items exported and discovered at runtime by means of MEF. Default set of activities resides in a separate “WorkflowDesigner.Activities.dll” assembly and can be easily replaced or extended. There’s also an additional “WorkflowDesigner.Sdk.dll” assembly that is mean to be shared across 3rd party libraries and aids in creating custom activity libraries.

You can add activities to the surface by double-clicking the corresponding item in the toolbox. For the sake of simplicity there is no drag and drop support for the toolbox but it can be easily introduced. The quickest way may be reusing Telerik’s drag and drop manager with fancy visual cues, but this is out of scope of this article.

Design surface is based on MVC pattern and showcases basic set of functions like: drag and drop of activities across the surface, drawing connection lines, removing nodes or connections, clearing entire surface. Every visual node is mapped to underlying model (activity) at runtime. That means that both activity and it’s visual representation are completely decoupled and any of the parts can be easily tuned or extended.

For demonstration purposes default activities emulate the behavior of OData- or SQL-based entities with simple UI editors, entire project emulates the process of creating a workflow that deals with data aggregation.

08.slwfdesigner-activity

UI dialogs are not bound to any particular business logic except assigning corresponding property values of the model entity. However this may be a good start building user experiences based on your real-life scenarios.

09.slwfdesigner-dialog3

06.slwfdesigner-dialog1

Source view

In addition the Source view feature is supported. It allows you switching to the XML representation of the workflow at any time during design process. Serialization is completely custom and was kept as simple as possible in order to be replaceable or customized. Based on your real-life scenarios the resulting XML can travel to server side and can be turned into object graph without UI dependencies, etc.

03.slwfdesigner-sourceview

Project structure

I will be giving only brief overview of the project structure in this article. Most of the code is split into 2 areas and resides in 2 different class libraries: “WorkflowDesigner.Sdk” and “WorkflowDesigner.Activities“:

04.slwfdesigner-activities

05.slwfdesigner-sdk

As soon as you figure out the process of creation of new activities you most probably may need only “WorkflowDesigner.Sdk” assembly that contains all core and shared functionality.

Source code

You can grab the source code at my GitHub repository.

Advertisements

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:

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.

Silverlight 3 PropertyGrid Development Progress


There was no information about Silverlight version of the PropertyGrid control for some period. I would like to leak some information towards the current development progress as well as highlight some of the most remarkable features.

Multiple layouts support

Silverlight PropertyGrid will support at least Alphabetical and Categorized layouts out-of-box. There will be a possibility to write your own layouts with least amount of efforts possible.

Here’s how the the “Categorized” one looks like and defined in XAML:

SPG01

SPG02

“Categorized” layout will be the default one. This means that you won’t need defining anything if “Categorized” behavior is those you expect to have by default.

Note that control will support “Description Box” similar to native Windows Forms PropertyGrid control.

Here’s how the “Alphabetical” layout looks like and defined in XAML:

SPG03

SPG04

Both POCO (Plain Old CLR Objects) and Dependency objects are to be supported. Here’s the Button control bound to PropertyGrid:

SPG05

Property Filtering feature will provide exactly the same functionality Microsoft Expression Blend’s PropertyGrid control gives. It will be possible to filter out properties according to their names and types:

SPG06

SPG07

After Silverlight 3 went RTM the Silverlight PropertyGrid development progress went rapid and smooth and hopefully the control will be available very soon.

More news are coming soon…