Search code examples
c#scriptcs

Execute ScriptCS from c# application


Background

I'm creating a c# application that runs some status checks (think nagios style checks).

What I ideally want is this c# application to look at a specific directory, and just compile/execute any scriptcs scripts within it, and act on the results (send email alerts for failing status checks for example).

I would expect the script to return an integer or something (for example) and that integer would indicate weather the status check succeeded or failed.

Values returned back to C# application.

0 - Success
1 - Warning
2 - Error

When first tasked with this I thought this is a job for MEF, but it would be vastly more convenient to create these 'status checks' without having to create a project or compile anything, just plopping a scriptcs script within a folder seems way more attractive.

So my questions are

  1. Is there any documentation/samples on using a c# app and scriptcs together (google didn't net me much)?

  2. Is this a use case for scriptcs or was it never really intended to be used like this?

  3. Would I have an easier time just creating a custom solution using roslyn or some dynamic compilation/execution? (I have very little experience with scriptsc)


Solution

  • I found some good easy examples on how to do this:

    Loading a script from a file on disk and running it: https://github.com/glennblock/scriptcs-hosting-example

    A web site where you can submit code, and it will return the result: https://github.com/filipw/sample-scriptcs-webhost

    Here is an example of how to load a script file, run it and return the result:

    public dynamic RunScript()
    {
        var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
        var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), logger).
            LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptEngine<RoslynScriptEngine>();
    
        var scriptcs = scriptServicesBuilder.Build();
    
        scriptcs.Executor.Initialize(new[] { "System.Web" }, Enumerable.Empty<IScriptPack>());
        scriptcs.Executor.AddReferences(Assembly.GetExecutingAssembly());
    
        var result = scriptcs.Executor.Execute("HelloWorld.csx");
    
        scriptcs.Executor.Terminate();
    
        if (result.CompileExceptionInfo != null)
            return new { error = result.CompileExceptionInfo.SourceException.Message };
        if (result.ExecuteExceptionInfo != null)
            return new { error = result.ExecuteExceptionInfo.SourceException.Message };
    
        return result.ReturnValue;
    }