Created
April 16, 2013 22:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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> | |
| <input id="fromVal" type="text"/><br/> | |
| <span>formula:</span> | |
| <input id="formula" type="text"/><br/> | |
| <input type="button" onclick="javascript:convert();" | |
| value="Convert" /><br/> | |
| <span>toValue:</span> <span id="toVal"></span> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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