Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created April 16, 2013 22:13
Show Gist options
  • Select an option

  • Save akimboyko/5400102 to your computer and use it in GitHub Desktop.

Select an option

Save akimboyko/5400102 to your computer and use it in GitHub Desktop.
#Metaprogramming via scripting JavaScropt sample from 'Metaprogramming in .NET' by Kevin Hazzard and Jason Bock and C# script eval using Roslyn CTP
<!DOCTYPE html>
<!--
Metaprogramming via scripting
from book 'Metaprogramming in .NET'
by Kevin Hazzard and Jason Bock
http://www.manning.com/hazzard/
-->
<html>
<head>
<script type="text/javascript">
function convert() {
var fromValue = eval(fromVal.value);
toVal.innerHTML = eval(formula.value).toString();
}
</script>
</head>
<body>
<span>fromValue:</span>&nbsp;
<input id="fromVal" type="text"/><br/>
<span>formula:</span>&nbsp;
<input id="formula" type="text"/><br/>
<input type="button" onclick="javascript:convert();"
value="Convert" /><br/>
<span>toValue:</span>&nbsp;<span id="toVal"></span>
</body>
</html>
// limitations of scripts:
// * no `dynamic` keyword allowed
// * no async/await allowed
// For example:
// var x = 6;
// System.Math.Sqrt(x * 7)
var scripts = new []
{
Util.ReadLine(@"fromValue:"),
Util.ReadLine(@"formula:")
};
var engine = new ScriptEngine();
Array.ForEach(
new[] { typeof(object).Assembly, this.GetType().Assembly },
@assembly => engine.AddReference(@assembly));
Array.ForEach(
new[] { "System" },
@namespace => engine.ImportNamespace(@namespace));
var session = engine.CreateSession();
dynamic resultModel = null;
foreach(var script in scripts)
{
resultModel = session
.CompileSubmission<dynamic>(script)
.Execute();
}
(resultModel as object).Dump();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment