web 2.0

Execute Code String at Runtime with Silverlight 2.0 DLR

Requisites

  • Microsoft Visual Studio 2008
  • Silverlight 1.1 Alpha November Refresh or Newer

Introduction

One of the best additions in Silverlight 2.0 is the implementation of the Common Language Runtime and then the Dynamic Language Runtime, both of which were missing in Silverlight 1.0. Let’s dig a bit deeper in this CLR and DLR thing.

Silverlight 2.0 CLR is a stripped down version of .NET Framework 3.5 featuring the same type system, JIT compiler, garbage collector and a shipload of the same .NET 3.5 namespaces. Silverlight CLR allows .NET code to execute in a sandboxed environment on the client-side. But here’s the problem: Full .NET Framework has the full implementation of System.CodeDom framework which allows .NET code compilation at runtime, but Silverlight CLR strips out 99% of System.CodeDom namespace for security and space concerns. Therefore, you can no longer compile .NET code through the CodeDom in Silverlight. This is when DLR comes to rescue!

Silverlight DLR is implemented on top of the CLR to allow both compilation and execution of dynamic code in runtime. Without DLR, only the already-compiled code can execute. The good thing about DLR is that it can compile and execute code in Dynamic VB.NET, IronPython, IronRuby and Managed JScript—C# is not supported by the DLR yet—at a blazingly fast performance, as the dynamic code is first JIT-compiled before being executed. With DLR, we can now write dynamic code that can fully interact with Silverlight elements at runtime.

Executing a String

I’m going to demonstrate how to compile and execute JScript code to set the text of a TextBlock to current date and time. Firstly, create a new Silverlight Project in Visual Studio 2008, name it “SilverlightProjectDLR” and add references to Microsoft.JScript.Compiler and Microsoft.Scripting libraries.

Now we have two main files Page.xaml and Page.xaml.vb. Add a TextBlock control into the Page.xaml. Set its Name to “txtHello” and Text to “Hello World”.  See the shorten Page.xaml:

<Canvas ...>

  <TextBlock x:Name="txtHello" Text="Hello World" FontWeight="Normal" />

</Canvas>


We want to change the text of the TextBlock to current time when it is clicked, using dynamic JScript code. Let’s see the completed Page.xaml.vb file:

Imports Microsoft.JScript
Imports Microsoft.Scripting

Partial Public Class Page
Inherits Canvas

  Public Sub Page_Loaded(ByVal o As Object, ByVal e As EventArgs)
    ' Required to initialize variables
    InitializeComponent()
  End Sub

  Private Sub txtHello_MouseLeftButtonDown( _
      ByVal sender As Object, _
      ByVal e As System.Windows.Input.MouseEventArgs) _
      Handles txtHello.MouseLeftButtonDown

    ' Get scripting engine
   Dim engine As Compiler.Engine = Compiler.Engine.CurrentEngine

   ' Create a default module and add variables
   Dim mo As ScriptModule = _
   ScriptDomainManager.CurrentManager.CreateModule("main")
   mo.SetVariable("txtHello", txtHello)

   ' Compile and execute the dynamic code
   Dim code As Hosting.ICompiledCode = _
   engine.CompileCode("txtHello.Text = new Date().toString();", mo)
   code.Execute(mo)

  End Sub

End Class

 

The code is straight forward. Firstly, we get the default instance of JScript engine and then create a script module for the dynamic code to run in. We need to explicitly add txtHello reference to the module so that the scripting engine knows how to access it. If we don’t, the scripting engine will throw MissingMemberException.

    mo.SetVariable("txtHello", txtHello)

 

The last part is to compile and execute the JScript code the string in the module. The code will change the text of the TextBlock to current date and time.

   Dim code As Hosting.ICompiledCode = _
   engine.CompileCode("txtHello.Text = new Date().toString();", mo)
   code.Execute(mo)

 

Conclusion

You can see that it takes only several lines of code to compile and execute dynamic code at run time. It is neat and fast. Don’t let this short example fools to think that you can do only simple things with DLR. The possibility is end-less. In fact, DLR allows Silverlight to extend its development support to other languages such as IronPython and IronRuby. I can’t wait to see more advanced examples using DLR to push the limit.

Source Code

SilverlightProjectDLR.zip (11.05 kb)

Comments

busby seo test , on 12/7/2008 5:05:21 PM Said:

busby seo test

Nice one, thank you for the information...

busbyseotest , on 12/21/2008 5:50:11 AM Said:

busbyseotest

many thanks you have a great post information.

Busby SEO Test Pinay , on 12/25/2008 1:51:24 AM Said:

Busby SEO Test Pinay

hi,
  
Me pregunto por qué a las grandes es esta tecnología y un montón de usuario, ¿cuál es la mejor palabra o de prensa esta blogengine?

best regards,
busby

divorce solicitors London , on 1/6/2009 9:46:09 PM Said:

divorce solicitors London

Nice post - keep up the good work!

saville row tailors , on 1/6/2009 9:46:47 PM Said:

saville row tailors

Good work fella - interesting post and very useful

gigabite ethernet , on 1/16/2009 3:39:03 AM Said:

gigabite ethernet

This looks like a really useful post - i am trying to get to grips with Sliverlight and Sharepoint at the moment

Perfect Home Design , on 3/11/2009 6:06:13 AM Said:

Perfect Home Design

yeah silverlight application will do

Philippines Real Estate , on 3/18/2009 10:02:40 PM Said:

Philippines Real Estate

This is really a wonderful post. Silverlight application is very useful and reliable.

Electroplating , on 4/27/2009 5:59:45 AM Said:

Electroplating

This blog post was absolutely fantastic. When I used to work in electroplating they sometimes encouraged us to write, but I could never come up with something as well written as that.

Simulation pret immobilier , on 5/14/2009 7:18:52 PM Said:

Simulation pret immobilier

Thanks a lot for this very good post!

tukang nggame , on 6/25/2009 3:24:53 AM Said:

tukang nggame

thanks for sharing great post

club penguin , on 7/5/2009 8:09:43 PM Said:

club penguin

Me pregunto por qué a las grandes es esta tecnología y un montón de usuario, ¿cuál es la mejor palabra o de prensa esta blogengine?

Kerja Keras Adalah Energi Kita , on 10/19/2009 6:58:27 AM Said:

Kerja Keras Adalah Energi Kita

this article very useful. thanks for advice.

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading