Scripting .NET Applications Using Clearscript

Introduction

Clearscript is a .NET library that allows scripting .net applications using JavaScript (using Google V8 JavaScript engine and Microsoft Jscript engine) and VBScript. Clearscript is a lightweight script engine that supports interoperability between C# and JavaScript and vice versa.

Clearscript supports most of the C# features like delegates, Indexers, Extension methods, optional parameters, param arrays, methods, fields and events without any modification or code change to host type. It also has full support for generic types and methods.

Sample Code:

  1. Create WPF Application project. Add textbox and button as shown in image.

    application

  2. Add Clearscript reference using nuget package manager.

    package

  3. Create a script engine object.
    1. V8ScriptEngine scriptEngine = null;  
    2. scriptEngine = new V8ScriptEngine();  
  4. Expose host type, host object and host assemblies to script engine.
    1. scriptEngine.AddHostType("MessageBox"typeof(MessageBox));  
    2. scriptEngine.AddHostType("Console"typeof(Console));  
    3. scriptEngine.AddHostObject("host"new HostFunctions());  
    4. scriptEngine.AddHostObject("lib"new HostTypeCollection("mscorlib""System.Core"));  

  5. Execute script by calling execute method of script engine.
    1. //scriptEngine.Execute("MessageBox.Show('Praveen')");  
    2. scriptEngine.Execute(script);  
  6. Run application.

    application

Note: Download sample working application.

Reference:- http://clearscript.codeplex.com/

Ebook Download
View all
Learn
View all