|
| 1 | +# Westwind CSharp Scripting |
| 2 | +### Dynamically compile and execute CSharp code at runtime |
| 3 | + |
| 4 | +This small `CSharpScripting` class provides an easy way to compile and execute C# on the fly at runtime using the .NET compiler services. This is ideal to provide support for addin's and application automation tasks that are user configurable. |
| 5 | + |
| 6 | +The library supports both the latest Roslyn compiler and classic CSharp compilation. |
| 7 | + |
| 8 | +> #### Requires Roslyn Code Providers for your Project |
| 9 | +> If you want to use Roslyn compilation you have to make sure you add the `Microsoft.CodeDom.CompilerServices` NuGet Package to your project to provide the required compiler binaries for your application. This should be added to the application's start project. |
| 10 | +> |
| 11 | +> Note that this adds a sizable chunk of files to your application's output folder in the `roslyn` folder. If you don't want this you can use the classic compiler, at the cost of not having access to C# 6+ features. |
| 12 | +
|
| 13 | +## Usage |
| 14 | +Using the `CSharpScriptExecution` class is very easy. It works by letting you provide either a simple code snippet that can optionally `return` a value, or a complete method signature with a method header and return statement. You can also provide multiple method that can be called explicitly using the `InvokeMethod()` operation. |
| 15 | + |
| 16 | +You can add **Assembly References** and **Namespaces** via the `AddReferece()` and `AddNamespace()` methods. |
| 17 | + |
| 18 | +Script Execution is gated rather than throwing directly to provide |
| 19 | + |
| 20 | +### Executing a Code Snippet |
| 21 | +A code snippet can be **any block of .NET code** that can be executed. You can pass any number of parameters to the snippets which are accessible via a `parameters` object array. You can optionally `return` a value by providing a `return` statement. |
| 22 | + |
| 23 | + |
| 24 | +```cs |
| 25 | +var script = new CSharpScriptExecution() |
| 26 | +{ |
| 27 | + SaveGeneratedCode = true, |
| 28 | + CompilerMode = ScriptCompilerModes.Roslyn |
| 29 | +}; |
| 30 | +script.AddDefaultReferencesAndNamespaces(); |
| 31 | + |
| 32 | +//script.AddAssembly("Westwind.Utilities.dll"); |
| 33 | +//script.AddNamespace("Westwind.Utilities"); |
| 34 | +
|
| 35 | +var code = $@" |
| 36 | +// Check some C# 6+ lang features |
| 37 | +var s = new {{ name = ""Rick""}}; // anonymous types |
| 38 | +Console.WriteLine(s?.name); // null propagation |
| 39 | +
|
| 40 | +int num1 = (int)parameters[0]; |
| 41 | +int num2 = (int)parameters[1]; |
| 42 | +
|
| 43 | +// string templates |
| 44 | +var result = $""{{num1}} + {{num2}} = {{(num1 + num2)}}""; |
| 45 | +Console.WriteLine(result); |
| 46 | +
|
| 47 | +return result; |
| 48 | +"; |
| 49 | + |
| 50 | +string result = script.ExecuteCode(code,10,20) as string; |
| 51 | + |
| 52 | +Console.WriteLine($"Result: {result}"); |
| 53 | +Console.WriteLine($"Error: {script.Error}"); |
| 54 | +Console.WriteLine(script.ErrorMessage); |
| 55 | +Console.WriteLine(script.GeneratedClassCodeWithLineNumbers); |
| 56 | + |
| 57 | +Assert.IsFalse(script.Error, script.ErrorMessage); |
| 58 | +Assert.IsTrue(result.Contains(" = 30")); |
| 59 | +``` |
| 60 | + |
| 61 | +### Executing a Method |
| 62 | +Another way to execute code is to provide a full method body which is a little more explicit and makes it easier to reference parameters passed in. |
| 63 | + |
| 64 | +```csharp |
| 65 | +var script = new CSharpScriptExecution() |
| 66 | +{ |
| 67 | + SaveGeneratedCode = true, |
| 68 | + CompilerMode = ScriptCompilerModes.Roslyn, |
| 69 | + GeneratedClassName = "HelloWorldTestClass" |
| 70 | +}; |
| 71 | +script.AddDefaultReferencesAndNamespaces(); |
| 72 | + |
| 73 | +string code = $@" |
| 74 | +public string HelloWorld(string name) |
| 75 | +{{ |
| 76 | +string result = $""Hello {{name}}. Time is: {{DateTime.Now}}.""; |
| 77 | +return result; |
| 78 | +}}"; |
| 79 | + |
| 80 | +string result = script.ExecuteMethod(code,"HelloWorld","Rick") as string; |
| 81 | + |
| 82 | +Console.WriteLine($"Result: {result}"); |
| 83 | +Console.WriteLine($"Error: {script.Error}"); |
| 84 | +Console.WriteLine(script.ErrorMessage); |
| 85 | +Console.WriteLine(script.GeneratedClassCode); |
| 86 | + |
| 87 | +Assert.IsFalse(script.Error); |
| 88 | +Assert.IsTrue(result.Contains("Hello Rick")); |
| 89 | +``` |
| 90 | + |
| 91 | +### More than just a Single Method |
| 92 | +Note that you can provide more than a method in the code block - you can provide an entire **class body** including additional methods, properties/fields, events and so on. Effectively you can build out an entire class this way. After intial execution you can access the `ObjectInstance` member and use either Reflection or `dynamic` to access the functionality on that class. |
| 93 | + |
| 94 | +```cs |
| 95 | +var script = new CSharpScriptExecution() |
| 96 | +{ |
| 97 | + SaveGeneratedCode = true, |
| 98 | + CompilerMode = ScriptCompilerModes.Roslyn |
| 99 | +}; |
| 100 | +script.AddDefaultReferencesAndNamespaces(); |
| 101 | + |
| 102 | +// Class body with multiple methods and properties |
| 103 | +string code = $@" |
| 104 | +public string HelloWorld(string name) |
| 105 | +{{ |
| 106 | +string result = $""Hello {{name}}. Time is: {{DateTime.Now}}.""; |
| 107 | +return result; |
| 108 | +}} |
| 109 | +
|
| 110 | +public string GoodbyeName {{ get; set; }} |
| 111 | +
|
| 112 | +public string GoodbyeWorld() |
| 113 | +{{ |
| 114 | +string result = $""Goodbye {{GoodbyeName}}. Time is: {{DateTime.Now}}.""; |
| 115 | +return result; |
| 116 | +}} |
| 117 | +"; |
| 118 | + |
| 119 | +string result = script.ExecuteMethod(code, "HelloWorld", "Rick") as string; |
| 120 | + |
| 121 | +Console.WriteLine($"Result: {result}"); |
| 122 | +Console.WriteLine($"Error: {script.Error}"); |
| 123 | +Console.WriteLine(script.ErrorMessage); |
| 124 | +Console.WriteLine(script.GeneratedClassCode); |
| 125 | + |
| 126 | +Assert.IsFalse(script.Error); |
| 127 | +Assert.IsTrue(result.Contains("Hello Rick")); |
| 128 | + |
| 129 | +// You can pick up the ObjectInstance of the generated class |
| 130 | +// Make dynamic for easier access |
| 131 | +dynamic instance = script.ObjectInstance; |
| 132 | + |
| 133 | +instance.GoodbyeName = "Markus"; |
| 134 | +result = instance.GoodbyeWorld(); |
| 135 | + |
| 136 | +Console.WriteLine($"Result: {result}"); |
| 137 | +Assert.IsTrue(result.Contains("Goodbye Markus")); |
| 138 | +``` |
0 commit comments