CSharpScriptExecution Class

Class that can be used to execute code snippets or entire blocks of methods dynamically. Two methods are provided:

  • ExecuteCode - executes code. Pass parameters and return a value * ExecuteMethod - lets you provide one or more method bodies to execute * Evaluate - Evaluates an expression on the fly (uses ExecuteCode internally) * CompileClass - compiles a class and returns the a class instance

Assemblies used for execution are cached and are reused for a given block of code provided.

System.Object
   Westwind.Scripting.CSharpScriptExecution

Class Members

MemberDescription
Constructor
AddAssemblies Add several reference assemblies in batch.Useful for use with Basic.ReferenceAssemblies from Nugetto load framework dependencies in…
public void AddAssemblies(IEnumerable references)
AddAssembly Adds an assembly from disk. Provide a full path if possibleor a path that can resolve as part of the application folderor the runtime folder.
public bool AddAssembly(string assemblyDll)
AddDefaultReferencesAndNamespaces Adds core system assemblies and namespaces for basic operation.Any additional references need to be explicitly added.Alternatelively use: AddLoadedReferences()
public void AddDefaultReferencesAndNamespaces()
AddLoadedReferences Explicitly adds all referenced assemblies of the currently executingprocess. Also adds default namespaces.Useful in .NET Core to ensure that all those little tiny system assembliesthat comprise…
public void AddLoadedReferences()
AddNamespace Adds a namespace to the referenced namespacesused at compile time.
public void AddNamespace(string nameSpace)
AddNamespaces Adds a set of namespace to the referenced namespacesused at compile time.
public void AddNamespaces(String[] namespaces)
AddNetCoreDefaultReferences
public void AddNetCoreDefaultReferences()
AddNetFrameworkDefaultReferences
public void AddNetFrameworkDefaultReferences()
CompileAssembly Compiles a class and creates an assembly from the compiled class.Assembly is stored on the `.Assembly` property. Use `noLoad()`to bypass loading of the assemblyMust include parameterless ctor()
public bool CompileAssembly(string source, bool noLoad)
CompileClass This method compiles a class and hands back adynamic reference to that class that you cancall members on.Must have include parameterless ctor()
public object CompileClass(string code)
CompileClassToType This method compiles a class and hands back adynamic reference to that class that you cancall members on.
public Type CompileClassToType(string code)
CreateDefault Creates a default Execution Engine which has:* AddDefaultReferences and Namespaces set* SaveGeneratedCode = trueOptionally allows to pass in references and namespaces
public CSharpScriptExecution CreateDefault(String[] references, String[] namespaces, Type[] referenceTypes)
CreateInstance Creates an instance of the object specifiedby the GeneratedNamespace and GeneratedClassNamein the currently active, compiled assemblySets the ObjectInstance member which is returnedand which can…
public object CreateInstance(bool force)
Evaluate Evaluates a single value or expression that returns a value.
public object Evaluate(string code, object[] parameters)
EvaluateAsync Evaluates an awaitable expression that returns a valueExample:script.EvaluateAsync("await ActiveEditor.GetSelection()",model);
public Task EvaluateAsync(string code, object[] parameters)
ExecuteCode Executes a snippet of code. Pass in a variable number of parameters(accessible via the parameters[0..n] array) and return an object parameter.Code should include: return (object) SomeValue as the…
public object ExecuteCode(string code, object[] parameters)
ExecuteCodeAsync Executes a snippet of code. Pass in a variable number of parameters(accessible via the parameters[0..n] array) and return an `object` value.Code should always return a result:include: `return…
ExecuteCodeFromAssembly Executes a method from an assembly that was previously compiled
public object ExecuteCodeFromAssembly(string code, Assembly assembly, object[] parameters)
ExecuteCodeFromAssemblyAsync
public Task ExecuteCodeFromAssemblyAsync(string code, Assembly assembly, object[] parameters)
ExecuteMethod Executes a complete method by wrapping it into a class, compilingand instantiating the class and calling the method.Code should include full method header (instance type, return value and…
public object ExecuteMethod(string code, string methodName, object[] parameters)
ExecuteMethodAsync Executes a complete async method by wrapping it into a class, compilingand instantiating the class and calling the method. This method has toreturn a result value - it cannot be void!Class should…
public Task ExecuteMethodAsync(string code, string methodName, object[] parameters)
ExecuteMethodAsyncVoid Executes a complete async method by wrapping it into a class, compilingand instantiating the class and calling the method. This method returnsno value.Class should include full class header (instance…
public Task ExecuteMethodAsyncVoid(string code, string methodName, object[] parameters)
ExecuteScript
public string ExecuteScript(string csharpTemplate, TModelType model)
ExecuteScriptAsync
public Task ExecuteScriptAsync(string csharpTemplate, TModelType model)
FindCodeLine Returns 0 offset line number where matched line lives
public int FindCodeLine(string code, string matchLine)
GetLines Parses a string into an array of lines brokenby \r\n or \n
public String[] GetLines(string s, int maxLines)
InvokeMethod Helper method to invoke a method on an object using Reflection
public object InvokeMethod(object instance, string method, object[] parameters)
ToString
public string ToString()
AllowReferencesInCode If true parses references in code that are referenced with:#r assembly.dll
AlternateAssemblyLoadContext The AssemblyLoadContext the assembly should be loaded in.If not assigned, assemblies will get loaded by the default Assembly.Load methodsIf the alternate AssemblyLoadContext is assigned, that will be…
Assembly Internal reference to the Assembly Generated
CodeInjection Optional code injections at various points in the code generation
CompileWithDebug Determines whether the code is compiled in Debug or Release modeDefaults to Release and there's no good reason for scripts to useanything else since debug info is not available in Reflection…
DisableAssemblyCaching If disabled, assemblies will not be cached through hashesInstead for each execution a new unique assembly will get generated and loadedThis combined with an alternate AssemblyLoadContext can lower…
DisableObjectCaching Disables caching object instances that are created after CompileClassIf true you can't execute new code on the instance as the class instanceis cached. If false the instance is cached and…
Error Error flag that is set if an error occurred during the invokedmethod or script call
ErrorMessage Error message if an error occurred during the invokedmethod or script call
ErrorType Determines whether the error is a compile timeerror or runtime error
GeneratedClassCode Last generated code for this code snippet if SaveGeneratedCode = true
GeneratedClassCodeWithLineNumbers Last generated code for this code snippet with line numbers
GeneratedClassName Name of the class when a class name is not explicitly providedas part of the code compiled.Always used for the module name.By default this value is a unique generated id. Make sure if youcreate…
GeneratedNamespace Name of the namespace that a class is generated in
LastException Last Exception fired when a runtime error occursGenerally this only contains the error message, butthere's no call stack information available dueto the Reflection or dynamic code invocation
Namespaces List of additional namespaces to add to the script
ObjectInstance Internal reference to the generated type thatis to be invokedCan also be used to cache an object instanceusing ReuseObjectInstance, which is usefulif you work with a single object/methodthat is…
OutputAssembly Filename for the output assembly to generate. If empty theassembly is generated in memory (dynamic filename managed bythe .NET runtime)
References List of additional assembly references that are added to thecompiler parameters in order to execute the script code.
ReuseObjectInstance If true reuses the ObjectInstance fromt he previousoperation (if set) instead of creating a new instance.Use if you pre-generate a single instance and call oneor more methods/scripts repeatedly…
SaveGeneratedCode Determines whether GeneratedCode will be set with the sourcecode for the full generated class
ThrowExceptions If true throws exceptions when executing the code ratherthan setting the `Error`, `ErrorMessage` and `LastException`properties.Note: Compilation errors will not throw, but always set properties!
Namespace: Westwind.Scripting

Assembly: Westwind.Scripting.dll