Last active
September 29, 2017 21:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With this version, I now can do
Require<Wpf>();