RSS

Category Archives: Silverlight

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.

 
Leave a comment

Posted by on December 6, 2012 in .NET, Silverlight

 

Tags: ,

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

 
3 Comments

Posted by on October 27, 2011 in Silverlight

 

Tags: , , ,

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.

 
10 Comments

Posted by on April 27, 2011 in .NET, Silverlight

 

Tags: , , ,

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 “http://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=”http://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.

 
7 Comments

Posted by on October 8, 2010 in .NET, Silverlight

 

Tags: , ,

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:

 
2 Comments

Posted by on May 19, 2010 in S#, Scripting, Silverlight

 

Tags: , ,

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.

 
3 Comments

Posted by on February 21, 2010 in .NET, Silverlight

 

Tags: , , ,

Introducing S# scripting language and runtime


Today we are very excited and proud to announce that we finished testing and moved to the packaging procedure for our next brainchild called “Orbifold S#“. The purpose of this article is to give a brief overview of what S# actually is, key features and possible use cases.

S# is a weakly-typed dynamic language and runtime infrastructure to make your applications extendable, customizable and highly flexible. It allows introducing expressions and large code blocks evaluation within your applications in the similar way Microsoft Office deals with VBScript, gives you possibilities providing rich formula evaluation capabilities like it can be seen in MS Excel, etc.

“Orbifold S# Runtime” will be distributed absolutely free for academic and non-commercial usage!. You can download runtime right now from here.

The key principles of S# are:

  • Be simple
  • Be efficient
  • Be intuitive

S# runtime has been designed to be easily hosted by applications. Minimum script execution scenario requires two lines of code! The important part of S# is its well-defined extendable runtime engine together with the application programming interface that allows full bi-directional communication between script and application code. In particular it is easy to extend S# by embedding external functions and functional objects, shared static or dynamic variables, operator handlings and type filters from the host application. Moreover the execution semantics of some language constructs has extensibility mechanisms available externally. This enables developers to create user-friendly executable business/domain specific languages on S# basis.

S# can work in single-expression mode in order to execute string expressions to values. This is especially helpful when application should allow users executing only light-weight portions of the functionality. S# is a pure .NET interpreted language completely written in C#.

For the moment it is ported to the following platforms:

  • Microsoft .NET 3.5 (SP1)
  • Microsoft Silverlight 3.0
  • Microsoft .NET Compact Framework
  • Microsoft XNA Framework
  • MONO

This means that S# runtime can be hosted by applications based on .NET like Console, Windows Forms, ASP.NET, Silverlight 2 and 3, Windows Presentation Foundation (WPF), XNA (both PC and XBox scenarios) and MONO (Linux).

Key features that will be dwelled on in the upcoming articles are:

  • Designed to be easily embedded into applications
  • Highly extensible grammar and language
  • Rich and controlled communication between runtime and host application in both directions
  • Sits on the top of .NET, has support for interaction with .NET code
  • Works in a single-expression evaluation mode to execute string expressions to values and return results to application
  • No code emitting, no CodeDom or background compilation, 100% interpreted language (own Virtual Machine and Debugging facilities are in progress)
  • Completely in-memory execution, does not require temp files, local system access, etc
  • C# and Java-like language syntax designed to be familiar to .NET and Java developers; easy to study for non-developer users
  • Various platforms are supported
  • Fully remotable; expressions and scripts can be sent across the wire and executed on a remote machine
  • Weakly-typed as IronPython and IronRuby for .NET

Installation Experience

You will need a couple of clicks in order to install S# runtime on your machine. For the moment runtime requires less than 1 MB on you hard drive.

SSharp_Installation_1

SSharp_Installation_2

SSharp_Installation_3

SSharp_Installation_4

For the moment you will have runtimes only for .NET 3.5 and Silverlight 3.0 installed by default. Both components are automatically registered within the “Add Reference” dialog in Visual Studio 2008 (note this requires installation to be started by a user with administrator account).

When creating a new Silverlight application you will be able adding S# reference without any additional implications related to finding the assembly installed on the local drive:

SSharp_Installation_VS

From Installation right to Execution

I am going to show you how easily you can start hosting S# runtime right after installation process is finished. You need to create an empty “Silverlight 3″ application project and add reference to “Orbifold S# for Silverlight” assembly using “Add Reference” dialog in Visual Studio 2008.

Next open “MainPage.xam” file and add a Canvas control. We are going to execute scripts that perform some operations against the Canvas element.

