Skip to content

Instantly share code, notes, and snippets.

@bitbonk
Last active September 29, 2017 21:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitbonk/aea4cb41a21b7d666e80 to your computer and use it in GitHub Desktop.
Save bitbonk/aea4cb41a21b7d666e80 to your computer and use it in GitHub Desktop.
Host ScriptCs in a console application and install a script pack at startup
namespace ConsoleHostedScriptCs
{
using System;
using Common.Logging.Simple;
using NuGet;
using ScriptCs.Contracts;
using ScriptCs.Engine.Roslyn;
using ScriptCs.Hosting;
using PackageReference = ScriptCs.PackageReference;
internal class Program
{
private static void Main(string[] args)
{
var scriptcs = new ScriptServicesBuilder(new ScriptConsole(), new NoOpLogger())
.Repl()
.ScriptEngine<RoslynScriptEngine>()
.Build();
scriptcs.InstallationProvider.Initialize();
// Install ScriptCs.Wpf
var packageReference = new PackageReference(
"ScriptCs.Wpf",
VersionUtility.ParseFrameworkName("net40"),
new Version(0, 1, 4));
scriptcs.InstallationProvider.InstallPackage(packageReference);
scriptcs.Executor.Initialize(
scriptcs.AssemblyResolver.GetAssemblyPaths(Environment.CurrentDirectory),
scriptcs.ScriptPackResolver.GetPacks());
while (true)
{
// I can now do
// var wpf = Require<Wpf>();
// wpf.RunInSTA(() => new Window() { Content = "Kölle Alaaf!" }.ShowDialog());
var command = Console.ReadLine();
ScriptResult result;
try
{
result = scriptcs.Executor.ExecuteScript(command);
}
catch (Exception e)
{
WriteError(e.Message);
continue;
}
if (result.CompileExceptionInfo != null)
{
WriteError(result.CompileExceptionInfo.SourceException.Message);
continue;
}
if (result.ExecuteExceptionInfo != null)
{
WriteError(result.ExecuteExceptionInfo.SourceException.Message);
continue;
}
var returnValue = string.Format("{0}", result.ReturnValue);
if (!string.IsNullOrEmpty(returnValue))
{
Console.WriteLine(returnValue);
}
}
scriptcs.Executor.Terminate();
}
private static void WriteError(string error)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(error);
Console.ResetColor();
}
}
}
@bitbonk
Copy link
Author

bitbonk commented Mar 20, 2015

With this version, I now can do Require<Wpf>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment