15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

In the following example, we use IronPython to evaluate an expression created at<br />

runtime from within C#. This script could be used to write a calculator.<br />

To run this code, download IronPython (search the Internet<br />

for IronPython), and then reference the IronPython,<br />

Microsoft.Scripting, and Microsoft.Scripting.Core assemblies<br />

from your C# application.<br />

using System;<br />

using IronPython.Hosting;<br />

using Microsoft.Scripting;<br />

using Microsoft.Scripting.Hosting;<br />

class Calculator<br />

{<br />

static void Main()<br />

{<br />

int result = (int) Calculate ("2 * 3");<br />

Console.WriteLine (result); // 6<br />

}<br />

static object Calculate (string expression)<br />

{<br />

ScriptEngine engine = Python.CreateEngine();<br />

return engine.Execute (expression);<br />

}<br />

}<br />

Because we’re passing a string into Python, the expression will be evaluated according<br />

to Python’s rules and not C#’s. It also means we can use Python’s language<br />

features, such as lists:<br />

var list = (IEnumerable) Calculate ("[1, 2, 3] + [4, 5]");<br />

foreach (int n in list) Console.Write (n); // 12345<br />

Passing State Between C# and a Script<br />

To pass variables from C# to Python, a few more steps are required. The following<br />

example illustrates those steps, and could be the basis of a rules engine:<br />

// The following string could come from a file or database:<br />

string auditRule = "taxPaidLastYear / taxPaidThisYear > 2";<br />

ScriptEngine engine = Python.CreateEngine ();<br />

ScriptScope scope = engine.CreateScope ();<br />

scope.SetVariable ("taxPaidLastYear", 20000m);<br />

scope.SetVariable ("taxPaidThisYear", 8000m);<br />

ScriptSource source = engine.CreateScriptSourceFromString (<br />

auditRule, SourceCodeKind.Expression);<br />

bool auditRequired = (bool) source.Execute (scope);<br />

Console.WriteLine (auditRequired); // True<br />

748 | Chapter 19: Dynamic Programming

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!