SSharp_Intro_1

After that you will need opening the code-behind file “MainPage.xaml.cs”. S# runtime hosting will require at least 2 namespaces involved: “Orbifold.SSharp” and “Orbifold.SSharp.Runtime”

SSharp_Intro_2

Note that S# runtime should be initialized before executing scripts. This procedure should be done once and I would recommend placing “RuntimeHost.Initialize()” method call somewhere in “App.xaml.cs” in the future.

Now it’s time to do some scripting on the “MainPage.Loaded” event:

SSharp_Intro_3

S# runtime supports a large amount of Scoping facilities (local scopes, global scopes, dynamic or application-controlled scopes). The same goes to execution contexts. Execution Contexts is a highly valuable and extensible area that deserves a separate article. All this will be  described in future articles and in API guides.

As I want promoting my “canvas” element to the runtime I need creating a simple execution context for my future script and provide possibility accessing “canvas” during runtime. This is achieved by adding a “canvas” variable to the scope that references our “canvas” element inside application. Note that you can provide any “alias” you want and it may not carry the same name as host-side variable/element.

Next step is defining the body of the script. I’m going to assign a new background brush for the Canvas and add a Rectangle element. Note that I don’t have to use full namespace paths for .NET classes as they are resolved automatically by S# runtime. You may forget about endless “using” clauses here.

After that I create a Rectanlge, configure it’s properties (including attached ones) and add it to the Children collection of the Canvas control by referencing “canvas” variable.

Finally I call “Script.RunCode” providing the body of the script and root execution context. When launching this Silverlight application you will see the following result:

SSharp_Intro_4

Yes, everything works perfect. Script got access to application structures and even managed to create and add new objects using core .NET Silverlight functionality. I would like to highlight “namespace resolving” feature once more as it really simplifies coding efforts. Let’s extend the script above to apply rotation for the Rectangle shape. “RotateTransform” class resides in “System.Windows.Media” namespace in Silverlight 3.0.

SSharp_Intro_5

As S# is a weakly-typed language you don’t have a need worrying about value types as they will be resolved automatically during runtime.

When running modified script you should see the following results:

SSharp_Intro_6

Extending Language with Custom Functions

Though S# supports a huge part of C# syntax constructions it may be required adding some domain-specific constructions or functions that simplify script building for end-users.

I am going to create two new functions: “CreateRectangle” that creates a Rectangle shape in a simplified manner and “Rotate” that will rotate FrameworkElement.

CreateRectangleFunction

SSharp_Ext_2

RotateElementFunction

SSharp_Ext_3

Both functions are fairly simple and don’t require comments. Please note that each S# function element should expose “IInvokable” interface. This is the only requirement for external functions integration.

In order to promote these functions you will need to include them into the scope the same fashion “Canvas” element was done – ScriptContext.SetItem() method. However to reduce development time there are also generics-based methods:

SSharp_Ext_1

Note that you can provide any name for the function. In this case I used “CreateRectangle” and “Rotate”. Now let’s modify the code from the samples above in order to consume new functions:

SSharp_Ext_4

This time the code becomes less complex but more efficient. I can create a Rectangle shape providing position and size and can call “Rotate” in order to apply Rotate Transformation.

Just for demonstration purposes I’ve added a function usage sample. I’ve introduced a function (event handler) called “OnCanvasClick” that is wired with “MouseLeftButtonDown” event of Canvas. Function requests access to global variable scope via the “global” keyword (similar to PHP)

SSharp_Ext_5

Now if you execute a script Rectangle will rotate 10 degrees each time you click design surface with a left button of the mouse. Another important point is that weakly-typed and dynamic nature of S# allows me accessing Angle value of RenderTransform property as of RotateTransform actually. By default RenderTransform property is of Transform type. S# didn’t require me doing type casting or conversion in order to set property value and this is really helpful in many scenarios.

The S# language has a great number of features and runtime is extremely extensible. We will unveil more details, links and samples for S# very soon.

UPDATE: Meanwhile we are finishing all the packaging work you can download the raw runtime (without documentation, samples and some other stuff) right now here.

 
4 Comments

Posted by on November 8, 2009 in .NET, Info, Silverlight, WPF

 

Tags: , ,

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…

 
4 Comments

Posted by on October 31, 2009 in .NET, Silverlight

 

Dynamic Geometry with Silverlight 2.0


