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.


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):









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


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:




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:


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

namespace XamlOnlyUtils
  [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:

   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 =
       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();

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

     foreach (var handler in handlers)

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:

   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:




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”:


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
   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:




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:




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




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:




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




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:




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.

S# 1.3 is out with .NET Compact Framework 3.5 support

I would like to announce that tomorrow we are releasing an updated version of S# Scripting Runtime (version 1.3) containing a set of bug fixes, performance and API enhancements and .NET CF 3.5 support.

Please refer to the official product page for getting more details and latest installation package.

Starting from now you will be able enriching your mobile software with rich capabilities of S# scripting. Here’s a couple of screenshots:


S# allows you creating content dynamically on the fly and that should be extremely valuable in various scenarios:


Execution of the script above will create a new Form with a TextBox control on it:


The sample above requires only 3 lines of code


Also we’ve updated the setup package to simplify your development efforts. The corresponding assembly will be automatically displayed within the “Add reference” dialog in Visual Studio:


Please refer to the official product page for getting more details and latest installation package.

Any feedback, suggestions or ideas are much appreciated.

Happy coding!

Building refactoring-friendly observable objects in C#

INotifyPropertyChanged is one the most frequently used .NET interfaces nowadays. I use this interface every day within the models in all kinds of applications: Windows Forms, WPF, Silverlight.

However there is one disadvantage in using INotifyPropertyChanged I have to deal with very often – it is not “refactoring-friendly” and requires a lot of efforts when supporting large scalable enterprise applications/frameworks.

Here’s a skeleton of a common observable object exposing INotifyPropertyChanged interface we all usually deal with:

public class MyCommonObject : INotifyPropertyChanged
  #region INotifyPropertyChanged Members

  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
    var handler = PropertyChanged;
    if (handler != null) 
      handler(this, new PropertyChangedEventArgs(propertyName));



Now let’s take a “Name” property that supports value change notifications:

public class MyCommonObject : INotifyPropertyChanged
  private string _Name;

  public string Name
    get { return _Name; }
      if (_Name == value) return;
      _Name = value;

  #region INotifyPropertyChanged Members  


When you want to rename “Name” property above to something like “FirstName” using some refactoring tool the notification will work properly only when the “OnPropertyChanged” call argument is changed as well. It is quite easy to change the code above to call OnPropertyChanged(“FirstName”) but it’s not so easy when you deal with hundreds of objects with possibly hundreds of properties spread over more than one project/solution. Sometimes it is not only the property who notifies about value changes and this makes the refactoring/support task extremely difficult and error-prone.

Being tired of searching broken “OnPropertyChanged” occurrences I’ve started to think over modifying this pattern in order to make it “refactoring-aware”. I wanted to pass something like a “pointer” to the property rather than it’s name so that each time the property name is changed the “pointer” does not require additional tuning. After trying out several approaches I finally found the one that perfectly suits my needs.

Linq Expressions to the rescue…

I’ve decided to reuse Linq Expressions and lambda Functions in order to pass a strongly-typed reference to the object’s property for the “OnPropertyChanged” method. I ended with the following modification of basic “INotifyPropertyChanged” implementation:

public class ObservableObject<T> : INotifyPropertyChanged
  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged(Expression<Func<T, object>> property)
    if (property == null || property.Body == null) return;

    var memberExp = property.Body as MemberExpression;
    if (memberExp == null) return;
    var handler = PropertyChanged;
    if (handler != null)
      handler(this, new PropertyChangedEventArgs(memberExp.Member.Name));

As you can see “OnPropertyChanged” method was changed to receive Expression<Func<T, object>> instead of a string-based property name.

You don’t need compiling or executing this expression. The primary goal is accessing its Body that is represented by a MemberExpression. MemberExpression instance wraps a common “System.Reflection.MemberInfo” as a Member property and so it is obvious that you can get the actual name of the property based on reflection and create a proper event arguments on the fly.

Note: This is a basic implementation and does not consider various possible scenarios. I simply exit method execution if things go the unexpected way. You may want providing some exceptions or error handling.

As you may have noticed I’ve provided a generic class implementation that can be consumed by my objects. Here’s a basic sample of the object consuming modified pattern:

public class MyObject : ObservableObject<MyObject>
  private bool _BoolProperty;
  public bool BoolProperty
    get { return _BoolProperty; }
      if (_BoolProperty == value) return;
      _BoolProperty = value;
      OnPropertyChanged(@this => @this.BoolProperty);

  private int _IntProperty;
  public int IntProperty
    get { return _IntProperty; }
      if (_IntProperty == value) return;
      _IntProperty = value;
      OnPropertyChanged(@this => @this.IntProperty);

  private string _StringProperty;
  public string StringProperty
    get { return _StringProperty; }
      if (_StringProperty == value) return;
      _StringProperty = value;
      OnPropertyChanged(@this => @this.StringProperty);

  private object _ObjectProperty;
  public object ObjectProperty
    get { return _ObjectProperty; }
      if (_ObjectProperty == value) return;
      _ObjectProperty = value;
      OnPropertyChanged(@this => @this.ObjectProperty);


I guess the sample above does not need detailed comments. Instead of string-based property name you now pass the property. If you or someone else decides refactoring the name of the property all notification logic will be automatically updated.

Proper implementation

However when running the following test I found that the code above was not working as expected:

class Program
  static void Main(string[] args)
    MyObject my = new MyObject();
    my.PropertyChanged += (sender, e) => Console.WriteLine(e.PropertyName);

    my.BoolProperty = true;
    my.IntProperty = 100;
    my.StringProperty = "something";
    my.ObjectProperty = 100;

    Console.WriteLine("Press Enter to exit...");

I was receiving only notifications for “StringProperty” and “ObjectProperty” properties, but nothing for “BoolProperty” and “IntProperty”.

After some investigation I found out that my problem was in “object” declaration in Expression<Func<T,object>>. Linq wraps value type instances with additional “Convert” expression so my check for “MemberExpression” was receiving null value during type casting.

This produced another slight modification that covered all aspects of expression passing:

public class ObservableObject<T> : INotifyPropertyChanged
  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged(Expression<Func<T, object>> property)
    if (property == null || property.Body == null) return;

    var memberExp = property.Body as MemberExpression;
    if (memberExp == null)
      UnaryExpression unary = property.Body as UnaryExpression;
      if (unary != null) memberExp = unary.Operand as MemberExpression;
      if (memberExp == null) return;

    var handler = PropertyChanged;
    if (handler != null)
      handler(this, new PropertyChangedEventArgs(memberExp.Member.Name));

As you can see I’ve added a fallback step to check whether an Unary Expression is actually being received. In this case I’m taking it’s Operand as the expected Member expression and this works like magic. Now my test output is correct and provides notification for all the properties.


The approach above consumes more CPU cycles than the common INotifyPropertyChanged use so it might slightly decrease performance. However I’m sure it may greatly reduce the cost of code support in future and save your time and money.

Feel free playing with the source code for this article.

Windows Automation: Automating Windows 7 Notepad within S# Script

Today we have updated S# with another sample covering the use of Windows Automation API from within a common S# script.

Auto# (AutoSharp)

This is a demo project shows how easily your S# scripts can be enhanced with a set of functions that target Windows UI Automation API and the ways of forming a QA-friendly language on the top of S# runtime. Full source code for this sample is available within the latest S# runtime update here.

Note: Sample project targets Windows 7 Notepad and may not work properly on other versions of Windows because of control ids difference.

To find Windows Automation API for your version of Windows please refer to this article.

Auto# introduces 9 functions that provide Windows Automation support S# scripts:

  • Kill – close all running instances of some process
  • Launch – launch a new process and return its main window
  • Wait – sleep for some time, often required when waiting application response
  • FindByClassName – finds element by Class Name
  • FindById – finds element by Automation ID
  • FindByName – finds element by its Name
  • Expand – expands menu element
  • InvokeById – invokes element by Automation ID
  • FocusEditor – focuses textbox editor

The following workflow is executed in order to automate Notepad:

  1. Kill all running Notepad instances
  2. Launch a new Notepad process
  3. Type some text
  4. Click “File” – “Save As” in the main menu
  5. Type destination file name
  6. Agree to overwrite existing file if confirmation dialog appears
  7. Click “File” – “Exit” to close Notepad

Here’s how the S# script may look like:

// Close existing instances of Notepad



// Launch a new Notepad instance and get main window

window = Launch(“notepad”);

// Wait 1 second



// Get main editor region

edit = FindByClassName(window, “Edit”);


// focus main editor



// Send sample text to the editor region

SendKeys.SendWait(“Automating Notepad using Windows UI Automation and S#”);



// Find [File] menu

mnuFile = FindById(window, “Item 1”);


// Expand [File] menu




// Invoke [Save As] menu item

InvokeById(window, “Item 4”);



// Get [Save As] dialog

saveAsDialog = FindByName(window, “Save As”);


// Get access to [FileName] textbox

saveAsName = FindById(saveAsDialog, “1001”);


// Focus filename editor



// Write down file name


// Send [Enter] keypress




// Check whether Overwrite Dialog appeared

confirmSaveAs = FindByName(saveAsDialog, “Confirm Save As”);

if (confirmSaveAs != null)


    // Click [OK] button

    InvokeById(confirmSaveAs, “CommandButton_6”);




// Expand [File] menu




// Click [Exit] item

InvokeById(window, “Item 7”);



Demo project also includes a very simply UI providing possibility to alter the script above and execute it.

Unleash your fantasy 🙂

S# 1.1 and Processing# Visualization Language for Silverlight 3.0

We are happy to announce that S# 1.1 was released today.

“Extension Methods”

It is now possible extending .NET types with custom methods that can be invoked during script execution. It is not the support for.NET extension methods but functionality is somewhat similar.

Let’s take a .NET “System.Math” class. It is a static class that “Provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions”. You can freely access all its members from S# script (omitting namespace) but at some point you may want to extend existing set of methods with some custom or missing (in your opinion) ones. For example conversion to radians, mapping/constraint of numeric values, distance calculation, etc. But “System.Math” is a static class and cannot be inherited for customization purpose.

In S# 1.0 we used the following workaround for such cases: we would have created a “MathEx” class to mimic “System.Math” one with same methods being re-directed to original “Math” plus containing additional members like “Distance()”, “Radians()” etc. After that we’ve been suppressing original “Math” class with our own implementation with the help of RuntimeHost features like “AddType”: RuntimeHost.AddType(“Math”, typeof(MathEx)); From that moment all “Math.*” calls were redirected to a custom implementation and original “System.Math” was hidden from the scripts.

Though the approach above is still valid and you can easily suppress any type with your own implementation we decided to provide an out-of-box support in S# 1.1 for such scenarios:


.AddExtensionMethod(typeof(Math), “Constrain”, new

.AddExtensionMethod(typeof(Math), “Degrees”, new

.AddExtensionMethod(typeof(Math), “Distance”, new

.AddExtensionMethod(typeof(Math), “Distance2D”, new

.AddExtensionMethod(typeof(Math), “Distance3D”, new

.AddExtensionMethod(typeof(Math), “Map”, new

.AddExtensionMethod(typeof(Math), “Radians”, new

Now you can create invokable functions and bind them to ANY .net type with a single line of code. The sample above demonstrates how easily “System.Math” type is enriched with 7 new methods. Here’s how I’m using it now within my scripts:

ang1 = Math.Radians(i); // convert degrees to radians

ang2 = Math.Radians(j); // convert degrees to radians

pos1 = Surface.Width/2 + (sc * Math.Cos(ang1));

pos2 = Surface.Width/2 + (sc * Math.Sin(ang1));

pos3 = Surface.Width/2 + (sc * Math.Cos(ang2));

pos4 = Surface.Width/2 + (sc * Math.Sin(ang2));

We hope this feature will greatly reduce development efforts for numerous scenarios as well as well as enrich your scripts.

Processing# Visualization Language for Silverlight 3.0

“Processing#” is a showcase sample demonstrating most of the powerful capabilities of S#. Being greatly inspired by “Processing” language implementation in Java we decided to port it to Silverlight powering with S# runtime. After installing S# 1.1 runtime you will find the complete source code under the “Samples\Silverlight 3.0” folder.

Solution contains a simple console where you can write and immediately execute scripts. There are more than 30 “Processing.org” samples that were successfully ported to “Processing#” and that are available within the Silverlight console. The syntax was made slightly different by intention and will be getting more parity in later versions.

Source code also contains a ported to Silverlight demo from “OpenProcessing.org” to demonstrate the capabilities of Processing# powered by S# 1.1 runtime:

function Setup()



Surface.Size(320, 480);


//Main Body

Surface.Defaults.StrokeThickness = 2;

Surface.Defaults.Fill = new SolidColorBrush(Color.FromArgb(255, 203, 224, 142));


using (Surface)



    Vertex(154, 65);

    Vertex(182, 71);

    Vertex(225, 82);

    Vertex(250, 90);

    Vertex(258, 96);

The image above is rendered by Silverlight 3 and has no visual difference comparing to that created by Java.

You can download the latest runtime with Processing# demo here: Orbifold S# Runtime 1.1

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.





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:


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.


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”


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:


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:


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.


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:


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.





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:


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:


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)


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.