While preparing an updated article related to diagramming with Silverlight 2.0 I came across an awesome project at CodePlex named "Dynamic Geometry" made with Silverlight 2 Beta 2. So I’ve decided to postpone my article for a while and mention this project worth looking at.

DynamicGeometry

 
3 Comments

Posted by on July 3, 2008 in Silverlight

 

Silverlight Diagramming. Part 1.


 

Notes: The article and samples are based on Silverlight 2 Beta 1. For more details refer to Microsoft Silverlight site. Sample project requires "Microsoft Silverlight Tools Beta 1 for Visual Studio 2008". Details for installing the tools you can find here.

Introduction

When I’ve downloaded and installed the first cooked beta for Silverlight 2 I was really enraptured from what I’ve seen there. I didn’t expect such a huge jump ahead in such a small term (comparing with previous versions of Silverlight). At last my dream is started to come true.

I’ve been working for several years with the early versions of Ajax especially the Michael Schwarz xmlhttp implementation which I personally considered to be the best among the variety of existing projects. Later on with appearance of Atlas I’ve also devoted a lot of time digging and elaborating. But WPF appearance dramatically changed my attitude towards the technologies and products I want spend my working and spare time with. Being rather tired of ASP.NET and JavaScript "spaghetti coding" I didn’t touch a lot first Silverlight versions. I was clear enough for me that further versions of Silverlight have to provide the developers much more power in the future releases and we all should only wait patiently when WPF will get another Renderer rather then emulation for IE. This is when comes Silverlight 2.0. Even the first beta can impress anyone being really in love with .net 3.5/WPF. Xaml, Dependency objects/properties, C# and a great number of other candies. You should really take a loot at that!

I appreciate the work done by MS guys to deliver it to the community and realize how much work is to be performed for us to get the real power Silverlight is supposed to bring.

Diagramming sample

SilverlightDiagram1

Actually my intention was to test how much time could take me to cook anything working with Silverlight 2 beta 1. As we are facing something like WPF port I’ve decided to test how the common basic project could be ported to browser. First of all I was interested in problems rather than successful results. Anyway I was pleased much with both. As it is the first beta and serve for demonstration purposes my hands were quite tied in doing some efficient code behind. Even having nearly everything as "sealed" I must admit it is quite possible implementing a lot :)

It took me only one evening (approximately 3 or 4 hours of pure time) porting basics of my previous diagramming samples to Silverlight 2. Later on I’ll continue enhancing the sample to eliminate difference between my two implementations.

SilverlightDiagramming.Core

I’ve implemented a separate Silverlight Library for placing some common stuff there and also testing the Library project itself. I didn’t manage to find any helper class for walking visual and logical trees so I’ve implemented simple LogicalTreeHelper for my own needs, mainly hit testing the canvas and recursive parent search.

Shapes

As I’ve stuck a bit with styling and templating (I’ve played a bit with generics.xaml and it’s compilation as a Resource within the Library projects but guess this part is an early beta so I couldn’t get most of it I wanted) and downgraded to introducing simply separate User Controls for each of the shape. Also I managed to do the basic class for all the shapes to suite as an example later on (according to forums there’s a lot of troubles with inheritance at Beta 1 especially with dependency objects, but we can live with it up to next betas I think).

DiagramCanvas

Basic subclass of Canvas panel. Generic approach for adding children and input delegation to the underlying BasicTool for drawing straight line connections.

Drag and drop

I didn’t introduce anything here as there’s already cooked drag and drop samples that can be found in the Silverlight 2 documentation. Of course later on it can be replaced with some more efficient managers or whatever but as for now the MS sample is really good.

Connections and bindings

I’ve decided not to implement fancy bindings/multibindings for the first version as again I was interested in time more than additional facilities. I came across some issues with code behind bindings and quickly switched to INotifyPropertyChanged interface implementation. The only code behind binding sample between ToggleButton and StraightLineTool can be found in the Page.xaml.cs. Line positioning was left to owner driven layout updates on drag operations.

 

Conclusion

I must admit that it was a real pleasure preparing this sample. I’ll definitely continue enhancing the sample described alongside with preparing some more detailed overviews of issues I came across and walkarounds performed.

The source code for the article can be found at my SkyDrive

 
4 Comments

Posted by on March 17, 2008 in Silverlight

 
 
Follow

Get every new post delivered to your Inbox.

Join 71 other followers

%d bloggers like this: